code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const std = @import("std");
const Self = @This();
fn root() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
const root_path = root() ++ "/";
pub const include_dir = root_path ++ "ffmpeg";
pub const config_dir = root_path ++ "config";
pub const Library = struct {
avcodec: *std.build.LibExeObjStep,
avutil: *std.build.LibExeObjStep,
avformat: *std.build.LibExeObjStep,
avfilter: *std.build.LibExeObjStep,
swresample: *std.build.LibExeObjStep,
swscale: *std.build.LibExeObjStep,
pub fn link(self: Library, other: *std.build.LibExeObjStep) void {
other.addIncludeDir(include_dir);
other.addIncludeDir(config_dir);
inline for (std.meta.fields(Library)) |field| {
other.linkLibrary(@field(self, field.name));
}
}
};
/// requires zlib, mp3lame
pub fn create(b: *std.build.Builder, target: std.zig.CrossTarget, mode: std.builtin.Mode) !Library {
var ret = Library{
.avutil = b.addStaticLibrary("avutil", null),
.avformat = b.addStaticLibrary("avformat", null),
.avfilter = b.addStaticLibrary("avfilter", null),
.swresample = b.addStaticLibrary("swresample", null),
.swscale = b.addStaticLibrary("swscale", null),
.avcodec = b.addStaticLibrary("avcodec", null),
};
inline for (std.meta.fields(Library)) |field| {
@field(ret, field.name).setTarget(target);
@field(ret, field.name).setBuildMode(mode);
@field(ret, field.name).linkLibC();
@field(ret, field.name).addIncludeDir(include_dir);
@field(ret, field.name).addIncludeDir(root_path ++ "config");
@field(ret, field.name).defineCMacro("FFMPEG_VERSION", "\"n4.4.1\"");
@field(ret, field.name).defineCMacro("AV_HAVE_BIGENDIAN", "0");
@field(ret, field.name).defineCMacro("AV_HAVE_FAST_UNALIGNED", "1");
}
ret.avcodec.addCSourceFiles(avcodec_sources, flags ++ [_][]const u8{
"-DBUILDING_avcodec",
});
ret.avutil.addCSourceFiles(avutil_sources, flags ++ [_][]const u8{
"-DBUILDING_avutil",
});
ret.avformat.addCSourceFiles(avformat_sources, flags ++ [_][]const u8{
"-DBUILDING_avformat",
});
ret.avfilter.addCSourceFiles(avfilter_sources, flags ++ [_][]const u8{
"-DBUILDING_avfilter",
});
ret.swresample.addCSourceFiles(swresample_sources, flags ++ [_][]const u8{
"-DBUILDING_swresample",
});
ret.swscale.addCSourceFiles(swscale_sources, flags ++ [_][]const u8{
"-DBUILDING_swscale",
});
return ret;
}
const flags = &[_][]const u8{
"-D_ISOC99_SOURCE",
"-D_FILE_OFFSET_BITS=64",
"-D_LARGEFILE_SOURCE",
"-D_POSIX_C_SOURCE=200112",
"-D_XOPEN_SOURCE=600",
"-DZLIB_CONST",
"-DHAVE_AV_CONFIG_H",
"-std=c11",
"-fno-math-errno",
"-fno-signed-zeros",
"-fno-tree-vectorize",
"-Wno-pointer-to-int-cast",
"-Wno-parentheses",
"-Wno-switch",
"-Wno-format-zero-length",
"-Wno-pointer-sign",
"-Wno-unused-const-variable",
"-Wno-bool-operation",
"-Wno-char-subscripts",
};
const avcodec_sources = &.{
root_path ++ "ffmpeg/libavcodec/012v.c",
root_path ++ "ffmpeg/libavcodec/4xm.c",
root_path ++ "ffmpeg/libavcodec/8bps.c",
root_path ++ "ffmpeg/libavcodec/8svx.c",
root_path ++ "ffmpeg/libavcodec/a64multienc.c",
root_path ++ "ffmpeg/libavcodec/aac_ac3_parser.c",
root_path ++ "ffmpeg/libavcodec/aac_adtstoasc_bsf.c",
root_path ++ "ffmpeg/libavcodec/aac_parser.c",
root_path ++ "ffmpeg/libavcodec/aaccoder.c",
root_path ++ "ffmpeg/libavcodec/aacdec.c",
root_path ++ "ffmpeg/libavcodec/aacdec_fixed.c",
root_path ++ "ffmpeg/libavcodec/aacenc.c",
root_path ++ "ffmpeg/libavcodec/aacenc_is.c",
root_path ++ "ffmpeg/libavcodec/aacenc_ltp.c",
root_path ++ "ffmpeg/libavcodec/aacenc_pred.c",
root_path ++ "ffmpeg/libavcodec/aacenc_tns.c",
root_path ++ "ffmpeg/libavcodec/aacenctab.c",
root_path ++ "ffmpeg/libavcodec/aacps_common.c",
root_path ++ "ffmpeg/libavcodec/aacps_fixed.c",
root_path ++ "ffmpeg/libavcodec/aacps_float.c",
root_path ++ "ffmpeg/libavcodec/aacpsdsp_fixed.c",
root_path ++ "ffmpeg/libavcodec/aacpsdsp_float.c",
root_path ++ "ffmpeg/libavcodec/aacpsy.c",
root_path ++ "ffmpeg/libavcodec/aacsbr.c",
root_path ++ "ffmpeg/libavcodec/aacsbr_fixed.c",
root_path ++ "ffmpeg/libavcodec/aactab.c",
root_path ++ "ffmpeg/libavcodec/aandcttab.c",
root_path ++ "ffmpeg/libavcodec/aasc.c",
root_path ++ "ffmpeg/libavcodec/ac3.c",
root_path ++ "ffmpeg/libavcodec/ac3_parser.c",
root_path ++ "ffmpeg/libavcodec/ac3dec_data.c",
root_path ++ "ffmpeg/libavcodec/ac3dec_fixed.c",
root_path ++ "ffmpeg/libavcodec/ac3dec_float.c",
root_path ++ "ffmpeg/libavcodec/ac3dsp.c",
root_path ++ "ffmpeg/libavcodec/ac3enc.c",
root_path ++ "ffmpeg/libavcodec/ac3enc_fixed.c",
root_path ++ "ffmpeg/libavcodec/ac3enc_float.c",
root_path ++ "ffmpeg/libavcodec/ac3tab.c",
root_path ++ "ffmpeg/libavcodec/acelp_filters.c",
root_path ++ "ffmpeg/libavcodec/acelp_pitch_delay.c",
root_path ++ "ffmpeg/libavcodec/acelp_vectors.c",
root_path ++ "ffmpeg/libavcodec/adpcm.c",
root_path ++ "ffmpeg/libavcodec/adpcm_data.c",
root_path ++ "ffmpeg/libavcodec/adpcmenc.c",
root_path ++ "ffmpeg/libavcodec/adts_header.c",
root_path ++ "ffmpeg/libavcodec/adts_parser.c",
root_path ++ "ffmpeg/libavcodec/adx.c",
root_path ++ "ffmpeg/libavcodec/adx_parser.c",
root_path ++ "ffmpeg/libavcodec/adxdec.c",
root_path ++ "ffmpeg/libavcodec/adxenc.c",
root_path ++ "ffmpeg/libavcodec/agm.c",
root_path ++ "ffmpeg/libavcodec/aic.c",
root_path ++ "ffmpeg/libavcodec/alac.c",
root_path ++ "ffmpeg/libavcodec/alac_data.c",
root_path ++ "ffmpeg/libavcodec/alacdsp.c",
root_path ++ "ffmpeg/libavcodec/alacenc.c",
root_path ++ "ffmpeg/libavcodec/aliaspixdec.c",
root_path ++ "ffmpeg/libavcodec/aliaspixenc.c",
root_path ++ "ffmpeg/libavcodec/allcodecs.c",
root_path ++ "ffmpeg/libavcodec/alsdec.c",
root_path ++ "ffmpeg/libavcodec/amrnbdec.c",
root_path ++ "ffmpeg/libavcodec/amrwbdec.c",
root_path ++ "ffmpeg/libavcodec/anm.c",
root_path ++ "ffmpeg/libavcodec/ansi.c",
root_path ++ "ffmpeg/libavcodec/apedec.c",
root_path ++ "ffmpeg/libavcodec/aptx.c",
root_path ++ "ffmpeg/libavcodec/aptxdec.c",
root_path ++ "ffmpeg/libavcodec/aptxenc.c",
root_path ++ "ffmpeg/libavcodec/arbc.c",
root_path ++ "ffmpeg/libavcodec/argo.c",
root_path ++ "ffmpeg/libavcodec/ass.c",
root_path ++ "ffmpeg/libavcodec/ass_split.c",
root_path ++ "ffmpeg/libavcodec/assdec.c",
root_path ++ "ffmpeg/libavcodec/assenc.c",
root_path ++ "ffmpeg/libavcodec/asv.c",
root_path ++ "ffmpeg/libavcodec/asvdec.c",
root_path ++ "ffmpeg/libavcodec/asvenc.c",
root_path ++ "ffmpeg/libavcodec/atrac.c",
root_path ++ "ffmpeg/libavcodec/atrac1.c",
root_path ++ "ffmpeg/libavcodec/atrac3.c",
root_path ++ "ffmpeg/libavcodec/atrac3plus.c",
root_path ++ "ffmpeg/libavcodec/atrac3plusdec.c",
root_path ++ "ffmpeg/libavcodec/atrac3plusdsp.c",
root_path ++ "ffmpeg/libavcodec/atrac9dec.c",
root_path ++ "ffmpeg/libavcodec/atsc_a53.c",
root_path ++ "ffmpeg/libavcodec/audio_frame_queue.c",
root_path ++ "ffmpeg/libavcodec/audiodsp.c",
root_path ++ "ffmpeg/libavcodec/aura.c",
root_path ++ "ffmpeg/libavcodec/av1_frame_merge_bsf.c",
root_path ++ "ffmpeg/libavcodec/av1_frame_split_bsf.c",
root_path ++ "ffmpeg/libavcodec/av1_metadata_bsf.c",
root_path ++ "ffmpeg/libavcodec/av1_parse.c",
root_path ++ "ffmpeg/libavcodec/av1_parser.c",
root_path ++ "ffmpeg/libavcodec/av1dec.c",
root_path ++ "ffmpeg/libavcodec/avcodec.c",
root_path ++ "ffmpeg/libavcodec/avdct.c",
root_path ++ "ffmpeg/libavcodec/avfft.c",
root_path ++ "ffmpeg/libavcodec/avpacket.c",
root_path ++ "ffmpeg/libavcodec/avpicture.c",
root_path ++ "ffmpeg/libavcodec/avrndec.c",
root_path ++ "ffmpeg/libavcodec/avs.c",
root_path ++ "ffmpeg/libavcodec/avs2_parser.c",
root_path ++ "ffmpeg/libavcodec/avs3_parser.c",
root_path ++ "ffmpeg/libavcodec/avuidec.c",
root_path ++ "ffmpeg/libavcodec/avuienc.c",
root_path ++ "ffmpeg/libavcodec/bethsoftvideo.c",
root_path ++ "ffmpeg/libavcodec/bfi.c",
root_path ++ "ffmpeg/libavcodec/bgmc.c",
root_path ++ "ffmpeg/libavcodec/bink.c",
root_path ++ "ffmpeg/libavcodec/binkaudio.c",
root_path ++ "ffmpeg/libavcodec/binkdsp.c",
root_path ++ "ffmpeg/libavcodec/bintext.c",
root_path ++ "ffmpeg/libavcodec/bitpacked.c",
root_path ++ "ffmpeg/libavcodec/bitstream.c",
root_path ++ "ffmpeg/libavcodec/bitstream_filter.c",
root_path ++ "ffmpeg/libavcodec/bitstream_filters.c",
root_path ++ "ffmpeg/libavcodec/blockdsp.c",
root_path ++ "ffmpeg/libavcodec/bmp.c",
root_path ++ "ffmpeg/libavcodec/bmp_parser.c",
root_path ++ "ffmpeg/libavcodec/bmpenc.c",
root_path ++ "ffmpeg/libavcodec/bmvaudio.c",
root_path ++ "ffmpeg/libavcodec/bmvvideo.c",
root_path ++ "ffmpeg/libavcodec/brenderpix.c",
root_path ++ "ffmpeg/libavcodec/bsf.c",
root_path ++ "ffmpeg/libavcodec/bswapdsp.c",
root_path ++ "ffmpeg/libavcodec/c93.c",
root_path ++ "ffmpeg/libavcodec/cabac.c",
root_path ++ "ffmpeg/libavcodec/canopus.c",
root_path ++ "ffmpeg/libavcodec/cavs.c",
root_path ++ "ffmpeg/libavcodec/cavs_parser.c",
root_path ++ "ffmpeg/libavcodec/cavsdata.c",
root_path ++ "ffmpeg/libavcodec/cavsdec.c",
root_path ++ "ffmpeg/libavcodec/cavsdsp.c",
root_path ++ "ffmpeg/libavcodec/cbrt_data.c",
root_path ++ "ffmpeg/libavcodec/cbrt_data_fixed.c",
root_path ++ "ffmpeg/libavcodec/cbs.c",
root_path ++ "ffmpeg/libavcodec/cbs_av1.c",
root_path ++ "ffmpeg/libavcodec/cbs_bsf.c",
root_path ++ "ffmpeg/libavcodec/cbs_h2645.c",
root_path ++ "ffmpeg/libavcodec/cbs_mpeg2.c",
root_path ++ "ffmpeg/libavcodec/cbs_sei.c",
root_path ++ "ffmpeg/libavcodec/cbs_vp9.c",
root_path ++ "ffmpeg/libavcodec/ccaption_dec.c",
root_path ++ "ffmpeg/libavcodec/cdgraphics.c",
root_path ++ "ffmpeg/libavcodec/cdtoons.c",
root_path ++ "ffmpeg/libavcodec/cdxl.c",
root_path ++ "ffmpeg/libavcodec/celp_filters.c",
root_path ++ "ffmpeg/libavcodec/celp_math.c",
root_path ++ "ffmpeg/libavcodec/cfhd.c",
root_path ++ "ffmpeg/libavcodec/cfhddata.c",
root_path ++ "ffmpeg/libavcodec/cfhddsp.c",
root_path ++ "ffmpeg/libavcodec/cfhdenc.c",
root_path ++ "ffmpeg/libavcodec/cfhdencdsp.c",
root_path ++ "ffmpeg/libavcodec/cga_data.c",
root_path ++ "ffmpeg/libavcodec/chomp_bsf.c",
root_path ++ "ffmpeg/libavcodec/cinepak.c",
root_path ++ "ffmpeg/libavcodec/cinepakenc.c",
root_path ++ "ffmpeg/libavcodec/clearvideo.c",
root_path ++ "ffmpeg/libavcodec/cljrdec.c",
root_path ++ "ffmpeg/libavcodec/cljrenc.c",
root_path ++ "ffmpeg/libavcodec/cllc.c",
root_path ++ "ffmpeg/libavcodec/cngdec.c",
root_path ++ "ffmpeg/libavcodec/cngenc.c",
root_path ++ "ffmpeg/libavcodec/codec2utils.c",
root_path ++ "ffmpeg/libavcodec/codec_desc.c",
root_path ++ "ffmpeg/libavcodec/codec_par.c",
root_path ++ "ffmpeg/libavcodec/cook.c",
root_path ++ "ffmpeg/libavcodec/cook_parser.c",
root_path ++ "ffmpeg/libavcodec/cpia.c",
root_path ++ "ffmpeg/libavcodec/cri.c",
root_path ++ "ffmpeg/libavcodec/cri_parser.c",
root_path ++ "ffmpeg/libavcodec/cscd.c",
root_path ++ "ffmpeg/libavcodec/cyuv.c",
root_path ++ "ffmpeg/libavcodec/d3d11va.c",
root_path ++ "ffmpeg/libavcodec/dca.c",
root_path ++ "ffmpeg/libavcodec/dca_core.c",
root_path ++ "ffmpeg/libavcodec/dca_core_bsf.c",
root_path ++ "ffmpeg/libavcodec/dca_exss.c",
root_path ++ "ffmpeg/libavcodec/dca_lbr.c",
root_path ++ "ffmpeg/libavcodec/dca_parser.c",
root_path ++ "ffmpeg/libavcodec/dca_xll.c",
root_path ++ "ffmpeg/libavcodec/dcaadpcm.c",
root_path ++ "ffmpeg/libavcodec/dcadata.c",
root_path ++ "ffmpeg/libavcodec/dcadct.c",
root_path ++ "ffmpeg/libavcodec/dcadec.c",
root_path ++ "ffmpeg/libavcodec/dcadsp.c",
root_path ++ "ffmpeg/libavcodec/dcaenc.c",
root_path ++ "ffmpeg/libavcodec/dcahuff.c",
root_path ++ "ffmpeg/libavcodec/dct.c",
root_path ++ "ffmpeg/libavcodec/dct32_fixed.c",
root_path ++ "ffmpeg/libavcodec/dct32_float.c",
root_path ++ "ffmpeg/libavcodec/dds.c",
root_path ++ "ffmpeg/libavcodec/decode.c",
root_path ++ "ffmpeg/libavcodec/dfa.c",
root_path ++ "ffmpeg/libavcodec/dirac.c",
root_path ++ "ffmpeg/libavcodec/dirac_arith.c",
root_path ++ "ffmpeg/libavcodec/dirac_dwt.c",
root_path ++ "ffmpeg/libavcodec/dirac_parser.c",
root_path ++ "ffmpeg/libavcodec/dirac_vlc.c",
root_path ++ "ffmpeg/libavcodec/diracdec.c",
root_path ++ "ffmpeg/libavcodec/diracdsp.c",
root_path ++ "ffmpeg/libavcodec/diractab.c",
root_path ++ "ffmpeg/libavcodec/dnxhd_parser.c",
root_path ++ "ffmpeg/libavcodec/dnxhddata.c",
root_path ++ "ffmpeg/libavcodec/dnxhddec.c",
root_path ++ "ffmpeg/libavcodec/dnxhdenc.c",
root_path ++ "ffmpeg/libavcodec/dolby_e.c",
root_path ++ "ffmpeg/libavcodec/dolby_e_parse.c",
root_path ++ "ffmpeg/libavcodec/dolby_e_parser.c",
root_path ++ "ffmpeg/libavcodec/dpcm.c",
root_path ++ "ffmpeg/libavcodec/dpx.c",
root_path ++ "ffmpeg/libavcodec/dpx_parser.c",
root_path ++ "ffmpeg/libavcodec/dpxenc.c",
root_path ++ "ffmpeg/libavcodec/dsd.c",
root_path ++ "ffmpeg/libavcodec/dsddec.c",
root_path ++ "ffmpeg/libavcodec/dsicinaudio.c",
root_path ++ "ffmpeg/libavcodec/dsicinvideo.c",
root_path ++ "ffmpeg/libavcodec/dss_sp.c",
root_path ++ "ffmpeg/libavcodec/dstdec.c",
root_path ++ "ffmpeg/libavcodec/dump_extradata_bsf.c",
root_path ++ "ffmpeg/libavcodec/dv.c",
root_path ++ "ffmpeg/libavcodec/dv_profile.c",
root_path ++ "ffmpeg/libavcodec/dvaudio_parser.c",
root_path ++ "ffmpeg/libavcodec/dvaudiodec.c",
root_path ++ "ffmpeg/libavcodec/dvbsub_parser.c",
root_path ++ "ffmpeg/libavcodec/dvbsubdec.c",
root_path ++ "ffmpeg/libavcodec/dvbsubenc.c",
root_path ++ "ffmpeg/libavcodec/dvd_nav_parser.c",
root_path ++ "ffmpeg/libavcodec/dvdata.c",
root_path ++ "ffmpeg/libavcodec/dvdec.c",
root_path ++ "ffmpeg/libavcodec/dvdsub.c",
root_path ++ "ffmpeg/libavcodec/dvdsub_parser.c",
root_path ++ "ffmpeg/libavcodec/dvdsubdec.c",
root_path ++ "ffmpeg/libavcodec/dvdsubenc.c",
root_path ++ "ffmpeg/libavcodec/dvenc.c",
root_path ++ "ffmpeg/libavcodec/dxa.c",
root_path ++ "ffmpeg/libavcodec/dxtory.c",
root_path ++ "ffmpeg/libavcodec/dxv.c",
root_path ++ "ffmpeg/libavcodec/dynamic_hdr10_plus.c",
root_path ++ "ffmpeg/libavcodec/eac3_core_bsf.c",
root_path ++ "ffmpeg/libavcodec/eac3_data.c",
root_path ++ "ffmpeg/libavcodec/eac3enc.c",
root_path ++ "ffmpeg/libavcodec/eacmv.c",
root_path ++ "ffmpeg/libavcodec/eaidct.c",
root_path ++ "ffmpeg/libavcodec/eamad.c",
root_path ++ "ffmpeg/libavcodec/eatgq.c",
root_path ++ "ffmpeg/libavcodec/eatgv.c",
root_path ++ "ffmpeg/libavcodec/eatqi.c",
root_path ++ "ffmpeg/libavcodec/elbg.c",
root_path ++ "ffmpeg/libavcodec/elsdec.c",
root_path ++ "ffmpeg/libavcodec/encode.c",
root_path ++ "ffmpeg/libavcodec/error_resilience.c",
root_path ++ "ffmpeg/libavcodec/escape124.c",
root_path ++ "ffmpeg/libavcodec/escape130.c",
root_path ++ "ffmpeg/libavcodec/evrcdec.c",
root_path ++ "ffmpeg/libavcodec/exif.c",
root_path ++ "ffmpeg/libavcodec/exr.c",
root_path ++ "ffmpeg/libavcodec/exrdsp.c",
root_path ++ "ffmpeg/libavcodec/exrenc.c",
root_path ++ "ffmpeg/libavcodec/extract_extradata_bsf.c",
root_path ++ "ffmpeg/libavcodec/faandct.c",
root_path ++ "ffmpeg/libavcodec/faanidct.c",
root_path ++ "ffmpeg/libavcodec/fastaudio.c",
root_path ++ "ffmpeg/libavcodec/faxcompr.c",
root_path ++ "ffmpeg/libavcodec/fdctdsp.c",
root_path ++ "ffmpeg/libavcodec/fft_fixed_32.c",
root_path ++ "ffmpeg/libavcodec/fft_float.c",
root_path ++ "ffmpeg/libavcodec/fft_init_table.c",
root_path ++ "ffmpeg/libavcodec/ffv1.c",
root_path ++ "ffmpeg/libavcodec/ffv1dec.c",
root_path ++ "ffmpeg/libavcodec/ffv1enc.c",
root_path ++ "ffmpeg/libavcodec/ffwavesynth.c",
root_path ++ "ffmpeg/libavcodec/fic.c",
root_path ++ "ffmpeg/libavcodec/filter_units_bsf.c",
root_path ++ "ffmpeg/libavcodec/fits.c",
root_path ++ "ffmpeg/libavcodec/fitsdec.c",
root_path ++ "ffmpeg/libavcodec/fitsenc.c",
root_path ++ "ffmpeg/libavcodec/flac.c",
root_path ++ "ffmpeg/libavcodec/flac_parser.c",
root_path ++ "ffmpeg/libavcodec/flacdata.c",
root_path ++ "ffmpeg/libavcodec/flacdec.c",
root_path ++ "ffmpeg/libavcodec/flacdsp.c",
root_path ++ "ffmpeg/libavcodec/flacenc.c",
root_path ++ "ffmpeg/libavcodec/flashsv.c",
root_path ++ "ffmpeg/libavcodec/flashsv2enc.c",
root_path ++ "ffmpeg/libavcodec/flashsvenc.c",
root_path ++ "ffmpeg/libavcodec/flicvideo.c",
root_path ++ "ffmpeg/libavcodec/flvdec.c",
root_path ++ "ffmpeg/libavcodec/flvenc.c",
root_path ++ "ffmpeg/libavcodec/fmtconvert.c",
root_path ++ "ffmpeg/libavcodec/fmvc.c",
root_path ++ "ffmpeg/libavcodec/frame_thread_encoder.c",
root_path ++ "ffmpeg/libavcodec/fraps.c",
root_path ++ "ffmpeg/libavcodec/frwu.c",
root_path ++ "ffmpeg/libavcodec/g2meet.c",
root_path ++ "ffmpeg/libavcodec/g722.c",
root_path ++ "ffmpeg/libavcodec/g722dec.c",
root_path ++ "ffmpeg/libavcodec/g722dsp.c",
root_path ++ "ffmpeg/libavcodec/g722enc.c",
root_path ++ "ffmpeg/libavcodec/g723_1.c",
root_path ++ "ffmpeg/libavcodec/g723_1_parser.c",
root_path ++ "ffmpeg/libavcodec/g723_1dec.c",
root_path ++ "ffmpeg/libavcodec/g723_1enc.c",
root_path ++ "ffmpeg/libavcodec/g726.c",
root_path ++ "ffmpeg/libavcodec/g729_parser.c",
root_path ++ "ffmpeg/libavcodec/g729dec.c",
root_path ++ "ffmpeg/libavcodec/g729postfilter.c",
root_path ++ "ffmpeg/libavcodec/gdv.c",
root_path ++ "ffmpeg/libavcodec/gif.c",
root_path ++ "ffmpeg/libavcodec/gif_parser.c",
root_path ++ "ffmpeg/libavcodec/gifdec.c",
root_path ++ "ffmpeg/libavcodec/golomb.c",
root_path ++ "ffmpeg/libavcodec/gsm_parser.c",
root_path ++ "ffmpeg/libavcodec/gsmdec.c",
root_path ++ "ffmpeg/libavcodec/gsmdec_data.c",
root_path ++ "ffmpeg/libavcodec/h261.c",
root_path ++ "ffmpeg/libavcodec/h261_parser.c",
root_path ++ "ffmpeg/libavcodec/h261data.c",
root_path ++ "ffmpeg/libavcodec/h261dec.c",
root_path ++ "ffmpeg/libavcodec/h261enc.c",
root_path ++ "ffmpeg/libavcodec/h263.c",
root_path ++ "ffmpeg/libavcodec/h263_parser.c",
root_path ++ "ffmpeg/libavcodec/h263data.c",
root_path ++ "ffmpeg/libavcodec/h263dec.c",
root_path ++ "ffmpeg/libavcodec/h263dsp.c",
root_path ++ "ffmpeg/libavcodec/h2645_parse.c",
root_path ++ "ffmpeg/libavcodec/h264_cabac.c",
root_path ++ "ffmpeg/libavcodec/h264_cavlc.c",
root_path ++ "ffmpeg/libavcodec/h264_direct.c",
root_path ++ "ffmpeg/libavcodec/h264_levels.c",
root_path ++ "ffmpeg/libavcodec/h264_loopfilter.c",
root_path ++ "ffmpeg/libavcodec/h264_mb.c",
root_path ++ "ffmpeg/libavcodec/h264_metadata_bsf.c",
root_path ++ "ffmpeg/libavcodec/h264_mp4toannexb_bsf.c",
root_path ++ "ffmpeg/libavcodec/h264_parse.c",
root_path ++ "ffmpeg/libavcodec/h264_parser.c",
root_path ++ "ffmpeg/libavcodec/h264_picture.c",
root_path ++ "ffmpeg/libavcodec/h264_ps.c",
root_path ++ "ffmpeg/libavcodec/h264_redundant_pps_bsf.c",
root_path ++ "ffmpeg/libavcodec/h264_refs.c",
root_path ++ "ffmpeg/libavcodec/h264_sei.c",
root_path ++ "ffmpeg/libavcodec/h264_slice.c",
root_path ++ "ffmpeg/libavcodec/h264chroma.c",
root_path ++ "ffmpeg/libavcodec/h264data.c",
root_path ++ "ffmpeg/libavcodec/h264dec.c",
root_path ++ "ffmpeg/libavcodec/h264dsp.c",
root_path ++ "ffmpeg/libavcodec/h264idct.c",
root_path ++ "ffmpeg/libavcodec/h264pred.c",
root_path ++ "ffmpeg/libavcodec/h264qpel.c",
root_path ++ "ffmpeg/libavcodec/h265_metadata_bsf.c",
root_path ++ "ffmpeg/libavcodec/h265_profile_level.c",
root_path ++ "ffmpeg/libavcodec/hap.c",
root_path ++ "ffmpeg/libavcodec/hapdec.c",
root_path ++ "ffmpeg/libavcodec/hapqa_extract_bsf.c",
root_path ++ "ffmpeg/libavcodec/hcadec.c",
root_path ++ "ffmpeg/libavcodec/hcom.c",
root_path ++ "ffmpeg/libavcodec/hevc_cabac.c",
root_path ++ "ffmpeg/libavcodec/hevc_data.c",
root_path ++ "ffmpeg/libavcodec/hevc_filter.c",
root_path ++ "ffmpeg/libavcodec/hevc_mp4toannexb_bsf.c",
root_path ++ "ffmpeg/libavcodec/hevc_mvs.c",
root_path ++ "ffmpeg/libavcodec/hevc_parse.c",
root_path ++ "ffmpeg/libavcodec/hevc_parser.c",
root_path ++ "ffmpeg/libavcodec/hevc_ps.c",
root_path ++ "ffmpeg/libavcodec/hevc_refs.c",
root_path ++ "ffmpeg/libavcodec/hevc_sei.c",
root_path ++ "ffmpeg/libavcodec/hevcdec.c",
root_path ++ "ffmpeg/libavcodec/hevcdsp.c",
root_path ++ "ffmpeg/libavcodec/hevcpred.c",
root_path ++ "ffmpeg/libavcodec/hnm4video.c",
root_path ++ "ffmpeg/libavcodec/hpeldsp.c",
root_path ++ "ffmpeg/libavcodec/hq_hqa.c",
root_path ++ "ffmpeg/libavcodec/hq_hqadata.c",
root_path ++ "ffmpeg/libavcodec/hq_hqadsp.c",
root_path ++ "ffmpeg/libavcodec/hqx.c",
root_path ++ "ffmpeg/libavcodec/hqxdsp.c",
root_path ++ "ffmpeg/libavcodec/hqxvlc.c",
root_path ++ "ffmpeg/libavcodec/htmlsubtitles.c",
root_path ++ "ffmpeg/libavcodec/huffman.c",
root_path ++ "ffmpeg/libavcodec/huffyuv.c",
root_path ++ "ffmpeg/libavcodec/huffyuvdec.c",
root_path ++ "ffmpeg/libavcodec/huffyuvdsp.c",
root_path ++ "ffmpeg/libavcodec/huffyuvenc.c",
root_path ++ "ffmpeg/libavcodec/huffyuvencdsp.c",
root_path ++ "ffmpeg/libavcodec/idcinvideo.c",
root_path ++ "ffmpeg/libavcodec/idctdsp.c",
root_path ++ "ffmpeg/libavcodec/iff.c",
root_path ++ "ffmpeg/libavcodec/iirfilter.c",
root_path ++ "ffmpeg/libavcodec/ilbcdec.c",
root_path ++ "ffmpeg/libavcodec/imc.c",
root_path ++ "ffmpeg/libavcodec/imgconvert.c",
root_path ++ "ffmpeg/libavcodec/imm4.c",
root_path ++ "ffmpeg/libavcodec/imm5.c",
root_path ++ "ffmpeg/libavcodec/imx.c",
root_path ++ "ffmpeg/libavcodec/imx_dump_header_bsf.c",
root_path ++ "ffmpeg/libavcodec/indeo2.c",
root_path ++ "ffmpeg/libavcodec/indeo3.c",
root_path ++ "ffmpeg/libavcodec/indeo4.c",
root_path ++ "ffmpeg/libavcodec/indeo5.c",
root_path ++ "ffmpeg/libavcodec/intelh263dec.c",
root_path ++ "ffmpeg/libavcodec/interplayacm.c",
root_path ++ "ffmpeg/libavcodec/interplayvideo.c",
root_path ++ "ffmpeg/libavcodec/intrax8.c",
root_path ++ "ffmpeg/libavcodec/intrax8dsp.c",
root_path ++ "ffmpeg/libavcodec/ipu_parser.c",
root_path ++ "ffmpeg/libavcodec/ituh263dec.c",
root_path ++ "ffmpeg/libavcodec/ituh263enc.c",
root_path ++ "ffmpeg/libavcodec/ivi.c",
root_path ++ "ffmpeg/libavcodec/ivi_dsp.c",
root_path ++ "ffmpeg/libavcodec/j2kenc.c",
root_path ++ "ffmpeg/libavcodec/jacosubdec.c",
root_path ++ "ffmpeg/libavcodec/jfdctfst.c",
root_path ++ "ffmpeg/libavcodec/jfdctint.c",
root_path ++ "ffmpeg/libavcodec/jni.c",
root_path ++ "ffmpeg/libavcodec/jpeg2000.c",
root_path ++ "ffmpeg/libavcodec/jpeg2000_parser.c",
root_path ++ "ffmpeg/libavcodec/jpeg2000dec.c",
root_path ++ "ffmpeg/libavcodec/jpeg2000dsp.c",
root_path ++ "ffmpeg/libavcodec/jpeg2000dwt.c",
root_path ++ "ffmpeg/libavcodec/jpegls.c",
root_path ++ "ffmpeg/libavcodec/jpeglsdec.c",
root_path ++ "ffmpeg/libavcodec/jpeglsenc.c",
root_path ++ "ffmpeg/libavcodec/jpegtables.c",
root_path ++ "ffmpeg/libavcodec/jrevdct.c",
root_path ++ "ffmpeg/libavcodec/jvdec.c",
root_path ++ "ffmpeg/libavcodec/kbdwin.c",
root_path ++ "ffmpeg/libavcodec/kgv1dec.c",
root_path ++ "ffmpeg/libavcodec/kmvc.c",
root_path ++ "ffmpeg/libavcodec/lagarith.c",
root_path ++ "ffmpeg/libavcodec/lagarithrac.c",
root_path ++ "ffmpeg/libavcodec/latm_parser.c",
root_path ++ "ffmpeg/libavcodec/lcldec.c",
root_path ++ "ffmpeg/libavcodec/lclenc.c",
root_path ++ "ffmpeg/libavcodec/libmp3lame.c",
root_path ++ "ffmpeg/libavcodec/ljpegenc.c",
root_path ++ "ffmpeg/libavcodec/loco.c",
root_path ++ "ffmpeg/libavcodec/lossless_audiodsp.c",
root_path ++ "ffmpeg/libavcodec/lossless_videodsp.c",
root_path ++ "ffmpeg/libavcodec/lossless_videoencdsp.c",
root_path ++ "ffmpeg/libavcodec/lpc.c",
root_path ++ "ffmpeg/libavcodec/lscrdec.c",
root_path ++ "ffmpeg/libavcodec/lsp.c",
root_path ++ "ffmpeg/libavcodec/lzf.c",
root_path ++ "ffmpeg/libavcodec/lzw.c",
root_path ++ "ffmpeg/libavcodec/lzwenc.c",
root_path ++ "ffmpeg/libavcodec/m101.c",
root_path ++ "ffmpeg/libavcodec/mace.c",
root_path ++ "ffmpeg/libavcodec/magicyuv.c",
root_path ++ "ffmpeg/libavcodec/magicyuvenc.c",
root_path ++ "ffmpeg/libavcodec/mathtables.c",
root_path ++ "ffmpeg/libavcodec/mdct15.c",
root_path ++ "ffmpeg/libavcodec/mdct_fixed_32.c",
root_path ++ "ffmpeg/libavcodec/mdct_float.c",
root_path ++ "ffmpeg/libavcodec/mdec.c",
root_path ++ "ffmpeg/libavcodec/me_cmp.c",
root_path ++ "ffmpeg/libavcodec/mediacodec.c",
root_path ++ "ffmpeg/libavcodec/metasound.c",
root_path ++ "ffmpeg/libavcodec/metasound_data.c",
root_path ++ "ffmpeg/libavcodec/microdvddec.c",
root_path ++ "ffmpeg/libavcodec/midivid.c",
root_path ++ "ffmpeg/libavcodec/mimic.c",
root_path ++ "ffmpeg/libavcodec/mjpeg2jpeg_bsf.c",
root_path ++ "ffmpeg/libavcodec/mjpeg_parser.c",
root_path ++ "ffmpeg/libavcodec/mjpega_dump_header_bsf.c",
root_path ++ "ffmpeg/libavcodec/mjpegbdec.c",
root_path ++ "ffmpeg/libavcodec/mjpegdec.c",
root_path ++ "ffmpeg/libavcodec/mjpegdec_common.c",
root_path ++ "ffmpeg/libavcodec/mjpegenc.c",
root_path ++ "ffmpeg/libavcodec/mjpegenc_common.c",
root_path ++ "ffmpeg/libavcodec/mjpegenc_huffman.c",
root_path ++ "ffmpeg/libavcodec/mlp.c",
root_path ++ "ffmpeg/libavcodec/mlp_parse.c",
root_path ++ "ffmpeg/libavcodec/mlp_parser.c",
root_path ++ "ffmpeg/libavcodec/mlpdec.c",
root_path ++ "ffmpeg/libavcodec/mlpdsp.c",
root_path ++ "ffmpeg/libavcodec/mlpenc.c",
root_path ++ "ffmpeg/libavcodec/mlz.c",
root_path ++ "ffmpeg/libavcodec/mmvideo.c",
root_path ++ "ffmpeg/libavcodec/mobiclip.c",
root_path ++ "ffmpeg/libavcodec/motion_est.c",
root_path ++ "ffmpeg/libavcodec/motionpixels.c",
root_path ++ "ffmpeg/libavcodec/movsub_bsf.c",
root_path ++ "ffmpeg/libavcodec/movtextdec.c",
root_path ++ "ffmpeg/libavcodec/movtextenc.c",
root_path ++ "ffmpeg/libavcodec/mp3_header_decompress_bsf.c",
root_path ++ "ffmpeg/libavcodec/mpc.c",
root_path ++ "ffmpeg/libavcodec/mpc7.c",
root_path ++ "ffmpeg/libavcodec/mpc8.c",
root_path ++ "ffmpeg/libavcodec/mpeg12.c",
root_path ++ "ffmpeg/libavcodec/mpeg12data.c",
root_path ++ "ffmpeg/libavcodec/mpeg12dec.c",
root_path ++ "ffmpeg/libavcodec/mpeg12enc.c",
root_path ++ "ffmpeg/libavcodec/mpeg12framerate.c",
root_path ++ "ffmpeg/libavcodec/mpeg2_metadata_bsf.c",
root_path ++ "ffmpeg/libavcodec/mpeg4_unpack_bframes_bsf.c",
root_path ++ "ffmpeg/libavcodec/mpeg4audio.c",
root_path ++ "ffmpeg/libavcodec/mpeg4video.c",
root_path ++ "ffmpeg/libavcodec/mpeg4video_parser.c",
root_path ++ "ffmpeg/libavcodec/mpeg4videodec.c",
root_path ++ "ffmpeg/libavcodec/mpeg4videoenc.c",
root_path ++ "ffmpeg/libavcodec/mpeg_er.c",
root_path ++ "ffmpeg/libavcodec/mpegaudio.c",
root_path ++ "ffmpeg/libavcodec/mpegaudio_parser.c",
root_path ++ "ffmpeg/libavcodec/mpegaudiodata.c",
root_path ++ "ffmpeg/libavcodec/mpegaudiodec_common.c",
root_path ++ "ffmpeg/libavcodec/mpegaudiodec_fixed.c",
root_path ++ "ffmpeg/libavcodec/mpegaudiodec_float.c",
root_path ++ "ffmpeg/libavcodec/mpegaudiodecheader.c",
root_path ++ "ffmpeg/libavcodec/mpegaudiodsp.c",
root_path ++ "ffmpeg/libavcodec/mpegaudiodsp_data.c",
root_path ++ "ffmpeg/libavcodec/mpegaudiodsp_fixed.c",
root_path ++ "ffmpeg/libavcodec/mpegaudiodsp_float.c",
root_path ++ "ffmpeg/libavcodec/mpegaudioenc_fixed.c",
root_path ++ "ffmpeg/libavcodec/mpegaudioenc_float.c",
root_path ++ "ffmpeg/libavcodec/mpegpicture.c",
root_path ++ "ffmpeg/libavcodec/mpegutils.c",
root_path ++ "ffmpeg/libavcodec/mpegvideo.c",
root_path ++ "ffmpeg/libavcodec/mpegvideo_enc.c",
root_path ++ "ffmpeg/libavcodec/mpegvideo_motion.c",
root_path ++ "ffmpeg/libavcodec/mpegvideo_parser.c",
root_path ++ "ffmpeg/libavcodec/mpegvideodata.c",
root_path ++ "ffmpeg/libavcodec/mpegvideodsp.c",
root_path ++ "ffmpeg/libavcodec/mpegvideoencdsp.c",
root_path ++ "ffmpeg/libavcodec/mpl2dec.c",
root_path ++ "ffmpeg/libavcodec/mqc.c",
root_path ++ "ffmpeg/libavcodec/mqcdec.c",
root_path ++ "ffmpeg/libavcodec/mqcenc.c",
root_path ++ "ffmpeg/libavcodec/mscc.c",
root_path ++ "ffmpeg/libavcodec/msgsmdec.c",
root_path ++ "ffmpeg/libavcodec/msmpeg4.c",
root_path ++ "ffmpeg/libavcodec/msmpeg4data.c",
root_path ++ "ffmpeg/libavcodec/msmpeg4dec.c",
root_path ++ "ffmpeg/libavcodec/msmpeg4enc.c",
root_path ++ "ffmpeg/libavcodec/msp2dec.c",
root_path ++ "ffmpeg/libavcodec/msrle.c",
root_path ++ "ffmpeg/libavcodec/msrledec.c",
root_path ++ "ffmpeg/libavcodec/mss1.c",
root_path ++ "ffmpeg/libavcodec/mss12.c",
root_path ++ "ffmpeg/libavcodec/mss2.c",
root_path ++ "ffmpeg/libavcodec/mss2dsp.c",
root_path ++ "ffmpeg/libavcodec/mss3.c",
root_path ++ "ffmpeg/libavcodec/mss34dsp.c",
root_path ++ "ffmpeg/libavcodec/mss4.c",
root_path ++ "ffmpeg/libavcodec/msvideo1.c",
root_path ++ "ffmpeg/libavcodec/msvideo1enc.c",
root_path ++ "ffmpeg/libavcodec/mv30.c",
root_path ++ "ffmpeg/libavcodec/mvcdec.c",
root_path ++ "ffmpeg/libavcodec/mvha.c",
root_path ++ "ffmpeg/libavcodec/mwsc.c",
root_path ++ "ffmpeg/libavcodec/mxpegdec.c",
root_path ++ "ffmpeg/libavcodec/nellymoser.c",
root_path ++ "ffmpeg/libavcodec/nellymoserdec.c",
root_path ++ "ffmpeg/libavcodec/nellymoserenc.c",
root_path ++ "ffmpeg/libavcodec/noise_bsf.c",
root_path ++ "ffmpeg/libavcodec/notchlc.c",
root_path ++ "ffmpeg/libavcodec/null_bsf.c",
root_path ++ "ffmpeg/libavcodec/nuv.c",
root_path ++ "ffmpeg/libavcodec/on2avc.c",
root_path ++ "ffmpeg/libavcodec/on2avcdata.c",
root_path ++ "ffmpeg/libavcodec/options.c",
root_path ++ "ffmpeg/libavcodec/opus.c",
root_path ++ "ffmpeg/libavcodec/opus_celt.c",
root_path ++ "ffmpeg/libavcodec/opus_metadata_bsf.c",
root_path ++ "ffmpeg/libavcodec/opus_parser.c",
root_path ++ "ffmpeg/libavcodec/opus_pvq.c",
root_path ++ "ffmpeg/libavcodec/opus_rc.c",
root_path ++ "ffmpeg/libavcodec/opus_silk.c",
root_path ++ "ffmpeg/libavcodec/opusdec.c",
root_path ++ "ffmpeg/libavcodec/opusdsp.c",
root_path ++ "ffmpeg/libavcodec/opusenc.c",
root_path ++ "ffmpeg/libavcodec/opusenc_psy.c",
root_path ++ "ffmpeg/libavcodec/opustab.c",
root_path ++ "ffmpeg/libavcodec/pafaudio.c",
root_path ++ "ffmpeg/libavcodec/pafvideo.c",
root_path ++ "ffmpeg/libavcodec/pamenc.c",
root_path ++ "ffmpeg/libavcodec/parser.c",
root_path ++ "ffmpeg/libavcodec/parsers.c",
root_path ++ "ffmpeg/libavcodec/pcm-bluray.c",
root_path ++ "ffmpeg/libavcodec/pcm-dvd.c",
root_path ++ "ffmpeg/libavcodec/pcm-dvdenc.c",
root_path ++ "ffmpeg/libavcodec/pcm.c",
root_path ++ "ffmpeg/libavcodec/pcm_rechunk_bsf.c",
root_path ++ "ffmpeg/libavcodec/pcx.c",
root_path ++ "ffmpeg/libavcodec/pcxenc.c",
root_path ++ "ffmpeg/libavcodec/pgssubdec.c",
root_path ++ "ffmpeg/libavcodec/pgxdec.c",
root_path ++ "ffmpeg/libavcodec/photocd.c",
root_path ++ "ffmpeg/libavcodec/pictordec.c",
root_path ++ "ffmpeg/libavcodec/pixblockdsp.c",
root_path ++ "ffmpeg/libavcodec/pixlet.c",
root_path ++ "ffmpeg/libavcodec/png.c",
root_path ++ "ffmpeg/libavcodec/png_parser.c",
root_path ++ "ffmpeg/libavcodec/pngdec.c",
root_path ++ "ffmpeg/libavcodec/pngdsp.c",
root_path ++ "ffmpeg/libavcodec/pngenc.c",
root_path ++ "ffmpeg/libavcodec/pnm.c",
root_path ++ "ffmpeg/libavcodec/pnm_parser.c",
root_path ++ "ffmpeg/libavcodec/pnmdec.c",
root_path ++ "ffmpeg/libavcodec/pnmenc.c",
root_path ++ "ffmpeg/libavcodec/profiles.c",
root_path ++ "ffmpeg/libavcodec/prores_metadata_bsf.c",
root_path ++ "ffmpeg/libavcodec/proresdata.c",
root_path ++ "ffmpeg/libavcodec/proresdec2.c",
root_path ++ "ffmpeg/libavcodec/proresdsp.c",
root_path ++ "ffmpeg/libavcodec/proresenc_anatoliy.c",
root_path ++ "ffmpeg/libavcodec/proresenc_kostya.c",
root_path ++ "ffmpeg/libavcodec/prosumer.c",
root_path ++ "ffmpeg/libavcodec/psd.c",
root_path ++ "ffmpeg/libavcodec/psymodel.c",
root_path ++ "ffmpeg/libavcodec/pthread.c",
root_path ++ "ffmpeg/libavcodec/pthread_frame.c",
root_path ++ "ffmpeg/libavcodec/pthread_slice.c",
root_path ++ "ffmpeg/libavcodec/ptx.c",
root_path ++ "ffmpeg/libavcodec/qcelpdec.c",
root_path ++ "ffmpeg/libavcodec/qdm2.c",
root_path ++ "ffmpeg/libavcodec/qdmc.c",
root_path ++ "ffmpeg/libavcodec/qdrw.c",
root_path ++ "ffmpeg/libavcodec/qpeg.c",
root_path ++ "ffmpeg/libavcodec/qpeldsp.c",
root_path ++ "ffmpeg/libavcodec/qsv_api.c",
root_path ++ "ffmpeg/libavcodec/qtrle.c",
root_path ++ "ffmpeg/libavcodec/qtrleenc.c",
root_path ++ "ffmpeg/libavcodec/r210dec.c",
root_path ++ "ffmpeg/libavcodec/r210enc.c",
root_path ++ "ffmpeg/libavcodec/ra144.c",
root_path ++ "ffmpeg/libavcodec/ra144dec.c",
root_path ++ "ffmpeg/libavcodec/ra144enc.c",
root_path ++ "ffmpeg/libavcodec/ra288.c",
root_path ++ "ffmpeg/libavcodec/ralf.c",
root_path ++ "ffmpeg/libavcodec/rangecoder.c",
root_path ++ "ffmpeg/libavcodec/rasc.c",
root_path ++ "ffmpeg/libavcodec/ratecontrol.c",
root_path ++ "ffmpeg/libavcodec/raw.c",
root_path ++ "ffmpeg/libavcodec/rawdec.c",
root_path ++ "ffmpeg/libavcodec/rawenc.c",
root_path ++ "ffmpeg/libavcodec/rdft.c",
root_path ++ "ffmpeg/libavcodec/realtextdec.c",
root_path ++ "ffmpeg/libavcodec/remove_extradata_bsf.c",
root_path ++ "ffmpeg/libavcodec/rl.c",
root_path ++ "ffmpeg/libavcodec/rl2.c",
root_path ++ "ffmpeg/libavcodec/rle.c",
root_path ++ "ffmpeg/libavcodec/roqaudioenc.c",
root_path ++ "ffmpeg/libavcodec/roqvideo.c",
root_path ++ "ffmpeg/libavcodec/roqvideodec.c",
root_path ++ "ffmpeg/libavcodec/roqvideoenc.c",
root_path ++ "ffmpeg/libavcodec/rpza.c",
root_path ++ "ffmpeg/libavcodec/rpzaenc.c",
root_path ++ "ffmpeg/libavcodec/rscc.c",
root_path ++ "ffmpeg/libavcodec/rtjpeg.c",
root_path ++ "ffmpeg/libavcodec/rv10.c",
root_path ++ "ffmpeg/libavcodec/rv10enc.c",
root_path ++ "ffmpeg/libavcodec/rv20enc.c",
root_path ++ "ffmpeg/libavcodec/rv30.c",
root_path ++ "ffmpeg/libavcodec/rv30dsp.c",
root_path ++ "ffmpeg/libavcodec/rv34.c",
root_path ++ "ffmpeg/libavcodec/rv34_parser.c",
root_path ++ "ffmpeg/libavcodec/rv34dsp.c",
root_path ++ "ffmpeg/libavcodec/rv40.c",
root_path ++ "ffmpeg/libavcodec/rv40dsp.c",
root_path ++ "ffmpeg/libavcodec/s302m.c",
root_path ++ "ffmpeg/libavcodec/s302menc.c",
root_path ++ "ffmpeg/libavcodec/samidec.c",
root_path ++ "ffmpeg/libavcodec/sanm.c",
root_path ++ "ffmpeg/libavcodec/sbc.c",
root_path ++ "ffmpeg/libavcodec/sbc_parser.c",
root_path ++ "ffmpeg/libavcodec/sbcdec.c",
root_path ++ "ffmpeg/libavcodec/sbcdec_data.c",
root_path ++ "ffmpeg/libavcodec/sbcdsp.c",
root_path ++ "ffmpeg/libavcodec/sbcdsp_data.c",
root_path ++ "ffmpeg/libavcodec/sbcenc.c",
root_path ++ "ffmpeg/libavcodec/sbrdsp.c",
root_path ++ "ffmpeg/libavcodec/sbrdsp_fixed.c",
root_path ++ "ffmpeg/libavcodec/scpr.c",
root_path ++ "ffmpeg/libavcodec/screenpresso.c",
root_path ++ "ffmpeg/libavcodec/setts_bsf.c",
root_path ++ "ffmpeg/libavcodec/sga.c",
root_path ++ "ffmpeg/libavcodec/sgidec.c",
root_path ++ "ffmpeg/libavcodec/sgienc.c",
root_path ++ "ffmpeg/libavcodec/sgirledec.c",
root_path ++ "ffmpeg/libavcodec/sheervideo.c",
root_path ++ "ffmpeg/libavcodec/shorten.c",
root_path ++ "ffmpeg/libavcodec/simple_idct.c",
root_path ++ "ffmpeg/libavcodec/sinewin.c",
root_path ++ "ffmpeg/libavcodec/sipr.c",
root_path ++ "ffmpeg/libavcodec/sipr16k.c",
root_path ++ "ffmpeg/libavcodec/sipr_parser.c",
root_path ++ "ffmpeg/libavcodec/siren.c",
root_path ++ "ffmpeg/libavcodec/smacker.c",
root_path ++ "ffmpeg/libavcodec/smc.c",
root_path ++ "ffmpeg/libavcodec/snappy.c",
root_path ++ "ffmpeg/libavcodec/snow.c",
root_path ++ "ffmpeg/libavcodec/snow_dwt.c",
root_path ++ "ffmpeg/libavcodec/snowdec.c",
root_path ++ "ffmpeg/libavcodec/snowenc.c",
root_path ++ "ffmpeg/libavcodec/sonic.c",
root_path ++ "ffmpeg/libavcodec/sp5xdec.c",
root_path ++ "ffmpeg/libavcodec/speedhq.c",
root_path ++ "ffmpeg/libavcodec/speedhqenc.c",
root_path ++ "ffmpeg/libavcodec/srtdec.c",
root_path ++ "ffmpeg/libavcodec/srtenc.c",
root_path ++ "ffmpeg/libavcodec/startcode.c",
root_path ++ "ffmpeg/libavcodec/subviewerdec.c",
root_path ++ "ffmpeg/libavcodec/sunrast.c",
root_path ++ "ffmpeg/libavcodec/sunrastenc.c",
root_path ++ "ffmpeg/libavcodec/svq1.c",
root_path ++ "ffmpeg/libavcodec/svq1dec.c",
root_path ++ "ffmpeg/libavcodec/svq1enc.c",
root_path ++ "ffmpeg/libavcodec/svq3.c",
root_path ++ "ffmpeg/libavcodec/synth_filter.c",
root_path ++ "ffmpeg/libavcodec/tak.c",
root_path ++ "ffmpeg/libavcodec/tak_parser.c",
root_path ++ "ffmpeg/libavcodec/takdec.c",
root_path ++ "ffmpeg/libavcodec/takdsp.c",
root_path ++ "ffmpeg/libavcodec/targa.c",
root_path ++ "ffmpeg/libavcodec/targa_y216dec.c",
root_path ++ "ffmpeg/libavcodec/targaenc.c",
root_path ++ "ffmpeg/libavcodec/tdsc.c",
root_path ++ "ffmpeg/libavcodec/textdec.c",
root_path ++ "ffmpeg/libavcodec/texturedsp.c",
root_path ++ "ffmpeg/libavcodec/tiertexseqv.c",
root_path ++ "ffmpeg/libavcodec/tiff.c",
root_path ++ "ffmpeg/libavcodec/tiff_common.c",
root_path ++ "ffmpeg/libavcodec/tiffenc.c",
root_path ++ "ffmpeg/libavcodec/tmv.c",
root_path ++ "ffmpeg/libavcodec/tpeldsp.c",
root_path ++ "ffmpeg/libavcodec/trace_headers_bsf.c",
root_path ++ "ffmpeg/libavcodec/truehd_core_bsf.c",
root_path ++ "ffmpeg/libavcodec/truemotion1.c",
root_path ++ "ffmpeg/libavcodec/truemotion2.c",
root_path ++ "ffmpeg/libavcodec/truemotion2rt.c",
root_path ++ "ffmpeg/libavcodec/truespeech.c",
root_path ++ "ffmpeg/libavcodec/tscc.c",
root_path ++ "ffmpeg/libavcodec/tscc2.c",
root_path ++ "ffmpeg/libavcodec/tta.c",
root_path ++ "ffmpeg/libavcodec/ttadata.c",
root_path ++ "ffmpeg/libavcodec/ttadsp.c",
root_path ++ "ffmpeg/libavcodec/ttaenc.c",
root_path ++ "ffmpeg/libavcodec/ttaencdsp.c",
root_path ++ "ffmpeg/libavcodec/ttmlenc.c",
root_path ++ "ffmpeg/libavcodec/twinvq.c",
root_path ++ "ffmpeg/libavcodec/twinvqdec.c",
root_path ++ "ffmpeg/libavcodec/txd.c",
root_path ++ "ffmpeg/libavcodec/ulti.c",
root_path ++ "ffmpeg/libavcodec/utils.c",
root_path ++ "ffmpeg/libavcodec/utvideodec.c",
root_path ++ "ffmpeg/libavcodec/utvideodsp.c",
root_path ++ "ffmpeg/libavcodec/utvideoenc.c",
root_path ++ "ffmpeg/libavcodec/v210dec.c",
root_path ++ "ffmpeg/libavcodec/v210enc.c",
root_path ++ "ffmpeg/libavcodec/v210x.c",
root_path ++ "ffmpeg/libavcodec/v308dec.c",
root_path ++ "ffmpeg/libavcodec/v308enc.c",
root_path ++ "ffmpeg/libavcodec/v408dec.c",
root_path ++ "ffmpeg/libavcodec/v408enc.c",
root_path ++ "ffmpeg/libavcodec/v410dec.c",
root_path ++ "ffmpeg/libavcodec/v410enc.c",
root_path ++ "ffmpeg/libavcodec/v4l2_buffers.c",
root_path ++ "ffmpeg/libavcodec/v4l2_context.c",
root_path ++ "ffmpeg/libavcodec/v4l2_fmt.c",
root_path ++ "ffmpeg/libavcodec/v4l2_m2m.c",
root_path ++ "ffmpeg/libavcodec/v4l2_m2m_dec.c",
root_path ++ "ffmpeg/libavcodec/v4l2_m2m_enc.c",
root_path ++ "ffmpeg/libavcodec/vb.c",
root_path ++ "ffmpeg/libavcodec/vble.c",
root_path ++ "ffmpeg/libavcodec/vc1.c",
root_path ++ "ffmpeg/libavcodec/vc1_block.c",
root_path ++ "ffmpeg/libavcodec/vc1_loopfilter.c",
root_path ++ "ffmpeg/libavcodec/vc1_mc.c",
root_path ++ "ffmpeg/libavcodec/vc1_parser.c",
root_path ++ "ffmpeg/libavcodec/vc1_pred.c",
root_path ++ "ffmpeg/libavcodec/vc1data.c",
root_path ++ "ffmpeg/libavcodec/vc1dec.c",
root_path ++ "ffmpeg/libavcodec/vc1dsp.c",
root_path ++ "ffmpeg/libavcodec/vc2enc.c",
root_path ++ "ffmpeg/libavcodec/vc2enc_dwt.c",
root_path ++ "ffmpeg/libavcodec/vcr1.c",
root_path ++ "ffmpeg/libavcodec/videodsp.c",
root_path ++ "ffmpeg/libavcodec/vima.c",
root_path ++ "ffmpeg/libavcodec/vmdaudio.c",
root_path ++ "ffmpeg/libavcodec/vmdvideo.c",
root_path ++ "ffmpeg/libavcodec/vmnc.c",
root_path ++ "ffmpeg/libavcodec/vorbis.c",
root_path ++ "ffmpeg/libavcodec/vorbis_data.c",
root_path ++ "ffmpeg/libavcodec/vorbis_parser.c",
root_path ++ "ffmpeg/libavcodec/vorbisdec.c",
root_path ++ "ffmpeg/libavcodec/vorbisdsp.c",
root_path ++ "ffmpeg/libavcodec/vorbisenc.c",
root_path ++ "ffmpeg/libavcodec/vp3.c",
root_path ++ "ffmpeg/libavcodec/vp3_parser.c",
root_path ++ "ffmpeg/libavcodec/vp3dsp.c",
root_path ++ "ffmpeg/libavcodec/vp5.c",
root_path ++ "ffmpeg/libavcodec/vp56.c",
root_path ++ "ffmpeg/libavcodec/vp56data.c",
root_path ++ "ffmpeg/libavcodec/vp56dsp.c",
root_path ++ "ffmpeg/libavcodec/vp56rac.c",
root_path ++ "ffmpeg/libavcodec/vp6.c",
root_path ++ "ffmpeg/libavcodec/vp6dsp.c",
root_path ++ "ffmpeg/libavcodec/vp8.c",
root_path ++ "ffmpeg/libavcodec/vp8_parser.c",
root_path ++ "ffmpeg/libavcodec/vp8dsp.c",
root_path ++ "ffmpeg/libavcodec/vp9.c",
root_path ++ "ffmpeg/libavcodec/vp9_metadata_bsf.c",
root_path ++ "ffmpeg/libavcodec/vp9_parser.c",
root_path ++ "ffmpeg/libavcodec/vp9_raw_reorder_bsf.c",
root_path ++ "ffmpeg/libavcodec/vp9_superframe_bsf.c",
root_path ++ "ffmpeg/libavcodec/vp9_superframe_split_bsf.c",
root_path ++ "ffmpeg/libavcodec/vp9block.c",
root_path ++ "ffmpeg/libavcodec/vp9data.c",
root_path ++ "ffmpeg/libavcodec/vp9dsp.c",
root_path ++ "ffmpeg/libavcodec/vp9dsp_10bpp.c",
root_path ++ "ffmpeg/libavcodec/vp9dsp_12bpp.c",
root_path ++ "ffmpeg/libavcodec/vp9dsp_8bpp.c",
root_path ++ "ffmpeg/libavcodec/vp9lpf.c",
root_path ++ "ffmpeg/libavcodec/vp9mvs.c",
root_path ++ "ffmpeg/libavcodec/vp9prob.c",
root_path ++ "ffmpeg/libavcodec/vp9recon.c",
root_path ++ "ffmpeg/libavcodec/vqavideo.c",
root_path ++ "ffmpeg/libavcodec/wavpack.c",
root_path ++ "ffmpeg/libavcodec/wavpackdata.c",
root_path ++ "ffmpeg/libavcodec/wavpackenc.c",
root_path ++ "ffmpeg/libavcodec/wcmv.c",
root_path ++ "ffmpeg/libavcodec/webp.c",
root_path ++ "ffmpeg/libavcodec/webp_parser.c",
root_path ++ "ffmpeg/libavcodec/webvttdec.c",
root_path ++ "ffmpeg/libavcodec/webvttenc.c",
root_path ++ "ffmpeg/libavcodec/wma.c",
root_path ++ "ffmpeg/libavcodec/wma_common.c",
root_path ++ "ffmpeg/libavcodec/wma_freqs.c",
root_path ++ "ffmpeg/libavcodec/wmadec.c",
root_path ++ "ffmpeg/libavcodec/wmaenc.c",
root_path ++ "ffmpeg/libavcodec/wmalosslessdec.c",
root_path ++ "ffmpeg/libavcodec/wmaprodec.c",
root_path ++ "ffmpeg/libavcodec/wmavoice.c",
root_path ++ "ffmpeg/libavcodec/wmv2.c",
root_path ++ "ffmpeg/libavcodec/wmv2data.c",
root_path ++ "ffmpeg/libavcodec/wmv2dec.c",
root_path ++ "ffmpeg/libavcodec/wmv2dsp.c",
root_path ++ "ffmpeg/libavcodec/wmv2enc.c",
root_path ++ "ffmpeg/libavcodec/wnv1.c",
root_path ++ "ffmpeg/libavcodec/wrapped_avframe.c",
root_path ++ "ffmpeg/libavcodec/ws-snd1.c",
root_path ++ "ffmpeg/libavcodec/x86/aacencdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/aacpsdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/ac3dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/alacdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/audiodsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/blockdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/bswapdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/cavsdsp.c",
root_path ++ "ffmpeg/libavcodec/x86/celt_pvq_init.c",
root_path ++ "ffmpeg/libavcodec/x86/cfhddsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/cfhdencdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/constants.c",
root_path ++ "ffmpeg/libavcodec/x86/dcadsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/dct_init.c",
root_path ++ "ffmpeg/libavcodec/x86/dirac_dwt_init.c",
root_path ++ "ffmpeg/libavcodec/x86/diracdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/dnxhdenc_init.c",
root_path ++ "ffmpeg/libavcodec/x86/exrdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/fdct.c",
root_path ++ "ffmpeg/libavcodec/x86/fdctdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/fft_init.c",
root_path ++ "ffmpeg/libavcodec/x86/flacdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/fmtconvert_init.c",
root_path ++ "ffmpeg/libavcodec/x86/g722dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/h263dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/h264_intrapred_init.c",
root_path ++ "ffmpeg/libavcodec/x86/h264_qpel.c",
root_path ++ "ffmpeg/libavcodec/x86/h264chroma_init.c",
root_path ++ "ffmpeg/libavcodec/x86/h264dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/hevcdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/hpeldsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/hpeldsp_vp3_init.c",
root_path ++ "ffmpeg/libavcodec/x86/huffyuvdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/huffyuvencdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/idctdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/jpeg2000dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/lossless_audiodsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/lossless_videodsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/lossless_videoencdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/lpc.c",
root_path ++ "ffmpeg/libavcodec/x86/mdct15_init.c",
root_path ++ "ffmpeg/libavcodec/x86/me_cmp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/mlpdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/mpegaudiodsp.c",
root_path ++ "ffmpeg/libavcodec/x86/mpegvideo.c",
root_path ++ "ffmpeg/libavcodec/x86/mpegvideodsp.c",
root_path ++ "ffmpeg/libavcodec/x86/mpegvideoenc.c",
root_path ++ "ffmpeg/libavcodec/x86/mpegvideoencdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/opusdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/pixblockdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/pngdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/proresdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/qpeldsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/rv34dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/rv40dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/sbcdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/sbrdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/snowdsp.c",
root_path ++ "ffmpeg/libavcodec/x86/svq1enc_init.c",
root_path ++ "ffmpeg/libavcodec/x86/synth_filter_init.c",
root_path ++ "ffmpeg/libavcodec/x86/takdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/ttadsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/ttaencdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/utvideodsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/v210-init.c",
root_path ++ "ffmpeg/libavcodec/x86/v210enc_init.c",
root_path ++ "ffmpeg/libavcodec/x86/vc1dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/vc1dsp_mmx.c",
root_path ++ "ffmpeg/libavcodec/x86/videodsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/vorbisdsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/vp3dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/vp6dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/vp8dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/vp9dsp_init.c",
root_path ++ "ffmpeg/libavcodec/x86/vp9dsp_init_10bpp.c",
root_path ++ "ffmpeg/libavcodec/x86/vp9dsp_init_12bpp.c",
root_path ++ "ffmpeg/libavcodec/x86/vp9dsp_init_16bpp.c",
root_path ++ "ffmpeg/libavcodec/x86/xvididct_init.c",
root_path ++ "ffmpeg/libavcodec/xan.c",
root_path ++ "ffmpeg/libavcodec/xbm_parser.c",
root_path ++ "ffmpeg/libavcodec/xbmdec.c",
root_path ++ "ffmpeg/libavcodec/xbmenc.c",
root_path ++ "ffmpeg/libavcodec/xface.c",
root_path ++ "ffmpeg/libavcodec/xfacedec.c",
root_path ++ "ffmpeg/libavcodec/xfaceenc.c",
root_path ++ "ffmpeg/libavcodec/xiph.c",
root_path ++ "ffmpeg/libavcodec/xl.c",
root_path ++ "ffmpeg/libavcodec/xma_parser.c",
root_path ++ "ffmpeg/libavcodec/xpmdec.c",
root_path ++ "ffmpeg/libavcodec/xsubdec.c",
root_path ++ "ffmpeg/libavcodec/xsubenc.c",
root_path ++ "ffmpeg/libavcodec/xvididct.c",
root_path ++ "ffmpeg/libavcodec/xwddec.c",
root_path ++ "ffmpeg/libavcodec/xwdenc.c",
root_path ++ "ffmpeg/libavcodec/xxan.c",
root_path ++ "ffmpeg/libavcodec/y41pdec.c",
root_path ++ "ffmpeg/libavcodec/y41penc.c",
root_path ++ "ffmpeg/libavcodec/ylc.c",
root_path ++ "ffmpeg/libavcodec/yop.c",
root_path ++ "ffmpeg/libavcodec/yuv4dec.c",
root_path ++ "ffmpeg/libavcodec/yuv4enc.c",
root_path ++ "ffmpeg/libavcodec/zerocodec.c",
root_path ++ "ffmpeg/libavcodec/zmbv.c",
root_path ++ "ffmpeg/libavcodec/zmbvenc.c",
};
const avutil_sources = &.{
root_path ++ "ffmpeg/libavutil/adler32.c",
root_path ++ "ffmpeg/libavutil/aes.c",
root_path ++ "ffmpeg/libavutil/aes_ctr.c",
root_path ++ "ffmpeg/libavutil/audio_fifo.c",
root_path ++ "ffmpeg/libavutil/avsscanf.c",
root_path ++ "ffmpeg/libavutil/avstring.c",
root_path ++ "ffmpeg/libavutil/base64.c",
root_path ++ "ffmpeg/libavutil/blowfish.c",
root_path ++ "ffmpeg/libavutil/bprint.c",
root_path ++ "ffmpeg/libavutil/buffer.c",
root_path ++ "ffmpeg/libavutil/camellia.c",
root_path ++ "ffmpeg/libavutil/cast5.c",
root_path ++ "ffmpeg/libavutil/channel_layout.c",
root_path ++ "ffmpeg/libavutil/color_utils.c",
root_path ++ "ffmpeg/libavutil/cpu.c",
root_path ++ "ffmpeg/libavutil/crc.c",
root_path ++ "ffmpeg/libavutil/des.c",
root_path ++ "ffmpeg/libavutil/dict.c",
root_path ++ "ffmpeg/libavutil/display.c",
root_path ++ "ffmpeg/libavutil/dovi_meta.c",
root_path ++ "ffmpeg/libavutil/downmix_info.c",
root_path ++ "ffmpeg/libavutil/encryption_info.c",
root_path ++ "ffmpeg/libavutil/error.c",
root_path ++ "ffmpeg/libavutil/eval.c",
root_path ++ "ffmpeg/libavutil/fifo.c",
root_path ++ "ffmpeg/libavutil/file.c",
root_path ++ "ffmpeg/libavutil/file_open.c",
root_path ++ "ffmpeg/libavutil/film_grain_params.c",
root_path ++ "ffmpeg/libavutil/fixed_dsp.c",
root_path ++ "ffmpeg/libavutil/float_dsp.c",
root_path ++ "ffmpeg/libavutil/frame.c",
root_path ++ "ffmpeg/libavutil/hash.c",
root_path ++ "ffmpeg/libavutil/hdr_dynamic_metadata.c",
root_path ++ "ffmpeg/libavutil/hmac.c",
root_path ++ "ffmpeg/libavutil/hwcontext.c",
root_path ++ "ffmpeg/libavutil/imgutils.c",
root_path ++ "ffmpeg/libavutil/integer.c",
root_path ++ "ffmpeg/libavutil/intmath.c",
root_path ++ "ffmpeg/libavutil/lfg.c",
root_path ++ "ffmpeg/libavutil/lls.c",
root_path ++ "ffmpeg/libavutil/log.c",
root_path ++ "ffmpeg/libavutil/log2_tab.c",
root_path ++ "ffmpeg/libavutil/lzo.c",
root_path ++ "ffmpeg/libavutil/mastering_display_metadata.c",
root_path ++ "ffmpeg/libavutil/mathematics.c",
root_path ++ "ffmpeg/libavutil/md5.c",
root_path ++ "ffmpeg/libavutil/mem.c",
root_path ++ "ffmpeg/libavutil/murmur3.c",
root_path ++ "ffmpeg/libavutil/opt.c",
root_path ++ "ffmpeg/libavutil/parseutils.c",
root_path ++ "ffmpeg/libavutil/pixdesc.c",
root_path ++ "ffmpeg/libavutil/pixelutils.c",
root_path ++ "ffmpeg/libavutil/random_seed.c",
root_path ++ "ffmpeg/libavutil/rational.c",
root_path ++ "ffmpeg/libavutil/rc4.c",
root_path ++ "ffmpeg/libavutil/reverse.c",
root_path ++ "ffmpeg/libavutil/ripemd.c",
root_path ++ "ffmpeg/libavutil/samplefmt.c",
root_path ++ "ffmpeg/libavutil/sha.c",
root_path ++ "ffmpeg/libavutil/sha512.c",
root_path ++ "ffmpeg/libavutil/slicethread.c",
root_path ++ "ffmpeg/libavutil/spherical.c",
root_path ++ "ffmpeg/libavutil/stereo3d.c",
root_path ++ "ffmpeg/libavutil/tea.c",
root_path ++ "ffmpeg/libavutil/threadmessage.c",
root_path ++ "ffmpeg/libavutil/time.c",
root_path ++ "ffmpeg/libavutil/timecode.c",
root_path ++ "ffmpeg/libavutil/tree.c",
root_path ++ "ffmpeg/libavutil/twofish.c",
root_path ++ "ffmpeg/libavutil/tx.c",
root_path ++ "ffmpeg/libavutil/tx_double.c",
root_path ++ "ffmpeg/libavutil/tx_float.c",
root_path ++ "ffmpeg/libavutil/tx_int32.c",
root_path ++ "ffmpeg/libavutil/utils.c",
root_path ++ "ffmpeg/libavutil/video_enc_params.c",
root_path ++ "ffmpeg/libavutil/x86/cpu.c",
root_path ++ "ffmpeg/libavutil/x86/fixed_dsp_init.c",
root_path ++ "ffmpeg/libavutil/x86/float_dsp_init.c",
root_path ++ "ffmpeg/libavutil/x86/imgutils_init.c",
root_path ++ "ffmpeg/libavutil/x86/lls_init.c",
root_path ++ "ffmpeg/libavutil/x86/pixelutils_init.c",
root_path ++ "ffmpeg/libavutil/xga_font_data.c",
root_path ++ "ffmpeg/libavutil/xtea.c",
};
const avformat_sources = &.{
root_path ++ "ffmpeg/libavformat/3dostr.c",
root_path ++ "ffmpeg/libavformat/4xm.c",
root_path ++ "ffmpeg/libavformat/a64.c",
root_path ++ "ffmpeg/libavformat/aacdec.c",
root_path ++ "ffmpeg/libavformat/aadec.c",
root_path ++ "ffmpeg/libavformat/aaxdec.c",
root_path ++ "ffmpeg/libavformat/ac3dec.c",
root_path ++ "ffmpeg/libavformat/acedec.c",
root_path ++ "ffmpeg/libavformat/acm.c",
root_path ++ "ffmpeg/libavformat/act.c",
root_path ++ "ffmpeg/libavformat/adp.c",
root_path ++ "ffmpeg/libavformat/ads.c",
root_path ++ "ffmpeg/libavformat/adtsenc.c",
root_path ++ "ffmpeg/libavformat/adxdec.c",
root_path ++ "ffmpeg/libavformat/aea.c",
root_path ++ "ffmpeg/libavformat/afc.c",
root_path ++ "ffmpeg/libavformat/aiff.c",
root_path ++ "ffmpeg/libavformat/aiffdec.c",
root_path ++ "ffmpeg/libavformat/aiffenc.c",
root_path ++ "ffmpeg/libavformat/aixdec.c",
root_path ++ "ffmpeg/libavformat/allformats.c",
root_path ++ "ffmpeg/libavformat/alp.c",
root_path ++ "ffmpeg/libavformat/amr.c",
root_path ++ "ffmpeg/libavformat/amvenc.c",
root_path ++ "ffmpeg/libavformat/anm.c",
root_path ++ "ffmpeg/libavformat/apc.c",
root_path ++ "ffmpeg/libavformat/ape.c",
root_path ++ "ffmpeg/libavformat/apetag.c",
root_path ++ "ffmpeg/libavformat/apm.c",
root_path ++ "ffmpeg/libavformat/apngdec.c",
root_path ++ "ffmpeg/libavformat/apngenc.c",
root_path ++ "ffmpeg/libavformat/aptxdec.c",
root_path ++ "ffmpeg/libavformat/aqtitledec.c",
root_path ++ "ffmpeg/libavformat/argo_asf.c",
root_path ++ "ffmpeg/libavformat/argo_brp.c",
root_path ++ "ffmpeg/libavformat/asf.c",
root_path ++ "ffmpeg/libavformat/asfcrypt.c",
root_path ++ "ffmpeg/libavformat/asfdec_f.c",
root_path ++ "ffmpeg/libavformat/asfdec_o.c",
root_path ++ "ffmpeg/libavformat/asfenc.c",
root_path ++ "ffmpeg/libavformat/assdec.c",
root_path ++ "ffmpeg/libavformat/assenc.c",
root_path ++ "ffmpeg/libavformat/ast.c",
root_path ++ "ffmpeg/libavformat/astdec.c",
root_path ++ "ffmpeg/libavformat/astenc.c",
root_path ++ "ffmpeg/libavformat/async.c",
root_path ++ "ffmpeg/libavformat/au.c",
root_path ++ "ffmpeg/libavformat/av1.c",
root_path ++ "ffmpeg/libavformat/av1dec.c",
root_path ++ "ffmpeg/libavformat/avc.c",
root_path ++ "ffmpeg/libavformat/avidec.c",
root_path ++ "ffmpeg/libavformat/avienc.c",
root_path ++ "ffmpeg/libavformat/avio.c",
root_path ++ "ffmpeg/libavformat/aviobuf.c",
root_path ++ "ffmpeg/libavformat/avlanguage.c",
root_path ++ "ffmpeg/libavformat/avr.c",
root_path ++ "ffmpeg/libavformat/avs.c",
root_path ++ "ffmpeg/libavformat/avs2dec.c",
root_path ++ "ffmpeg/libavformat/avs3dec.c",
root_path ++ "ffmpeg/libavformat/bethsoftvid.c",
root_path ++ "ffmpeg/libavformat/bfi.c",
root_path ++ "ffmpeg/libavformat/bink.c",
root_path ++ "ffmpeg/libavformat/binka.c",
root_path ++ "ffmpeg/libavformat/bintext.c",
root_path ++ "ffmpeg/libavformat/bit.c",
root_path ++ "ffmpeg/libavformat/bmv.c",
root_path ++ "ffmpeg/libavformat/boadec.c",
root_path ++ "ffmpeg/libavformat/brstm.c",
root_path ++ "ffmpeg/libavformat/c93.c",
root_path ++ "ffmpeg/libavformat/cache.c",
root_path ++ "ffmpeg/libavformat/caf.c",
root_path ++ "ffmpeg/libavformat/cafdec.c",
root_path ++ "ffmpeg/libavformat/cafenc.c",
root_path ++ "ffmpeg/libavformat/cavsvideodec.c",
root_path ++ "ffmpeg/libavformat/cdg.c",
root_path ++ "ffmpeg/libavformat/cdxl.c",
root_path ++ "ffmpeg/libavformat/cinedec.c",
root_path ++ "ffmpeg/libavformat/codec2.c",
root_path ++ "ffmpeg/libavformat/concat.c",
root_path ++ "ffmpeg/libavformat/concatdec.c",
root_path ++ "ffmpeg/libavformat/crcenc.c",
root_path ++ "ffmpeg/libavformat/crypto.c",
root_path ++ "ffmpeg/libavformat/dash.c",
root_path ++ "ffmpeg/libavformat/dashenc.c",
root_path ++ "ffmpeg/libavformat/data_uri.c",
root_path ++ "ffmpeg/libavformat/dauddec.c",
root_path ++ "ffmpeg/libavformat/daudenc.c",
root_path ++ "ffmpeg/libavformat/dcstr.c",
root_path ++ "ffmpeg/libavformat/derf.c",
root_path ++ "ffmpeg/libavformat/dfa.c",
root_path ++ "ffmpeg/libavformat/dhav.c",
root_path ++ "ffmpeg/libavformat/diracdec.c",
root_path ++ "ffmpeg/libavformat/dnxhddec.c",
root_path ++ "ffmpeg/libavformat/dsfdec.c",
root_path ++ "ffmpeg/libavformat/dsicin.c",
root_path ++ "ffmpeg/libavformat/dss.c",
root_path ++ "ffmpeg/libavformat/dtsdec.c",
root_path ++ "ffmpeg/libavformat/dtshddec.c",
root_path ++ "ffmpeg/libavformat/dump.c",
root_path ++ "ffmpeg/libavformat/dv.c",
root_path ++ "ffmpeg/libavformat/dvbsub.c",
root_path ++ "ffmpeg/libavformat/dvbtxt.c",
root_path ++ "ffmpeg/libavformat/dvenc.c",
root_path ++ "ffmpeg/libavformat/dxa.c",
root_path ++ "ffmpeg/libavformat/eacdata.c",
root_path ++ "ffmpeg/libavformat/electronicarts.c",
root_path ++ "ffmpeg/libavformat/epafdec.c",
root_path ++ "ffmpeg/libavformat/ffmetadec.c",
root_path ++ "ffmpeg/libavformat/ffmetaenc.c",
root_path ++ "ffmpeg/libavformat/fifo.c",
root_path ++ "ffmpeg/libavformat/fifo_test.c",
root_path ++ "ffmpeg/libavformat/file.c",
root_path ++ "ffmpeg/libavformat/filmstripdec.c",
root_path ++ "ffmpeg/libavformat/filmstripenc.c",
root_path ++ "ffmpeg/libavformat/fitsdec.c",
root_path ++ "ffmpeg/libavformat/fitsenc.c",
root_path ++ "ffmpeg/libavformat/flac_picture.c",
root_path ++ "ffmpeg/libavformat/flacdec.c",
root_path ++ "ffmpeg/libavformat/flacenc.c",
root_path ++ "ffmpeg/libavformat/flacenc_header.c",
root_path ++ "ffmpeg/libavformat/flic.c",
root_path ++ "ffmpeg/libavformat/flvdec.c",
root_path ++ "ffmpeg/libavformat/flvenc.c",
root_path ++ "ffmpeg/libavformat/format.c",
root_path ++ "ffmpeg/libavformat/framecrcenc.c",
root_path ++ "ffmpeg/libavformat/framehash.c",
root_path ++ "ffmpeg/libavformat/frmdec.c",
root_path ++ "ffmpeg/libavformat/fsb.c",
root_path ++ "ffmpeg/libavformat/ftp.c",
root_path ++ "ffmpeg/libavformat/fwse.c",
root_path ++ "ffmpeg/libavformat/g722.c",
root_path ++ "ffmpeg/libavformat/g723_1.c",
root_path ++ "ffmpeg/libavformat/g726.c",
root_path ++ "ffmpeg/libavformat/g729dec.c",
root_path ++ "ffmpeg/libavformat/gdv.c",
root_path ++ "ffmpeg/libavformat/genh.c",
root_path ++ "ffmpeg/libavformat/gif.c",
root_path ++ "ffmpeg/libavformat/gifdec.c",
root_path ++ "ffmpeg/libavformat/gopher.c",
root_path ++ "ffmpeg/libavformat/gsmdec.c",
root_path ++ "ffmpeg/libavformat/gxf.c",
root_path ++ "ffmpeg/libavformat/gxfenc.c",
root_path ++ "ffmpeg/libavformat/h261dec.c",
root_path ++ "ffmpeg/libavformat/h263dec.c",
root_path ++ "ffmpeg/libavformat/h264dec.c",
root_path ++ "ffmpeg/libavformat/hashenc.c",
root_path ++ "ffmpeg/libavformat/hca.c",
root_path ++ "ffmpeg/libavformat/hcom.c",
root_path ++ "ffmpeg/libavformat/hdsenc.c",
root_path ++ "ffmpeg/libavformat/hevc.c",
root_path ++ "ffmpeg/libavformat/hevcdec.c",
root_path ++ "ffmpeg/libavformat/hls.c",
root_path ++ "ffmpeg/libavformat/hlsenc.c",
root_path ++ "ffmpeg/libavformat/hlsplaylist.c",
root_path ++ "ffmpeg/libavformat/hlsproto.c",
root_path ++ "ffmpeg/libavformat/hnm.c",
root_path ++ "ffmpeg/libavformat/http.c",
root_path ++ "ffmpeg/libavformat/httpauth.c",
root_path ++ "ffmpeg/libavformat/icecast.c",
root_path ++ "ffmpeg/libavformat/icodec.c",
root_path ++ "ffmpeg/libavformat/icoenc.c",
root_path ++ "ffmpeg/libavformat/id3v1.c",
root_path ++ "ffmpeg/libavformat/id3v2.c",
root_path ++ "ffmpeg/libavformat/id3v2enc.c",
root_path ++ "ffmpeg/libavformat/idcin.c",
root_path ++ "ffmpeg/libavformat/idroqdec.c",
root_path ++ "ffmpeg/libavformat/idroqenc.c",
root_path ++ "ffmpeg/libavformat/iff.c",
root_path ++ "ffmpeg/libavformat/ifv.c",
root_path ++ "ffmpeg/libavformat/ilbc.c",
root_path ++ "ffmpeg/libavformat/img2.c",
root_path ++ "ffmpeg/libavformat/img2_alias_pix.c",
root_path ++ "ffmpeg/libavformat/img2_brender_pix.c",
root_path ++ "ffmpeg/libavformat/img2dec.c",
root_path ++ "ffmpeg/libavformat/img2enc.c",
root_path ++ "ffmpeg/libavformat/imx.c",
root_path ++ "ffmpeg/libavformat/ingenientdec.c",
root_path ++ "ffmpeg/libavformat/ip.c",
root_path ++ "ffmpeg/libavformat/ipmovie.c",
root_path ++ "ffmpeg/libavformat/ipudec.c",
root_path ++ "ffmpeg/libavformat/ircam.c",
root_path ++ "ffmpeg/libavformat/ircamdec.c",
root_path ++ "ffmpeg/libavformat/ircamenc.c",
root_path ++ "ffmpeg/libavformat/isom.c",
root_path ++ "ffmpeg/libavformat/isom_tags.c",
root_path ++ "ffmpeg/libavformat/iss.c",
root_path ++ "ffmpeg/libavformat/iv8.c",
root_path ++ "ffmpeg/libavformat/ivfdec.c",
root_path ++ "ffmpeg/libavformat/ivfenc.c",
root_path ++ "ffmpeg/libavformat/jacosubdec.c",
root_path ++ "ffmpeg/libavformat/jacosubenc.c",
root_path ++ "ffmpeg/libavformat/jvdec.c",
root_path ++ "ffmpeg/libavformat/kvag.c",
root_path ++ "ffmpeg/libavformat/latmenc.c",
root_path ++ "ffmpeg/libavformat/lmlm4.c",
root_path ++ "ffmpeg/libavformat/loasdec.c",
root_path ++ "ffmpeg/libavformat/lrc.c",
root_path ++ "ffmpeg/libavformat/lrcdec.c",
root_path ++ "ffmpeg/libavformat/lrcenc.c",
root_path ++ "ffmpeg/libavformat/luodatdec.c",
root_path ++ "ffmpeg/libavformat/lvfdec.c",
root_path ++ "ffmpeg/libavformat/lxfdec.c",
root_path ++ "ffmpeg/libavformat/m4vdec.c",
root_path ++ "ffmpeg/libavformat/matroska.c",
root_path ++ "ffmpeg/libavformat/matroskadec.c",
root_path ++ "ffmpeg/libavformat/matroskaenc.c",
root_path ++ "ffmpeg/libavformat/mca.c",
root_path ++ "ffmpeg/libavformat/mccdec.c",
root_path ++ "ffmpeg/libavformat/md5proto.c",
root_path ++ "ffmpeg/libavformat/metadata.c",
root_path ++ "ffmpeg/libavformat/mgsts.c",
root_path ++ "ffmpeg/libavformat/microdvddec.c",
root_path ++ "ffmpeg/libavformat/microdvdenc.c",
root_path ++ "ffmpeg/libavformat/mj2kdec.c",
root_path ++ "ffmpeg/libavformat/mkvtimestamp_v2.c",
root_path ++ "ffmpeg/libavformat/mlpdec.c",
root_path ++ "ffmpeg/libavformat/mlvdec.c",
root_path ++ "ffmpeg/libavformat/mm.c",
root_path ++ "ffmpeg/libavformat/mmf.c",
root_path ++ "ffmpeg/libavformat/mms.c",
root_path ++ "ffmpeg/libavformat/mmsh.c",
root_path ++ "ffmpeg/libavformat/mmst.c",
root_path ++ "ffmpeg/libavformat/mods.c",
root_path ++ "ffmpeg/libavformat/moflex.c",
root_path ++ "ffmpeg/libavformat/mov.c",
root_path ++ "ffmpeg/libavformat/mov_chan.c",
root_path ++ "ffmpeg/libavformat/mov_esds.c",
root_path ++ "ffmpeg/libavformat/movenc.c",
root_path ++ "ffmpeg/libavformat/movenccenc.c",
root_path ++ "ffmpeg/libavformat/movenchint.c",
root_path ++ "ffmpeg/libavformat/mp3dec.c",
root_path ++ "ffmpeg/libavformat/mp3enc.c",
root_path ++ "ffmpeg/libavformat/mpc.c",
root_path ++ "ffmpeg/libavformat/mpc8.c",
root_path ++ "ffmpeg/libavformat/mpeg.c",
root_path ++ "ffmpeg/libavformat/mpegenc.c",
root_path ++ "ffmpeg/libavformat/mpegts.c",
root_path ++ "ffmpeg/libavformat/mpegtsenc.c",
root_path ++ "ffmpeg/libavformat/mpegvideodec.c",
root_path ++ "ffmpeg/libavformat/mpjpeg.c",
root_path ++ "ffmpeg/libavformat/mpjpegdec.c",
root_path ++ "ffmpeg/libavformat/mpl2dec.c",
root_path ++ "ffmpeg/libavformat/mpsubdec.c",
root_path ++ "ffmpeg/libavformat/msf.c",
root_path ++ "ffmpeg/libavformat/msnwc_tcp.c",
root_path ++ "ffmpeg/libavformat/mspdec.c",
root_path ++ "ffmpeg/libavformat/mtaf.c",
root_path ++ "ffmpeg/libavformat/mtv.c",
root_path ++ "ffmpeg/libavformat/musx.c",
root_path ++ "ffmpeg/libavformat/mux.c",
root_path ++ "ffmpeg/libavformat/mvdec.c",
root_path ++ "ffmpeg/libavformat/mvi.c",
root_path ++ "ffmpeg/libavformat/mxf.c",
root_path ++ "ffmpeg/libavformat/mxfdec.c",
root_path ++ "ffmpeg/libavformat/mxfenc.c",
root_path ++ "ffmpeg/libavformat/mxg.c",
root_path ++ "ffmpeg/libavformat/ncdec.c",
root_path ++ "ffmpeg/libavformat/network.c",
root_path ++ "ffmpeg/libavformat/nistspheredec.c",
root_path ++ "ffmpeg/libavformat/nspdec.c",
root_path ++ "ffmpeg/libavformat/nsvdec.c",
root_path ++ "ffmpeg/libavformat/nullenc.c",
root_path ++ "ffmpeg/libavformat/nut.c",
root_path ++ "ffmpeg/libavformat/nutdec.c",
root_path ++ "ffmpeg/libavformat/nutenc.c",
root_path ++ "ffmpeg/libavformat/nuv.c",
root_path ++ "ffmpeg/libavformat/oggdec.c",
root_path ++ "ffmpeg/libavformat/oggenc.c",
root_path ++ "ffmpeg/libavformat/oggparsecelt.c",
root_path ++ "ffmpeg/libavformat/oggparsedirac.c",
root_path ++ "ffmpeg/libavformat/oggparseflac.c",
root_path ++ "ffmpeg/libavformat/oggparseogm.c",
root_path ++ "ffmpeg/libavformat/oggparseopus.c",
root_path ++ "ffmpeg/libavformat/oggparseskeleton.c",
root_path ++ "ffmpeg/libavformat/oggparsespeex.c",
root_path ++ "ffmpeg/libavformat/oggparsetheora.c",
root_path ++ "ffmpeg/libavformat/oggparsevorbis.c",
root_path ++ "ffmpeg/libavformat/oggparsevp8.c",
root_path ++ "ffmpeg/libavformat/oma.c",
root_path ++ "ffmpeg/libavformat/omadec.c",
root_path ++ "ffmpeg/libavformat/omaenc.c",
root_path ++ "ffmpeg/libavformat/options.c",
root_path ++ "ffmpeg/libavformat/os_support.c",
root_path ++ "ffmpeg/libavformat/paf.c",
root_path ++ "ffmpeg/libavformat/pcm.c",
root_path ++ "ffmpeg/libavformat/pcmdec.c",
root_path ++ "ffmpeg/libavformat/pcmenc.c",
root_path ++ "ffmpeg/libavformat/pjsdec.c",
root_path ++ "ffmpeg/libavformat/pmpdec.c",
root_path ++ "ffmpeg/libavformat/pp_bnk.c",
root_path ++ "ffmpeg/libavformat/prompeg.c",
root_path ++ "ffmpeg/libavformat/protocols.c",
root_path ++ "ffmpeg/libavformat/psxstr.c",
root_path ++ "ffmpeg/libavformat/pva.c",
root_path ++ "ffmpeg/libavformat/pvfdec.c",
root_path ++ "ffmpeg/libavformat/qcp.c",
root_path ++ "ffmpeg/libavformat/qtpalette.c",
root_path ++ "ffmpeg/libavformat/r3d.c",
root_path ++ "ffmpeg/libavformat/rawdec.c",
root_path ++ "ffmpeg/libavformat/rawenc.c",
root_path ++ "ffmpeg/libavformat/rawutils.c",
root_path ++ "ffmpeg/libavformat/rawvideodec.c",
root_path ++ "ffmpeg/libavformat/rdt.c",
root_path ++ "ffmpeg/libavformat/realtextdec.c",
root_path ++ "ffmpeg/libavformat/redspark.c",
root_path ++ "ffmpeg/libavformat/replaygain.c",
root_path ++ "ffmpeg/libavformat/riff.c",
root_path ++ "ffmpeg/libavformat/riffdec.c",
root_path ++ "ffmpeg/libavformat/riffenc.c",
root_path ++ "ffmpeg/libavformat/rl2.c",
root_path ++ "ffmpeg/libavformat/rm.c",
root_path ++ "ffmpeg/libavformat/rmdec.c",
root_path ++ "ffmpeg/libavformat/rmenc.c",
root_path ++ "ffmpeg/libavformat/rmsipr.c",
root_path ++ "ffmpeg/libavformat/rpl.c",
root_path ++ "ffmpeg/libavformat/rsd.c",
root_path ++ "ffmpeg/libavformat/rso.c",
root_path ++ "ffmpeg/libavformat/rsodec.c",
root_path ++ "ffmpeg/libavformat/rsoenc.c",
root_path ++ "ffmpeg/libavformat/rtmpdigest.c",
root_path ++ "ffmpeg/libavformat/rtmphttp.c",
root_path ++ "ffmpeg/libavformat/rtmppkt.c",
root_path ++ "ffmpeg/libavformat/rtmpproto.c",
root_path ++ "ffmpeg/libavformat/rtp.c",
root_path ++ "ffmpeg/libavformat/rtpdec.c",
root_path ++ "ffmpeg/libavformat/rtpdec_ac3.c",
root_path ++ "ffmpeg/libavformat/rtpdec_amr.c",
root_path ++ "ffmpeg/libavformat/rtpdec_asf.c",
root_path ++ "ffmpeg/libavformat/rtpdec_dv.c",
root_path ++ "ffmpeg/libavformat/rtpdec_g726.c",
root_path ++ "ffmpeg/libavformat/rtpdec_h261.c",
root_path ++ "ffmpeg/libavformat/rtpdec_h263.c",
root_path ++ "ffmpeg/libavformat/rtpdec_h263_rfc2190.c",
root_path ++ "ffmpeg/libavformat/rtpdec_h264.c",
root_path ++ "ffmpeg/libavformat/rtpdec_hevc.c",
root_path ++ "ffmpeg/libavformat/rtpdec_ilbc.c",
root_path ++ "ffmpeg/libavformat/rtpdec_jpeg.c",
root_path ++ "ffmpeg/libavformat/rtpdec_latm.c",
root_path ++ "ffmpeg/libavformat/rtpdec_mpa_robust.c",
root_path ++ "ffmpeg/libavformat/rtpdec_mpeg12.c",
root_path ++ "ffmpeg/libavformat/rtpdec_mpeg4.c",
root_path ++ "ffmpeg/libavformat/rtpdec_mpegts.c",
root_path ++ "ffmpeg/libavformat/rtpdec_qcelp.c",
root_path ++ "ffmpeg/libavformat/rtpdec_qdm2.c",
root_path ++ "ffmpeg/libavformat/rtpdec_qt.c",
root_path ++ "ffmpeg/libavformat/rtpdec_rfc4175.c",
root_path ++ "ffmpeg/libavformat/rtpdec_svq3.c",
root_path ++ "ffmpeg/libavformat/rtpdec_vc2hq.c",
root_path ++ "ffmpeg/libavformat/rtpdec_vp8.c",
root_path ++ "ffmpeg/libavformat/rtpdec_vp9.c",
root_path ++ "ffmpeg/libavformat/rtpdec_xiph.c",
root_path ++ "ffmpeg/libavformat/rtpenc.c",
root_path ++ "ffmpeg/libavformat/rtpenc_aac.c",
root_path ++ "ffmpeg/libavformat/rtpenc_amr.c",
root_path ++ "ffmpeg/libavformat/rtpenc_chain.c",
root_path ++ "ffmpeg/libavformat/rtpenc_h261.c",
root_path ++ "ffmpeg/libavformat/rtpenc_h263.c",
root_path ++ "ffmpeg/libavformat/rtpenc_h263_rfc2190.c",
root_path ++ "ffmpeg/libavformat/rtpenc_h264_hevc.c",
root_path ++ "ffmpeg/libavformat/rtpenc_jpeg.c",
root_path ++ "ffmpeg/libavformat/rtpenc_latm.c",
root_path ++ "ffmpeg/libavformat/rtpenc_mpegts.c",
root_path ++ "ffmpeg/libavformat/rtpenc_mpv.c",
root_path ++ "ffmpeg/libavformat/rtpenc_vc2hq.c",
root_path ++ "ffmpeg/libavformat/rtpenc_vp8.c",
root_path ++ "ffmpeg/libavformat/rtpenc_vp9.c",
root_path ++ "ffmpeg/libavformat/rtpenc_xiph.c",
root_path ++ "ffmpeg/libavformat/rtpproto.c",
root_path ++ "ffmpeg/libavformat/rtsp.c",
root_path ++ "ffmpeg/libavformat/rtspdec.c",
root_path ++ "ffmpeg/libavformat/rtspenc.c",
root_path ++ "ffmpeg/libavformat/s337m.c",
root_path ++ "ffmpeg/libavformat/samidec.c",
root_path ++ "ffmpeg/libavformat/sapdec.c",
root_path ++ "ffmpeg/libavformat/sapenc.c",
root_path ++ "ffmpeg/libavformat/sauce.c",
root_path ++ "ffmpeg/libavformat/sbcdec.c",
root_path ++ "ffmpeg/libavformat/sbgdec.c",
root_path ++ "ffmpeg/libavformat/sccdec.c",
root_path ++ "ffmpeg/libavformat/sccenc.c",
root_path ++ "ffmpeg/libavformat/sdp.c",
root_path ++ "ffmpeg/libavformat/sdr2.c",
root_path ++ "ffmpeg/libavformat/sdsdec.c",
root_path ++ "ffmpeg/libavformat/sdxdec.c",
root_path ++ "ffmpeg/libavformat/segafilm.c",
root_path ++ "ffmpeg/libavformat/segafilmenc.c",
root_path ++ "ffmpeg/libavformat/segment.c",
root_path ++ "ffmpeg/libavformat/serdec.c",
root_path ++ "ffmpeg/libavformat/sga.c",
root_path ++ "ffmpeg/libavformat/shortendec.c",
root_path ++ "ffmpeg/libavformat/sierravmd.c",
root_path ++ "ffmpeg/libavformat/siff.c",
root_path ++ "ffmpeg/libavformat/smacker.c",
root_path ++ "ffmpeg/libavformat/smjpeg.c",
root_path ++ "ffmpeg/libavformat/smjpegdec.c",
root_path ++ "ffmpeg/libavformat/smjpegenc.c",
root_path ++ "ffmpeg/libavformat/smoothstreamingenc.c",
root_path ++ "ffmpeg/libavformat/smush.c",
root_path ++ "ffmpeg/libavformat/sol.c",
root_path ++ "ffmpeg/libavformat/soxdec.c",
root_path ++ "ffmpeg/libavformat/soxenc.c",
root_path ++ "ffmpeg/libavformat/spdif.c",
root_path ++ "ffmpeg/libavformat/spdifdec.c",
root_path ++ "ffmpeg/libavformat/spdifenc.c",
root_path ++ "ffmpeg/libavformat/srtdec.c",
root_path ++ "ffmpeg/libavformat/srtenc.c",
root_path ++ "ffmpeg/libavformat/srtp.c",
root_path ++ "ffmpeg/libavformat/srtpproto.c",
root_path ++ "ffmpeg/libavformat/stldec.c",
root_path ++ "ffmpeg/libavformat/subfile.c",
root_path ++ "ffmpeg/libavformat/subtitles.c",
root_path ++ "ffmpeg/libavformat/subviewer1dec.c",
root_path ++ "ffmpeg/libavformat/subviewerdec.c",
root_path ++ "ffmpeg/libavformat/supdec.c",
root_path ++ "ffmpeg/libavformat/supenc.c",
root_path ++ "ffmpeg/libavformat/svag.c",
root_path ++ "ffmpeg/libavformat/svs.c",
root_path ++ "ffmpeg/libavformat/swf.c",
root_path ++ "ffmpeg/libavformat/swfdec.c",
root_path ++ "ffmpeg/libavformat/swfenc.c",
root_path ++ "ffmpeg/libavformat/takdec.c",
root_path ++ "ffmpeg/libavformat/tcp.c",
root_path ++ "ffmpeg/libavformat/tedcaptionsdec.c",
root_path ++ "ffmpeg/libavformat/tee.c",
root_path ++ "ffmpeg/libavformat/tee_common.c",
root_path ++ "ffmpeg/libavformat/teeproto.c",
root_path ++ "ffmpeg/libavformat/thp.c",
root_path ++ "ffmpeg/libavformat/tiertexseq.c",
root_path ++ "ffmpeg/libavformat/tmv.c",
root_path ++ "ffmpeg/libavformat/tta.c",
root_path ++ "ffmpeg/libavformat/ttaenc.c",
root_path ++ "ffmpeg/libavformat/ttmlenc.c",
root_path ++ "ffmpeg/libavformat/tty.c",
root_path ++ "ffmpeg/libavformat/txd.c",
root_path ++ "ffmpeg/libavformat/ty.c",
root_path ++ "ffmpeg/libavformat/udp.c",
root_path ++ "ffmpeg/libavformat/uncodedframecrcenc.c",
root_path ++ "ffmpeg/libavformat/unix.c",
root_path ++ "ffmpeg/libavformat/url.c",
root_path ++ "ffmpeg/libavformat/urldecode.c",
root_path ++ "ffmpeg/libavformat/utils.c",
root_path ++ "ffmpeg/libavformat/v210.c",
root_path ++ "ffmpeg/libavformat/vag.c",
root_path ++ "ffmpeg/libavformat/vc1dec.c",
root_path ++ "ffmpeg/libavformat/vc1test.c",
root_path ++ "ffmpeg/libavformat/vc1testenc.c",
root_path ++ "ffmpeg/libavformat/vividas.c",
root_path ++ "ffmpeg/libavformat/vivo.c",
root_path ++ "ffmpeg/libavformat/voc.c",
root_path ++ "ffmpeg/libavformat/voc_packet.c",
root_path ++ "ffmpeg/libavformat/vocdec.c",
root_path ++ "ffmpeg/libavformat/vocenc.c",
root_path ++ "ffmpeg/libavformat/vorbiscomment.c",
root_path ++ "ffmpeg/libavformat/vpcc.c",
root_path ++ "ffmpeg/libavformat/vpk.c",
root_path ++ "ffmpeg/libavformat/vplayerdec.c",
root_path ++ "ffmpeg/libavformat/vqf.c",
root_path ++ "ffmpeg/libavformat/w64.c",
root_path ++ "ffmpeg/libavformat/wavdec.c",
root_path ++ "ffmpeg/libavformat/wavenc.c",
root_path ++ "ffmpeg/libavformat/wc3movie.c",
root_path ++ "ffmpeg/libavformat/webm_chunk.c",
root_path ++ "ffmpeg/libavformat/webmdashenc.c",
root_path ++ "ffmpeg/libavformat/webpenc.c",
root_path ++ "ffmpeg/libavformat/webvttdec.c",
root_path ++ "ffmpeg/libavformat/webvttenc.c",
root_path ++ "ffmpeg/libavformat/westwood_aud.c",
root_path ++ "ffmpeg/libavformat/westwood_vqa.c",
root_path ++ "ffmpeg/libavformat/wsddec.c",
root_path ++ "ffmpeg/libavformat/wtv_common.c",
root_path ++ "ffmpeg/libavformat/wtvdec.c",
root_path ++ "ffmpeg/libavformat/wtvenc.c",
root_path ++ "ffmpeg/libavformat/wv.c",
root_path ++ "ffmpeg/libavformat/wvdec.c",
root_path ++ "ffmpeg/libavformat/wvedec.c",
root_path ++ "ffmpeg/libavformat/wvenc.c",
root_path ++ "ffmpeg/libavformat/xa.c",
root_path ++ "ffmpeg/libavformat/xmv.c",
root_path ++ "ffmpeg/libavformat/xvag.c",
root_path ++ "ffmpeg/libavformat/xwma.c",
root_path ++ "ffmpeg/libavformat/yop.c",
root_path ++ "ffmpeg/libavformat/yuv4mpegdec.c",
root_path ++ "ffmpeg/libavformat/yuv4mpegenc.c",
};
const avfilter_sources = &.{
root_path ++ "ffmpeg/libavfilter/aeval.c",
root_path ++ "ffmpeg/libavfilter/af_acontrast.c",
root_path ++ "ffmpeg/libavfilter/af_acopy.c",
root_path ++ "ffmpeg/libavfilter/af_acrossover.c",
root_path ++ "ffmpeg/libavfilter/af_acrusher.c",
root_path ++ "ffmpeg/libavfilter/af_adeclick.c",
root_path ++ "ffmpeg/libavfilter/af_adelay.c",
root_path ++ "ffmpeg/libavfilter/af_adenorm.c",
root_path ++ "ffmpeg/libavfilter/af_aderivative.c",
root_path ++ "ffmpeg/libavfilter/af_aecho.c",
root_path ++ "ffmpeg/libavfilter/af_aemphasis.c",
root_path ++ "ffmpeg/libavfilter/af_aexciter.c",
root_path ++ "ffmpeg/libavfilter/af_afade.c",
root_path ++ "ffmpeg/libavfilter/af_afftdn.c",
root_path ++ "ffmpeg/libavfilter/af_afftfilt.c",
root_path ++ "ffmpeg/libavfilter/af_afir.c",
root_path ++ "ffmpeg/libavfilter/af_aformat.c",
root_path ++ "ffmpeg/libavfilter/af_afreqshift.c",
root_path ++ "ffmpeg/libavfilter/af_agate.c",
root_path ++ "ffmpeg/libavfilter/af_aiir.c",
root_path ++ "ffmpeg/libavfilter/af_alimiter.c",
root_path ++ "ffmpeg/libavfilter/af_amerge.c",
root_path ++ "ffmpeg/libavfilter/af_amix.c",
root_path ++ "ffmpeg/libavfilter/af_amultiply.c",
root_path ++ "ffmpeg/libavfilter/af_anequalizer.c",
root_path ++ "ffmpeg/libavfilter/af_anlmdn.c",
root_path ++ "ffmpeg/libavfilter/af_anlms.c",
root_path ++ "ffmpeg/libavfilter/af_anull.c",
root_path ++ "ffmpeg/libavfilter/af_apad.c",
root_path ++ "ffmpeg/libavfilter/af_aphaser.c",
root_path ++ "ffmpeg/libavfilter/af_apulsator.c",
root_path ++ "ffmpeg/libavfilter/af_aresample.c",
root_path ++ "ffmpeg/libavfilter/af_arnndn.c",
root_path ++ "ffmpeg/libavfilter/af_asetnsamples.c",
root_path ++ "ffmpeg/libavfilter/af_asetrate.c",
root_path ++ "ffmpeg/libavfilter/af_ashowinfo.c",
root_path ++ "ffmpeg/libavfilter/af_asoftclip.c",
root_path ++ "ffmpeg/libavfilter/af_astats.c",
root_path ++ "ffmpeg/libavfilter/af_asubboost.c",
root_path ++ "ffmpeg/libavfilter/af_asupercut.c",
root_path ++ "ffmpeg/libavfilter/af_atempo.c",
root_path ++ "ffmpeg/libavfilter/af_axcorrelate.c",
root_path ++ "ffmpeg/libavfilter/af_biquads.c",
root_path ++ "ffmpeg/libavfilter/af_channelmap.c",
root_path ++ "ffmpeg/libavfilter/af_channelsplit.c",
root_path ++ "ffmpeg/libavfilter/af_chorus.c",
root_path ++ "ffmpeg/libavfilter/af_compand.c",
root_path ++ "ffmpeg/libavfilter/af_compensationdelay.c",
root_path ++ "ffmpeg/libavfilter/af_crossfeed.c",
root_path ++ "ffmpeg/libavfilter/af_crystalizer.c",
root_path ++ "ffmpeg/libavfilter/af_dcshift.c",
root_path ++ "ffmpeg/libavfilter/af_deesser.c",
root_path ++ "ffmpeg/libavfilter/af_drmeter.c",
root_path ++ "ffmpeg/libavfilter/af_dynaudnorm.c",
root_path ++ "ffmpeg/libavfilter/af_earwax.c",
root_path ++ "ffmpeg/libavfilter/af_extrastereo.c",
root_path ++ "ffmpeg/libavfilter/af_firequalizer.c",
root_path ++ "ffmpeg/libavfilter/af_flanger.c",
root_path ++ "ffmpeg/libavfilter/af_haas.c",
root_path ++ "ffmpeg/libavfilter/af_hdcd.c",
root_path ++ "ffmpeg/libavfilter/af_headphone.c",
root_path ++ "ffmpeg/libavfilter/af_join.c",
root_path ++ "ffmpeg/libavfilter/af_loudnorm.c",
root_path ++ "ffmpeg/libavfilter/af_mcompand.c",
root_path ++ "ffmpeg/libavfilter/af_pan.c",
root_path ++ "ffmpeg/libavfilter/af_replaygain.c",
root_path ++ "ffmpeg/libavfilter/af_sidechaincompress.c",
root_path ++ "ffmpeg/libavfilter/af_silencedetect.c",
root_path ++ "ffmpeg/libavfilter/af_silenceremove.c",
root_path ++ "ffmpeg/libavfilter/af_speechnorm.c",
root_path ++ "ffmpeg/libavfilter/af_stereotools.c",
root_path ++ "ffmpeg/libavfilter/af_stereowiden.c",
root_path ++ "ffmpeg/libavfilter/af_superequalizer.c",
root_path ++ "ffmpeg/libavfilter/af_surround.c",
root_path ++ "ffmpeg/libavfilter/af_tremolo.c",
root_path ++ "ffmpeg/libavfilter/af_vibrato.c",
root_path ++ "ffmpeg/libavfilter/af_volume.c",
root_path ++ "ffmpeg/libavfilter/af_volumedetect.c",
root_path ++ "ffmpeg/libavfilter/allfilters.c",
root_path ++ "ffmpeg/libavfilter/asink_anullsink.c",
root_path ++ "ffmpeg/libavfilter/asrc_afirsrc.c",
root_path ++ "ffmpeg/libavfilter/asrc_anoisesrc.c",
root_path ++ "ffmpeg/libavfilter/asrc_anullsrc.c",
root_path ++ "ffmpeg/libavfilter/asrc_hilbert.c",
root_path ++ "ffmpeg/libavfilter/asrc_sinc.c",
root_path ++ "ffmpeg/libavfilter/asrc_sine.c",
root_path ++ "ffmpeg/libavfilter/audio.c",
root_path ++ "ffmpeg/libavfilter/avf_abitscope.c",
root_path ++ "ffmpeg/libavfilter/avf_ahistogram.c",
root_path ++ "ffmpeg/libavfilter/avf_aphasemeter.c",
root_path ++ "ffmpeg/libavfilter/avf_avectorscope.c",
root_path ++ "ffmpeg/libavfilter/avf_concat.c",
root_path ++ "ffmpeg/libavfilter/avf_showcqt.c",
root_path ++ "ffmpeg/libavfilter/avf_showfreqs.c",
root_path ++ "ffmpeg/libavfilter/avf_showspatial.c",
root_path ++ "ffmpeg/libavfilter/avf_showspectrum.c",
root_path ++ "ffmpeg/libavfilter/avf_showvolume.c",
root_path ++ "ffmpeg/libavfilter/avf_showwaves.c",
root_path ++ "ffmpeg/libavfilter/avfilter.c",
root_path ++ "ffmpeg/libavfilter/avfiltergraph.c",
root_path ++ "ffmpeg/libavfilter/bbox.c",
root_path ++ "ffmpeg/libavfilter/buffersink.c",
root_path ++ "ffmpeg/libavfilter/buffersrc.c",
root_path ++ "ffmpeg/libavfilter/colorspace.c",
root_path ++ "ffmpeg/libavfilter/colorspacedsp.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_backend_native.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_backend_native_layer_avgpool.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_backend_native_layer_conv2d.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_backend_native_layer_dense.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_backend_native_layer_depth2space.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_backend_native_layer_mathbinary.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_backend_native_layer_mathunary.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_backend_native_layer_maximum.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_backend_native_layer_pad.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_backend_native_layers.c",
//root_path ++ "ffmpeg/libavfilter/dnn/dnn_backend_openvino.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_interface.c",
root_path ++ "ffmpeg/libavfilter/dnn/dnn_io_proc.c",
root_path ++ "ffmpeg/libavfilter/dnn/queue.c",
root_path ++ "ffmpeg/libavfilter/dnn/safe_queue.c",
root_path ++ "ffmpeg/libavfilter/dnn_filter_common.c",
root_path ++ "ffmpeg/libavfilter/dnn_filter_common.c",
root_path ++ "ffmpeg/libavfilter/drawutils.c",
root_path ++ "ffmpeg/libavfilter/ebur128.c",
root_path ++ "ffmpeg/libavfilter/f_bench.c",
root_path ++ "ffmpeg/libavfilter/f_cue.c",
root_path ++ "ffmpeg/libavfilter/f_drawgraph.c",
root_path ++ "ffmpeg/libavfilter/f_ebur128.c",
root_path ++ "ffmpeg/libavfilter/f_graphmonitor.c",
root_path ++ "ffmpeg/libavfilter/f_interleave.c",
root_path ++ "ffmpeg/libavfilter/f_loop.c",
root_path ++ "ffmpeg/libavfilter/f_metadata.c",
root_path ++ "ffmpeg/libavfilter/f_perms.c",
root_path ++ "ffmpeg/libavfilter/f_realtime.c",
root_path ++ "ffmpeg/libavfilter/f_reverse.c",
root_path ++ "ffmpeg/libavfilter/f_select.c",
root_path ++ "ffmpeg/libavfilter/f_sendcmd.c",
root_path ++ "ffmpeg/libavfilter/f_sidedata.c",
root_path ++ "ffmpeg/libavfilter/f_streamselect.c",
root_path ++ "ffmpeg/libavfilter/fifo.c",
root_path ++ "ffmpeg/libavfilter/formats.c",
root_path ++ "ffmpeg/libavfilter/framepool.c",
root_path ++ "ffmpeg/libavfilter/framequeue.c",
root_path ++ "ffmpeg/libavfilter/framesync.c",
root_path ++ "ffmpeg/libavfilter/generate_wave_table.c",
root_path ++ "ffmpeg/libavfilter/graphdump.c",
root_path ++ "ffmpeg/libavfilter/graphparser.c",
root_path ++ "ffmpeg/libavfilter/lavfutils.c",
root_path ++ "ffmpeg/libavfilter/lswsutils.c",
root_path ++ "ffmpeg/libavfilter/motion_estimation.c",
root_path ++ "ffmpeg/libavfilter/pthread.c",
root_path ++ "ffmpeg/libavfilter/qp_table.c",
root_path ++ "ffmpeg/libavfilter/scale_eval.c",
root_path ++ "ffmpeg/libavfilter/scene_sad.c",
root_path ++ "ffmpeg/libavfilter/setpts.c",
root_path ++ "ffmpeg/libavfilter/settb.c",
root_path ++ "ffmpeg/libavfilter/split.c",
root_path ++ "ffmpeg/libavfilter/src_movie.c",
root_path ++ "ffmpeg/libavfilter/transform.c",
root_path ++ "ffmpeg/libavfilter/trim.c",
root_path ++ "ffmpeg/libavfilter/vaf_spectrumsynth.c",
root_path ++ "ffmpeg/libavfilter/vf_addroi.c",
root_path ++ "ffmpeg/libavfilter/vf_alphamerge.c",
root_path ++ "ffmpeg/libavfilter/vf_amplify.c",
root_path ++ "ffmpeg/libavfilter/vf_aspect.c",
root_path ++ "ffmpeg/libavfilter/vf_atadenoise.c",
root_path ++ "ffmpeg/libavfilter/vf_avgblur.c",
root_path ++ "ffmpeg/libavfilter/vf_bbox.c",
root_path ++ "ffmpeg/libavfilter/vf_bilateral.c",
root_path ++ "ffmpeg/libavfilter/vf_bitplanenoise.c",
root_path ++ "ffmpeg/libavfilter/vf_blackdetect.c",
root_path ++ "ffmpeg/libavfilter/vf_blend.c",
root_path ++ "ffmpeg/libavfilter/vf_bm3d.c",
root_path ++ "ffmpeg/libavfilter/vf_bwdif.c",
root_path ++ "ffmpeg/libavfilter/vf_cas.c",
root_path ++ "ffmpeg/libavfilter/vf_chromakey.c",
root_path ++ "ffmpeg/libavfilter/vf_chromanr.c",
root_path ++ "ffmpeg/libavfilter/vf_chromashift.c",
root_path ++ "ffmpeg/libavfilter/vf_ciescope.c",
root_path ++ "ffmpeg/libavfilter/vf_codecview.c",
root_path ++ "ffmpeg/libavfilter/vf_colorbalance.c",
root_path ++ "ffmpeg/libavfilter/vf_colorchannelmixer.c",
root_path ++ "ffmpeg/libavfilter/vf_colorconstancy.c",
root_path ++ "ffmpeg/libavfilter/vf_colorcontrast.c",
root_path ++ "ffmpeg/libavfilter/vf_colorcorrect.c",
root_path ++ "ffmpeg/libavfilter/vf_colorize.c",
root_path ++ "ffmpeg/libavfilter/vf_colorkey.c",
root_path ++ "ffmpeg/libavfilter/vf_colorlevels.c",
root_path ++ "ffmpeg/libavfilter/vf_colorspace.c",
root_path ++ "ffmpeg/libavfilter/vf_colortemperature.c",
root_path ++ "ffmpeg/libavfilter/vf_convolution.c",
root_path ++ "ffmpeg/libavfilter/vf_convolve.c",
root_path ++ "ffmpeg/libavfilter/vf_copy.c",
root_path ++ "ffmpeg/libavfilter/vf_crop.c",
root_path ++ "ffmpeg/libavfilter/vf_curves.c",
root_path ++ "ffmpeg/libavfilter/vf_datascope.c",
root_path ++ "ffmpeg/libavfilter/vf_dblur.c",
root_path ++ "ffmpeg/libavfilter/vf_dctdnoiz.c",
root_path ++ "ffmpeg/libavfilter/vf_deband.c",
root_path ++ "ffmpeg/libavfilter/vf_deblock.c",
root_path ++ "ffmpeg/libavfilter/vf_decimate.c",
root_path ++ "ffmpeg/libavfilter/vf_dedot.c",
root_path ++ "ffmpeg/libavfilter/vf_deflicker.c",
root_path ++ "ffmpeg/libavfilter/vf_dejudder.c",
root_path ++ "ffmpeg/libavfilter/vf_derain.c",
root_path ++ "ffmpeg/libavfilter/vf_deshake.c",
root_path ++ "ffmpeg/libavfilter/vf_despill.c",
root_path ++ "ffmpeg/libavfilter/vf_detelecine.c",
root_path ++ "ffmpeg/libavfilter/vf_displace.c",
root_path ++ "ffmpeg/libavfilter/vf_dnn_processing.c",
root_path ++ "ffmpeg/libavfilter/vf_drawbox.c",
root_path ++ "ffmpeg/libavfilter/vf_edgedetect.c",
root_path ++ "ffmpeg/libavfilter/vf_elbg.c",
root_path ++ "ffmpeg/libavfilter/vf_entropy.c",
root_path ++ "ffmpeg/libavfilter/vf_epx.c",
root_path ++ "ffmpeg/libavfilter/vf_estdif.c",
root_path ++ "ffmpeg/libavfilter/vf_exposure.c",
root_path ++ "ffmpeg/libavfilter/vf_extractplanes.c",
root_path ++ "ffmpeg/libavfilter/vf_fade.c",
root_path ++ "ffmpeg/libavfilter/vf_fftdnoiz.c",
root_path ++ "ffmpeg/libavfilter/vf_fftfilt.c",
root_path ++ "ffmpeg/libavfilter/vf_field.c",
root_path ++ "ffmpeg/libavfilter/vf_fieldhint.c",
root_path ++ "ffmpeg/libavfilter/vf_fieldmatch.c",
root_path ++ "ffmpeg/libavfilter/vf_fieldorder.c",
root_path ++ "ffmpeg/libavfilter/vf_fillborders.c",
root_path ++ "ffmpeg/libavfilter/vf_floodfill.c",
root_path ++ "ffmpeg/libavfilter/vf_format.c",
root_path ++ "ffmpeg/libavfilter/vf_fps.c",
root_path ++ "ffmpeg/libavfilter/vf_framepack.c",
root_path ++ "ffmpeg/libavfilter/vf_framerate.c",
root_path ++ "ffmpeg/libavfilter/vf_framestep.c",
root_path ++ "ffmpeg/libavfilter/vf_freezedetect.c",
root_path ++ "ffmpeg/libavfilter/vf_freezeframes.c",
root_path ++ "ffmpeg/libavfilter/vf_gblur.c",
root_path ++ "ffmpeg/libavfilter/vf_geq.c",
root_path ++ "ffmpeg/libavfilter/vf_gradfun.c",
root_path ++ "ffmpeg/libavfilter/vf_hflip.c",
root_path ++ "ffmpeg/libavfilter/vf_histogram.c",
root_path ++ "ffmpeg/libavfilter/vf_hqx.c",
root_path ++ "ffmpeg/libavfilter/vf_hue.c",
root_path ++ "ffmpeg/libavfilter/vf_hwdownload.c",
root_path ++ "ffmpeg/libavfilter/vf_hwmap.c",
root_path ++ "ffmpeg/libavfilter/vf_hwupload.c",
root_path ++ "ffmpeg/libavfilter/vf_hysteresis.c",
root_path ++ "ffmpeg/libavfilter/vf_identity.c",
root_path ++ "ffmpeg/libavfilter/vf_idet.c",
root_path ++ "ffmpeg/libavfilter/vf_il.c",
root_path ++ "ffmpeg/libavfilter/vf_lagfun.c",
root_path ++ "ffmpeg/libavfilter/vf_lenscorrection.c",
root_path ++ "ffmpeg/libavfilter/vf_limiter.c",
root_path ++ "ffmpeg/libavfilter/vf_lumakey.c",
root_path ++ "ffmpeg/libavfilter/vf_lut.c",
root_path ++ "ffmpeg/libavfilter/vf_lut2.c",
root_path ++ "ffmpeg/libavfilter/vf_lut3d.c",
root_path ++ "ffmpeg/libavfilter/vf_maskedclamp.c",
root_path ++ "ffmpeg/libavfilter/vf_maskedmerge.c",
root_path ++ "ffmpeg/libavfilter/vf_maskedminmax.c",
root_path ++ "ffmpeg/libavfilter/vf_maskedthreshold.c",
root_path ++ "ffmpeg/libavfilter/vf_maskfun.c",
root_path ++ "ffmpeg/libavfilter/vf_median.c",
root_path ++ "ffmpeg/libavfilter/vf_mergeplanes.c",
root_path ++ "ffmpeg/libavfilter/vf_mestimate.c",
root_path ++ "ffmpeg/libavfilter/vf_midequalizer.c",
root_path ++ "ffmpeg/libavfilter/vf_minterpolate.c",
root_path ++ "ffmpeg/libavfilter/vf_mix.c",
root_path ++ "ffmpeg/libavfilter/vf_monochrome.c",
root_path ++ "ffmpeg/libavfilter/vf_neighbor.c",
root_path ++ "ffmpeg/libavfilter/vf_nlmeans.c",
root_path ++ "ffmpeg/libavfilter/vf_noise.c",
root_path ++ "ffmpeg/libavfilter/vf_normalize.c",
root_path ++ "ffmpeg/libavfilter/vf_null.c",
root_path ++ "ffmpeg/libavfilter/vf_overlay.c",
root_path ++ "ffmpeg/libavfilter/vf_pad.c",
root_path ++ "ffmpeg/libavfilter/vf_palettegen.c",
root_path ++ "ffmpeg/libavfilter/vf_paletteuse.c",
root_path ++ "ffmpeg/libavfilter/vf_photosensitivity.c",
root_path ++ "ffmpeg/libavfilter/vf_pixdesctest.c",
root_path ++ "ffmpeg/libavfilter/vf_premultiply.c",
root_path ++ "ffmpeg/libavfilter/vf_pseudocolor.c",
root_path ++ "ffmpeg/libavfilter/vf_psnr.c",
root_path ++ "ffmpeg/libavfilter/vf_qp.c",
root_path ++ "ffmpeg/libavfilter/vf_random.c",
root_path ++ "ffmpeg/libavfilter/vf_readeia608.c",
root_path ++ "ffmpeg/libavfilter/vf_readvitc.c",
root_path ++ "ffmpeg/libavfilter/vf_remap.c",
root_path ++ "ffmpeg/libavfilter/vf_removegrain.c",
root_path ++ "ffmpeg/libavfilter/vf_removelogo.c",
root_path ++ "ffmpeg/libavfilter/vf_rotate.c",
root_path ++ "ffmpeg/libavfilter/vf_scale.c",
root_path ++ "ffmpeg/libavfilter/vf_scale_cuda.h",
root_path ++ "ffmpeg/libavfilter/vf_scdet.c",
root_path ++ "ffmpeg/libavfilter/vf_scroll.c",
root_path ++ "ffmpeg/libavfilter/vf_selectivecolor.c",
root_path ++ "ffmpeg/libavfilter/vf_separatefields.c",
root_path ++ "ffmpeg/libavfilter/vf_setparams.c",
root_path ++ "ffmpeg/libavfilter/vf_shear.c",
root_path ++ "ffmpeg/libavfilter/vf_showinfo.c",
root_path ++ "ffmpeg/libavfilter/vf_showpalette.c",
root_path ++ "ffmpeg/libavfilter/vf_shuffleframes.c",
root_path ++ "ffmpeg/libavfilter/vf_shufflepixels.c",
root_path ++ "ffmpeg/libavfilter/vf_shuffleplanes.c",
root_path ++ "ffmpeg/libavfilter/vf_signalstats.c",
root_path ++ "ffmpeg/libavfilter/vf_sr.c",
root_path ++ "ffmpeg/libavfilter/vf_ssim.c",
root_path ++ "ffmpeg/libavfilter/vf_stack.c",
root_path ++ "ffmpeg/libavfilter/vf_swaprect.c",
root_path ++ "ffmpeg/libavfilter/vf_swapuv.c",
root_path ++ "ffmpeg/libavfilter/vf_telecine.c",
root_path ++ "ffmpeg/libavfilter/vf_threshold.c",
root_path ++ "ffmpeg/libavfilter/vf_thumbnail.c",
root_path ++ "ffmpeg/libavfilter/vf_tile.c",
root_path ++ "ffmpeg/libavfilter/vf_tmidequalizer.c",
root_path ++ "ffmpeg/libavfilter/vf_tonemap.c",
root_path ++ "ffmpeg/libavfilter/vf_tpad.c",
root_path ++ "ffmpeg/libavfilter/vf_transpose.c",
root_path ++ "ffmpeg/libavfilter/vf_unsharp.c",
root_path ++ "ffmpeg/libavfilter/vf_untile.c",
root_path ++ "ffmpeg/libavfilter/vf_v360.c",
root_path ++ "ffmpeg/libavfilter/vf_vectorscope.c",
root_path ++ "ffmpeg/libavfilter/vf_vflip.c",
root_path ++ "ffmpeg/libavfilter/vf_vfrdet.c",
root_path ++ "ffmpeg/libavfilter/vf_vibrance.c",
root_path ++ "ffmpeg/libavfilter/vf_vif.c",
root_path ++ "ffmpeg/libavfilter/vf_vignette.c",
root_path ++ "ffmpeg/libavfilter/vf_vmafmotion.c",
root_path ++ "ffmpeg/libavfilter/vf_w3fdif.c",
root_path ++ "ffmpeg/libavfilter/vf_waveform.c",
root_path ++ "ffmpeg/libavfilter/vf_weave.c",
root_path ++ "ffmpeg/libavfilter/vf_xbr.c",
root_path ++ "ffmpeg/libavfilter/vf_xfade.c",
root_path ++ "ffmpeg/libavfilter/vf_xmedian.c",
root_path ++ "ffmpeg/libavfilter/vf_yadif.c",
root_path ++ "ffmpeg/libavfilter/vf_yaepblur.c",
root_path ++ "ffmpeg/libavfilter/vf_zoompan.c",
root_path ++ "ffmpeg/libavfilter/video.c",
root_path ++ "ffmpeg/libavfilter/vsink_nullsink.c",
root_path ++ "ffmpeg/libavfilter/vsrc_cellauto.c",
root_path ++ "ffmpeg/libavfilter/vsrc_gradients.c",
root_path ++ "ffmpeg/libavfilter/vsrc_life.c",
root_path ++ "ffmpeg/libavfilter/vsrc_mandelbrot.c",
root_path ++ "ffmpeg/libavfilter/vsrc_sierpinski.c",
root_path ++ "ffmpeg/libavfilter/vsrc_testsrc.c",
root_path ++ "ffmpeg/libavfilter/x86/af_afir_init.c",
root_path ++ "ffmpeg/libavfilter/x86/af_anlmdn_init.c",
root_path ++ "ffmpeg/libavfilter/x86/af_volume_init.c",
root_path ++ "ffmpeg/libavfilter/x86/avf_showcqt_init.c",
root_path ++ "ffmpeg/libavfilter/x86/colorspacedsp_init.c",
root_path ++ "ffmpeg/libavfilter/x86/scene_sad_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_atadenoise_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_blend_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_bwdif_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_convolution_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_framerate_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_gblur_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_gradfun_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_hflip_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_idet_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_limiter_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_maskedclamp_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_maskedmerge_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_noise.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_overlay_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_psnr_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_removegrain_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_ssim_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_threshold_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_transpose_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_v360_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_w3fdif_init.c",
root_path ++ "ffmpeg/libavfilter/x86/vf_yadif_init.c",
root_path ++ "ffmpeg/libavfilter/yadif_common.c",
};
const swresample_sources = &.{
root_path ++ "ffmpeg/libswresample/audioconvert.c",
root_path ++ "ffmpeg/libswresample/dither.c",
root_path ++ "ffmpeg/libswresample/options.c",
root_path ++ "ffmpeg/libswresample/rematrix.c",
root_path ++ "ffmpeg/libswresample/resample.c",
root_path ++ "ffmpeg/libswresample/resample_dsp.c",
root_path ++ "ffmpeg/libswresample/swresample.c",
root_path ++ "ffmpeg/libswresample/swresample_frame.c",
root_path ++ "ffmpeg/libswresample/x86/audio_convert_init.c",
root_path ++ "ffmpeg/libswresample/x86/rematrix_init.c",
root_path ++ "ffmpeg/libswresample/x86/resample_init.c",
};
const swscale_sources = &.{
root_path ++ "ffmpeg/libswscale/alphablend.c",
root_path ++ "ffmpeg/libswscale/gamma.c",
root_path ++ "ffmpeg/libswscale/hscale.c",
root_path ++ "ffmpeg/libswscale/hscale_fast_bilinear.c",
root_path ++ "ffmpeg/libswscale/input.c",
root_path ++ "ffmpeg/libswscale/options.c",
root_path ++ "ffmpeg/libswscale/output.c",
root_path ++ "ffmpeg/libswscale/rgb2rgb.c",
root_path ++ "ffmpeg/libswscale/slice.c",
root_path ++ "ffmpeg/libswscale/swscale.c",
root_path ++ "ffmpeg/libswscale/swscale_unscaled.c",
root_path ++ "ffmpeg/libswscale/utils.c",
root_path ++ "ffmpeg/libswscale/vscale.c",
root_path ++ "ffmpeg/libswscale/x86/hscale_fast_bilinear_simd.c",
root_path ++ "ffmpeg/libswscale/x86/rgb2rgb.c",
root_path ++ "ffmpeg/libswscale/x86/swscale.c",
root_path ++ "ffmpeg/libswscale/x86/yuv2rgb.c",
root_path ++ "ffmpeg/libswscale/yuv2rgb.c",
}; | ffmpeg.zig |
const std = @import("std");
/// wraps either a free function or a bound function that takes an Event as a parameter
pub fn Delegate(comptime Event: type) type {
return struct {
const Self = @This();
ctx_ptr_address: usize = 0,
callback: union(enum) {
free: fn (Event) void,
bound: fn (usize, Event) void,
},
/// sets a bound function as the Delegate callback
pub fn initBound(ctx: anytype, comptime fn_name: []const u8) Self {
std.debug.assert(@typeInfo(@TypeOf(ctx)) == .Pointer);
std.debug.assert(@ptrToInt(ctx) != 0);
const T = @TypeOf(ctx);
return Self{
.ctx_ptr_address = @ptrToInt(ctx),
.callback = .{
.bound = struct {
fn cb(self: usize, param: Event) void {
@call(.{ .modifier = .always_inline }, @field(@intToPtr(T, self), fn_name), .{param});
}
}.cb,
},
};
}
/// sets a free function as the Delegate callback
pub fn initFree(func: fn (Event) void) Self {
return Self{
.callback = .{ .free = func },
};
}
pub fn trigger(self: Self, param: Event) void {
switch (self.callback) {
.free => |func| @call(.{}, func, .{param}),
.bound => |func| @call(.{}, func, .{ self.ctx_ptr_address, param }),
}
}
pub fn containsFree(self: Self, callback: fn (Event) void) bool {
return switch (self.callback) {
.free => |func| func == callback,
else => false,
};
}
pub fn containsBound(self: Self, ctx: anytype) bool {
std.debug.assert(@ptrToInt(ctx) != 0);
std.debug.assert(@typeInfo(@TypeOf(ctx)) == .Pointer);
return switch (self.callback) {
.bound => @ptrToInt(ctx) == self.ctx_ptr_address,
else => false,
};
}
};
}
fn tester(param: u32) void {
std.testing.expectEqual(@as(u32, 666), param) catch unreachable;
}
const Thing = struct {
field: f32 = 0,
pub fn tester(_: *Thing, param: u32) void {
std.testing.expectEqual(@as(u32, 777), param) catch unreachable;
}
};
test "free Delegate" {
var d = Delegate(u32).initFree(tester);
d.trigger(666);
}
test "bound Delegate" {
var thing = Thing{};
var d = Delegate(u32).initBound(&thing, "tester");
d.trigger(777);
} | src/signals/delegate.zig |
const std = @import("std");
const stdx = @import("stdx");
const uv = @import("uv");
const v8 = @import("v8");
const t = stdx.testing;
const Null = stdx.ds.CompactNull(u32);
const RuntimeContext = @import("runtime.zig").RuntimeContext;
const EventDispatcher = stdx.events.EventDispatcher;
const log = stdx.log.scoped(.timer);
/// High performance timer to handle large amounts of timers and callbacks.
/// A binary min-heap is used to track the next closest timeout.
/// A hashmap is used to lookup group nodes by timeout value.
/// Each group node has timeouts clamped to the same millisecond with a singly linked list.
pub const Timer = struct {
const Self = @This();
alloc: std.mem.Allocator,
timer: *uv.uv_timer_t,
watch: std.time.Timer,
heap: std.PriorityQueue(u32, void, compare),
// Keys are in milliseconds relative to the watch start time. (This avoids having to update the timeout.)
map: std.AutoHashMap(u32, GroupNode),
ll_buf: stdx.ds.CompactSinglyLinkedListBuffer(u32, Node),
// Relative timeout in ms from watch start time that is currently set for the uv timer.
// If a new timeout is set at or past this value, we don't need to reset the timer.
// If a new timeout is set before this value, we do need to invoke uv_timer_start again.
// The initial state is at max(u32) so the first timeout should set the uv timer.
active_timeout: u32,
ctx: v8.Persistent(v8.Context),
receiver: v8.Value,
dispatcher: EventDispatcher,
/// RuntimeContext must already have inited uv_loop.
pub fn init(self: *Self, rt: *RuntimeContext) !void {
const alloc = rt.alloc;
const timer = alloc.create(uv.uv_timer_t) catch unreachable;
var res = uv.uv_timer_init(rt.uv_loop, timer);
uv.assertNoError(res);
timer.data = self;
self.* = .{
.alloc = alloc,
.timer = timer,
.heap = std.PriorityQueue(u32, void, compare).init(alloc, {}),
.watch = try std.time.Timer.start(),
.map = std.AutoHashMap(u32, GroupNode).init(alloc),
.ll_buf = stdx.ds.CompactSinglyLinkedListBuffer(u32, Node).init(alloc),
.active_timeout = std.math.maxInt(u32),
.ctx = rt.context,
.receiver = rt.global.toValue(),
.dispatcher = rt.event_dispatcher,
};
}
pub fn close(self: Self) void {
const res = uv.uv_timer_stop(self.timer);
uv.assertNoError(res);
uv.uv_close(@ptrCast(*uv.uv_handle_t, self.timer), null);
}
/// Should be called after close and closing uv events have been processed.
pub fn deinit(self: *Self) void {
self.alloc.destroy(self.timer);
self.heap.deinit();
self.map.deinit();
self.ll_buf.deinit();
}
fn onTimeout(ptr: [*c]uv.uv_timer_t) callconv(.C) void {
const timer = @ptrCast(*uv.uv_timer_t, ptr);
const self = stdx.mem.ptrCastAlign(*Self, timer.data);
self.processNext();
}
pub fn setTimeout(self: *Self, timeout_ms: u32, cb: v8.Persistent(v8.Function), cb_arg: ?v8.Persistent(v8.Value)) !u32 {
const now = @floatToInt(u32, @intToFloat(f32, self.watch.read()) / 1e6);
const abs_ms = now + timeout_ms;
const entry = try self.map.getOrPut(abs_ms);
if (!entry.found_existing) {
const head = try self.ll_buf.add(.{
.cb = cb,
.cb_arg = cb_arg,
});
entry.value_ptr.* = .{
.timeout = abs_ms,
.head = head,
.last = head,
};
try self.heap.add(abs_ms);
// Check if we need to start the uv timer.
if (abs_ms < self.active_timeout) {
self.dispatcher.startTimer(self.timer, timeout_ms, onTimeout);
self.active_timeout = abs_ms;
}
return head;
} else {
// Append to the last node in the list.
const new = try self.ll_buf.insertAfter(entry.value_ptr.last, .{
.cb = cb,
.cb_arg = cb_arg,
});
entry.value_ptr.last = new;
return new;
}
}
pub fn peekNext(self: *Self) ?u32 {
return self.heap.peek();
}
pub fn processNext(self: *Self) void {
// Pop the next timeout.
const timeout = self.heap.remove();
const group = self.map.get(timeout).?;
const ctx = self.ctx.inner;
// Invoke each callback in order and deinit them.
var cur = group.head;
while (cur != Null) {
var node = self.ll_buf.getNodeNoCheck(cur);
if (node.data.cb_arg) |*cb_arg| {
_ = node.data.cb.inner.call(ctx, self.receiver, &.{ cb_arg.inner });
cb_arg.deinit();
} else {
_ = node.data.cb.inner.call(ctx, self.receiver, &.{});
}
node.data.cb.deinit();
self.ll_buf.removeAssumeNoPrev(cur) catch unreachable;
cur = node.next;
}
// Remove this GroupNode.
if (!self.map.remove(timeout)) unreachable;
// TODO: Consider processing next timeouts that have already expired.
// Schedule the next timeout.
if (self.heap.len > 0) {
const next_timeout = self.peekNext().?;
const now = @floatToInt(u32, @intToFloat(f32, self.watch.read()) / 1e6);
var rel_timeout: u32 = undefined;
if (next_timeout < now) {
rel_timeout = 0;
} else {
rel_timeout = next_timeout - now;
}
self.dispatcher.startTimer(self.timer, rel_timeout, onTimeout);
self.active_timeout = next_timeout;
} else {
self.active_timeout = std.math.maxInt(u32);
}
}
};
// This does not test the libuv mechanism.
test "Timer" {
var rt: RuntimeContext = undefined;
rt.alloc = t.alloc;
var timer: Timer = undefined;
try timer.init(&rt);
defer timer.deinit();
const cb: v8.Persistent(v8.Function) = undefined;
_ = try timer.setTimeout(100, cb, null);
_ = try timer.setTimeout(200, cb, null);
_ = try timer.setTimeout(0, cb, null);
_ = try timer.setTimeout(0, cb, null);
_ = try timer.setTimeout(300, cb, null);
_ = try timer.setTimeout(300, cb, null);
const timeout = timer.peekNext().?;
try t.eq(timeout, 0);
timer.processNext();
try t.eq(timer.peekNext().?, 100);
timer.processNext();
try t.eq(timer.peekNext().?, 200);
timer.processNext();
try t.eq(timer.peekNext().?, 300);
timer.processNext();
try t.eq(timer.peekNext(), null);
}
// Assume no duplicate nodes since timeouts will be grouped together.
fn compare(_: void, a: u32, b: u32) std.math.Order {
if (a < b) {
return .lt;
} else {
return .gt;
}
}
const GroupNode = struct {
// In milliseconds relative to the watch's start time.
timeout: u32,
head: u32,
last: u32,
};
const Node = struct {
cb: v8.Persistent(v8.Function),
cb_arg: ?v8.Persistent(v8.Value),
}; | runtime/timer.zig |
const std = @import("std");
const builtin = @import("builtin");
const ThreadPool = @This();
mutex: std.Thread.Mutex = .{},
cond: std.Thread.Condition = .{},
run_queue: RunQueue = .{},
is_running: bool = true,
allocator: std.mem.Allocator,
threads: []std.Thread,
const RunQueue = std.SinglyLinkedList(Runnable);
const Runnable = struct {
runFn: RunProto,
};
const RunProto = switch (builtin.zig_backend) {
.stage1 => fn (*Runnable) void,
else => *const fn (*Runnable) void,
};
pub fn init(self: *ThreadPool, allocator: std.mem.Allocator) !void {
self.* = .{
.allocator = allocator,
.threads = &[_]std.Thread{},
};
if (builtin.single_threaded) {
return;
}
const thread_count = std.math.max(1, std.Thread.getCpuCount() catch 1);
self.threads = try allocator.alloc(std.Thread, thread_count);
errdefer allocator.free(self.threads);
// kill and join any threads we spawned previously on error.
var spawned: usize = 0;
errdefer self.join(spawned);
for (self.threads) |*thread| {
thread.* = try std.Thread.spawn(.{}, worker, .{self});
spawned += 1;
}
}
pub fn deinit(self: *ThreadPool) void {
self.join(self.threads.len); // kill and join all threads.
self.* = undefined;
}
fn join(self: *ThreadPool, spawned: usize) void {
if (builtin.single_threaded) {
return;
}
{
self.mutex.lock();
defer self.mutex.unlock();
// ensure future worker threads exit the dequeue loop
self.is_running = false;
}
// wake up any sleeping threads (this can be done outside the mutex)
// then wait for all the threads we know are spawned to complete.
self.cond.broadcast();
for (self.threads[0..spawned]) |thread| {
thread.join();
}
self.allocator.free(self.threads);
}
pub fn spawn(self: *ThreadPool, comptime func: anytype, args: anytype) !void {
if (builtin.single_threaded) {
@call(.{}, func, args);
return;
}
const Args = @TypeOf(args);
const Closure = struct {
arguments: Args,
pool: *ThreadPool,
run_node: RunQueue.Node = .{ .data = .{ .runFn = runFn } },
fn runFn(runnable: *Runnable) void {
const run_node = @fieldParentPtr(RunQueue.Node, "data", runnable);
const closure = @fieldParentPtr(@This(), "run_node", run_node);
@call(.{}, func, closure.arguments);
// The thread pool's allocator is protected by the mutex.
const mutex = &closure.pool.mutex;
mutex.lock();
defer mutex.unlock();
closure.pool.allocator.destroy(closure);
}
};
{
self.mutex.lock();
defer self.mutex.unlock();
const closure = try self.allocator.create(Closure);
closure.* = .{
.arguments = args,
.pool = self,
};
self.run_queue.prepend(&closure.run_node);
}
// Notify waiting threads outside the lock to try and keep the critical section small.
self.cond.signal();
}
fn worker(self: *ThreadPool) void {
self.mutex.lock();
defer self.mutex.unlock();
while (true) {
while (self.run_queue.popFirst()) |run_node| {
// Temporarily unlock the mutex in order to execute the run_node
self.mutex.unlock();
defer self.mutex.lock();
const runFn = run_node.data.runFn;
runFn(&run_node.data);
}
// Stop executing instead of waiting if the thread pool is no longer running.
if (self.is_running) {
self.cond.wait(&self.mutex);
} else {
break;
}
}
} | src/ThreadPool.zig |
const kernel = @import("../../kernel.zig");
pub const Spinlock = @import("spinlock.zig");
pub const sync = @import("sync.zig");
pub const DeviceTree = @import("device_tree.zig");
pub const Timer = @import("timer.zig");
pub const Paging = @import("paging.zig");
pub const Physical = @import("physical.zig");
pub const Virtual = @import("virtual.zig");
pub const Interrupts = @import("interrupts.zig");
pub const SBI = @import("opensbi.zig");
pub const virtio = @import("virtio.zig");
const UART = @import("uart.zig").UART;
pub const page_size = 0x1000;
pub const sector_size = 0x200;
pub const max_cpu = 64;
pub const dt_read_int = kernel.read_int_big;
pub var cpu_count: u64 = 0;
pub var current_cpu: u64 = 0;
const log = kernel.log.scoped(.RISCV64);
const TODO = kernel.TODO;
const Context = struct {
integer: [32]u64,
pc: u64,
interrupt_stack: u64,
float: [32]u64,
hart_id: u64,
pid: u64,
};
pub fn get_indexed_stack(index: u64) u64 {
return @ptrToInt(&stack_top) - (hart_stack_size * index);
}
extern var stack_top: u64;
const hart_stack_size = 0x8000;
pub const LocalStorage = struct {
context: Context,
padding: [page_size - @sizeOf(Context)]u8,
comptime {
kernel.assert_unsafe(@sizeOf(LocalStorage) == page_size);
}
pub fn init(self: *@This(), hart_id: u64, boot_hart: bool) void {
self.context.hart_id = hart_id;
self.context.interrupt_stack = @ptrToInt(&stack_top) - hart_stack_size * hart_id;
log.debug("Interrupt stack: 0x{x}", .{self.context.interrupt_stack});
self.context.pid = 0;
sscratch.write(@ptrToInt(&self.context));
var sstatus_value = sstatus.read();
sstatus_value |= 1 << 18 | 1 << 1;
if (!boot_hart) sstatus_value |= 1 << 8 | 1 << 5;
sstatus.write(sstatus_value);
sie.write(0x220);
// TODO: correct names
sync.set_hart_id(@ptrToInt(self));
if (!boot_hart) {
TODO(@src());
}
//SBI.set_timer(0);
}
pub fn get() *LocalStorage {
return @intToPtr(*LocalStorage, tp.read());
}
};
pub var local_storage: [max_cpu]LocalStorage = undefined;
pub const OldContext = struct {
reg: [32]usize,
sstatus: usize,
sepc: usize,
};
const Scause = enum(u64) {
instruction_address_misaligned = 0,
instruction_access_fault = 1,
illegal_instruction = 2,
breakpoint = 3,
load_address_misaligned = 4,
load_access_fault = 5,
store_address_misaligned = 6,
store_access_fault = 7,
environment_call_from_user_mode = 8,
environment_call_from_supervisor_mode = 9,
instruction_page_fault = 12,
load_page_fault = 13,
store_page_fault = 15,
supervisor_software_interrupt = 0x8000_0000_0000_0001,
supervisor_timer_interrupt = 0x8000_0000_0000_0005,
supervisor_external_interrupt = 0x8000_0000_0000_0009,
};
const ilog = kernel.log.scoped(.Interrupt);
export fn kernel_interrupt_handler(context: *OldContext, scause: Scause, stval: usize) void {
kernel.arch.writer.should_lock = false;
defer kernel.arch.writer.should_lock = true;
_ = context;
_ = stval;
//ilog.debug("Interrupt. SCAUSE: {}. STVAL: 0x{x}", .{ scause, stval });
const hart_id = local_storage[current_cpu].context.hart_id;
switch (scause) {
.supervisor_external_interrupt => Interrupts.handle_external_interrupt(hart_id),
else => spinloop(),
}
}
pub fn spinloop() noreturn {
while (true) {}
}
pub const UART0 = 0x1000_0000;
pub var uart = UART(UART0){
.lock = Spinlock{
._lock = 0,
.hart = null,
},
};
pub var device_tree: DeviceTree = undefined;
fn CSR(comptime reg_name: []const u8, comptime BitT: type) type {
return struct {
pub const Bit = BitT;
pub inline fn write(value: u64) void {
asm volatile ("csrw " ++ reg_name ++ ", %[arg1]"
:
: [arg1] "r" (value),
);
}
pub inline fn read() u64 {
return asm volatile ("csrr %[ret], " ++ reg_name
: [ret] "=r" (-> usize),
);
}
pub inline fn set(comptime bit: Bit) void {
const value: u64 = 1 << @enumToInt(bit);
asm volatile ("csrs " ++ reg_name ++ ", %[arg1]"
:
: [arg1] "r" (value),
);
}
pub inline fn clear(comptime bit: Bit) void {
const value: u64 = 1 << @enumToInt(bit);
asm volatile ("csrc " ++ reg_name ++ ", %[arg1]"
:
: [arg1] "r" (value),
);
}
};
}
const sstatus = CSR("sstatus", enum(u32) {
SIE = 1,
SPIE = 5,
UBE = 6,
SPP = 8,
SUM = 18,
MXR = 19,
});
const sie = CSR("sie", enum(u32) {
SSIE = 1,
STIE = 5,
SEIE = 9,
});
const cycle = CSR("cycle", enum(u32) { foo = 0 });
const stvec = CSR("stvec", enum(u32) { foo = 0 });
pub const SATP = CSR("satp", enum(u32) { foo = 0 });
const sscratch = CSR("sscratch", enum(u32) { foo = 0 });
const SATP_SV39: usize = (8 << 60);
pub inline fn MAKE_SATP(pagetable: usize) usize {
return (SATP_SV39 | (pagetable >> 12));
}
pub fn enable_interrupts() void {
sstatus.set(.SIE);
}
// disable interrupt
pub fn disable_interrupts() void {
sstatus.clear(.SIE);
}
pub fn write_function(bytes: []const u8) u64 {
const bytes_written = uart.write_bytes(bytes);
return bytes_written;
}
//pub inline fn print(comptime format: []const u8, args: anytype) void {
//writer.print(format, args) catch unreachable;
//}
//pub inline fn write(bytes: []const u8) void {
//_ = writer.write(bytes) catch unreachable;
//}
pub const Bounds = struct {
extern const kernel_start: u8;
extern const kernel_end: u8;
pub inline fn get_start() u64 {
return @ptrToInt(&kernel_start);
}
pub inline fn get_end() u64 {
return @ptrToInt(&kernel_end);
}
};
pub const PTE_VALID: usize = (1 << 0);
pub const PTE_READ: usize = (1 << 1);
pub const PTE_WRITE: usize = (1 << 2);
pub const PTE_EXEC: usize = (1 << 3);
pub const PTE_USER: usize = (1 << 4);
pub const PTE_GLOBAL: usize = (1 << 5);
pub const PTE_ACCESSED: usize = (1 << 6);
pub const PTE_DIRTY: usize = (1 << 7);
pub const memory_layout = struct {
pub const UART0: usize = 0x1000_0000;
};
pub inline fn flush_tlb() void {
asm volatile ("sfence.vma zero, zero");
}
pub const PAGE_INDEX_MASK: usize = 0x1FF; // 9 bits
pub const PTE_FLAG_MASK: usize = 0x3FF; // 10 bits
pub inline fn PTE_FLAGS(pte: usize) usize {
return pte & PTE_FLAG_MASK;
}
pub inline fn PAGE_INDEX(level: usize, virtual_address: usize) usize {
const page_index = (virtual_address >> PAGE_INDEX_SHIFT(level)) & PAGE_INDEX_MASK;
return page_index;
}
pub inline fn PTE_TO_PA(pte: usize) usize {
const pa = (pte >> 10) << 12;
return pa;
}
pub inline fn PA_TO_PTE(pa: usize) usize {
const pte = (pa >> 12) << 10;
return pte;
}
pub inline fn PAGE_INDEX_SHIFT(level: usize) u6 {
return @intCast(u6, PAGE_SHIFT + 9 * level);
}
pub const PAGE_SHIFT: usize = 12;
pub fn get_context(hart_id: u64, machine: u64) u64 {
return 2 * hart_id + machine;
}
pub const AddressSpace = struct {};
pub const tp = CommonRegister("tp");
pub fn CommonRegister(comptime reg_name: []const u8) type {
return struct {
pub inline fn write(value: u64) void {
asm volatile ("mv " ++ reg_name ++ ", %[arg1]"
:
: [arg1] "r" (value),
);
}
pub inline fn read() u64 {
return asm volatile ("mv %[ret], " ++ reg_name
: [ret] "=r" (-> u64),
);
}
};
}
pub extern fn trap() callconv(.Naked) void;
pub fn register_trap_handler(trap_handler: u64) void {
stvec.write(trap_handler);
}
pub extern fn switch_context(old: *kernel.scheduler.Context, new: *kernel.scheduler.Context) callconv(.C) void;
comptime {
asm (
\\.section .text
\\.align 16
\\.global switch_context
\\switch_context:
\\ sd ra, 0(a0)
\\sd sp, 8(a0)
\\sd s0, 16(a0)
\\sd s1, 24(a0)
\\sd s2, 32(a0)
\\sd s3, 40(a0)
\\sd s4, 48(a0)
\\sd s5, 56(a0)
\\sd s6, 64(a0)
\\sd s7, 72(a0)
\\sd s8, 80(a0)
\\sd s9, 88(a0)
\\sd s10, 96(a0)
\\sd s11, 104(a0)
\\ld ra, 0(a1)
\\ld sp, 8(a1)
\\ld s0, 16(a1)
\\ld s1, 24(a1)
\\ld s2, 32(a1)
\\ld s3, 40(a1)
\\ld s4, 48(a1)
\\ld s5, 56(a1)
\\ld s6, 64(a1)
\\ld s7, 72(a1)
\\ld s8, 80(a1)
\\ld s9, 88(a1)
\\ld s10, 96(a1)
\\ld s11, 104(a1)
\\
\\ret
);
}
fn init_logger() void {
uart.init(false);
}
fn init_cpu_count() void {
log.debug("CPU count initialized with 1. Is it correct?", .{});
// TODO: take from the device tree
cpu_count = 1;
}
fn init_persistent_storage() void {
log.debug("Initializing persistent storage...", .{});
// TODO: use the device tree
kernel.Driver(kernel.Disk, virtio.Block).init(0x10008000) catch @panic("Failed to initialize block driver");
kernel.Driver(kernel.Filesystem, kernel.RNUFS).init(kernel.Disk.drivers[kernel.Disk.drivers.len - 1]) catch @panic("Failed to initialize filesystem driver");
}
fn init_graphics() void {
log.debug("Initializing graphics...", .{});
const driver = kernel.Filesystem.drivers[0];
const file = driver.read_file_callback(driver, "font.psf");
log.debug("Font read from disk", .{});
kernel.font = kernel.PSF1.Font.parse(file);
log.debug("Font parsed", .{});
// TODO: use the device tree
kernel.Driver(kernel.graphics, virtio.GPU).init(0x10007000) catch @panic("error initializating graphics driver");
}
export fn riscv_start(boot_hart_id: u64, fdt_address: u64) callconv(.C) noreturn {
current_cpu = boot_hart_id;
register_trap_handler(@ptrToInt(trap));
init_logger();
log.debug("Hello RNU. Arch: {s}. Build mode: {s}. Boot HART id: {}. Device tree address: 0x{x}", .{ @tagName(kernel.current_arch), @tagName(kernel.build_mode), boot_hart_id, fdt_address });
device_tree.base_address = fdt_address;
device_tree.parse();
init_cpu_count();
Timer.init();
const time_start = Timer.get_timestamp();
Paging.init();
Interrupts.init(boot_hart_id);
local_storage[boot_hart_id].init(boot_hart_id, true);
const time = Timer.get_time_from_timestamp(Timer.get_timestamp() - time_start);
init_persistent_storage();
init_graphics();
kernel.graphics.drivers[0].draw_horizontal_line(kernel.graphics.Line{ .start = kernel.graphics.Point{ .x = 10, .y = 10 }, .end = kernel.graphics.Point{ .x = 100, .y = 10 } }, kernel.graphics.Color{ .red = 0, .green = 0, .blue = 0, .alpha = 0 });
kernel.graphics.drivers[0].test_draw_rect();
kernel.graphics.drivers[0].draw_rect(kernel.graphics.Rect{ .x = 10, .y = 10, .width = 10, .height = 10 }, kernel.graphics.Color{ .red = 0, .green = 0, .blue = 0, .alpha = 0 });
var i: u64 = 0;
while (i < 100) : (i += 1) {
kernel.graphics.drivers[0].draw_string(kernel.graphics.Color{ .red = 0, .green = 0, .blue = 0, .alpha = 0 }, "Hello Mariana");
}
@ptrCast(*virtio.GPU, kernel.graphics.drivers[0]).send_and_flush_framebuffer();
log.debug("Initialized in {} s {} us", .{ time.s, time.us });
spinloop();
//kernel.scheduler.schedule();
} | src/kernel/arch/riscv64/riscv64.zig |
const std = @import("std");
const mem = std.mem;
const Narrow = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 32,
hi: u21 = 10630,
pub fn init(allocator: *mem.Allocator) !Narrow {
var instance = Narrow{
.allocator = allocator,
.array = try allocator.alloc(bool, 10599),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
instance.array[0] = true;
index = 1;
while (index <= 3) : (index += 1) {
instance.array[index] = true;
}
instance.array[4] = true;
index = 5;
while (index <= 7) : (index += 1) {
instance.array[index] = true;
}
instance.array[8] = true;
instance.array[9] = true;
instance.array[10] = true;
instance.array[11] = true;
instance.array[12] = true;
instance.array[13] = true;
index = 14;
while (index <= 15) : (index += 1) {
instance.array[index] = true;
}
index = 16;
while (index <= 25) : (index += 1) {
instance.array[index] = true;
}
index = 26;
while (index <= 27) : (index += 1) {
instance.array[index] = true;
}
index = 28;
while (index <= 30) : (index += 1) {
instance.array[index] = true;
}
index = 31;
while (index <= 32) : (index += 1) {
instance.array[index] = true;
}
index = 33;
while (index <= 58) : (index += 1) {
instance.array[index] = true;
}
instance.array[59] = true;
instance.array[60] = true;
instance.array[61] = true;
instance.array[62] = true;
instance.array[63] = true;
instance.array[64] = true;
index = 65;
while (index <= 90) : (index += 1) {
instance.array[index] = true;
}
instance.array[91] = true;
instance.array[92] = true;
instance.array[93] = true;
instance.array[94] = true;
index = 130;
while (index <= 131) : (index += 1) {
instance.array[index] = true;
}
instance.array[133] = true;
instance.array[134] = true;
instance.array[140] = true;
instance.array[143] = true;
instance.array[10182] = true;
instance.array[10183] = true;
instance.array[10184] = true;
instance.array[10185] = true;
instance.array[10186] = true;
instance.array[10187] = true;
instance.array[10188] = true;
instance.array[10189] = true;
instance.array[10597] = true;
instance.array[10598] = true;
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *Narrow) void {
self.allocator.free(self.array);
}
// isNarrow checks if cp is of the kind Narrow.
pub fn isNarrow(self: Narrow, cp: u21) bool {
if (cp < self.lo or cp > self.hi) return false;
const index = cp - self.lo;
return if (index >= self.array.len) false else self.array[index];
} | src/components/autogen/DerivedEastAsianWidth/Narrow.zig |
const std = @import("std");
const Builder = std.build.Builder;
const builtin = std.builtin;
const assert = std.debug.assert;
// var source_blob: *std.build.RunStep = undefined;
// var source_blob_path: []u8 = undefined;
// fn make_source_blob(b: *Builder) void {
// source_blob_path =
// std.mem.concat(b.allocator, u8,
// &[_][]const u8{ b.cache_root, "/sources.tar" }
// ) catch unreachable;
// source_blob = b.addSystemCommand(
// &[_][]const u8 {
// "tar", "--no-xattrs", "-cf", source_blob_path, "src", "build.zig",
// },
// );
// }
const TransformFileCommandStep = struct {
step: std.build.Step,
output_path: []const u8,
fn run_command(s: *std.build.Step) !void { }
};
fn make_transform(b: *Builder, dep: *std.build.Step, command: [][]const u8, output_path: []const u8) !*TransformFileCommandStep {
const transform = try b.allocator.create(TransformFileCommandStep);
transform.output_path = output_path;
transform.step = std.build.Step.init(.Custom, "", b.allocator, TransformFileCommandStep.run_command);
const command_step = b.addSystemCommand(command);
command_step.step.dependOn(dep);
transform.step.dependOn(&command_step.step);
return transform;
}
fn target(elf: *std.build.LibExeObjStep, arch: builtin.Arch, do_code_model: bool) void {
var disabled_features = std.Target.Cpu.Feature.Set.empty;
var enabled_feautres = std.Target.Cpu.Feature.Set.empty;
if(arch == .aarch64) {
const features = std.Target.aarch64.Feature;
// This is equal to -mgeneral-regs-only
disabled_features.addFeature(@enumToInt(features.fp_armv8));
disabled_features.addFeature(@enumToInt(features.crypto));
disabled_features.addFeature(@enumToInt(features.neon));
// We don't need the code model in asm blobs
if(do_code_model)
elf.code_model = .tiny;
}
elf.setTarget(std.zig.CrossTarget {
.cpu_arch = arch,
.os_tag = std.Target.Os.Tag.freestanding,
.abi = std.Target.Abi.none,
.cpu_features_sub = disabled_features,
.cpu_features_add = enabled_feautres,
});
}
pub fn board_supported(arch: builtin.Arch, target_name: []const u8) bool {
switch(arch) {
.aarch64 => {
if(std.mem.eql(u8, target_name, "virt"))
return true;
if(std.mem.eql(u8, target_name, "pine"))
return true;
return false;
},
else => return false,
}
}
pub fn build_elf(b: *Builder, arch: builtin.Arch, target_name: []const u8, path_prefix: []const u8) !*std.build.LibExeObjStep {
if(!board_supported(arch, target_name)) return error.UnsupportedBoard;
const elf_filename = b.fmt("Sabaton_{s}_{s}.elf", .{target_name, @tagName(arch)});
const platform_path = b.fmt("{s}src/platform/{s}_{s}", .{path_prefix, target_name, @tagName(arch)});
const elf = b.addExecutable(elf_filename, b.fmt("{s}/main.zig", .{platform_path}));
elf.setLinkerScriptPath(b.fmt("{s}/linker.ld", .{platform_path}));
elf.addAssemblyFile(b.fmt("{s}/entry.S", .{platform_path}));
elf.addBuildOption([] const u8, "board_name", target_name);
target(elf, arch, true);
elf.setBuildMode(.ReleaseSmall);
elf.setMainPkgPath(b.fmt("{s}src/", .{path_prefix}));
elf.setOutputDir(b.cache_root);
elf.disable_stack_probing = true;
elf.install();
//elf.step.dependOn(&source_blob.step);
return elf;
}
pub fn pad_file(b: *Builder, dep: *std.build.Step, path: []const u8) !*TransformFileCommandStep {
const padded_path = b.fmt("{s}.pad", .{path});
const pad_step = try make_transform(b, dep,
&[_][]const u8 {
"/bin/sh", "-c",
b.fmt("cp {s} {s} && truncate -s 64M {s}",
.{path, padded_path, padded_path})
},
padded_path,
);
pad_step.step.dependOn(dep);
return pad_step;
}
const pad_mode = enum{Padded, NotPadded};
fn section_blob(b: *Builder, elf: *std.build.LibExeObjStep, mode: pad_mode, section_name: []const u8) !*TransformFileCommandStep {
const dumped_path = b.fmt("{s}.bin", .{elf.getOutputPath()});
const dump_step = try make_transform(b, &elf.step,
&[_][]const u8 {
"llvm-objcopy", "-O", "binary", "--only-section", section_name,
elf.getOutputPath(), dumped_path,
},
dumped_path,
);
dump_step.step.dependOn(&elf.step);
if(mode == .Padded)
return pad_file(b, &dump_step.step, dump_step.output_path);
return dump_step;
}
fn blob(b: *Builder, elf: *std.build.LibExeObjStep, mode: pad_mode) !*TransformFileCommandStep {
return section_blob(b, elf, mode, ".blob");
}
fn assembly_blob(b: *Builder, arch: builtin.Arch, name: []const u8, asm_file: []const u8) !*TransformFileCommandStep {
const elf_filename = b.fmt("{s}_{s}.elf", .{name, @tagName(arch)});
const elf = b.addExecutable(elf_filename, null);
elf.setLinkerScriptPath("src/blob.ld");
elf.addAssemblyFile(asm_file);
target(elf, arch, false);
elf.setBuildMode(.ReleaseSafe);
elf.setMainPkgPath("src/");
elf.setOutputDir(b.cache_root);
elf.install();
return blob(b, elf, .NotPadded);
}
pub fn build_blob(b: *Builder, arch: builtin.Arch, target_name: []const u8, path_prefix: []const u8) !*TransformFileCommandStep {
const elf = try build_elf(b, arch, target_name, path_prefix);
return blob(b, elf, .Padded);
}
fn qemu_aarch64(b: *Builder, board_name: []const u8, desc: []const u8, dep_elf: *std.build.LibExeObjStep) !void {
const command_step = b.step(board_name, desc);
const dep = try blob(b, dep_elf, .Padded);
const params =
&[_][]const u8 {
"qemu-system-aarch64",
"-M", board_name,
"-cpu", "cortex-a57",
"-drive", b.fmt("if=pflash,format=raw,file={s},readonly=on", .{dep.output_path}),
"-m", "4G",
"-serial", "stdio",
//"-S", "-s",
"-d", "int",
"-smp", "8",
"-device", "ramfb",
"-fw_cfg", "opt/Sabaton/kernel,file=test/Flork_stivale2_aarch64",
};
const run_step = b.addSystemCommand(params);
run_step.step.dependOn(&dep.step);
command_step.dependOn(&run_step.step);
}
const Device = struct {
name: []const u8,
arch: builtin.Arch,
};
const AssemblyBlobSpec = struct {
name: []const u8,
arch: builtin.Arch,
path: []const u8,
};
pub fn build(b: *Builder) !void {
//make_source_blob(b);
try qemu_aarch64(b,
"virt",
"Run aarch64 sabaton on for the qemu virt board",
try build_elf(b, builtin.Arch.aarch64, "virt", "./"),
);
{
const assembly_blobs = &[_]AssemblyBlobSpec {
.{.path = "src/platform/pine_aarch64/identity.S", .name = "identity_pine", .arch = .aarch64},
};
for(assembly_blobs) |spec| {
const blob_file = try assembly_blob(b, spec.arch, spec.name, spec.path);
b.default_step.dependOn(&blob_file.step);
}
}
{
const elf_devices = &[_]Device{
};
for(elf_devices) |dev| {
const elf_file = try build_elf(b, builtin.Arch.aarch64, dev.name);
const s = b.step(dev.name, b.fmt("Build the blob for {s}", .{dev.name}));
s.dependOn(&elf_file.step);
b.default_step.dependOn(s);
}
}
{
const blob_devices = &[_]Device{
.{.name = "pine", .arch = builtin.Arch.aarch64},
};
for(blob_devices) |dev| {
const elf_file = try build_elf(b, builtin.Arch.aarch64, dev.name, "./");
const blob_file = try blob(b, elf_file, .NotPadded);
const s = b.step(dev.name, b.fmt("Build the blob for {s}", .{dev.name}));
s.dependOn(&blob_file.step);
b.default_step.dependOn(s);
}
}
// qemu_riscv(b,
// "virt",
// "Run riscv64 sabaton on for the qemu virt board",
// build_elf(b, builtin.Arch.riscv64, "virt"),
// );
} | build.zig |
const std = @import("std");
const math = std.math;
const glfw = @import("glfw");
const zgpu = @import("zgpu");
const gpu = zgpu.gpu;
const c = zgpu.cimgui;
const zm = @import("zmath");
const content_dir = @import("build_options").content_dir;
const window_title = "zig-gamedev: textured quad (wgpu)";
// zig fmt: off
const wgsl_common =
\\ struct Uniforms {
\\ aspect_ratio: f32,
\\ mip_level: f32,
\\ }
\\ @group(0) @binding(0) var<uniform> uniforms: Uniforms;
;
const wgsl_vs = wgsl_common ++
\\ struct VertexOut {
\\ @builtin(position) position_clip: vec4<f32>,
\\ @location(0) uv: vec2<f32>,
\\ }
\\ @stage(vertex) fn main(
\\ @location(0) position: vec2<f32>,
\\ @location(1) uv: vec2<f32>,
\\ ) -> VertexOut {
\\ let p = vec2(position.x / uniforms.aspect_ratio, position.y);
\\ var output: VertexOut;
\\ output.position_clip = vec4(p, 0.0, 1.0);
\\ output.uv = uv;
\\ return output;
\\ }
;
const wgsl_fs = wgsl_common ++
\\ @group(0) @binding(1) var image: texture_2d<f32>;
\\ @group(0) @binding(2) var image_sampler: sampler;
\\ @stage(fragment) fn main(
\\ @location(0) uv: vec2<f32>,
\\ ) -> @location(0) vec4<f32> {
\\ return textureSampleLevel(image, image_sampler, uv, uniforms.mip_level);
\\ }
// zig fmt: on
;
const Vertex = struct {
position: [2]f32,
uv: [2]f32,
};
const Uniforms = struct {
aspect_ratio: f32,
mip_level: f32,
};
const DemoState = struct {
gctx: *zgpu.GraphicsContext,
pipeline: zgpu.RenderPipelineHandle = .{},
bind_group: zgpu.BindGroupHandle,
vertex_buffer: zgpu.BufferHandle,
index_buffer: zgpu.BufferHandle,
texture: zgpu.TextureHandle,
texture_view: zgpu.TextureViewHandle,
sampler: zgpu.SamplerHandle,
mip_level: i32 = 0,
};
fn init(allocator: std.mem.Allocator, window: glfw.Window) !*DemoState {
const gctx = try zgpu.GraphicsContext.init(allocator, window);
var arena_state = std.heap.ArenaAllocator.init(allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const bind_group_layout = gctx.createBindGroupLayout(&.{
zgpu.bglBuffer(0, .{ .vertex = true, .fragment = true }, .uniform, true, 0),
zgpu.bglTexture(1, .{ .fragment = true }, .float, .dimension_2d, false),
zgpu.bglSampler(2, .{ .fragment = true }, .filtering),
});
defer gctx.destroyResource(bind_group_layout);
// Create a vertex buffer.
const vertex_data = [_]Vertex{
.{ .position = [2]f32{ -0.9, 0.9 }, .uv = [2]f32{ 0.0, 0.0 } },
.{ .position = [2]f32{ 0.9, 0.9 }, .uv = [2]f32{ 1.0, 0.0 } },
.{ .position = [2]f32{ 0.9, -0.9 }, .uv = [2]f32{ 1.0, 1.0 } },
.{ .position = [2]f32{ -0.9, -0.9 }, .uv = [2]f32{ 0.0, 1.0 } },
};
const vertex_buffer = gctx.createBuffer(.{
.usage = .{ .copy_dst = true, .vertex = true },
.size = vertex_data.len * @sizeOf(Vertex),
});
gctx.queue.writeBuffer(gctx.lookupResource(vertex_buffer).?, 0, Vertex, vertex_data[0..]);
// Create an index buffer.
const index_data = [_]u16{ 0, 1, 3, 1, 2, 3 };
const index_buffer = gctx.createBuffer(.{
.usage = .{ .copy_dst = true, .index = true },
.size = index_data.len * @sizeOf(u16),
});
gctx.queue.writeBuffer(gctx.lookupResource(index_buffer).?, 0, u16, index_data[0..]);
// Create a texture.
var image = try zgpu.stbi.Image.init(content_dir ++ "genart_0025_5.png", 4);
defer image.deinit();
const texture = gctx.createTexture(.{
.usage = .{ .texture_binding = true, .copy_dst = true },
.size = .{
.width = image.width,
.height = image.height,
.depth_or_array_layers = 1,
},
.format = .rgba8_unorm,
.mip_level_count = math.log2_int(u32, math.max(image.width, image.height)) + 1,
});
const texture_view = gctx.createTextureView(texture, .{});
gctx.queue.writeTexture(
&.{ .texture = gctx.lookupResource(texture).? },
image.data,
&.{
.bytes_per_row = image.width * image.channels_in_memory,
.rows_per_image = image.height,
},
&.{ .width = image.width, .height = image.height },
);
// Create a sampler.
const sampler = gctx.createSampler(.{});
const bind_group = gctx.createBindGroup(bind_group_layout, &[_]zgpu.BindGroupEntryInfo{
.{ .binding = 0, .buffer_handle = gctx.uniforms.buffer, .offset = 0, .size = 256 },
.{ .binding = 1, .texture_view_handle = texture_view },
.{ .binding = 2, .sampler_handle = sampler },
});
const demo = try allocator.create(DemoState);
demo.* = .{
.gctx = gctx,
.bind_group = bind_group,
.vertex_buffer = vertex_buffer,
.index_buffer = index_buffer,
.texture = texture,
.texture_view = texture_view,
.sampler = sampler,
};
// Generate mipmaps on the GPU.
{
const commands = commands: {
const encoder = gctx.device.createCommandEncoder(null);
defer encoder.release();
gctx.generateMipmaps(arena, encoder, demo.texture);
break :commands encoder.finish(null);
};
defer commands.release();
gctx.submit(&.{commands});
}
// (Async) Create a render pipeline.
{
const pipeline_layout = gctx.createPipelineLayout(&.{
bind_group_layout,
});
defer gctx.destroyResource(pipeline_layout);
const vs_module = gctx.device.createShaderModule(&.{ .label = "vs", .code = .{ .wgsl = wgsl_vs } });
defer vs_module.release();
const fs_module = gctx.device.createShaderModule(&.{ .label = "fs", .code = .{ .wgsl = wgsl_fs } });
defer fs_module.release();
const color_target = gpu.ColorTargetState{
.format = zgpu.GraphicsContext.swapchain_format,
.blend = &.{ .color = .{}, .alpha = .{} },
};
const vertex_attributes = [_]gpu.VertexAttribute{
.{ .format = .float32x2, .offset = 0, .shader_location = 0 },
.{ .format = .float32x2, .offset = @offsetOf(Vertex, "uv"), .shader_location = 1 },
};
const vertex_buffer_layout = gpu.VertexBufferLayout{
.array_stride = @sizeOf(Vertex),
.attribute_count = vertex_attributes.len,
.attributes = &vertex_attributes,
};
// Create a render pipeline.
const pipeline_descriptor = gpu.RenderPipeline.Descriptor{
.vertex = gpu.VertexState{
.module = vs_module,
.entry_point = "main",
.buffers = &.{vertex_buffer_layout},
},
.primitive = gpu.PrimitiveState{
.front_face = .cw,
.cull_mode = .back,
.topology = .triangle_list,
},
.fragment = &gpu.FragmentState{
.module = fs_module,
.entry_point = "main",
.targets = &.{color_target},
},
};
gctx.createRenderPipelineAsync(allocator, pipeline_layout, pipeline_descriptor, &demo.pipeline);
}
return demo;
}
fn deinit(allocator: std.mem.Allocator, demo: *DemoState) void {
demo.gctx.deinit(allocator);
allocator.destroy(demo);
}
fn update(demo: *DemoState) void {
zgpu.gui.newFrame(demo.gctx.swapchain_descriptor.width, demo.gctx.swapchain_descriptor.height);
if (c.igBegin("Demo Settings", null, c.ImGuiWindowFlags_NoMove | c.ImGuiWindowFlags_NoResize)) {
c.igBulletText(
"Average : %.3f ms/frame (%.1f fps)",
demo.gctx.stats.average_cpu_time,
demo.gctx.stats.fps,
);
_ = c.igSliderInt(
"Mipmap Level",
&demo.mip_level,
0,
@intCast(i32, demo.gctx.lookupResourceInfo(demo.texture).?.mip_level_count - 1),
null,
c.ImGuiSliderFlags_None,
);
}
c.igEnd();
}
fn draw(demo: *DemoState) void {
const gctx = demo.gctx;
const fb_width = gctx.swapchain_descriptor.width;
const fb_height = gctx.swapchain_descriptor.height;
const back_buffer_view = gctx.swapchain.getCurrentTextureView();
defer back_buffer_view.release();
const commands = commands: {
const encoder = gctx.device.createCommandEncoder(null);
defer encoder.release();
// Main pass.
pass: {
const vb_info = gctx.lookupResourceInfo(demo.vertex_buffer) orelse break :pass;
const ib_info = gctx.lookupResourceInfo(demo.index_buffer) orelse break :pass;
const pipeline = gctx.lookupResource(demo.pipeline) orelse break :pass;
const bind_group = gctx.lookupResource(demo.bind_group) orelse break :pass;
const color_attachment = gpu.RenderPassColorAttachment{
.view = back_buffer_view,
.load_op = .clear,
.store_op = .store,
};
const render_pass_info = gpu.RenderPassEncoder.Descriptor{
.color_attachments = &.{color_attachment},
};
const pass = encoder.beginRenderPass(&render_pass_info);
defer {
pass.end();
pass.release();
}
pass.setVertexBuffer(0, vb_info.gpuobj.?, 0, vb_info.size);
pass.setIndexBuffer(ib_info.gpuobj.?, .uint16, 0, ib_info.size);
pass.setPipeline(pipeline);
const mem = gctx.uniformsAllocate(Uniforms, 1);
mem.slice[0] = .{
.aspect_ratio = @intToFloat(f32, fb_width) / @intToFloat(f32, fb_height),
.mip_level = @intToFloat(f32, demo.mip_level),
};
pass.setBindGroup(0, bind_group, &.{mem.offset});
pass.drawIndexed(6, 1, 0, 0, 0);
}
// Gui pass.
{
const color_attachment = gpu.RenderPassColorAttachment{
.view = back_buffer_view,
.load_op = .load,
.store_op = .store,
};
const render_pass_info = gpu.RenderPassEncoder.Descriptor{
.color_attachments = &.{color_attachment},
};
const pass = encoder.beginRenderPass(&render_pass_info);
defer {
pass.end();
pass.release();
}
zgpu.gui.draw(pass);
}
break :commands encoder.finish(null);
};
defer commands.release();
gctx.submit(&.{commands});
_ = gctx.present();
}
pub fn main() !void {
zgpu.checkContent(content_dir) catch {
// In case of error zgpu.checkContent() will print error message.
return;
};
try glfw.init(.{});
defer glfw.terminate();
const window = try glfw.Window.create(1280, 960, window_title, null, null, .{
.client_api = .no_api,
.cocoa_retina_framebuffer = true,
});
defer window.destroy();
try window.setSizeLimits(.{ .width = 400, .height = 400 }, .{ .width = null, .height = null });
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const demo = try init(allocator, window);
defer deinit(allocator, demo);
zgpu.gui.init(window, demo.gctx.device, content_dir, "Roboto-Medium.ttf", 25.0);
defer zgpu.gui.deinit();
while (!window.shouldClose()) {
try glfw.pollEvents();
update(demo);
draw(demo);
}
} | samples/textured_quad_wgpu/src/textured_quad_wgpu.zig |
const tty = @import("tty.zig");
const x86 = @import("x86.zig");
// GDT segment selectors.
pub const KERNEL_CODE = 0x08;
pub const KERNEL_DATA = 0x10;
pub const USER_CODE = 0x18;
pub const USER_DATA = 0x20;
pub const TSS_DESC = 0x28;
// Privilege level of segment selector.
pub const KERNEL_RPL = 0b00;
pub const USER_RPL = 0b11;
// Access byte values.
const KERNEL = 0x90;
const USER = 0xF0;
const CODE = 0x0A;
const DATA = 0x02;
const TSS_ACCESS = 0x89;
// Segment flags.
const PROTECTED = (1 << 2);
const BLOCKS_4K = (1 << 3);
// Structure representing an entry in the GDT.
const GDTEntry = packed struct {
limit_low: u16,
base_low: u16,
base_mid: u8,
access: u8,
limit_high: u4,
flags: u4,
base_high: u8,
};
// GDT descriptor register.
const GDTRegister = packed struct {
limit: u16,
base: &const GDTEntry,
};
// Task State Segment.
const TSS = packed struct {
unused1: u32,
esp0: u32, // Stack to use when coming to ring 0 from ring > 0.
ss0: u32, // Segment to use when coming to ring 0 from ring > 0.
unused2: [22]u32,
unused3: u16,
iomap_base: u16, // Base of the IO bitmap.
};
////
// Generate a GDT entry structure.
//
// Arguments:
// base: Beginning of the segment.
// limit: Size of the segment.
// access: Access byte.
// flags: Segment flags.
//
fn makeEntry(base: usize, limit: usize, access: u8, flags: u4) GDTEntry {
return GDTEntry { .limit_low = u16( limit & 0xFFFF),
.base_low = u16( base & 0xFFFF),
.base_mid = u8((base >> 16) & 0xFF ),
.access = u8( access ),
.limit_high = u4((limit >> 16) & 0xF ),
.flags = u4( flags ),
.base_high = u8((base >> 24) & 0xFF ), };
}
// Fill in the GDT.
var gdt align(4) = []GDTEntry {
makeEntry(0, 0, 0, 0),
makeEntry(0, 0xFFFFF, KERNEL | CODE, PROTECTED | BLOCKS_4K),
makeEntry(0, 0xFFFFF, KERNEL | DATA, PROTECTED | BLOCKS_4K),
makeEntry(0, 0xFFFFF, USER | CODE, PROTECTED | BLOCKS_4K),
makeEntry(0, 0xFFFFF, USER | DATA, PROTECTED | BLOCKS_4K),
makeEntry(0, 0, 0, 0), // TSS (fill in at runtime).
};
// GDT descriptor register pointing at the GDT.
var gdtr = GDTRegister {
.limit = u16(@sizeOf(@typeOf(gdt))),
.base = &gdt[0],
};
// Instance of the Task State Segment.
var tss = TSS {
.unused1 = 0,
.esp0 = undefined,
.ss0 = KERNEL_DATA,
.unused2 = []u32 { 0 } ** 22,
.unused3 = 0,
.iomap_base = @sizeOf(TSS),
};
////
// Set the kernel stack to use when interrupting user mode.
//
// Arguments:
// esp0: Stack for Ring 0.
//
pub fn setKernelStack(esp0: usize) void {
tss.esp0 = esp0;
}
////
// Load the GDT into the system registers (defined in assembly).
//
// Arguments:
// gdtr: Pointer to the GDTR.
//
extern fn loadGDT(gdtr: &const GDTRegister)void;
////
// Initialize the Global Descriptor Table.
//
pub fn initialize() void {
tty.step("Setting up the Global Descriptor Table");
// Initialize GDT.
loadGDT(&gdtr);
// Initialize TSS.
const tss_entry = makeEntry(@ptrToInt(&tss), @sizeOf(TSS) - 1, TSS_ACCESS, PROTECTED);
gdt[TSS_DESC / @sizeOf(GDTEntry)] = tss_entry;
x86.ltr(TSS_DESC);
tty.stepOK();
} | kernel/gdt.zig |
const xcb = @import("../xcb.zig");
pub const id = xcb.Extension{ .name = "MIT-SCREEN-SAVER", .global_id = 0 };
pub const Kind = extern enum(c_uint) {
@"Blanked" = 0,
@"Internal" = 1,
@"External" = 2,
};
pub const Event = extern enum(c_uint) {
@"NotifyMask" = 1,
@"CycleMask" = 2,
};
pub const State = extern enum(c_uint) {
@"Off" = 0,
@"On" = 1,
@"Cycle" = 2,
@"Disabled" = 3,
};
/// @brief QueryVersioncookie
pub const QueryVersioncookie = struct {
sequence: c_uint,
};
/// @brief QueryVersionRequest
pub const QueryVersionRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 0,
@"length": u16,
@"client_major_version": u8,
@"client_minor_version": u8,
@"pad0": [2]u8,
};
/// @brief QueryVersionReply
pub const QueryVersionReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"server_major_version": u16,
@"server_minor_version": u16,
@"pad1": [20]u8,
};
/// @brief QueryInfocookie
pub const QueryInfocookie = struct {
sequence: c_uint,
};
/// @brief QueryInfoRequest
pub const QueryInfoRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 1,
@"length": u16,
@"drawable": xcb.DRAWABLE,
};
/// @brief QueryInfoReply
pub const QueryInfoReply = struct {
@"response_type": u8,
@"state": u8,
@"sequence": u16,
@"length": u32,
@"saver_window": xcb.WINDOW,
@"ms_until_server": u32,
@"ms_since_user_input": u32,
@"event_mask": u32,
@"kind": u8,
@"pad0": [7]u8,
};
/// @brief SelectInputRequest
pub const SelectInputRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 2,
@"length": u16,
@"drawable": xcb.DRAWABLE,
@"event_mask": u32,
};
/// @brief SetAttributesRequest
pub const SetAttributesRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 3,
@"length": u16,
@"drawable": xcb.DRAWABLE,
@"x": i16,
@"y": i16,
@"width": u16,
@"height": u16,
@"border_width": u16,
@"class": u8,
@"depth": u8,
@"visual": xcb.VISUALID,
@"value_mask": u32,
};
/// @brief UnsetAttributesRequest
pub const UnsetAttributesRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 4,
@"length": u16,
@"drawable": xcb.DRAWABLE,
};
/// @brief SuspendRequest
pub const SuspendRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 5,
@"length": u16,
@"suspend": u8,
@"pad0": [3]u8,
};
/// Opcode for Notify.
pub const NotifyOpcode = 0;
/// @brief NotifyEvent
pub const NotifyEvent = struct {
@"response_type": u8,
@"state": u8,
@"sequence": u16,
@"time": xcb.TIMESTAMP,
@"root": xcb.WINDOW,
@"window": xcb.WINDOW,
@"kind": u8,
@"forced": u8,
@"pad0": [14]u8,
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/auto/screensaver.zig |
const std = @import("std");
const Builder = std.build.Builder;
const builtin = std.builtin;
const assert = std.debug.assert;
const sabaton = @import("boot/Sabaton/build.zig");
const Context = enum {
kernel,
blobspace,
userspace,
};
var source_blob: *std.build.RunStep = undefined;
var source_blob_path: []u8 = undefined;
fn make_source_blob(b: *Builder) void {
source_blob_path = b.fmt("{s}/sources.tar", .{b.cache_root});
source_blob = b.addSystemCommand(
&[_][]const u8{
"tar", "--no-xattrs", "-cf", source_blob_path, "src", "build.zig",
},
);
}
fn target(exec: *std.build.LibExeObjStep, arch: builtin.Arch, context: Context) void {
var disabled_features = std.Target.Cpu.Feature.Set.empty;
var enabled_feautres = std.Target.Cpu.Feature.Set.empty;
switch (arch) {
.x86_64 => {
const features = std.Target.x86.Feature;
if (context == .kernel) {
// Disable SIMD registers
disabled_features.addFeature(@enumToInt(features.mmx));
disabled_features.addFeature(@enumToInt(features.sse));
disabled_features.addFeature(@enumToInt(features.sse2));
disabled_features.addFeature(@enumToInt(features.avx));
disabled_features.addFeature(@enumToInt(features.avx2));
enabled_feautres.addFeature(@enumToInt(features.soft_float));
exec.code_model = .kernel;
} else {
exec.code_model = .small;
}
},
.aarch64 => {
const features = std.Target.aarch64.Feature;
if (context == .kernel) {
// This is equal to -mgeneral-regs-only
disabled_features.addFeature(@enumToInt(features.fp_armv8));
disabled_features.addFeature(@enumToInt(features.crypto));
disabled_features.addFeature(@enumToInt(features.neon));
}
exec.code_model = .small;
},
.riscv64 => {
// idfk
exec.code_model = .small;
},
else => unreachable,
}
exec.disable_stack_probing = switch (context) {
.kernel => true,
.blobspace => true,
else => false,
};
exec.setTarget(.{
.cpu_arch = arch,
.os_tag = std.Target.Os.Tag.freestanding,
.abi = std.Target.Abi.none,
.cpu_features_sub = disabled_features,
.cpu_features_add = enabled_feautres,
});
}
fn add_libs(exec: *std.build.LibExeObjStep) void {
}
fn make_exec(b: *Builder, arch: builtin.Arch, ctx: Context, filename: []const u8, main: []const u8) *std.build.LibExeObjStep {
const exec = b.addExecutable(filename, main);
exec.addBuildOption([]const u8, "source_blob_path", b.fmt("../../{s}", .{source_blob_path}));
target(exec, arch, ctx);
add_libs(exec);
exec.setBuildMode(.ReleaseSafe);
exec.strip = false;
exec.setMainPkgPath("src/");
exec.setOutputDir(b.cache_root);
exec.install();
exec.step.dependOn(&source_blob.step);
return exec;
}
fn build_kernel(b: *Builder, arch: builtin.Arch, name: []const u8) *std.build.LibExeObjStep {
const kernel_filename = b.fmt("Flork_{s}_{s}", .{ name, @tagName(arch) });
const main_file = b.fmt("src/boot/{s}.zig", .{name});
const kernel = make_exec(b, arch, .kernel, kernel_filename, main_file);
kernel.addAssemblyFile(b.fmt("src/boot/{s}_{s}.S", .{ name, @tagName(arch) }));
kernel.setLinkerScriptPath("src/kernel/kernel.ld");
const laipath = "src/extern/lai/";
kernel.addIncludeDir(laipath ++ "include/");
const laiflags = &[_][]const u8{"-std=c99"};
kernel.addCSourceFile(laipath ++ "core/error.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/eval.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/exec-operand.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/exec.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/libc.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/ns.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/object.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/opregion.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/os_methods.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/variable.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/vsnprintf.c", laiflags);
kernel.addCSourceFile(laipath ++ "drivers/ec.c", laiflags);
kernel.addCSourceFile(laipath ++ "drivers/timer.c", laiflags);
if(arch == .x86_64)
kernel.addCSourceFile(laipath ++ "helpers/pc-bios.c", laiflags);
kernel.addCSourceFile(laipath ++ "helpers/pci.c", laiflags);
kernel.addCSourceFile(laipath ++ "helpers/pm.c", laiflags);
kernel.addCSourceFile(laipath ++ "helpers/resource.c", laiflags);
kernel.addCSourceFile(laipath ++ "helpers/sci.c", laiflags);
//kernel.step.dependOn(&build_dyld(b, arch).step);
return kernel;
}
fn build_dyld(b: *Builder, arch: builtin.Arch) *std.build.LibExeObjStep {
const dyld_filename = b.fmt("Dyld_", .{@tagName(arch)});
const dyld = make_exec(b, arch, .blobspace, dyld_filename, "src/userspace/dyld/dyld.zig");
dyld.setLinkerScriptPath("src/userspace/dyld/dyld.ld");
return dyld;
}
fn qemu_run_aarch64_sabaton(b: *Builder, board_name: []const u8, desc: []const u8) !void {
const sabaton_blob = try sabaton.build_blob(b, .aarch64, board_name, "boot/Sabaton/");
const flork = build_kernel(b, .aarch64, "stivale2");
const command_step = b.step(board_name, desc);
const params = &[_][]const u8 {
"qemu-system-aarch64",
"-M", board_name,
"-cpu", "cortex-a57",
"-drive", b.fmt("if=pflash,format=raw,file={s},readonly=on", .{sabaton_blob.output_path}),
"-fw_cfg", b.fmt("opt/Sabaton/kernel,file={s}", .{flork.getOutputPath()}),
"-m", "4G",
"-serial", "stdio",
//"-S", "-s",
"-smp", "4",
"-device", "virtio-gpu-pci",
"-device", "ramfb",
"-display", "gtk,zoom-to-fit=off",
};
const run_step = b.addSystemCommand(params);
run_step.step.dependOn(&sabaton_blob.step);
run_step.step.dependOn(&flork.step);
command_step.dependOn(&run_step.step);
}
fn qemu_run_riscv_sabaton(b: *Builder, board_name: []const u8, desc: []const u8, dep: *std.build.LibExeObjStep) void {
const command_step = b.step(board_name, desc);
const params = &[_][]const u8{
"qemu-system-riscv64",
"-M", board_name,
"-cpu", "rv64",
"-drive", b.fmt("if=pflash,format=raw,file=Sabaton/out/riscv64_{s}.bin,readonly=on", .{board_name}),
"-drive", b.fmt("if=pflash,format=raw,file={s},readonly=on", .{dep.getOutputPath()}),
"-m", "4G",
"-serial", "stdio",
//"-S", "-s",
"-d", "int",
"-smp", "4",
"-device", "virtio-gpu-pci",
};
const pad_step = b.addSystemCommand(
&[_][]const u8{
"truncate", "-s", "64M", dep.getOutputPath(),
},
);
const run_step = b.addSystemCommand(params);
pad_step.step.dependOn(&dep.step);
run_step.step.dependOn(&pad_step.step);
command_step.dependOn(&run_step.step);
}
fn qemu_run_image_x86_64(b: *Builder, image_path: []const u8) *std.build.RunStep {
const run_params = &[_][]const u8{
"qemu-system-x86_64",
"-drive", b.fmt("format=raw,file={s}", .{image_path}),
"-debugcon", "stdio",
"-vga", "virtio",
//"-serial", "stdio",
"-m", "4G",
"-display", "gtk,zoom-to-fit=off",
"-no-reboot",
"-no-shutdown",
"-machine", "q35",
"-device", "qemu-xhci",
"-smp", "8",
"-cpu", "host", "-enable-kvm",
//"-d", "int",
//"-s", "-S",
//"-trace", "ahci_*",
};
return b.addSystemCommand(run_params);
}
fn echfs_image(b: *Builder, image_path: []const u8, kernel_path: []const u8, install_command: []const u8) *std.build.RunStep {
const image_params = &[_][]const u8{
"/bin/sh", "-c",
std.mem.concat(b.allocator, u8, &[_][]const u8{
"make -C boot/echfs && ",
"rm ", image_path, " || true && ",
"dd if=/dev/zero bs=1048576 count=0 seek=8 of=", image_path, " && ",
"parted -s ", image_path, " mklabel msdos && ",
"parted -s ", image_path, " mkpart primary 1 100% && ",
"parted -s ", image_path, " set 1 boot on && ",
"./boot/echfs/echfs-utils -m -p0 ", image_path, " quick-format 32768 && ",
"./boot/echfs/echfs-utils -m -p0 ", image_path, " import '", kernel_path, "' flork.elf && ",
install_command,
}) catch unreachable,
};
return b.addSystemCommand(image_params);
}
fn limine_target(b: *Builder, command: []const u8, desc: []const u8, image_path: []const u8, root_path: []const u8, dep: *std.build.LibExeObjStep) void {
assert(dep.target.cpu_arch.? == .x86_64);
const command_step = b.step(command, desc);
const run_step = qemu_run_image_x86_64(b, image_path);
const image_step = echfs_image(b, image_path, dep.getOutputPath(), std.mem.concat(b.allocator, u8, &[_][]const u8{
"make -C boot/limine limine-install && ",
"make -C boot/echfs && ",
"./boot/echfs/echfs-utils -m -p0 ", image_path, " import ", root_path, "/limine.cfg limine.cfg && ",
"./boot/limine/limine-install ",
image_path,
}) catch unreachable);
image_step.step.dependOn(&dep.step);
run_step.step.dependOn(&image_step.step);
command_step.dependOn(&run_step.step);
}
pub fn build(b: *Builder) !void {
const sources = make_source_blob(b);
// try qemu_run_aarch64_sabaton(
// b,
// "raspi3",
// "(WIP) Run aarch64 kernel with Sabaton stivale2 on the raspi3 board",
// );
try qemu_run_aarch64_sabaton(
b,
"virt",
"Run aarch64 kernel with Sabaton stivale2 on the virt board",
);
// qemu_run_riscv_sabaton(b,
// "riscv-virt",
// "(WIP) Run risc-v kernel with Sabaton stivale2 on the virt board",
// build_kernel(b, builtin.Arch.riscv64, "stivale2"),
// );
limine_target(
b,
"x86_64-stivale2",
"Run x86_64 kernel with limine stivale2",
b.fmt("{s}/stivale2.img", .{b.cache_root}),
"boot/stivale2_image",
build_kernel(b, builtin.Arch.x86_64, "stivale2"),
);
} | build.zig |
const std = @import("std");
const mem = std.mem;
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const ir = @import("ir.zig");
const Module = @import("Module.zig");
const fs = std.fs;
const elf = std.elf;
const codegen = @import("codegen.zig");
const default_entry_addr = 0x8000000;
pub const Options = struct {
target: std.Target,
output_mode: std.builtin.OutputMode,
link_mode: std.builtin.LinkMode,
object_format: std.builtin.ObjectFormat,
/// Used for calculating how much space to reserve for symbols in case the binary file
/// does not already have a symbol table.
symbol_count_hint: u64 = 32,
/// Used for calculating how much space to reserve for executable program code in case
/// the binary file deos not already have such a section.
program_code_size_hint: u64 = 256 * 1024,
};
/// Attempts incremental linking, if the file already exists.
/// If incremental linking fails, falls back to truncating the file and rewriting it.
/// A malicious file is detected as incremental link failure and does not cause Illegal Behavior.
/// This operation is not atomic.
pub fn openBinFilePath(
allocator: *Allocator,
dir: fs.Dir,
sub_path: []const u8,
options: Options,
) !ElfFile {
const file = try dir.createFile(sub_path, .{ .truncate = false, .read = true, .mode = determineMode(options) });
errdefer file.close();
var bin_file = try openBinFile(allocator, file, options);
bin_file.owns_file_handle = true;
return bin_file;
}
/// Atomically overwrites the old file, if present.
pub fn writeFilePath(
allocator: *Allocator,
dir: fs.Dir,
sub_path: []const u8,
module: Module,
errors: *std.ArrayList(Module.ErrorMsg),
) !void {
const options: Options = .{
.target = module.target,
.output_mode = module.output_mode,
.link_mode = module.link_mode,
.object_format = module.object_format,
.symbol_count_hint = module.decls.items.len,
};
const af = try dir.atomicFile(sub_path, .{ .mode = determineMode(options) });
defer af.deinit();
const elf_file = try createElfFile(allocator, af.file, options);
for (module.decls.items) |decl| {
try elf_file.updateDecl(module, decl, errors);
}
try elf_file.flush();
if (elf_file.error_flags.no_entry_point_found) {
try errors.ensureCapacity(errors.items.len + 1);
errors.appendAssumeCapacity(.{
.byte_offset = 0,
.msg = try std.fmt.allocPrint(errors.allocator, "no entry point found", .{}),
});
}
try af.finish();
return result;
}
/// Attempts incremental linking, if the file already exists.
/// If incremental linking fails, falls back to truncating the file and rewriting it.
/// Returns an error if `file` is not already open with +read +write +seek abilities.
/// A malicious file is detected as incremental link failure and does not cause Illegal Behavior.
/// This operation is not atomic.
pub fn openBinFile(allocator: *Allocator, file: fs.File, options: Options) !ElfFile {
return openBinFileInner(allocator, file, options) catch |err| switch (err) {
error.IncrFailed => {
return createElfFile(allocator, file, options);
},
else => |e| return e,
};
}
pub const ElfFile = struct {
allocator: *Allocator,
file: ?fs.File,
owns_file_handle: bool,
options: Options,
ptr_width: enum { p32, p64 },
/// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write.
/// Same order as in the file.
sections: std.ArrayListUnmanaged(elf.Elf64_Shdr) = std.ArrayListUnmanaged(elf.Elf64_Shdr){},
shdr_table_offset: ?u64 = null,
/// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write.
/// Same order as in the file.
program_headers: std.ArrayListUnmanaged(elf.Elf64_Phdr) = std.ArrayListUnmanaged(elf.Elf64_Phdr){},
phdr_table_offset: ?u64 = null,
/// The index into the program headers of a PT_LOAD program header with Read and Execute flags
phdr_load_re_index: ?u16 = null,
/// The index into the program headers of the global offset table.
/// It needs PT_LOAD and Read flags.
phdr_got_index: ?u16 = null,
entry_addr: ?u64 = null,
shstrtab: std.ArrayListUnmanaged(u8) = std.ArrayListUnmanaged(u8){},
shstrtab_index: ?u16 = null,
text_section_index: ?u16 = null,
symtab_section_index: ?u16 = null,
got_section_index: ?u16 = null,
/// The same order as in the file. ELF requires global symbols to all be after the
/// local symbols, they cannot be mixed. So we must buffer all the global symbols and
/// write them at the end. These are only the local symbols. The length of this array
/// is the value used for sh_info in the .symtab section.
local_symbols: std.ArrayListUnmanaged(elf.Elf64_Sym) = std.ArrayListUnmanaged(elf.Elf64_Sym){},
global_symbols: std.ArrayListUnmanaged(elf.Elf64_Sym) = std.ArrayListUnmanaged(elf.Elf64_Sym){},
/// Same order as in the file. The value is the absolute vaddr value.
/// If the vaddr of the executable program header changes, the entire
/// offset table needs to be rewritten.
offset_table: std.ArrayListUnmanaged(u64) = std.ArrayListUnmanaged(u64){},
phdr_table_dirty: bool = false,
shdr_table_dirty: bool = false,
shstrtab_dirty: bool = false,
offset_table_count_dirty: bool = false,
error_flags: ErrorFlags = ErrorFlags{},
pub const ErrorFlags = struct {
no_entry_point_found: bool = false,
};
pub const Decl = struct {
/// Each decl always gets a local symbol with the fully qualified name.
/// The vaddr and size are found here directly.
/// The file offset is found by computing the vaddr offset from the section vaddr
/// the symbol references, and adding that to the file offset of the section.
/// If this field is 0, it means the codegen size = 0 and there is no symbol or
/// offset table entry.
local_sym_index: u32,
/// This field is undefined for symbols with size = 0.
offset_table_index: u32,
pub const empty = Decl{
.local_sym_index = 0,
.offset_table_index = undefined,
};
};
pub const Export = struct {
sym_index: ?u32 = null,
};
pub fn deinit(self: *ElfFile) void {
self.sections.deinit(self.allocator);
self.program_headers.deinit(self.allocator);
self.shstrtab.deinit(self.allocator);
self.local_symbols.deinit(self.allocator);
self.global_symbols.deinit(self.allocator);
self.offset_table.deinit(self.allocator);
if (self.owns_file_handle) {
if (self.file) |f| f.close();
}
}
pub fn makeExecutable(self: *ElfFile) !void {
assert(self.owns_file_handle);
if (self.file) |f| {
f.close();
self.file = null;
}
}
pub fn makeWritable(self: *ElfFile, dir: fs.Dir, sub_path: []const u8) !void {
assert(self.owns_file_handle);
if (self.file != null) return;
self.file = try dir.createFile(sub_path, .{
.truncate = false,
.read = true,
.mode = determineMode(self.options),
});
}
// `alloc_num / alloc_den` is the factor of padding when allocation
const alloc_num = 4;
const alloc_den = 3;
/// Returns end pos of collision, if any.
fn detectAllocCollision(self: *ElfFile, start: u64, size: u64) ?u64 {
const small_ptr = self.options.target.cpu.arch.ptrBitWidth() == 32;
const ehdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Ehdr) else @sizeOf(elf.Elf64_Ehdr);
if (start < ehdr_size)
return ehdr_size;
const end = start + satMul(size, alloc_num) / alloc_den;
if (self.shdr_table_offset) |off| {
const shdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Shdr) else @sizeOf(elf.Elf64_Shdr);
const tight_size = self.sections.items.len * shdr_size;
const increased_size = satMul(tight_size, alloc_num) / alloc_den;
const test_end = off + increased_size;
if (end > off and start < test_end) {
return test_end;
}
}
if (self.phdr_table_offset) |off| {
const phdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Phdr) else @sizeOf(elf.Elf64_Phdr);
const tight_size = self.sections.items.len * phdr_size;
const increased_size = satMul(tight_size, alloc_num) / alloc_den;
const test_end = off + increased_size;
if (end > off and start < test_end) {
return test_end;
}
}
for (self.sections.items) |section| {
const increased_size = satMul(section.sh_size, alloc_num) / alloc_den;
const test_end = section.sh_offset + increased_size;
if (end > section.sh_offset and start < test_end) {
return test_end;
}
}
for (self.program_headers.items) |program_header| {
const increased_size = satMul(program_header.p_filesz, alloc_num) / alloc_den;
const test_end = program_header.p_offset + increased_size;
if (end > program_header.p_offset and start < test_end) {
return test_end;
}
}
return null;
}
fn allocatedSize(self: *ElfFile, start: u64) u64 {
var min_pos: u64 = std.math.maxInt(u64);
if (self.shdr_table_offset) |off| {
if (off > start and off < min_pos) min_pos = off;
}
if (self.phdr_table_offset) |off| {
if (off > start and off < min_pos) min_pos = off;
}
for (self.sections.items) |section| {
if (section.sh_offset <= start) continue;
if (section.sh_offset < min_pos) min_pos = section.sh_offset;
}
for (self.program_headers.items) |program_header| {
if (program_header.p_offset <= start) continue;
if (program_header.p_offset < min_pos) min_pos = program_header.p_offset;
}
return min_pos - start;
}
fn findFreeSpace(self: *ElfFile, object_size: u64, min_alignment: u16) u64 {
var start: u64 = 0;
while (self.detectAllocCollision(start, object_size)) |item_end| {
start = mem.alignForwardGeneric(u64, item_end, min_alignment);
}
return start;
}
fn makeString(self: *ElfFile, bytes: []const u8) !u32 {
try self.shstrtab.ensureCapacity(self.allocator, self.shstrtab.items.len + bytes.len + 1);
const result = self.shstrtab.items.len;
self.shstrtab.appendSliceAssumeCapacity(bytes);
self.shstrtab.appendAssumeCapacity(0);
return @intCast(u32, result);
}
fn getString(self: *ElfFile, str_off: u32) []const u8 {
assert(str_off < self.shstrtab.items.len);
return mem.spanZ(@ptrCast([*:0]const u8, self.shstrtab.items.ptr + str_off));
}
fn updateString(self: *ElfFile, old_str_off: u32, new_name: []const u8) !u32 {
const existing_name = self.getString(old_str_off);
if (mem.eql(u8, existing_name, new_name)) {
return old_str_off;
}
return self.makeString(new_name);
}
pub fn populateMissingMetadata(self: *ElfFile) !void {
const small_ptr = switch (self.ptr_width) {
.p32 => true,
.p64 => false,
};
const ptr_size: u8 = switch (self.ptr_width) {
.p32 => 4,
.p64 => 8,
};
if (self.phdr_load_re_index == null) {
self.phdr_load_re_index = @intCast(u16, self.program_headers.items.len);
const file_size = self.options.program_code_size_hint;
const p_align = 0x1000;
const off = self.findFreeSpace(file_size, p_align);
//std.debug.warn("found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
try self.program_headers.append(self.allocator, .{
.p_type = elf.PT_LOAD,
.p_offset = off,
.p_filesz = file_size,
.p_vaddr = default_entry_addr,
.p_paddr = default_entry_addr,
.p_memsz = file_size,
.p_align = p_align,
.p_flags = elf.PF_X | elf.PF_R,
});
self.entry_addr = null;
self.phdr_table_dirty = true;
}
if (self.phdr_got_index == null) {
self.phdr_got_index = @intCast(u16, self.program_headers.items.len);
const file_size = @as(u64, ptr_size) * self.options.symbol_count_hint;
// We really only need ptr alignment but since we are using PROGBITS, linux requires
// page align.
const p_align = 0x1000;
const off = self.findFreeSpace(file_size, p_align);
//std.debug.warn("found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
// TODO instead of hard coding the vaddr, make a function to find a vaddr to put things at.
// we'll need to re-use that function anyway, in case the GOT grows and overlaps something
// else in virtual memory.
const default_got_addr = 0x4000000;
try self.program_headers.append(self.allocator, .{
.p_type = elf.PT_LOAD,
.p_offset = off,
.p_filesz = file_size,
.p_vaddr = default_got_addr,
.p_paddr = default_got_addr,
.p_memsz = file_size,
.p_align = p_align,
.p_flags = elf.PF_R,
});
self.phdr_table_dirty = true;
}
if (self.shstrtab_index == null) {
self.shstrtab_index = @intCast(u16, self.sections.items.len);
assert(self.shstrtab.items.len == 0);
try self.shstrtab.append(self.allocator, 0); // need a 0 at position 0
const off = self.findFreeSpace(self.shstrtab.items.len, 1);
//std.debug.warn("found shstrtab free space 0x{x} to 0x{x}\n", .{ off, off + self.shstrtab.items.len });
try self.sections.append(self.allocator, .{
.sh_name = try self.makeString(".shstrtab"),
.sh_type = elf.SHT_STRTAB,
.sh_flags = 0,
.sh_addr = 0,
.sh_offset = off,
.sh_size = self.shstrtab.items.len,
.sh_link = 0,
.sh_info = 0,
.sh_addralign = 1,
.sh_entsize = 0,
});
self.shstrtab_dirty = true;
self.shdr_table_dirty = true;
}
if (self.text_section_index == null) {
self.text_section_index = @intCast(u16, self.sections.items.len);
const phdr = &self.program_headers.items[self.phdr_load_re_index.?];
try self.sections.append(self.allocator, .{
.sh_name = try self.makeString(".text"),
.sh_type = elf.SHT_PROGBITS,
.sh_flags = elf.SHF_ALLOC | elf.SHF_EXECINSTR,
.sh_addr = phdr.p_vaddr,
.sh_offset = phdr.p_offset,
.sh_size = phdr.p_filesz,
.sh_link = 0,
.sh_info = 0,
.sh_addralign = phdr.p_align,
.sh_entsize = 0,
});
self.shdr_table_dirty = true;
}
if (self.got_section_index == null) {
self.got_section_index = @intCast(u16, self.sections.items.len);
const phdr = &self.program_headers.items[self.phdr_got_index.?];
try self.sections.append(self.allocator, .{
.sh_name = try self.makeString(".got"),
.sh_type = elf.SHT_PROGBITS,
.sh_flags = elf.SHF_ALLOC,
.sh_addr = phdr.p_vaddr,
.sh_offset = phdr.p_offset,
.sh_size = phdr.p_filesz,
.sh_link = 0,
.sh_info = 0,
.sh_addralign = phdr.p_align,
.sh_entsize = 0,
});
self.shdr_table_dirty = true;
}
if (self.symtab_section_index == null) {
self.symtab_section_index = @intCast(u16, self.sections.items.len);
const min_align: u16 = if (small_ptr) @alignOf(elf.Elf32_Sym) else @alignOf(elf.Elf64_Sym);
const each_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Sym) else @sizeOf(elf.Elf64_Sym);
const file_size = self.options.symbol_count_hint * each_size;
const off = self.findFreeSpace(file_size, min_align);
//std.debug.warn("found symtab free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
try self.sections.append(self.allocator, .{
.sh_name = try self.makeString(".symtab"),
.sh_type = elf.SHT_SYMTAB,
.sh_flags = 0,
.sh_addr = 0,
.sh_offset = off,
.sh_size = file_size,
// The section header index of the associated string table.
.sh_link = self.shstrtab_index.?,
.sh_info = @intCast(u32, self.local_symbols.items.len),
.sh_addralign = min_align,
.sh_entsize = each_size,
});
self.shdr_table_dirty = true;
try self.writeSymbol(0);
}
const shsize: u64 = switch (self.ptr_width) {
.p32 => @sizeOf(elf.Elf32_Shdr),
.p64 => @sizeOf(elf.Elf64_Shdr),
};
const shalign: u16 = switch (self.ptr_width) {
.p32 => @alignOf(elf.Elf32_Shdr),
.p64 => @alignOf(elf.Elf64_Shdr),
};
if (self.shdr_table_offset == null) {
self.shdr_table_offset = self.findFreeSpace(self.sections.items.len * shsize, shalign);
self.shdr_table_dirty = true;
}
const phsize: u64 = switch (self.ptr_width) {
.p32 => @sizeOf(elf.Elf32_Phdr),
.p64 => @sizeOf(elf.Elf64_Phdr),
};
const phalign: u16 = switch (self.ptr_width) {
.p32 => @alignOf(elf.Elf32_Phdr),
.p64 => @alignOf(elf.Elf64_Phdr),
};
if (self.phdr_table_offset == null) {
self.phdr_table_offset = self.findFreeSpace(self.program_headers.items.len * phsize, phalign);
self.phdr_table_dirty = true;
}
}
/// Commit pending changes and write headers.
pub fn flush(self: *ElfFile) !void {
const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
// Unfortunately these have to be buffered and done at the end because ELF does not allow
// mixing local and global symbols within a symbol table.
try self.writeAllGlobalSymbols();
if (self.phdr_table_dirty) {
const phsize: u64 = switch (self.ptr_width) {
.p32 => @sizeOf(elf.Elf32_Phdr),
.p64 => @sizeOf(elf.Elf64_Phdr),
};
const phalign: u16 = switch (self.ptr_width) {
.p32 => @alignOf(elf.Elf32_Phdr),
.p64 => @alignOf(elf.Elf64_Phdr),
};
const allocated_size = self.allocatedSize(self.phdr_table_offset.?);
const needed_size = self.program_headers.items.len * phsize;
if (needed_size > allocated_size) {
self.phdr_table_offset = null; // free the space
self.phdr_table_offset = self.findFreeSpace(needed_size, phalign);
}
switch (self.ptr_width) {
.p32 => {
const buf = try self.allocator.alloc(elf.Elf32_Phdr, self.program_headers.items.len);
defer self.allocator.free(buf);
for (buf) |*phdr, i| {
phdr.* = progHeaderTo32(self.program_headers.items[i]);
if (foreign_endian) {
bswapAllFields(elf.Elf32_Phdr, phdr);
}
}
try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.phdr_table_offset.?);
},
.p64 => {
const buf = try self.allocator.alloc(elf.Elf64_Phdr, self.program_headers.items.len);
defer self.allocator.free(buf);
for (buf) |*phdr, i| {
phdr.* = self.program_headers.items[i];
if (foreign_endian) {
bswapAllFields(elf.Elf64_Phdr, phdr);
}
}
try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.phdr_table_offset.?);
},
}
self.phdr_table_dirty = false;
}
{
const shstrtab_sect = &self.sections.items[self.shstrtab_index.?];
if (self.shstrtab_dirty or self.shstrtab.items.len != shstrtab_sect.sh_size) {
const allocated_size = self.allocatedSize(shstrtab_sect.sh_offset);
const needed_size = self.shstrtab.items.len;
if (needed_size > allocated_size) {
shstrtab_sect.sh_size = 0; // free the space
shstrtab_sect.sh_offset = self.findFreeSpace(needed_size, 1);
}
shstrtab_sect.sh_size = needed_size;
//std.debug.warn("shstrtab start=0x{x} end=0x{x}\n", .{ shstrtab_sect.sh_offset, shstrtab_sect.sh_offset + needed_size });
try self.file.?.pwriteAll(self.shstrtab.items, shstrtab_sect.sh_offset);
if (!self.shdr_table_dirty) {
// Then it won't get written with the others and we need to do it.
try self.writeSectHeader(self.shstrtab_index.?);
}
self.shstrtab_dirty = false;
}
}
if (self.shdr_table_dirty) {
const shsize: u64 = switch (self.ptr_width) {
.p32 => @sizeOf(elf.Elf32_Shdr),
.p64 => @sizeOf(elf.Elf64_Shdr),
};
const shalign: u16 = switch (self.ptr_width) {
.p32 => @alignOf(elf.Elf32_Shdr),
.p64 => @alignOf(elf.Elf64_Shdr),
};
const allocated_size = self.allocatedSize(self.shdr_table_offset.?);
const needed_size = self.sections.items.len * shsize;
if (needed_size > allocated_size) {
self.shdr_table_offset = null; // free the space
self.shdr_table_offset = self.findFreeSpace(needed_size, shalign);
}
switch (self.ptr_width) {
.p32 => {
const buf = try self.allocator.alloc(elf.Elf32_Shdr, self.sections.items.len);
defer self.allocator.free(buf);
for (buf) |*shdr, i| {
shdr.* = sectHeaderTo32(self.sections.items[i]);
if (foreign_endian) {
bswapAllFields(elf.Elf32_Shdr, shdr);
}
}
try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.shdr_table_offset.?);
},
.p64 => {
const buf = try self.allocator.alloc(elf.Elf64_Shdr, self.sections.items.len);
defer self.allocator.free(buf);
for (buf) |*shdr, i| {
shdr.* = self.sections.items[i];
//std.debug.warn("writing section {}\n", .{shdr.*});
if (foreign_endian) {
bswapAllFields(elf.Elf64_Shdr, shdr);
}
}
try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.shdr_table_offset.?);
},
}
self.shdr_table_dirty = false;
}
if (self.entry_addr == null and self.options.output_mode == .Exe) {
self.error_flags.no_entry_point_found = true;
} else {
self.error_flags.no_entry_point_found = false;
try self.writeElfHeader();
}
// TODO find end pos and truncate
// The point of flush() is to commit changes, so nothing should be dirty after this.
assert(!self.phdr_table_dirty);
assert(!self.shdr_table_dirty);
assert(!self.shstrtab_dirty);
assert(!self.offset_table_count_dirty);
const syms_sect = &self.sections.items[self.symtab_section_index.?];
assert(syms_sect.sh_info == self.local_symbols.items.len);
}
fn writeElfHeader(self: *ElfFile) !void {
var hdr_buf: [@sizeOf(elf.Elf64_Ehdr)]u8 = undefined;
var index: usize = 0;
hdr_buf[0..4].* = "\x7fELF".*;
index += 4;
hdr_buf[index] = switch (self.ptr_width) {
.p32 => elf.ELFCLASS32,
.p64 => elf.ELFCLASS64,
};
index += 1;
const endian = self.options.target.cpu.arch.endian();
hdr_buf[index] = switch (endian) {
.Little => elf.ELFDATA2LSB,
.Big => elf.ELFDATA2MSB,
};
index += 1;
hdr_buf[index] = 1; // ELF version
index += 1;
// OS ABI, often set to 0 regardless of target platform
// ABI Version, possibly used by glibc but not by static executables
// padding
mem.set(u8, hdr_buf[index..][0..9], 0);
index += 9;
assert(index == 16);
const elf_type = switch (self.options.output_mode) {
.Exe => elf.ET.EXEC,
.Obj => elf.ET.REL,
.Lib => switch (self.options.link_mode) {
.Static => elf.ET.REL,
.Dynamic => elf.ET.DYN,
},
};
mem.writeInt(u16, hdr_buf[index..][0..2], @enumToInt(elf_type), endian);
index += 2;
const machine = self.options.target.cpu.arch.toElfMachine();
mem.writeInt(u16, hdr_buf[index..][0..2], @enumToInt(machine), endian);
index += 2;
// ELF Version, again
mem.writeInt(u32, hdr_buf[index..][0..4], 1, endian);
index += 4;
const e_entry = if (elf_type == .REL) 0 else self.entry_addr.?;
switch (self.ptr_width) {
.p32 => {
mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(u32, e_entry), endian);
index += 4;
// e_phoff
mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(u32, self.phdr_table_offset.?), endian);
index += 4;
// e_shoff
mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(u32, self.shdr_table_offset.?), endian);
index += 4;
},
.p64 => {
// e_entry
mem.writeInt(u64, hdr_buf[index..][0..8], e_entry, endian);
index += 8;
// e_phoff
mem.writeInt(u64, hdr_buf[index..][0..8], self.phdr_table_offset.?, endian);
index += 8;
// e_shoff
mem.writeInt(u64, hdr_buf[index..][0..8], self.shdr_table_offset.?, endian);
index += 8;
},
}
const e_flags = 0;
mem.writeInt(u32, hdr_buf[index..][0..4], e_flags, endian);
index += 4;
const e_ehsize: u16 = switch (self.ptr_width) {
.p32 => @sizeOf(elf.Elf32_Ehdr),
.p64 => @sizeOf(elf.Elf64_Ehdr),
};
mem.writeInt(u16, hdr_buf[index..][0..2], e_ehsize, endian);
index += 2;
const e_phentsize: u16 = switch (self.ptr_width) {
.p32 => @sizeOf(elf.Elf32_Phdr),
.p64 => @sizeOf(elf.Elf64_Phdr),
};
mem.writeInt(u16, hdr_buf[index..][0..2], e_phentsize, endian);
index += 2;
const e_phnum = @intCast(u16, self.program_headers.items.len);
mem.writeInt(u16, hdr_buf[index..][0..2], e_phnum, endian);
index += 2;
const e_shentsize: u16 = switch (self.ptr_width) {
.p32 => @sizeOf(elf.Elf32_Shdr),
.p64 => @sizeOf(elf.Elf64_Shdr),
};
mem.writeInt(u16, hdr_buf[index..][0..2], e_shentsize, endian);
index += 2;
const e_shnum = @intCast(u16, self.sections.items.len);
mem.writeInt(u16, hdr_buf[index..][0..2], e_shnum, endian);
index += 2;
mem.writeInt(u16, hdr_buf[index..][0..2], self.shstrtab_index.?, endian);
index += 2;
assert(index == e_ehsize);
try self.file.?.pwriteAll(hdr_buf[0..index], 0);
}
const AllocatedBlock = struct {
vaddr: u64,
file_offset: u64,
size_capacity: u64,
};
fn allocateTextBlock(self: *ElfFile, new_block_size: u64, alignment: u64) !AllocatedBlock {
const phdr = &self.program_headers.items[self.phdr_load_re_index.?];
const shdr = &self.sections.items[self.text_section_index.?];
// TODO Also detect virtual address collisions.
const text_capacity = self.allocatedSize(shdr.sh_offset);
// TODO instead of looping here, maintain a free list and a pointer to the end.
var last_start: u64 = phdr.p_vaddr;
var last_size: u64 = 0;
for (self.local_symbols.items) |sym| {
if (sym.st_value + sym.st_size > last_start + last_size) {
last_start = sym.st_value;
last_size = sym.st_size;
}
}
const end_vaddr = last_start + (last_size * alloc_num / alloc_den);
const aligned_start_vaddr = mem.alignForwardGeneric(u64, end_vaddr, alignment);
const needed_size = (aligned_start_vaddr + new_block_size) - phdr.p_vaddr;
if (needed_size > text_capacity) {
// Must move the entire text section.
const new_offset = self.findFreeSpace(needed_size, 0x1000);
const text_size = (last_start + last_size) - phdr.p_vaddr;
const amt = try self.file.?.copyRangeAll(shdr.sh_offset, self.file.?, new_offset, text_size);
if (amt != text_size) return error.InputOutput;
shdr.sh_offset = new_offset;
phdr.p_offset = new_offset;
}
// Now that we know the code size, we need to update the program header for executable code
shdr.sh_size = needed_size;
phdr.p_memsz = needed_size;
phdr.p_filesz = needed_size;
self.phdr_table_dirty = true; // TODO look into making only the one program header dirty
self.shdr_table_dirty = true; // TODO look into making only the one section dirty
return AllocatedBlock{
.vaddr = aligned_start_vaddr,
.file_offset = shdr.sh_offset + (aligned_start_vaddr - phdr.p_vaddr),
.size_capacity = text_capacity - needed_size,
};
}
fn findAllocatedTextBlock(self: *ElfFile, sym: elf.Elf64_Sym) AllocatedBlock {
const phdr = &self.program_headers.items[self.phdr_load_re_index.?];
const shdr = &self.sections.items[self.text_section_index.?];
// Find the next sym after this one.
// TODO look into using a hash map to speed up perf.
const text_capacity = self.allocatedSize(shdr.sh_offset);
var next_vaddr_start = phdr.p_vaddr + text_capacity;
for (self.local_symbols.items) |elem| {
if (elem.st_value < sym.st_value) continue;
if (elem.st_value < next_vaddr_start) next_vaddr_start = elem.st_value;
}
return .{
.vaddr = sym.st_value,
.file_offset = shdr.sh_offset + (sym.st_value - phdr.p_vaddr),
.size_capacity = next_vaddr_start - sym.st_value,
};
}
pub fn allocateDeclIndexes(self: *ElfFile, decl: *Module.Decl) !void {
if (decl.link.local_sym_index != 0) return;
try self.local_symbols.ensureCapacity(self.allocator, self.local_symbols.items.len + 1);
try self.offset_table.ensureCapacity(self.allocator, self.offset_table.items.len + 1);
const local_sym_index = self.local_symbols.items.len;
const offset_table_index = self.offset_table.items.len;
const phdr = &self.program_headers.items[self.phdr_load_re_index.?];
self.local_symbols.appendAssumeCapacity(.{
.st_name = 0,
.st_info = 0,
.st_other = 0,
.st_shndx = 0,
.st_value = phdr.p_vaddr,
.st_size = 0,
});
errdefer self.local_symbols.shrink(self.allocator, self.local_symbols.items.len - 1);
self.offset_table.appendAssumeCapacity(0);
errdefer self.offset_table.shrink(self.allocator, self.offset_table.items.len - 1);
self.offset_table_count_dirty = true;
decl.link = .{
.local_sym_index = @intCast(u32, local_sym_index),
.offset_table_index = @intCast(u32, offset_table_index),
};
}
pub fn updateDecl(self: *ElfFile, module: *Module, decl: *Module.Decl) !void {
var code_buffer = std.ArrayList(u8).init(self.allocator);
defer code_buffer.deinit();
const typed_value = decl.typed_value.most_recent.typed_value;
const code = switch (try codegen.generateSymbol(self, decl.src, typed_value, &code_buffer)) {
.externally_managed => |x| x,
.appended => code_buffer.items,
.fail => |em| {
decl.analysis = .codegen_failure;
_ = try module.failed_decls.put(decl, em);
return;
},
};
const required_alignment = typed_value.ty.abiAlignment(self.options.target);
const file_offset = blk: {
const stt_bits: u8 = switch (typed_value.ty.zigTypeTag()) {
.Fn => elf.STT_FUNC,
else => elf.STT_OBJECT,
};
if (decl.link.local_sym_index != 0) {
const local_sym = &self.local_symbols.items[decl.link.local_sym_index];
const existing_block = self.findAllocatedTextBlock(local_sym.*);
const need_realloc = local_sym.st_size == 0 or
code.len > existing_block.size_capacity or
!mem.isAlignedGeneric(u64, local_sym.st_value, required_alignment);
// TODO check for collision with another symbol
const file_offset = if (need_realloc) fo: {
const new_block = try self.allocateTextBlock(code.len, required_alignment);
local_sym.st_value = new_block.vaddr;
self.offset_table.items[decl.link.offset_table_index] = new_block.vaddr;
//std.debug.warn("{}: writing got index {}=0x{x}\n", .{
// decl.name,
// decl.link.offset_table_index,
// self.offset_table.items[decl.link.offset_table_index],
//});
try self.writeOffsetTableEntry(decl.link.offset_table_index);
break :fo new_block.file_offset;
} else existing_block.file_offset;
local_sym.st_size = code.len;
local_sym.st_name = try self.updateString(local_sym.st_name, mem.spanZ(decl.name));
local_sym.st_info = (elf.STB_LOCAL << 4) | stt_bits;
local_sym.st_other = 0;
local_sym.st_shndx = self.text_section_index.?;
// TODO this write could be avoided if no fields of the symbol were changed.
try self.writeSymbol(decl.link.local_sym_index);
//std.debug.warn("updating {} at vaddr 0x{x}\n", .{ decl.name, local_sym.st_value });
break :blk file_offset;
} else {
try self.local_symbols.ensureCapacity(self.allocator, self.local_symbols.items.len + 1);
try self.offset_table.ensureCapacity(self.allocator, self.offset_table.items.len + 1);
const decl_name = mem.spanZ(decl.name);
const name_str_index = try self.makeString(decl_name);
const new_block = try self.allocateTextBlock(code.len, required_alignment);
const local_sym_index = self.local_symbols.items.len;
const offset_table_index = self.offset_table.items.len;
//std.debug.warn("add symbol for {} at vaddr 0x{x}, size {}\n", .{ decl.name, new_block.vaddr, code.len });
self.local_symbols.appendAssumeCapacity(.{
.st_name = name_str_index,
.st_info = (elf.STB_LOCAL << 4) | stt_bits,
.st_other = 0,
.st_shndx = self.text_section_index.?,
.st_value = new_block.vaddr,
.st_size = code.len,
});
errdefer self.local_symbols.shrink(self.allocator, self.local_symbols.items.len - 1);
self.offset_table.appendAssumeCapacity(new_block.vaddr);
errdefer self.offset_table.shrink(self.allocator, self.offset_table.items.len - 1);
self.offset_table_count_dirty = true;
try self.writeSymbol(local_sym_index);
try self.writeOffsetTableEntry(offset_table_index);
decl.link = .{
.local_sym_index = @intCast(u32, local_sym_index),
.offset_table_index = @intCast(u32, offset_table_index),
};
//std.debug.warn("writing new {} at vaddr 0x{x}\n", .{ decl.name, new_block.vaddr });
break :blk new_block.file_offset;
}
};
try self.file.?.pwriteAll(code, file_offset);
// Since we updated the vaddr and the size, each corresponding export symbol also needs to be updated.
const decl_exports = module.decl_exports.getValue(decl) orelse &[0]*Module.Export{};
return self.updateDeclExports(module, decl, decl_exports);
}
/// Must be called only after a successful call to `updateDecl`.
pub fn updateDeclExports(
self: *ElfFile,
module: *Module,
decl: *const Module.Decl,
exports: []const *Module.Export,
) !void {
try self.global_symbols.ensureCapacity(self.allocator, self.global_symbols.items.len + exports.len);
const typed_value = decl.typed_value.most_recent.typed_value;
if (decl.link.local_sym_index == 0) return;
const decl_sym = self.local_symbols.items[decl.link.local_sym_index];
for (exports) |exp| {
if (exp.options.section) |section_name| {
if (!mem.eql(u8, section_name, ".text")) {
try module.failed_exports.ensureCapacity(module.failed_exports.size + 1);
module.failed_exports.putAssumeCapacityNoClobber(
exp,
try Module.ErrorMsg.create(self.allocator, 0, "Unimplemented: ExportOptions.section", .{}),
);
continue;
}
}
const stb_bits: u8 = switch (exp.options.linkage) {
.Internal => elf.STB_LOCAL,
.Strong => blk: {
if (mem.eql(u8, exp.options.name, "_start")) {
self.entry_addr = decl_sym.st_value;
}
break :blk elf.STB_GLOBAL;
},
.Weak => elf.STB_WEAK,
.LinkOnce => {
try module.failed_exports.ensureCapacity(module.failed_exports.size + 1);
module.failed_exports.putAssumeCapacityNoClobber(
exp,
try Module.ErrorMsg.create(self.allocator, 0, "Unimplemented: GlobalLinkage.LinkOnce", .{}),
);
continue;
},
};
const stt_bits: u8 = @truncate(u4, decl_sym.st_info);
if (exp.link.sym_index) |i| {
const sym = &self.global_symbols.items[i];
sym.* = .{
.st_name = try self.updateString(sym.st_name, exp.options.name),
.st_info = (stb_bits << 4) | stt_bits,
.st_other = 0,
.st_shndx = self.text_section_index.?,
.st_value = decl_sym.st_value,
.st_size = decl_sym.st_size,
};
} else {
const name = try self.makeString(exp.options.name);
const i = self.global_symbols.items.len;
self.global_symbols.appendAssumeCapacity(.{
.st_name = name,
.st_info = (stb_bits << 4) | stt_bits,
.st_other = 0,
.st_shndx = self.text_section_index.?,
.st_value = decl_sym.st_value,
.st_size = decl_sym.st_size,
});
errdefer self.global_symbols.shrink(self.allocator, self.global_symbols.items.len - 1);
exp.link.sym_index = @intCast(u32, i);
}
}
}
fn writeProgHeader(self: *ElfFile, index: usize) !void {
const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
const offset = self.program_headers.items[index].p_offset;
switch (self.options.target.cpu.arch.ptrBitWidth()) {
32 => {
var phdr = [1]elf.Elf32_Phdr{progHeaderTo32(self.program_headers.items[index])};
if (foreign_endian) {
bswapAllFields(elf.Elf32_Phdr, &phdr[0]);
}
return self.file.?.pwriteAll(mem.sliceAsBytes(&phdr), offset);
},
64 => {
var phdr = [1]elf.Elf64_Phdr{self.program_headers.items[index]};
if (foreign_endian) {
bswapAllFields(elf.Elf64_Phdr, &phdr[0]);
}
return self.file.?.pwriteAll(mem.sliceAsBytes(&phdr), offset);
},
else => return error.UnsupportedArchitecture,
}
}
fn writeSectHeader(self: *ElfFile, index: usize) !void {
const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
const offset = self.sections.items[index].sh_offset;
switch (self.options.target.cpu.arch.ptrBitWidth()) {
32 => {
var shdr: [1]elf.Elf32_Shdr = undefined;
shdr[0] = sectHeaderTo32(self.sections.items[index]);
if (foreign_endian) {
bswapAllFields(elf.Elf32_Shdr, &shdr[0]);
}
return self.file.?.pwriteAll(mem.sliceAsBytes(&shdr), offset);
},
64 => {
var shdr = [1]elf.Elf64_Shdr{self.sections.items[index]};
if (foreign_endian) {
bswapAllFields(elf.Elf64_Shdr, &shdr[0]);
}
return self.file.?.pwriteAll(mem.sliceAsBytes(&shdr), offset);
},
else => return error.UnsupportedArchitecture,
}
}
fn writeOffsetTableEntry(self: *ElfFile, index: usize) !void {
const shdr = &self.sections.items[self.got_section_index.?];
const phdr = &self.program_headers.items[self.phdr_got_index.?];
const entry_size: u16 = switch (self.ptr_width) {
.p32 => 4,
.p64 => 8,
};
if (self.offset_table_count_dirty) {
// TODO Also detect virtual address collisions.
const allocated_size = self.allocatedSize(shdr.sh_offset);
const needed_size = self.local_symbols.items.len * entry_size;
if (needed_size > allocated_size) {
// Must move the entire got section.
const new_offset = self.findFreeSpace(needed_size, entry_size);
const amt = try self.file.?.copyRangeAll(shdr.sh_offset, self.file.?, new_offset, shdr.sh_size);
if (amt != shdr.sh_size) return error.InputOutput;
shdr.sh_offset = new_offset;
phdr.p_offset = new_offset;
}
shdr.sh_size = needed_size;
phdr.p_memsz = needed_size;
phdr.p_filesz = needed_size;
self.shdr_table_dirty = true; // TODO look into making only the one section dirty
self.phdr_table_dirty = true; // TODO look into making only the one program header dirty
self.offset_table_count_dirty = false;
}
const endian = self.options.target.cpu.arch.endian();
const off = shdr.sh_offset + @as(u64, entry_size) * index;
switch (self.ptr_width) {
.p32 => {
var buf: [4]u8 = undefined;
mem.writeInt(u32, &buf, @intCast(u32, self.offset_table.items[index]), endian);
try self.file.?.pwriteAll(&buf, off);
},
.p64 => {
var buf: [8]u8 = undefined;
mem.writeInt(u64, &buf, self.offset_table.items[index], endian);
try self.file.?.pwriteAll(&buf, off);
},
}
}
fn writeSymbol(self: *ElfFile, index: usize) !void {
const syms_sect = &self.sections.items[self.symtab_section_index.?];
// Make sure we are not pointlessly writing symbol data that will have to get relocated
// due to running out of space.
if (self.local_symbols.items.len != syms_sect.sh_info) {
const sym_size: u64 = switch (self.ptr_width) {
.p32 => @sizeOf(elf.Elf32_Sym),
.p64 => @sizeOf(elf.Elf64_Sym),
};
const sym_align: u16 = switch (self.ptr_width) {
.p32 => @alignOf(elf.Elf32_Sym),
.p64 => @alignOf(elf.Elf64_Sym),
};
const needed_size = (self.local_symbols.items.len + self.global_symbols.items.len) * sym_size;
if (needed_size > self.allocatedSize(syms_sect.sh_offset)) {
// Move all the symbols to a new file location.
const new_offset = self.findFreeSpace(needed_size, sym_align);
const existing_size = @as(u64, syms_sect.sh_info) * sym_size;
const amt = try self.file.?.copyRangeAll(syms_sect.sh_offset, self.file.?, new_offset, existing_size);
if (amt != existing_size) return error.InputOutput;
syms_sect.sh_offset = new_offset;
}
syms_sect.sh_info = @intCast(u32, self.local_symbols.items.len);
syms_sect.sh_size = needed_size; // anticipating adding the global symbols later
self.shdr_table_dirty = true; // TODO look into only writing one section
}
const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
switch (self.ptr_width) {
.p32 => {
var sym = [1]elf.Elf32_Sym{
.{
.st_name = self.local_symbols.items[index].st_name,
.st_value = @intCast(u32, self.local_symbols.items[index].st_value),
.st_size = @intCast(u32, self.local_symbols.items[index].st_size),
.st_info = self.local_symbols.items[index].st_info,
.st_other = self.local_symbols.items[index].st_other,
.st_shndx = self.local_symbols.items[index].st_shndx,
},
};
if (foreign_endian) {
bswapAllFields(elf.Elf32_Sym, &sym[0]);
}
const off = syms_sect.sh_offset + @sizeOf(elf.Elf32_Sym) * index;
try self.file.?.pwriteAll(mem.sliceAsBytes(sym[0..1]), off);
},
.p64 => {
var sym = [1]elf.Elf64_Sym{self.local_symbols.items[index]};
if (foreign_endian) {
bswapAllFields(elf.Elf64_Sym, &sym[0]);
}
const off = syms_sect.sh_offset + @sizeOf(elf.Elf64_Sym) * index;
try self.file.?.pwriteAll(mem.sliceAsBytes(sym[0..1]), off);
},
}
}
fn writeAllGlobalSymbols(self: *ElfFile) !void {
const syms_sect = &self.sections.items[self.symtab_section_index.?];
const sym_size: u64 = switch (self.ptr_width) {
.p32 => @sizeOf(elf.Elf32_Sym),
.p64 => @sizeOf(elf.Elf64_Sym),
};
//std.debug.warn("symtab start=0x{x} end=0x{x}\n", .{ syms_sect.sh_offset, syms_sect.sh_offset + needed_size });
const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
const global_syms_off = syms_sect.sh_offset + self.local_symbols.items.len * sym_size;
switch (self.ptr_width) {
.p32 => {
const buf = try self.allocator.alloc(elf.Elf32_Sym, self.global_symbols.items.len);
defer self.allocator.free(buf);
for (buf) |*sym, i| {
sym.* = .{
.st_name = self.global_symbols.items[i].st_name,
.st_value = @intCast(u32, self.global_symbols.items[i].st_value),
.st_size = @intCast(u32, self.global_symbols.items[i].st_size),
.st_info = self.global_symbols.items[i].st_info,
.st_other = self.global_symbols.items[i].st_other,
.st_shndx = self.global_symbols.items[i].st_shndx,
};
if (foreign_endian) {
bswapAllFields(elf.Elf32_Sym, sym);
}
}
try self.file.?.pwriteAll(mem.sliceAsBytes(buf), global_syms_off);
},
.p64 => {
const buf = try self.allocator.alloc(elf.Elf64_Sym, self.global_symbols.items.len);
defer self.allocator.free(buf);
for (buf) |*sym, i| {
sym.* = .{
.st_name = self.global_symbols.items[i].st_name,
.st_value = self.global_symbols.items[i].st_value,
.st_size = self.global_symbols.items[i].st_size,
.st_info = self.global_symbols.items[i].st_info,
.st_other = self.global_symbols.items[i].st_other,
.st_shndx = self.global_symbols.items[i].st_shndx,
};
if (foreign_endian) {
bswapAllFields(elf.Elf64_Sym, sym);
}
}
try self.file.?.pwriteAll(mem.sliceAsBytes(buf), global_syms_off);
},
}
}
};
/// Truncates the existing file contents and overwrites the contents.
/// Returns an error if `file` is not already open with +read +write +seek abilities.
pub fn createElfFile(allocator: *Allocator, file: fs.File, options: Options) !ElfFile {
switch (options.output_mode) {
.Exe => {},
.Obj => {},
.Lib => return error.TODOImplementWritingLibFiles,
}
switch (options.object_format) {
.unknown => unreachable, // TODO remove this tag from the enum
.coff => return error.TODOImplementWritingCOFF,
.elf => {},
.macho => return error.TODOImplementWritingMachO,
.wasm => return error.TODOImplementWritingWasmObjects,
}
var self: ElfFile = .{
.allocator = allocator,
.file = file,
.options = options,
.ptr_width = switch (options.target.cpu.arch.ptrBitWidth()) {
32 => .p32,
64 => .p64,
else => return error.UnsupportedELFArchitecture,
},
.shdr_table_dirty = true,
.owns_file_handle = false,
};
errdefer self.deinit();
// Index 0 is always a null symbol.
try self.local_symbols.append(allocator, .{
.st_name = 0,
.st_info = 0,
.st_other = 0,
.st_shndx = 0,
.st_value = 0,
.st_size = 0,
});
// There must always be a null section in index 0
try self.sections.append(allocator, .{
.sh_name = 0,
.sh_type = elf.SHT_NULL,
.sh_flags = 0,
.sh_addr = 0,
.sh_offset = 0,
.sh_size = 0,
.sh_link = 0,
.sh_info = 0,
.sh_addralign = 0,
.sh_entsize = 0,
});
try self.populateMissingMetadata();
return self;
}
/// Returns error.IncrFailed if incremental update could not be performed.
fn openBinFileInner(allocator: *Allocator, file: fs.File, options: Options) !ElfFile {
switch (options.output_mode) {
.Exe => {},
.Obj => {},
.Lib => return error.IncrFailed,
}
switch (options.object_format) {
.unknown => unreachable, // TODO remove this tag from the enum
.coff => return error.IncrFailed,
.elf => {},
.macho => return error.IncrFailed,
.wasm => return error.IncrFailed,
}
var self: ElfFile = .{
.allocator = allocator,
.file = file,
.owns_file_handle = false,
.options = options,
.ptr_width = switch (options.target.cpu.arch.ptrBitWidth()) {
32 => .p32,
64 => .p64,
else => return error.UnsupportedELFArchitecture,
},
};
errdefer self.deinit();
// TODO implement reading the elf file
return error.IncrFailed;
//try self.populateMissingMetadata();
//return self;
}
/// Saturating multiplication
fn satMul(a: var, b: var) @TypeOf(a, b) {
const T = @TypeOf(a, b);
return std.math.mul(T, a, b) catch std.math.maxInt(T);
}
fn bswapAllFields(comptime S: type, ptr: *S) void {
@panic("TODO implement bswapAllFields");
}
fn progHeaderTo32(phdr: elf.Elf64_Phdr) elf.Elf32_Phdr {
return .{
.p_type = phdr.p_type,
.p_flags = phdr.p_flags,
.p_offset = @intCast(u32, phdr.p_offset),
.p_vaddr = @intCast(u32, phdr.p_vaddr),
.p_paddr = @intCast(u32, phdr.p_paddr),
.p_filesz = @intCast(u32, phdr.p_filesz),
.p_memsz = @intCast(u32, phdr.p_memsz),
.p_align = @intCast(u32, phdr.p_align),
};
}
fn sectHeaderTo32(shdr: elf.Elf64_Shdr) elf.Elf32_Shdr {
return .{
.sh_name = shdr.sh_name,
.sh_type = shdr.sh_type,
.sh_flags = @intCast(u32, shdr.sh_flags),
.sh_addr = @intCast(u32, shdr.sh_addr),
.sh_offset = @intCast(u32, shdr.sh_offset),
.sh_size = @intCast(u32, shdr.sh_size),
.sh_link = shdr.sh_link,
.sh_info = shdr.sh_info,
.sh_addralign = @intCast(u32, shdr.sh_addralign),
.sh_entsize = @intCast(u32, shdr.sh_entsize),
};
}
fn determineMode(options: Options) fs.File.Mode {
// On common systems with a 0o022 umask, 0o777 will still result in a file created
// with 0o755 permissions, but it works appropriately if the system is configured
// more leniently. As another data point, C's fopen seems to open files with the
// 666 mode.
const executable_mode = if (std.Target.current.os.tag == .windows) 0 else 0o777;
switch (options.output_mode) {
.Lib => return switch (options.link_mode) {
.Dynamic => executable_mode,
.Static => fs.File.default_mode,
},
.Exe => return executable_mode,
.Obj => return fs.File.default_mode,
}
} | src-self-hosted/link.zig |
const std = @import("std");
const mem = std.mem;
const meta = std.meta;
const net = std.net;
const ArrayList = std.ArrayList;
usingnamespace @import("../frame.zig");
usingnamespace @import("../primitive_types.zig");
const testing = @import("../testing.zig");
/// SUPPORTED is sent by a node in response to a OPTIONS frame.
///
/// Described in the protocol spec at §4.2.4.
pub const SupportedFrame = struct {
const Self = @This();
pub const opcode: Opcode = .Supported;
protocol_versions: []ProtocolVersion,
cql_versions: []CQLVersion,
compression_algorithms: []CompressionAlgorithm,
pub fn read(allocator: *mem.Allocator, pr: *PrimitiveReader) !Self {
var frame = Self{
.protocol_versions = &[_]ProtocolVersion{},
.cql_versions = &[_]CQLVersion{},
.compression_algorithms = &[_]CompressionAlgorithm{},
};
const options = try pr.readStringMultimap(allocator);
if (options.get("CQL_VERSION")) |values| {
var list = std.ArrayList(CQLVersion).init(allocator);
for (values) |value| {
const version = try CQLVersion.fromString(value);
_ = try list.append(version);
}
frame.cql_versions = list.toOwnedSlice();
} else {
return error.NoCQLVersion;
}
if (options.get("COMPRESSION")) |values| {
var list = std.ArrayList(CompressionAlgorithm).init(allocator);
for (values) |value| {
const compression_algorithm = try CompressionAlgorithm.fromString(value);
_ = try list.append(compression_algorithm);
}
frame.compression_algorithms = list.toOwnedSlice();
}
if (options.get("PROTOCOL_VERSIONS")) |values| {
var list = std.ArrayList(ProtocolVersion).init(allocator);
for (values) |value| {
const version = try ProtocolVersion.fromString(value);
_ = try list.append(version);
}
frame.protocol_versions = list.toOwnedSlice();
}
return frame;
}
};
test "supported frame" {
var arena = testing.arenaAllocator();
defer arena.deinit();
// read
const exp = "\x84\x00\x00\x09\x06\x00\x00\x00\x60\x00\x03\x00\x11\x50\x52\x4f\x54\x4f\x43\x4f\x4c\x5f\x56\x45\x52\x53\x49\x4f\x4e\x53\x00\x03\x00\x04\x33\x2f\x76\x33\x00\x04\x34\x2f\x76\x34\x00\x09\x35\x2f\x76\x35\x2d\x62\x65\x74\x61\x00\x0b\x43\x4f\x4d\x50\x52\x45\x53\x53\x49\x4f\x4e\x00\x02\x00\x06\x73\x6e\x61\x70\x70\x79\x00\x03\x6c\x7a\x34\x00\x0b\x43\x51\x4c\x5f\x56\x45\x52\x53\x49\x4f\x4e\x00\x01\x00\x05\x33\x2e\x34\x2e\x34";
const raw_frame = try testing.readRawFrame(&arena.allocator, exp);
checkHeader(Opcode.Supported, exp.len, raw_frame.header);
var pr = PrimitiveReader.init();
pr.reset(raw_frame.body);
const frame = try SupportedFrame.read(&arena.allocator, &pr);
testing.expectEqual(@as(usize, 1), frame.cql_versions.len);
testing.expectEqual(CQLVersion{ .major = 3, .minor = 4, .patch = 4 }, frame.cql_versions[0]);
testing.expectEqual(@as(usize, 3), frame.protocol_versions.len);
testing.expect(frame.protocol_versions[0].is(3));
testing.expect(frame.protocol_versions[1].is(4));
testing.expect(frame.protocol_versions[2].is(5));
testing.expectEqual(@as(usize, 2), frame.compression_algorithms.len);
testing.expectEqual(CompressionAlgorithm.Snappy, frame.compression_algorithms[0]);
testing.expectEqual(CompressionAlgorithm.LZ4, frame.compression_algorithms[1]);
} | src/frames/supported.zig |
const std = @import("std");
const zp = @import("../../zplay.zig");
const ShaderProgram = zp.graphics.common.ShaderProgram;
const alg = zp.deps.alg;
const Vec3 = alg.Vec3;
const Self = @This();
/// light type
pub const Type = enum {
directional,
point,
spot,
};
/// light properties
pub const Data = union(Type) {
directional: struct {
ambient: Vec3,
diffuse: Vec3,
specular: Vec3 = Vec3.one(),
direction: Vec3,
},
point: struct {
ambient: Vec3,
diffuse: Vec3,
specular: Vec3 = Vec3.one(),
position: Vec3,
constant: f32 = 1.0,
linear: f32,
quadratic: f32,
},
spot: struct {
ambient: Vec3,
diffuse: Vec3,
specular: Vec3 = Vec3.one(),
position: Vec3,
direction: Vec3,
constant: f32 = 1.0,
linear: f32,
quadratic: f32,
cutoff: f32,
outer_cutoff: f32,
},
};
/// light property data
data: Data,
/// create a new light
pub fn init(data: Data) Self {
return .{
.data = data,
};
}
/// get light type
pub fn getType(self: Self) Type {
return @as(Type, self.data);
}
/// get light position
pub fn getPosition(self: Self) ?Vec3 {
return switch (self.data) {
.point => |d| d.position,
.spot => |d| d.position,
else => null,
};
}
/// update light colors
pub fn updateColors(self: *Self, ambient: ?Vec3, diffuse: ?Vec3, specular: ?Vec3) void {
switch (self.data) {
.directional => |*d| {
if (ambient) |color| {
d.ambient = color;
}
if (diffuse) |color| {
d.diffuse = color;
}
if (specular) |color| {
d.specular = color;
}
},
.point => |*d| {
if (ambient) |color| {
d.ambient = color;
}
if (diffuse) |color| {
d.diffuse = color;
}
if (specular) |color| {
d.specular = color;
}
},
.spot => |*d| {
if (ambient) |color| {
d.ambient = color;
}
if (diffuse) |color| {
d.diffuse = color;
}
if (specular) |color| {
d.specular = color;
}
},
}
}
/// apply light in the shader
pub fn apply(self: Self, program: *ShaderProgram, uniform_name: [:0]const u8) void {
const allocator = std.heap.raw_c_allocator;
var buf = allocator.alloc(u8, uniform_name.len + 64) catch unreachable;
defer allocator.free(buf);
switch (self.data) {
.directional => |d| {
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.ambient", .{uniform_name}) catch unreachable,
d.ambient,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.diffuse", .{uniform_name}) catch unreachable,
d.diffuse,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.specular", .{uniform_name}) catch unreachable,
d.specular,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.direction", .{uniform_name}) catch unreachable,
d.direction,
);
},
.point => |d| {
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.ambient", .{uniform_name}) catch unreachable,
d.ambient,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.diffuse", .{uniform_name}) catch unreachable,
d.diffuse,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.specular", .{uniform_name}) catch unreachable,
d.specular,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.position", .{uniform_name}) catch unreachable,
d.position,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.constant", .{uniform_name}) catch unreachable,
d.constant,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.linear", .{uniform_name}) catch unreachable,
d.linear,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.quadratic", .{uniform_name}) catch unreachable,
d.quadratic,
);
},
.spot => |d| {
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.ambient", .{uniform_name}) catch unreachable,
d.ambient,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.diffuse", .{uniform_name}) catch unreachable,
d.diffuse,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.specular", .{uniform_name}) catch unreachable,
d.specular,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.position", .{uniform_name}) catch unreachable,
d.position,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.direction", .{uniform_name}) catch unreachable,
d.direction,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.constant", .{uniform_name}) catch unreachable,
d.constant,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.linear", .{uniform_name}) catch unreachable,
d.linear,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.quadratic", .{uniform_name}) catch unreachable,
d.quadratic,
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.cutoff", .{uniform_name}) catch unreachable,
std.math.cos(alg.toRadians(d.cutoff)),
);
program.setUniformByName(
std.fmt.bufPrintZ(buf, "{s}.outer_cutoff", .{uniform_name}) catch unreachable,
std.math.cos(alg.toRadians(d.outer_cutoff)),
);
},
}
} | src/graphics/3d/Light.zig |
const std = @import("std");
const interop = @import("../interop.zig");
const iup = @import("../iup.zig");
const Impl = @import("../impl.zig").Impl;
const CallbackHandler = @import("../callback_handler.zig").CallbackHandler;
const debug = std.debug;
const trait = std.meta.trait;
const Element = iup.Element;
const Handle = iup.Handle;
const Error = iup.Error;
const ChildrenIterator = iup.ChildrenIterator;
const Size = iup.Size;
const Margin = iup.Margin;
///
/// Creates the File Dialog element.
/// It is a predefined dialog for selecting files or a directory.
/// The dialog can be shown with the IupPopup function only.
pub const FileDlg = opaque {
pub const CLASS_NAME = "filedlg";
pub const NATIVE_TYPE = iup.NativeType.Dialog;
const Self = @This();
pub const OnFocusFn = fn (self: *Self, arg0: i32) anyerror!void;
///
/// K_ANY K_ANY Action generated when a keyboard event occurs.
/// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) ->
/// (ret: number) [in Lua] ih: identifier of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// Returns: If IUP_IGNORE is returned the key is ignored and not processed by
/// the control and not propagated.
/// If returns IUP_CONTINUE, the key will be processed and the event will be
/// propagated to the parent of the element receiving it, this is the default behavior.
/// If returns IUP_DEFAULT the key is processed but it is not propagated.
/// IUP_CLOSE will be processed.
/// Notes Keyboard callbacks depend on the keyboard usage of the control with
/// the focus.
/// So if you return IUP_IGNORE the control will usually not process the key.
/// But be aware that sometimes the control process the key in another event so
/// even returning IUP_IGNORE the key can get processed.
/// Although it will not be propagated.
/// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on
/// the IUP_CONTINUE return value to work while the control is in focus.
/// If the callback does not exists it is automatically propagated to the
/// parent of the element.
/// K_* callbacks All defined keys are also callbacks of any element, called
/// when the respective key is activated.
/// For example: "K_cC" is also a callback activated when the user press
/// Ctrl+C, when the focus is at the element or at a children with focus.
/// This is the way an application can create shortcut keys, also called hot keys.
/// These callbacks are not available in IupLua.
/// Affects All elements with keyboard interaction.
pub const OnKAnyFn = fn (self: *Self, arg0: i32) anyerror!void;
///
/// HELP_CB HELP_CB Action generated when the user press F1 at a control.
/// In Motif is also activated by the Help button in some workstations keyboard.
/// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Returns: IUP_CLOSE will be processed.
/// Affects All elements with user interaction.
pub const OnHelpFn = fn (self: *Self) anyerror!void;
///
/// CLOSE_CB CLOSE_CB Called just before a dialog is closed when the user
/// clicks the close button of the title bar or an equivalent action.
/// Callback int function(Ihandle *ih); [in C] ih:close_cb() -> (ret: number)
/// [in Lua] ih: identifies the element that activated the event.
/// Returns: if IUP_IGNORE, it prevents the dialog from being closed.
/// If you destroy the dialog in this callback, you must return IUP_IGNORE.
/// IUP_CLOSE will be processed.
/// Affects IupDialog
pub const OnCloseFn = fn (self: *Self) anyerror!void;
pub const OnDropMotionFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: [:0]const u8) anyerror!void;
pub const OnDragEndFn = fn (self: *Self, arg0: i32) anyerror!void;
pub const OnDragBeginFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void;
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub const OnMapFn = fn (self: *Self) anyerror!void;
///
/// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also LEAVEWINDOW_CB
pub const OnEnterWindowFn = fn (self: *Self) anyerror!void;
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub const OnDestroyFn = fn (self: *Self) anyerror!void;
pub const OnDropDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: *iup.Unknow, arg2: i32, arg3: i32, arg4: i32) anyerror!void;
///
/// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus.
/// This callback is called before the GETFOCUS_CB of the element that gets the focus.
/// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Affects All elements with user interaction, except menus.
/// In Windows, there are restrictions when using this callback.
/// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any
/// function calls that display or activate a window.
/// This causes the thread to yield control and can cause the application to
/// stop responding to messages.
/// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus
pub const OnKillFocusFn = fn (self: *Self) anyerror!void;
pub const OnDragDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: *iup.Unknow, arg2: i32) anyerror!void;
pub const OnDragDataSizeFn = fn (self: *Self, arg0: [:0]const u8) anyerror!void;
///
/// SHOW_CB SHOW_CB Called right after the dialog is showed, hidden, maximized,
/// minimized or restored from minimized/maximized.
/// This callback is called when those actions were performed by the user or
/// programmatically by the application.
/// Callback int function(Ihandle *ih, int state); [in C] ih:show_cb(state:
/// number) -> (ret: number) [in Lua] ih: identifier of the element that
/// activated the event.
/// state: indicates which of the following situations generated the event:
/// IUP_HIDE (since 3.0) IUP_SHOW IUP_RESTORE (was minimized or maximized)
/// IUP_MINIMIZE IUP_MAXIMIZE (since 3.0) (not received in Motif when activated
/// from the maximize button) Returns: IUP_CLOSE will be processed.
/// Affects IupDialog
pub const OnShowFn = fn (self: *Self, arg0: i32) anyerror!void;
///
/// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control.
/// When several files are dropped at once, the callback is called several
/// times, once for each file.
/// If defined after the element is mapped then the attribute DROPFILESTARGET
/// must be set to YES.
/// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const
/// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename:
/// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the
/// element that activated the event.
/// filename: Name of the dropped file.
/// num: Number index of the dropped file.
/// If several files are dropped, num is the index of the dropped file starting
/// from "total-1" to "0".
/// x: X coordinate of the point where the user released the mouse button.
/// y: Y coordinate of the point where the user released the mouse button.
/// Returns: If IUP_IGNORE is returned the callback will NOT be called for the
/// next dropped files, and the processing of dropped files will be interrupted.
/// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList
pub const OnDropFilesFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: i32, arg3: i32) anyerror!void;
///
/// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed.
/// Callback int function(Ihandle *ih, int width, int height); [in C]
/// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// width: the width of the internal element size in pixels not considering the
/// decorations (client size) height: the height of the internal element size
/// in pixels not considering the decorations (client size) Notes For the
/// dialog, this action is also generated when the dialog is mapped, after the
/// map and before the show.
/// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is
/// hidden/shown after changing the DX or DY attributes from inside the
/// callback, the size of the drawing area will immediately change, so the
/// parameters with and height will be invalid.
/// To update the parameters consult the DRAWSIZE attribute.
/// Also activate the drawing toolkit only after updating the DX or DY attributes.
/// Affects IupCanvas, IupGLCanvas, IupDialog
pub const OnResizeFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void;
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub const OnUnmapFn = fn (self: *Self) anyerror!void;
pub const OnTrayClickFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: i32) anyerror!void;
///
/// When saving a file, the overwrite check is done before the FILE_CB callback
/// is called with status=OK.
/// If the application wants to add an extension to the file name inside the
/// FILE_CB callback when status=OK, then it must manually check if the file
/// with the extension exits and asks the user if the file should be replaced,
/// if not then the callback can set the FILE attribute and returns
/// IUP_CONTINUE, so the file dialog will remain open and the user will have an
/// opportunity to change the file name now that it contains the extension.
pub const OnFileFn = fn (self: *Self, arg0: [:0]const u8, arg1: [:0]const u8) anyerror!void;
///
/// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus.
/// This callback is called after the KILLFOCUS_CB of the element that loosed
/// the focus.
/// The IupGetFocus function during the callback returns the element that
/// loosed the focus.
/// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that received keyboard focus.
/// Affects All elements with user interaction, except menus.
/// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus
pub const OnGetFocusFn = fn (self: *Self) anyerror!void;
pub const OnLDestroyFn = fn (self: *Self) anyerror!void;
///
/// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also ENTERWINDOW_CB
pub const OnLeaveWindowFn = fn (self: *Self) anyerror!void;
pub const OnPostMessageFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: f64, arg3: *iup.Unknow) anyerror!void;
///
/// DIALOGTYPE: Type of dialog (Open, Save or Directory).
/// Can have values "OPEN", "SAVE" or "DIR".
/// Default: "OPEN".
/// In Windows, when DIALOGTYPE=DIR the dialog shown is not the same dialog for
/// OPEN and SAVE, this new dialog does not have the Help button neither filters.
/// Also this new dialog needs CoInitializeEx with COINIT_APARTMENTTHREADED
/// (done in IupOpen), if the COM library was initialized with
/// COINIT_MULTITHREADED prior to IupOpen then the new dialog will have limited functionality.
/// In Motif or GTK the dialog is the same, but it only allows the user to
/// select a directory.
pub const DialogType = enum {
Save,
Dir,
Open,
};
pub const ZOrder = enum {
Top,
Bottom,
};
pub const Expand = enum {
Yes,
Horizontal,
Vertical,
HorizontalFree,
VerticalFree,
No,
};
///
/// STATUS (read-only): Indicates the status of the selection made: "1": New file.
/// "0": Normal, existing file or directory.
/// "-1": Operation cancelled.
pub const Status = enum(i32) {
Normal = 0,
NewFile = 1,
Cancelled = -1,
};
pub const Placement = enum {
Maximized,
Minimized,
Full,
};
pub const Floating = enum {
Yes,
Ignore,
No,
};
pub const Initializer = struct {
last_error: ?anyerror = null,
ref: *Self,
///
/// Returns a pointer to IUP element or an error.
/// Only top-level or detached elements needs to be unwraped,
pub fn unwrap(self: Initializer) !*Self {
if (self.last_error) |e| {
return e;
} else {
return self.ref;
}
}
///
/// Captures a reference into a external variable
/// Allows to capture some references even using full declarative API
pub fn capture(self: *Initializer, ref: **Self) Initializer {
ref.* = self.ref;
return self.*;
}
pub fn setStrAttribute(self: *Initializer, attributeName: [:0]const u8, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
Self.setStrAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setIntAttribute(self: *Initializer, attributeName: [:0]const u8, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
Self.setIntAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setBoolAttribute(self: *Initializer, attributeName: [:0]const u8, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
Self.setBoolAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setPtrAttribute(self: *Initializer, comptime T: type, attributeName: [:0]const u8, value: ?*T) Initializer {
if (self.last_error) |_| return self.*;
Self.setPtrAttribute(self.ref, T, attributeName, value);
return self.*;
}
pub fn setHandle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandle(self.ref, arg);
return self.*;
}
pub fn setHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "HANDLENAME", .{}, arg);
return self.*;
}
pub fn setTipBgColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "TIPBGCOLOR", .{}, rgb);
return self.*;
}
pub fn setMdiClient(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MDICLIENT", .{}, arg);
return self.*;
}
pub fn setControl(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "CONTROL", .{}, arg);
return self.*;
}
pub fn setTipIcon(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TIPICON", .{}, arg);
return self.*;
}
///
/// SHOWPREVIEW: A preview area is shown inside the file dialog.
/// Can have values "YES" or "NO".
/// Default: "NO".
/// In Windows, you must link with the "iup.rc" resource file so the preview
/// area can be enabled (not necessary if using "iup.dll").
/// Valid only if the FILE_CB callback is defined, use it to retrieve the file
/// name and the necessary attributes to paint the preview area.
/// (in Motif since 3.0) Read only attributes that are valid inside the FILE_CB
/// callback when status="PAINT": PREVIEWDC: Returns the Device Context (HDC in
/// Windows and GC in UNIX) PREVIEWWIDTH and PREVIEWHEIGHT: Returns the width
/// and the height of the client rectangle for the preview area.
/// Also the attributes WID, HWND, XWINDOW and XDISPLAY are valid and are
/// relative to the preview area.
/// If the attribute PREVIEWGLCANVAS is defined then it is used as the name of
/// an existent IupGLCanvas control to be mapped internally to the preview canvas.
/// Notice that this is not a fully implemented IupGLCanvas that inherits from IupCanvas.
/// This does the minimum necessary so you can use IupGLCanvas auxiliary
/// functions for the preview canvas and call OpenGL functions.
/// No IupCanvas attributes or callbacks are available.
/// (since 3.0)
pub fn setShowPreview(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "SHOWPREVIEW", .{}, arg);
return self.*;
}
pub fn setMenu(self: *Initializer, arg: *iup.Menu) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "MENU", .{}, arg);
return self.*;
}
pub fn setMenuHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "MENU", .{}, arg);
return self.*;
}
pub fn setNoFlush(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "NOFLUSH", .{}, arg);
return self.*;
}
pub fn setMaxSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "MAXSIZE", .{}, value);
return self.*;
}
pub fn setOpacityImage(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "OPACITYIMAGE", .{}, arg);
return self.*;
}
///
/// NOCHANGEDIR: Indicates if the current working directory must be restored
/// after the user navigation.
/// Default: "YES".
pub fn setNoChangeDir(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "NOCHANGEDIR", .{}, arg);
return self.*;
}
pub fn setHelpButton(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "HELPBUTTON", .{}, arg);
return self.*;
}
pub fn setShowNoFocus(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "SHOWNOFOCUS", .{}, arg);
return self.*;
}
pub fn setOpacity(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "OPACITY", .{}, arg);
return self.*;
}
pub fn setPosition(self: *Initializer, x: i32, y: i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = iup.XYPos.intIntToString(&buffer, x, y, ',');
interop.setStrAttribute(self.ref, "POSITION", .{}, value);
return self.*;
}
pub fn setComposited(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "COMPOSITED", .{}, arg);
return self.*;
}
pub fn setDropFilesTarget(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DROPFILESTARGET", .{}, arg);
return self.*;
}
pub fn setTip(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TIP", .{}, arg);
return self.*;
}
pub fn setCanFocus(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "CANFOCUS", .{}, arg);
return self.*;
}
pub fn setDragSourceMove(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAGSOURCEMOVE", .{}, arg);
return self.*;
}
pub fn setIcon(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "ICON", .{}, arg);
return self.*;
}
pub fn setVisible(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "VISIBLE", .{}, arg);
return self.*;
}
pub fn setCursor(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "CURSOR", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setCursorHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "CURSOR", .{}, arg);
return self.*;
}
pub fn setMenuBox(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MENUBOX", .{}, arg);
return self.*;
}
///
/// DIALOGTYPE: Type of dialog (Open, Save or Directory).
/// Can have values "OPEN", "SAVE" or "DIR".
/// Default: "OPEN".
/// In Windows, when DIALOGTYPE=DIR the dialog shown is not the same dialog for
/// OPEN and SAVE, this new dialog does not have the Help button neither filters.
/// Also this new dialog needs CoInitializeEx with COINIT_APARTMENTTHREADED
/// (done in IupOpen), if the COM library was initialized with
/// COINIT_MULTITHREADED prior to IupOpen then the new dialog will have limited functionality.
/// In Motif or GTK the dialog is the same, but it only allows the user to
/// select a directory.
pub fn setDialogType(self: *Initializer, arg: ?DialogType) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Save => interop.setStrAttribute(self.ref, "DIALOGTYPE", .{}, "SAVE"),
.Dir => interop.setStrAttribute(self.ref, "DIALOGTYPE", .{}, "DIR"),
.Open => interop.setStrAttribute(self.ref, "DIALOGTYPE", .{}, "OPEN"),
} else {
interop.clearAttribute(self.ref, "DIALOGTYPE", .{});
}
return self.*;
}
pub fn zOrder(self: *Initializer, arg: ?ZOrder) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Top => interop.setStrAttribute(self.ref, "ZORDER", .{}, "TOP"),
.Bottom => interop.setStrAttribute(self.ref, "ZORDER", .{}, "BOTTOM"),
} else {
interop.clearAttribute(self.ref, "ZORDER", .{});
}
return self.*;
}
pub fn setHideTitleBar(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "HIDETITLEBAR", .{}, arg);
return self.*;
}
pub fn setMaxBox(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MAXBOX", .{}, arg);
return self.*;
}
pub fn setDragDrop(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAGDROP", .{}, arg);
return self.*;
}
pub fn setDialogHint(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DIALOGHINT", .{}, arg);
return self.*;
}
///
/// ALLOWNEW: Indicates if non-existent file names are accepted.
/// If equals "NO" and the user specifies a non-existing file, an alert dialog
/// is shown.
/// Default: if the dialog is of type "OPEN", default is "NO"; if the dialog is
/// of type "SAVE", default is "YES".
/// Not used when DIALOGTYPE=DIR.
pub fn setAllowNew(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "ALLOWNEW", .{}, arg);
return self.*;
}
pub fn setDialogFrame(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DIALOGFRAME", .{}, arg);
return self.*;
}
pub fn setNActive(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "NACTIVE", .{}, arg);
return self.*;
}
pub fn setTheme(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "THEME", .{}, arg);
return self.*;
}
pub fn setSaveUnder(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "SAVEUNDER", .{}, arg);
return self.*;
}
pub fn setTray(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TRAY", .{}, arg);
return self.*;
}
pub fn setChildOffset(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "CHILDOFFSET", .{}, value);
return self.*;
}
pub fn setExpand(self: *Initializer, arg: ?Expand) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self.ref, "EXPAND", .{}, "YES"),
.Horizontal => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTAL"),
.Vertical => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICAL"),
.HorizontalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTALFREE"),
.VerticalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICALFREE"),
.No => interop.setStrAttribute(self.ref, "EXPAND", .{}, "NO"),
} else {
interop.clearAttribute(self.ref, "EXPAND", .{});
}
return self.*;
}
pub fn setSize(self: *Initializer, width: ?iup.ScreenSize, height: ?iup.ScreenSize) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var str = iup.DialogSize.screenSizeToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "SIZE", .{}, str);
return self.*;
}
pub fn setTipMarkup(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TIPMARKUP", .{}, arg);
return self.*;
}
///
/// EXTDEFAULT: default extension to be used if selected file does not have an extension.
/// The inspected extension will consider to have the same number of characters
/// of the default extension.
/// It must NOT include the period ".".
/// (since 3.18)
pub fn setExtDefault(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "EXTDEFAULT", .{}, arg);
return self.*;
}
pub fn setMdiMenu(self: *Initializer, arg: *iup.Menu) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "MDIMENU", .{}, arg);
return self.*;
}
pub fn setMdiMenuHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "MDIMENU", .{}, arg);
return self.*;
}
pub fn setStartFocus(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "STARTFOCUS", .{}, arg);
return self.*;
}
pub fn setFontSize(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "FONTSIZE", .{}, arg);
return self.*;
}
pub fn setDropTypes(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DROPTYPES", .{}, arg);
return self.*;
}
pub fn setTrayTipMarkup(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TRAYTIPMARKUP", .{}, arg);
return self.*;
}
pub fn setUserSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "USERSIZE", .{}, value);
return self.*;
}
pub fn setTipDelay(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "TIPDELAY", .{}, arg);
return self.*;
}
pub fn setCustomFrame(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "CUSTOMFRAME", .{}, arg);
return self.*;
}
///
/// TITLE: Dialog's title.
pub fn setTitle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TITLE", .{}, arg);
return self.*;
}
pub fn setDefaultEsc(self: *Initializer, arg: *iup.Button) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "DEFAULTESC", .{}, arg);
return self.*;
}
pub fn setDefaultEscHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DEFAULTESC", .{}, arg);
return self.*;
}
pub fn setPlacement(self: *Initializer, arg: ?Placement) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Maximized => interop.setStrAttribute(self.ref, "PLACEMENT", .{}, "MAXIMIZED"),
.Minimized => interop.setStrAttribute(self.ref, "PLACEMENT", .{}, "MINIMIZED"),
.Full => interop.setStrAttribute(self.ref, "PLACEMENT", .{}, "FULL"),
} else {
interop.clearAttribute(self.ref, "PLACEMENT", .{});
}
return self.*;
}
///
/// EXTFILTER [Windows and GTK Only]: Defines several file filters.
/// It has priority over FILTERINFO and FILTER.
/// Must be a text with the format "FilterInfo1|Filter1|FilterInfo2|Filter2|...".
/// The list ends with character '|'.
/// Example: "Text files|*.txt;*.doc|Image files|*.gif;*.jpg;*.bmp|".
/// In GTK there is no way how to overwrite the filters, so it is recommended
/// to always add a less restrictive filter to the filter list, for example
/// "All Files|*.*".
pub fn setExtFilter(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "EXTFILTER", .{}, arg);
return self.*;
}
pub fn setPropagateFocus(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "PROPAGATEFOCUS", .{}, arg);
return self.*;
}
pub fn setBgColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "BGCOLOR", .{}, rgb);
return self.*;
}
pub fn setDropTarget(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DROPTARGET", .{}, arg);
return self.*;
}
pub fn setDragSource(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAGSOURCE", .{}, arg);
return self.*;
}
pub fn setResize(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "RESIZE", .{}, arg);
return self.*;
}
pub fn setFloating(self: *Initializer, arg: ?Floating) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self.ref, "FLOATING", .{}, "YES"),
.Ignore => interop.setStrAttribute(self.ref, "FLOATING", .{}, "IGNORE"),
.No => interop.setStrAttribute(self.ref, "FLOATING", .{}, "NO"),
} else {
interop.clearAttribute(self.ref, "FLOATING", .{});
}
return self.*;
}
pub fn setNormalizerGroup(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NORMALIZERGROUP", .{}, arg);
return self.*;
}
pub fn setRasterSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "RASTERSIZE", .{}, value);
return self.*;
}
pub fn setShapeImage(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "SHAPEIMAGE", .{}, arg);
return self.*;
}
pub fn setTipFgColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "TIPFGCOLOR", .{}, rgb);
return self.*;
}
pub fn setFontFace(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONTFACE", .{}, arg);
return self.*;
}
pub fn topMost(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TOPMOST", .{}, arg);
return self.*;
}
pub fn setName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NAME", .{}, arg);
return self.*;
}
pub fn setMinBox(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MINBOX", .{}, arg);
return self.*;
}
pub fn setDefaultEnter(self: *Initializer, arg: *iup.Button) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "DEFAULTENTER", .{}, arg);
return self.*;
}
pub fn setDefaultEnterHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DEFAULTENTER", .{}, arg);
return self.*;
}
///
/// PARENTDIALOG: Makes the dialog be treated as a child of the specified dialog.
pub fn setParentDialog(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Dialog, arg)) {
interop.setHandleAttribute(self.ref, "PARENTDIALOG", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setParentDialogHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "PARENTDIALOG", .{}, arg);
return self.*;
}
pub fn setBackground(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "BACKGROUND", .{}, rgb);
return self.*;
}
pub fn setHideTaskbar(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "HIDETASKBAR", .{}, arg);
return self.*;
}
///
/// FILTER: String containing a list of file filters separated by ';' without spaces.
/// Example: "*.C;*.LED;test.*".
/// In Motif only the first filter is used.
pub fn setFilter(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FILTER", .{}, arg);
return self.*;
}
pub fn setBringFront(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "BRINGFRONT", .{}, arg);
return self.*;
}
pub fn setTrayImage(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "TRAYIMAGE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setTrayImageHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TRAYIMAGE", .{}, arg);
return self.*;
}
pub fn setActive(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "ACTIVE", .{}, arg);
return self.*;
}
pub fn setTipVisible(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TIPVISIBLE", .{}, arg);
return self.*;
}
pub fn setExpandWeight(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "EXPANDWEIGHT", .{}, arg);
return self.*;
}
pub fn setMinSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "MINSIZE", .{}, value);
return self.*;
}
pub fn setNTheme(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NTHEME", .{}, arg);
return self.*;
}
pub fn setBorder(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "BORDER", .{}, arg);
return self.*;
}
pub fn setCustomFramesImulate(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "CUSTOMFRAMESIMULATE", .{}, arg);
return self.*;
}
pub fn setShrink(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "SHRINK", .{}, arg);
return self.*;
}
pub fn setClientSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "CLIENTSIZE", .{}, value);
return self.*;
}
pub fn setTrayTip(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TRAYTIP", .{}, arg);
return self.*;
}
pub fn setDragTypes(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DRAGTYPES", .{}, arg);
return self.*;
}
pub fn setToolBox(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TOOLBOX", .{}, arg);
return self.*;
}
pub fn setMdiFrame(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MDIFRAME", .{}, arg);
return self.*;
}
///
/// NOOVERWRITEPROMPT: do not prompt to overwrite an existent file when in
/// "SAVE" dialog.
/// Default is "NO", i.e.
/// prompt before overwrite.
/// (GTK 2.8)
pub fn setNoOverwritePrompt(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "NOOVERWRITEPROMPT", .{}, arg);
return self.*;
}
pub fn setFontStyle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONTSTYLE", .{}, arg);
return self.*;
}
///
/// DIRECTORY: Initial directory.
/// When consulted after the dialog is closed and the user pressed the OK
/// button, it will contain the directory of the selected file.
/// When set the last separator does not need to be specified, but when get the
/// returned value will always contains the last separator.
/// In Motif or GTK, if not defined, the dialog opens in the current directory.
/// In Windows, if not defined and the application has used the dialog in the
/// past, the path most recently used is selected as the initial directory.
/// However, if an application is not run for a long time, its saved selected
/// path is discarded.
/// Also if not defined and the current directory contains any files of the
/// specified filter types, the initial directory is the current directory.
/// Otherwise, the initial directory is the "My Documents" directory of the
/// current user.
/// Otherwise, the initial directory is the Desktop folder.
/// In Windows, the FILE and the DIRECTORY attributes also accept strings
/// containing "/" as path separators, but the VALUE attribute will always
/// return strings using the "\" character.
pub fn setDirectory(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DIRECTORY", .{}, arg);
return self.*;
}
pub fn setMdiChild(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MDICHILD", .{}, arg);
return self.*;
}
pub fn fullScreen(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "FULLSCREEN", .{}, arg);
return self.*;
}
pub fn setNativeParent(self: *Initializer, arg: anytype) !Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "NATIVEPARENT", .{}, arg);
return self.*;
}
pub fn setNativeParentHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NATIVEPARENT", .{}, arg);
return self.*;
}
pub fn setFont(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONT", .{}, arg);
return self.*;
}
pub fn simulateModal(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "SIMULATEMODAL", .{}, arg);
return self.*;
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabImage(self: *Initializer, index: i32, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "TABIMAGE", .{index}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setTabImageHandleName(self: *Initializer, index: i32, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TABIMAGE", .{index}, arg);
return self.*;
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabTitle(self: *Initializer, index: i32, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TABTITLE", .{index}, arg);
return self.*;
}
pub fn setFocusCallback(self: *Initializer, callback: ?OnFocusFn) Initializer {
const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// K_ANY K_ANY Action generated when a keyboard event occurs.
/// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) ->
/// (ret: number) [in Lua] ih: identifier of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// Returns: If IUP_IGNORE is returned the key is ignored and not processed by
/// the control and not propagated.
/// If returns IUP_CONTINUE, the key will be processed and the event will be
/// propagated to the parent of the element receiving it, this is the default behavior.
/// If returns IUP_DEFAULT the key is processed but it is not propagated.
/// IUP_CLOSE will be processed.
/// Notes Keyboard callbacks depend on the keyboard usage of the control with
/// the focus.
/// So if you return IUP_IGNORE the control will usually not process the key.
/// But be aware that sometimes the control process the key in another event so
/// even returning IUP_IGNORE the key can get processed.
/// Although it will not be propagated.
/// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on
/// the IUP_CONTINUE return value to work while the control is in focus.
/// If the callback does not exists it is automatically propagated to the
/// parent of the element.
/// K_* callbacks All defined keys are also callbacks of any element, called
/// when the respective key is activated.
/// For example: "K_cC" is also a callback activated when the user press
/// Ctrl+C, when the focus is at the element or at a children with focus.
/// This is the way an application can create shortcut keys, also called hot keys.
/// These callbacks are not available in IupLua.
/// Affects All elements with keyboard interaction.
pub fn setKAnyCallback(self: *Initializer, callback: ?OnKAnyFn) Initializer {
const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// HELP_CB HELP_CB Action generated when the user press F1 at a control.
/// In Motif is also activated by the Help button in some workstations keyboard.
/// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Returns: IUP_CLOSE will be processed.
/// Affects All elements with user interaction.
pub fn setHelpCallback(self: *Initializer, callback: ?OnHelpFn) Initializer {
const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// CLOSE_CB CLOSE_CB Called just before a dialog is closed when the user
/// clicks the close button of the title bar or an equivalent action.
/// Callback int function(Ihandle *ih); [in C] ih:close_cb() -> (ret: number)
/// [in Lua] ih: identifies the element that activated the event.
/// Returns: if IUP_IGNORE, it prevents the dialog from being closed.
/// If you destroy the dialog in this callback, you must return IUP_IGNORE.
/// IUP_CLOSE will be processed.
/// Affects IupDialog
pub fn setCloseCallback(self: *Initializer, callback: ?OnCloseFn) Initializer {
const Handler = CallbackHandler(Self, OnCloseFn, "CLOSE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDropMotionCallback(self: *Initializer, callback: ?OnDropMotionFn) Initializer {
const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragEndCallback(self: *Initializer, callback: ?OnDragEndFn) Initializer {
const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragBeginCallback(self: *Initializer, callback: ?OnDragBeginFn) Initializer {
const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setMapCallback(self: *Initializer, callback: ?OnMapFn) Initializer {
const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also LEAVEWINDOW_CB
pub fn setEnterWindowCallback(self: *Initializer, callback: ?OnEnterWindowFn) Initializer {
const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub fn setDestroyCallback(self: *Initializer, callback: ?OnDestroyFn) Initializer {
const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDropDataCallback(self: *Initializer, callback: ?OnDropDataFn) Initializer {
const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus.
/// This callback is called before the GETFOCUS_CB of the element that gets the focus.
/// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Affects All elements with user interaction, except menus.
/// In Windows, there are restrictions when using this callback.
/// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any
/// function calls that display or activate a window.
/// This causes the thread to yield control and can cause the application to
/// stop responding to messages.
/// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setKillFocusCallback(self: *Initializer, callback: ?OnKillFocusFn) Initializer {
const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragDataCallback(self: *Initializer, callback: ?OnDragDataFn) Initializer {
const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragDataSizeCallback(self: *Initializer, callback: ?OnDragDataSizeFn) Initializer {
const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// SHOW_CB SHOW_CB Called right after the dialog is showed, hidden, maximized,
/// minimized or restored from minimized/maximized.
/// This callback is called when those actions were performed by the user or
/// programmatically by the application.
/// Callback int function(Ihandle *ih, int state); [in C] ih:show_cb(state:
/// number) -> (ret: number) [in Lua] ih: identifier of the element that
/// activated the event.
/// state: indicates which of the following situations generated the event:
/// IUP_HIDE (since 3.0) IUP_SHOW IUP_RESTORE (was minimized or maximized)
/// IUP_MINIMIZE IUP_MAXIMIZE (since 3.0) (not received in Motif when activated
/// from the maximize button) Returns: IUP_CLOSE will be processed.
/// Affects IupDialog
pub fn setShowCallback(self: *Initializer, callback: ?OnShowFn) Initializer {
const Handler = CallbackHandler(Self, OnShowFn, "SHOW_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control.
/// When several files are dropped at once, the callback is called several
/// times, once for each file.
/// If defined after the element is mapped then the attribute DROPFILESTARGET
/// must be set to YES.
/// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const
/// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename:
/// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the
/// element that activated the event.
/// filename: Name of the dropped file.
/// num: Number index of the dropped file.
/// If several files are dropped, num is the index of the dropped file starting
/// from "total-1" to "0".
/// x: X coordinate of the point where the user released the mouse button.
/// y: Y coordinate of the point where the user released the mouse button.
/// Returns: If IUP_IGNORE is returned the callback will NOT be called for the
/// next dropped files, and the processing of dropped files will be interrupted.
/// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList
pub fn setDropFilesCallback(self: *Initializer, callback: ?OnDropFilesFn) Initializer {
const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed.
/// Callback int function(Ihandle *ih, int width, int height); [in C]
/// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// width: the width of the internal element size in pixels not considering the
/// decorations (client size) height: the height of the internal element size
/// in pixels not considering the decorations (client size) Notes For the
/// dialog, this action is also generated when the dialog is mapped, after the
/// map and before the show.
/// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is
/// hidden/shown after changing the DX or DY attributes from inside the
/// callback, the size of the drawing area will immediately change, so the
/// parameters with and height will be invalid.
/// To update the parameters consult the DRAWSIZE attribute.
/// Also activate the drawing toolkit only after updating the DX or DY attributes.
/// Affects IupCanvas, IupGLCanvas, IupDialog
pub fn setResizeCallback(self: *Initializer, callback: ?OnResizeFn) Initializer {
const Handler = CallbackHandler(Self, OnResizeFn, "RESIZE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setUnmapCallback(self: *Initializer, callback: ?OnUnmapFn) Initializer {
const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setTrayClickCallback(self: *Initializer, callback: ?OnTrayClickFn) Initializer {
const Handler = CallbackHandler(Self, OnTrayClickFn, "TRAYCLICK_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// When saving a file, the overwrite check is done before the FILE_CB callback
/// is called with status=OK.
/// If the application wants to add an extension to the file name inside the
/// FILE_CB callback when status=OK, then it must manually check if the file
/// with the extension exits and asks the user if the file should be replaced,
/// if not then the callback can set the FILE attribute and returns
/// IUP_CONTINUE, so the file dialog will remain open and the user will have an
/// opportunity to change the file name now that it contains the extension.
pub fn setFileCallback(self: *Initializer, callback: ?OnFileFn) Initializer {
const Handler = CallbackHandler(Self, OnFileFn, "FILE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus.
/// This callback is called after the KILLFOCUS_CB of the element that loosed
/// the focus.
/// The IupGetFocus function during the callback returns the element that
/// loosed the focus.
/// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that received keyboard focus.
/// Affects All elements with user interaction, except menus.
/// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setGetFocusCallback(self: *Initializer, callback: ?OnGetFocusFn) Initializer {
const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setLDestroyCallback(self: *Initializer, callback: ?OnLDestroyFn) Initializer {
const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also ENTERWINDOW_CB
pub fn setLeaveWindowCallback(self: *Initializer, callback: ?OnLeaveWindowFn) Initializer {
const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setPostMessageCallback(self: *Initializer, callback: ?OnPostMessageFn) Initializer {
const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
};
pub fn setStrAttribute(self: *Self, attribute: [:0]const u8, arg: [:0]const u8) void {
interop.setStrAttribute(self, attribute, .{}, arg);
}
pub fn getStrAttribute(self: *Self, attribute: [:0]const u8) [:0]const u8 {
return interop.getStrAttribute(self, attribute, .{});
}
pub fn setIntAttribute(self: *Self, attribute: [:0]const u8, arg: i32) void {
interop.setIntAttribute(self, attribute, .{}, arg);
}
pub fn getIntAttribute(self: *Self, attribute: [:0]const u8) i32 {
return interop.getIntAttribute(self, attribute, .{});
}
pub fn setBoolAttribute(self: *Self, attribute: [:0]const u8, arg: bool) void {
interop.setBoolAttribute(self, attribute, .{}, arg);
}
pub fn getBoolAttribute(self: *Self, attribute: [:0]const u8) bool {
return interop.getBoolAttribute(self, attribute, .{});
}
pub fn getPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8) ?*T {
return interop.getPtrAttribute(T, self, attribute, .{});
}
pub fn setPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8, value: ?*T) void {
interop.setPtrAttribute(T, self, attribute, .{}, value);
}
pub fn setHandle(self: *Self, arg: [:0]const u8) void {
interop.setHandle(self, arg);
}
pub fn fromHandleName(handle_name: [:0]const u8) ?*Self {
return interop.fromHandleName(Self, handle_name);
}
///
/// Creates an interface element given its class name and parameters.
/// After creation the element still needs to be attached to a container and mapped to the native system so it can be visible.
pub fn init() Initializer {
var handle = interop.create(Self);
if (handle) |valid| {
return .{
.ref = @ptrCast(*Self, valid),
};
} else {
return .{ .ref = undefined, .last_error = Error.NotInitialized };
}
}
///
/// Displays a dialog in the current position, or changes a control VISIBLE attribute.
/// For dialogs it is equivalent to call IupShowXY using IUP_CURRENT. See IupShowXY for more details.
/// For other controls, to call IupShow is the same as setting VISIBLE=YES.
pub fn show(self: *Self) !void {
try interop.show(self);
}
///
/// Hides an interface element. This function has the same effect as attributing value "NO" to the interface element’s VISIBLE attribute.
/// Once a dialog is hidden, either by means of IupHide or by changing the VISIBLE attribute or by means of a click in the window close button, the elements inside this dialog are not destroyed, so that you can show the dialog again. To destroy dialogs, the IupDestroy function must be called.
pub fn hide(self: *Self) void {
interop.hide(self);
}
///
/// Destroys an interface element and all its children.
/// Only dialogs, timers, popup menus and images should be normally destroyed, but detached elements can also be destroyed.
pub fn deinit(self: *Self) void {
interop.destroy(self);
}
///
/// Creates (maps) the native interface objects corresponding to the given IUP interface elements.
/// It will also called recursively to create the native element of all the children in the element's tree.
/// The element must be already attached to a mapped container, except the dialog. A child can only be mapped if its parent is already mapped.
/// This function is automatically called before the dialog is shown in IupShow, IupShowXY or IupPopup.
/// If the element is a dialog then the abstract layout will be updated even if the dialog is already mapped. If the dialog is visible the elements will be immediately repositioned. Calling IupMap for an already mapped dialog is the same as only calling IupRefresh for the dialog.
/// Calling IupMap for an already mapped element that is not a dialog does nothing.
/// If you add new elements to an already mapped dialog you must call IupMap for that elements. And then call IupRefresh to update the dialog layout.
/// If the WID attribute of an element is NULL, it means the element was not already mapped. Some containers do not have a native element associated, like VBOX and HBOX. In this case their WID is a fake value (void*)(-1).
/// It is useful for the application to call IupMap when the value of the WID attribute must be known, i.e. the native element must exist, before a dialog is made visible.
/// The MAP_CB callback is called at the end of the IupMap function, after all processing, so it can also be used to create other things that depend on the WID attribute. But notice that for non dialog elements it will be called before the dialog layout has been updated, so the element current size will still be 0x0 (since 3.14).
pub fn map(self: *Self) !void {
try interop.map(self);
}
pub fn popup(self: *Self, x: iup.DialogPosX, y: iup.DialogPosY) !void {
try interop.popup(self, x, y);
}
pub fn showXY(self: *Self, x: iup.DialogPosX, y: iup.DialogPosY) !void {
try interop.showXY(self, x, y);
}
///
/// Returns the the child element that has the NAME attribute equals to the given value on the same dialog hierarchy.
/// Works also for children of a menu that is associated with a dialog.
pub fn getDialogChild(self: *Self, byName: [:0]const u8) ?Element {
return interop.getDialogChild(self, byName);
}
///
/// Updates the size and layout of all controls in the same dialog.
/// To be used after changing size attributes, or attributes that affect the size of the control. Can be used for any element inside a dialog, but the layout of the dialog and all controls will be updated. It can change the layout of all the controls inside the dialog because of the dynamic layout positioning.
pub fn refresh(self: *Self) void {
Impl(Self).refresh(self);
}
pub fn getHandleName(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "HANDLENAME", .{});
}
pub fn setHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "HANDLENAME", .{}, arg);
}
pub fn getTipBgColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "TIPBGCOLOR", .{});
}
pub fn setTipBgColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "TIPBGCOLOR", .{}, rgb);
}
pub fn getMdiClient(self: *Self) bool {
return interop.getBoolAttribute(self, "MDICLIENT", .{});
}
pub fn setMdiClient(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "MDICLIENT", .{}, arg);
}
pub fn getControl(self: *Self) bool {
return interop.getBoolAttribute(self, "CONTROL", .{});
}
pub fn setControl(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "CONTROL", .{}, arg);
}
pub fn getTipIcon(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TIPICON", .{});
}
pub fn setTipIcon(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TIPICON", .{}, arg);
}
///
/// SHOWPREVIEW: A preview area is shown inside the file dialog.
/// Can have values "YES" or "NO".
/// Default: "NO".
/// In Windows, you must link with the "iup.rc" resource file so the preview
/// area can be enabled (not necessary if using "iup.dll").
/// Valid only if the FILE_CB callback is defined, use it to retrieve the file
/// name and the necessary attributes to paint the preview area.
/// (in Motif since 3.0) Read only attributes that are valid inside the FILE_CB
/// callback when status="PAINT": PREVIEWDC: Returns the Device Context (HDC in
/// Windows and GC in UNIX) PREVIEWWIDTH and PREVIEWHEIGHT: Returns the width
/// and the height of the client rectangle for the preview area.
/// Also the attributes WID, HWND, XWINDOW and XDISPLAY are valid and are
/// relative to the preview area.
/// If the attribute PREVIEWGLCANVAS is defined then it is used as the name of
/// an existent IupGLCanvas control to be mapped internally to the preview canvas.
/// Notice that this is not a fully implemented IupGLCanvas that inherits from IupCanvas.
/// This does the minimum necessary so you can use IupGLCanvas auxiliary
/// functions for the preview canvas and call OpenGL functions.
/// No IupCanvas attributes or callbacks are available.
/// (since 3.0)
pub fn getShowPreview(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "SHOWPREVIEW", .{});
}
///
/// SHOWPREVIEW: A preview area is shown inside the file dialog.
/// Can have values "YES" or "NO".
/// Default: "NO".
/// In Windows, you must link with the "iup.rc" resource file so the preview
/// area can be enabled (not necessary if using "iup.dll").
/// Valid only if the FILE_CB callback is defined, use it to retrieve the file
/// name and the necessary attributes to paint the preview area.
/// (in Motif since 3.0) Read only attributes that are valid inside the FILE_CB
/// callback when status="PAINT": PREVIEWDC: Returns the Device Context (HDC in
/// Windows and GC in UNIX) PREVIEWWIDTH and PREVIEWHEIGHT: Returns the width
/// and the height of the client rectangle for the preview area.
/// Also the attributes WID, HWND, XWINDOW and XDISPLAY are valid and are
/// relative to the preview area.
/// If the attribute PREVIEWGLCANVAS is defined then it is used as the name of
/// an existent IupGLCanvas control to be mapped internally to the preview canvas.
/// Notice that this is not a fully implemented IupGLCanvas that inherits from IupCanvas.
/// This does the minimum necessary so you can use IupGLCanvas auxiliary
/// functions for the preview canvas and call OpenGL functions.
/// No IupCanvas attributes or callbacks are available.
/// (since 3.0)
pub fn setShowPreview(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "SHOWPREVIEW", .{}, arg);
}
pub fn getMenu(self: *Self) ?*iup.Menu {
if (interop.getHandleAttribute(self, "MENU", .{})) |handle| {
return @ptrCast(*iup.Menu, handle);
} else {
return null;
}
}
pub fn setMenu(self: *Self, arg: *iup.Menu) void {
interop.setHandleAttribute(self, "MENU", .{}, arg);
}
pub fn setMenuHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "MENU", .{}, arg);
}
pub fn getNoFlush(self: *Self) bool {
return interop.getBoolAttribute(self, "NOFLUSH", .{});
}
pub fn setNoFlush(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "NOFLUSH", .{}, arg);
}
pub fn getMaxSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "MAXSIZE", .{});
return Size.parse(str);
}
pub fn setMaxSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "MAXSIZE", .{}, value);
}
pub fn getOpacityImage(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "OPACITYIMAGE", .{});
}
pub fn setOpacityImage(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "OPACITYIMAGE", .{}, arg);
}
///
/// NOCHANGEDIR: Indicates if the current working directory must be restored
/// after the user navigation.
/// Default: "YES".
pub fn getNoChangeDir(self: *Self) bool {
return interop.getBoolAttribute(self, "NOCHANGEDIR", .{});
}
///
/// NOCHANGEDIR: Indicates if the current working directory must be restored
/// after the user navigation.
/// Default: "YES".
pub fn setNoChangeDir(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "NOCHANGEDIR", .{}, arg);
}
pub fn getHelpButton(self: *Self) bool {
return interop.getBoolAttribute(self, "HELPBUTTON", .{});
}
pub fn setHelpButton(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "HELPBUTTON", .{}, arg);
}
pub fn getShowNoFocus(self: *Self) bool {
return interop.getBoolAttribute(self, "SHOWNOFOCUS", .{});
}
pub fn setShowNoFocus(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "SHOWNOFOCUS", .{}, arg);
}
pub fn getScreenPosition(self: *Self) iup.XYPos {
var str = interop.getStrAttribute(self, "SCREENPOSITION", .{});
return iup.XYPos.parse(str, ',');
}
pub fn getOpacity(self: *Self) i32 {
return interop.getIntAttribute(self, "OPACITY", .{});
}
pub fn setOpacity(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "OPACITY", .{}, arg);
}
pub fn getPosition(self: *Self) iup.XYPos {
var str = interop.getStrAttribute(self, "POSITION", .{});
return iup.XYPos.parse(str, ',');
}
pub fn setPosition(self: *Self, x: i32, y: i32) void {
var buffer: [128]u8 = undefined;
var value = iup.XYPos.intIntToString(&buffer, x, y, ',');
interop.setStrAttribute(self, "POSITION", .{}, value);
}
pub fn getComposited(self: *Self) bool {
return interop.getBoolAttribute(self, "COMPOSITED", .{});
}
pub fn setComposited(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "COMPOSITED", .{}, arg);
}
pub fn getDropFilesTarget(self: *Self) bool {
return interop.getBoolAttribute(self, "DROPFILESTARGET", .{});
}
pub fn setDropFilesTarget(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DROPFILESTARGET", .{}, arg);
}
pub fn getBorderSize(self: *Self) i32 {
return interop.getIntAttribute(self, "BORDERSIZE", .{});
}
pub fn getTip(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TIP", .{});
}
pub fn setTip(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TIP", .{}, arg);
}
pub fn getCanFocus(self: *Self) bool {
return interop.getBoolAttribute(self, "CANFOCUS", .{});
}
pub fn setCanFocus(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "CANFOCUS", .{}, arg);
}
pub fn getDragSourceMove(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAGSOURCEMOVE", .{});
}
pub fn setDragSourceMove(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAGSOURCEMOVE", .{}, arg);
}
pub fn getIcon(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "ICON", .{});
}
pub fn setIcon(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "ICON", .{}, arg);
}
pub fn getVisible(self: *Self) bool {
return interop.getBoolAttribute(self, "VISIBLE", .{});
}
pub fn setVisible(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "VISIBLE", .{}, arg);
}
pub fn getCursor(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "CURSOR", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setCursor(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "CURSOR", .{}, arg);
}
pub fn setCursorHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "CURSOR", .{}, arg);
}
pub fn getMenuBox(self: *Self) bool {
return interop.getBoolAttribute(self, "MENUBOX", .{});
}
pub fn setMenuBox(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "MENUBOX", .{}, arg);
}
///
/// DIALOGTYPE: Type of dialog (Open, Save or Directory).
/// Can have values "OPEN", "SAVE" or "DIR".
/// Default: "OPEN".
/// In Windows, when DIALOGTYPE=DIR the dialog shown is not the same dialog for
/// OPEN and SAVE, this new dialog does not have the Help button neither filters.
/// Also this new dialog needs CoInitializeEx with COINIT_APARTMENTTHREADED
/// (done in IupOpen), if the COM library was initialized with
/// COINIT_MULTITHREADED prior to IupOpen then the new dialog will have limited functionality.
/// In Motif or GTK the dialog is the same, but it only allows the user to
/// select a directory.
pub fn getDialogType(self: *Self) ?DialogType {
var ret = interop.getStrAttribute(self, "DIALOGTYPE", .{});
if (std.ascii.eqlIgnoreCase("SAVE", ret)) return .Save;
if (std.ascii.eqlIgnoreCase("DIR", ret)) return .Dir;
if (std.ascii.eqlIgnoreCase("OPEN", ret)) return .Open;
return null;
}
///
/// DIALOGTYPE: Type of dialog (Open, Save or Directory).
/// Can have values "OPEN", "SAVE" or "DIR".
/// Default: "OPEN".
/// In Windows, when DIALOGTYPE=DIR the dialog shown is not the same dialog for
/// OPEN and SAVE, this new dialog does not have the Help button neither filters.
/// Also this new dialog needs CoInitializeEx with COINIT_APARTMENTTHREADED
/// (done in IupOpen), if the COM library was initialized with
/// COINIT_MULTITHREADED prior to IupOpen then the new dialog will have limited functionality.
/// In Motif or GTK the dialog is the same, but it only allows the user to
/// select a directory.
pub fn setDialogType(self: *Self, arg: ?DialogType) void {
if (arg) |value| switch (value) {
.Save => interop.setStrAttribute(self, "DIALOGTYPE", .{}, "SAVE"),
.Dir => interop.setStrAttribute(self, "DIALOGTYPE", .{}, "DIR"),
.Open => interop.setStrAttribute(self, "DIALOGTYPE", .{}, "OPEN"),
} else {
interop.clearAttribute(self, "DIALOGTYPE", .{});
}
}
pub fn zOrder(self: *Self, arg: ?ZOrder) void {
if (arg) |value| switch (value) {
.Top => interop.setStrAttribute(self, "ZORDER", .{}, "TOP"),
.Bottom => interop.setStrAttribute(self, "ZORDER", .{}, "BOTTOM"),
} else {
interop.clearAttribute(self, "ZORDER", .{});
}
}
pub fn getX(self: *Self) i32 {
return interop.getIntAttribute(self, "X", .{});
}
pub fn getY(self: *Self) i32 {
return interop.getIntAttribute(self, "Y", .{});
}
pub fn getHideTitleBar(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "HIDETITLEBAR", .{});
}
pub fn setHideTitleBar(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "HIDETITLEBAR", .{}, arg);
}
pub fn getMaxBox(self: *Self) bool {
return interop.getBoolAttribute(self, "MAXBOX", .{});
}
pub fn setMaxBox(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "MAXBOX", .{}, arg);
}
pub fn getDragDrop(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAGDROP", .{});
}
pub fn setDragDrop(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAGDROP", .{}, arg);
}
pub fn getDialogHint(self: *Self) bool {
return interop.getBoolAttribute(self, "DIALOGHINT", .{});
}
pub fn setDialogHint(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DIALOGHINT", .{}, arg);
}
///
/// ALLOWNEW: Indicates if non-existent file names are accepted.
/// If equals "NO" and the user specifies a non-existing file, an alert dialog
/// is shown.
/// Default: if the dialog is of type "OPEN", default is "NO"; if the dialog is
/// of type "SAVE", default is "YES".
/// Not used when DIALOGTYPE=DIR.
pub fn getAllowNew(self: *Self) bool {
return interop.getBoolAttribute(self, "ALLOWNEW", .{});
}
///
/// ALLOWNEW: Indicates if non-existent file names are accepted.
/// If equals "NO" and the user specifies a non-existing file, an alert dialog
/// is shown.
/// Default: if the dialog is of type "OPEN", default is "NO"; if the dialog is
/// of type "SAVE", default is "YES".
/// Not used when DIALOGTYPE=DIR.
pub fn setAllowNew(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "ALLOWNEW", .{}, arg);
}
pub fn getDialogFrame(self: *Self) bool {
return interop.getBoolAttribute(self, "DIALOGFRAME", .{});
}
pub fn setDialogFrame(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DIALOGFRAME", .{}, arg);
}
pub fn getNActive(self: *Self) bool {
return interop.getBoolAttribute(self, "NACTIVE", .{});
}
pub fn setNActive(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "NACTIVE", .{}, arg);
}
pub fn getTheme(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "THEME", .{});
}
pub fn setTheme(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "THEME", .{}, arg);
}
pub fn getSaveUnder(self: *Self) bool {
return interop.getBoolAttribute(self, "SAVEUNDER", .{});
}
pub fn setSaveUnder(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "SAVEUNDER", .{}, arg);
}
pub fn getTray(self: *Self) bool {
return interop.getBoolAttribute(self, "TRAY", .{});
}
pub fn setTray(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "TRAY", .{}, arg);
}
pub fn getChildOffset(self: *Self) Size {
var str = interop.getStrAttribute(self, "CHILDOFFSET", .{});
return Size.parse(str);
}
pub fn setChildOffset(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "CHILDOFFSET", .{}, value);
}
pub fn getExpand(self: *Self) ?Expand {
var ret = interop.getStrAttribute(self, "EXPAND", .{});
if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes;
if (std.ascii.eqlIgnoreCase("HORIZONTAL", ret)) return .Horizontal;
if (std.ascii.eqlIgnoreCase("VERTICAL", ret)) return .Vertical;
if (std.ascii.eqlIgnoreCase("HORIZONTALFREE", ret)) return .HorizontalFree;
if (std.ascii.eqlIgnoreCase("VERTICALFREE", ret)) return .VerticalFree;
if (std.ascii.eqlIgnoreCase("NO", ret)) return .No;
return null;
}
pub fn setExpand(self: *Self, arg: ?Expand) void {
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self, "EXPAND", .{}, "YES"),
.Horizontal => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTAL"),
.Vertical => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICAL"),
.HorizontalFree => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTALFREE"),
.VerticalFree => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICALFREE"),
.No => interop.setStrAttribute(self, "EXPAND", .{}, "NO"),
} else {
interop.clearAttribute(self, "EXPAND", .{});
}
}
pub fn getSize(self: *Self) iup.DialogSize {
var str = interop.getStrAttribute(self, "SIZE", .{});
return iup.DialogSize.parse(str);
}
pub fn setSize(self: *Self, width: ?iup.ScreenSize, height: ?iup.ScreenSize) void {
var buffer: [128]u8 = undefined;
var str = iup.DialogSize.screenSizeToString(&buffer, width, height);
interop.setStrAttribute(self, "SIZE", .{}, str);
}
pub fn getWId(self: *Self) i32 {
return interop.getIntAttribute(self, "WID", .{});
}
///
/// STATUS (read-only): Indicates the status of the selection made: "1": New file.
/// "0": Normal, existing file or directory.
/// "-1": Operation cancelled.
pub fn getStatus(self: *Self) Status {
var ret = interop.getIntAttribute(self, "STATUS", .{});
return @intToEnum(Status, ret);
}
pub fn getTipMarkup(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TIPMARKUP", .{});
}
pub fn setTipMarkup(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TIPMARKUP", .{}, arg);
}
///
/// EXTDEFAULT: default extension to be used if selected file does not have an extension.
/// The inspected extension will consider to have the same number of characters
/// of the default extension.
/// It must NOT include the period ".".
/// (since 3.18)
pub fn getExtDefault(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "EXTDEFAULT", .{});
}
///
/// EXTDEFAULT: default extension to be used if selected file does not have an extension.
/// The inspected extension will consider to have the same number of characters
/// of the default extension.
/// It must NOT include the period ".".
/// (since 3.18)
pub fn setExtDefault(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "EXTDEFAULT", .{}, arg);
}
pub fn getMdiMenu(self: *Self) ?*iup.Menu {
if (interop.getHandleAttribute(self, "MDIMENU", .{})) |handle| {
return @ptrCast(*iup.Menu, handle);
} else {
return null;
}
}
pub fn setMdiMenu(self: *Self, arg: *iup.Menu) void {
interop.setHandleAttribute(self, "MDIMENU", .{}, arg);
}
pub fn setMdiMenuHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "MDIMENU", .{}, arg);
}
pub fn getStartFocus(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "STARTFOCUS", .{});
}
pub fn setStartFocus(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "STARTFOCUS", .{}, arg);
}
pub fn getFontSize(self: *Self) i32 {
return interop.getIntAttribute(self, "FONTSIZE", .{});
}
pub fn setFontSize(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "FONTSIZE", .{}, arg);
}
pub fn getNaturalSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "NATURALSIZE", .{});
return Size.parse(str);
}
pub fn getDropTypes(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "DROPTYPES", .{});
}
pub fn setDropTypes(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DROPTYPES", .{}, arg);
}
pub fn getTrayTipMarkup(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TRAYTIPMARKUP", .{});
}
pub fn setTrayTipMarkup(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TRAYTIPMARKUP", .{}, arg);
}
pub fn getUserSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "USERSIZE", .{});
return Size.parse(str);
}
pub fn setUserSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "USERSIZE", .{}, value);
}
pub fn getTipDelay(self: *Self) i32 {
return interop.getIntAttribute(self, "TIPDELAY", .{});
}
pub fn setTipDelay(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "TIPDELAY", .{}, arg);
}
pub fn getCustomFrame(self: *Self) bool {
return interop.getBoolAttribute(self, "CUSTOMFRAME", .{});
}
pub fn setCustomFrame(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "CUSTOMFRAME", .{}, arg);
}
///
/// TITLE: Dialog's title.
pub fn getTitle(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TITLE", .{});
}
///
/// TITLE: Dialog's title.
pub fn setTitle(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TITLE", .{}, arg);
}
pub fn getDefaultEsc(self: *Self) ?*iup.Button {
if (interop.getHandleAttribute(self, "DEFAULTESC", .{})) |handle| {
return @ptrCast(*iup.Button, handle);
} else {
return null;
}
}
pub fn setDefaultEsc(self: *Self, arg: *iup.Button) void {
interop.setHandleAttribute(self, "DEFAULTESC", .{}, arg);
}
pub fn setDefaultEscHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DEFAULTESC", .{}, arg);
}
pub fn getPlacement(self: *Self) ?Placement {
var ret = interop.getStrAttribute(self, "PLACEMENT", .{});
if (std.ascii.eqlIgnoreCase("MAXIMIZED", ret)) return .Maximized;
if (std.ascii.eqlIgnoreCase("MINIMIZED", ret)) return .Minimized;
if (std.ascii.eqlIgnoreCase("FULL", ret)) return .Full;
return null;
}
pub fn setPlacement(self: *Self, arg: ?Placement) void {
if (arg) |value| switch (value) {
.Maximized => interop.setStrAttribute(self, "PLACEMENT", .{}, "MAXIMIZED"),
.Minimized => interop.setStrAttribute(self, "PLACEMENT", .{}, "MINIMIZED"),
.Full => interop.setStrAttribute(self, "PLACEMENT", .{}, "FULL"),
} else {
interop.clearAttribute(self, "PLACEMENT", .{});
}
}
///
/// EXTFILTER [Windows and GTK Only]: Defines several file filters.
/// It has priority over FILTERINFO and FILTER.
/// Must be a text with the format "FilterInfo1|Filter1|FilterInfo2|Filter2|...".
/// The list ends with character '|'.
/// Example: "Text files|*.txt;*.doc|Image files|*.gif;*.jpg;*.bmp|".
/// In GTK there is no way how to overwrite the filters, so it is recommended
/// to always add a less restrictive filter to the filter list, for example
/// "All Files|*.*".
pub fn getExtFilter(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "EXTFILTER", .{});
}
///
/// EXTFILTER [Windows and GTK Only]: Defines several file filters.
/// It has priority over FILTERINFO and FILTER.
/// Must be a text with the format "FilterInfo1|Filter1|FilterInfo2|Filter2|...".
/// The list ends with character '|'.
/// Example: "Text files|*.txt;*.doc|Image files|*.gif;*.jpg;*.bmp|".
/// In GTK there is no way how to overwrite the filters, so it is recommended
/// to always add a less restrictive filter to the filter list, for example
/// "All Files|*.*".
pub fn setExtFilter(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "EXTFILTER", .{}, arg);
}
pub fn getPropagateFocus(self: *Self) bool {
return interop.getBoolAttribute(self, "PROPAGATEFOCUS", .{});
}
pub fn setPropagateFocus(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "PROPAGATEFOCUS", .{}, arg);
}
pub fn getBgColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "BGCOLOR", .{});
}
pub fn setBgColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "BGCOLOR", .{}, rgb);
}
pub fn getDropTarget(self: *Self) bool {
return interop.getBoolAttribute(self, "DROPTARGET", .{});
}
pub fn setDropTarget(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DROPTARGET", .{}, arg);
}
pub fn getDragSource(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAGSOURCE", .{});
}
pub fn setDragSource(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAGSOURCE", .{}, arg);
}
pub fn getResize(self: *Self) bool {
return interop.getBoolAttribute(self, "RESIZE", .{});
}
pub fn setResize(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "RESIZE", .{}, arg);
}
pub fn getMaximized(self: *Self) bool {
return interop.getBoolAttribute(self, "MAXIMIZED", .{});
}
pub fn getFloating(self: *Self) ?Floating {
var ret = interop.getStrAttribute(self, "FLOATING", .{});
if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes;
if (std.ascii.eqlIgnoreCase("IGNORE", ret)) return .Ignore;
if (std.ascii.eqlIgnoreCase("NO", ret)) return .No;
return null;
}
pub fn setFloating(self: *Self, arg: ?Floating) void {
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self, "FLOATING", .{}, "YES"),
.Ignore => interop.setStrAttribute(self, "FLOATING", .{}, "IGNORE"),
.No => interop.setStrAttribute(self, "FLOATING", .{}, "NO"),
} else {
interop.clearAttribute(self, "FLOATING", .{});
}
}
pub fn getNormalizerGroup(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NORMALIZERGROUP", .{});
}
pub fn setNormalizerGroup(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NORMALIZERGROUP", .{}, arg);
}
pub fn getRasterSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "RASTERSIZE", .{});
return Size.parse(str);
}
pub fn setRasterSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "RASTERSIZE", .{}, value);
}
pub fn getShapeImage(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "SHAPEIMAGE", .{});
}
pub fn setShapeImage(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "SHAPEIMAGE", .{}, arg);
}
pub fn getTipFgColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "TIPFGCOLOR", .{});
}
pub fn setTipFgColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "TIPFGCOLOR", .{}, rgb);
}
pub fn getFontFace(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONTFACE", .{});
}
pub fn setFontFace(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONTFACE", .{}, arg);
}
pub fn topMost(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "TOPMOST", .{}, arg);
}
pub fn getName(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NAME", .{});
}
pub fn setName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NAME", .{}, arg);
}
pub fn getMinBox(self: *Self) bool {
return interop.getBoolAttribute(self, "MINBOX", .{});
}
pub fn setMinBox(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "MINBOX", .{}, arg);
}
pub fn getDefaultEnter(self: *Self) ?*iup.Button {
if (interop.getHandleAttribute(self, "DEFAULTENTER", .{})) |handle| {
return @ptrCast(*iup.Button, handle);
} else {
return null;
}
}
pub fn setDefaultEnter(self: *Self, arg: *iup.Button) void {
interop.setHandleAttribute(self, "DEFAULTENTER", .{}, arg);
}
pub fn setDefaultEnterHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DEFAULTENTER", .{}, arg);
}
pub fn getModal(self: *Self) bool {
return interop.getBoolAttribute(self, "MODAL", .{});
}
///
/// PARENTDIALOG: Makes the dialog be treated as a child of the specified dialog.
pub fn getParentDialog(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "PARENTDIALOG", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// PARENTDIALOG: Makes the dialog be treated as a child of the specified dialog.
pub fn setParentDialog(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Dialog, arg);
interop.setHandleAttribute(self, "PARENTDIALOG", .{}, arg);
}
pub fn setParentDialogHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "PARENTDIALOG", .{}, arg);
}
pub fn getBackground(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "BACKGROUND", .{});
}
pub fn setBackground(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "BACKGROUND", .{}, rgb);
}
pub fn getHideTaskbar(self: *Self) bool {
return interop.getBoolAttribute(self, "HIDETASKBAR", .{});
}
pub fn setHideTaskbar(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "HIDETASKBAR", .{}, arg);
}
///
/// FILTER: String containing a list of file filters separated by ';' without spaces.
/// Example: "*.C;*.LED;test.*".
/// In Motif only the first filter is used.
pub fn getFilter(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FILTER", .{});
}
///
/// FILTER: String containing a list of file filters separated by ';' without spaces.
/// Example: "*.C;*.LED;test.*".
/// In Motif only the first filter is used.
pub fn setFilter(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FILTER", .{}, arg);
}
///
/// VALUE (read-only): Name of the selected file(s), or NULL if no file was selected.
/// If FILE is not defined this is used as the initial value.
/// When MULTIPLEFILES=Yes it contains the path (but NOT the same value
/// returned in DIRECTORY, it does not contains the last separator) and several
/// file names separated by the '|' character.
/// The file list ends with character '|'.
/// BUT when the user selects just one file, the directory and the file are not
/// separated by '|'.
/// For example: "/tecgraf/iup/test|a.txt|b.txt|c.txt|" (MULTIPLEFILES=Yes and
/// more than one file is selected) "/tecgraf/iup/test/a.txt" (only one file is selected).
/// In Windows, the FILE and the DIRECTORY attributes also accept strings
/// containing "/" as path separators, but the VALUE attribute will always
/// return strings using the "\" character.
pub fn getValue(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "VALUE", .{});
}
pub fn getBringFront(self: *Self) bool {
return interop.getBoolAttribute(self, "BRINGFRONT", .{});
}
pub fn setBringFront(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "BRINGFRONT", .{}, arg);
}
pub fn getTrayImage(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "TRAYIMAGE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setTrayImage(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "TRAYIMAGE", .{}, arg);
}
pub fn setTrayImageHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TRAYIMAGE", .{}, arg);
}
pub fn getActive(self: *Self) bool {
return interop.getBoolAttribute(self, "ACTIVE", .{});
}
pub fn setActive(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "ACTIVE", .{}, arg);
}
pub fn getTipVisible(self: *Self) bool {
return interop.getBoolAttribute(self, "TIPVISIBLE", .{});
}
pub fn setTipVisible(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "TIPVISIBLE", .{}, arg);
}
pub fn getExpandWeight(self: *Self) f64 {
return interop.getDoubleAttribute(self, "EXPANDWEIGHT", .{});
}
pub fn setExpandWeight(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "EXPANDWEIGHT", .{}, arg);
}
pub fn getMinSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "MINSIZE", .{});
return Size.parse(str);
}
pub fn setMinSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "MINSIZE", .{}, value);
}
pub fn getActiveWindow(self: *Self) bool {
return interop.getBoolAttribute(self, "ACTIVEWINDOW", .{});
}
pub fn getNTheme(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NTHEME", .{});
}
pub fn setNTheme(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NTHEME", .{}, arg);
}
pub fn getBorder(self: *Self) bool {
return interop.getBoolAttribute(self, "BORDER", .{});
}
pub fn setBorder(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "BORDER", .{}, arg);
}
pub fn getCustomFramesImulate(self: *Self) bool {
return interop.getBoolAttribute(self, "CUSTOMFRAMESIMULATE", .{});
}
pub fn setCustomFramesImulate(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "CUSTOMFRAMESIMULATE", .{}, arg);
}
pub fn getShrink(self: *Self) bool {
return interop.getBoolAttribute(self, "SHRINK", .{});
}
pub fn setShrink(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "SHRINK", .{}, arg);
}
pub fn getCharSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "CHARSIZE", .{});
return Size.parse(str);
}
pub fn getClientSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "CLIENTSIZE", .{});
return Size.parse(str);
}
pub fn setClientSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "CLIENTSIZE", .{}, value);
}
pub fn getClientOffset(self: *Self) Size {
var str = interop.getStrAttribute(self, "CLIENTOFFSET", .{});
return Size.parse(str);
}
pub fn getTrayTip(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TRAYTIP", .{});
}
pub fn setTrayTip(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TRAYTIP", .{}, arg);
}
pub fn getDragTypes(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "DRAGTYPES", .{});
}
pub fn setDragTypes(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DRAGTYPES", .{}, arg);
}
pub fn getToolBox(self: *Self) bool {
return interop.getBoolAttribute(self, "TOOLBOX", .{});
}
pub fn setToolBox(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "TOOLBOX", .{}, arg);
}
pub fn getMdiFrame(self: *Self) bool {
return interop.getBoolAttribute(self, "MDIFRAME", .{});
}
pub fn setMdiFrame(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "MDIFRAME", .{}, arg);
}
///
/// NOOVERWRITEPROMPT: do not prompt to overwrite an existent file when in
/// "SAVE" dialog.
/// Default is "NO", i.e.
/// prompt before overwrite.
/// (GTK 2.8)
pub fn getNoOverwritePrompt(self: *Self) bool {
return interop.getBoolAttribute(self, "NOOVERWRITEPROMPT", .{});
}
///
/// NOOVERWRITEPROMPT: do not prompt to overwrite an existent file when in
/// "SAVE" dialog.
/// Default is "NO", i.e.
/// prompt before overwrite.
/// (GTK 2.8)
pub fn setNoOverwritePrompt(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "NOOVERWRITEPROMPT", .{}, arg);
}
pub fn getFontStyle(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONTSTYLE", .{});
}
pub fn setFontStyle(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONTSTYLE", .{}, arg);
}
///
/// DIRECTORY: Initial directory.
/// When consulted after the dialog is closed and the user pressed the OK
/// button, it will contain the directory of the selected file.
/// When set the last separator does not need to be specified, but when get the
/// returned value will always contains the last separator.
/// In Motif or GTK, if not defined, the dialog opens in the current directory.
/// In Windows, if not defined and the application has used the dialog in the
/// past, the path most recently used is selected as the initial directory.
/// However, if an application is not run for a long time, its saved selected
/// path is discarded.
/// Also if not defined and the current directory contains any files of the
/// specified filter types, the initial directory is the current directory.
/// Otherwise, the initial directory is the "My Documents" directory of the
/// current user.
/// Otherwise, the initial directory is the Desktop folder.
/// In Windows, the FILE and the DIRECTORY attributes also accept strings
/// containing "/" as path separators, but the VALUE attribute will always
/// return strings using the "\" character.
pub fn getDirectory(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "DIRECTORY", .{});
}
///
/// DIRECTORY: Initial directory.
/// When consulted after the dialog is closed and the user pressed the OK
/// button, it will contain the directory of the selected file.
/// When set the last separator does not need to be specified, but when get the
/// returned value will always contains the last separator.
/// In Motif or GTK, if not defined, the dialog opens in the current directory.
/// In Windows, if not defined and the application has used the dialog in the
/// past, the path most recently used is selected as the initial directory.
/// However, if an application is not run for a long time, its saved selected
/// path is discarded.
/// Also if not defined and the current directory contains any files of the
/// specified filter types, the initial directory is the current directory.
/// Otherwise, the initial directory is the "My Documents" directory of the
/// current user.
/// Otherwise, the initial directory is the Desktop folder.
/// In Windows, the FILE and the DIRECTORY attributes also accept strings
/// containing "/" as path separators, but the VALUE attribute will always
/// return strings using the "\" character.
pub fn setDirectory(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DIRECTORY", .{}, arg);
}
pub fn getMdiChild(self: *Self) bool {
return interop.getBoolAttribute(self, "MDICHILD", .{});
}
pub fn setMdiChild(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "MDICHILD", .{}, arg);
}
pub fn fullScreen(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "FULLSCREEN", .{}, arg);
}
pub fn getNativeParent(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "NATIVEPARENT", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setNativeParent(self: *Self, arg: anytype) !void {
interop.setHandleAttribute(self, "NATIVEPARENT", .{}, arg);
}
pub fn setNativeParentHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NATIVEPARENT", .{}, arg);
}
pub fn getFont(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONT", .{});
}
pub fn setFont(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONT", .{}, arg);
}
pub fn simulateModal(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "SIMULATEMODAL", .{}, arg);
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn getTabImage(self: *Self, index: i32) ?iup.Element {
if (interop.getHandleAttribute(self, "TABIMAGE", .{index})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabImage(self: *Self, index: i32, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "TABIMAGE", .{index}, arg);
}
pub fn setTabImageHandleName(self: *Self, index: i32, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TABIMAGE", .{index}, arg);
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn getTabTitle(self: *Self, index: i32) [:0]const u8 {
return interop.getStrAttribute(self, "TABTITLE", .{index});
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabTitle(self: *Self, index: i32, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TABTITLE", .{index}, arg);
}
pub fn setFocusCallback(self: *Self, callback: ?OnFocusFn) void {
const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB");
Handler.setCallback(self, callback);
}
///
/// K_ANY K_ANY Action generated when a keyboard event occurs.
/// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) ->
/// (ret: number) [in Lua] ih: identifier of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// Returns: If IUP_IGNORE is returned the key is ignored and not processed by
/// the control and not propagated.
/// If returns IUP_CONTINUE, the key will be processed and the event will be
/// propagated to the parent of the element receiving it, this is the default behavior.
/// If returns IUP_DEFAULT the key is processed but it is not propagated.
/// IUP_CLOSE will be processed.
/// Notes Keyboard callbacks depend on the keyboard usage of the control with
/// the focus.
/// So if you return IUP_IGNORE the control will usually not process the key.
/// But be aware that sometimes the control process the key in another event so
/// even returning IUP_IGNORE the key can get processed.
/// Although it will not be propagated.
/// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on
/// the IUP_CONTINUE return value to work while the control is in focus.
/// If the callback does not exists it is automatically propagated to the
/// parent of the element.
/// K_* callbacks All defined keys are also callbacks of any element, called
/// when the respective key is activated.
/// For example: "K_cC" is also a callback activated when the user press
/// Ctrl+C, when the focus is at the element or at a children with focus.
/// This is the way an application can create shortcut keys, also called hot keys.
/// These callbacks are not available in IupLua.
/// Affects All elements with keyboard interaction.
pub fn setKAnyCallback(self: *Self, callback: ?OnKAnyFn) void {
const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY");
Handler.setCallback(self, callback);
}
///
/// HELP_CB HELP_CB Action generated when the user press F1 at a control.
/// In Motif is also activated by the Help button in some workstations keyboard.
/// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Returns: IUP_CLOSE will be processed.
/// Affects All elements with user interaction.
pub fn setHelpCallback(self: *Self, callback: ?OnHelpFn) void {
const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB");
Handler.setCallback(self, callback);
}
///
/// CLOSE_CB CLOSE_CB Called just before a dialog is closed when the user
/// clicks the close button of the title bar or an equivalent action.
/// Callback int function(Ihandle *ih); [in C] ih:close_cb() -> (ret: number)
/// [in Lua] ih: identifies the element that activated the event.
/// Returns: if IUP_IGNORE, it prevents the dialog from being closed.
/// If you destroy the dialog in this callback, you must return IUP_IGNORE.
/// IUP_CLOSE will be processed.
/// Affects IupDialog
pub fn setCloseCallback(self: *Self, callback: ?OnCloseFn) void {
const Handler = CallbackHandler(Self, OnCloseFn, "CLOSE_CB");
Handler.setCallback(self, callback);
}
pub fn setDropMotionCallback(self: *Self, callback: ?OnDropMotionFn) void {
const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB");
Handler.setCallback(self, callback);
}
pub fn setDragEndCallback(self: *Self, callback: ?OnDragEndFn) void {
const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB");
Handler.setCallback(self, callback);
}
pub fn setDragBeginCallback(self: *Self, callback: ?OnDragBeginFn) void {
const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB");
Handler.setCallback(self, callback);
}
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setMapCallback(self: *Self, callback: ?OnMapFn) void {
const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB");
Handler.setCallback(self, callback);
}
///
/// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also LEAVEWINDOW_CB
pub fn setEnterWindowCallback(self: *Self, callback: ?OnEnterWindowFn) void {
const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB");
Handler.setCallback(self, callback);
}
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub fn setDestroyCallback(self: *Self, callback: ?OnDestroyFn) void {
const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB");
Handler.setCallback(self, callback);
}
pub fn setDropDataCallback(self: *Self, callback: ?OnDropDataFn) void {
const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB");
Handler.setCallback(self, callback);
}
///
/// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus.
/// This callback is called before the GETFOCUS_CB of the element that gets the focus.
/// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Affects All elements with user interaction, except menus.
/// In Windows, there are restrictions when using this callback.
/// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any
/// function calls that display or activate a window.
/// This causes the thread to yield control and can cause the application to
/// stop responding to messages.
/// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setKillFocusCallback(self: *Self, callback: ?OnKillFocusFn) void {
const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB");
Handler.setCallback(self, callback);
}
pub fn setDragDataCallback(self: *Self, callback: ?OnDragDataFn) void {
const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB");
Handler.setCallback(self, callback);
}
pub fn setDragDataSizeCallback(self: *Self, callback: ?OnDragDataSizeFn) void {
const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB");
Handler.setCallback(self, callback);
}
///
/// SHOW_CB SHOW_CB Called right after the dialog is showed, hidden, maximized,
/// minimized or restored from minimized/maximized.
/// This callback is called when those actions were performed by the user or
/// programmatically by the application.
/// Callback int function(Ihandle *ih, int state); [in C] ih:show_cb(state:
/// number) -> (ret: number) [in Lua] ih: identifier of the element that
/// activated the event.
/// state: indicates which of the following situations generated the event:
/// IUP_HIDE (since 3.0) IUP_SHOW IUP_RESTORE (was minimized or maximized)
/// IUP_MINIMIZE IUP_MAXIMIZE (since 3.0) (not received in Motif when activated
/// from the maximize button) Returns: IUP_CLOSE will be processed.
/// Affects IupDialog
pub fn setShowCallback(self: *Self, callback: ?OnShowFn) void {
const Handler = CallbackHandler(Self, OnShowFn, "SHOW_CB");
Handler.setCallback(self, callback);
}
///
/// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control.
/// When several files are dropped at once, the callback is called several
/// times, once for each file.
/// If defined after the element is mapped then the attribute DROPFILESTARGET
/// must be set to YES.
/// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const
/// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename:
/// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the
/// element that activated the event.
/// filename: Name of the dropped file.
/// num: Number index of the dropped file.
/// If several files are dropped, num is the index of the dropped file starting
/// from "total-1" to "0".
/// x: X coordinate of the point where the user released the mouse button.
/// y: Y coordinate of the point where the user released the mouse button.
/// Returns: If IUP_IGNORE is returned the callback will NOT be called for the
/// next dropped files, and the processing of dropped files will be interrupted.
/// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList
pub fn setDropFilesCallback(self: *Self, callback: ?OnDropFilesFn) void {
const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB");
Handler.setCallback(self, callback);
}
///
/// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed.
/// Callback int function(Ihandle *ih, int width, int height); [in C]
/// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// width: the width of the internal element size in pixels not considering the
/// decorations (client size) height: the height of the internal element size
/// in pixels not considering the decorations (client size) Notes For the
/// dialog, this action is also generated when the dialog is mapped, after the
/// map and before the show.
/// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is
/// hidden/shown after changing the DX or DY attributes from inside the
/// callback, the size of the drawing area will immediately change, so the
/// parameters with and height will be invalid.
/// To update the parameters consult the DRAWSIZE attribute.
/// Also activate the drawing toolkit only after updating the DX or DY attributes.
/// Affects IupCanvas, IupGLCanvas, IupDialog
pub fn setResizeCallback(self: *Self, callback: ?OnResizeFn) void {
const Handler = CallbackHandler(Self, OnResizeFn, "RESIZE_CB");
Handler.setCallback(self, callback);
}
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setUnmapCallback(self: *Self, callback: ?OnUnmapFn) void {
const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB");
Handler.setCallback(self, callback);
}
pub fn setTrayClickCallback(self: *Self, callback: ?OnTrayClickFn) void {
const Handler = CallbackHandler(Self, OnTrayClickFn, "TRAYCLICK_CB");
Handler.setCallback(self, callback);
}
///
/// When saving a file, the overwrite check is done before the FILE_CB callback
/// is called with status=OK.
/// If the application wants to add an extension to the file name inside the
/// FILE_CB callback when status=OK, then it must manually check if the file
/// with the extension exits and asks the user if the file should be replaced,
/// if not then the callback can set the FILE attribute and returns
/// IUP_CONTINUE, so the file dialog will remain open and the user will have an
/// opportunity to change the file name now that it contains the extension.
pub fn setFileCallback(self: *Self, callback: ?OnFileFn) void {
const Handler = CallbackHandler(Self, OnFileFn, "FILE_CB");
Handler.setCallback(self, callback);
}
///
/// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus.
/// This callback is called after the KILLFOCUS_CB of the element that loosed
/// the focus.
/// The IupGetFocus function during the callback returns the element that
/// loosed the focus.
/// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that received keyboard focus.
/// Affects All elements with user interaction, except menus.
/// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setGetFocusCallback(self: *Self, callback: ?OnGetFocusFn) void {
const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB");
Handler.setCallback(self, callback);
}
pub fn setLDestroyCallback(self: *Self, callback: ?OnLDestroyFn) void {
const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB");
Handler.setCallback(self, callback);
}
///
/// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also ENTERWINDOW_CB
pub fn setLeaveWindowCallback(self: *Self, callback: ?OnLeaveWindowFn) void {
const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB");
Handler.setCallback(self, callback);
}
pub fn setPostMessageCallback(self: *Self, callback: ?OnPostMessageFn) void {
const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB");
Handler.setCallback(self, callback);
}
};
test "FileDlg HandleName" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setHandleName("Hello").unwrap());
defer item.deinit();
var ret = item.getHandleName();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg TipBgColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTipBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getTipBgColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "FileDlg MdiClient" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setMdiClient(true).unwrap());
defer item.deinit();
var ret = item.getMdiClient();
try std.testing.expect(ret == true);
}
test "FileDlg Control" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setControl(true).unwrap());
defer item.deinit();
var ret = item.getControl();
try std.testing.expect(ret == true);
}
test "FileDlg TipIcon" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTipIcon("Hello").unwrap());
defer item.deinit();
var ret = item.getTipIcon();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg ShowPreview" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setShowPreview("Hello").unwrap());
defer item.deinit();
var ret = item.getShowPreview();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg NoFlush" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setNoFlush(true).unwrap());
defer item.deinit();
var ret = item.getNoFlush();
try std.testing.expect(ret == true);
}
test "FileDlg MaxSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setMaxSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getMaxSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "FileDlg OpacityImage" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setOpacityImage("Hello").unwrap());
defer item.deinit();
var ret = item.getOpacityImage();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg NoChangeDir" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setNoChangeDir(true).unwrap());
defer item.deinit();
var ret = item.getNoChangeDir();
try std.testing.expect(ret == true);
}
test "FileDlg HelpButton" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setHelpButton(true).unwrap());
defer item.deinit();
var ret = item.getHelpButton();
try std.testing.expect(ret == true);
}
test "FileDlg ShowNoFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setShowNoFocus(true).unwrap());
defer item.deinit();
var ret = item.getShowNoFocus();
try std.testing.expect(ret == true);
}
test "FileDlg Opacity" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setOpacity(42).unwrap());
defer item.deinit();
var ret = item.getOpacity();
try std.testing.expect(ret == 42);
}
test "FileDlg Position" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setPosition(9, 10).unwrap());
defer item.deinit();
var ret = item.getPosition();
try std.testing.expect(ret.x == 9 and ret.y == 10);
}
test "FileDlg Composited" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setComposited(true).unwrap());
defer item.deinit();
var ret = item.getComposited();
try std.testing.expect(ret == true);
}
test "FileDlg DropFilesTarget" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setDropFilesTarget(true).unwrap());
defer item.deinit();
var ret = item.getDropFilesTarget();
try std.testing.expect(ret == true);
}
test "FileDlg Tip" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTip("Hello").unwrap());
defer item.deinit();
var ret = item.getTip();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg CanFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setCanFocus(true).unwrap());
defer item.deinit();
var ret = item.getCanFocus();
try std.testing.expect(ret == true);
}
test "FileDlg DragSourceMove" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setDragSourceMove(true).unwrap());
defer item.deinit();
var ret = item.getDragSourceMove();
try std.testing.expect(ret == true);
}
test "FileDlg Icon" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setIcon("Hello").unwrap());
defer item.deinit();
var ret = item.getIcon();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg Visible" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setVisible(true).unwrap());
defer item.deinit();
var ret = item.getVisible();
try std.testing.expect(ret == true);
}
test "FileDlg MenuBox" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setMenuBox(true).unwrap());
defer item.deinit();
var ret = item.getMenuBox();
try std.testing.expect(ret == true);
}
test "FileDlg DialogType" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setDialogType(.Save).unwrap());
defer item.deinit();
var ret = item.getDialogType();
try std.testing.expect(ret != null and ret.? == .Save);
}
test "FileDlg HideTitleBar" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setHideTitleBar("Hello").unwrap());
defer item.deinit();
var ret = item.getHideTitleBar();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg MaxBox" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setMaxBox(true).unwrap());
defer item.deinit();
var ret = item.getMaxBox();
try std.testing.expect(ret == true);
}
test "FileDlg DragDrop" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setDragDrop(true).unwrap());
defer item.deinit();
var ret = item.getDragDrop();
try std.testing.expect(ret == true);
}
test "FileDlg DialogHint" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setDialogHint(true).unwrap());
defer item.deinit();
var ret = item.getDialogHint();
try std.testing.expect(ret == true);
}
test "FileDlg AllowNew" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setAllowNew(true).unwrap());
defer item.deinit();
var ret = item.getAllowNew();
try std.testing.expect(ret == true);
}
test "FileDlg DialogFrame" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setDialogFrame(true).unwrap());
defer item.deinit();
var ret = item.getDialogFrame();
try std.testing.expect(ret == true);
}
test "FileDlg NActive" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setNActive(true).unwrap());
defer item.deinit();
var ret = item.getNActive();
try std.testing.expect(ret == true);
}
test "FileDlg Theme" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTheme("Hello").unwrap());
defer item.deinit();
var ret = item.getTheme();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg SaveUnder" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setSaveUnder(true).unwrap());
defer item.deinit();
var ret = item.getSaveUnder();
try std.testing.expect(ret == true);
}
test "FileDlg Tray" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTray(true).unwrap());
defer item.deinit();
var ret = item.getTray();
try std.testing.expect(ret == true);
}
test "FileDlg ChildOffset" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setChildOffset(9, 10).unwrap());
defer item.deinit();
var ret = item.getChildOffset();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "FileDlg Expand" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setExpand(.Yes).unwrap());
defer item.deinit();
var ret = item.getExpand();
try std.testing.expect(ret != null and ret.? == .Yes);
}
test "FileDlg TipMarkup" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTipMarkup("Hello").unwrap());
defer item.deinit();
var ret = item.getTipMarkup();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg ExtDefault" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setExtDefault("Hello").unwrap());
defer item.deinit();
var ret = item.getExtDefault();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg StartFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setStartFocus("Hello").unwrap());
defer item.deinit();
var ret = item.getStartFocus();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg FontSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setFontSize(42).unwrap());
defer item.deinit();
var ret = item.getFontSize();
try std.testing.expect(ret == 42);
}
test "FileDlg DropTypes" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setDropTypes("Hello").unwrap());
defer item.deinit();
var ret = item.getDropTypes();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg TrayTipMarkup" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTrayTipMarkup("Hello").unwrap());
defer item.deinit();
var ret = item.getTrayTipMarkup();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg UserSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setUserSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getUserSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "FileDlg TipDelay" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTipDelay(42).unwrap());
defer item.deinit();
var ret = item.getTipDelay();
try std.testing.expect(ret == 42);
}
test "FileDlg CustomFrame" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setCustomFrame(true).unwrap());
defer item.deinit();
var ret = item.getCustomFrame();
try std.testing.expect(ret == true);
}
test "FileDlg Title" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTitle("Hello").unwrap());
defer item.deinit();
var ret = item.getTitle();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg Placement" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setPlacement(.Maximized).unwrap());
defer item.deinit();
var ret = item.getPlacement();
try std.testing.expect(ret != null and ret.? == .Maximized);
}
test "FileDlg ExtFilter" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setExtFilter("Hello").unwrap());
defer item.deinit();
var ret = item.getExtFilter();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg PropagateFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setPropagateFocus(true).unwrap());
defer item.deinit();
var ret = item.getPropagateFocus();
try std.testing.expect(ret == true);
}
test "FileDlg BgColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getBgColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "FileDlg DropTarget" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setDropTarget(true).unwrap());
defer item.deinit();
var ret = item.getDropTarget();
try std.testing.expect(ret == true);
}
test "FileDlg DragSource" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setDragSource(true).unwrap());
defer item.deinit();
var ret = item.getDragSource();
try std.testing.expect(ret == true);
}
test "FileDlg Resize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setResize(true).unwrap());
defer item.deinit();
var ret = item.getResize();
try std.testing.expect(ret == true);
}
test "FileDlg Floating" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setFloating(.Yes).unwrap());
defer item.deinit();
var ret = item.getFloating();
try std.testing.expect(ret != null and ret.? == .Yes);
}
test "FileDlg NormalizerGroup" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setNormalizerGroup("Hello").unwrap());
defer item.deinit();
var ret = item.getNormalizerGroup();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg RasterSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setRasterSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getRasterSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "FileDlg ShapeImage" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setShapeImage("Hello").unwrap());
defer item.deinit();
var ret = item.getShapeImage();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg TipFgColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTipFgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getTipFgColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "FileDlg FontFace" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setFontFace("Hello").unwrap());
defer item.deinit();
var ret = item.getFontFace();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg Name" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setName("Hello").unwrap());
defer item.deinit();
var ret = item.getName();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg MinBox" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setMinBox(true).unwrap());
defer item.deinit();
var ret = item.getMinBox();
try std.testing.expect(ret == true);
}
test "FileDlg Background" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setBackground(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getBackground();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "FileDlg HideTaskbar" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setHideTaskbar(true).unwrap());
defer item.deinit();
var ret = item.getHideTaskbar();
try std.testing.expect(ret == true);
}
test "FileDlg Filter" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setFilter("Hello").unwrap());
defer item.deinit();
var ret = item.getFilter();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg BringFront" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setBringFront(true).unwrap());
defer item.deinit();
var ret = item.getBringFront();
try std.testing.expect(ret == true);
}
test "FileDlg Active" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setActive(true).unwrap());
defer item.deinit();
var ret = item.getActive();
try std.testing.expect(ret == true);
}
test "FileDlg TipVisible" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTipVisible(true).unwrap());
defer item.deinit();
var ret = item.getTipVisible();
try std.testing.expect(ret == true);
}
test "FileDlg ExpandWeight" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setExpandWeight(3.14).unwrap());
defer item.deinit();
var ret = item.getExpandWeight();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "FileDlg MinSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setMinSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getMinSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "FileDlg NTheme" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setNTheme("Hello").unwrap());
defer item.deinit();
var ret = item.getNTheme();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg Border" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setBorder(true).unwrap());
defer item.deinit();
var ret = item.getBorder();
try std.testing.expect(ret == true);
}
test "FileDlg CustomFramesImulate" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setCustomFramesImulate(true).unwrap());
defer item.deinit();
var ret = item.getCustomFramesImulate();
try std.testing.expect(ret == true);
}
test "FileDlg Shrink" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setShrink(true).unwrap());
defer item.deinit();
var ret = item.getShrink();
try std.testing.expect(ret == true);
}
test "FileDlg ClientSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setClientSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getClientSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "FileDlg TrayTip" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setTrayTip("Hello").unwrap());
defer item.deinit();
var ret = item.getTrayTip();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg DragTypes" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setDragTypes("Hello").unwrap());
defer item.deinit();
var ret = item.getDragTypes();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg ToolBox" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setToolBox(true).unwrap());
defer item.deinit();
var ret = item.getToolBox();
try std.testing.expect(ret == true);
}
test "FileDlg MdiFrame" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setMdiFrame(true).unwrap());
defer item.deinit();
var ret = item.getMdiFrame();
try std.testing.expect(ret == true);
}
test "FileDlg NoOverwritePrompt" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setNoOverwritePrompt(true).unwrap());
defer item.deinit();
var ret = item.getNoOverwritePrompt();
try std.testing.expect(ret == true);
}
test "FileDlg FontStyle" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setFontStyle("Hello").unwrap());
defer item.deinit();
var ret = item.getFontStyle();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg Directory" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setDirectory("Hello").unwrap());
defer item.deinit();
var ret = item.getDirectory();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "FileDlg MdiChild" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setMdiChild(true).unwrap());
defer item.deinit();
var ret = item.getMdiChild();
try std.testing.expect(ret == true);
}
test "FileDlg Font" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.FileDlg.init().setFont("Hello").unwrap());
defer item.deinit();
var ret = item.getFont();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
} | src/elements/file_dlg.zig |
const std = @import("std");
const backend = @import("backend.zig");
const Size = @import("data.zig").Size;
const DataWrapper = @import("data.zig").DataWrapper;
const Container_Impl = @import("containers.zig").Container_Impl;
/// A button component. Instantiated using `Button(.{ })`
pub const Button_Impl = struct {
pub usingnamespace @import("internal.zig").All(Button_Impl);
peer: ?backend.Button = null,
handlers: Button_Impl.Handlers = undefined,
dataWrappers: Button_Impl.DataWrappers = .{},
label: [:0]const u8 = "",
enabled: DataWrapper(bool),
pub const Config = struct {
label: [:0]const u8 = "",
onclick: ?Button_Impl.Callback = null,
};
pub fn init() Button_Impl {
return Button_Impl.init_events(Button_Impl{ .enabled = DataWrapper(bool).of(true) });
}
pub fn initLabeled(label: [:0]const u8) Button_Impl {
var button = Button_Impl.init();
button.setLabel(label);
return button;
}
pub fn _pointerMoved(self: *Button_Impl) void {
self.enabled.updateBinders();
}
pub fn show(self: *Button_Impl) !void {
if (self.peer == null) {
self.peer = try backend.Button.create();
self.peer.?.setLabel(self.label);
try self.show_events();
}
}
pub fn getPreferredSize(self: *Button_Impl, available: Size) Size {
_ = self;
_ = available;
// TODO getting hint from native peer
return Size{ .width = 100.0, .height = 40.0 };
}
pub fn setLabel(self: *Button_Impl, label: [:0]const u8) void {
if (self.peer) |*peer| {
peer.setLabel(label);
} else {
self.label = label;
}
}
pub fn getLabel(self: *Button_Impl) [:0]const u8 {
if (self.peer) |*peer| {
return peer.getLabel();
} else {
return self.label;
}
}
pub fn setEnabledUpdater(self: *Button_Impl, updater: fn (*Container_Impl) bool) Button_Impl {
self.enabled.updater = updater;
return self.*;
}
};
pub fn Button(config: Button_Impl.Config) Button_Impl {
var btn = Button_Impl.initLabeled(config.label);
if (config.onclick) |onclick| {
btn.addClickHandler(onclick) catch unreachable; // TODO: improve
}
return btn;
}
test "Button" {
var button = Button(.{ .label = "Test Label" });
try std.testing.expectEqualStrings("Test Label", button.getLabel());
button.setLabel("New Label");
try std.testing.expectEqualStrings("New Label", button.getLabel());
} | src/button.zig |
const std = @import("std");
const log = std.debug.warn;
const stdout = &std.io.getStdOut().outStream();
const c = @import("c.zig");
const gmp = c.gmp;
const gw = c.gw;
const glue = @import("glue.zig");
/// caller owns the result
pub fn calculate_N(k: u32, n: u32) gmp.mpz_t {
var N: gmp.mpz_t = undefined;
gmp.mpz_init(&N);
// set N to Riesel number base at first
gmp.mpz_set_ui(&N, 2);
// raise b^n
gmp.mpz_pow_ui(&N, &N, n);
// multiply with k
gmp.mpz_mul_ui(&N, &N, k);
// and subtract the 1
gmp.mpz_sub_ui(&N, &N, 1);
return N;
}
pub fn find_V1(N: gmp.mpz_t) u32 {
var minus: gmp.mpz_t = undefined;
var plus: gmp.mpz_t = undefined;
gmp.mpz_init(&minus);
gmp.mpz_init(&plus);
var V1: u32 = 2;
while (V1 < 1000) {
gmp.mpz_set_ui(&minus, V1 - 2);
gmp.mpz_set_ui(&plus, V1 + 2);
const minus_val = gmp.mpz_jacobi(&minus, &N);
const plus_val = gmp.mpz_jacobi(&plus, &N);
if (minus_val == 1 and plus_val == -1) {
gmp.mpz_clear(&minus);
gmp.mpz_clear(&plus);
return V1;
}
V1 += 1;
}
unreachable;
}
/// this is O(log(len(n))) lucas sequence algorithm
/// fastest solution even for large k's
/// ! current default
/// FIXME: use gwnum here?
pub fn do_fastest_lucas_sequence(k: u32, _P: u32, Q: u32, N: gmp.mpz_t) gmp.mpz_t {
var k_tmp: gmp.mpz_t = undefined;
gmp.mpz_init(&k_tmp);
gmp.mpz_set_ui(&k_tmp, k);
const k_bitlen: usize = gmp.mpz_sizeinbase(&k_tmp, 2);
var x: gmp.mpz_t = undefined;
var y: gmp.mpz_t = undefined;
var one: gmp.mpz_t = undefined;
// init gmps
gmp.mpz_init(&x);
gmp.mpz_init(&y);
gmp.mpz_init(&one);
gmp.mpz_set_ui(&one, 1);
// setup
// x = v1
gmp.mpz_set_ui(&x, _P);
// y = (v1*v1) - 2 mod N
gmp.mpz_set_ui(&y, _P);
gmp.mpz_mul(&y, &y, &y);
gmp.mpz_sub_ui(&y, &y, 2);
gmp.mpz_powm(&y, &y, &one, &N);
// if bitlen is less than 2 then we have an edge case
var i: u32 = blk: {
if (k_bitlen >= 2) {
break :blk @intCast(u32, @intCast(i32, k_bitlen) - 2);
}
break :blk 0;
};
var one2: i32 = 1;
while (i > 0) {
// FIXME: dirty hack for 1<<i
var mask: u32 = 1;
var j: u32 = 0;
while (j < i) {
mask *= 2;
j += 1;
}
const bit_is_set = (k & mask) != 0;
if (bit_is_set) {
// x = (x*y) - v1 mod N
gmp.mpz_mul(&x, &x, &y);
gmp.mpz_sub_ui(&x, &x, _P);
gmp.mpz_powm(&x, &x, &one, &N);
// y = (y * y) - 2 mod N
gmp.mpz_mul(&y, &y, &y);
gmp.mpz_sub_ui(&y, &y, 2);
gmp.mpz_powm(&y, &y, &one, &N);
} else {
// y = (x*y) - v1 mod N
gmp.mpz_mul(&y, &x, &y);
gmp.mpz_sub_ui(&y, &y, _P);
gmp.mpz_powm(&y, &y, &one, &N);
// x = (x * x) - 2 mod N
gmp.mpz_mul(&x, &x, &x);
gmp.mpz_sub_ui(&x, &x, 2);
gmp.mpz_powm(&x, &x, &one, &N);
}
// if k == 1
if (i == 0) {
break;
}
i -= 1;
}
// finish up
// x *= y; x -= P; x %= N
gmp.mpz_mul(&x, &x, &y);
gmp.mpz_sub_ui(&x, &x, _P);
gmp.mpz_powm(&x, &x, &one, &N);
return x;
}
/// body method for do_fast_lucas_sequence
/// !!! slow - not used currently
fn fast_inner(_m: u32, _x: u32, N: gmp.mpz_t) gmp.mpz_t {
// required precision 102765*2^333354[100355 digits] == 1KB*227 (0.44)
// required precision 81*2^240743[72473 digits] == 130 (0.62)
// required precision 17295*2^217577[65502 digits] == 1KB*54 (0.31) [fft 16K]
// required precision 39547695*2^454240[136748 digits] == 1MB*86 (0.43) [fft 48K]
// required precision 133603707*2^100014[136748 digits] == 350?-425+MB
const start = std.time.milliTimestamp();
var one: gmp.mpf_t = undefined;
gmp.mpf_init(&one);
gmp.mpf_set_ui(&one, 1);
var x: gmp.mpf_t = undefined;
var a: gmp.mpf_t = undefined;
var inner: gmp.mpf_t = undefined;
var buf: gmp.mpf_t = undefined;
// we do not automagically calculate the required precision, but it seems
// to be a function of at least 2 numbers. 1 is k, the other is? [haven't got to it yet]
// this number will be unusably large for k's in the millions
const super_precision: u32 = 1024;
// initialize structs
gmp.mpf_init2(&x, super_precision);
gmp.mpf_init(&a);
gmp.mpf_init2(&inner, super_precision);
gmp.mpf_init(&buf);
// write some default values
gmp.mpf_set_ui(&x, @intCast(u64, _x));
// do the inner calculation first
// srt((x^2)-4) == sqrt((x+2)(x-2))
// alt: x - (sqrt(4) / x) # seems to work on larger numbers, also fails a lot
gmp.mpf_pow_ui(&inner, &x, 2);
gmp.mpf_sub_ui(&inner, &inner, 4);
gmp.mpf_sqrt(&inner, &inner);
// do deep negative exponentiation
// 2^-m
gmp.mpf_set_ui(&a, 2);
gmp.mpf_div(&a, &one, &a);
gmp.mpf_pow_ui(&a, &a, _m);
// do the core calculation
// ceil [ ((x + inner)^m*a) ]
// ~= y=[x + sqrt((x^2)-4)] [ y^m / 2^m ]
// move pow and mul earlier. use mod pow, b/c m is huge and is a power
gmp.mpf_add(&x, &x, &inner);
gmp.mpf_set_prec(&x, 63);
gmp.mpf_pow_ui(&x, &x, _m);
gmp.mpf_mul(&x, &x, &a);
gmp.mpf_ceil(&x, &x);
var result: gmp.mpz_t = undefined;
gmp.mpz_init(&result);
gmp.mpz_set_f(&result, &x);
return result;
}
/// https://vixra.org/pdf/1303.0195v1.pdf
/// i figured it out on my own that the constant 4 in Pb/2(4) is actually the P
/// value we found with the Jacoby symbol. so this is a general U0 finder
/// if you have the Jacobi calculation results
/// currently unused as it requires too much floating precision with large k's
/// and thus get's unbearably slow with k's in the millions
/// this is probably a more optical solution for small k's
/// caller owns the result
/// !!! slow for large k - not used currently
pub fn do_fast_lucas_sequence(k: u32, _P: u32, Q: u32, N: gmp.mpz_t) gmp.mpz_t {
// P_generic(b * k // mpz2, P_generic(b // mpz2, mpz(4), debug), debug)
var P: gmp.mpz_t = undefined;
gmp.mpz_init(&P);
gmp.mpz_set_ui(&P, _P);
// technically it should be b / 2', but b is 2 for us, so just '1'
const inner = fast_inner(1, _P, N);
const buf = @intCast(u32, gmp.mpz_get_ui(&inner));
// technically it should be 'b * k / 2', but b is 2 for us, so just 'k'
const result = fast_inner(k, buf, N);
// result is actually a working U0
return result;
}
/// caller owns the result
/// !!! slow for large k - not used currently
pub fn do_iterative_lucas_sequence(k: u32, P: u32, Q: u32, N: gmp.mpz_t) gmp.mpz_t {
// Vk(P,1) mod N ==
// xn = P * Xn-1 - Q * xn-2
var luc_min2: gmp.mpz_t = undefined;
var luc_min1: gmp.mpz_t = undefined;
gmp.mpz_init(&luc_min2);
gmp.mpz_init(&luc_min1);
gmp.mpz_set_ui(&luc_min2, 2); // 2
gmp.mpz_set_ui(&luc_min1, P); // P
var buf: gmp.mpz_t = undefined;
gmp.mpz_init(&buf);
gmp.mpz_set_ui(&buf, 0);
var temp_k: u34 = k;
while (temp_k > 2) {
const new = temp_k / 2;
var new_partner = new;
if (temp_k % 2 != 0) {
new_partner += 1;
}
temp_k = new;
}
var i: u32 = 2;
while (i <= k) {
// use luc_min2 as temporary buffer
gmp.mpz_mul_ui(&luc_min2, &luc_min2, Q);
gmp.mpz_mul_ui(&buf, &luc_min1, P);
gmp.mpz_sub(&buf, &buf, &luc_min2);
// luc_min2 is now correct
gmp.mpz_swap(&luc_min1, &luc_min2);
// luc_min1 is now correct
gmp.mpz_swap(&buf, &luc_min1);
i += 1;
}
// move the result to buf (for clarity)
if (k == 0) {
// these assumes no loop iterations were done
gmp.mpz_swap(&buf, &luc_min2);
} else {
gmp.mpz_swap(&buf, &luc_min1);
}
gmp.mpz_clear(&luc_min1);
gmp.mpz_clear(&luc_min2);
return buf;
}
pub fn find_u0(k: u32, n: u32, N: gmp.mpz_t, u_zero_out: *gmp.mpz_t) !void {
var V1: u32 = undefined;
if (k % 3 != 0) {
try stdout.print("using V1=4 because [k % 3 != 0]\n", .{});
V1 = 4;
} else {
// do the Jacobi to find V1
const start_jacobi = std.time.milliTimestamp();
V1 = find_V1(N);
const jacobi_took = std.time.milliTimestamp() - start_jacobi;
try stdout.print("found V1 [{}] using Jacobi Symbols in {}ms\n", .{ V1, jacobi_took });
}
const start_lucas = std.time.milliTimestamp();
// version 1 - slow
// calculate and store lucas sequence - slow
// does all the sequence steps in a loop
//u_zero_out.* = do_iterative_lucas_sequence(k, V1, 1, N);
// version 2 - slow
// fast lucas sequence process does deep negative powers of k
// and requires high precision - limiting with large k's
//u_zero_out.* = do_fast_lucas_sequence(k, V1, 1, N);
// version 3 - fast
// is O(log(len(k)))
u_zero_out.* = do_fastest_lucas_sequence(k, V1, 1, N);
const lucas_took = std.time.milliTimestamp() - start_lucas;
try stdout.print("found U0 using Lucas Sequence in {}ms\n", .{lucas_took});
// do the mod just in case it's not done
//gmp.mpz_mod(u_zero_out, u_zero_out, &N);
} | u_zero.zig |
const std = @import("std");
const lexer = @import("lexer.zig");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const ArrayList = std.ArrayList;
const Token = lexer.Token;
const TokenType = lexer.TokenType;
pub const Ast = struct {
/// Root node of our tree.
root: AstNode,
/// Mostly used for testing purpose, but all allocated memory
/// in this struct shared their lifetimes inside this arena allocator.
arena: ArenaAllocator,
/// Operators counter.
op_count: i32 = 0,
/// Commands counter.
cmd_count: i32 = 0,
/// Arguments counter.
args_count: i32 = 0,
};
pub const AstNode = struct {
children: ArrayList(AstNode),
args: ArrayList([]const u8),
cmd: ?[]const u8 = null,
kind: TokenType,
fn init(alloc: Allocator, kind: TokenType) AstNode {
return .{
.children = ArrayList(AstNode).init(alloc),
.args = ArrayList([]const u8).init(alloc),
.kind = kind,
};
}
};
pub fn parse(child_alloc: Allocator, tokens: []const Token) !Ast {
var ast = Ast{
.root = undefined,
.arena = ArenaAllocator.init(child_alloc),
};
const alloc = ast.arena.allocator();
var current: ?AstNode = null;
var i: usize = 0;
while (i < tokens.len) {
const token = tokens[i];
switch (token.kind) {
.AND, .OR, .PIPE => {
var operator_node = AstNode.init(alloc, token.kind);
if (current) |*node| {
if (node.kind != operator_node.kind) {
try operator_node.children.append(current.?);
current = operator_node;
}
}
ast.op_count += 1;
i += 1;
},
.CMD => {
var cmd_node = AstNode.init(alloc, token.kind);
var delimiter: usize = 0;
for (tokens[i..]) |item| {
if (item.kind != .CMD) break;
delimiter += 1;
}
for (tokens[i .. i + delimiter]) |next_cmd, index| {
if (index == 0) {
cmd_node.cmd = next_cmd.value;
ast.cmd_count += 1;
} else {
try cmd_node.args.append(next_cmd.value);
ast.args_count += 1;
}
}
if (current) |*node| {
try node.children.append(cmd_node);
} else {
current = cmd_node;
}
i += (1 + cmd_node.args.items.len);
},
}
}
if (current) |node| {
ast.root = node;
} else {
std.debug.panic("Shouldn't be an empty AST.", .{});
}
return ast;
} | zig/src/parser.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
fn part1(alloc: std.mem.Allocator, in: [][]const u8) usize {
var mem = std.AutoHashMap(usize, usize).init(alloc);
defer mem.deinit();
var mask0: usize = undefined;
var mask1: usize = undefined;
for (in) |line| {
if (line[1] == 'a') { // mask line
mask0 = 0;
mask1 = 0;
for (line[7..]) |ch| {
mask0 <<= 1;
mask1 <<= 1;
if (ch == '0') {
mask0 += 1;
} else if (ch == '1') {
mask1 += 1;
}
}
mask0 ^= 0xfffffffff;
//warn("1s mask = {}\n0s mask = {}\n", .{ mask1, mask0 });
} else { // mem line
var vit = std.mem.split(u8, line, " = ");
const astr = vit.next().?;
var val = std.fmt.parseUnsigned(usize, vit.next().?, 10) catch unreachable;
const addr = std.fmt.parseUnsigned(usize, astr[4 .. astr.len - 1], 10) catch unreachable;
//warn("addr={} value={}\n", .{ addr, val });
val &= mask0;
val |= mask1;
mem.put(addr, val) catch unreachable;
}
}
var sum: usize = 0;
var it = mem.iterator();
while (it.next()) |entry| {
sum += entry.value_ptr.*;
}
return sum;
}
fn part2(alloc: std.mem.Allocator, in: [][]const u8) usize {
var mem = std.AutoHashMap(usize, usize).init(alloc);
defer mem.deinit();
var mask1: usize = undefined;
var maskx: usize = undefined;
for (in) |line| {
if (line[1] == 'a') { // mask line
mask1 = 0;
maskx = 0;
for (line[7..]) |ch| {
mask1 <<= 1;
maskx <<= 1;
if (ch == '1') {
mask1 += 1;
} else if (ch == 'X') {
maskx += 1;
}
}
//warn("1s mask = {}\nXs mask = {}\n", .{ mask1, maskx });
} else { // mem line
var vit = std.mem.split(u8, line, " = ");
const astr = vit.next().?;
const val = std.fmt.parseUnsigned(usize, vit.next().?, 10) catch unreachable;
var addr = std.fmt.parseUnsigned(usize, astr[4 .. astr.len - 1], 10) catch unreachable;
//warn("addr={} value={}\n", .{ addr, val });
addr |= mask1;
var addrs = std.ArrayList(usize).init(alloc);
defer addrs.deinit();
addrs.append(addr) catch unreachable;
var m: usize = (1 << 35);
while (m >= 1) : (m >>= 1) {
if ((m & maskx) != 0) {
for (addrs.items) |a| {
if ((a & m) != 0) { // existing entry has 1
addrs.append(a & (0xfffffffff ^ m)) catch unreachable;
} else { // existing entry has 0
addrs.append(a | m) catch unreachable;
}
}
}
}
for (addrs.items) |a| {
mem.put(a, val) catch unreachable;
}
}
}
var sum: usize = 0;
var it = mem.iterator();
while (it.next()) |entry| {
sum += entry.value_ptr.*;
}
return sum;
}
test "examples" {
const test1 = aoc.readLines(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const test2 = aoc.readLines(aoc.talloc, aoc.test2file);
defer aoc.talloc.free(test2);
const inp = aoc.readLines(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
try aoc.assertEq(@as(usize, 165), part1(aoc.talloc, test1));
try aoc.assertEq(@as(usize, 51), part1(aoc.talloc, test2));
try aoc.assertEq(@as(usize, 4297467072083), part1(aoc.talloc, inp));
try aoc.assertEq(@as(usize, 208), part2(aoc.talloc, test2));
try aoc.assertEq(@as(usize, 5030603328768), part2(aoc.talloc, inp));
}
fn day14(inp: []const u8, bench: bool) anyerror!void {
const lines = aoc.readLines(aoc.halloc, inp);
defer aoc.halloc.free(lines);
var p1 = part1(aoc.halloc, lines);
var p2 = part2(aoc.halloc, lines);
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day14);
} | 2020/14/aoc.zig |
const DebugSymbols = @This();
const std = @import("std");
const assert = std.debug.assert;
const fs = std.fs;
const log = std.log.scoped(.link);
const macho = std.macho;
const mem = std.mem;
const DW = std.dwarf;
const leb = std.leb;
const Allocator = mem.Allocator;
const build_options = @import("build_options");
const trace = @import("../../tracy.zig").trace;
const Module = @import("../../Module.zig");
const Type = @import("../../type.zig").Type;
const link = @import("../../link.zig");
const MachO = @import("../MachO.zig");
const SrcFn = MachO.SrcFn;
const TextBlock = MachO.TextBlock;
const satMul = MachO.satMul;
const alloc_num = MachO.alloc_num;
const alloc_den = MachO.alloc_den;
const makeStaticString = MachO.makeStaticString;
usingnamespace @import("commands.zig");
const page_size: u16 = 0x1000;
base: *MachO,
file: fs.File,
/// Mach header
header: ?macho.mach_header_64 = null,
/// Table of all load commands
load_commands: std.ArrayListUnmanaged(LoadCommand) = .{},
/// __PAGEZERO segment
pagezero_segment_cmd_index: ?u16 = null,
/// __TEXT segment
text_segment_cmd_index: ?u16 = null,
/// __DATA segment
data_segment_cmd_index: ?u16 = null,
/// __LINKEDIT segment
linkedit_segment_cmd_index: ?u16 = null,
/// __DWARF segment
dwarf_segment_cmd_index: ?u16 = null,
/// Symbol table
symtab_cmd_index: ?u16 = null,
/// UUID load command
uuid_cmd_index: ?u16 = null,
/// Index into __TEXT,__text section.
text_section_index: ?u16 = null,
linkedit_off: u16 = page_size,
linkedit_size: u16 = page_size,
debug_info_section_index: ?u16 = null,
debug_abbrev_section_index: ?u16 = null,
debug_str_section_index: ?u16 = null,
debug_aranges_section_index: ?u16 = null,
debug_line_section_index: ?u16 = null,
debug_abbrev_table_offset: ?u64 = null,
/// A list of `SrcFn` whose Line Number Programs have surplus capacity.
/// This is the same concept as `text_block_free_list`; see those doc comments.
dbg_line_fn_free_list: std.AutoHashMapUnmanaged(*SrcFn, void) = .{},
dbg_line_fn_first: ?*SrcFn = null,
dbg_line_fn_last: ?*SrcFn = null,
/// A list of `TextBlock` whose corresponding .debug_info tags have surplus capacity.
/// This is the same concept as `text_block_free_list`; see those doc comments.
dbg_info_decl_free_list: std.AutoHashMapUnmanaged(*TextBlock, void) = .{},
dbg_info_decl_first: ?*TextBlock = null,
dbg_info_decl_last: ?*TextBlock = null,
/// Table of debug symbol names aka the debug string table.
debug_string_table: std.ArrayListUnmanaged(u8) = .{},
header_dirty: bool = false,
load_commands_dirty: bool = false,
string_table_dirty: bool = false,
debug_string_table_dirty: bool = false,
debug_abbrev_section_dirty: bool = false,
debug_aranges_section_dirty: bool = false,
debug_info_header_dirty: bool = false,
debug_line_header_dirty: bool = false,
const abbrev_compile_unit = 1;
const abbrev_subprogram = 2;
const abbrev_subprogram_retvoid = 3;
const abbrev_base_type = 4;
const abbrev_pad1 = 5;
const abbrev_parameter = 6;
/// The reloc offset for the virtual address of a function in its Line Number Program.
/// Size is a virtual address integer.
const dbg_line_vaddr_reloc_index = 3;
/// The reloc offset for the virtual address of a function in its .debug_info TAG_subprogram.
/// Size is a virtual address integer.
const dbg_info_low_pc_reloc_index = 1;
const min_nop_size = 2;
/// You must call this function *after* `MachO.populateMissingMetadata()`
/// has been called to get a viable debug symbols output.
pub fn populateMissingMetadata(self: *DebugSymbols, allocator: *Allocator) !void {
if (self.header == null) {
const base_header = self.base.header.?;
var header: macho.mach_header_64 = undefined;
header.magic = macho.MH_MAGIC_64;
header.cputype = base_header.cputype;
header.cpusubtype = base_header.cpusubtype;
header.filetype = macho.MH_DSYM;
// These will get populated at the end of flushing the results to file.
header.ncmds = 0;
header.sizeofcmds = 0;
header.flags = 0;
header.reserved = 0;
self.header = header;
self.header_dirty = true;
}
if (self.uuid_cmd_index == null) {
const base_cmd = self.base.load_commands.items[self.base.uuid_cmd_index.?];
self.uuid_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(allocator, base_cmd);
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.symtab_cmd_index == null) {
self.symtab_cmd_index = @intCast(u16, self.load_commands.items.len);
const base_cmd = self.base.load_commands.items[self.base.symtab_cmd_index.?].Symtab;
const symtab_size = base_cmd.nsyms * @sizeOf(macho.nlist_64);
const symtab_off = self.findFreeSpaceLinkedit(symtab_size, @sizeOf(macho.nlist_64));
log.debug("found dSym symbol table free space 0x{x} to 0x{x}", .{ symtab_off, symtab_off + symtab_size });
const strtab_off = self.findFreeSpaceLinkedit(base_cmd.strsize, 1);
log.debug("found dSym string table free space 0x{x} to 0x{x}", .{ strtab_off, strtab_off + base_cmd.strsize });
try self.load_commands.append(allocator, .{
.Symtab = .{
.cmd = macho.LC_SYMTAB,
.cmdsize = @sizeOf(macho.symtab_command),
.symoff = @intCast(u32, symtab_off),
.nsyms = base_cmd.nsyms,
.stroff = @intCast(u32, strtab_off),
.strsize = base_cmd.strsize,
},
});
self.header_dirty = true;
self.load_commands_dirty = true;
self.string_table_dirty = true;
}
if (self.pagezero_segment_cmd_index == null) {
self.pagezero_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
const base_cmd = self.base.load_commands.items[self.base.pagezero_segment_cmd_index.?].Segment;
const cmd = try self.copySegmentCommand(allocator, base_cmd);
try self.load_commands.append(allocator, .{ .Segment = cmd });
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.text_segment_cmd_index == null) {
self.text_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
const base_cmd = self.base.load_commands.items[self.base.text_segment_cmd_index.?].Segment;
const cmd = try self.copySegmentCommand(allocator, base_cmd);
try self.load_commands.append(allocator, .{ .Segment = cmd });
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.data_segment_cmd_index == null) outer: {
if (self.base.data_segment_cmd_index == null) break :outer; // __DATA is optional
self.data_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
const base_cmd = self.base.load_commands.items[self.base.data_segment_cmd_index.?].Segment;
const cmd = try self.copySegmentCommand(allocator, base_cmd);
try self.load_commands.append(allocator, .{ .Segment = cmd });
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.linkedit_segment_cmd_index == null) {
self.linkedit_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
const base_cmd = self.base.load_commands.items[self.base.linkedit_segment_cmd_index.?].Segment;
var cmd = try self.copySegmentCommand(allocator, base_cmd);
cmd.inner.vmsize = self.linkedit_size;
cmd.inner.fileoff = self.linkedit_off;
cmd.inner.filesize = self.linkedit_size;
try self.load_commands.append(allocator, .{ .Segment = cmd });
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.dwarf_segment_cmd_index == null) {
self.dwarf_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
const linkedit = self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const ideal_size: u16 = 200 + 128 + 160 + 250;
const needed_size = mem.alignForwardGeneric(u64, satMul(ideal_size, alloc_num) / alloc_den, page_size);
const off = linkedit.inner.fileoff + linkedit.inner.filesize;
const vmaddr = linkedit.inner.vmaddr + linkedit.inner.vmsize;
log.debug("found dSym __DWARF segment free space 0x{x} to 0x{x}", .{ off, off + needed_size });
try self.load_commands.append(allocator, .{
.Segment = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString("__DWARF"),
.vmaddr = vmaddr,
.vmsize = needed_size,
.fileoff = off,
.filesize = needed_size,
.maxprot = 0,
.initprot = 0,
.nsects = 0,
.flags = 0,
}),
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.debug_str_section_index == null) {
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
self.debug_str_section_index = @intCast(u16, dwarf_segment.sections.items.len);
assert(self.debug_string_table.items.len == 0);
try dwarf_segment.addSection(allocator, .{
.sectname = makeStaticString("__debug_str"),
.segname = makeStaticString("__DWARF"),
.addr = dwarf_segment.inner.vmaddr,
.size = @intCast(u32, self.debug_string_table.items.len),
.offset = @intCast(u32, dwarf_segment.inner.fileoff),
.@"align" = 1,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_REGULAR,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
self.debug_string_table_dirty = true;
}
if (self.debug_info_section_index == null) {
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
self.debug_info_section_index = @intCast(u16, dwarf_segment.sections.items.len);
const file_size_hint = 200;
const p_align = 1;
const off = dwarf_segment.findFreeSpace(file_size_hint, p_align, null);
log.debug("found dSym __debug_info free space 0x{x} to 0x{x}", .{ off, off + file_size_hint });
try dwarf_segment.addSection(allocator, .{
.sectname = makeStaticString("__debug_info"),
.segname = makeStaticString("__DWARF"),
.addr = dwarf_segment.inner.vmaddr + off - dwarf_segment.inner.fileoff,
.size = file_size_hint,
.offset = @intCast(u32, off),
.@"align" = p_align,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_REGULAR,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
self.debug_info_header_dirty = true;
}
if (self.debug_abbrev_section_index == null) {
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
self.debug_abbrev_section_index = @intCast(u16, dwarf_segment.sections.items.len);
const file_size_hint = 128;
const p_align = 1;
const off = dwarf_segment.findFreeSpace(file_size_hint, p_align, null);
log.debug("found dSym __debug_abbrev free space 0x{x} to 0x{x}", .{ off, off + file_size_hint });
try dwarf_segment.addSection(allocator, .{
.sectname = makeStaticString("__debug_abbrev"),
.segname = makeStaticString("__DWARF"),
.addr = dwarf_segment.inner.vmaddr + off - dwarf_segment.inner.fileoff,
.size = file_size_hint,
.offset = @intCast(u32, off),
.@"align" = p_align,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_REGULAR,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
self.debug_abbrev_section_dirty = true;
}
if (self.debug_aranges_section_index == null) {
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
self.debug_aranges_section_index = @intCast(u16, dwarf_segment.sections.items.len);
const file_size_hint = 160;
const p_align = 16;
const off = dwarf_segment.findFreeSpace(file_size_hint, p_align, null);
log.debug("found dSym __debug_aranges free space 0x{x} to 0x{x}", .{ off, off + file_size_hint });
try dwarf_segment.addSection(allocator, .{
.sectname = makeStaticString("__debug_aranges"),
.segname = makeStaticString("__DWARF"),
.addr = dwarf_segment.inner.vmaddr + off - dwarf_segment.inner.fileoff,
.size = file_size_hint,
.offset = @intCast(u32, off),
.@"align" = p_align,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_REGULAR,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
self.debug_aranges_section_dirty = true;
}
if (self.debug_line_section_index == null) {
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
self.debug_line_section_index = @intCast(u16, dwarf_segment.sections.items.len);
const file_size_hint = 250;
const p_align = 1;
const off = dwarf_segment.findFreeSpace(file_size_hint, p_align, null);
log.debug("found dSym __debug_line free space 0x{x} to 0x{x}", .{ off, off + file_size_hint });
try dwarf_segment.addSection(allocator, .{
.sectname = makeStaticString("__debug_line"),
.segname = makeStaticString("__DWARF"),
.addr = dwarf_segment.inner.vmaddr + off - dwarf_segment.inner.fileoff,
.size = file_size_hint,
.offset = @intCast(u32, off),
.@"align" = p_align,
.reloff = 0,
.nreloc = 0,
.flags = macho.S_REGULAR,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
self.debug_line_header_dirty = true;
}
}
pub fn flushModule(self: *DebugSymbols, allocator: *Allocator, options: link.Options) !void {
// TODO This linker code currently assumes there is only 1 compilation unit and it corresponds to the
// Zig source code.
const module = options.module orelse return error.LinkingWithoutZigSourceUnimplemented;
const init_len_size: usize = 4;
if (self.debug_abbrev_section_dirty) {
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
const debug_abbrev_sect = &dwarf_segment.sections.items[self.debug_abbrev_section_index.?];
// These are LEB encoded but since the values are all less than 127
// we can simply append these bytes.
const abbrev_buf = [_]u8{
abbrev_compile_unit, DW.TAG_compile_unit, DW.CHILDREN_yes, // header
DW.AT_stmt_list, DW.FORM_sec_offset, // offset
DW.AT_low_pc, DW.FORM_addr,
DW.AT_high_pc, DW.FORM_addr,
DW.AT_name, DW.FORM_strp,
DW.AT_comp_dir, DW.FORM_strp,
DW.AT_producer, DW.FORM_strp,
DW.AT_language, DW.FORM_data2,
0, 0, // table sentinel
abbrev_subprogram, DW.TAG_subprogram, DW.CHILDREN_yes, // header
DW.AT_low_pc, DW.FORM_addr, // start VM address
DW.AT_high_pc, DW.FORM_data4,
DW.AT_type, DW.FORM_ref4,
DW.AT_name, DW.FORM_string,
DW.AT_decl_line, DW.FORM_data4,
DW.AT_decl_file, DW.FORM_data1,
0, 0, // table sentinel
abbrev_subprogram_retvoid,
DW.TAG_subprogram, DW.CHILDREN_yes, // header
DW.AT_low_pc, DW.FORM_addr,
DW.AT_high_pc, DW.FORM_data4,
DW.AT_name, DW.FORM_string,
DW.AT_decl_line, DW.FORM_data4,
DW.AT_decl_file, DW.FORM_data1,
0, 0, // table sentinel
abbrev_base_type, DW.TAG_base_type, DW.CHILDREN_no, // header
DW.AT_encoding, DW.FORM_data1, DW.AT_byte_size,
DW.FORM_data1, DW.AT_name, DW.FORM_string,
0, 0, // table sentinel
abbrev_pad1, DW.TAG_unspecified_type, DW.CHILDREN_no, // header
0, 0, // table sentinel
abbrev_parameter, DW.TAG_formal_parameter, DW.CHILDREN_no, // header
DW.AT_location, DW.FORM_exprloc, DW.AT_type,
DW.FORM_ref4, DW.AT_name, DW.FORM_string,
0, 0, // table sentinel
0, 0, 0, // section sentinel
};
const needed_size = abbrev_buf.len;
const allocated_size = dwarf_segment.allocatedSize(debug_abbrev_sect.offset);
if (needed_size > allocated_size) {
debug_abbrev_sect.size = 0; // free the space
const offset = dwarf_segment.findFreeSpace(needed_size, 1, null);
debug_abbrev_sect.offset = @intCast(u32, offset);
debug_abbrev_sect.addr = dwarf_segment.inner.vmaddr + offset - dwarf_segment.inner.fileoff;
}
debug_abbrev_sect.size = needed_size;
log.debug("__debug_abbrev start=0x{x} end=0x{x}", .{
debug_abbrev_sect.offset,
debug_abbrev_sect.offset + needed_size,
});
const abbrev_offset = 0;
self.debug_abbrev_table_offset = abbrev_offset;
try self.file.pwriteAll(&abbrev_buf, debug_abbrev_sect.offset + abbrev_offset);
self.load_commands_dirty = true;
self.debug_abbrev_section_dirty = false;
}
if (self.debug_info_header_dirty) debug_info: {
// If this value is null it means there is an error in the module;
// leave debug_info_header_dirty=true.
const first_dbg_info_decl = self.dbg_info_decl_first orelse break :debug_info;
const last_dbg_info_decl = self.dbg_info_decl_last.?;
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
const debug_info_sect = &dwarf_segment.sections.items[self.debug_info_section_index.?];
var di_buf = std.ArrayList(u8).init(allocator);
defer di_buf.deinit();
// We have a function to compute the upper bound size, because it's needed
// for determining where to put the offset of the first `LinkBlock`.
try di_buf.ensureCapacity(self.dbgInfoNeededHeaderBytes());
// initial length - length of the .debug_info contribution for this compilation unit,
// not including the initial length itself.
// We have to come back and write it later after we know the size.
const after_init_len = di_buf.items.len + init_len_size;
// +1 for the final 0 that ends the compilation unit children.
const dbg_info_end = last_dbg_info_decl.dbg_info_off + last_dbg_info_decl.dbg_info_len + 1;
const init_len = dbg_info_end - after_init_len;
mem.writeIntLittle(u32, di_buf.addManyAsArrayAssumeCapacity(4), @intCast(u32, init_len));
mem.writeIntLittle(u16, di_buf.addManyAsArrayAssumeCapacity(2), 4); // DWARF version
const abbrev_offset = self.debug_abbrev_table_offset.?;
mem.writeIntLittle(u32, di_buf.addManyAsArrayAssumeCapacity(4), @intCast(u32, abbrev_offset));
di_buf.appendAssumeCapacity(8); // address size
// Write the form for the compile unit, which must match the abbrev table above.
const name_strp = try self.makeDebugString(allocator, module.root_pkg.root_src_path);
const comp_dir_strp = try self.makeDebugString(allocator, module.root_pkg.root_src_directory.path orelse ".");
const producer_strp = try self.makeDebugString(allocator, link.producer_string);
// Currently only one compilation unit is supported, so the address range is simply
// identical to the main program header virtual address and memory size.
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const text_section = text_segment.sections.items[self.text_section_index.?];
const low_pc = text_section.addr;
const high_pc = text_section.addr + text_section.size;
di_buf.appendAssumeCapacity(abbrev_compile_unit);
mem.writeIntLittle(u32, di_buf.addManyAsArrayAssumeCapacity(4), 0); // DW.AT_stmt_list, DW.FORM_sec_offset
mem.writeIntLittle(u64, di_buf.addManyAsArrayAssumeCapacity(8), low_pc);
mem.writeIntLittle(u64, di_buf.addManyAsArrayAssumeCapacity(8), high_pc);
mem.writeIntLittle(u32, di_buf.addManyAsArrayAssumeCapacity(4), @intCast(u32, name_strp));
mem.writeIntLittle(u32, di_buf.addManyAsArrayAssumeCapacity(4), @intCast(u32, comp_dir_strp));
mem.writeIntLittle(u32, di_buf.addManyAsArrayAssumeCapacity(4), @intCast(u32, producer_strp));
// We are still waiting on dwarf-std.org to assign DW_LANG_Zig a number:
// http://dwarfstd.org/ShowIssue.php?issue=171115.1
// Until then we say it is C99.
mem.writeIntLittle(u16, di_buf.addManyAsArrayAssumeCapacity(2), DW.LANG_C99);
if (di_buf.items.len > first_dbg_info_decl.dbg_info_off) {
// Move the first N decls to the end to make more padding for the header.
@panic("TODO: handle __debug_info header exceeding its padding");
}
const jmp_amt = first_dbg_info_decl.dbg_info_off - di_buf.items.len;
try self.pwriteDbgInfoNops(0, di_buf.items, jmp_amt, false, debug_info_sect.offset);
self.debug_info_header_dirty = false;
}
if (self.debug_aranges_section_dirty) {
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
const debug_aranges_sect = &dwarf_segment.sections.items[self.debug_aranges_section_index.?];
const debug_info_sect = dwarf_segment.sections.items[self.debug_info_section_index.?];
var di_buf = std.ArrayList(u8).init(allocator);
defer di_buf.deinit();
// Enough for all the data without resizing. When support for more compilation units
// is added, the size of this section will become more variable.
try di_buf.ensureCapacity(100);
// initial length - length of the .debug_aranges contribution for this compilation unit,
// not including the initial length itself.
// We have to come back and write it later after we know the size.
const init_len_index = di_buf.items.len;
di_buf.items.len += init_len_size;
const after_init_len = di_buf.items.len;
mem.writeIntLittle(u16, di_buf.addManyAsArrayAssumeCapacity(2), 2); // version
// When more than one compilation unit is supported, this will be the offset to it.
// For now it is always at offset 0 in .debug_info.
mem.writeIntLittle(u32, di_buf.addManyAsArrayAssumeCapacity(4), 0); // __debug_info offset
di_buf.appendAssumeCapacity(@sizeOf(u64)); // address_size
di_buf.appendAssumeCapacity(0); // segment_selector_size
const end_header_offset = di_buf.items.len;
const begin_entries_offset = mem.alignForward(end_header_offset, @sizeOf(u64) * 2);
di_buf.appendNTimesAssumeCapacity(0, begin_entries_offset - end_header_offset);
// Currently only one compilation unit is supported, so the address range is simply
// identical to the main program header virtual address and memory size.
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const text_section = text_segment.sections.items[self.text_section_index.?];
mem.writeIntLittle(u64, di_buf.addManyAsArrayAssumeCapacity(8), text_section.addr);
mem.writeIntLittle(u64, di_buf.addManyAsArrayAssumeCapacity(8), text_section.size);
// Sentinel.
mem.writeIntLittle(u32, di_buf.addManyAsArrayAssumeCapacity(4), 0);
mem.writeIntLittle(u32, di_buf.addManyAsArrayAssumeCapacity(4), 0);
// Go back and populate the initial length.
const init_len = di_buf.items.len - after_init_len;
// initial length - length of the .debug_aranges contribution for this compilation unit,
// not including the initial length itself.
mem.writeIntLittle(u32, di_buf.items[init_len_index..][0..4], @intCast(u32, init_len));
const needed_size = di_buf.items.len;
const allocated_size = dwarf_segment.allocatedSize(debug_aranges_sect.offset);
if (needed_size > allocated_size) {
debug_aranges_sect.size = 0; // free the space
const new_offset = dwarf_segment.findFreeSpace(needed_size, 16, null);
debug_aranges_sect.addr = dwarf_segment.inner.vmaddr + new_offset - dwarf_segment.inner.fileoff;
debug_aranges_sect.offset = @intCast(u32, new_offset);
}
debug_aranges_sect.size = needed_size;
log.debug("__debug_aranges start=0x{x} end=0x{x}", .{
debug_aranges_sect.offset,
debug_aranges_sect.offset + needed_size,
});
try self.file.pwriteAll(di_buf.items, debug_aranges_sect.offset);
self.load_commands_dirty = true;
self.debug_aranges_section_dirty = false;
}
if (self.debug_line_header_dirty) debug_line: {
if (self.dbg_line_fn_first == null) {
break :debug_line; // Error in module; leave debug_line_header_dirty=true.
}
const dbg_line_prg_off = self.getDebugLineProgramOff();
const dbg_line_prg_end = self.getDebugLineProgramEnd();
assert(dbg_line_prg_end != 0);
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
const debug_line_sect = &dwarf_segment.sections.items[self.debug_line_section_index.?];
var di_buf = std.ArrayList(u8).init(allocator);
defer di_buf.deinit();
// The size of this header is variable, depending on the number of directories,
// files, and padding. We have a function to compute the upper bound size, however,
// because it's needed for determining where to put the offset of the first `SrcFn`.
try di_buf.ensureCapacity(self.dbgLineNeededHeaderBytes(module));
// initial length - length of the .debug_line contribution for this compilation unit,
// not including the initial length itself.
const after_init_len = di_buf.items.len + init_len_size;
const init_len = dbg_line_prg_end - after_init_len;
mem.writeIntLittle(u32, di_buf.addManyAsArrayAssumeCapacity(4), @intCast(u32, init_len));
mem.writeIntLittle(u16, di_buf.addManyAsArrayAssumeCapacity(2), 4); // version
// Empirically, debug info consumers do not respect this field, or otherwise
// consider it to be an error when it does not point exactly to the end of the header.
// Therefore we rely on the NOP jump at the beginning of the Line Number Program for
// padding rather than this field.
const before_header_len = di_buf.items.len;
di_buf.items.len += @sizeOf(u32); // We will come back and write this.
const after_header_len = di_buf.items.len;
const opcode_base = DW.LNS_set_isa + 1;
di_buf.appendSliceAssumeCapacity(&[_]u8{
1, // minimum_instruction_length
1, // maximum_operations_per_instruction
1, // default_is_stmt
1, // line_base (signed)
1, // line_range
opcode_base,
// Standard opcode lengths. The number of items here is based on `opcode_base`.
// The value is the number of LEB128 operands the instruction takes.
0, // `DW.LNS_copy`
1, // `DW.LNS_advance_pc`
1, // `DW.LNS_advance_line`
1, // `DW.LNS_set_file`
1, // `DW.LNS_set_column`
0, // `DW.LNS_negate_stmt`
0, // `DW.LNS_set_basic_block`
0, // `DW.LNS_const_add_pc`
1, // `DW.LNS_fixed_advance_pc`
0, // `DW.LNS_set_prologue_end`
0, // `DW.LNS_set_epilogue_begin`
1, // `DW.LNS_set_isa`
0, // include_directories (none except the compilation unit cwd)
});
// file_names[0]
di_buf.appendSliceAssumeCapacity(module.root_pkg.root_src_path); // relative path name
di_buf.appendSliceAssumeCapacity(&[_]u8{
0, // null byte for the relative path name
0, // directory_index
0, // mtime (TODO supply this)
0, // file size bytes (TODO supply this)
0, // file_names sentinel
});
const header_len = di_buf.items.len - after_header_len;
mem.writeIntLittle(u32, di_buf.items[before_header_len..][0..4], @intCast(u32, header_len));
// We use NOPs because consumers empirically do not respect the header length field.
if (di_buf.items.len > dbg_line_prg_off) {
// Move the first N files to the end to make more padding for the header.
@panic("TODO: handle __debug_line header exceeding its padding");
}
const jmp_amt = dbg_line_prg_off - di_buf.items.len;
try self.pwriteDbgLineNops(0, di_buf.items, jmp_amt, debug_line_sect.offset);
self.debug_line_header_dirty = false;
}
{
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
const debug_strtab_sect = &dwarf_segment.sections.items[self.debug_str_section_index.?];
if (self.debug_string_table_dirty or self.debug_string_table.items.len != debug_strtab_sect.size) {
const allocated_size = dwarf_segment.allocatedSize(debug_strtab_sect.offset);
const needed_size = self.debug_string_table.items.len;
if (needed_size > allocated_size) {
debug_strtab_sect.size = 0; // free the space
const new_offset = dwarf_segment.findFreeSpace(needed_size, 1, null);
debug_strtab_sect.addr = dwarf_segment.inner.vmaddr + new_offset - dwarf_segment.inner.fileoff;
debug_strtab_sect.offset = @intCast(u32, new_offset);
}
debug_strtab_sect.size = @intCast(u32, needed_size);
log.debug("__debug_strtab start=0x{x} end=0x{x}", .{
debug_strtab_sect.offset,
debug_strtab_sect.offset + needed_size,
});
try self.file.pwriteAll(self.debug_string_table.items, debug_strtab_sect.offset);
self.load_commands_dirty = true;
self.debug_string_table_dirty = false;
}
}
try self.writeStringTable();
self.updateDwarfSegment();
try self.writeLoadCommands(allocator);
try self.writeHeader();
assert(!self.header_dirty);
assert(!self.load_commands_dirty);
assert(!self.string_table_dirty);
assert(!self.debug_abbrev_section_dirty);
assert(!self.debug_aranges_section_dirty);
assert(!self.debug_string_table_dirty);
}
pub fn deinit(self: *DebugSymbols, allocator: *Allocator) void {
self.dbg_info_decl_free_list.deinit(allocator);
self.dbg_line_fn_free_list.deinit(allocator);
self.debug_string_table.deinit(allocator);
for (self.load_commands.items) |*lc| {
lc.deinit(allocator);
}
self.load_commands.deinit(allocator);
self.file.close();
}
fn copySegmentCommand(self: *DebugSymbols, allocator: *Allocator, base_cmd: SegmentCommand) !SegmentCommand {
var cmd = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = base_cmd.inner.cmdsize,
.segname = undefined,
.vmaddr = base_cmd.inner.vmaddr,
.vmsize = base_cmd.inner.vmsize,
.fileoff = 0,
.filesize = 0,
.maxprot = base_cmd.inner.maxprot,
.initprot = base_cmd.inner.initprot,
.nsects = base_cmd.inner.nsects,
.flags = base_cmd.inner.flags,
});
mem.copy(u8, &cmd.inner.segname, &base_cmd.inner.segname);
try cmd.sections.ensureCapacity(allocator, cmd.inner.nsects);
for (base_cmd.sections.items) |base_sect, i| {
var sect = macho.section_64{
.sectname = undefined,
.segname = undefined,
.addr = base_sect.addr,
.size = base_sect.size,
.offset = 0,
.@"align" = base_sect.@"align",
.reloff = 0,
.nreloc = 0,
.flags = base_sect.flags,
.reserved1 = base_sect.reserved1,
.reserved2 = base_sect.reserved2,
.reserved3 = base_sect.reserved3,
};
mem.copy(u8, §.sectname, &base_sect.sectname);
mem.copy(u8, §.segname, &base_sect.segname);
if (self.base.text_section_index.? == i) {
self.text_section_index = @intCast(u16, i);
}
cmd.sections.appendAssumeCapacity(sect);
}
return cmd;
}
fn updateDwarfSegment(self: *DebugSymbols) void {
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
var file_size: u64 = 0;
for (dwarf_segment.sections.items) |sect| {
file_size += sect.size;
}
if (file_size != dwarf_segment.inner.filesize) {
dwarf_segment.inner.filesize = file_size;
if (dwarf_segment.inner.vmsize < dwarf_segment.inner.filesize) {
dwarf_segment.inner.vmsize = mem.alignForwardGeneric(u64, dwarf_segment.inner.filesize, page_size);
}
self.load_commands_dirty = true;
}
}
/// Writes all load commands and section headers.
fn writeLoadCommands(self: *DebugSymbols, allocator: *Allocator) !void {
if (!self.load_commands_dirty) return;
var sizeofcmds: usize = 0;
for (self.load_commands.items) |lc| {
sizeofcmds += lc.cmdsize();
}
var buffer = try allocator.alloc(u8, sizeofcmds);
defer allocator.free(buffer);
var writer = std.io.fixedBufferStream(buffer).writer();
for (self.load_commands.items) |lc| {
try lc.write(writer);
}
const off = @sizeOf(macho.mach_header_64);
log.debug("writing {} dSym load commands from 0x{x} to 0x{x}", .{ self.load_commands.items.len, off, off + sizeofcmds });
try self.file.pwriteAll(buffer, off);
self.load_commands_dirty = false;
}
fn writeHeader(self: *DebugSymbols) !void {
if (!self.header_dirty) return;
self.header.?.ncmds = @intCast(u32, self.load_commands.items.len);
var sizeofcmds: u32 = 0;
for (self.load_commands.items) |cmd| {
sizeofcmds += cmd.cmdsize();
}
self.header.?.sizeofcmds = sizeofcmds;
log.debug("writing Mach-O dSym header {}", .{self.header.?});
try self.file.pwriteAll(mem.asBytes(&self.header.?), 0);
self.header_dirty = false;
}
fn allocatedSizeLinkedit(self: *DebugSymbols, start: u64) u64 {
assert(start > 0);
var min_pos: u64 = std.math.maxInt(u64);
if (self.symtab_cmd_index) |idx| {
const symtab = self.load_commands.items[idx].Symtab;
if (symtab.symoff >= start and symtab.symoff < min_pos) min_pos = symtab.symoff;
if (symtab.stroff >= start and symtab.stroff < min_pos) min_pos = symtab.stroff;
}
return min_pos - start;
}
fn detectAllocCollisionLinkedit(self: *DebugSymbols, start: u64, size: u64) ?u64 {
const end = start + satMul(size, alloc_num) / alloc_den;
if (self.symtab_cmd_index) |idx| outer: {
if (self.load_commands.items.len == idx) break :outer;
const symtab = self.load_commands.items[idx].Symtab;
{
// Symbol table
const symsize = symtab.nsyms * @sizeOf(macho.nlist_64);
const increased_size = satMul(symsize, alloc_num) / alloc_den;
const test_end = symtab.symoff + increased_size;
if (end > symtab.symoff and start < test_end) {
return test_end;
}
}
{
// String table
const increased_size = satMul(symtab.strsize, alloc_num) / alloc_den;
const test_end = symtab.stroff + increased_size;
if (end > symtab.stroff and start < test_end) {
return test_end;
}
}
}
return null;
}
fn findFreeSpaceLinkedit(self: *DebugSymbols, object_size: u64, min_alignment: u16) u64 {
var start: u64 = self.linkedit_off;
while (self.detectAllocCollisionLinkedit(start, object_size)) |item_end| {
start = mem.alignForwardGeneric(u64, item_end, min_alignment);
}
return start;
}
fn relocateSymbolTable(self: *DebugSymbols) !void {
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
const nlocals = self.base.local_symbols.items.len;
const nglobals = self.base.global_symbols.items.len;
const nsyms = nlocals + nglobals;
if (symtab.nsyms < nsyms) {
const linkedit_segment = self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const needed_size = nsyms * @sizeOf(macho.nlist_64);
if (needed_size > self.allocatedSizeLinkedit(symtab.symoff)) {
// Move the entire symbol table to a new location
const new_symoff = self.findFreeSpaceLinkedit(needed_size, @alignOf(macho.nlist_64));
const existing_size = symtab.nsyms * @sizeOf(macho.nlist_64);
assert(new_symoff + existing_size <= self.linkedit_off + self.linkedit_size); // TODO expand LINKEDIT segment.
log.debug("relocating dSym symbol table from 0x{x}-0x{x} to 0x{x}-0x{x}", .{
symtab.symoff,
symtab.symoff + existing_size,
new_symoff,
new_symoff + existing_size,
});
const amt = try self.file.copyRangeAll(symtab.symoff, self.file, new_symoff, existing_size);
if (amt != existing_size) return error.InputOutput;
symtab.symoff = @intCast(u32, new_symoff);
}
symtab.nsyms = @intCast(u32, nsyms);
self.load_commands_dirty = true;
}
}
pub fn writeLocalSymbol(self: *DebugSymbols, index: usize) !void {
const tracy = trace(@src());
defer tracy.end();
try self.relocateSymbolTable();
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
const off = symtab.symoff + @sizeOf(macho.nlist_64) * index;
log.debug("writing dSym local symbol {} at 0x{x}", .{ index, off });
try self.file.pwriteAll(mem.asBytes(&self.base.local_symbols.items[index]), off);
}
fn writeStringTable(self: *DebugSymbols) !void {
if (!self.string_table_dirty) return;
const tracy = trace(@src());
defer tracy.end();
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
const allocated_size = self.allocatedSizeLinkedit(symtab.stroff);
const needed_size = mem.alignForwardGeneric(u64, self.base.string_table.items.len, @alignOf(u64));
if (needed_size > allocated_size) {
symtab.strsize = 0;
symtab.stroff = @intCast(u32, self.findFreeSpaceLinkedit(needed_size, 1));
}
symtab.strsize = @intCast(u32, needed_size);
log.debug("writing dSym string table from 0x{x} to 0x{x}", .{ symtab.stroff, symtab.stroff + symtab.strsize });
try self.file.pwriteAll(self.base.string_table.items, symtab.stroff);
self.load_commands_dirty = true;
self.string_table_dirty = false;
}
pub fn updateDeclLineNumber(self: *DebugSymbols, module: *Module, decl: *const Module.Decl) !void {
const tracy = trace(@src());
defer tracy.end();
const container_scope = decl.scope.cast(Module.Scope.Container).?;
const tree = container_scope.file_scope.contents.tree;
const file_ast_decls = tree.root_node.decls();
// TODO Look into improving the performance here by adding a token-index-to-line
// lookup table. Currently this involves scanning over the source code for newlines.
const fn_proto = file_ast_decls[decl.src_index].castTag(.FnProto).?;
const block = fn_proto.getBodyNode().?.castTag(.Block).?;
const line_delta = std.zig.lineDelta(tree.source, 0, tree.token_locs[block.lbrace].start);
const casted_line_off = @intCast(u28, line_delta);
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
const shdr = &dwarf_segment.sections.items[self.debug_line_section_index.?];
const file_pos = shdr.offset + decl.fn_link.macho.off + getRelocDbgLineOff();
var data: [4]u8 = undefined;
leb.writeUnsignedFixed(4, &data, casted_line_off);
try self.file.pwriteAll(&data, file_pos);
}
pub const DeclDebugBuffers = struct {
dbg_line_buffer: std.ArrayList(u8),
dbg_info_buffer: std.ArrayList(u8),
dbg_info_type_relocs: link.File.DbgInfoTypeRelocsTable,
};
/// Caller owns the returned memory.
pub fn initDeclDebugBuffers(
self: *DebugSymbols,
allocator: *Allocator,
module: *Module,
decl: *Module.Decl,
) !DeclDebugBuffers {
const tracy = trace(@src());
defer tracy.end();
var dbg_line_buffer = std.ArrayList(u8).init(allocator);
var dbg_info_buffer = std.ArrayList(u8).init(allocator);
var dbg_info_type_relocs: link.File.DbgInfoTypeRelocsTable = .{};
const typed_value = decl.typed_value.most_recent.typed_value;
switch (typed_value.ty.zigTypeTag()) {
.Fn => {
const zir_dumps = if (std.builtin.is_test) &[0][]const u8{} else build_options.zir_dumps;
if (zir_dumps.len != 0) {
for (zir_dumps) |fn_name| {
if (mem.eql(u8, mem.spanZ(decl.name), fn_name)) {
std.debug.print("\n{}\n", .{decl.name});
typed_value.val.cast(Value.Payload.Function).?.func.dump(module.*);
}
}
}
// For functions we need to add a prologue to the debug line program.
try dbg_line_buffer.ensureCapacity(26);
const line_off: u28 = blk: {
if (decl.scope.cast(Module.Scope.Container)) |container_scope| {
const tree = container_scope.file_scope.contents.tree;
const file_ast_decls = tree.root_node.decls();
// TODO Look into improving the performance here by adding a token-index-to-line
// lookup table. Currently this involves scanning over the source code for newlines.
const fn_proto = file_ast_decls[decl.src_index].castTag(.FnProto).?;
const block = fn_proto.getBodyNode().?.castTag(.Block).?;
const line_delta = std.zig.lineDelta(tree.source, 0, tree.token_locs[block.lbrace].start);
break :blk @intCast(u28, line_delta);
} else if (decl.scope.cast(Module.Scope.ZIRModule)) |zir_module| {
const byte_off = zir_module.contents.module.decls[decl.src_index].inst.src;
const line_delta = std.zig.lineDelta(zir_module.source.bytes, 0, byte_off);
break :blk @intCast(u28, line_delta);
} else {
unreachable;
}
};
dbg_line_buffer.appendSliceAssumeCapacity(&[_]u8{
DW.LNS_extended_op,
@sizeOf(u64) + 1,
DW.LNE_set_address,
});
// This is the "relocatable" vaddr, corresponding to `code_buffer` index `0`.
assert(dbg_line_vaddr_reloc_index == dbg_line_buffer.items.len);
dbg_line_buffer.items.len += @sizeOf(u64);
dbg_line_buffer.appendAssumeCapacity(DW.LNS_advance_line);
// This is the "relocatable" relative line offset from the previous function's end curly
// to this function's begin curly.
assert(getRelocDbgLineOff() == dbg_line_buffer.items.len);
// Here we use a ULEB128-fixed-4 to make sure this field can be overwritten later.
leb.writeUnsignedFixed(4, dbg_line_buffer.addManyAsArrayAssumeCapacity(4), line_off);
dbg_line_buffer.appendAssumeCapacity(DW.LNS_set_file);
assert(getRelocDbgFileIndex() == dbg_line_buffer.items.len);
// Once we support more than one source file, this will have the ability to be more
// than one possible value.
const file_index = 1;
leb.writeUnsignedFixed(4, dbg_line_buffer.addManyAsArrayAssumeCapacity(4), file_index);
// Emit a line for the begin curly with prologue_end=false. The codegen will
// do the work of setting prologue_end=true and epilogue_begin=true.
dbg_line_buffer.appendAssumeCapacity(DW.LNS_copy);
// .debug_info subprogram
const decl_name_with_null = decl.name[0 .. mem.lenZ(decl.name) + 1];
try dbg_info_buffer.ensureCapacity(dbg_info_buffer.items.len + 27 + decl_name_with_null.len);
const fn_ret_type = typed_value.ty.fnReturnType();
const fn_ret_has_bits = fn_ret_type.hasCodeGenBits();
if (fn_ret_has_bits) {
dbg_info_buffer.appendAssumeCapacity(abbrev_subprogram);
} else {
dbg_info_buffer.appendAssumeCapacity(abbrev_subprogram_retvoid);
}
// These get overwritten after generating the machine code. These values are
// "relocations" and have to be in this fixed place so that functions can be
// moved in virtual address space.
assert(dbg_info_low_pc_reloc_index == dbg_info_buffer.items.len);
dbg_info_buffer.items.len += @sizeOf(u64); // DW.AT_low_pc, DW.FORM_addr
assert(getRelocDbgInfoSubprogramHighPC() == dbg_info_buffer.items.len);
dbg_info_buffer.items.len += 4; // DW.AT_high_pc, DW.FORM_data4
if (fn_ret_has_bits) {
const gop = try dbg_info_type_relocs.getOrPut(allocator, fn_ret_type);
if (!gop.found_existing) {
gop.entry.value = .{
.off = undefined,
.relocs = .{},
};
}
try gop.entry.value.relocs.append(allocator, @intCast(u32, dbg_info_buffer.items.len));
dbg_info_buffer.items.len += 4; // DW.AT_type, DW.FORM_ref4
}
dbg_info_buffer.appendSliceAssumeCapacity(decl_name_with_null); // DW.AT_name, DW.FORM_string
mem.writeIntLittle(u32, dbg_info_buffer.addManyAsArrayAssumeCapacity(4), line_off + 1); // DW.AT_decl_line, DW.FORM_data4
dbg_info_buffer.appendAssumeCapacity(file_index); // DW.AT_decl_file, DW.FORM_data1
},
else => {
// TODO implement .debug_info for global variables
},
}
return DeclDebugBuffers{
.dbg_info_buffer = dbg_info_buffer,
.dbg_line_buffer = dbg_line_buffer,
.dbg_info_type_relocs = dbg_info_type_relocs,
};
}
pub fn commitDeclDebugInfo(
self: *DebugSymbols,
allocator: *Allocator,
module: *Module,
decl: *Module.Decl,
debug_buffers: *DeclDebugBuffers,
target: std.Target,
) !void {
const tracy = trace(@src());
defer tracy.end();
var dbg_line_buffer = &debug_buffers.dbg_line_buffer;
var dbg_info_buffer = &debug_buffers.dbg_info_buffer;
var dbg_info_type_relocs = &debug_buffers.dbg_info_type_relocs;
const symbol = self.base.local_symbols.items[decl.link.macho.local_sym_index];
const text_block = &decl.link.macho;
// If the Decl is a function, we need to update the __debug_line program.
const typed_value = decl.typed_value.most_recent.typed_value;
switch (typed_value.ty.zigTypeTag()) {
.Fn => {
// Perform the relocations based on vaddr.
{
const ptr = dbg_line_buffer.items[dbg_line_vaddr_reloc_index..][0..8];
mem.writeIntLittle(u64, ptr, symbol.n_value);
}
{
const ptr = dbg_info_buffer.items[dbg_info_low_pc_reloc_index..][0..8];
mem.writeIntLittle(u64, ptr, symbol.n_value);
}
{
const ptr = dbg_info_buffer.items[getRelocDbgInfoSubprogramHighPC()..][0..4];
mem.writeIntLittle(u32, ptr, @intCast(u32, text_block.size));
}
try dbg_line_buffer.appendSlice(&[_]u8{ DW.LNS_extended_op, 1, DW.LNE_end_sequence });
// Now we have the full contents and may allocate a region to store it.
// This logic is nearly identical to the logic below in `updateDeclDebugInfo` for
// `TextBlock` and the .debug_info. If you are editing this logic, you
// probably need to edit that logic too.
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
const debug_line_sect = &dwarf_segment.sections.items[self.debug_line_section_index.?];
const src_fn = &decl.fn_link.macho;
src_fn.len = @intCast(u32, dbg_line_buffer.items.len);
if (self.dbg_line_fn_last) |last| {
if (src_fn.next) |next| {
// Update existing function - non-last item.
if (src_fn.off + src_fn.len + min_nop_size > next.off) {
// It grew too big, so we move it to a new location.
if (src_fn.prev) |prev| {
_ = self.dbg_line_fn_free_list.put(allocator, prev, {}) catch {};
prev.next = src_fn.next;
}
next.prev = src_fn.prev;
src_fn.next = null;
// Populate where it used to be with NOPs.
const file_pos = debug_line_sect.offset + src_fn.off;
try self.pwriteDbgLineNops(0, &[0]u8{}, src_fn.len, file_pos);
// TODO Look at the free list before appending at the end.
src_fn.prev = last;
last.next = src_fn;
self.dbg_line_fn_last = src_fn;
src_fn.off = last.off + (last.len * alloc_num / alloc_den);
}
} else if (src_fn.prev == null) {
// Append new function.
// TODO Look at the free list before appending at the end.
src_fn.prev = last;
last.next = src_fn;
self.dbg_line_fn_last = src_fn;
src_fn.off = last.off + (last.len * alloc_num / alloc_den);
}
} else {
// This is the first function of the Line Number Program.
self.dbg_line_fn_first = src_fn;
self.dbg_line_fn_last = src_fn;
src_fn.off = self.dbgLineNeededHeaderBytes(module) * alloc_num / alloc_den;
}
const last_src_fn = self.dbg_line_fn_last.?;
const needed_size = last_src_fn.off + last_src_fn.len;
if (needed_size != debug_line_sect.size) {
if (needed_size > dwarf_segment.allocatedSize(debug_line_sect.offset)) {
const new_offset = dwarf_segment.findFreeSpace(needed_size, 1, null);
const existing_size = last_src_fn.off;
log.debug("moving __debug_line section: {} bytes from 0x{x} to 0x{x}", .{
existing_size,
debug_line_sect.offset,
new_offset,
});
const amt = try self.file.copyRangeAll(debug_line_sect.offset, self.file, new_offset, existing_size);
if (amt != existing_size) return error.InputOutput;
debug_line_sect.offset = @intCast(u32, new_offset);
debug_line_sect.addr = dwarf_segment.inner.vmaddr + new_offset - dwarf_segment.inner.fileoff;
}
debug_line_sect.size = needed_size;
self.load_commands_dirty = true; // TODO look into making only the one section dirty
self.debug_line_header_dirty = true;
}
const prev_padding_size: u32 = if (src_fn.prev) |prev| src_fn.off - (prev.off + prev.len) else 0;
const next_padding_size: u32 = if (src_fn.next) |next| next.off - (src_fn.off + src_fn.len) else 0;
// We only have support for one compilation unit so far, so the offsets are directly
// from the .debug_line section.
const file_pos = debug_line_sect.offset + src_fn.off;
try self.pwriteDbgLineNops(prev_padding_size, dbg_line_buffer.items, next_padding_size, file_pos);
// .debug_info - End the TAG_subprogram children.
try dbg_info_buffer.append(0);
},
else => {},
}
// Now we emit the .debug_info types of the Decl. These will count towards the size of
// the buffer, so we have to do it before computing the offset, and we can't perform the actual
// relocations yet.
var it = dbg_info_type_relocs.iterator();
while (it.next()) |entry| {
entry.value.off = @intCast(u32, dbg_info_buffer.items.len);
try self.addDbgInfoType(entry.key, dbg_info_buffer, target);
}
try self.updateDeclDebugInfoAllocation(allocator, text_block, @intCast(u32, dbg_info_buffer.items.len));
// Now that we have the offset assigned we can finally perform type relocations.
it = dbg_info_type_relocs.iterator();
while (it.next()) |entry| {
for (entry.value.relocs.items) |off| {
mem.writeIntLittle(
u32,
dbg_info_buffer.items[off..][0..4],
text_block.dbg_info_off + entry.value.off,
);
}
}
try self.writeDeclDebugInfo(text_block, dbg_info_buffer.items);
}
/// Asserts the type has codegen bits.
fn addDbgInfoType(
self: *DebugSymbols,
ty: Type,
dbg_info_buffer: *std.ArrayList(u8),
target: std.Target,
) !void {
switch (ty.zigTypeTag()) {
.Void => unreachable,
.NoReturn => unreachable,
.Bool => {
try dbg_info_buffer.appendSlice(&[_]u8{
abbrev_base_type,
DW.ATE_boolean, // DW.AT_encoding , DW.FORM_data1
1, // DW.AT_byte_size, DW.FORM_data1
'b',
'o',
'o',
'l',
0, // DW.AT_name, DW.FORM_string
});
},
.Int => {
const info = ty.intInfo(target);
try dbg_info_buffer.ensureCapacity(dbg_info_buffer.items.len + 12);
dbg_info_buffer.appendAssumeCapacity(abbrev_base_type);
// DW.AT_encoding, DW.FORM_data1
dbg_info_buffer.appendAssumeCapacity(switch (info.signedness) {
.signed => DW.ATE_signed,
.unsigned => DW.ATE_unsigned,
});
// DW.AT_byte_size, DW.FORM_data1
dbg_info_buffer.appendAssumeCapacity(@intCast(u8, ty.abiSize(target)));
// DW.AT_name, DW.FORM_string
try dbg_info_buffer.writer().print("{}\x00", .{ty});
},
else => {
std.log.scoped(.compiler).err("TODO implement .debug_info for type '{}'", .{ty});
try dbg_info_buffer.append(abbrev_pad1);
},
}
}
fn updateDeclDebugInfoAllocation(
self: *DebugSymbols,
allocator: *Allocator,
text_block: *TextBlock,
len: u32,
) !void {
const tracy = trace(@src());
defer tracy.end();
// This logic is nearly identical to the logic above in `updateDecl` for
// `SrcFn` and the line number programs. If you are editing this logic, you
// probably need to edit that logic too.
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
const debug_info_sect = &dwarf_segment.sections.items[self.debug_info_section_index.?];
text_block.dbg_info_len = len;
if (self.dbg_info_decl_last) |last| {
if (text_block.dbg_info_next) |next| {
// Update existing Decl - non-last item.
if (text_block.dbg_info_off + text_block.dbg_info_len + min_nop_size > next.dbg_info_off) {
// It grew too big, so we move it to a new location.
if (text_block.dbg_info_prev) |prev| {
_ = self.dbg_info_decl_free_list.put(allocator, prev, {}) catch {};
prev.dbg_info_next = text_block.dbg_info_next;
}
next.dbg_info_prev = text_block.dbg_info_prev;
text_block.dbg_info_next = null;
// Populate where it used to be with NOPs.
const file_pos = debug_info_sect.offset + text_block.dbg_info_off;
try self.pwriteDbgInfoNops(0, &[0]u8{}, text_block.dbg_info_len, false, file_pos);
// TODO Look at the free list before appending at the end.
text_block.dbg_info_prev = last;
last.dbg_info_next = text_block;
self.dbg_info_decl_last = text_block;
text_block.dbg_info_off = last.dbg_info_off + (last.dbg_info_len * alloc_num / alloc_den);
}
} else if (text_block.dbg_info_prev == null) {
// Append new Decl.
// TODO Look at the free list before appending at the end.
text_block.dbg_info_prev = last;
last.dbg_info_next = text_block;
self.dbg_info_decl_last = text_block;
text_block.dbg_info_off = last.dbg_info_off + (last.dbg_info_len * alloc_num / alloc_den);
}
} else {
// This is the first Decl of the .debug_info
self.dbg_info_decl_first = text_block;
self.dbg_info_decl_last = text_block;
text_block.dbg_info_off = self.dbgInfoNeededHeaderBytes() * alloc_num / alloc_den;
}
}
fn writeDeclDebugInfo(self: *DebugSymbols, text_block: *TextBlock, dbg_info_buf: []const u8) !void {
const tracy = trace(@src());
defer tracy.end();
// This logic is nearly identical to the logic above in `updateDecl` for
// `SrcFn` and the line number programs. If you are editing this logic, you
// probably need to edit that logic too.
const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment;
const debug_info_sect = &dwarf_segment.sections.items[self.debug_info_section_index.?];
const last_decl = self.dbg_info_decl_last.?;
// +1 for a trailing zero to end the children of the decl tag.
const needed_size = last_decl.dbg_info_off + last_decl.dbg_info_len + 1;
if (needed_size != debug_info_sect.size) {
if (needed_size > dwarf_segment.allocatedSize(debug_info_sect.offset)) {
const new_offset = dwarf_segment.findFreeSpace(needed_size, 1, null);
const existing_size = last_decl.dbg_info_off;
log.debug("moving __debug_info section: {} bytes from 0x{x} to 0x{x}", .{
existing_size,
debug_info_sect.offset,
new_offset,
});
const amt = try self.file.copyRangeAll(debug_info_sect.offset, self.file, new_offset, existing_size);
if (amt != existing_size) return error.InputOutput;
debug_info_sect.offset = @intCast(u32, new_offset);
debug_info_sect.addr = dwarf_segment.inner.vmaddr + new_offset - dwarf_segment.inner.fileoff;
}
debug_info_sect.size = needed_size;
self.load_commands_dirty = true; // TODO look into making only the one section dirty
self.debug_info_header_dirty = true;
}
const prev_padding_size: u32 = if (text_block.dbg_info_prev) |prev|
text_block.dbg_info_off - (prev.dbg_info_off + prev.dbg_info_len)
else
0;
const next_padding_size: u32 = if (text_block.dbg_info_next) |next|
next.dbg_info_off - (text_block.dbg_info_off + text_block.dbg_info_len)
else
0;
// To end the children of the decl tag.
const trailing_zero = text_block.dbg_info_next == null;
// We only have support for one compilation unit so far, so the offsets are directly
// from the .debug_info section.
const file_pos = debug_info_sect.offset + text_block.dbg_info_off;
try self.pwriteDbgInfoNops(prev_padding_size, dbg_info_buf, next_padding_size, trailing_zero, file_pos);
}
fn getDebugLineProgramOff(self: DebugSymbols) u32 {
return self.dbg_line_fn_first.?.off;
}
fn getDebugLineProgramEnd(self: DebugSymbols) u32 {
return self.dbg_line_fn_last.?.off + self.dbg_line_fn_last.?.len;
}
/// TODO Improve this to use a table.
fn makeDebugString(self: *DebugSymbols, allocator: *Allocator, bytes: []const u8) !u32 {
try self.debug_string_table.ensureCapacity(allocator, self.debug_string_table.items.len + bytes.len + 1);
const result = self.debug_string_table.items.len;
self.debug_string_table.appendSliceAssumeCapacity(bytes);
self.debug_string_table.appendAssumeCapacity(0);
return @intCast(u32, result);
}
/// The reloc offset for the line offset of a function from the previous function's line.
/// It's a fixed-size 4-byte ULEB128.
fn getRelocDbgLineOff() usize {
return dbg_line_vaddr_reloc_index + @sizeOf(u64) + 1;
}
fn getRelocDbgFileIndex() usize {
return getRelocDbgLineOff() + 5;
}
fn getRelocDbgInfoSubprogramHighPC() u32 {
return dbg_info_low_pc_reloc_index + @sizeOf(u64);
}
fn dbgLineNeededHeaderBytes(self: DebugSymbols, module: *Module) u32 {
const directory_entry_format_count = 1;
const file_name_entry_format_count = 1;
const directory_count = 1;
const file_name_count = 1;
const root_src_dir_path_len = if (module.root_pkg.root_src_directory.path) |p| p.len else 1; // "."
return @intCast(u32, 53 + directory_entry_format_count * 2 + file_name_entry_format_count * 2 +
directory_count * 8 + file_name_count * 8 +
// These are encoded as DW.FORM_string rather than DW.FORM_strp as we would like
// because of a workaround for readelf and gdb failing to understand DWARFv5 correctly.
root_src_dir_path_len +
module.root_pkg.root_src_path.len);
}
fn dbgInfoNeededHeaderBytes(self: DebugSymbols) u32 {
return 120;
}
/// Writes to the file a buffer, prefixed and suffixed by the specified number of
/// bytes of NOPs. Asserts each padding size is at least `min_nop_size` and total padding bytes
/// are less than 126,976 bytes (if this limit is ever reached, this function can be
/// improved to make more than one pwritev call, or the limit can be raised by a fixed
/// amount by increasing the length of `vecs`).
fn pwriteDbgLineNops(
self: *DebugSymbols,
prev_padding_size: usize,
buf: []const u8,
next_padding_size: usize,
offset: u64,
) !void {
const tracy = trace(@src());
defer tracy.end();
const page_of_nops = [1]u8{DW.LNS_negate_stmt} ** 4096;
const three_byte_nop = [3]u8{ DW.LNS_advance_pc, 0b1000_0000, 0 };
var vecs: [32]std.os.iovec_const = undefined;
var vec_index: usize = 0;
{
var padding_left = prev_padding_size;
if (padding_left % 2 != 0) {
vecs[vec_index] = .{
.iov_base = &three_byte_nop,
.iov_len = three_byte_nop.len,
};
vec_index += 1;
padding_left -= three_byte_nop.len;
}
while (padding_left > page_of_nops.len) {
vecs[vec_index] = .{
.iov_base = &page_of_nops,
.iov_len = page_of_nops.len,
};
vec_index += 1;
padding_left -= page_of_nops.len;
}
if (padding_left > 0) {
vecs[vec_index] = .{
.iov_base = &page_of_nops,
.iov_len = padding_left,
};
vec_index += 1;
}
}
vecs[vec_index] = .{
.iov_base = buf.ptr,
.iov_len = buf.len,
};
vec_index += 1;
{
var padding_left = next_padding_size;
if (padding_left % 2 != 0) {
vecs[vec_index] = .{
.iov_base = &three_byte_nop,
.iov_len = three_byte_nop.len,
};
vec_index += 1;
padding_left -= three_byte_nop.len;
}
while (padding_left > page_of_nops.len) {
vecs[vec_index] = .{
.iov_base = &page_of_nops,
.iov_len = page_of_nops.len,
};
vec_index += 1;
padding_left -= page_of_nops.len;
}
if (padding_left > 0) {
vecs[vec_index] = .{
.iov_base = &page_of_nops,
.iov_len = padding_left,
};
vec_index += 1;
}
}
try self.file.pwritevAll(vecs[0..vec_index], offset - prev_padding_size);
}
/// Writes to the file a buffer, prefixed and suffixed by the specified number of
/// bytes of padding.
fn pwriteDbgInfoNops(
self: *DebugSymbols,
prev_padding_size: usize,
buf: []const u8,
next_padding_size: usize,
trailing_zero: bool,
offset: u64,
) !void {
const tracy = trace(@src());
defer tracy.end();
const page_of_nops = [1]u8{abbrev_pad1} ** 4096;
var vecs: [32]std.os.iovec_const = undefined;
var vec_index: usize = 0;
{
var padding_left = prev_padding_size;
while (padding_left > page_of_nops.len) {
vecs[vec_index] = .{
.iov_base = &page_of_nops,
.iov_len = page_of_nops.len,
};
vec_index += 1;
padding_left -= page_of_nops.len;
}
if (padding_left > 0) {
vecs[vec_index] = .{
.iov_base = &page_of_nops,
.iov_len = padding_left,
};
vec_index += 1;
}
}
vecs[vec_index] = .{
.iov_base = buf.ptr,
.iov_len = buf.len,
};
vec_index += 1;
{
var padding_left = next_padding_size;
while (padding_left > page_of_nops.len) {
vecs[vec_index] = .{
.iov_base = &page_of_nops,
.iov_len = page_of_nops.len,
};
vec_index += 1;
padding_left -= page_of_nops.len;
}
if (padding_left > 0) {
vecs[vec_index] = .{
.iov_base = &page_of_nops,
.iov_len = padding_left,
};
vec_index += 1;
}
}
if (trailing_zero) {
var zbuf = [1]u8{0};
vecs[vec_index] = .{
.iov_base = &zbuf,
.iov_len = zbuf.len,
};
vec_index += 1;
}
try self.file.pwritevAll(vecs[0..vec_index], offset - prev_padding_size);
} | src/link/MachO/DebugSymbols.zig |
const std = @import("../std.zig");
const mem = std.mem;
/// Allocator that fails after N allocations, useful for making sure out of
/// memory conditions are handled correctly.
///
/// To use this, first initialize it and get an allocator with
///
/// `const failing_allocator = &FailingAllocator.init(<allocator>,
/// <fail_index>).allocator;`
///
/// Then use `failing_allocator` anywhere you would have used a
/// different allocator.
pub const FailingAllocator = struct {
allocator: mem.Allocator,
index: usize,
fail_index: usize,
internal_allocator: *mem.Allocator,
allocated_bytes: usize,
freed_bytes: usize,
allocations: usize,
deallocations: usize,
/// `fail_index` is the number of successful allocations you can
/// expect from this allocator. The next allocation will fail.
/// For example, if this is called with `fail_index` equal to 2,
/// the following test will pass:
///
/// var a = try failing_alloc.create(i32);
/// var b = try failing_alloc.create(i32);
/// testing.expectError(error.OutOfMemory, failing_alloc.create(i32));
pub fn init(allocator: *mem.Allocator, fail_index: usize) FailingAllocator {
return FailingAllocator{
.internal_allocator = allocator,
.fail_index = fail_index,
.index = 0,
.allocated_bytes = 0,
.freed_bytes = 0,
.allocations = 0,
.deallocations = 0,
.allocator = mem.Allocator{
.reallocFn = realloc,
.shrinkFn = shrink,
},
};
}
fn realloc(allocator: *mem.Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);
if (self.index == self.fail_index) {
return error.OutOfMemory;
}
const result = try self.internal_allocator.reallocFn(
self.internal_allocator,
old_mem,
old_align,
new_size,
new_align,
);
if (new_size < old_mem.len) {
self.freed_bytes += old_mem.len - new_size;
if (new_size == 0)
self.deallocations += 1;
} else if (new_size > old_mem.len) {
self.allocated_bytes += new_size - old_mem.len;
if (old_mem.len == 0)
self.allocations += 1;
}
self.index += 1;
return result;
}
fn shrink(allocator: *mem.Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);
const r = self.internal_allocator.shrinkFn(self.internal_allocator, old_mem, old_align, new_size, new_align);
self.freed_bytes += old_mem.len - r.len;
if (new_size == 0)
self.deallocations += 1;
return r;
}
}; | lib/std/debug/failing_allocator.zig |
const std = @import("std");
const debug = std.debug.print;
const testing = std.testing;
pub const HttpMethod = enum {
CONNECT,
DELETE,
GET,
HEAD,
OPTIONS,
PATCH,
POST,
PUT,
TRACE,
pub fn string(self: HttpMethod) [:0]const u8 {
return @tagName(self);
}
pub fn create(raw: []const u8) !HttpMethod {
return std.meta.stringToEnum(HttpMethod, raw) orelse error.NoSuchHttpMethod;
}
};
pub const HttpHeader = struct {
pub const MAX_HEADER_LEN = 8*1024;
name: std.BoundedArray(u8, 256),
value: std.BoundedArray(u8, MAX_HEADER_LEN),
pub fn create(name: []const u8, value: []const u8) !HttpHeader {
return HttpHeader{
.name = std.BoundedArray(u8, 256).fromSlice(std.mem.trim(u8, name, " ")) catch {
return error.ParseError;
},
.value = std.BoundedArray(u8, MAX_HEADER_LEN).fromSlice(std.mem.trim(u8, value, " ")) catch {
return error.ParseError;
},
};
}
pub fn render(self: *HttpHeader, comptime capacity: usize, out: *std.BoundedArray(u8, capacity)) !void {
try out.appendSlice(self.name.slice());
try out.appendSlice(": ");
try out.appendSlice(self.value.slice());
}
};
const HttpRequest = struct {
const MAX_HEADER_LEN = 8*1024;
const MAX_URI_LEN = 8*1024;
const ParseState = enum {
expecting_request_line,
getting_method,
getting_uri,
getting_http_version,
expecting_headers,
expecting_header,
expecting_header_start,
parsing_header_got_nl,
parsing_header,
end_of_headers,
expecting_payload,
start, // Waiting to find token
cr, // Expecting lf -> .start
method, //
url,
http_version,
header_start,
header,
header_end,
eof, // This means that we're good to go!
};
allocator: *std.mem.Allocator,
method: HttpMethod = HttpMethod.GET,
uri: std.BoundedArray(u8, 8 * 1024) = std.BoundedArray(u8, MAX_URI_LEN).init(0) catch unreachable,
http_version: std.BoundedArray(u8, 32) = std.BoundedArray(u8, 32).init(0) catch unreachable,
// URL: protocol, domain, subsection, hash, query
/// Headers
headers: std.StringArrayHashMap(HttpHeader),
/// Payload. Allocated on heap. After parse, it must be free'd
maybe_payload: ?[]u8 = null,
parse_state: ParseState = ParseState.expecting_request_line,
fn addHeader(self: *@This(), header_buf: []const u8) !void {
var key_scrap: [256]u8 = undefined;
var col_pos = std.mem.indexOf(u8, header_buf, ":") orelse return error.InvalidHeaderFormat;
var key = std.mem.trim(u8, header_buf[0..col_pos], " ");
// std.mem.copy(u8, scrap[0..], key);
var key_lc = std.ascii.lowerString(key_scrap[0..], key);
var value = std.mem.trim(u8, header_buf[col_pos+1..], " "); // TODO: remove inner newlines
debug("Added entry: {s}: {s}\n", .{key_lc, value});
try self.headers.put(key_lc, try HttpHeader.create(key_lc, value));
}
fn getHeader(self: *@This(), header: []const u8) ?[]const u8 {
debug("...: {s}\n", .{self.headers.get(header)});
return "Dummy";
// return self.headers.get(header).?.constSlice();
}
fn init(allocator: *std.mem.Allocator) HttpRequest {
return .{
.allocator = allocator,
.headers = std.StringArrayHashMap(HttpHeader).init(allocator),
// .uri = @TypeOf(@This().uri).init(0) catch unreachable,
};
}
fn deinit(self: *HttpRequest) void {
if (self.maybe_payload) |payload| {
self.allocator.destroy(payload.ptr);
}
self.headers.deinit();
}
fn feedParser(self: *HttpRequest, buf_chunk: []const u8) !ParseState {
const Token = struct {
source_buf: []const u8,
start: usize = 0,
end: usize = 0,
pub fn slice(_self: *@This()) []const u8 {
return _self.source_buf[_self.start.._self.end];
}
};
// Read through chunk, and parse out parts as far as possible
// Always store point of last finished piece of information
// How to keep remainder? Have an internal buffer which use for
// scrap?
// Or, since we kind of know what we are expecting to be parsing, we can keep an unfinished piece of this?
// Request-line? Header?, payload (only if Content-Length)?
// start assuming that we get the entire header in one chunk...
var tok = Token{
.source_buf = buf_chunk,
};
var idx: usize = 0;
while (idx < buf_chunk.len) : (idx += 1) {
const c = buf_chunk[idx];
switch (self.parse_state) {
////////////////////////////////////////////////////
// Parsing request line
////////////////////////////////////////////////////
.expecting_request_line => switch (c) {
// '\r' => { self.parse_state = .cr; },
'A'...'Z' => {
tok.start = idx;
self.parse_state = .getting_method;
},
else => {
return error.MalformedHeader;
},
},
.getting_method => switch (c) {
' ' => {
tok.end = idx;
self.method = try HttpMethod.create(tok.slice());
self.parse_state = .getting_uri;
tok.start = idx + 1;
// TODO: Are there always only one space here?
},
else => {},
},
.getting_uri => switch (c) {
' ' => {
tok.end = idx;
try self.uri.appendSlice(tok.slice());
self.parse_state = .getting_http_version;
tok.start = idx + 1;
},
else => {},
},
.getting_http_version => switch (c) {
'\r' => {
tok.end = idx;
try self.http_version.appendSlice(tok.slice());
self.parse_state = .expecting_headers;
},
else => {},
},
////////////////////////////////////////////////////
// Finished parsing request line
////////////////////////////////////////////////////
// Parse headers
// Only store headers we care for?
// Header starts at newline, and ends at next newline which is followed by a non-space character
////////////////////////////////////////////////////
.expecting_headers => switch(c) {
//'a'...'z','A'...'Z' => {
'\n' => {
self.parse_state = .expecting_header_start;
},
else => {},
},
.expecting_header_start => switch(c) {
'a'...'z','A'...'Z' => {
self.parse_state = .parsing_header;
tok.start = idx;
},
else => {},
},
.parsing_header => switch(c) {
// Parse until newline+alpha
'\n' => {
self.parse_state = .parsing_header_got_nl;
},
else => {}
},
.parsing_header_got_nl => switch(c) {
'\r', '\n' => {
tok.end = idx-2;
try self.addHeader(tok.slice());
self.parse_state = .end_of_headers;
},
'a'...'z','A'...'Z' => {
// Got end of previous header, starting new
tok.end = idx-2;
try self.addHeader(tok.slice());
// debug("Got header: {s}\n", .{tok.slice()});
// Store header
// Continue parsing
self.parse_state = .expecting_header_start;
},
else => {}
},
////////////////////////////////////////////////////
// Finished parsing headers
////////////////////////////////////////////////////
// Possibly parse body
////////////////////////////////////////////////////
////////////////////////////////////////////////////
// Finished
////////////////////////////////////////////////////
else => {},
}
}
// const ParseState = enum {
// start,
// method,
// url,
// http_version,
// header_start,
// header,
// header_end,
// eof,
// };
return self.parse_state;
}
};
test "HttpRequest" {
var allocator = testing.allocator;
var request = HttpRequest.init(allocator);
defer request.deinit();
var state = try request.feedParser("GET /index.html HTTP/1.1\r\nContent-Type: application/xml\r\n\r\n");
debug("state: {s}\n", .{state});
// try testing.expectEqualStrings("GET", request.method[0..]);
try testing.expectEqual(HttpMethod.GET, request.method);
try testing.expectEqualStrings("/index.html", request.uri.slice());
try testing.expectEqualStrings("HTTP/1.1", request.http_version.slice());
// try testing.expectEqualStrings("application/xml", request.getHeader("content-type").?);
// try request.headers.put("key", try std.BoundedArray(u8, 8*1024).fromSlice("value"));
// for(request.headers.keys()) |key| {
// if(request.headers.getKeyPtr(key.ptr.*)) |entry| {
// debug("key: {s} - {s}: {s}\n", .{key, entry.name, entry.value});
// }
// }
var it = request.headers.iterator();
var maybe_value = it.next();
while(maybe_value) |value| {
// debug("* '{s}': '{s}'\n", .{request.headers.getKeyPtr(value.key_ptr.*), value.value_ptr.slice()});
debug("* '{s}': '{s}'\n", .{ value.value_ptr.name.slice(), value.value_ptr.value.slice()});
// debug("* {s}: {s}\n", .{header, request.headers.get(header).?.slice()});
maybe_value = it.next();
}
}
pub fn main() !void {
// Initiate
var server = std.net.StreamServer.init(.{});
defer server.deinit();
// Listen for requests
try server.listen(std.net.Address.initIp4([_]u8{ 127, 0, 0, 1 }, 8181));
// loop:
// Dispatch to thread
var conn = try server.accept();
// Read and parse request
var read_buf: [1024]u8 = undefined;
var len = try conn.stream.read(read_buf[0..]);
debug("Got: {d} - {s}\n", .{ len, read_buf[0..len] });
// Send response
_ = try conn.stream.write("Out!\n");
} | server/main.zig |
const std = @import("std");
const testing = std.testing;
const debug = std.debug.print;
const daya = @import("daya");
const main = @import("main.zig");
pub const OutputFormat = enum {
dot,
png,
svg
};
pub const AppArgs = struct {
input_file: []const u8,
output_file: []const u8,
output_format: OutputFormat = .png,
};
pub fn printHelp(full: bool) void {
debug(
\\{0s} v{1s} - Quick graphing utility
\\
\\Usage: {0s} [arguments] input.daya output.png
\\
, .{ main.APP_NAME, main.APP_VERSION});
if (!full) {
debug(
\\
\\try '{0s} --help' for more information.
\\
, .{main.APP_NAME});
return;
}
debug(
\\
\\Examples:
\\ {0s} myapp.daya mynicediagram.png
\\ {0s} myapp.daya mynicediagram.svg
\\ {0s} myapp.daya mynicediagram.dot
\\
\\Arguments
\\ -h, --help Show this help and exit
\\ --version Show version and exit
// \\ -v, --verbose Verbose output
\\
\\https://github.com/michaelo/daya
\\
, .{main.APP_NAME});
}
fn argIs(arg: []const u8, full: []const u8, short: ?[]const u8) bool {
return std.mem.eql(u8, arg, full) or std.mem.eql(u8, arg, short orelse "321NOSUCHTHING123");
}
fn argHasValue(arg: []const u8, full: []const u8, short: ?[]const u8) ?[]const u8 {
const eq_pos = std.mem.indexOf(u8, arg, "=") orelse return null;
const key = arg[0..eq_pos];
if(argIs(key, full, short)) {
return arg[eq_pos + 1 ..];
} else return null;
}
fn getLowercaseFileext(file: []const u8, scrap: []u8) ![]u8 {
const last_dot = std.mem.lastIndexOf(u8, file, ".") orelse return error.NoExtFound;
return std.ascii.lowerString(scrap, file[last_dot+1..]);
}
pub fn parseArgs(args: []const []const u8) !AppArgs {
if(args.len < 1) {
debug("ERROR: No arguments provided\n", .{});
printHelp(false);
return error.NoArguments;
}
var scrap: [64]u8 = undefined;
var maybe_input_file: ?[]const u8 = null;
var maybe_output_file: ?[]const u8 = null;
var maybe_output_format: ?OutputFormat = null;
for (args) |arg| {
// Flags
if(argIs(arg, "--help", "-h")) {
printHelp(true);
return error.OkExit;
}
if(argIs(arg, "--version", null)) {
debug("{0s} v{1s} (libdaya v{2s})\n", .{main.APP_NAME, main.APP_VERSION, daya.LIB_VERSION});
return error.OkExit;
}
if(arg[0] == '-') {
debug("ERROR: Unsupported argument '{s}'\n", .{arg});
printHelp(false);
return error.InvalidArgument;
}
// Check for input file
const ext = getLowercaseFileext(arg, scrap[0..]) catch {
debug("WARNING: Could not read file-extension of argument '{s}' (ignoring)\n", .{arg});
continue;
};
if(std.mem.eql(u8, ext, "daya")) {
maybe_input_file = arg[0..];
continue;
}
// Check for valid output-file
if(std.meta.stringToEnum(OutputFormat, ext)) |format| {
maybe_output_file = arg[0..];
maybe_output_format = format;
continue;
}
debug("WARNING: Unhandled argument: '{s}'\n", .{arg});
}
// Validate parsed args
const input_file = maybe_input_file orelse {
debug("ERROR: Missing input file\n", .{});
return error.NoInputFile;
};
const output_file = maybe_output_file orelse {
debug("ERROR: Missing output file\n", .{});
return error.NoOutputFile;
};
const output_format = maybe_output_format orelse {
debug("ERROR: Unknown output format\n", .{});
return error.NoOutputFormat;
};
// Donaroo
return AppArgs{
.input_file = input_file,
.output_file = output_file,
.output_format = output_format,
};
}
test "ArgParse" {
try testing.expectError(error.OkExit, parseArgs(&.{"--help"}));
try testing.expectError(error.OkExit, parseArgs(&.{"-h"}));
try testing.expectError(error.OkExit, parseArgs(&.{"--version"}));
} | compiler/src/argparse.zig |
const std = @import("std");
const fs = std.fs;
const Image = @import("../image.zig").Image;
const upaya = @import("../upaya.zig");
const math = upaya.math;
const stb = upaya.stb;
pub const TexturePacker = struct {
pub const Sprite = struct {
name: []const u8,
source: math.Rect,
origin: math.Point,
};
pub const Atlas = struct {
sprites: []Sprite,
width: u16,
height: u16,
image: upaya.Image = undefined,
heightmap: upaya.Image = undefined,
pub fn init(frames: []stb.stbrp_rect, origins: []math.Point, files: [][]const u8, size: Size, method: PackingMethod) Atlas {
std.debug.assert(frames.len == files.len);
var res_atlas = Atlas{
.sprites = upaya.mem.allocator.alloc(Sprite, files.len) catch unreachable,
.width = size.width,
.height = size.height,
};
// convert to upaya rects
for (frames) |frame, i| {
res_atlas.sprites[i].source = .{ .x = frame.x, .y = frame.y, .width = frame.w, .height = frame.h };
}
for (files) |file, i| {
res_atlas.sprites[i].name = upaya.mem.allocator.dupe(u8, fs.path.basename(file)) catch unreachable;
}
for (origins) |origin, i| {
res_atlas.sprites[i].origin = origin;
}
// generate the atlas
var image = upaya.Image.init(size.width, size.height);
image.fillRect(.{ .width = size.width, .height = size.height }, upaya.math.Color.transparent);
var heightmap = upaya.Image.init(size.width, size.height);
heightmap.fillRect(.{ .width = size.width, .height = size.height }, upaya.math.Color.transparent);
for (files) |file, i| {
var sub_image = upaya.Image.initFromFile(file);
defer sub_image.deinit();
if (method == .Tight) {
_ = sub_image.crop();
}
image.blit(sub_image, frames[i].x, frames[i].y);
var height_sub_image = upaya.Image.initFromFile(file);
defer height_sub_image.deinit();
var r: u8 = 1;
var row: i32 = @intCast(i32, height_sub_image.h);
var containsColor: bool = false;
var j: usize = height_sub_image.pixels.len - 1;
while (j > 0) : (j -= 1) {
var temp_row = @intCast(i32, @divTrunc(j, height_sub_image.w));
if (temp_row != row and r < 255) {
r += 1;
row = temp_row;
}
if (height_sub_image.pixels[j] & 0xFF000000 != 0) {
var color = upaya.math.Color.fromBytes(r, r, r, 255);
height_sub_image.pixels[j] = color.value;
containsColor = true;
}
}
if (method == .Tight) {
_ = height_sub_image.crop();
}
heightmap.blit(height_sub_image, frames[i].x, frames[i].y);
}
res_atlas.image = image;
res_atlas.heightmap = heightmap;
return res_atlas;
}
pub fn initImages(frames: []stb.stbrp_rect, origins: []math.Point, files: [][]const u8, images: []upaya.Image, size: Size, method: PackingMethod) Atlas {
_ = method;
std.debug.assert(frames.len == files.len and frames.len == images.len);
var res_atlas = Atlas{
.sprites = upaya.mem.allocator.alloc(Sprite, images.len) catch unreachable,
.width = size.width,
.height = size.height,
};
// convert to upaya rects
for (frames) |frame, i| {
res_atlas.sprites[i].source = .{ .x = frame.x, .y = frame.y, .width = frame.w, .height = frame.h };
}
for (files) |file, i| {
res_atlas.sprites[i].name = file;
}
for (origins) |origin, i| {
res_atlas.sprites[i].origin = origin;
}
// generate the atlas
var image = upaya.Image.init(size.width, size.height);
image.fillRect(.{ .width = size.width, .height = size.height }, upaya.math.Color.transparent);
var heightmap = upaya.Image.init(size.width, size.height);
heightmap.fillRect(.{ .width = size.width, .height = size.height }, upaya.math.Color.transparent);
for (images) |im, i| {
var sub_image = im;
//defer sub_image.deinit();
// if (method == .Tight) {
// _ = sub_image.crop();
// }
image.blit(sub_image, frames[i].x, frames[i].y);
var height_sub_image = im;
defer height_sub_image.deinit();
var r: u8 = 1;
var row: i32 = @intCast(i32, height_sub_image.h);
var containsColor: bool = false;
var j: usize = height_sub_image.pixels.len - 1;
while (j > 0) : (j -= 1) {
var temp_row = @intCast(i32, @divTrunc(j, height_sub_image.w));
if (temp_row != row and r < 255) {
r += 1;
row = temp_row;
}
if (height_sub_image.pixels[j] & 0xFF000000 != 0) {
var color = upaya.math.Color.fromBytes(r, r, r, 255);
height_sub_image.pixels[j] = color.value;
containsColor = true;
}
}
// if (method == .Tight) {
// _ = height_sub_image.crop();
// }
heightmap.blit(height_sub_image, frames[i].x, frames[i].y);
}
res_atlas.image = image;
res_atlas.heightmap = heightmap;
return res_atlas;
}
pub fn deinit(self: Atlas) void {
for (self.sprites) |sprite| {
upaya.mem.allocator.free(sprite.name);
}
upaya.mem.allocator.free(self.sprites);
self.image.deinit();
}
/// saves the atlas image and a json file with the atlas details. filename should be only the name with no extension.
pub fn save(self: Atlas, folder: []const u8, filename: []const u8) void {
const img_filename = std.mem.concat(upaya.mem.allocator, u8, &[_][]const u8{ filename, ".png" }) catch unreachable;
const atlas_filename = std.mem.concat(upaya.mem.allocator, u8, &[_][]const u8{ filename, ".atlas" }) catch unreachable;
const heightmap_filename = std.mem.concat(upaya.mem.allocator, u8, &[_][]const u8{ filename, "_h.png" }) catch unreachable;
var out_file = fs.path.join(upaya.mem.tmp_allocator, &[_][]const u8{ folder, img_filename }) catch unreachable;
self.image.save(out_file);
out_file = fs.path.join(upaya.mem.tmp_allocator, &[_][]const u8{ folder, heightmap_filename }) catch unreachable;
self.heightmap.save(out_file);
out_file = fs.path.join(upaya.mem.tmp_allocator, &[_][]const u8{ folder, atlas_filename }) catch unreachable;
var handle = std.fs.cwd().createFile(out_file, .{}) catch unreachable;
defer handle.close();
const out_stream = handle.writer();
const options = std.json.StringifyOptions{ .whitespace = .{} };
std.json.stringify(.{ .sprites = self.sprites }, options, out_stream) catch unreachable;
}
};
pub const Size = struct {
width: u16,
height: u16,
};
pub const PackingMethod = enum {
Full,
Tight,
};
pub fn pack(folder: []const u8, method: PackingMethod) !Atlas {
const pngs = upaya.fs.getAllFilesOfType(upaya.mem.allocator, folder, ".png", true);
var origins = std.ArrayList(math.Point).init(upaya.mem.allocator);
const frames = getFramesForPngs(pngs, &origins, method);
if (runRectPacker(frames)) |atlas_size| {
return Atlas.init(frames, origins.items, pngs, atlas_size, method);
} else {
return error.NotEnoughRoom;
}
}
pub fn packPyxelEdit(files: []upaya.importers.PyxelEdit, method: PackingMethod) !Atlas {
var origins = std.ArrayList(math.Point).init(upaya.mem.allocator);
var names = std.ArrayList([]const u8).init(upaya.mem.allocator);
var images = std.ArrayList(upaya.Image).init(upaya.mem.allocator);
var frames = std.ArrayList(stb.stbrp_rect).init(upaya.mem.allocator);
for (files) |p| {
for (p.animations) |a| {
var i: usize = 0;
while (i < a.length) : (i += 1) {
const w = @intCast(usize, p.canvas.tileWidth);
const h = @intCast(usize, p.canvas.tileHeight);
const tilesWide = @divExact(@intCast(usize, p.canvas.width), w);
const tile = @intCast(usize, a.baseTile) + i;
const col = @mod(tile, tilesWide);
const row = @divTrunc(tile, tilesWide);
const src_x = col * w;
const src_y = row * h;
var img = upaya.Image.init(w, h);
img.fillRect(.{ .width = p.canvas.tileWidth, .height = p.canvas.tileHeight }, upaya.math.Color.transparent);
for (p.layers) |l| {
if (l.hidden or l.muted) {
continue;
}
var j = img.h;
var dst_y: usize = 0;
var yy = src_y;
var data = img.pixels[dst_y * img.w ..];
while (j > 0) : (j -= 1) {
const src_row = l.texture.pixels[src_x + (yy * l.texture.w) .. (src_x + (yy * l.texture.w)) + img.w];
//std.mem.copy(u32, data, src_row);
for (src_row) |pixel, k| {
if (data[k] & 0xFF000000 == 0){
if (pixel & 0xFF000000 != 0){
data[k] = src_row[k];
}
}
}
yy += 1;
dst_y += 1;
data = img.pixels[dst_y * img.w ..];
}
}
if (method == .Tight) {
const offset = img.crop();
try origins.append(.{ .x = 0 - offset.x, .y = 0 - offset.y });
}
if (method == .Full) {
try origins.append(.{ .x = 0, .y = 0 });
}
try frames.append(.{
.id = @intCast(c_int, i),
.w = @intCast(u16, img.w),
.h = @intCast(u16, img.h),
});
var name = try std.mem.concat(upaya.mem.allocator, u8, &[_][]const u8{ a.name, "_", try std.fmt.allocPrint(upaya.mem.allocator, "{d}", .{i}) });
try names.append(name);
try images.append(img);
}
}
}
if (runRectPacker(frames.items)) |atlas_size| {
return Atlas.initImages(frames.items, origins.items, names.items, images.items, atlas_size, method);
} else {
return error.NotEnoughRoom;
}
}
fn getFramesForPngs(pngs: [][]const u8, origins: *std.ArrayList(math.Point), method: PackingMethod) []stb.stbrp_rect {
var frames = std.ArrayList(stb.stbrp_rect).init(upaya.mem.allocator);
for (pngs) |png, i| {
var tex = upaya.Image.initFromFile(png);
defer tex.deinit();
if (method == .Tight) {
var offset = tex.crop();
origins.*.append(.{ .x = 0 - offset.x, .y = 0 - offset.y }) catch unreachable;
}
if (method == .Full) {
origins.*.append(.{ .x = 0, .y = 0 }) catch unreachable;
}
frames.append(.{
.id = @intCast(c_int, i),
.w = @intCast(u16, tex.w),
.h = @intCast(u16, tex.h),
}) catch unreachable;
}
return frames.toOwnedSlice();
}
fn runRectPacker(frames: []stb.stbrp_rect) ?Size {
var ctx: stb.stbrp_context = undefined;
const node_count = 4096 * 2;
var nodes: [node_count]stb.stbrp_node = undefined;
const texture_sizes = [_][2]c_int{
[_]c_int{ 256, 256 }, [_]c_int{ 512, 256 }, [_]c_int{ 256, 512 },
[_]c_int{ 512, 512 }, [_]c_int{ 1024, 512 }, [_]c_int{ 512, 1024 },
[_]c_int{ 1024, 1024 }, [_]c_int{ 2048, 1024 }, [_]c_int{ 1024, 2048 },
[_]c_int{ 2048, 2048 }, [_]c_int{ 4096, 2048 }, [_]c_int{ 2048, 4096 },
[_]c_int{ 4096, 4096 }, [_]c_int{ 8192, 4096 }, [_]c_int{ 4096, 8192 },
};
for (texture_sizes) |tex_size| {
stb.stbrp_init_target(&ctx, tex_size[0], tex_size[1], &nodes, node_count);
stb.stbrp_setup_heuristic(&ctx, stb.STBRP_HEURISTIC_Skyline_default);
if (stb.stbrp_pack_rects(&ctx, frames.ptr, @intCast(c_int, frames.len)) == 1) {
return Size{ .width = @intCast(u16, tex_size[0]), .height = @intCast(u16, tex_size[1]) };
}
}
return null;
}
}; | src/utils/texture_packer.zig |
const std = @import("std");
const bigInt = std.math.big.int.Managed;
const Point = struct {
x: *bigInt,
y: *bigInt,
};
pub fn main() !void {
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{};
defer _ = gpa.deinit();
const alloc = &gpa.allocator;
var gx = try bigInt.init(alloc);
defer gx.deinit();
var gy = try bigInt.init(alloc);
defer gy.deinit();
var G: Point = .{
.x = &gx,
.y = &gy,
};
try ECCPointDouble(alloc, G);
std.debug.print("G: {any}\n", .{G});
}
/// Point doubling
/// lambda = (3X^2 + a)/(2y)
/// xr = lambda^2 - x1 - x2
/// yr = lambda(x1 - x2)-y1
pub fn ECCPointDouble(alloc: *std.mem.Allocator, P: Point) anyerror!void {
var divident = try bigInt.init(alloc);
defer divident.deinit();
var divider = try bigInt.init(alloc);
defer divider.deinit();
var lambda = try bigInt.init(alloc);
defer lambda.deinit();
var temp = try bigInt.initSet(alloc, 3);
defer temp.deinit();
var result_x = try bigInt.init(alloc);
errdefer result_x.deinit();
var result_y = try bigInt.init(alloc);
errdefer result_y.deinit();
var result: Point = .{
.x = &result_x,
.y = &result_y,
};
try bigInt.pow(÷nt, P.x.toConst, 2);
try bigInt.mul(÷nt, divident.toConst(), temp.toConst());
// FIXME add proper eliptic curve parameter
try temp.setString(16, "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc");
try bigInt.add(÷nt, divident.toConst(), temp.toConst());
try temp.set(2);
try bigInt.mul(÷r, P.y.toConst(), temp.toConst());
try bigInt.divFloor(&temp, &lambda, divident.toConst(), divider.toConst());
try bigInt.pow(result.x, lambda.toConst(), 2);
try bigInt.sub(result.x, result.x.toConst(), P.x.toConst());
try bigInt.sub(result.x, result.x.toConst(), P.x.toConst());
try bigInt.sub(result.y, P.x.toConst(), result.x.toConst());
try bigInt.mul(result.y, result.y.toConst(), lambda.toConst());
try bigInt.sub(result.y, result.y.toConst(), P.y.toConst());
return result;
}
/// Point addition
/// xr = lambda^2 - x1 - x2
/// yr = lambda(x1 - x2)-y1
pub fn ECCPointAdd() void {} | src/crypto.zig |
const c = @import("../../c_global.zig").c_imp;
const std = @import("std");
// dross-zig
const FramebufferType = @import("../framebuffer.zig").FramebufferType;
const FramebufferAttachmentType = @import("../framebuffer.zig").FramebufferAttachmentType;
const texture = @import("../texture.zig");
const Texture = texture.Texture;
// -----------------------------------------
// - FramebufferGl -
// -----------------------------------------
pub const FramebufferGl = struct {
handle: c_uint = undefined,
target: c_uint = undefined,
const Self = @This();
pub fn new(allocator: *std.mem.Allocator) !*Self {
var self = try allocator.create(FramebufferGl);
// Generate the framebuffer handle
c.glGenFramebuffers(1, &self.handle);
return self;
}
pub fn free(allocator: *std.mem.Allocator, self: *Self) void {
// Delete the buffer
c.glDeleteFramebuffers(1, &self.handle);
allocator.destroy(self);
}
/// Binds the framebuffer
pub fn bind(self: *Self, target: FramebufferType) void {
self.target = convertBufferType(target);
// GL_FRAMEBUFFER will make the buffer the target for the next
// read AND write operations.
// Other options being GL_READ_FRAMEBUFFER for read, and
// GL_DRAW_FRAMEBUFFER for write.
c.glBindFramebuffer(self.target, self.handle);
}
/// Attaches texture to the framebuffer as the color buffer, depth buffer, and/or stencil buffer.
pub fn attach2d(self: *Self, id: texture.TextureId, attachment: FramebufferAttachmentType) void {
const attachment_convert = convertAttachmentType(attachment);
c.glFramebufferTexture2D(
self.target, // Framebuffer type
attachment_convert, // Attachment Type
c.GL_TEXTURE_2D, // Texture type
id.id_gl, // Texture id
0, // Mipmap level
);
}
/// Checks to see if the framebuffer if complete
pub fn check(self: *Self) void {
const status = c.glCheckFramebufferStatus(self.target);
if (status != c.GL_FRAMEBUFFER_COMPLETE) {
std.debug.print("[FRAMEBUFFER]: Framebuffer is not yet complete! {}", .{status});
}
}
/// Clears framebuffer to the default
pub fn resetFramebuffer() void {
c.glBindFramebuffer(c.GL_FRAMEBUFFER, 0);
}
fn convertBufferType(target: FramebufferType) c_uint {
switch (target) {
FramebufferType.Both => return c.GL_FRAMEBUFFER,
FramebufferType.Draw => return c.GL_READ_FRAMEBUFFER,
FramebufferType.Read => return c.GL_DRAW_FRAMEBUFFER,
}
}
fn convertAttachmentType(attachment: FramebufferAttachmentType) c_uint {
switch (attachment) {
FramebufferAttachmentType.Color0 => return c.GL_COLOR_ATTACHMENT0,
FramebufferAttachmentType.Depth => return c.GL_DEPTH_ATTACHMENT,
FramebufferAttachmentType.Stencil => return c.GL_STENCIL_ATTACHMENT,
FramebufferAttachmentType.DepthStencil => return c.GL_DEPTH_STENCIL_ATTACHMENT,
}
}
}; | src/renderer/backend/framebuffer_opengl.zig |
const std = @import("std");
const c = @import("c.zig");
const Mat4 = @import("math3d.zig").Mat4;
const Vec3 = @import("math3d.zig").Vec3;
const glsl = @cImport({
@cInclude("sokol/sokol_gfx.h");
@cInclude("shaders/cube.glsl.h");
});
const SampleCount = 4;
const State = struct {
pass_action: c.sg_pass_action,
main_pipeline: c.sg_pipeline,
main_bindings: c.sg_bindings,
};
var rx: f32 = 0.0;
var ry: f32 = 0.0;
var state: State = undefined;
export fn init() void {
var desc = std.mem.zeroes(c.sg_desc);
desc.context = c.sapp_sgcontext();
c.sg_setup(&desc);
c.stm_setup();
state.pass_action.colors[0].action = .SG_ACTION_CLEAR;
state.pass_action.colors[0].value = c.sg_color{ .r = 0.2, .g = 0.2, .b = 0.2, .a = 1.0 };
const vertices = [_]f32{
// positions // colors
-1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 1.0,
1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 1.0,
1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0,
-1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0,
-1.0, -1.0, 1.0, 0.0, 1.0, 0.0, 1.0,
1.0, -1.0, 1.0, 0.0, 1.0, 0.0, 1.0,
1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0,
-1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0,
-1.0, -1.0, -1.0, 0.0, 0.0, 1.0, 1.0,
-1.0, 1.0, -1.0, 0.0, 0.0, 1.0, 1.0,
-1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0,
-1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0,
1.0, -1.0, -1.0, 1.0, 0.5, 0.0, 1.0,
1.0, 1.0, -1.0, 1.0, 0.5, 0.0, 1.0,
1.0, 1.0, 1.0, 1.0, 0.5, 0.0, 1.0,
1.0, -1.0, 1.0, 1.0, 0.5, 0.0, 1.0,
-1.0, -1.0, -1.0, 0.0, 0.5, 1.0, 1.0,
-1.0, -1.0, 1.0, 0.0, 0.5, 1.0, 1.0,
1.0, -1.0, 1.0, 0.0, 0.5, 1.0, 1.0,
1.0, -1.0, -1.0, 0.0, 0.5, 1.0, 1.0,
-1.0, 1.0, -1.0, 1.0, 0.0, 0.5, 1.0,
-1.0, 1.0, 1.0, 1.0, 0.0, 0.5, 1.0,
1.0, 1.0, 1.0, 1.0, 0.0, 0.5, 1.0,
1.0, 1.0, -1.0, 1.0, 0.0, 0.5, 1.0,
};
const indices = [_]u16{
0, 1, 2, 0, 2, 3,
6, 5, 4, 7, 6, 4,
8, 9, 10, 8, 10, 11,
14, 13, 12, 15, 14, 12,
16, 17, 18, 16, 18, 19,
22, 21, 20, 23, 22, 20,
};
var buffer_desc = std.mem.zeroes(c.sg_buffer_desc);
buffer_desc.size = vertices.len * @sizeOf(f32);
buffer_desc.data = .{ .ptr = &vertices[0], .size = buffer_desc.size };
state.main_bindings.vertex_buffers[0] = c.sg_make_buffer(&buffer_desc);
buffer_desc = std.mem.zeroes(c.sg_buffer_desc);
buffer_desc.type = .SG_BUFFERTYPE_INDEXBUFFER;
buffer_desc.size = indices.len * @sizeOf(u16);
buffer_desc.data = .{ .ptr = &indices[0], .size = buffer_desc.size };
state.main_bindings.index_buffer = c.sg_make_buffer(&buffer_desc);
const shader_desc = @ptrCast([*]const c.sg_shader_desc, glsl.cube_shader_desc(glsl.sg_query_backend()));
const shader = c.sg_make_shader(shader_desc);
var pipeline_desc = std.mem.zeroes(c.sg_pipeline_desc);
pipeline_desc.layout.attrs[0].format = .SG_VERTEXFORMAT_FLOAT3;
pipeline_desc.layout.attrs[1].format = .SG_VERTEXFORMAT_FLOAT4;
pipeline_desc.layout.buffers[0].stride = 28;
pipeline_desc.shader = shader;
pipeline_desc.index_type = .SG_INDEXTYPE_UINT16;
pipeline_desc.depth.compare = .SG_COMPAREFUNC_LESS_EQUAL;
pipeline_desc.depth.write_enabled = true;
pipeline_desc.cull_mode = .SG_CULLMODE_BACK;
state.main_pipeline = c.sg_make_pipeline(&pipeline_desc);
}
export fn update() void {
const width = c.sapp_width();
const height = c.sapp_height();
const w: f32 = @intToFloat(f32, width);
const h: f32 = @intToFloat(f32, height);
const radians: f32 = 1.0472; //60 degrees
var proj: Mat4 = Mat4.createPerspective(radians, w / h, 0.01, 100.0);
var view: Mat4 = Mat4.createLookAt(Vec3.new(2.0, 3.5, 2.0), Vec3.new(0.0, 0.0, 0.0), Vec3.new(0.0, 1.0, 0.0));
var view_proj = Mat4.mul(proj, view);
rx += 1.0 / 220.0;
ry += 2.0 / 220.0;
var rxm = Mat4.createAngleAxis(Vec3.new(1, 0, 0), rx);
var rym = Mat4.createAngleAxis(Vec3.new(0, 1, 0), ry);
var model = Mat4.mul(rxm, rym);
var mvp = Mat4.mul(view_proj, model);
var vs_params = glsl.vs_params_t{
.mvp = mvp.toArray(),
};
c.sg_begin_default_pass(&state.pass_action, width, height);
c.sg_apply_pipeline(state.main_pipeline);
c.sg_apply_bindings(&state.main_bindings);
c.sg_apply_uniforms(.SG_SHADERSTAGE_VS, 0, &.{ .ptr = &vs_params, .size = @sizeOf(glsl.vs_params_t) });
c.sg_draw(0, 36, 1);
c.sg_end_pass();
c.sg_commit();
}
export fn cleanup() void {
c.sg_shutdown();
}
pub fn main() void {
var app_desc = std.mem.zeroes(c.sapp_desc);
app_desc.width = 1280;
app_desc.height = 720;
app_desc.init_cb = init;
app_desc.frame_cb = update;
app_desc.cleanup_cb = cleanup;
app_desc.sample_count = SampleCount;
app_desc.window_title = "Cube (sokol-zig)";
_ = c.sapp_run(&app_desc);
} | src/example_cube.zig |
usingnamespace @import("root").preamble;
const log = lib.output.log.scoped(.{
.prefix = "PCI",
.filter = .info,
});
const paging = os.memory.paging;
const range = lib.util.range.range;
pub const Handler = struct { function: fn (*os.platform.InterruptFrame, u64) void, context: u64 };
var handlers: [0x100]Handler = undefined;
pub const Cap = struct {
addr: Addr,
off: u8,
pub fn next(self: *Cap) void {
self.off = self.addr.read(u8, self.off + 0x01);
}
pub fn id(self: *const Cap) u8 {
return self.addr.read(u8, self.off + 0x00);
}
pub fn read(self: *const Cap, comptime T: type, off: regoff) T {
return self.addr.read(T, self.off + off);
}
pub fn write(self: *const Cap, comptime T: type, off: regoff, value: T) void {
self.addr.write(T, self.off + off, value);
}
};
pub const Addr = struct {
bus: u8,
device: u5,
function: u3,
const vendor_id = cfgreg(u16, 0x00);
const device_id = cfgreg(u16, 0x02);
const command = cfgreg(u16, 0x04);
const status = cfgreg(u16, 0x06);
const prog_if = cfgreg(u8, 0x09);
const header_type = cfgreg(u8, 0x0E);
const base_class = cfgreg(u8, 0x0B);
const sub_class = cfgreg(u8, 0x0A);
const secondary_bus = cfgreg(u8, 0x19);
const cap_ptr = cfgreg(u8, 0x34);
const int_line = cfgreg(u8, 0x3C);
const int_pin = cfgreg(u8, 0x3D);
pub fn cap(self: Addr) Cap {
return .{ .addr = self, .off = self.cap_ptr().read() & 0xFC };
}
pub fn barinfo(self: Addr, bar_idx: u8) BarInfo {
var orig: u64 = self.read(u32, 0x10 + bar_idx * 4) & 0xFFFFFFF0;
self.write(u32, 0x10 + bar_idx * 4, 0xFFFFFFFF);
var pci_out = self.read(u32, 0x10 + bar_idx * 4);
const is64 = ((pci_out & 0b110) >> 1) == 2; // bits 1:2, bar type (0 = 32bit, 1 = 64bit)
self.write(u32, 0x10 + bar_idx * 4, @truncate(u32, orig));
// The BARs can be either 64 or 32 bit, but the trick works for both
var response: u64 = @as(u64, pci_out & 0xFFFFFFF0);
if (is64) {
orig |= @as(u64, self.read(u32, 0x14 + bar_idx * 4)) << 32;
self.write(u32, 0x14 + bar_idx * 4, 0xFFFFFFFF); // 64bit bar = two 32-bit bars
response |= @as(u64, self.read(u32, 0x14 + bar_idx * 4)) << 32;
self.write(u32, 0x14 + bar_idx * 4, @truncate(u32, orig >> 32));
return .{ .phy = orig, .size = ~response +% 1 };
} else {
return .{ .phy = orig, .size = (~response +% 1) & 0xFFFFFFFF };
}
}
pub fn read(self: Addr, comptime T: type, offset: regoff) T {
if (pci_mmio[self.bus] != null) {
const buf = mmio(self, offset)[0..@sizeOf(T)].*;
return std.mem.readIntLittle(T, &buf);
}
if (@hasDecl(os.platform, "pci_space"))
return os.platform.pci_space.read(T, self, offset);
@panic("No pci module!");
}
pub fn write(self: Addr, comptime T: type, offset: regoff, value: T) void {
if (pci_mmio[self.bus] != null) {
var buf: [@sizeOf(T)]u8 = undefined;
std.mem.writeIntLittle(T, &buf, value);
mmio(self, offset)[0..@sizeOf(T)].* = buf;
return;
}
if (@hasDecl(os.platform, "pci_space"))
return os.platform.pci_space.write(T, self, offset, value);
@panic("No pci module!");
}
pub fn format(self: Addr, fmt: anytype) void {
fmt("[{0X}:{0X}:{0X}]", .{ self.bus, self.device, self.function });
fmt("{{{0X}:{0X}}} ", .{ self.vendor_id().read(), self.device_id().read() });
fmt("({0X}:{0X}:{0X})", .{ self.base_class().read(), self.sub_class().read(), self.prog_if().read() });
}
};
pub const MsixTableEntry = packed struct {
addr: u64,
data: u32,
control: u32 = 0,
};
pub const MsiInfo = union(enum) { // TODO: add MSI
none,
msix: struct {
table: [*]volatile MsixTableEntry,
size: u32,
}
};
pub fn msi_enable(a: Addr) MsiInfo {
var cap = a.cap();
var m: MsiInfo = .none;
while (cap.off != 0) {
if (cap.id() == 0x11) {
const t = cap.read(u32, 0x4);
const tableOff = t & (~@as(u32, 0b111));
const tableBir = @truncate(u8, t & 0b111);
a.command().write(a.command().read() | 0x400); // disable intx
cap.write(u16, 0x2, 0x8000 | (cap.read(u16, 0x2) & (~@as(u16, 0x4000)))); // enable msi-x, unmask
m = .{ .msix = .{
.table = os.platform.phys_ptr([*]volatile MsixTableEntry).from_int(a.barinfo(tableBir).phy + tableOff).get_uncached(),
.size = (cap.read(u16, 0x2) & 0x7FF) + 1,
}};
break;
}
cap.next();
}
return m;
}
pub const regoff = u8;
fn mmio(addr: Addr, offset: regoff) [*]volatile u8 {
return @ptrCast([*]volatile u8, pci_mmio[addr.bus].?) + (@as(u64, addr.device) << 15 | @as(u64, addr.function) << 12 | @as(u64, offset));
}
const BarInfo = struct {
phy: u64,
size: u64,
};
fn function_scan(addr: Addr) void {
if (addr.vendor_id().read() == 0xFFFF)
return;
const l = log.start(.info, "{} ", .{addr});
switch (addr.base_class().read()) {
else => {
log.finish(.info, "Unknown class!", .{}, l);
},
0x00 => {
switch (addr.sub_class().read()) {
else => {
log.finish(.info, "Unknown unclassified device!", .{}, l);
},
}
},
0x01 => {
switch (addr.sub_class().read()) {
else => {
log.finish(.info, "Unknown storage controller!", .{}, l);
},
0x06 => {
log.finish(.info, "AHCI controller", .{}, l);
os.drivers.block.ahci.registerController(addr);
},
0x08 => {
switch (addr.prog_if().read()) {
else => {
log.finish(.info, "Unknown non-volatile memory controller!", .{}, l);
},
0x02 => {
log.finish(.info, "NVMe controller", .{}, l);
os.drivers.block.nvme.registerController(addr);
},
}
},
}
},
0x02 => {
switch (addr.sub_class().read()) {
else => {
log.finish(.info, "Unknown network controller!", .{}, l);
},
0x00 => {
if (addr.vendor_id().read() == 0x8086 and addr.device_id().read() == 0x100E) {
log.finish(.info, "E1000 Ethernet controller", .{}, l);
os.drivers.net.e1000.registerController(addr);
} else if (addr.vendor_id().read() == 0x1AF4) {
log.finish(.info, "Virtio Ethernet controller", .{}, l);
os.drivers.net.virtio.registerController(addr);
} else {
log.finish(.info, "Unknown Ethernet controller", .{}, l);
}
},
0x80 => {
log.finish(.info, "Other network controller", .{}, l);
},
}
},
0x03 => {
if (addr.vendor_id().read() == 0x1AF4) {
log.finish(.info, "Virtio display controller", .{}, l);
os.drivers.gpu.virtio.registerController(addr);
} else switch (addr.sub_class().read()) {
else => {
log.finish(.info, "Unknown display controller!", .{}, l);
},
0x00 => {
log.finish(.info, "VGA compatible controller", .{}, l);
},
}
},
0x04 => {
switch (addr.sub_class().read()) {
else => {
log.finish(.info, "Unknown multimedia controller!", .{}, l);
},
0x03 => {
log.finish(.info, "Audio device", .{}, l);
},
}
},
0x06 => {
switch (addr.sub_class().read()) {
else => {
log.finish(.info, "Unknown bridge device!", .{}, l);
},
0x00 => {
log.finish(.info, "Host bridge", .{}, l);
},
0x01 => {
log.finish(.info, "ISA bridge", .{}, l);
},
0x04 => {
log.cont(.info, "PCI-to-PCI bridge", .{}, l);
if ((addr.header_type().read() & 0x7F) != 0x01) {
log.finish(.info, ": Not PCI-to-PCI bridge header type!", .{}, l);
} else {
const secondary_bus = addr.secondary_bus().read();
log.finish(.info, ", recursively scanning bus {0X}", .{secondary_bus}, l);
bus_scan(secondary_bus);
}
},
}
},
0x0c => {
switch (addr.sub_class().read()) {
else => {
log.finish(.info, "Unknown serial bus controller!", .{}, l);
},
0x03 => {
switch (addr.prog_if().read()) {
else => {
log.finish(.info, "Unknown USB controller!", .{}, l);
},
0x20 => {
log.finish(.info, "USB2 EHCI controller", .{}, l);
},
0x30 => {
log.finish(.info, "USB3 XHCI controller", .{}, l);
os.drivers.usb.xhci.registerController(addr);
},
}
},
}
},
}
}
fn laihost_addr(seg: u16, bus: u8, slot: u8, fun: u8) Addr {
return .{
.bus = bus,
.device = @intCast(u5, slot),
.function = @intCast(u3, fun),
};
}
export fn laihost_pci_writeb(seg: u16, bus: u8, slot: u8, fun: u8, offset: u16, value: u8) void {
laihost_addr(seg, bus, slot, fun).write(u8, @intCast(u8, offset), value);
}
export fn laihost_pci_readb(seg: u16, bus: u8, slot: u8, fun: u8, offset: u16) u8 {
return laihost_addr(seg, bus, slot, fun).read(u8, @intCast(u8, offset));
}
export fn laihost_pci_writew(seg: u16, bus: u8, slot: u8, fun: u8, offset: u16, value: u16) void {
laihost_addr(seg, bus, slot, fun).write(u16, @intCast(u8, offset), value);
}
export fn laihost_pci_readw(seg: u16, bus: u8, slot: u8, fun: u8, offset: u16) u16 {
return laihost_addr(seg, bus, slot, fun).read(u16, @intCast(u8, offset));
}
export fn laihost_pci_writed(seg: u16, bus: u8, slot: u8, fun: u8, offset: u16, value: u32) void {
laihost_addr(seg, bus, slot, fun).write(u32, @intCast(u8, offset), value);
}
export fn laihost_pci_readd(seg: u16, bus: u8, slot: u8, fun: u8, offset: u16) u32 {
return laihost_addr(seg, bus, slot, fun).read(u32, @intCast(u8, offset));
}
fn device_scan(bus: u8, device: u5) void {
const nullfunc: Addr = .{ .bus = bus, .device = device, .function = 0 };
if (nullfunc.vendor_id().read() == 0xFFFF)
return;
function_scan(nullfunc);
// Return already if this isn't a multi-function device
if (nullfunc.header_type().read() & 0x80 == 0)
return;
inline for (range((1 << 3) - 1)) |function| {
function_scan(.{ .bus = bus, .device = device, .function = function + 1 });
}
}
fn bus_scan(bus: u8) void {
if (!config.kernel.pci.enable)
return;
// We can't scan this bus
if (!@hasDecl(os.platform, "pci_space") and pci_mmio[bus] == null)
return;
inline for (range(1 << 5)) |device| {
device_scan(bus, device);
}
}
pub fn init_pci() !void {
bus_scan(0);
}
pub fn register_mmio(bus: u8, physaddr: u64) !void {
pci_mmio[bus] = os.platform.phys_ptr([*]u8).from_int(physaddr).get_uncached()[0 .. 1 << 20];
}
var pci_mmio: [0x100]?*[1 << 20]u8 linksection(".bss") = undefined;
fn PciFn(comptime T: type, comptime off: regoff) type {
return struct {
self: Addr,
pub fn read(self: @This()) T {
return self.self.read(T, off);
}
pub fn write(self: @This(), val: T) void {
self.self.write(T, off, val);
}
};
}
fn cfgreg(comptime T: type, comptime off: regoff) fn (self: Addr) PciFn(T, off) {
return struct {
fn function(self: Addr) PciFn(T, off) {
return .{ .self = self };
}
}.function;
}
pub const PCI_CAP_MSIX_MSGCTRL = 0x02;
pub const PCI_CAP_MSIX_TABLE = 0x04;
pub const PCI_CAP_MSIX_PBA = 0x08;
pub const PCI_COMMAND_BUSMASTER = 1 << 2;
pub const PCI_COMMAND_LEGACYINT_DISABLE = 1 << 10; | subprojects/flork/src/platform/pci.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const col = @import("color.zig");
const Image = @This();
const colormap_len = 0x100;
width: u32,
height: u32,
pixels: []u8,
colormap: ?[]u8 = null,
allocator: Allocator,
pub fn initEmptyRgba(allocator: Allocator, width: u32, height: u32) !Image {
const self = Image{
.width = width,
.height = height,
.pixels = try allocator.alloc(u8, 4 * width * height),
.allocator = allocator,
};
std.mem.set(u8, self.pixels, 0);
return self;
}
pub fn initFromFile(allocator: Allocator, file_path: []const u8) !Image {
var image_width: u32 = undefined;
var image_height: u32 = undefined;
var colormap_entries: u32 = undefined;
const c_file_path = try std.cstr.addNullByte(allocator, file_path);
defer allocator.free(c_file_path);
var err = readPngFileInfo(c_file_path, &image_width, &image_height, &colormap_entries);
if (err != 0) return error.ReadInfoFail;
const bytes_per_pixel: u32 = if (colormap_entries > 0) 1 else 4; // indexed or rgba
const image_size = bytes_per_pixel * image_width * image_height;
var self: Image = Image{
.width = image_width,
.height = image_height,
.pixels = try allocator.alloc(u8, image_size),
.allocator = allocator,
};
errdefer self.deinit();
if (colormap_entries > 0) {
const colormap = try allocator.alloc(u8, 4 * colormap_len);
// init remaining entries to black
var i: usize = colormap_entries;
while (i < colormap_len) : (i += 1) {
std.mem.copy(u8, colormap[4 * i ..][0..4], &col.black);
}
self.colormap = colormap;
}
err = readPngFile(c_file_path, self.pixels.ptr, if (self.colormap) |colormap| colormap.ptr else null);
if (err != 0) return error.ReadPngFail;
return self;
}
pub fn initFromMemory(allocator: Allocator, memory: []const u8) !Image {
var image_width: u32 = undefined;
var image_height: u32 = undefined;
var colormap_entries: u32 = undefined;
var err = readPngMemoryInfo(memory.ptr, memory.len, &image_width, &image_height, &colormap_entries);
if (err != 0) return error.ReadInfoFail;
const bytes_per_pixel: u32 = if (colormap_entries > 0) 1 else 4; // indexed or rgba
const image_size = bytes_per_pixel * image_width * image_height;
var self: Image = Image{
.width = image_width,
.height = image_height,
.pixels = try allocator.alloc(u8, image_size),
.allocator = allocator,
};
errdefer self.deinit();
if (colormap_entries > 0) {
const colormap = try allocator.alloc(u8, 4 * colormap_len);
// init remaining entries to black
var i: usize = colormap_entries;
while (i < colormap_len) : (i += 1) {
std.mem.copy(u8, colormap[4 * i ..][0..4], &col.black);
}
self.colormap = colormap;
}
err = readPngMemory(memory.ptr, memory.len, self.pixels.ptr, if (self.colormap) |colormap| colormap.ptr else null);
if (err != 0) return error.ReadPngFail;
return self;
}
pub fn deinit(self: Image) void {
self.allocator.free(self.pixels);
if (self.colormap) |colormap| self.allocator.free(colormap);
}
pub fn clone(self: Image, allocator: std.mem.Allocator) !Image {
if (self.colormap != null) @panic("Not implementated");
return Image{
.allocator = allocator,
.width = self.width,
.height = self.height,
.pixels = try allocator.dupe(u8, self.pixels),
};
}
pub fn writeToFile(self: Image, file_path: []const u8) !void {
var colormap_entries: u32 = 0;
var colormap_ptr: [*c]const u8 = null;
if (self.colormap) |colormap| {
colormap_ptr = colormap.ptr;
colormap_entries = @truncate(u32, colormap.len / 4);
}
const c_file_path = try std.cstr.addNullByte(self.allocator, file_path);
defer self.allocator.free(c_file_path);
const err = writePngFile(c_file_path, self.width, self.height, self.pixels.ptr, colormap_ptr, colormap_entries);
if (err != 0) return error.WritePngFail;
}
pub fn writeToMemory(self: Image, allocator: Allocator) ![]const u8 {
var colormap_entries: u32 = 0;
var colormap_ptr: [*c]const u8 = null;
if (self.colormap) |colormap| {
colormap_ptr = colormap.ptr;
colormap_entries = @truncate(u32, colormap.len / 4);
}
var mem_len: usize = undefined;
var err = writePngMemory(null, &mem_len, self.width, self.height, self.pixels.ptr, colormap_ptr, colormap_entries);
if (err != 0) return error.WritePngDetermineSizeFail;
const mem = try allocator.alloc(u8, mem_len);
errdefer allocator.free(mem);
err = writePngMemory(mem.ptr, &mem_len, self.width, self.height, self.pixels.ptr, colormap_ptr, colormap_entries);
if (err != 0) return error.WritePngFail;
return mem;
}
fn convertIndexedToRgba(allocator: Allocator, indexed_image: Image) !Image {
const image = try initEmptyRgba(allocator, indexed_image.width, indexed_image.height);
const colormap = indexed_image.colormap.?;
const pixel_count = indexed_image.width * indexed_image.height;
var i: usize = 0;
while (i < pixel_count) : (i += 1) {
const index = @intCast(usize, indexed_image.pixels[i]);
std.mem.copy(u8, image.pixels[4 * i ..][0..4], colormap[4 * index ..][0..4]);
}
return image;
}
// implementation in c/png_image.c
extern fn readPngFileInfo(file_path: [*c]const u8, width: [*c]u32, height: [*c]u32, colormap_entries: [*c]u32) callconv(.C) c_int;
extern fn readPngFile(file_path: [*c]const u8, pixels: [*c]const u8, colormap: [*c]const u8) callconv(.C) c_int;
extern fn readPngMemoryInfo(memory: [*c]const u8, len: usize, width: [*c]u32, height: [*c]u32, colormap_entries: [*c]u32) callconv(.C) c_int;
extern fn readPngMemory(memory: [*c]const u8, len: usize, pixels: [*c]const u8, colormap: [*c]const u8) callconv(.C) c_int;
extern fn writePngFile(file_path: [*c]const u8, width: u32, height: u32, pixels: [*c]const u8, colormap: [*c]const u8, colormap_entries: u32) callconv(.C) c_int;
extern fn writePngMemory(memory: [*c]const u8, len: [*c]usize, width: u32, height: u32, pixels: [*c]const u8, colormap: [*c]const u8, colormap_entries: u32) callconv(.C) c_int; | src/Image.zig |
const std = @import("std");
const assert = std.debug.assert;
pub const OffsetType = enum {
linear,
periodic,
step,
non_ideal,
};
pub const Time = struct {
const Self = @This();
/// The duration of a single tick in nanoseconds.
resolution: u64,
offset_type: OffsetType,
/// Co-efficients to scale the offset according to the `offset_type`.
/// Linear offset is described as A * x + B: A is the drift per tick and B the initial offset.
/// Periodic is described as A * sin(x * pi / B): A controls the amplitude and B the period in
/// terms of ticks.
/// Step function represents a discontinuous jump in the wall-clock time. B is the period in
/// which the jumps occur. A is the amplitude of the step.
/// Non-ideal is similar to periodic except the phase is adjusted using a random number taken
/// from a normal distribution with mean=0, stddev=10. Finally, a random offset (up to
/// offset_coefficientC) is added to the result.
offset_coefficient_A: i64,
offset_coefficient_B: i64,
offset_coefficient_C: u32 = 0,
prng: std.rand.DefaultPrng = std.rand.DefaultPrng.init(0),
/// The number of ticks elapsed since initialization.
ticks: u64 = 0,
/// The instant in time chosen as the origin of this time source.
epoch: i64 = 0,
pub fn monotonic(self: *Self) u64 {
return self.ticks * self.resolution;
}
pub fn realtime(self: *Self) i64 {
return self.epoch + @intCast(i64, self.monotonic()) - self.offset(self.ticks);
}
pub fn offset(self: *Self, ticks: u64) i64 {
switch (self.offset_type) {
.linear => {
const drift_per_tick = self.offset_coefficient_A;
return @intCast(i64, ticks) * drift_per_tick + @intCast(
i64,
self.offset_coefficient_B,
);
},
.periodic => {
const unscaled = std.math.sin(@intToFloat(f64, ticks) * 2 * std.math.pi /
@intToFloat(f64, self.offset_coefficient_B));
const scaled = @intToFloat(f64, self.offset_coefficient_A) * unscaled;
return @floatToInt(i64, std.math.floor(scaled));
},
.step => {
return if (ticks > self.offset_coefficient_B) self.offset_coefficient_A else 0;
},
.non_ideal => {
const phase: f64 = @intToFloat(f64, ticks) * 2 * std.math.pi /
(@intToFloat(f64, self.offset_coefficient_B) + self.prng.random().floatNorm(f64) * 10);
const unscaled = std.math.sin(phase);
const scaled = @intToFloat(f64, self.offset_coefficient_A) * unscaled;
return @floatToInt(i64, std.math.floor(scaled)) +
self.prng.random().intRangeAtMost(
i64,
-@intCast(i64, self.offset_coefficient_C),
self.offset_coefficient_C,
);
},
}
}
pub fn tick(self: *Self) void {
self.ticks += 1;
}
}; | src/test/time.zig |
const build_options = @import("build_options");
const std = @import("std");
const warn = std.log.warn;
const mem = std.mem;
const fs = std.fs;
const sapp = @import("sokol").app;
const host = @import("host");
const gfx = host.gfx;
const audio = host.audio;
const time = host.time;
const Args = host.Args;
const KC85 = @import("emu").KC85;
const Model = KC85.Model;
const ModuleType = KC85.ModuleType;
const state = struct {
var kc: *KC85 = undefined;
var args: Args = undefined;
var file_data: ?[]const u8 = null;
var arena: std.heap.ArenaAllocator = undefined;
};
const kc85_model: Model = switch (build_options.kc85_model) {
.KC85_2 => .KC85_2,
.KC85_3 => .KC85_3,
.KC85_4 => .KC85_4,
};
const load_delay_us = switch(build_options.kc85_model) {
.KC85_2, .KC85_3 => 480 * 16_667,
.KC85_4 => 180 * 16_667,
};
const max_file_size = 64 * 1024;
pub fn main() !void {
state.arena = std.heap.ArenaAllocator.init(std.heap.c_allocator);
defer state.arena.deinit();
// parse arguments
state.args = Args.parse(state.arena.allocator()) catch {
warn("Failed to parse arguments\n", .{});
std.process.exit(5);
};
if (state.args.help) {
return;
}
// start sokol-app "game loop"
sapp.run(.{
.init_cb = init,
.frame_cb = frame,
.cleanup_cb = cleanup,
.event_cb = input,
.width = gfx.WindowWidth,
.height = gfx.WindowHeight,
.icon = .{
// FIXME: KC85 logo
.sokol_default = true,
},
.window_title = switch (kc85_model) {
.KC85_2 => "KC85/2",
.KC85_3 => "KC85/3",
.KC85_4 => "KC85/4"
}
});
}
export fn init() void {
gfx.setup();
audio.setup();
time.setup();
// setup KC85 emulator instance
state.kc = KC85.create(state.arena.allocator(), .{
.pixel_buffer = gfx.pixel_buffer[0..],
.audio_func = .{ .func = audio.push },
.audio_sample_rate = audio.sampleRate(),
.patch_func = .{ .func = patchFunc },
.rom_caos22 = if (kc85_model == .KC85_2) @embedFile("roms/caos22.852") else null,
.rom_caos31 = if (kc85_model == .KC85_3) @embedFile("roms/caos31.853") else null,
.rom_caos42c = if (kc85_model == .KC85_4) @embedFile("roms/caos42c.854") else null,
.rom_caos42e = if (kc85_model == .KC85_4) @embedFile("roms/caos42e.854") else null,
.rom_kcbasic = if (kc85_model != .KC85_2) @embedFile("roms/basic_c0.853") else null,
}) catch |err| {
warn("Failed to allocate KC85 instance with: {}\n", .{ err });
std.process.exit(10);
};
// insert any modules defined on the command line
for (state.args.slots) |slot| {
if (slot.mod_name) |mod_name| {
var mod_type = moduleNameToType(mod_name);
var rom_image: ?[]const u8 = null;
if (slot.mod_path) |path| {
rom_image = fs.cwd().readFileAlloc(state.arena.allocator(), path, max_file_size) catch |err| blk:{
warn("Failed to load ROM file '{s}' with: {}\n", .{ path, err });
mod_type = .NONE;
break :blk null;
};
}
state.kc.insertModule(slot.addr, mod_type, rom_image) catch |err| {
warn("Failed to insert module '{s}' with: {}\n", .{ mod_name, err });
};
}
}
// preload the KCC or TAP file image, this will be loaded later when the
// system has finished booting
if (state.args.file) |path| {
state.file_data = fs.cwd().readFileAlloc(state.arena.allocator(), path, max_file_size) catch |err| blk:{
warn("Failed to load snapshot file '{s}' with: {}\n", .{ path, err });
break :blk null;
};
}
else {
state.file_data = null;
}
}
export fn frame() void {
const frame_time_us = time.frameTime();
state.kc.exec(frame_time_us);
gfx.draw();
// check if KCC or TAP file should be loaded (after giving the system
// enough time to boot up)
if ((state.file_data != null) and time.elapsed(load_delay_us)) {
state.kc.load(state.file_data.?) catch |err| {
warn("Failed to load snapshot file '{s}' with: {}\n", .{ state.args.file.?, err });
};
// arena allocator takes care of deallocation
state.file_data = null;
}
}
export fn cleanup() void {
state.kc.destroy(state.arena.allocator());
audio.shutdown();
gfx.shutdown();
}
export fn input(event: ?*const sapp.Event) void {
const ev = event.?;
switch (ev.type) {
.CHAR => {
var char = ev.char_code;
if ((char > 0x20) and (char < 0x7F)) {
// need to invert case
if ((char >= 'A') and (char <= 'Z')) {
char |= 0x20;
}
else if ((char >= 'a') and (char <= 'z')) {
char &= ~@as(u8,0x20);
}
const key = @truncate(u8, char);
state.kc.keyDown(key);
state.kc.keyUp(key);
}
},
.KEY_DOWN, .KEY_UP => {
const key: u8 = switch (ev.key_code) {
.SPACE => 0x20,
.ENTER => 0x0D,
.RIGHT => 0x09,
.LEFT => 0x08,
.DOWN => 0x0A,
.UP => 0x0B,
.HOME => 0x10,
.INSERT => 0x1A,
.BACKSPACE => 0x01,
.ESCAPE => 0x03,
.F1 => 0xF1,
.F2 => 0xF2,
.F3 => 0xF3,
.F4 => 0xF4,
.F5 => 0xF5,
.F6 => 0xF6,
.F7 => 0xF7,
.F8 => 0xF8,
.F9 => 0xF9,
.F10 => 0xFA,
.F11 => 0xFB,
.F12 => 0xFC,
else => 0,
};
if (0 != key) {
switch (ev.type) {
.KEY_DOWN => state.kc.keyDown(key),
.KEY_UP => state.kc.keyUp(key),
else => unreachable,
}
}
},
else => { },
}
}
fn moduleNameToType(name: []const u8) KC85.ModuleType {
const modules = .{
.{ "m006", .M006_BASIC },
.{ "m011", .M011_64KBYTE },
.{ "m012", .M012_TEXOR },
.{ "m022", .M022_16KBYTE },
.{ "m026", .M026_FORTH },
.{ "m027", .M027_DEVELOPMENT },
};
inline for (modules) |module| {
if (mem.eql(u8, name, module[0])) {
return module[1];
}
}
else {
return .NONE;
}
}
// this patches some known issues with game images
fn patchFunc(snapshot_name: []const u8, userdata: usize) void {
_ = userdata;
if (mem.startsWith(u8, snapshot_name, "JUNGLE ")) {
// patch start level 1 into memory
state.kc.mem.w8(0x36B7, 1);
state.kc.mem.w8(0x3697, 1);
var i: u16 = 0;
while (i < 5): (i += 1) {
const b = state.kc.mem.r8(0x36B6 +% i);
state.kc.mem.w8(0x1770 +% i, b);
}
}
else if (mem.startsWith(u8, snapshot_name, "DIGGER COM\x01")) {
// time for delay loop 0x0160 instead of 0x0260
state.kc.mem.w16(0x09AA, 0x0160);
// OR L instead of OR (HL)
state.kc.mem.w8(0x3D3A, 0xB5);
}
else if (mem.startsWith(u8, snapshot_name, "DIGGERJ")) {
state.kc.mem.w16(0x09AA, 0x0260);
state.kc.mem.w8(0x3D3A, 0xB5);
}
} | src/main.zig |
const std = @import("std");
const mem = std.mem;
const unicode = std.unicode;
const ascii = @import("ascii.zig");
const ziglyph = @import("ziglyph");
const CodePointIterator = ziglyph.CodePointIterator;
const Grapheme = ziglyph.Grapheme;
const GraphemeIterator = Grapheme.GraphemeIterator;
const prop_list = ziglyph.prop_list;
const Self = @This();
allocator: mem.Allocator,
bytes: std.ArrayList(u8),
/// fromBytes returns a new Zigstr from the byte slice `str`, which will *not* be freed on `deinit`.
pub fn fromBytes(allocator: mem.Allocator, str: []const u8) !Self {
return Self{
.allocator = allocator,
.bytes = blk: {
var al = try std.ArrayList(u8).initCapacity(allocator, str.len);
al.appendSliceAssumeCapacity(str);
break :blk al;
},
};
}
/// fromOwnedBytes returns a new Zigstr from the owned byte slice `str`, which will be freed on `deinit`.
pub fn fromOwnedBytes(allocator: mem.Allocator, str: []u8) !Self {
return Self{
.allocator = allocator,
.bytes = std.ArrayList(u8).fromOwnedSlice(allocator, str),
};
}
/// fromCodePoints returns a new Zigstr from `code points`.
pub fn fromCodePoints(allocator: mem.Allocator, code_points: []const u21) !Self {
const ascii_only = blk_ascii: {
break :blk_ascii for (code_points) |cp| {
if (cp > 127) break false;
} else true;
};
if (ascii_only) {
return Self{
.allocator = allocator,
.bytes = blk_b: {
var al = try std.ArrayList(u8).initCapacity(allocator, code_points.len);
for (code_points) |cp| {
al.appendAssumeCapacity(@intCast(u8, cp));
}
break :blk_b al;
},
};
} else {
return Self{
.allocator = allocator,
.bytes = blk_b: {
var al = std.ArrayList(u8).init(allocator);
var cp_buf: [4]u8 = undefined;
for (code_points) |cp| {
const len = try unicode.utf8Encode(cp, &cp_buf);
try al.appendSlice(cp_buf[0..len]);
}
break :blk_b al;
},
};
}
}
test "Zigstr from code points" {
var allocator = std.testing.allocator;
const cp_array = [_]u21{ 0x68, 0x65, 0x6C, 0x6C, 0x6F }; // "hello"
var str = try fromCodePoints(allocator, &cp_array);
defer str.deinit();
try expectEqualStrings(str.bytes.items, "hello");
}
/// fromJoined returns a new Zigstr from the concatenation of strings in `slice` with `sep` separator.
pub fn fromJoined(allocator: mem.Allocator, slice: []const []const u8, sep: []const u8) !Self {
return fromOwnedBytes(allocator, try mem.join(allocator, sep, slice));
}
test "Zigstr fromJoined" {
var str = try fromJoined(std.testing.allocator, &[_][]const u8{ "Hello", "World" }, " ");
defer str.deinit();
try expect(str.eql("Hello World"));
}
pub fn deinit(self: *Self) void {
self.bytes.deinit();
}
/// toOwnedSlice returns the bytes of this Zigstr to be freed by caller. This Zigstr is reset to empty.
pub fn toOwnedSlice(self: *Self) ![]u8 {
return self.bytes.toOwnedSlice();
}
test "Zigstr toOwnedSlice" {
var allocator = std.testing.allocator;
var str = try fromBytes(allocator, "Hello");
defer str.deinit();
try expect(str.eql("Hello"));
const bytes = try str.toOwnedSlice();
defer allocator.free(bytes);
try expectEqualStrings(bytes, "Hello");
try expect(str.eql(""));
}
/// reset reinitializes this Zigstr from the byte slice `str`.
pub fn reset(self: *Self, str: []const u8) !void {
try self.bytes.replaceRange(0, self.bytes.items.len, str);
}
/// byteCount returns the number of bytes, which can be different from the number of code points and the
/// number of graphemes.
pub fn byteCount(self: Self) usize {
return self.bytes.items.len;
}
/// codePointIter returns a code point iterator based on the bytes of this Zigstr.
pub fn codePointIter(self: Self) CodePointIterator {
return CodePointIterator{ .bytes = self.bytes.items };
}
/// codePoints returns the code points that make up this Zigstr. Caller must free returned slice.
pub fn codePoints(self: *Self, allocator: mem.Allocator) ![]u21 {
var code_points = try std.ArrayList(u21).initCapacity(allocator, self.bytes.items.len);
defer code_points.deinit();
var iter = self.codePointIter();
while (iter.next()) |cp| {
code_points.appendAssumeCapacity(cp.scalar);
}
return code_points.toOwnedSlice();
}
/// codePointCount returns the number of code points, which can be different from the number of bytes
/// and the number of graphemes.
pub fn codePointCount(self: *Self) !usize {
const cps = try self.codePoints(self.allocator);
defer self.allocator.free(cps);
return cps.len;
}
/// graphemeIter returns a grapheme cluster iterator based on the bytes of this Zigstr. Each grapheme
/// can be composed of multiple code points, so the next method returns a slice of bytes.
pub fn graphemeIter(self: *Self) anyerror!GraphemeIterator {
return GraphemeIterator.init(self.bytes.items);
}
/// graphemes returns the grapheme clusters that make up this Zigstr. Caller must free returned slice.
pub fn graphemes(self: *Self, allocator: mem.Allocator) ![]Grapheme {
// Cache miss, generate.
var giter = try self.graphemeIter();
var gcs = try std.ArrayList(Grapheme).initCapacity(allocator, self.bytes.items.len);
defer gcs.deinit();
while (giter.next()) |gc| {
gcs.appendAssumeCapacity(gc);
}
return gcs.toOwnedSlice();
}
/// graphemeCount returns the number of grapheme clusters, which can be different from the number of bytes
/// and the number of code points.
pub fn graphemeCount(self: *Self) !usize {
const gcs = try self.graphemes(self.allocator);
defer self.allocator.free(gcs);
return gcs.len;
}
/// copy a Zigstr to a new Zigstr. Don't forget to to `deinit` the returned Zigstr.
pub fn copy(self: Self, allocator: mem.Allocator) !Self {
return Self{
.allocator = allocator,
.bytes = b_blk: {
var al = try std.ArrayList(u8).initCapacity(allocator, self.bytes.items.len);
al.appendSliceAssumeCapacity(self.bytes.items);
break :b_blk al;
},
};
}
/// sameAs convenience method to test exact byte equality of two Zigstrs.
pub fn sameAs(self: Self, other: Self) bool {
return self.eql(other.bytes.items);
}
/// eql compares for exact byte per byte equality with `other`.
pub fn eql(self: Self, other: []const u8) bool {
return mem.eql(u8, self.bytes.items, other);
}
/// isAsciiStr checks if a string (`[]const uu`) is composed solely of ASCII characters.
pub fn isAsciiStr(str: []const u8) !bool {
// Shamelessly stolen from std.unicode.
const N = @sizeOf(usize);
const MASK = 0x80 * (std.math.maxInt(usize) / 0xff);
var i: usize = 0;
while (i < str.len) {
// Fast path for ASCII sequences
while (i + N <= str.len) : (i += N) {
const v = mem.readIntNative(usize, str[i..][0..N]);
if (v & MASK != 0) {
return false;
}
}
if (i < str.len) {
const n = try unicode.utf8ByteSequenceLength(str[i]);
if (i + n > str.len) return error.TruncatedInput;
switch (n) {
1 => {}, // ASCII
else => return false,
}
i += n;
}
}
return true;
}
/// trimLeft removes `str` from the left of this Zigstr, mutating it.
pub fn trimLeft(self: *Self, str: []const u8) !void {
const trimmed = mem.trimLeft(u8, self.bytes.items, str);
try self.bytes.replaceRange(0, self.bytes.items.len, trimmed);
}
/// trimRight removes `str` from the right of this Zigstr, mutating it.
pub fn trimRight(self: *Self, str: []const u8) !void {
const trimmed = mem.trimRight(u8, self.bytes.items, str);
try self.bytes.replaceRange(0, self.bytes.items.len, trimmed);
}
/// trim removes `str` from both the left and right of this Zigstr, mutating it.
pub fn trim(self: *Self, str: []const u8) !void {
const trimmed = mem.trim(u8, self.bytes.items, str);
try self.bytes.replaceRange(0, self.bytes.items.len, trimmed);
}
/// dropLeft removes `n` graphemes from the left of this Zigstr, mutating it.
pub fn dropLeft(self: *Self, n: usize) !void {
const gcs = try self.graphemes(self.allocator);
defer self.allocator.free(gcs);
if (n >= gcs.len) return error.IndexOutOfBounds;
const offset = gcs[n].offset;
mem.rotate(u8, self.bytes.items, offset);
self.bytes.shrinkRetainingCapacity(self.bytes.items.len - offset);
}
test "Zigstr dropLeft" {
var str = try fromBytes(std.testing.allocator, "Héllo");
defer str.deinit();
try str.dropLeft(4);
try expect(str.eql("o"));
}
/// dropRight removes `n` graphemes from the right of this Zigstr, mutating it.
pub fn dropRight(self: *Self, n: usize) !void {
const gcs = try self.graphemes(self.allocator);
defer self.allocator.free(gcs);
if (n > gcs.len) return error.IndexOutOfBounds;
if (n == gcs.len) {
try self.reset("");
return;
}
const offset = gcs[gcs.len - n].offset;
self.bytes.shrinkRetainingCapacity(offset);
}
test "Zigstr dropRight" {
var str = try fromBytes(std.testing.allocator, "Héllo");
defer str.deinit();
try str.dropRight(4);
try expect(str.eql("H"));
}
/// inserts `str` at grapheme index `n`. This operation is O(n).
pub fn insert(self: *Self, str: []const u8, n: usize) !void {
const gcs = try self.graphemes(self.allocator);
defer self.allocator.free(gcs);
if (n < gcs.len) {
try self.bytes.insertSlice(gcs[n].offset, str);
} else {
try self.bytes.insertSlice(gcs[n - 1].offset + gcs[n - 1].bytes.len, str);
}
}
test "Zigstr insertions" {
var str = try fromBytes(std.testing.allocator, "Hélo");
defer str.deinit();
try str.insert("l", 3);
try expect(str.eql("Héllo"));
try str.insert("Hey ", 0);
try expect(str.eql("H<NAME>"));
try str.insert("!", try str.graphemeCount());
try expect(str.eql("Hey Héllo!"));
}
/// indexOf returns the index of `needle` in this Zigstr or null if not found.
pub fn indexOf(self: Self, needle: []const u8) !?usize {
var iter = try GraphemeIterator.init(self.bytes.items);
var i: usize = 0;
while (iter.next()) |grapheme| : (i += 1) {
if (std.mem.startsWith(u8, grapheme.bytes, needle)) return i;
}
return null;
}
/// containes ceonvenience method to check if `str` is a substring of this Zigstr.
pub fn contains(self: Self, str: []const u8) !bool {
return (try self.indexOf(str)) != null;
}
/// lastIndexOf returns the index of `needle` in this Zigstr starting from the end, or null if not found.
pub fn lastIndexOf(self: Self, needle: []const u8) !?usize {
var iter = try GraphemeIterator.init(self.bytes.items);
var i: usize = 0;
var index: ?usize = null;
while (iter.next()) |grapheme| : (i += 1) {
if (std.mem.startsWith(u8, grapheme.bytes, needle)) index = i;
}
return index;
}
/// count returns the number of `needle`s in this Zigstr.
pub fn count(self: Self, needle: []const u8) usize {
return mem.count(u8, self.bytes.items, needle);
}
/// tokenIter returns an iterator on tokens resulting from splitting this Zigstr at every `delim`.
/// Semantics are that of `std.mem.tokenize`.
pub fn tokenIter(self: Self, delim: []const u8) mem.TokenIterator(u8) {
return mem.tokenize(u8, self.bytes.items, delim);
}
/// tokenize returns a slice of tokens resulting from splitting this Zigstr at every `delim`.
/// Caller must free returned slice.
pub fn tokenize(self: Self, delim: []const u8, allocator: mem.Allocator) ![][]const u8 {
var ts = try std.ArrayList([]const u8).initCapacity(allocator, self.bytes.items.len);
defer ts.deinit();
var iter = self.tokenIter(delim);
while (iter.next()) |t| {
ts.appendAssumeCapacity(t);
}
return ts.toOwnedSlice();
}
/// splitIter returns an iterator on substrings resulting from splitting this Zigstr at every `delim`.
/// Semantics are that of `std.mem.split`.
pub fn splitIter(self: Self, delim: []const u8) mem.SplitIterator(u8) {
return mem.split(u8, self.bytes.items, delim);
}
/// split returns a slice of substrings resulting from splitting this Zigstr at every `delim`.
/// Caller must free returned slice.
pub fn split(self: Self, delim: []const u8, allocator: mem.Allocator) ![][]const u8 {
var ss = try std.ArrayList([]const u8).initCapacity(allocator, self.bytes.items.len);
defer ss.deinit();
var iter = mem.split(u8, self.bytes.items, delim);
while (iter.next()) |s| {
ss.appendAssumeCapacity(s);
}
return ss.toOwnedSlice();
}
/// lineIter returns an iterator of lines separated by \n in this Zigstr.
pub fn lineIter(self: Self) mem.SplitIterator(u8) {
return self.splitIter("\n");
}
/// lines returns a slice of substrings resulting from splitting this Zigstr at every \n.
/// Caller must free returned slice.
pub fn lines(self: Self, allocator: mem.Allocator) ![][]const u8 {
return self.split("\n", allocator);
}
test "Zigstr lines" {
var allocator = std.testing.allocator;
var str = try fromBytes(allocator, "Hello\nWorld");
defer str.deinit();
var iter = str.lineIter();
try expectEqualStrings(iter.next().?, "Hello");
try expectEqualStrings(iter.next().?, "World");
var lines_array = try str.lines(allocator);
defer allocator.free(lines_array);
try expectEqualStrings(lines_array[0], "Hello");
try expectEqualStrings(lines_array[1], "World");
}
/// reverses the grapheme clusters in this Zigstr, mutating it.
pub fn reverse(self: *Self) !void {
const gcs = try self.graphemes(self.allocator);
defer self.allocator.free(gcs);
var new_al = try std.ArrayList(u8).initCapacity(self.allocator, self.bytes.items.len);
var gc_index: isize = @intCast(isize, gcs.len) - 1;
while (gc_index >= 0) : (gc_index -= 1) {
new_al.appendSliceAssumeCapacity(gcs[@intCast(usize, gc_index)].bytes);
}
self.bytes.deinit();
self.bytes = new_al;
}
test "Zigstr reverse" {
var str = try fromBytes(std.testing.allocator, "Héllo 😊");
defer str.deinit();
try str.reverse();
try expectEqualStrings(str.bytes.items, "😊 olléH");
}
/// startsWith returns true if this Zigstr starts with `str`.
pub fn startsWith(self: Self, str: []const u8) bool {
return mem.startsWith(u8, self.bytes.items, str);
}
/// endsWith returns true if this Zigstr ends with `str`.
pub fn endsWith(self: Self, str: []const u8) bool {
return mem.endsWith(u8, self.bytes.items, str);
}
/// concatAll appends each string in `others` to this Zigstr, mutating it.
pub fn concatAll(self: *Self, others: []const []const u8) !void {
for (others) |o| {
try self.bytes.appendSlice(o);
}
}
/// concat appends `other` to this Zigstr, mutating it.
pub fn concat(self: *Self, other: []const u8) !void {
try self.concatAll(&[1][]const u8{other});
}
/// replace all occurrences of `needle` with `replacement`, mutating this Zigstr. Returns the total
/// replacements made.
pub fn replace(self: *Self, needle: []const u8, replacement: []const u8) !usize {
const len = mem.replacementSize(u8, self.bytes.items, needle, replacement);
var buf = try self.allocator.alloc(u8, len);
defer self.allocator.free(buf);
const replacements = mem.replace(u8, self.bytes.items, needle, replacement, buf);
try self.bytes.replaceRange(0, self.bytes.items.len, buf);
return replacements;
}
/// remove `str` from this Zigstr, mutating it.
pub fn remove(self: *Self, str: []const u8) !void {
_ = try self.replace(str, "");
}
test "Zigstr remove" {
var str = try fromBytes(std.testing.allocator, "HiHello");
defer str.deinit();
try str.remove("Hi");
try expect(str.eql("Hello"));
try str.remove("Hello");
try expect(str.eql(""));
}
/// append adds `cp` to the end of this Zigstr, mutating it.
pub fn append(self: *Self, cp: u21) !void {
var buf: [4]u8 = undefined;
const len = try unicode.utf8Encode(cp, &buf);
try self.concat(buf[0..len]);
}
/// append adds `cp` to the end of this Zigstr, mutating it.
pub fn appendAll(self: *Self, cp_list: []const u21) !void {
var cp_bytes = try std.ArrayList(u8).initCapacity(self.allocator, cp_list.len * 4);
defer cp_bytes.deinit();
var buf: [4]u8 = undefined;
for (cp_list) |cp| {
const len = try unicode.utf8Encode(cp, &buf);
cp_bytes.appendSliceAssumeCapacity(buf[0..len]);
}
try self.concat(cp_bytes.items);
}
/// isEmpty returns true if this Zigstr has no bytes.
pub fn isEmpty(self: Self) bool {
return self.bytes.items.len == 0;
}
/// isBlank returns true if this Zigstr consits of whitespace only .
pub fn isBlank(self: *Self) !bool {
const cps = try self.codePoints(self.allocator);
defer self.allocator.free(cps);
return for (cps) |cp| {
if (!prop_list.isWhiteSpace(cp)) break false;
} else true;
}
test "Zigstr isBlank" {
var str = try fromBytes(std.testing.allocator, " \t ");
defer str.deinit();
try expect(try str.isBlank());
try str.reset(" a b \t");
try expect(!try str.isBlank());
}
/// chomp will remove trailing \n or \r\n from this Zigstr, mutating it.
pub fn chomp(self: *Self) !void {
if (self.isEmpty()) return;
const len = self.bytes.items.len;
const last = self.bytes.items[len - 1];
if (last == '\r' or last == '\n') {
// CR
var chomp_size: usize = 1;
if (len > 1 and last == '\n' and self.bytes.items[self.bytes.items.len - 2] == '\r') chomp_size = 2; // CR+LF
self.bytes.shrinkRetainingCapacity(len - chomp_size);
}
}
/// byteAt returns the byte at index `i`.
pub fn byteAt(self: Self, i: isize) !u8 {
if (i >= self.bytes.items.len) return error.IndexOutOfBounds;
if (i < 0) {
if (-%i > self.bytes.items.len) return error.IndexOutOfBounds;
return self.bytes.items[self.bytes.items.len - @intCast(usize, -i)];
}
return self.bytes.items[@intCast(usize, i)];
}
/// codePointAt returns the `i`th code point.
pub fn codePointAt(self: *Self, i: isize) !u21 {
const cps = try self.codePoints(self.allocator);
defer self.allocator.free(cps);
if (i >= cps.len) return error.IndexOutOfBounds;
if (i < 0) {
if (-%i > cps.len) return error.IndexOutOfBounds;
return cps[cps.len - @intCast(usize, -i)];
}
return cps[@intCast(usize, i)];
}
/// graphemeAt returns the `i`th grapheme cluster.
pub fn graphemeAt(self: *Self, i: isize) !Grapheme {
const gcs = try self.graphemes(self.allocator);
defer self.allocator.free(gcs);
if (i >= gcs.len) return error.IndexOutOfBounds;
if (i < 0) {
if (-%i > gcs.len) return error.IndexOutOfBounds;
return gcs[gcs.len - @intCast(usize, -i)];
}
return gcs[@intCast(usize, i)];
}
/// byteSlice returnes the bytes from this Zigstr in the specified range from `start` to `end` - 1.
pub fn byteSlice(self: Self, start: usize, end: usize) ![]const u8 {
if (end <= start) return error.InvalidRange;
if (start >= self.bytes.items.len or end > self.bytes.items.len) return error.IndexOutOfBounds;
return self.bytes.items[start..end];
}
/// codePointSlice returnes the code points from this Zigstr in the specified range from `start` to `end` - 1.
/// Caller must free returned slice.
pub fn codePointSlice(self: *Self, allocator: mem.Allocator, start: usize, end: usize) ![]u21 {
if (end <= start) return error.InvalidRange;
const cps = try self.codePoints(allocator);
defer allocator.free(cps);
if (start >= cps.len or end > cps.len) return error.IndexOutOfBounds;
var rcps = try std.ArrayList(u21).initCapacity(allocator, end - start);
defer rcps.deinit();
for (cps[start..end]) |cp| {
rcps.appendAssumeCapacity(cp);
}
return rcps.toOwnedSlice();
}
/// graphemeSlice returnes the grapheme clusters from this Zigstr in the specified range from `start` to `end` - 1.
/// Caller must free returned slice.
pub fn graphemeSlice(self: *Self, allocator: mem.Allocator, start: usize, end: usize) ![]Grapheme {
if (end <= start) return error.InvalidRange;
const gcs = try self.graphemes(allocator);
defer allocator.free(gcs);
if (start >= gcs.len or end > gcs.len) return error.IndexOutOfBounds;
var rgcs = try std.ArrayList(Grapheme).initCapacity(allocator, end - start);
defer rgcs.deinit();
for (gcs[start..end]) |gc| {
rgcs.appendAssumeCapacity(gc);
}
return rgcs.toOwnedSlice();
}
/// substr returns a byte slice representing the grapheme range starting at `start` grapheme index
/// up to `end` grapheme index - 1.
pub fn substr(self: *Self, start: usize, end: usize) ![]const u8 {
if (end <= start) return error.InvalidRange;
if (try isAsciiStr(self.bytes.items)) {
if (start >= self.bytes.items.len or end > self.bytes.items.len) return error.IndexOutOfBounds;
return self.bytes.items[start..end];
}
const gcs = try self.graphemes(self.allocator);
defer self.allocator.free(gcs);
if (start >= gcs.len or end > gcs.len) return error.IndexOutOfBounds;
return self.bytes.items[gcs[start].offset..gcs[end].offset];
}
/// isLower detects if all the code points in this Zigstr are lowercase.
pub fn isLower(self: *Self) !bool {
return ziglyph.isLowerStr(self.bytes.items);
}
/// toLower converts this Zigstr to lowercase, mutating it.
pub fn toLower(self: *Self) !void {
const lower = try ziglyph.toLowerStr(self.allocator, self.bytes.items);
defer self.allocator.free(lower);
try self.reset(lower);
}
/// isUpper detects if all the code points in this Zigstr are uppercase.
pub fn isUpper(self: *Self) !bool {
return ziglyph.isUpperStr(self.bytes.items);
}
/// toUpper converts this Zigstr to uppercase, mutating it.
pub fn toUpper(self: *Self) !void {
const upper = try ziglyph.toUpperStr(self.allocator, self.bytes.items);
defer self.allocator.free(upper);
try self.reset(upper);
}
/// toTitle converts this Zigstr to titlecase, mutating it.
pub fn toTitle(self: *Self) !void {
const title = try ziglyph.toTitleStr(self.allocator, self.bytes.items);
defer self.allocator.free(title);
try self.reset(title);
}
/// format implements the `std.fmt` format interface for printing types.
pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
_ = try writer.print("{s}", .{self.bytes.items});
}
/// parseInt tries to parse this Zigstr as an integer of type `T` in base `radix`.
pub fn parseInt(self: Self, comptime T: type, radix: u8) !T {
return std.fmt.parseInt(T, self.bytes.items, radix);
}
/// parseFloat tries to parse this Zigstr as an floating point number of type `T`.
pub fn parseFloat(self: Self, comptime T: type) !T {
return std.fmt.parseFloat(T, self.bytes.items);
}
test "Zigstr parse numbers" {
var str = try fromBytes(std.testing.allocator, "2112");
defer str.deinit();
try expectEqual(@as(u16, 2112), try str.parseInt(u16, 10));
try expectEqual(@as(i16, 2112), try str.parseInt(i16, 10));
try expectEqual(@as(f16, 2112.0), try str.parseFloat(f16));
}
/// repeats the contents of this Zigstr `n` times, mutating it.
pub fn repeat(self: *Self, n: usize) !void {
if (n == 1) return;
var new_al = try std.ArrayList(u8).initCapacity(self.allocator, self.bytes.items.len * n);
var i: usize = 0;
while (i < n) : (i += 1) {
new_al.appendSliceAssumeCapacity(self.bytes.items);
}
self.bytes.deinit();
self.bytes = new_al;
}
test "Zigstr repeat" {
var str = try fromBytes(std.testing.allocator, "*");
defer str.deinit();
try str.repeat(10);
try expectEqualStrings(str.bytes.items, "**********");
try str.repeat(1);
try expectEqualStrings(str.bytes.items, "**********");
try str.repeat(0);
try expectEqualStrings(str.bytes.items, "");
}
/// parseBool parses this Zigstr as either true or false.
pub fn parseBool(self: Self) !bool {
if (mem.eql(u8, self.bytes.items, "true")) return true;
if (mem.eql(u8, self.bytes.items, "false")) return false;
return error.ParseBoolError;
}
/// parseTruthy parses this Zigstr as a *truthy* value:
/// * True and T in any case combination are true.
/// * False and F in any case combination are false.
/// * 0 is false, 1 is true.
/// * Yes, Y, and On in any case combination are true.
/// * No, N, and Off in any case combination are false.
pub fn parseTruthy(self: Self) !bool {
var lstr = try fromBytes(self.allocator, self.bytes.items);
defer lstr.deinit();
try lstr.toLower();
// True
if (mem.eql(u8, lstr.bytes.items, "true")) return true;
if (mem.eql(u8, lstr.bytes.items, "t")) return true;
if (mem.eql(u8, lstr.bytes.items, "on")) return true;
if (mem.eql(u8, lstr.bytes.items, "yes")) return true;
if (mem.eql(u8, lstr.bytes.items, "y")) return true;
if (mem.eql(u8, lstr.bytes.items, "1")) return true;
// False
if (mem.eql(u8, lstr.bytes.items, "false")) return false;
if (mem.eql(u8, lstr.bytes.items, "f")) return false;
if (mem.eql(u8, lstr.bytes.items, "off")) return false;
if (mem.eql(u8, lstr.bytes.items, "no")) return false;
if (mem.eql(u8, lstr.bytes.items, "n")) return false;
if (mem.eql(u8, lstr.bytes.items, "0")) return false;
return error.ParseTruthyError;
}
test "Zigstr parse bool truthy" {
var str = try fromBytes(std.testing.allocator, "true");
defer str.deinit();
try expect(try str.parseBool());
try expect(try str.parseTruthy());
try str.reset("false");
try expect(!try str.parseBool());
try expect(!try str.parseTruthy());
try str.reset("true");
try expect(try str.parseTruthy());
try str.reset("t");
try expect(try str.parseTruthy());
try str.reset("on");
try expect(try str.parseTruthy());
try str.reset("yes");
try expect(try str.parseTruthy());
try str.reset("y");
try expect(try str.parseTruthy());
try str.reset("1");
try expect(try str.parseTruthy());
try str.reset("TrUe");
try expect(try str.parseTruthy());
try str.reset("false");
try expect(!try str.parseTruthy());
try str.reset("f");
try expect(!try str.parseTruthy());
try str.reset("off");
try expect(!try str.parseTruthy());
try str.reset("no");
try expect(!try str.parseTruthy());
try str.reset("n");
try expect(!try str.parseTruthy());
try str.reset("0");
try expect(!try str.parseTruthy());
try str.reset("FaLsE");
try expect(!try str.parseTruthy());
}
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualSlices = std.testing.expectEqualSlices;
const expectEqualStrings = std.testing.expectEqualStrings;
const expectError = std.testing.expectError;
test "Zigstr code points" {
var allocator = std.testing.allocator;
var str = try fromBytes(allocator, "Héllo");
defer str.deinit();
var cp_iter = str.codePointIter();
var want = [_]u21{ 'H', 0x00E9, 'l', 'l', 'o' };
var i: usize = 0;
while (cp_iter.next()) |cp| : (i += 1) {
try expectEqual(want[i], cp.scalar);
}
const cps = try str.codePoints(allocator);
defer allocator.free(cps);
try expectEqualSlices(u21, &want, cps);
try expectEqual(@as(usize, 6), str.byteCount());
try expectEqual(@as(usize, 5), try str.codePointCount());
}
test "Zigstr graphemes" {
var allocator = std.testing.allocator;
var str = try fromBytes(allocator, "Héllo");
defer str.deinit();
var giter = try str.graphemeIter();
var want = [_][]const u8{ "H", "é", "l", "l", "o" };
var i: usize = 0;
while (giter.next()) |gc| : (i += 1) {
try expect(gc.eql(want[i]));
}
const gcs = try str.graphemes(allocator);
defer allocator.free(gcs);
for (gcs) |gc, j| {
try expect(gc.eql(want[j]));
}
try expectEqual(@as(usize, 6), str.byteCount());
try expectEqual(@as(usize, 5), try str.graphemeCount());
}
test "Zigstr copy" {
var str1 = try fromBytes(std.testing.allocator, "Zig");
defer str1.deinit();
var str2 = try str1.copy(std.testing.allocator);
defer str2.deinit();
try expect(str1.eql(str2.bytes.items));
try expect(str2.eql("Zig"));
try expect(str1.sameAs(str2));
}
test "Zigstr isAsciiStr" {
try expect(try isAsciiStr("Hello!"));
try expect(!try isAsciiStr("Héllo!"));
}
test "Zigstr trimLeft" {
var str = try fromBytes(std.testing.allocator, " Hello");
defer str.deinit();
try str.trimLeft(" ");
try expect(str.eql("Hello"));
}
test "Zigstr trimRight" {
var str = try fromBytes(std.testing.allocator, "Hello ");
defer str.deinit();
try str.trimRight(" ");
try expect(str.eql("Hello"));
}
test "Zigstr trim" {
var str = try fromBytes(std.testing.allocator, " Hello ");
defer str.deinit();
try str.trim(" ");
try expect(str.eql("Hello"));
}
test "Zigstr indexOf" {
var str = try fromBytes(std.testing.allocator, "Hello");
defer str.deinit();
try expectEqual(try str.indexOf("l"), 2);
try expectEqual(try str.indexOf("z"), null);
try expect(try str.contains("l"));
try expect(!try str.contains("z"));
}
test "Zigstr lastIndexOf" {
var str = try fromBytes(std.testing.allocator, "Hello");
defer str.deinit();
try expectEqual(try str.lastIndexOf("l"), 3);
try expectEqual(try str.lastIndexOf("z"), null);
}
test "Zigstr count" {
var str = try fromBytes(std.testing.allocator, "Hello");
defer str.deinit();
try expectEqual(str.count("l"), 2);
try expectEqual(str.count("ll"), 1);
try expectEqual(str.count("z"), 0);
}
test "Zigstr tokenize" {
var allocator = std.testing.allocator;
var str = try fromBytes(allocator, " Hello World ");
defer str.deinit();
var iter = str.tokenIter(" ");
try expectEqualStrings("Hello", iter.next().?);
try expectEqualStrings("World", iter.next().?);
try expect(iter.next() == null);
var ts = try str.tokenize(" ", allocator);
defer allocator.free(ts);
try expectEqual(@as(usize, 2), ts.len);
try expectEqualStrings("Hello", ts[0]);
try expectEqualStrings("World", ts[1]);
}
test "Zigstr split" {
var allocator = std.testing.allocator;
var str = try fromBytes(allocator, " Hello World ");
defer str.deinit();
var iter = str.splitIter(" ");
try expectEqualStrings("", iter.next().?);
try expectEqualStrings("Hello", iter.next().?);
try expectEqualStrings("World", iter.next().?);
try expectEqualStrings("", iter.next().?);
try expect(iter.next() == null);
var ss = try str.split(" ", allocator);
defer allocator.free(ss);
try expectEqual(@as(usize, 4), ss.len);
try expectEqualStrings("", ss[0]);
try expectEqualStrings("Hello", ss[1]);
try expectEqualStrings("World", ss[2]);
try expectEqualStrings("", ss[3]);
}
test "Zigstr startsWith" {
var str = try fromBytes(std.testing.allocator, "Hello World");
defer str.deinit();
try expect(str.startsWith("Hell"));
try expect(!str.startsWith("Zig"));
}
test "Zigstr endsWith" {
var str = try fromBytes(std.testing.allocator, "Hello World");
defer str.deinit();
try expect(str.endsWith("World"));
try expect(!str.endsWith("Zig"));
}
test "Zigstr concat" {
var str = try fromBytes(std.testing.allocator, "Hello");
defer str.deinit();
try str.concat(" World");
try expectEqualStrings("Hello World", str.bytes.items);
var others = [_][]const u8{ " is", " the", " tradition!" };
try str.concatAll(&others);
try expectEqualStrings("Hello World is the tradition!", str.bytes.items);
}
test "Zigstr replace" {
var str = try fromBytes(std.testing.allocator, "Hello");
defer str.deinit();
var replacements = try str.replace("l", "z");
try expectEqual(@as(usize, 2), replacements);
try expect(str.eql("Hezzo"));
replacements = try str.replace("z", "");
try expectEqual(@as(usize, 2), replacements);
try expect(str.eql("Heo"));
}
test "Zigstr append" {
var str = try fromBytes(std.testing.allocator, "Hell");
defer str.deinit();
try str.append('o');
try expectEqual(@as(usize, 5), str.bytes.items.len);
try expect(str.eql("Hello"));
try str.appendAll(&[_]u21{ ' ', 'W', 'o', 'r', 'l', 'd' });
try expectEqual(@as(usize, 11), str.bytes.items.len);
try expect(str.eql("Hello World"));
}
test "Zigstr chomp" {
var str = try fromBytes(std.testing.allocator, "Hello\n");
defer str.deinit();
try str.chomp();
try expectEqual(@as(usize, 5), str.bytes.items.len);
try expect(str.eql("Hello"));
try str.reset("Hello\r");
try str.chomp();
try expectEqual(@as(usize, 5), str.bytes.items.len);
try expect(str.eql("Hello"));
try str.reset("Hello\r\n");
try str.chomp();
try expectEqual(@as(usize, 5), str.bytes.items.len);
try expect(str.eql("Hello"));
}
test "Zigstr xAt" {
var str = try fromBytes(std.testing.allocator, "H\u{0065}\u{0301}llo");
defer str.deinit();
try expectEqual(try str.byteAt(2), 0x00CC);
try expectEqual(try str.byteAt(-5), 0x00CC);
try expectError(error.IndexOutOfBounds, str.byteAt(7));
try expectError(error.IndexOutOfBounds, str.byteAt(-8));
try expectEqual(try str.codePointAt(1), 0x0065);
try expectEqual(try str.codePointAt(-5), 0x0065);
try expectError(error.IndexOutOfBounds, str.codePointAt(6));
try expectError(error.IndexOutOfBounds, str.codePointAt(-7));
try expect((try str.graphemeAt(1)).eql("\u{0065}\u{0301}"));
try expect((try str.graphemeAt(-4)).eql("\u{0065}\u{0301}"));
try expectError(error.IndexOutOfBounds, str.graphemeAt(5));
try expectError(error.IndexOutOfBounds, str.graphemeAt(-6));
}
test "Zigstr extractions" {
var allocator = std.testing.allocator;
var str = try fromBytes(allocator, "H\u{0065}\u{0301}llo");
defer str.deinit();
// Slices
const bytes = try str.byteSlice(1, 4);
try expectEqualSlices(u8, bytes, "\u{0065}\u{0301}");
const cps = try str.codePointSlice(allocator, 1, 3);
defer allocator.free(cps);
try expectEqualSlices(u21, cps, &[_]u21{ '\u{0065}', '\u{0301}' });
const gcs = try str.graphemeSlice(allocator, 1, 2);
defer allocator.free(gcs);
try expect(gcs[0].eql("\u{0065}\u{0301}"));
// Substrings
var sub = try str.substr(1, 2);
try expectEqualStrings("\u{0065}\u{0301}", sub);
try expectEqualStrings(bytes, sub);
}
test "Zigstr casing" {
var str = try fromBytes(std.testing.allocator, "Héllo! 123");
defer str.deinit();
try expect(!try str.isLower());
try expect(!try str.isUpper());
try str.toLower();
try expect(try str.isLower());
try expect(str.eql("héllo! 123"));
try str.toUpper();
try expect(try str.isUpper());
try expect(str.eql("HÉLLO! 123"));
}
test "Zigstr format" {
var str = try fromBytes(std.testing.allocator, "Héllo 😊");
defer str.deinit();
std.debug.print("{}\n", .{str});
} | src/Zigstr.zig |
const std = @import("std");
const logger = std.log.scoped(.qoi);
pub const Color = extern struct {
r: u8,
g: u8,
b: u8,
a: u8 = 0xFF,
fn hash(c: Color) u6 {
return @truncate(u6, c.r *% 3 +% c.g *% 5 +% c.b *% 7 +% c.a *% 11);
}
pub fn eql(a: Color, b: Color) bool {
return std.meta.eql(a, b);
}
};
/// A QOI image with RGBA pixels.
pub const Image = struct {
width: u32,
height: u32,
pixels: []Color,
colorspace: Colorspace,
pub fn asConst(self: Image) ConstImage {
return ConstImage{
.width = self.width,
.height = self.height,
.pixels = self.pixels,
.colorspace = self.colorspace,
};
}
pub fn deinit(self: *Image, allocator: std.mem.Allocator) void {
allocator.free(self.pixels);
self.* = undefined;
}
};
/// A QOI image with RGBA pixels.
pub const ConstImage = struct {
width: u32,
height: u32,
pixels: []const Color,
colorspace: Colorspace,
};
/// Returns true if `bytes` appear to contain a valid QOI image.
pub fn isQOI(bytes: []const u8) bool {
if (bytes.len < Header.size)
return false;
const header = Header.decode(bytes[0..Header.size].*) catch return false;
return (bytes.len >= Header.size + header.size);
}
pub const DecodeError = error{ OutOfMemory, InvalidData, EndOfStream };
/// Decodes a buffer containing a QOI image and returns the decoded image.
pub fn decodeBuffer(allocator: std.mem.Allocator, buffer: []const u8) DecodeError!Image {
if (buffer.len < Header.size)
return error.InvalidData;
var stream = std.io.fixedBufferStream(buffer);
return try decodeStream(allocator, stream.reader());
}
fn LimitedBufferedStream(comptime UnderlyingReader: type, comptime buffer_size: usize) type {
return struct {
const Self = @This();
const Error = UnderlyingReader.Error || error{EndOfStream};
const FifoType = std.fifo.LinearFifo(u8, std.fifo.LinearFifoBufferType{ .Static = buffer_size });
unbuffered_reader: UnderlyingReader,
limit: usize,
fifo: FifoType = FifoType.init(),
pub const Reader = std.io.Reader(*Self, Error, read);
pub fn reader(self: *Self) Reader {
return Reader{ .context = self };
}
pub fn read(self: *Self, dest: []u8) Error!usize {
var dest_index: usize = 0;
while (dest_index < dest.len) {
const written = self.fifo.read(dest[dest_index..]);
if (written == 0) {
// fifo empty, fill it
const writable = self.fifo.writableSlice(0);
std.debug.assert(writable.len > 0);
if (self.limit == 0)
return error.EndOfStream;
const max_data = std.math.min(self.limit, writable.len);
const n = try self.unbuffered_reader.read(writable[0..max_data]);
if (n == 0) {
// reading from the unbuffered stream returned nothing
// so we have nothing left to read.
return dest_index;
}
self.limit -= n;
self.fifo.update(n);
}
dest_index += written;
}
return dest.len;
}
};
}
const debug_decode_qoi_opcodes = false;
/// Decodes a QOI stream and returns the decoded image.
pub fn decodeStream(allocator: std.mem.Allocator, reader: anytype) (DecodeError || @TypeOf(reader).Error)!Image {
var header_data: [Header.size]u8 = undefined;
try reader.readNoEof(&header_data);
const header = Header.decode(header_data) catch return error.InvalidData;
const size_raw = @as(u64, header.width) * @as(u64, header.height);
const size = std.math.cast(usize, size_raw) catch return error.OutOfMemory;
var img = Image{
.width = header.width,
.height = header.height,
.pixels = try allocator.alloc(Color, size),
.colorspace = header.colorspace,
};
errdefer allocator.free(img.pixels);
var current_color = Color{ .r = 0, .g = 0, .b = 0, .a = 0xFF };
var color_lut = std.mem.zeroes([64]Color);
var index: usize = 0;
while (index < img.pixels.len) {
var byte = try reader.readByte();
var new_color = current_color;
var count: usize = 1;
if (byte == 0b11111110) { // QOI_OP_RGB
new_color.r = try reader.readByte();
new_color.g = try reader.readByte();
new_color.b = try reader.readByte();
if (debug_decode_qoi_opcodes) {
new_color = Color{ .r = 0xFF, .g = 0x00, .b = 0x00 };
}
} else if (byte == 0b11111111) { // QOI_OP_RGBA
new_color.r = try reader.readByte();
new_color.g = try reader.readByte();
new_color.b = try reader.readByte();
new_color.a = try reader.readByte();
if (debug_decode_qoi_opcodes) {
new_color = Color{ .r = 0x00, .g = 0xFF, .b = 0x00 };
}
} else if (hasPrefix(byte, u2, 0b00)) { // QOI_OP_INDEX
const color_index = @truncate(u6, byte);
new_color = color_lut[color_index];
if (debug_decode_qoi_opcodes) {
new_color = Color{ .r = 0x00, .g = 0x00, .b = 0xFF };
}
} else if (hasPrefix(byte, u2, 0b01)) { // QOI_OP_DIFF
const diff_r = unmapRange2(byte >> 4);
const diff_g = unmapRange2(byte >> 2);
const diff_b = unmapRange2(byte >> 0);
add8(&new_color.r, diff_r);
add8(&new_color.g, diff_g);
add8(&new_color.b, diff_b);
if (debug_decode_qoi_opcodes) {
new_color = Color{ .r = 0xFF, .g = 0xFF, .b = 0x00 };
}
} else if (hasPrefix(byte, u2, 0b10)) { // QOI_OP_LUMA
const diff_g = unmapRange6(byte);
const diff_rg_rb = try reader.readByte();
const diff_rg = unmapRange4(diff_rg_rb >> 4);
const diff_rb = unmapRange4(diff_rg_rb >> 0);
const diff_r = @as(i8, diff_g) + diff_rg;
const diff_b = @as(i8, diff_g) + diff_rb;
add8(&new_color.r, diff_r);
add8(&new_color.g, diff_g);
add8(&new_color.b, diff_b);
if (debug_decode_qoi_opcodes) {
new_color = Color{ .r = 0xFF, .g = 0x00, .b = 0xFF };
}
} else if (hasPrefix(byte, u2, 0b11)) { // QOI_OP_RUN
count = @as(usize, @truncate(u6, byte)) + 1;
std.debug.assert(count >= 1 and count <= 62);
if (debug_decode_qoi_opcodes) {
new_color = Color{ .r = 0x00, .g = 0xFF, .b = 0xFF };
}
} else {
// we have covered all possibilities.
unreachable;
}
// this will happen when a file has an invalid run length
// and we would decode more pixels than there are in the image.
if (index + count > img.pixels.len) {
return error.InvalidData;
}
while (count > 0) {
count -= 1;
img.pixels[index] = new_color;
index += 1;
if (debug_decode_qoi_opcodes) {
new_color = Color{ .r = 0x80, .g = 0x80, .b = 0x80 };
}
}
color_lut[new_color.hash()] = new_color;
current_color = new_color;
}
return img;
}
pub const EncodeError = error{};
/// Encodes a given `image` into a QOI buffer.
pub fn encodeBuffer(allocator: std.mem.Allocator, image: ConstImage) (std.mem.Allocator.Error || EncodeError)![]u8 {
var destination_buffer = std.ArrayList(u8).init(allocator);
defer destination_buffer.deinit();
try encodeStream(image, destination_buffer.writer());
return destination_buffer.toOwnedSlice();
}
/// Encodes a given `image` into a QOI buffer.
pub fn encodeStream(image: ConstImage, writer: anytype) (EncodeError || @TypeOf(writer).Error)!void {
var format = for (image.pixels) |pix| {
if (pix.a != 0xFF)
break Format.rgba;
} else Format.rgb;
var header = Header{
.width = image.width,
.height = image.height,
.format = format,
.colorspace = .sRGB,
};
try writer.writeAll(&header.encode());
var color_lut = std.mem.zeroes([64]Color);
var previous_pixel = Color{ .r = 0, .g = 0, .b = 0, .a = 0xFF };
var run_length: usize = 0;
for (image.pixels) |pixel, i| {
defer previous_pixel = pixel;
const same_pixel = pixel.eql(previous_pixel);
if (same_pixel) {
run_length += 1;
}
if (run_length > 0 and (run_length == 62 or !same_pixel or (i == (image.pixels.len - 1)))) {
// QOI_OP_RUN
std.debug.assert(run_length >= 1 and run_length <= 62);
try writer.writeByte(0b1100_0000 | @truncate(u8, run_length - 1));
run_length = 0;
}
if (!same_pixel) {
const hash = pixel.hash();
if (color_lut[hash].eql(pixel)) {
// QOI_OP_INDEX
try writer.writeByte(0b0000_0000 | hash);
} else {
color_lut[hash] = pixel;
const diff_r = @as(i16, pixel.r) - @as(i16, previous_pixel.r);
const diff_g = @as(i16, pixel.g) - @as(i16, previous_pixel.g);
const diff_b = @as(i16, pixel.b) - @as(i16, previous_pixel.b);
const diff_a = @as(i16, pixel.a) - @as(i16, previous_pixel.a);
const diff_rg = diff_r - diff_g;
const diff_rb = diff_b - diff_g;
if (diff_a == 0 and inRange2(diff_r) and inRange2(diff_g) and inRange2(diff_b)) {
// QOI_OP_DIFF
const byte = 0b0100_0000 |
(mapRange2(diff_r) << 4) |
(mapRange2(diff_g) << 2) |
(mapRange2(diff_b) << 0);
try writer.writeByte(byte);
} else if (diff_a == 0 and inRange6(diff_g) and inRange4(diff_rg) and inRange4(diff_rb)) {
// QOI_OP_LUMA
try writer.writeAll(&[2]u8{
0b1000_0000 | mapRange6(diff_g),
(mapRange4(diff_rg) << 4) | (mapRange4(diff_rb) << 0),
});
} else if (diff_a == 0) {
// QOI_OP_RGB
try writer.writeAll(&[4]u8{
0b1111_1110,
pixel.r,
pixel.g,
pixel.b,
});
} else {
// QOI_OP_RGBA
try writer.writeAll(&[5]u8{
0b1111_1111,
pixel.r,
pixel.g,
pixel.b,
pixel.a,
});
}
}
}
}
try writer.writeAll(&[8]u8{
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x01,
});
}
fn mapRange2(val: i16) u8 {
return @intCast(u2, val + 2);
}
fn mapRange4(val: i16) u8 {
return @intCast(u4, val + 8);
}
fn mapRange6(val: i16) u8 {
return @intCast(u6, val + 32);
}
fn unmapRange2(val: u32) i2 {
return @intCast(i2, @as(i8, @truncate(u2, val)) - 2);
}
fn unmapRange4(val: u32) i4 {
return @intCast(i4, @as(i8, @truncate(u4, val)) - 8);
}
fn unmapRange6(val: u32) i6 {
return @intCast(i6, @as(i8, @truncate(u6, val)) - 32);
}
fn inRange2(val: i16) bool {
return (val >= -2) and (val <= 1);
}
fn inRange4(val: i16) bool {
return (val >= -8) and (val <= 7);
}
fn inRange6(val: i16) bool {
return (val >= -32) and (val <= 31);
}
fn add8(dst: *u8, diff: i8) void {
dst.* +%= @bitCast(u8, diff);
}
fn hasPrefix(value: u8, comptime T: type, prefix: T) bool {
return (@truncate(T, value >> (8 - @bitSizeOf(T))) == prefix);
}
pub const Header = struct {
const size = 14;
const correct_magic = [4]u8{ 'q', 'o', 'i', 'f' };
width: u32,
height: u32,
format: Format,
colorspace: Colorspace,
fn decode(buffer: [size]u8) !Header {
if (!std.mem.eql(u8, buffer[0..4], &correct_magic))
return error.InvalidMagic;
return Header{
.width = std.mem.readIntBig(u32, buffer[4..8]),
.height = std.mem.readIntBig(u32, buffer[8..12]),
.format = try std.meta.intToEnum(Format, buffer[12]),
.colorspace = try std.meta.intToEnum(Colorspace, buffer[13]),
};
}
fn encode(header: Header) [size]u8 {
var result: [size]u8 = undefined;
std.mem.copy(u8, result[0..4], &correct_magic);
std.mem.writeIntBig(u32, result[4..8], header.width);
std.mem.writeIntBig(u32, result[8..12], header.height);
result[12] = @enumToInt(header.format);
result[13] = @enumToInt(header.colorspace);
return result;
}
};
pub const Colorspace = enum(u8) {
/// sRGB color, linear alpha
sRGB = 0,
/// Every channel is linear
linear = 1,
};
pub const Format = enum(u8) {
rgb = 3,
rgba = 4,
};
test "decode qoi" {
const src_data = @embedFile("../data/zero.qoi");
var image = try decodeBuffer(std.testing.allocator, src_data);
defer image.deinit(std.testing.allocator);
try std.testing.expectEqual(@as(u32, 512), image.width);
try std.testing.expectEqual(@as(u32, 512), image.height);
try std.testing.expectEqual(@as(usize, 512 * 512), image.pixels.len);
const dst_data = @embedFile("../data/zero.raw");
try std.testing.expectEqualSlices(u8, dst_data, std.mem.sliceAsBytes(image.pixels));
}
test "decode qoi file" {
var file = try std.fs.cwd().openFile("data/zero.qoi", .{});
defer file.close();
var image = try decodeStream(std.testing.allocator, file.reader());
defer image.deinit(std.testing.allocator);
try std.testing.expectEqual(@as(u32, 512), image.width);
try std.testing.expectEqual(@as(u32, 512), image.height);
try std.testing.expectEqual(@as(usize, 512 * 512), image.pixels.len);
const dst_data = @embedFile("../data/zero.raw");
try std.testing.expectEqualSlices(u8, dst_data, std.mem.sliceAsBytes(image.pixels));
}
test "encode qoi" {
const src_data = @embedFile("../data/zero.raw");
var dst_data = try encodeBuffer(std.testing.allocator, ConstImage{
.width = 512,
.height = 512,
.pixels = std.mem.bytesAsSlice(Color, src_data),
.colorspace = .sRGB,
});
defer std.testing.allocator.free(dst_data);
const ref_data = @embedFile("../data/zero.qoi");
try std.testing.expectEqualSlices(u8, ref_data, dst_data);
}
test "random encode/decode" {
var rng_engine = std.rand.DefaultPrng.init(0x1337);
const rng = rng_engine.random();
const width = 251;
const height = 49;
var rounds: usize = 512;
while (rounds > 0) {
rounds -= 1;
var input_buffer: [width * height]Color = undefined;
rng.bytes(std.mem.sliceAsBytes(&input_buffer));
var encoded_data = try encodeBuffer(std.testing.allocator, ConstImage{
.width = width,
.height = height,
.pixels = &input_buffer,
.colorspace = if (rng.boolean()) Colorspace.sRGB else Colorspace.linear,
});
defer std.testing.allocator.free(encoded_data);
var image = try decodeBuffer(std.testing.allocator, encoded_data);
defer image.deinit(std.testing.allocator);
try std.testing.expectEqual(@as(u32, width), image.width);
try std.testing.expectEqual(@as(u32, height), image.height);
try std.testing.expectEqualSlices(Color, &input_buffer, image.pixels);
}
}
test "input fuzzer. plz do not crash" {
var rng_engine = std.rand.DefaultPrng.init(0x1337);
const rng = rng_engine.random();
var rounds: usize = 32;
while (rounds > 0) {
rounds -= 1;
var input_buffer: [1 << 20]u8 = undefined; // perform on a 1 MB buffer
rng.bytes(&input_buffer);
if ((rounds % 4) != 0) { // 25% is fully random 75% has a correct looking header
std.mem.copy(u8, &input_buffer, &(Header{
.width = rng.int(u16),
.height = rng.int(u16),
.format = rng.enumValue(Format),
.colorspace = rng.enumValue(Colorspace),
}).encode());
}
var stream = std.io.fixedBufferStream(&input_buffer);
if (decodeStream(std.testing.allocator, stream.reader())) |*image| {
defer image.deinit(std.testing.allocator);
} else |err| {
// error is also okay, just no crashes plz
err catch {};
}
}
} | sharing-part2/ZigAdventures/zighello/src/qoi.zig |
const std = @import("std");
const Op = @import("op.zig");
const Module = @import("module.zig");
const Instance = @import("instance.zig");
const Memory = @import("Memory.zig");
const util = @import("util.zig");
const Execution = @This();
memory: *Memory,
funcs: []const Instance.Func,
allocator: *std.mem.Allocator,
instance: *const Instance,
stack: []Op.Fixval,
stack_top: usize,
current_frame: Frame = Frame.terminus(),
result: Op.WasmTrap!?Op.Fixval,
pub fn run(instance: *Instance, stack: []Op.Fixval, func_id: usize, params: []Op.Fixval) !?Op.Fixval {
var ctx = Execution{
.memory = &instance.memory,
.funcs = instance.funcs,
.allocator = instance.allocator,
.instance = instance,
.stack = stack,
.stack_top = 0,
.result = undefined,
};
// initCall assumes the params are already pushed onto the stack
for (params) |param| {
try ctx.push(Op.Fixval, param);
}
try ctx.initCall(func_id);
if (ctx.current_frame.isTerminus()) {
return switch (ctx.stack_top) {
0 => null,
1 => ctx.stack[0],
else => unreachable,
};
}
tailDispatch(&ctx, undefined);
return ctx.result;
}
fn tailDispatch(self: *Execution, arg: Op.Arg) callconv(.C) void {
const func = self.funcs[self.current_frame.func];
if (self.current_frame.instr >= func.kind.instrs.len) {
return @call(.{ .modifier = .always_tail }, tailUnwind, .{ self, arg });
}
const instr = func.kind.instrs[self.current_frame.instr];
self.current_frame.instr += 1;
const TailCalls = comptime blk: {
var result: [256]fn (self: *Execution, arg: Op.Arg) callconv(.C) void = undefined;
@setEvalBranchQuota(10000);
for (Op.Meta.sparse) |meta| {
const Tail = TailWrap(meta.code);
result[@enumToInt(meta.code)] = Tail.call;
}
break :blk result;
};
return @call(.{ .modifier = .always_tail }, TailCalls[@enumToInt(instr.op)], .{ self, instr.arg });
}
fn tailUnwind(self: *Execution, arg: Op.Arg) callconv(.C) void {
const result = self.unwindCall();
if (self.current_frame.isTerminus()) {
std.debug.assert(self.stack_top == 0);
self.result = result;
return;
} else {
if (result) |res| {
self.push(Op.Fixval, res) catch unreachable;
}
}
return @call(.{ .modifier = .always_inline }, tailDispatch, .{ self, arg });
}
fn TailWrap(comptime opcode: std.wasm.Opcode) type {
const meta = Op.Meta.of(opcode);
return struct {
fn call(ctx: *Execution, arg: Op.Arg) callconv(.C) void {
const pops = ctx.popN(meta.pop.len);
const result = @call(
.{ .modifier = .always_inline },
Op.stepName,
.{ meta.func_name, ctx, arg, pops.ptr },
) catch |err| {
ctx.result = err;
return;
};
if (result) |res| {
ctx.push(@TypeOf(res), res) catch |err| {
ctx.result = err;
return;
};
}
return @call(.{ .modifier = .always_inline }, tailDispatch, .{ ctx, arg });
}
};
}
pub fn getLocal(self: Execution, idx: usize) Op.Fixval {
return self.stack[idx + self.current_frame.locals_begin];
}
pub fn getLocals(self: Execution, idx: usize, len: usize) []Op.Fixval {
return self.stack[idx + self.current_frame.locals_begin ..][0..len];
}
pub fn setLocal(self: Execution, idx: usize, value: Op.Fixval) void {
self.stack[idx + self.current_frame.locals_begin] = value;
}
pub fn getGlobal(self: Execution, idx: usize) Op.Fixval {
return self.instance.globals[idx];
}
pub fn setGlobal(self: Execution, idx: usize, value: Op.Fixval) void {
self.instance.globals[idx] = value;
}
pub fn initCall(self: *Execution, func_id: usize) !void {
const func = self.funcs[func_id];
if (func.kind == .imported) {
// TODO: investigate imported calling another imported
const params = self.popN(func.params.len);
const result = try func.kind.imported.func(self, params);
if (result) |res| {
self.push(Op.Fixval, res) catch unreachable;
}
} else {
const locals_begin = self.stack_top - func.params.len;
for (func.locals) |local| {
// TODO: assert params on the callstack are correct
_ = local;
try self.push(u128, 0);
}
try self.push(Frame, self.current_frame);
self.current_frame = .{
.func = @intCast(u32, func_id),
.instr = 0,
.stack_begin = @intCast(u32, self.stack_top),
.locals_begin = @intCast(u32, locals_begin),
};
}
}
pub fn unwindCall(self: *Execution) ?Op.Fixval {
const func = self.funcs[self.current_frame.func];
const result = if (func.result) |_|
self.pop(Op.Fixval)
else
null;
self.stack_top = self.current_frame.stack_begin;
self.current_frame = self.pop(Frame);
_ = self.popN(func.params.len + func.locals.len);
return result;
}
pub fn jump(self: *Execution, table_idx: ?u32) void {
const meta = self.instance.module.post_process.?.jumps.get(.{
.func = self.current_frame.func,
.instr = self.current_frame.instr - 1,
}).?;
const target = if (table_idx) |idx|
meta.many[idx]
else
meta.one;
const result = if (target.has_value)
self.peek(Op.Fixval)
else
null;
_ = self.popN(target.stack_unroll);
// Jumps to 1 after the target.
// If target == "end", this skips a noop and is faster.
// If target == "else", this correctly skips over the annoying check.
self.current_frame.instr = target.addr + 1;
if (result) |value| {
self.push(Op.Fixval, value) catch unreachable;
}
}
pub fn peek(self: *Execution, comptime T: type) T {
std.debug.assert(@sizeOf(T) == 16);
return @bitCast(T, self.stack[self.stack_top - 1]);
}
pub fn pop(self: *Execution, comptime T: type) T {
std.debug.assert(@sizeOf(T) == 16);
self.stack_top -= 1;
return @bitCast(T, self.stack[self.stack_top]);
}
pub fn popN(self: *Execution, size: usize) []Op.Fixval {
std.debug.assert(self.stack_top + size <= self.stack.len);
self.stack_top -= size;
return self.stack[self.stack_top..][0..size];
}
pub fn push(self: *Execution, comptime T: type, value: T) !void {
std.debug.assert(@sizeOf(T) == 16);
self.stack[self.stack_top] = @bitCast(Op.Fixval, value);
self.stack_top = try std.math.add(usize, self.stack_top, 1);
}
pub fn pushOpaque(self: *Execution, comptime len: usize) !*[len]Op.Fixval {
const start = self.stack_top;
self.stack_top = try std.math.add(usize, len, 1);
return self.stack[start..][0..len];
}
const Frame = extern struct {
func: u32,
instr: u32,
stack_begin: u32,
locals_begin: u32,
pub fn terminus() Frame {
return @bitCast(Frame, @as(u128, 0));
}
pub fn isTerminus(self: Frame) bool {
return @bitCast(u128, self) == 0;
}
}; | src/execution.zig |
const std = @import("std");
const generator = @import("generator");
const Handle = generator.Handle;
const Generator = generator.Generator;
const Map = generator.Map;
pub const io_mode = .evented;
const expect = std.testing.expect;
pub fn main() !void {
try benchDrain();
try benchGeneratorVsCallback();
}
pub fn benchDrain() !void {
std.debug.print("\n=== Benchmark: generator draining\n", .{});
const ty = struct {
n: usize,
pub fn generate(self: *@This(), handle: *Handle(u8)) !u8 {
while (self.n > 0) {
try handle.yield(1);
self.n -= 1;
}
return 3;
}
};
// ensure they behave as expected
const G = Generator(ty, u8);
var g = G.init(ty{ .n = 1 });
try g.drain();
try expect(g.state.Returned == 3);
// measure performance
const bench = @import("bench");
try bench.benchmark(struct {
pub const args = [_]usize{ 1, 2, 3, 5, 10, 100 };
pub const arg_names = [_][]const u8{ "1", "2", "3", "5", "10", "100" };
pub fn return_value(n: usize) !void {
var gen = G.init(ty{ .n = n });
try gen.drain();
try expect(gen.state.Returned == 3);
}
});
}
pub fn benchGeneratorVsCallback() !void {
const W = fn (u8) callconv(.Async) anyerror!void;
const busy_work = struct {
fn do(_: u8) callconv(.Async) !void {
std.os.nanosleep(0, 10);
}
};
const no_work = struct {
fn do(_: u8) callconv(.Async) !void {}
};
_ = no_work;
std.debug.print("\n=== Benchmark: generator vs callback\n", .{});
const ty = struct {
pub fn generate(_: *@This(), handle: *Handle(u8)) !u8 {
try handle.yield(0);
try handle.yield(1);
try handle.yield(2);
return 3;
}
};
const tyc = struct {
pub fn run(_: *@This(), cb: fn (u8) callconv(.Async) anyerror!void) !u8 {
var frame_buffer: [64]u8 align(@alignOf(@Frame(busy_work.do))) = undefined;
var result: anyerror!void = undefined;
suspend {
resume @frame();
}
try await @asyncCall(&frame_buffer, &result, cb, .{0});
suspend {
resume @frame();
}
try await @asyncCall(&frame_buffer, &result, cb, .{1});
suspend {
resume @frame();
}
try await @asyncCall(&frame_buffer, &result, cb, .{2});
return 3;
}
};
// ensure they behave as expected
const G = Generator(ty, u8);
var g = G.init(ty{});
try g.drain();
try expect(g.state.Returned == 3);
// measure performance
const bench = @import("bench");
try bench.benchmark(struct {
pub const args = [_]W{
no_work.do,
busy_work.do,
};
pub const arg_names = [_][]const u8{
"no work",
"busy work",
};
pub fn generator(w: W) !void {
var gen = G.init(ty{});
var frame_buffer: [64]u8 align(@alignOf(@Frame(busy_work.do))) = undefined;
var result: anyerror!void = undefined;
while (try gen.next()) |v| {
try await @asyncCall(&frame_buffer, &result, w, .{v});
}
try expect(gen.state.Returned == 3);
}
pub fn callback(w: W) !void {
var c = tyc{};
try expect((try await async c.run(w)) == 3);
}
});
} | benchmarks.zig |
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
pub fn Frexp(comptime T: type) type {
return struct {
significand: T,
exponent: i32,
};
}
/// Breaks x into a normalized fraction and an integral power of two.
/// f == frac * 2^exp, with |frac| in the interval [0.5, 1).
///
/// Special Cases:
/// - frexp(+-0) = +-0, 0
/// - frexp(+-inf) = +-inf, 0
/// - frexp(nan) = nan, undefined
pub fn frexp(x: anytype) Frexp(@TypeOf(x)) {
const T = @TypeOf(x);
return switch (T) {
f32 => frexp32(x),
f64 => frexp64(x),
f128 => frexp128(x),
else => @compileError("frexp not implemented for " ++ @typeName(T)),
};
}
// TODO: unify all these implementations using generics
fn frexp32(x: f32) Frexp(f32) {
var result: Frexp(f32) = undefined;
var y = @bitCast(u32, x);
const e = @intCast(i32, y >> 23) & 0xFF;
if (e == 0) {
if (x != 0) {
// subnormal
result = frexp32(x * 0x1.0p64);
result.exponent -= 64;
} else {
// frexp(+-0) = (+-0, 0)
result.significand = x;
result.exponent = 0;
}
return result;
} else if (e == 0xFF) {
// frexp(nan) = (nan, undefined)
result.significand = x;
result.exponent = undefined;
// frexp(+-inf) = (+-inf, 0)
if (math.isInf(x)) {
result.exponent = 0;
}
return result;
}
result.exponent = e - 0x7E;
y &= 0x807FFFFF;
y |= 0x3F000000;
result.significand = @bitCast(f32, y);
return result;
}
fn frexp64(x: f64) Frexp(f64) {
var result: Frexp(f64) = undefined;
var y = @bitCast(u64, x);
const e = @intCast(i32, y >> 52) & 0x7FF;
if (e == 0) {
if (x != 0) {
// subnormal
result = frexp64(x * 0x1.0p64);
result.exponent -= 64;
} else {
// frexp(+-0) = (+-0, 0)
result.significand = x;
result.exponent = 0;
}
return result;
} else if (e == 0x7FF) {
// frexp(nan) = (nan, undefined)
result.significand = x;
result.exponent = undefined;
// frexp(+-inf) = (+-inf, 0)
if (math.isInf(x)) {
result.exponent = 0;
}
return result;
}
result.exponent = e - 0x3FE;
y &= 0x800FFFFFFFFFFFFF;
y |= 0x3FE0000000000000;
result.significand = @bitCast(f64, y);
return result;
}
fn frexp128(x: f128) Frexp(f128) {
var result: Frexp(f128) = undefined;
var y = @bitCast(u128, x);
const e = @intCast(i32, y >> 112) & 0x7FFF;
if (e == 0) {
if (x != 0) {
// subnormal
result = frexp128(x * 0x1.0p120);
result.exponent -= 120;
} else {
// frexp(+-0) = (+-0, 0)
result.significand = x;
result.exponent = 0;
}
return result;
} else if (e == 0x7FFF) {
// frexp(nan) = (nan, undefined)
result.significand = x;
result.exponent = undefined;
// frexp(+-inf) = (+-inf, 0)
if (math.isInf(x)) {
result.exponent = 0;
}
return result;
}
result.exponent = e - 0x3FFE;
y &= 0x8000FFFFFFFFFFFFFFFFFFFFFFFFFFFF;
y |= 0x3FFE0000000000000000000000000000;
result.significand = @bitCast(f128, y);
return result;
}
test "type dispatch" {
const a = frexp(@as(f32, 1.3));
const b = frexp32(1.3);
try expect(a.significand == b.significand and a.exponent == b.exponent);
const c = frexp(@as(f64, 1.3));
const d = frexp64(1.3);
try expect(c.significand == d.significand and c.exponent == d.exponent);
const e = frexp(@as(f128, 1.3));
const f = frexp128(1.3);
try expect(e.significand == f.significand and e.exponent == f.exponent);
}
test "32" {
const epsilon = 0.000001;
var r: Frexp(f32) = undefined;
r = frexp32(1.3);
try expect(math.approxEqAbs(f32, r.significand, 0.65, epsilon) and r.exponent == 1);
r = frexp32(78.0234);
try expect(math.approxEqAbs(f32, r.significand, 0.609558, epsilon) and r.exponent == 7);
}
test "64" {
const epsilon = 0.000001;
var r: Frexp(f64) = undefined;
r = frexp64(1.3);
try expect(math.approxEqAbs(f64, r.significand, 0.65, epsilon) and r.exponent == 1);
r = frexp64(78.0234);
try expect(math.approxEqAbs(f64, r.significand, 0.609558, epsilon) and r.exponent == 7);
}
test "128" {
const epsilon = 0.000001;
var r: Frexp(f128) = undefined;
r = frexp128(1.3);
try expect(math.approxEqAbs(f128, r.significand, 0.65, epsilon) and r.exponent == 1);
r = frexp128(78.0234);
try expect(math.approxEqAbs(f128, r.significand, 0.609558, epsilon) and r.exponent == 7);
}
test "32 special" {
var r: Frexp(f32) = undefined;
r = frexp32(0.0);
try expect(r.significand == 0.0 and r.exponent == 0);
r = frexp32(-0.0);
try expect(r.significand == -0.0 and r.exponent == 0);
r = frexp32(math.inf(f32));
try expect(math.isPositiveInf(r.significand) and r.exponent == 0);
r = frexp32(-math.inf(f32));
try expect(math.isNegativeInf(r.significand) and r.exponent == 0);
r = frexp32(math.nan(f32));
try expect(math.isNan(r.significand));
}
test "64 special" {
var r: Frexp(f64) = undefined;
r = frexp64(0.0);
try expect(r.significand == 0.0 and r.exponent == 0);
r = frexp64(-0.0);
try expect(r.significand == -0.0 and r.exponent == 0);
r = frexp64(math.inf(f64));
try expect(math.isPositiveInf(r.significand) and r.exponent == 0);
r = frexp64(-math.inf(f64));
try expect(math.isNegativeInf(r.significand) and r.exponent == 0);
r = frexp64(math.nan(f64));
try expect(math.isNan(r.significand));
}
test "128 special" {
var r: Frexp(f128) = undefined;
r = frexp128(0.0);
try expect(r.significand == 0.0 and r.exponent == 0);
r = frexp128(-0.0);
try expect(r.significand == -0.0 and r.exponent == 0);
r = frexp128(math.inf(f128));
try expect(math.isPositiveInf(r.significand) and r.exponent == 0);
r = frexp128(-math.inf(f128));
try expect(math.isNegativeInf(r.significand) and r.exponent == 0);
r = frexp128(math.nan(f128));
try expect(math.isNan(r.significand));
} | lib/std/math/frexp.zig |
const std = @import("std");
const zupnp = @import("zupnp");
pub fn main() !void {
var lib = try zupnp.ZUPnP.init(std.heap.page_allocator, .{});
defer lib.deinit();
lib.server.static_root_dir = "static";
try lib.server.start();
const zig_png = "/zig.png";
const zig_png_url = try std.fmt.allocPrint(std.heap.page_allocator, "{s}{s}", .{lib.server.base_url, zig_png});
defer std.heap.page_allocator.free(zig_png_url);
var media_server = try lib.device_manager.createDevice(zupnp.upnp.device.MediaServer, .{
.UDN = &try zupnp.util.uuid.generateUuid(),
.friendlyName = "ZUPnP Test",
.manufacturer = "ZUPnP",
.modelName = "Put something fun here",
.iconList = .{
.icon = &.{
.{
.mimetype = "image/png",
.width = 48,
.height = 48,
.depth = 24,
.url = zig_png,
},
},
},
}, {});
const videosId = "1";
const imagesId = "2";
const audioId = "3";
try media_server.content_directory.containers.appendSlice(&.{
.{
.__attributes__ = .{
.id = videosId,
},
.@"dc:title" = "Videos",
.@"upnp:class" = "object.container",
},
.{
.__attributes__ = .{
.id = imagesId,
},
.@"dc:title" = "Images",
.@"upnp:class" = "object.container",
},
.{
.__attributes__ = .{
.id = audioId,
},
.@"dc:title" = "Audio",
.@"upnp:class" = "object.container",
},
});
// TODO all type signatures are required, otherwise compiler crashes
try media_server.content_directory.items.appendSlice(&[_] zupnp.upnp.definition.content_directory.Item {
.{
.__attributes__ = .{
.id = "99",
},
.@"dc:title" = "Zig!",
.@"upnp:class" = "object.item.imageItem.photo",
.res = &[_] zupnp.upnp.definition.content_directory.Res {
.{
.__attributes__ = .{
.protocolInfo = "http-get:*:image/png:*"
},
.__item__ = zig_png_url,
},
},
},
.{
.__attributes__ = .{
.id = "100",
.parentID = videosId,
},
.@"dc:title" = "1MB MP4",
.@"upnp:class" = "object.item.videoItem.movie",
.res = &[_] zupnp.upnp.definition.content_directory.Res {
.{
.__attributes__ = .{
.protocolInfo = "http-get:*:video/mp4:*"
},
.__item__ = "http://172.16.31.10/video123/mp4/720/big_buck_bunny_720p_1mb.mp4",
},
},
},
.{
.__attributes__ = .{
.id = "101",
.parentID = videosId,
},
.@"dc:title" = "1MB FLV",
.@"upnp:class" = "object.item.videoItem.movie",
.res = &[_] zupnp.upnp.definition.content_directory.Res {
.{
.__attributes__ = .{
.protocolInfo = "http-get:*:video/x-flv:*"
},
.__item__ = "http://172.16.31.10/video123/flv/720/big_buck_bunny_720p_1mb.flv",
},
},
},
.{
.__attributes__ = .{
.id = "102",
.parentID = videosId,
},
.@"dc:title" = "1MB MKV",
.@"upnp:class" = "object.item.videoItem.movie",
.res = &[_] zupnp.upnp.definition.content_directory.Res {
.{
.__attributes__ = .{
.protocolInfo = "http-get:*:video/x-matroska:*"
},
.__item__ = "http://172.16.31.10/video123/mkv/720/big_buck_bunny_720p_1mb.mkv",
},
},
},
.{
.__attributes__ = .{
.id = "103",
.parentID = videosId,
},
.@"dc:title" = "1MB 3GP",
.@"upnp:class" = "object.item.videoItem.movie",
.res = &[_] zupnp.upnp.definition.content_directory.Res {
.{
.__attributes__ = .{
.protocolInfo = "http-get:*:video/3gpp:*"
},
.__item__ = "http://172.16.31.10/video123/3gp/240/big_buck_bunny_240p_1mb.3gp",
},
},
},
.{
.__attributes__ = .{
.id = "200",
.parentID = imagesId,
},
.@"dc:title" = "50kB JPG",
.@"upnp:class" = "object.item.imageItem.photo",
.res = &[_] zupnp.upnp.definition.content_directory.Res {
.{
.__attributes__ = .{
.protocolInfo = "http-get:*:image/jpeg:*"
},
.__item__ = "http://172.16.31.10/img/Sample-jpg-image-50kb.jpg",
},
},
},
.{
.__attributes__ = .{
.id = "201",
.parentID = imagesId,
},
.@"dc:title" = "100kB PNG",
.@"upnp:class" = "object.item.imageItem.photo",
.res = &[_] zupnp.upnp.definition.content_directory.Res {
.{
.__attributes__ = .{
.protocolInfo = "http-get:*:image/png:*"
},
.__item__ = "http://172.16.31.10/img/Sample-png-image-100kb.png",
},
},
},
.{
.__attributes__ = .{
.id = "202",
.parentID = imagesId,
},
.@"dc:title" = "40kB GIF",
.@"upnp:class" = "object.item.imageItem.photo",
.res = &[_] zupnp.upnp.definition.content_directory.Res {
.{
.__attributes__ = .{
.protocolInfo = "http-get:*:image/gif:*"
},
.__item__ = "http://172.16.31.10/gif/3.gif",
},
},
},
// .{
// .__attributes__ = .{
// .id = "203",
// .parentID = imagesId,
// },
// .@"dc:title" = "23kB SVG",
// .@"upnp:class" = "object.item.imageItem.photo",
// .res = &[_] zupnp.upnp.definition.content_directory.Res {
// .{
// .__attributes__ = .{
// .protocolInfo = "http-get:*:image/svg+xml:*"
// },
// .__item__ = "http://172.16.31.10/svg/1.svg",
// },
// },
// },
.{
.__attributes__ = .{
.id = "300",
.parentID = audioId,
},
.@"dc:title" = "0.4MB MP3",
.@"upnp:class" = "object.item.audioItem.musicTrack",
.res = &[_] zupnp.upnp.definition.content_directory.Res {
.{
.__attributes__ = .{
.protocolInfo = "http-get:*:audio/mpeg:*"
},
.__item__ = "http://172.16.31.10/audio/mp3/crowd-cheering.mp3",
},
},
},
});
while (true) {
std.time.sleep(1_000_000);
}
} | samples/mediaserver/src/main.zig |
const getty = @import("../../lib.zig");
const std = @import("std");
pub fn Map(
comptime Context: type,
comptime Error: type,
comptime nextKeySeed: @TypeOf(struct {
fn f(_: Context, _: ?std.mem.Allocator, seed: anytype) Error!?@TypeOf(seed).Value {
unreachable;
}
}.f),
comptime nextValueSeed: @TypeOf(struct {
fn f(_: Context, _: ?std.mem.Allocator, seed: anytype) Error!@TypeOf(seed).Value {
unreachable;
}
}.f),
) type {
return struct {
pub const @"getty.de.Map" = struct {
context: Context,
const Self = @This();
pub const Error = Error;
pub fn nextKeySeed(self: Self, allocator: ?std.mem.Allocator, seed: anytype) KeyReturn(@TypeOf(seed)) {
return try nextKeySeed(self.context, allocator, seed);
}
pub fn nextValueSeed(self: Self, allocator: ?std.mem.Allocator, seed: anytype) ValueReturn(@TypeOf(seed)) {
return try nextValueSeed(self.context, allocator, seed);
}
//pub fn nextEntrySeed(self: Self, kseed: anytype, vseed: anytype) Error!?std.meta.Tuple(.{ @TypeOf(kseed).Value, @TypeOf(vseed).Value }) {
//_ = self;
//}
pub fn nextKey(self: Self, allocator: ?std.mem.Allocator, comptime K: type) !?K {
var seed = getty.de.DefaultSeed(K){};
const ds = seed.seed();
return try self.nextKeySeed(allocator, ds);
}
pub fn nextValue(self: Self, allocator: ?std.mem.Allocator, comptime V: type) !V {
var seed = getty.de.DefaultSeed(V){};
const ds = seed.seed();
return try self.nextValueSeed(allocator, ds);
}
//pub fn nextEntry(self: Self, comptime K: type, comptime V: type) !?std.meta.Tuple(.{ K, V }) {
//_ = self;
//}
fn KeyReturn(comptime Seed: type) type {
comptime getty.concepts.@"getty.de.Seed"(Seed);
return Error!?Seed.Value;
}
fn ValueReturn(comptime Seed: type) type {
comptime getty.concepts.@"getty.de.Seed"(Seed);
return Error!Seed.Value;
}
};
pub fn map(self: Context) @"getty.de.Map" {
return .{ .context = self };
}
};
} | src/de/interface/map.zig |
const std = @import("std");
const debug = std.debug;
const mem = std.mem;
const debug_logging: bool = false;
pub fn main() !void {
var allocator = &std.heap.DirectAllocator.init().allocator;
debug.warn("10-1:");
try printMessage(allocator, input_lights);
const result2 = try getTimeOfSmallestBoundingArea(allocator, input_lights);
debug.warn("10-2: {}\n", result2);
}
fn printMessage(allocator: *mem.Allocator, lights: []const Light) !void {
var message_time = try getTimeOfSmallestBoundingArea(allocator, lights);
var lights_prime = try getLightsAtTime(allocator, lights, message_time);
printLights(lights_prime);
}
test "print message" {
var allocator = debug.global_allocator;
try printMessage(allocator, test_lights);
}
fn printLights(lights: []const Light) void {
var bound = getBoundingArea(lights);
debug.warn("\n");
var cursor = bound.nw;
while (cursor.y <= bound.se.y) : (cursor.y += 1) {
cursor.x = bound.nw.x;
while (cursor.x <= bound.se.x) : (cursor.x += 1) {
var light_is_here: bool = false;
for (lights) |l| {
if (V2.equal(l.p, cursor)) {
light_is_here = true;
debug.warn("#");
break;
}
}
if (!light_is_here) {
debug.warn(".");
}
}
debug.warn("\n");
}
debug.warn("\n");
}
/// Caller responsible for freeing returned buffer
fn getLightsAtTime(allocator: *mem.Allocator, lights: []const Light, time: u64) ![]Light {
var lights_prime = try allocator.alloc(Light, lights.len);
mem.copy(Light, lights_prime, lights);
for (lights_prime) |*l| {
l.p = V2.add(l.p, V2.scale(l.v, @intCast(i64, time)));
}
return lights_prime;
}
fn getTimeOfSmallestBoundingArea(allocator: *mem.Allocator, lights: []const Light) !u64 {
var time: u64 = 0;
var area = getBoundingArea(lights).area();
var last_area: isize = 0;
while (true) {
last_area = area;
time += 1;
var lights_prime = try getLightsAtTime(allocator, lights, time);
defer allocator.free(lights_prime);
area = getBoundingArea(lights_prime).area();
if (area > last_area) {
break;
}
}
return time - 1;
}
test "get time of smallest bounding area" {
var allocator = debug.global_allocator;
debug.assert(3 == try getTimeOfSmallestBoundingArea(allocator, test_lights));
}
fn getBoundingArea(lights: []const Light) Rect {
var min = V2.init(@maxValue(i64), @maxValue(i64));
var max = V2.init(@minValue(i64), @minValue(i64));
for (lights) |l| {
if (l.p.x < min.x) {
min.x = l.p.x;
} else if (l.p.x > max.x) {
max.x = l.p.x;
}
if (l.p.y < min.y) {
min.y = l.p.y;
} else if (l.p.y > max.y) {
max.y = l.p.y;
}
}
debug.assert(min.x < max.x);
debug.assert(min.y < max.y);
var area = Rect {
.nw = min,
.se = max,
};
return area;
}
test "get bounding area" {
debug.assert(352 == getBoundingArea(test_lights).area());
}
const Light = struct {
p: V2,
v: V2,
};
const Rect = struct {
nw: V2,
se: V2,
pub fn area(self: Rect) isize {
var xdim = self.se.x - self.nw.x + 1;
var ydim = self.se.y - self.nw.y + 1;
return xdim * ydim;
}
};
const V2 = struct {
x: i64,
y: i64,
pub fn init(_x: i64, _y: i64) V2 {
return V2 {
.x = _x,
.y = _y,
};
}
pub fn equal(self: V2, other: V2) bool {
return (self.x == other.x and self.y == other.y);
}
pub fn add(vec1: V2, vec2: V2) V2 {
return V2.init(vec1.x + vec2.x, vec1.y + vec2.y);
}
pub fn scale(self: V2, scalar: i64) V2 {
return V2.init(self.x * scalar, self.y * scalar);
}
pub fn print(v: V2) void {
logDebug("({}, {})\n", v.x, v.y);
}
};
test "v2 add" {
debug.assert(V2.equal(V2.init(1, 3), V2.add(V2.init(0, 0), V2.init(1, 3))));
debug.assert(V2.equal(V2.init(299, 11), V2.add(V2.init(-23, 14), V2.init(322, -3))));
}
test "v2 scale" {
debug.assert(V2.equal(V2.init(0, 0), V2.init(0, 0).scale(100)));
debug.assert(V2.equal(V2.init(-2400, 3000), V2.init(-24, 30).scale(100)));
debug.assert(V2.equal(V2.init(-1, 1), V2.init(1, -1).scale(-1)));
}
fn logDebug(comptime format_str: []const u8, args: ...) void {
if (debug_logging) {
debug.warn(format_str, args);
}
}
inline fn light(px: i64, py: i64, vx: i64, vy: i64) Light {
return Light {
.p = V2.init(px, py),
.v = V2.init(vx, vy),
};
}
const test_lights = []Light {
light( 9, 1, 0, 2),
light( 7, 0, -1, 0),
light( 3, -2, -1, 1),
light( 6, 10, -2, -1),
light( 2, -4, 2, 2),
light(-6, 10, 2, -2),
light( 1, 8, 1, -1),
light( 1, 7, 1, 0),
light(-3, 11, 1, -2),
light( 7, 6, -1, -1),
light(-2, 3, 1, 0),
light(-4, 3, 2, 0),
light(10, -3, -1, 1),
light( 5, 11, 1, -2),
light( 4, 7, 0, -1),
light( 8, -2, 0, 1),
light(15, 0, -2, 0),
light( 1, 6, 1, 0),
light( 8, 9, 0, -1),
light( 3, 3, -1, 1),
light( 0, 5, 0, -1),
light(-2, 2, 2, 0),
light( 5, -2, 1, 2),
light( 1, 4, 2, 1),
light(-2, 7, 2, -2),
light( 3, 6, -1, -1),
light( 5, 0, 1, 0),
light(-6, 0, 2, 0),
light( 5, 9, 1, -2),
light(14, 7, -2, 0),
light(-3, 6, 2, -1),
};
const input_lights = []Light {
light( 31766, -52454, -3, 5),
light(-52374, -41935, 5, 4),
light( 31758, -31427, -3, 3),
light(-41862, 31671, 4, -3),
light( 10747, -41934, -1, 4),
light( 21267, 42181, -2, -4),
light( 52759, -20913, -5, 2),
light( 31734, 52701, -3, -5),
light(-41823, 31669, 4, -3),
light(-52346, 42184, 5, -4),
light(-20801, -52451, 2, 5),
light( 31760, -20904, -3, 2),
light(-31356, -10397, 3, 1),
light(-41823, -41934, 4, 4),
light( 10724, -10389, -1, 1),
light(-31344, -31427, 3, 3),
light(-41826, 42186, 4, -4),
light(-52393, 42186, 5, -4),
light( 42281, 52698, -4, -5),
light( 10700, -10398, -1, 1),
light( 21259, 31667, -2, -3),
light( 21215, 31662, -2, -3),
light(-10294, 10635, 1, -1),
light( 31734, -10392, -3, 1),
light( 52764, 52698, -5, -5),
light(-52394, 21148, 5, -2),
light(-20809, -31428, 2, 3),
light(-52333, 31666, 5, -3),
light( 31787, -20913, -3, 2),
light( 52776, -10391, -5, 1),
light(-52393, -52449, 5, 5),
light( 31768, 52701, -3, -5),
light( 31734, 21155, -3, -2),
light(-41847, -52455, 4, 5),
light( 21220, 21147, -2, -2),
light( 42273, 10640, -4, -1),
light( 10753, 52696, -1, -5),
light(-10309, -10389, 1, 1),
light( 42241, 21149, -4, -2),
light( 52806, 52701, -5, -5),
light(-20801, 31670, 2, -3),
light( 10720, 21152, -1, -2),
light( 31737, 42181, -3, -4),
light(-31332, -20913, 3, 2),
light(-10321, 52695, 1, -5),
light(-10294, 31664, 1, -3),
light(-10331, -41943, 1, 4),
light( 52788, -10397, -5, 1),
light( 52766, -31428, -5, 3),
light(-31332, -52458, 3, 5),
light(-31356, -20909, 3, 2),
light(-10329, -52453, 1, 5),
light(-31346, -31419, 3, 3),
light( 31787, 10638, -3, -1),
light( 10736, 21152, -1, -2),
light( 21255, -31419, -2, 3),
light(-31308, 31669, 3, -3),
light(-52386, 42186, 5, -4),
light(-10314, -20912, 1, 2),
light( 31766, -41938, -3, 4),
light( 42273, 21149, -4, -2),
light( 21255, -31419, -2, 3),
light(-41860, -41934, 4, 4),
light(-20817, -31421, 2, 3),
light( 21231, 52695, -2, -5),
light(-20793, 21151, 2, -2),
light( 42274, 31671, -4, -3),
light(-31353, 10636, 3, -1),
light( 21235, -41937, -2, 4),
light( 21251, -52452, -2, 5),
light( 42289, -20905, -4, 2),
light( 52766, 31666, -5, -3),
light(-52357, 52701, 5, -5),
light(-52386, -41935, 5, 4),
light( 42260, -20913, -4, 2),
light(-20836, 42180, 2, -4),
light(-52386, 31670, 5, -3),
light( 10757, -10390, -1, 1),
light( 10752, 42183, -1, -4),
light(-52381, 10633, 5, -1),
light(-31332, 31667, 3, -3),
light( 21237, 52701, -2, -5),
light( 10731, -41934, -1, 4),
light( 31787, -31425, -3, 3),
light( 52757, -41943, -5, 4),
light(-52374, 52698, 5, -5),
light(-52338, -52456, 5, 5),
light(-20844, 42178, 2, -4),
light(-20825, -52456, 2, 5),
light(-52367, -10389, 5, 1),
light( 10744, 52697, -1, -5),
light( 10704, -52457, -1, 5),
light( 31766, 42186, -3, -4),
light( 52761, -10390, -5, 1),
light( 31777, -20904, -3, 2),
light(-41818, -41938, 4, 4),
light(-52370, 10637, 5, -1),
light( 21267, 10639, -2, -1),
light(-52382, -10394, 5, 1),
light(-52370, 42180, 5, -4),
light( 21223, -31428, -2, 3),
light(-20845, -20913, 2, 2),
light( 52812, 21148, -5, -2),
light( 42241, -41935, -4, 4),
light( 52814, 52696, -5, -5),
light(-31316, -10398, 3, 1),
light( 52776, 10636, -5, -1),
light(-41823, 21148, 4, -2),
light( 52788, -10391, -5, 1),
light(-52370, 42186, 5, -4),
light( 10721, 52701, -1, -5),
light( 10744, 42185, -1, -4),
light( 21219, -41939, -2, 4),
light(-52378, -52451, 5, 5),
light( 31758, -20911, -3, 2),
light(-31332, 52697, 3, -5),
light(-10329, 31671, 1, -3),
light(-31308, 42179, 3, -4),
light( 31726, -20911, -3, 2),
light( 42275, 52701, -4, -5),
light(-20829, 21149, 2, -2),
light( 10706, 52696, -1, -5),
light(-31312, 52701, 3, -5),
light(-31364, -10397, 3, 1),
light(-41855, 42179, 4, -4),
light(-41823, 31665, 4, -3),
light(-31362, -10389, 3, 1),
light( 42273, -20912, -4, 2),
light( 10700, -52453, -1, 5),
light( 52788, 21149, -5, -2),
light(-10324, -31424, 1, 3),
light(-31356, -31423, 3, 3),
light( 10725, 52701, -1, -5),
light(-52343, 42186, 5, -4),
light(-31324, -31425, 3, 3),
light( 52799, -31419, -5, 3),
light( 10716, -52458, -1, 5),
light(-20849, 10638, 2, -1),
light(-52378, -20905, 5, 2),
light( 52764, -10391, -5, 1),
light( 31726, 10635, -3, -1),
light( 31750, -20907, -3, 2),
light(-31344, 10636, 3, -1),
light(-41839, -10397, 4, 1),
light(-52333, 52701, 5, -5),
light( 52780, -41939, -5, 4),
light( 42242, 10641, -4, -1),
light( 10728, -20909, -1, 2),
light( 52780, -41943, -5, 4),
light( 31766, -41939, -3, 4),
light(-20846, -41934, 2, 4),
light(-31303, 10640, 3, -1),
light( 42282, -41934, -4, 4),
light( 52780, -20907, -5, 2),
light( 31726, -20908, -3, 2),
light(-10310, 31666, 1, -3),
light(-31316, -41940, 3, 4),
light(-20801, 10635, 2, -1),
light(-41859, -10396, 4, 1),
light( 31750, 31669, -3, -3),
light(-52370, 21151, 5, -2),
light(-31312, -52449, 3, 5),
light(-20821, -10389, 2, 1),
light( 10744, 42179, -1, -4),
light( 31766, -20909, -3, 2),
light(-41870, 52692, 4, -5),
light(-52366, 31671, 5, -3),
light(-31364, -41938, 3, 4),
light(-31324, 52700, 3, -5),
light( 42289, -52449, -4, 5),
light(-10298, 21156, 1, -2),
light( 21212, 31662, -2, -3),
light( 10696, -20907, -1, 2),
light( 52776, 52699, -5, -5),
light( 42261, 52697, -4, -5),
light( 21235, -20905, -2, 2),
light(-52334, 42181, 5, -4),
light( 52777, -31428, -5, 3),
light( 10716, 31665, -1, -3),
light( 52817, -41943, -5, 4),
light( 52798, -41934, -5, 4),
light(-52338, 52696, 5, -5),
light(-52338, 42178, 5, -4),
light( 31787, 42186, -3, -4),
light(-31356, -52454, 3, 5),
light( 21259, 31667, -2, -3),
light(-20807, 10641, 2, -1),
light(-31319, 10641, 3, -1),
light( 31746, 31667, -3, -3),
light(-31324, 31671, 3, -3),
light(-10278, -10398, 1, 1),
light(-10286, 42181, 1, -4),
light( 42257, -10390, -4, 1),
light(-52354, 10641, 5, -1),
light(-20845, -31423, 2, 3),
light( 21220, -31424, -2, 3),
light( 21230, -20904, -2, 2),
light(-52392, -41934, 5, 4),
light(-20793, 52694, 2, -5),
light( 10744, -41941, -1, 4),
light( 31758, 42185, -3, -4),
light(-20788, 21149, 2, -2),
light(-52346, -31428, 5, 3),
light( 31729, -20908, -3, 2),
light( 52804, -20909, -5, 2),
light(-20841, 52697, 2, -5),
light(-20820, -41934, 2, 4),
light(-20829, -41936, 2, 4),
light(-52375, 10632, 5, -1),
light(-41874, 42184, 4, -4),
light( 52756, 52700, -5, -5),
light( 42265, 42184, -4, -4),
light(-31364, 31668, 3, -3),
light(-10310, 42178, 1, -4),
light( 10716, -52454, -1, 5),
light( 31774, -41937, -3, 4),
light(-52389, 10638, 5, -1),
light( 31747, 52692, -3, -5),
light(-31316, -52457, 3, 5),
light( 52760, -31423, -5, 3),
light(-31305, 21151, 3, -2),
light( 10736, -31421, -1, 3),
light(-10326, 10634, 1, -1),
light(-41847, -20905, 4, 2),
light(-10286, 31666, 1, -3),
light( 31787, -20906, -3, 2),
light( 42290, -31419, -4, 3),
light( 21223, -10394, -2, 1),
light(-31306, -10394, 3, 1),
light(-20801, 21149, 2, -2),
light( 31753, -52449, -3, 5),
light( 31787, 21151, -3, -2),
light(-10314, 10634, 1, -1),
light( 42284, 21156, -4, -2),
light( 21235, 10632, -2, -1),
light( 21228, 31671, -2, -3),
light(-20825, 21147, 2, -2),
light( 31758, 21153, -3, -2),
light(-31305, -20909, 3, 2),
light( 42241, 42184, -4, -4),
light(-20801, 31663, 2, -3),
light( 52796, -52453, -5, 5),
light(-10334, -31423, 1, 3),
light( 52764, -31425, -5, 3),
light( 10720, -10393, -1, 1),
light(-20844, -31422, 2, 3),
light( 10704, 10635, -1, -1),
light( 42250, 52696, -4, -5),
light(-10273, 52695, 1, -5),
light( 10698, 31662, -1, -3),
light(-10278, 10638, 1, -1),
light( 21211, 52693, -2, -5),
light( 42298, -31424, -4, 3),
light(-10326, 52701, 1, -5),
light( 31760, 31671, -3, -3),
light( 10752, 10641, -1, -1),
light(-10313, -10398, 1, 1),
light(-31311, 31671, 3, -3),
light( 42273, -31422, -4, 3),
light( 10720, 42184, -1, -4),
light(-20845, 31670, 2, -3),
light(-31347, 10641, 3, -1),
light(-10332, 52692, 1, -5),
light(-31332, -31419, 3, 3),
light( 42293, 21156, -4, -2),
light(-31353, 10632, 3, -1),
light(-31316, 52699, 3, -5),
light(-31364, 21149, 3, -2),
light(-10278, 21156, 1, -2),
light( 42302, -31427, -4, 3),
light( 21219, -41942, -2, 4),
light( 31731, 52701, -3, -5),
light( 42241, -20909, -4, 2),
light(-31344, -10397, 3, 1),
light( 42277, -20904, -4, 2),
light(-10274, -41939, 1, 4),
light( 31782, -52450, -3, 5),
light(-41876, 31667, 4, -3),
light( 10749, -20904, -1, 2),
light( 21224, -20911, -2, 2),
light( 31734, 31662, -3, -3),
light( 21231, 10635, -2, -1),
light(-52389, -31419, 5, 3),
light( 31734, -41937, -3, 4),
light( 42257, -20905, -4, 2),
light( 42297, 52697, -4, -5),
light( 52805, 21156, -5, -2),
light( 10709, -20910, -1, 2),
light(-52370, -31420, 5, 3),
light(-10326, 21152, 1, -2),
}; | 2018/day_10.zig |
const std = @import("std");
const Condition = @import("./Condition.zig").Condition;
const ArrayBlockingQueue = @import("./ArrayBlockingQueue.zig").ArrayBlockingQueue;
//const LinkedBlockingQueue = @import("./LinkedBlockingQueue.zig").LinkedBlockingQueue;
const CountDownLatch = @import("./CountDownLatch.zig").CountDownLatch;
const bq = ArrayBlockingQueue(f32);
//const bq = LinkedBlockingQueue(f32);
var end: u32 = 0;
const Param = struct {
queue: *bq,
id: usize,
latch: *CountDownLatch,
rlatch: *CountDownLatch,
};
var result:[16]u32=undefined;
fn example_take(param: Param) !void {
var queue = param.queue;
var id = param.id;
var val:f32=0;
const inf = std.math.inf(f32);
param.rlatch.countDown();
param.latch.wait();
//std.debug.print("{} {} start\n", .{id, std.time.nanoTimestamp()});
var last:f32 =0.0;
var count:u32 = 0;
var dst:[2]f32 = undefined;
var meet_infs:i32 = 0;
while(meet_infs==0){
//last = val;
//val = queue.take();
const items = queue.takeMany(&dst);
//if (val == inf)
for(items)|item|{
if(item == inf)
meet_infs += 1;
if(item != inf){
count += 1;
last = item;
}
}
if(items.len > 500){
//std.debug.print("batch {}\n", .{items.len});
}
//count += 1;
//std.debug.print("{} {} take {d:<25}\n", .{id,std.time.nanoTimestamp() , val});
}
result[id-8]=count;
std.debug.print("{} {} take end={d} actual={} infs={}\n", .{id, std.time.nanoTimestamp(), last, count,meet_infs});
while(meet_infs > 1){
queue.put(std.math.inf(f32));
meet_infs -= 1;
}
}
fn example_poll(param: Param) !void {
var queue = param.queue;
var id = param.id;
var val:?f32=0;
const inf = std.math.inf(f32);
param.rlatch.countDown();
param.latch.wait();
var failed_cnt:u32 = 0;
var last:?f32 =0.0;
var total_cnt:u32 = 0;
var dst:[20]f32 = undefined;
var meet_infs:u32 = 0;
var num: u32 = 0;
while(meet_infs==0){
last = val;
//val = queue.timedPoll(10000);
val = queue.poll();
if (val != null and val.? == inf)
break;
//const items = queue.pollMany(dst[0..]);
//if(items.len > 0){
// for(items)|item|{
// if(item == inf)
// meet_infs += 1;
// if(item != inf){
// last = item;
// }
// }
//} else {
// failed_cnt +=1;
//}
//num += @intCast(u32, items.len);
if(val==null){
failed_cnt +=1;
}
total_cnt += 1;
//std.debug.print("{} {} take {d:<25}\n", .{id,std.time.nanoTimestamp() , val});
}
//result[id-8]=num - meet_infs;
result[id-8]=total_cnt - failed_cnt;
std.debug.print("{} {} poll end={d} try={} failed={} actual={}\n", .{id, std.time.nanoTimestamp(), last, total_cnt,failed_cnt,total_cnt-failed_cnt});
//while(meet_infs > 1){
// queue.put(std.math.inf(f32));
// meet_infs -= 1;
//}
}
fn example_put(param: Param) !void {
var f:i32 = 0;
var queue = param.queue;
var id = param.id;
var succ_cnt:u32 = 0;
param.rlatch.countDown();
param.latch.wait();
//std.debug.print("{} {} start\n", .{id, std.time.nanoTimestamp()});
while(end != 0){
if(f >= 200000){
break;
}
queue.put(@intToFloat(f32, f));
//std.debug.print("{} {} put {d}\n", .{id, std.time.nanoTimestamp() , f});
f = f + 1;
succ_cnt += 1;
//std.time.sleep(700000000);
}
queue.put(std.math.inf(f32));
queue.put(std.math.inf(f32));
std.debug.print("{} {} put end actual={}\n", .{id, std.time.nanoTimestamp(), succ_cnt});
}
fn example_offer(param: Param) !void {
var f:i32 = 0;
var queue = param.queue;
var id = param.id;
param.rlatch.countDown();
param.latch.wait();
var succ_cnt:u32 = 0;
var total_cnt:u32 = 0;
while(end != 0){
if(f >= 200000){
break;
}
//if(queue.offer(@intToFloat(f32, f)) != false){
if(queue.timedOffer(@intToFloat(f32, f), 10) != false){
f = f + 1;
succ_cnt += 1;
}
total_cnt += 1;
}
queue.put(std.math.inf(f32));
queue.put(std.math.inf(f32));
std.debug.print("{} {} offer end try={} failed={} actual={}\n", .{id, std.time.nanoTimestamp(), total_cnt,total_cnt-succ_cnt,succ_cnt});
}
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var mem:[]u8 = arena.allocator.alloc(u8, 100000000) catch unreachable;
var tsfba = std.heap.ThreadSafeFixedBufferAllocator.init(mem);
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var queue = bq.init(&gpa.allocator,10000);
defer queue.deinit();
var a:[24]*std.Thread = undefined;
end = 1;
var latch = CountDownLatch.init(1);
var rlatch = CountDownLatch.init(24);
var param = Param{.queue=&queue, .id=0, .latch=&latch , .rlatch=&rlatch};
for(a[0..4]) |*item|{
item.* = std.Thread.spawn(param, example_put) catch unreachable;
param.id+=1;
}
for(a[4..8]) |*item|{
item.* = std.Thread.spawn(param, example_offer) catch unreachable;
param.id+=1;
}
for(a[8..16]) |*item|{
item.* = std.Thread.spawn(param, example_take) catch unreachable;
param.id+=1;
}
for(a[16..24]) |*item|{
item.* = std.Thread.spawn(param, example_poll) catch unreachable;
param.id+=1;
}
rlatch.wait();
var start = std.time.milliTimestamp();
latch.countDown();
for(a)|item, idx|{
item.wait();
}
var count:u32 = 0;
for(result)|v|{
count += v;
}
std.debug.print("{} {}\n", .{std.time.milliTimestamp() - start, count});
} | example.zig |
const std = @import("std");
const virtual_keys = v: {
@setEvalBranchQuota(100000);
const list = @embedFile("c/vk_list");
var i: usize = 0;
var vks = [_]VirtualKey{std.mem.zeroes(VirtualKey)} ** (std.mem.count(u8, list, "\n") + 1);
var lines = std.mem.split(u8, list, "\n");
while (lines.next()) |line| {
var line_vals = std.mem.split(u8, line, " ");
var symbol = line_vals.next().?;
var value = std.mem.trim(u8, line_vals.next().?, &std.ascii.spaces);
vks[i] = .{ .symbol = symbol, .value = std.fmt.parseInt(u16, value, 10) catch @compileError("bruh") };
i += 1;
}
break :v &vks;
};
pub const VirtualKey = struct {
const Self = @This();
symbol: []const u8,
value: u16,
pub fn fromSymbolic(symbol: []const u8) ?Self {
for (virtual_keys) |v| {
if (std.mem.eql(u8, v.symbol, symbol)) return v;
}
return null;
}
pub fn fromValue(value: u16) ?Self {
for (virtual_keys) |v| {
if (value == v.value) return v;
}
return null;
}
pub fn is(self: Self, symbol: []const u8) bool {
return std.ascii.eqlIgnoreCase(self.symbol, symbol);
}
};
pub const Coords = struct { x: i16, y: i16 };
pub const Rect = struct { left: i16, top: i16, right: i16, bottom: i16 };
pub const ScreenBufferInfo = struct {
size: Coords,
cursor_position: Coords,
attributes: u16,
viewport_rect: Rect,
max_window_size: Coords,
};
pub const InputMode = struct {
enable_echo_input: bool = true,
enable_insert_mode: bool = true,
enable_line_input: bool = true,
enable_mouse_input: bool = true,
enable_processed_input: bool = true,
enable_quick_edit_mode: bool = true,
enable_window_input: bool = false,
enable_virtual_terminal_input: bool = false,
enable_extended_flags: bool = true,
};
pub const OutputMode = struct {
enable_processed_output: bool = true,
enable_wrap_at_eol_output: bool = true,
enable_virtual_terminal_processing: bool = false,
disable_newline_auto_return: bool = false,
enable_lvb_grid_worldwide: bool = false,
};
pub const Key = union(enum) {
ascii: u8,
unicode: u16,
virtual_key: VirtualKey,
unknown: void,
};
pub const ControlKeys = struct {
capslock_on: bool = false,
enhanced_key: bool = false,
left_alt_pressed: bool = false,
left_ctrl_pressed: bool = false,
numlock_on: bool = false,
right_alt_pressed: bool = false,
right_ctrl_pressed: bool = false,
scrolllock_on: bool = false,
shift_pressed: bool = false,
};
pub const KeyEvent = struct {
key: Key,
is_down: bool,
control_keys: ControlKeys,
};
pub const MouseButtons = struct {
left_mouse_button: bool = false,
middle_mouse_button: bool = false,
right_mouse_button: bool = false,
};
pub const MouseFlags = struct {
double_click: bool = false,
mouse_hwheeled: bool = false,
mouse_moved: bool = false,
mouse_wheeled: bool = false,
};
pub const MouseScrollDirection = enum {
up,
down,
left,
right,
};
pub const MouseEvent = struct {
abs_coords: Coords,
mouse_buttons: MouseButtons,
mouse_flags: MouseFlags,
mouse_scroll_direction: ?MouseScrollDirection,
control_keys: ControlKeys,
}; | src/types.zig |
const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem;
const expect = std.testing.expect;
test "@select vectors" {
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
comptime try selectVectors();
try selectVectors();
}
fn selectVectors() !void {
var a = @Vector(4, bool){ true, false, true, false };
var b = @Vector(4, i32){ -1, 4, 999, -31 };
var c = @Vector(4, i32){ -5, 1, 0, 1234 };
var abc = @select(i32, a, b, c);
try expect(abc[0] == -1);
try expect(abc[1] == 1);
try expect(abc[2] == 999);
try expect(abc[3] == 1234);
var x = @Vector(4, bool){ false, false, false, true };
var y = @Vector(4, f32){ 0.001, 33.4, 836, -3381.233 };
var z = @Vector(4, f32){ 0.0, 312.1, -145.9, 9993.55 };
var xyz = @select(f32, x, y, z);
try expect(mem.eql(f32, &@as([4]f32, xyz), &[4]f32{ 0.0, 312.1, -145.9, -3381.233 }));
}
test "@select arrays" {
if (builtin.zig_backend == .stage1) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
comptime try selectArrays();
try selectArrays();
}
fn selectArrays() !void {
var a = [4]bool{ false, true, false, true };
var b = [4]usize{ 0, 1, 2, 3 };
var c = [4]usize{ 4, 5, 6, 7 };
var abc = @select(usize, a, b, c);
try expect(abc[0] == 4);
try expect(abc[1] == 1);
try expect(abc[2] == 6);
try expect(abc[3] == 3);
var x = [4]bool{ false, false, false, true };
var y = [4]f32{ 0.001, 33.4, 836, -3381.233 };
var z = [4]f32{ 0.0, 312.1, -145.9, 9993.55 };
var xyz = @select(f32, x, y, z);
try expect(mem.eql(f32, &@as([4]f32, xyz), &[4]f32{ 0.0, 312.1, -145.9, -3381.233 }));
} | test/behavior/select.zig |
const inputFile = @embedFile("./input/day16.txt");
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Str = []const u8;
const BitSet = std.DynamicBitSet;
const StrMap = std.StringHashMap;
const HashMap = std.HashMap;
const Map = std.AutoHashMap;
const PriorityQueue = std.PriorityQueue;
const assert = std.debug.assert;
const tokenize = std.mem.tokenize;
const print = std.debug.print;
const parseInt = std.fmt.parseInt;
fn sort(comptime T: type, items: []T) void {
std.sort.sort(T, items, {}, comptime std.sort.asc(T));
}
fn println(x: Str) void {
print("{s}\n", .{x});
}
const PacketType = enum(u3) {
Sum,
Product,
Minimum,
Maximum,
Lit,
Greater,
Less,
Equal,
};
const BitStreamWithPos = struct {
stream: std.io.BitReader(.Big, std.io.FixedBufferStream(Str).Reader),
numBitsRead: usize,
};
const ParsePacketResult = struct {
versionSum: usize,
val: usize,
};
/// The packet parsing forms a state machine
/// parsePackets --> parsePacketInner <--------> parseOperator
/// |----------> parseLit
/// TODO write it non recursively
fn parsePackets(input: Input) !ParsePacketResult {
// Zig comes with bit reading built in :)
var buf = std.io.fixedBufferStream(input.items);
var bitStream = .{
.stream = std.io.bitReader(.Big, buf.reader()),
.numBitsRead = 0,
};
// TODO:For fun, trying to write this parser non-recursively
// var parsingState = List(PacketType).init(allocator);
const result = try parsePacketInner(&bitStream);
return result;
}
const PacketParseError = error{PacketIncomplete} || std.io.FixedBufferStream(Str).ReadError;
fn parsePacketInner(bitStream: *BitStreamWithPos) PacketParseError!ParsePacketResult {
var outBits: usize = undefined;
const version = try bitStream.stream.readBits(usize, 3, &outBits);
if (outBits != 3) return error.PacketIncomplete;
bitStream.numBitsRead += outBits;
const typeId: u3 = try bitStream.stream.readBits(u3, 3, &outBits);
if (outBits != 3) return error.PacketIncomplete;
bitStream.numBitsRead += outBits;
const packetType = @intToEnum(PacketType, typeId);
switch (packetType) {
.Lit => {
const val = try parseLit(bitStream);
return ParsePacketResult{ .versionSum = version, .val = val };
},
else => {
const result = try parseOperator(bitStream, packetType);
return ParsePacketResult{ .versionSum = version + result.versionSum, .val = result.val };
},
}
}
const litContinueMask: u5 = 0b10000;
fn parseLit(bitStream: *BitStreamWithPos) !u64 {
var outBits: usize = undefined;
// read 5 at a time until it starts with 0
var result: u64 = 0;
while (true) {
const num = try bitStream.stream.readBits(u5, 5, &outBits);
if (outBits != 5) return error.PacketIncomplete;
bitStream.numBitsRead += outBits;
const isLastBlock = (litContinueMask & num) == 0;
// parse
const data = ~litContinueMask & num;
result = (result << 4) + data;
if (isLastBlock) return result;
}
}
/// So we don't have to allocate memory
const OperatorAccumulator = struct {
type: PacketType,
currVal: ?usize,
const Self = @This();
pub fn init(pktType: PacketType) Self {
return Self{
.type = pktType,
.currVal = null,
};
}
pub fn accumulate(self: *Self, val: usize) void {
if (self.currVal) |curr| {
switch (self.type) {
.Sum => self.currVal = curr + val,
.Product => self.currVal = curr * val,
.Minimum => self.currVal = std.math.min(curr, val),
.Maximum => self.currVal = std.math.max(curr, val),
.Lit => unreachable,
// TODO should find some way to make this panic if given more than two value
.Greater => self.currVal = if (curr > val) 1 else 0,
.Less => self.currVal = if (curr < val) 1 else 0,
.Equal => self.currVal = if (curr == val) 1 else 0,
}
} else {
self.currVal = val;
}
}
};
fn parseOperator(bitStream: *BitStreamWithPos, packetType: PacketType) !ParsePacketResult {
var versionSum: usize = 0;
var accumulator = OperatorAccumulator.init(packetType);
var outBits: usize = undefined;
const lengthTypeId = try bitStream.stream.readBits(u1, 1, &outBits);
if (outBits != 1) return error.PacketIncomplete;
bitStream.numBitsRead += outBits;
if (lengthTypeId == 0) {
// ============= Parse the next 15 bits as a length ================
const len = try bitStream.stream.readBits(u15, 15, &outBits);
if (outBits != 15) return error.PacketIncomplete;
bitStream.numBitsRead += outBits;
const expectedPos = bitStream.numBitsRead + len;
while (bitStream.numBitsRead < expectedPos) {
const result = try parsePacketInner(bitStream);
versionSum += result.versionSum;
accumulator.accumulate(result.val);
}
assert(bitStream.numBitsRead == expectedPos);
} else {
// ============= Parse the next 11 bits as the number of packets succeeding ================
const numPackets = try bitStream.stream.readBits(u11, 11, &outBits);
if (outBits != 11) return error.PacketIncomplete;
bitStream.numBitsRead += outBits;
var i: u11 = 0;
while (i < numPackets) : (i += 1) {
const result = try parsePacketInner(bitStream);
versionSum += result.versionSum;
accumulator.accumulate(result.val);
}
}
return ParsePacketResult{ .versionSum = versionSum, .val = accumulator.currVal.? };
}
pub fn main() !void {
// Standard boilerplate for Aoc problems
const stdout = std.io.getStdOut().writer();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var gpaAllocator = gpa.allocator();
defer assert(!gpa.deinit()); // Check for memory leaks
var arena = std.heap.ArenaAllocator.init(gpaAllocator);
defer arena.deinit();
var allocator = arena.allocator();
const input = try parseInput(inputFile, allocator);
const result = try parsePackets(input);
try stdout.print("Part 1: {d}Part2: {d}\n", .{ result.versionSum, result.val });
}
const Input = struct {
items: Str,
allocator: Allocator,
pub fn deinit(self: @This()) void {
self.allocator.free(self.items);
}
};
fn parseInput(input: Str, allocator: Allocator) !Input {
var inputTrimmed = std.mem.trim(u8, input, "\n");
var items = try allocator.alloc(u8, inputTrimmed.len / 2);
errdefer allocator.free(items);
// Zig comes with this built in :)
items = try std.fmt.hexToBytes(items, inputTrimmed);
return Input{ .items = items, .allocator = allocator };
}
test "Part 1-1" {
var allocator = std.testing.allocator;
const testInput = "38006F45291200";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 9), (try parsePackets(input)).versionSum);
}
test "Part 1-2" {
var allocator = std.testing.allocator;
const testInput = "EE00D40C823060";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 14), (try parsePackets(input)).versionSum);
}
test "Part 1-3" {
var allocator = std.testing.allocator;
const testInput = "8A004A801A8002F478";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 16), (try parsePackets(input)).versionSum);
}
test "Part 1-4" {
var allocator = std.testing.allocator;
const testInput = "620080001611562C8802118E34";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 12), (try parsePackets(input)).versionSum);
}
test "Part 1-5" {
var allocator = std.testing.allocator;
const testInput = "C0015000016115A2E0802F182340";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 23), (try parsePackets(input)).versionSum);
}
test "Part 1-6" {
var allocator = std.testing.allocator;
const testInput = "A0016C880162017C3686B18A3D4780";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 31), (try parsePackets(input)).versionSum);
}
test "Part 2-1" {
var allocator = std.testing.allocator;
const testInput = "C200B40A82";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 3), (try parsePackets(input)).val);
}
test "Part 2-2" {
var allocator = std.testing.allocator;
const testInput = "04005AC33890";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 54), (try parsePackets(input)).val);
}
test "Part 2-3" {
var allocator = std.testing.allocator;
const testInput = "880086C3E88112";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 7), (try parsePackets(input)).val);
}
test "Part 2-4" {
var allocator = std.testing.allocator;
const testInput = "CE00C43D881120";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 9), (try parsePackets(input)).val);
}
test "Part 2-5" {
var allocator = std.testing.allocator;
const testInput = "D8005AC2A8F0";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 1), (try parsePackets(input)).val);
}
test "Part 2-6" {
var allocator = std.testing.allocator;
const testInput = "F600BC2D8F";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 0), (try parsePackets(input)).val);
}
test "Part 2-7" {
var allocator = std.testing.allocator;
const testInput = "9C005AC2F8F0";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 0), (try parsePackets(input)).val);
}
test "Part 2-8" {
var allocator = std.testing.allocator;
const testInput = "9C0141080250320F1802104A08";
const input = try parseInput(testInput, allocator);
defer input.deinit();
try std.testing.expectEqual(@as(usize, 1), (try parsePackets(input)).val);
} | src/day16.zig |
const std = @import("std");
const config = @import("config.zig");
const main = @import("main.zig");
const linux = std.os.linux;
const c = @import("c.zig");
pub fn windowClose(window: u64, arg: config.Arg) void {
var workspace = main.manager.getActiveScreen().getActiveWorkspace();
var win = workspace.getFocusedWindow();
main.xlib.closeWindow(win);
workspace.removeWindow(win);
}
pub fn run(window: u64, arg: config.Arg) void {
//var cmd cmd: []const []const u8
var cmd = arg.StringList;
const rc = linux.fork();
if (rc == 0) {
var allocator = std.heap.page_allocator;
var e = std.ChildProcess.exec(.{
.allocator=allocator,
.argv=cmd,
.cwd=null,
.max_output_bytes=2 * 1024
});
linux.exit(0);
}
}
pub fn notify(window: u64, arg: config.Arg) void {
var msg = arg.String;
var cmd = [_][]const u8{
"notify-send",
"-t",
"2000",
msg,
};
var argToPass = config.Arg{.StringList=&cmd};
run(window, argToPass);
}
pub fn exit(window: u64, arg: config.Arg) void {
main.manager.running = false;
}
pub fn doLayout(window: u64, arg: config.Arg) void {
}
pub fn windowMove(window: u64, arg: config.Arg) void {
// TODO: xlib direcly called maybe move to x.zig
var mouseEvent: c.XEvent = undefined;
// NOTE: have to grab pointer that quering events XMaskEvent will work
var xlib = main.xlib;
_ = c.XGrabPointer(xlib.display, xlib.root, 0, c.ButtonReleaseMask | c.PointerMotionMask, c.GrabModeAsync, c.GrabModeAsync,
0, xlib.cursor, c.CurrentTime);
var maskToQuery = c.ButtonReleaseMask | c.PointerMotionMask | c.ExposureMask | c.SubstructureRedirectMask;
// TODO: find better while construct in zig
_ = c.XMaskEvent(xlib.display, maskToQuery, &mouseEvent);
std.debug.warn("before dragStartPos\n", .{});
var dragStartPos = main.xlib.getPointerPos(window);
std.debug.warn("after dragStartPos {} {}\n", .{dragStartPos[0], dragStartPos[1]});
while (mouseEvent.type != c.ButtonRelease) {
switch (mouseEvent.type) {
c.MotionNotify => {
xlib.move(window,
mouseEvent.xmotion.x - dragStartPos[0],
mouseEvent.xmotion.y - dragStartPos[1]);
},
else => {},
}
_ = c.XMaskEvent(xlib.display, maskToQuery, &mouseEvent);
}
_ = c.XUngrabPointer(xlib.display, c.CurrentTime);
}
pub fn windowNext(window: u64, arg: config.Arg) void {
var workspace = main.manager.getActiveScreen().getActiveWorkspace();
main.windowFocus(workspace.getNextWindow());
}
pub fn windowPrevious(window: u64, arg: config.Arg) void {
var workspace = main.manager.getActiveScreen().getActiveWorkspace();
main.windowFocus(workspace.getPreviousWindow());
}
pub fn workspaceShow(window: u64, arg: config.Arg) void {
var index = arg.UInt;
var screen = main.manager.getActiveScreen();
var workspace = screen.getActiveWorkspace();
for (workspace.windows[0..workspace.amountOfWindows]) |win| {
main.xlib.hideWindow(win);
}
screen.workspaceFocus(index);
workspace = screen.getActiveWorkspace();
main.layouts[main.manager.activeScreenIndex].stack(workspace, &main.xlib);
main.drawBar();
if (workspace.amountOfWindows > 0) {
main.windowFocus(workspace.getFocusedWindow());
} else {
main.xlib.focusWindow(main.xlib.root);
}
}
pub fn workspaceFocusPrevious(window: u64, arg: config.Arg) void {
var screen = main.manager.getActiveScreen();
var a = config.Arg{.UInt=screen.previousWorkspace};
workspaceShow(window, a);
}
pub fn screenSelectByDelta(window: u64, arg: config.Arg) void {
var delta = arg.Int;
var amount: i32 = @intCast(i32, main.manager.amountScreens);
var index: i32 = @intCast(i32, main.manager.activeScreenIndex) + delta;
// TODO: use min and max
if (index < 0) {
index = 0;
} else if (index >= amount) {
index = amount - 1;
}
main.manager.activeScreenIndex = @intCast(u32, index);
var windowToFocus = main.xlib.root;
var screen = main.manager.getActiveScreen();
var workspace = screen.getActiveWorkspace();
if (workspace.amountOfWindows > 0) {
windowToFocus = workspace.getFocusedWindow();
}
main.windowFocus(windowToFocus);
main.xlib.setPointer(screen.info.x + @intCast(i32, @divFloor(screen.info.width, 2)),
screen.info.y + @intCast(i32, @divFloor(screen.info.height, 2)));
main.drawBar();
} | src/commands.zig |
const std = @import("std");
const print = std.debug.print;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day13.txt");
pub fn main() !void {
var timer = try std.time.Timer.start();
const width : u32 = 1500;
var paper = std.StaticBitSet(width * width).initEmpty();
{
var dataAndFolds = std.mem.split(data, "fold along ");
{
var lines = std.mem.tokenize(dataAndFolds.next().?, "\r\n");
while (lines.next()) |line| {
var lineIterator = std.mem.tokenize(line, ",");
const x = try std.fmt.parseInt(u32, lineIterator.next().?, 10);
const y = try std.fmt.parseInt(u32, lineIterator.next().?, 10);
std.debug.assert(x < width);
std.debug.assert(y < width);
paper.set(y * width + x);
}
}
var firstFold = true;
while (dataAndFolds.next()) |fold| {
var lineIterator = std.mem.tokenize(fold, "=\r\n");
const direction = lineIterator.next().?;
const position = try std.fmt.parseInt(u32, lineIterator.next().?, 10);
std.debug.assert(position < width);
var dots = paper.iterator(.{});
if (direction[0] == 'x') {
while (dots.next()) |dot| {
const x = dot % width;
const y = dot / width;
// Skip any dots that lie in the non-folded region.
if (x < position) {
continue;
}
const newX = position - (x - position);
paper.set(y * width + newX);
paper.unset(dot);
}
} else {
while (dots.next()) |dot| {
const x = dot % width;
const y = dot / width;
// Skip any dots that lie in the non-folded region.
if (y < position) {
continue;
}
const newY = position - (y - position);
paper.set(newY * width + x);
paper.unset(dot);
}
}
if (firstFold) {
firstFold = false;
print("🎁 First fold dots: {}\n", .{paper.count()});
print("Day 13 - part 01 took {:15}ns\n", .{timer.lap()});
timer.reset();
}
}
}
// Work out the remaining actual width of the output after the folds.
var xMax : usize = 0;
var yMax : usize = 0;
{
var dots = paper.iterator(.{});
while (dots.next()) |dot| {
const x = dot % width;
const y = dot / width;
if (x > xMax) {
xMax = x;
}
if (y > yMax) {
yMax = y;
}
}
}
// Now we need to work out how to print the code.
var y : usize = 0;
while (y <= yMax) : (y += 1) {
var x : usize = 0;
while (x <= xMax) : (x += 1) {
if (paper.isSet(y * width + x)) {
print("#", .{});
} else {
print(" ", .{});
}
}
print("\n", .{});
}
print("Day 13 - part 02 took {:15}ns\n", .{timer.lap()});
print("❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️\n", .{});
} | src/day13.zig |
const std = @import("std");
const Client = @import("requestz").Client;
pub const Update = struct {
updateId: i64,
chatId: i64,
text: []const u8,
};
const GetUpdatesError = error{
NoMessages
};
pub fn main() anyerror!void {
try runEchoBot();
}
pub fn runEchoBot() anyerror!void {
var buffer: [94]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buffer);
const token_allocator = fba.allocator();
const token = try getToken(token_allocator);
defer token_allocator.free(token);
var updateId: i64 = undefined;
while (true) {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var client = try Client.init(allocator);
defer client.deinit();
defer std.time.sleep(1e+10);
var update = try getUpdates(allocator, client, token);
defer allocator.free(update.text);
var newUpdateId = update.updateId;
if (updateId == newUpdateId) {
continue;
}
updateId = newUpdateId;
try sendMessage(allocator, client, token, update);
}
}
pub fn getToken(allocator: std.mem.Allocator) ![]u8 {
const file = try std.fs.cwd().openFile(
"token.txt",
.{ .mode = .read_only }
);
defer file.close();
const token_length = 46;
const token_file = try file.reader().readAllAlloc(
allocator,
token_length+1, //The last character should be ignored
);
defer allocator.free(token_file);
const token = allocator.dupe(u8, token_file[0..token_length]);
return token;
}
pub fn getUpdates(allocator: std.mem.Allocator, client: Client, token: []u8) !Update {
const methodName = "getUpdates?offset=-1";
const telegramUrlTemplate = "https://api.telegram.org/bot{s}/" ++ methodName;
const telegramUrl = try std.fmt.allocPrint(allocator, telegramUrlTemplate, .{ token });
var response = try client.get(telegramUrl, .{});
var tree = try response.json();
defer tree.deinit();
var result = tree.root.Object.get("result").?;
if (result.Array.items.len < 1) {
return GetUpdatesError.NoMessages;
}
var lastIndex = result.Array.items.len - 1;
var updateId = result.Array.items[0].Object.get("update_id").?.Integer;
var message = result.Array.items[lastIndex].Object.get("message").?;
var text = message.Object.get("text").?;
var chat = message.Object.get("chat").?;
var chatId = chat.Object.get("id").?;
return Update{
.updateId = updateId,
.chatId = chatId.Integer,
.text = try allocator.dupe(u8, text.String),
};
}
pub fn sendMessage(allocator: std.mem.Allocator, client: Client, token: []u8, update: Update) !void {
const messageMethod = "sendMessage";
const sendMessageUrlTemplate = "https://api.telegram.org/bot{s}/" ++ messageMethod;
const sendMessageUrl = try std.fmt.allocPrint(allocator, sendMessageUrlTemplate, .{ token });
const rawJson = \\ {{ "chat_id": {d}, "text": "{s}" }}
;
const echoResponseJsonString = try std.fmt.allocPrint(allocator, rawJson, .{ update.chatId, update.text });
const echoComplete = try std.fmt.allocPrint(allocator, "{s}", .{echoResponseJsonString});
defer allocator.free(echoResponseJsonString);
var headers = .{.{ "Content-Type", "application/json" }};
std.debug.print("\n echoComplete: {s}\n", .{echoComplete});
var response1 = try client.post(sendMessageUrl, .{ .content = echoComplete, .headers = headers });
defer response1.deinit();
std.debug.print("\n{s}\n", .{response1.body});
} | src/main.zig |
const std = @import("std");
const exec = @import("../../buildutil/exec.zig");
const config = @import("../../config/config.zig");
const Copernicus = @import("../copernicus/build.zig");
const Arch = if (@hasField(std.builtin, "Arch")) std.builtin.Arch else std.Target.Cpu.Arch;
pub fn buildKernel(params: struct {
builder: *std.build.Builder,
arch: Arch,
boot_proto: []const u8 = "stivale2",
}) !*std.build.LibExeObjStep {
const arch = params.arch;
const proto = params.boot_proto;
const flork_path = "subprojects/flork/";
const kernel_filename = params.builder.fmt("Flork_{s}_{s}", .{ proto, @tagName(arch) });
const main_file = params.builder.fmt(flork_path ++ "src/boot/{s}.zig", .{proto});
// For some reason if I define this directly in exec.makeExec param struct, it will
// contain incorrect values. ZIG BUG
const blob = .{
.global_source_path = flork_path ++ "/src",
.source_blob_name = kernel_filename,
};
const kernel = exec.makeExec(.{
.builder = params.builder,
.arch = arch,
.ctx = .kernel,
.filename = kernel_filename,
.main = main_file,
.source_blob = if (config.kernel.build_source_blob)
blob
else
null,
.mode = config.kernel.build_mode,
.strip_symbols = config.kernel.strip_symbols,
});
const copernicus = try Copernicus.buildCopernicus(.{
.builder = params.builder,
.arch = params.arch,
});
kernel.addBuildOption([]const u8, "copernicus_path", copernicus.output_path);
kernel.step.dependOn(&copernicus.step);
kernel.addAssemblyFile(params.builder.fmt(flork_path ++ "src/boot/{s}_{s}.S", .{
proto,
@tagName(arch),
}));
kernel.setLinkerScriptPath(.{ .path = flork_path ++ "src/kernel/kernel.ld" });
const laipath = flork_path ++ "src/extern/lai/";
kernel.addIncludeDir(laipath ++ "include/");
const laiflags = &[_][]const u8{"-std=c99"};
kernel.addCSourceFile(laipath ++ "core/error.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/eval.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/exec-operand.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/exec.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/libc.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/ns.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/object.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/opregion.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/os_methods.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/variable.c", laiflags);
kernel.addCSourceFile(laipath ++ "core/vsnprintf.c", laiflags);
kernel.addCSourceFile(laipath ++ "drivers/ec.c", laiflags);
kernel.addCSourceFile(laipath ++ "drivers/timer.c", laiflags);
if (arch == .x86_64)
kernel.addCSourceFile(laipath ++ "helpers/pc-bios.c", laiflags);
kernel.addCSourceFile(laipath ++ "helpers/pci.c", laiflags);
kernel.addCSourceFile(laipath ++ "helpers/pm.c", laiflags);
kernel.addCSourceFile(laipath ++ "helpers/resource.c", laiflags);
kernel.addCSourceFile(laipath ++ "helpers/sci.c", laiflags);
switch (params.arch) {
.x86_64 => { // Worse boot protocol, have to do pic
kernel.pie = true;
kernel.force_pic = true;
},
else => {},
}
return kernel;
} | subprojects/flork/build.zig |
const std = @import("std");
const testing = std.testing;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Public API:
/// Serializes the given `value: T` into the `stream`.
/// - `stream` is a instance of `std.io.Writer`
/// - `T` is the type to serialize
/// - `value` is the instance to serialize.
pub fn serialize(stream: anytype, comptime T: type, value: T) @TypeOf(stream).Error!void {
comptime validateTopLevelType(T);
const type_hash = comptime computeTypeHash(T);
try stream.writeAll(&type_hash);
try serializeRecursive(stream, T, @as(T, value)); // use @as() to coerce to non-tuple type
}
/// Deserializes a value of type `T` from the `stream`.
/// - `stream` is a instance of `std.io.Reader`
/// - `T` is the type to deserialize
pub fn deserialize(stream: anytype, comptime T: type) (@TypeOf(stream).Error || error{ UnexpectedData, EndOfStream })!T {
comptime validateTopLevelType(T);
if (comptime requiresAllocationForDeserialize(T))
@compileError(@typeName(T) ++ " requires allocation to be deserialized. Use deserializeAlloc instead of deserialize!");
return deserializeInternal(stream, T, null) catch |err| switch (err) {
error.OutOfMemory => unreachable,
else => |e| return e,
};
}
/// Deserializes a value of type `T` from the `stream`.
/// - `stream` is a instance of `std.io.Reader`
/// - `T` is the type to deserialize
/// - `allocator` is an allocator require to allocate slices and pointers.
/// Result must be freed by using `free()`.
pub fn deserializeAlloc(stream: anytype, comptime T: type, allocator: std.mem.Allocator) (@TypeOf(stream).Error || error{ UnexpectedData, OutOfMemory, EndOfStream })!T {
comptime validateTopLevelType(T);
return try deserializeInternal(stream, T, allocator);
}
/// Releases all memory allocated by `deserializeAlloc`.
/// - `allocator` is the allocator passed to `deserializeAlloc`.
/// - `T` is the type that was passed to `deserializeAlloc`.
/// - `value` is the value that was returned by `deserializeAlloc`.
pub fn free(allocator: std.mem.Allocator, comptime T: type, value: *T) void {
recursiveFree(allocator, T, value);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Implementation:
fn serializeRecursive(stream: anytype, comptime T: type, value: T) @TypeOf(stream).Error!void {
switch (@typeInfo(T)) {
// Primitive types:
.Void => {}, // no data
.Bool => try stream.writeByte(@boolToInt(value)),
.Float => switch (T) {
f16 => try stream.writeIntLittle(u16, @bitCast(u16, value)),
f32 => try stream.writeIntLittle(u32, @bitCast(u32, value)),
f64 => try stream.writeIntLittle(u64, @bitCast(u64, value)),
f80 => try stream.writeIntLittle(u80, @bitCast(u80, value)),
f128 => try stream.writeIntLittle(u128, @bitCast(u128, value)),
else => unreachable,
},
.Int => {
if (T == usize) {
try stream.writeIntLittle(u64, value);
} else {
try stream.writeIntLittle(T, value);
}
},
.Pointer => |ptr| {
if (ptr.sentinel != null) @compileError("Sentinels are not supported yet!");
switch (ptr.size) {
.One => try serializeRecursive(stream, ptr.child, value.*),
.Slice => {
try stream.writeIntLittle(u64, value.len);
for (value) |item| {
try serializeRecursive(stream, ptr.child, item);
}
},
.C => unreachable,
.Many => unreachable,
}
},
.Array => |arr| {
for (value) |item| {
try serializeRecursive(stream, arr.child, item);
}
if (arr.sentinel != null) @compileError("Sentinels are not supported yet!");
},
.Struct => |str| {
// we can safely ignore the struct layout here as we will serialize the data by field order,
// instead of memory representation
inline for (str.fields) |fld| {
try serializeRecursive(stream, fld.field_type, @field(value, fld.name));
}
},
.Optional => |opt| {
if (value) |item| {
try stream.writeIntLittle(u8, 1);
try serializeRecursive(stream, opt.child, item);
} else {
try stream.writeIntLittle(u8, 0);
}
},
.ErrorUnion => |eu| {
if (value) |item| {
try stream.writeIntLittle(u8, 1);
try serializeRecursive(stream, eu.payload, item);
} else |item| {
try stream.writeIntLittle(u8, 0);
try serializeRecursive(stream, eu.error_set, item);
}
},
.ErrorSet => {
// Error unions are serialized by "index of sorted name", so we
// hash all names in the right order
const names = getSortedErrorNames(T);
const index = for (names) |name, i| {
if (std.mem.eql(u8, name, @errorName(value)))
break @intCast(u16, i);
} else unreachable;
try stream.writeIntLittle(u16, index);
},
.Enum => |list| {
const Tag = if (list.tag_type == usize) u64 else list.tag_type;
try stream.writeIntLittle(Tag, @enumToInt(value));
},
.Union => |un| {
const Tag = un.tag_type orelse @compileError("Untagged unions are not supported!");
const active_tag = std.meta.activeTag(value);
try serializeRecursive(stream, Tag, active_tag);
inline for (std.meta.fields(T)) |fld| {
if (@field(Tag, fld.name) == active_tag) {
try serializeRecursive(stream, fld.field_type, @field(value, fld.name));
}
}
},
.Vector => |vec| {
var array: [vec.len]vec.child = value;
try serializeRecursive(stream, @TypeOf(array), array);
},
// Unsupported types:
.NoReturn,
.Type,
.ComptimeFloat,
.ComptimeInt,
.Undefined,
.Null,
.Fn,
.BoundFn,
.Opaque,
.Frame,
.AnyFrame,
.EnumLiteral,
=> unreachable,
}
}
fn deserializeInternal(stream: anytype, comptime T: type, allocator: ?std.mem.Allocator) (@TypeOf(stream).Error || error{ UnexpectedData, OutOfMemory, EndOfStream })!T {
const type_hash = comptime computeTypeHash(T);
var ref_hash: [type_hash.len]u8 = undefined;
try stream.readNoEof(&ref_hash);
if (!std.mem.eql(u8, &type_hash, &ref_hash))
return error.UnexpectedData;
var result: T = undefined;
try recursiveDeserialize(stream, T, allocator, &result);
return result;
}
fn readIntLittleAny(stream: anytype, comptime T: type) !T {
const BiggerInt = std.meta.Int(@typeInfo(T).Int.signedness, 8 * @as(usize, ((@bitSizeOf(T) + 7)) / 8));
return @truncate(T, try stream.readIntLittle(BiggerInt));
}
fn recursiveDeserialize(stream: anytype, comptime T: type, allocator: ?std.mem.Allocator, target: *T) (@TypeOf(stream).Error || error{ UnexpectedData, OutOfMemory, EndOfStream })!void {
switch (@typeInfo(T)) {
// Primitive types:
.Void => target.* = {},
.Bool => target.* = (try stream.readByte()) != 0,
.Float => target.* = @bitCast(T, switch (T) {
f16 => try stream.readIntLittle(u16),
f32 => try stream.readIntLittle(u32),
f64 => try stream.readIntLittle(u64),
f80 => try stream.readIntLittle(u80),
f128 => try stream.readIntLittle(u128),
else => unreachable,
}),
.Int => target.* = if (T == usize)
std.math.cast(usize, try stream.readIntLittle(u64)) catch return error.UnexpectedData
else
try readIntLittleAny(stream, T),
.Pointer => |ptr| {
if (ptr.sentinel != null) @compileError("Sentinels are not supported yet!");
switch (ptr.size) {
.One => {
const pointer = try allocator.?.create(ptr.child);
errdefer allocator.?.destroy(pointer);
try recursiveDeserialize(stream, ptr.child, allocator, pointer);
target.* = pointer;
},
.Slice => {
const length = std.math.cast(usize, try stream.readIntLittle(u64)) catch return error.UnexpectedData;
const slice = try allocator.?.alloc(ptr.child, length);
errdefer allocator.?.free(slice);
for (slice) |*item| {
try recursiveDeserialize(stream, ptr.child, allocator, item);
}
target.* = slice;
},
.C => unreachable,
.Many => unreachable,
}
},
.Array => |arr| {
for (target.*) |*item| {
try recursiveDeserialize(stream, arr.child, allocator, item);
}
},
.Struct => |str| {
// we can safely ignore the struct layout here as we will serialize the data by field order,
// instead of memory representation
inline for (str.fields) |fld| {
try recursiveDeserialize(stream, fld.field_type, allocator, &@field(target.*, fld.name));
}
},
.Optional => |opt| {
const is_set = try stream.readIntLittle(u8);
if (is_set != 0) {
target.* = @as(opt.child, undefined);
try recursiveDeserialize(stream, opt.child, allocator, &target.*.?);
} else {
target.* = null;
}
},
.ErrorUnion => |eu| {
const is_value = try stream.readIntLittle(u8);
if (is_value != 0) {
var value: eu.payload = undefined;
try recursiveDeserialize(stream, eu.payload, allocator, &value);
target.* = value;
} else {
var err: eu.error_set = undefined;
try recursiveDeserialize(stream, eu.error_set, allocator, &err);
target.* = err;
}
},
.ErrorSet => {
// Error unions are serialized by "index of sorted name", so we
// hash all names in the right order
const names = comptime getSortedErrorNames(T);
const index = try stream.readIntLittle(u16);
inline for (names) |name, i| {
if (i == index) {
target.* = @field(T, name);
return;
}
}
return error.UnexpectedData;
},
.Enum => |list| {
const Tag = if (list.tag_type == usize) u64 else list.tag_type;
const tag_value = try readIntLittleAny(stream, Tag);
if (list.is_exhaustive) {
target.* = std.meta.intToEnum(T, tag_value) catch return error.UnexpectedData;
} else {
target.* = @intToEnum(T, tag_value);
}
},
.Union => |un| {
const Tag = un.tag_type orelse @compileError("Untagged unions are not supported!");
var active_tag: Tag = undefined;
try recursiveDeserialize(stream, Tag, allocator, &active_tag);
inline for (std.meta.fields(T)) |fld| {
if (@field(Tag, fld.name) == active_tag) {
var union_value: fld.field_type = undefined;
try recursiveDeserialize(stream, fld.field_type, allocator, &union_value);
target.* = @unionInit(T, fld.name, union_value);
return;
}
}
return error.UnexpectedData;
},
.Vector => |vec| {
var array: [vec.len]vec.child = undefined;
try recursiveDeserialize(stream, @TypeOf(array), allocator, &array);
target.* = array;
},
// Unsupported types:
.NoReturn,
.Type,
.ComptimeFloat,
.ComptimeInt,
.Undefined,
.Null,
.Fn,
.BoundFn,
.Opaque,
.Frame,
.AnyFrame,
.EnumLiteral,
=> unreachable,
}
}
fn makeMutableSlice(comptime T: type, slice: []const T) []T {
if (slice.len == 0) {
var buf: [0]T = .{};
return &buf;
} else {
return @intToPtr([*]T, @ptrToInt(slice.ptr))[0..slice.len];
}
}
fn makeMutablePtr(comptime T: type, ptr: *const T) *T {
return @intToPtr(*T, @ptrToInt(ptr));
}
fn recursiveFree(allocator: std.mem.Allocator, comptime T: type, value: *T) void {
switch (@typeInfo(T)) {
// Non-allocating primitives:
.Void, .Bool, .Float, .Int, .ErrorSet, .Enum => {},
// Composite types:
.Pointer => |ptr| {
switch (ptr.size) {
.One => {
const mut_ptr = makeMutablePtr(ptr.child, value.*);
recursiveFree(allocator, ptr.child, mut_ptr);
allocator.destroy(mut_ptr);
},
.Slice => {
const mut_slice = makeMutableSlice(ptr.child, value.*);
for (mut_slice) |*item| {
recursiveFree(allocator, ptr.child, item);
}
allocator.free(mut_slice);
},
.C => unreachable,
.Many => unreachable,
}
},
.Array => |arr| {
for (value.*) |*item| {
recursiveFree(allocator, arr.child, item);
}
},
.Struct => |str| {
// we can safely ignore the struct layout here as we will serialize the data by field order,
// instead of memory representation
inline for (str.fields) |fld| {
recursiveFree(allocator, fld.field_type, &@field(value.*, fld.name));
}
},
.Optional => |opt| {
if (value.*) |*item| {
recursiveFree(allocator, opt.child, item);
}
},
.ErrorUnion => |eu| {
if (value.*) |*item| {
recursiveFree(allocator, eu.payload, item);
} else |_| {
// errors aren't meant to be freed
}
},
.Union => |un| {
const Tag = un.tag_type orelse @compileError("Untagged unions are not supported!");
var active_tag: Tag = value.*;
inline for (std.meta.fields(T)) |fld| {
if (@field(Tag, fld.name) == active_tag) {
recursiveFree(allocator, fld.field_type, &@field(value.*, fld.name));
return;
}
}
},
.Vector => |vec| {
var array: [vec.len]vec.child = value.*;
for (array) |*item| {
recursiveFree(allocator, vec.child, item);
}
},
// Unsupported types:
.NoReturn,
.Type,
.ComptimeFloat,
.ComptimeInt,
.Undefined,
.Null,
.Fn,
.BoundFn,
.Opaque,
.Frame,
.AnyFrame,
.EnumLiteral,
=> unreachable,
}
}
/// Returns `true` if `T` requires allocation to be deserialized.
fn requiresAllocationForDeserialize(comptime T: type) bool {
switch (@typeInfo(T)) {
.Pointer => return true,
.Struct, .Union => {
inline for (comptime std.meta.fields(T)) |fld| {
if (requiresAllocationForDeserialize(fld.field_type)) {
return true;
}
}
return false;
},
.ErrorUnion => |eu| return requiresAllocationForDeserialize(eu.payload),
else => return false,
}
}
const TypeHashFn = std.hash.Fnv1a_64;
fn intToLittleEndianBytes(val: anytype) [@sizeOf(@TypeOf(val))]u8 {
var res: [@sizeOf(@TypeOf(val))]u8 = undefined;
std.mem.writeIntLittle(@TypeOf(val), &res, val);
return res;
}
/// Computes a unique type hash from `T` to identify deserializing invalid data.
/// Incorporates field order and field type, but not field names, so only checks for structural equivalence.
/// Compile errors on unsupported or comptime types.
fn computeTypeHash(comptime T: type) [8]u8 {
var hasher = TypeHashFn.init();
computeTypeHashInternal(&hasher, T);
return intToLittleEndianBytes(hasher.final());
}
fn getSortedErrorNames(comptime T: type) []const []const u8 {
comptime {
const error_set = @typeInfo(T).ErrorSet orelse @compileError("Cannot serialize anyerror");
var sorted_names: [error_set.len][]const u8 = undefined;
for (error_set) |err, i| {
sorted_names[i] = err.name;
}
std.sort.sort([]const u8, &sorted_names, {}, struct {
fn order(ctx: void, lhs: []const u8, rhs: []const u8) bool {
_ = ctx;
return (std.mem.order(u8, lhs, rhs) == .lt);
}
}.order);
return &sorted_names;
}
}
fn getSortedEnumNames(comptime T: type) []const []const u8 {
comptime {
const type_info = @typeInfo(T).Enum;
if (type_info.layout != .Auto) @compileError("Only automatically tagged enums require sorting!");
var sorted_names: [type_info.fields.len][]const u8 = undefined;
for (type_info.fields) |err, i| {
sorted_names[i] = err.name;
}
std.sort.sort([]const u8, &sorted_names, {}, struct {
fn order(ctx: void, lhs: []const u8, rhs: []const u8) bool {
_ = ctx;
return (std.mem.order(u8, lhs, rhs) == .lt);
}
}.order);
return &sorted_names;
}
}
fn computeTypeHashInternal(hasher: *TypeHashFn, comptime T: type) void {
@setEvalBranchQuota(10_000);
switch (@typeInfo(T)) {
// Primitive types:
.Void,
.Bool,
.Float,
=> hasher.update(@typeName(T)),
.Int => {
if (T == usize) {
// special case: usize can differ between platforms, this
// format uses u64 internally.
hasher.update(@typeName(u64));
} else {
hasher.update(@typeName(T));
}
},
.Pointer => |ptr| {
if (ptr.is_volatile) @compileError("Serializing volatile pointers is most likely a mistake.");
if (ptr.sentinel != null) @compileError("Sentinels are not supported yet!");
switch (ptr.size) {
.One => {
hasher.update("pointer");
computeTypeHashInternal(hasher, ptr.child);
},
.Slice => {
hasher.update("slice");
computeTypeHashInternal(hasher, ptr.child);
},
.C => @compileError("C-pointers are not supported"),
.Many => @compileError("Many-pointers are not supported"),
}
},
.Array => |arr| {
hasher.update(&intToLittleEndianBytes(@as(u64, arr.len)));
computeTypeHashInternal(hasher, arr.child);
if (arr.sentinel != null) @compileError("Sentinels are not supported yet!");
},
.Struct => |str| {
// we can safely ignore the struct layout here as we will serialize the data by field order,
// instead of memory representation
// add some generic marker to the hash so emtpy structs get
// added as information
hasher.update("struct");
for (str.fields) |fld| {
if (fld.is_comptime) @compileError("comptime fields are not supported.");
computeTypeHashInternal(hasher, fld.field_type);
}
},
.Optional => |opt| {
hasher.update("optional");
computeTypeHashInternal(hasher, opt.child);
},
.ErrorUnion => |eu| {
hasher.update("error union");
computeTypeHashInternal(hasher, eu.error_set);
computeTypeHashInternal(hasher, eu.payload);
},
.ErrorSet => {
// Error unions are serialized by "index of sorted name", so we
// hash all names in the right order
hasher.update("error set");
const names = getSortedErrorNames(T);
for (names) |name| {
hasher.update(name);
}
},
.Enum => |list| {
const Tag = if (list.tag_type == usize)
u64
else if (list.tag_type == isize)
i64
else
list.tag_type;
if (list.is_exhaustive) {
// Exhaustive enums only allow certain values, so we
// tag them via the value type
hasher.update("enum.exhaustive");
computeTypeHashInternal(hasher, Tag);
const names = getSortedEnumNames(T);
inline for (names) |name| {
hasher.update(name);
hasher.update(&intToLittleEndianBytes(@as(Tag, @enumToInt(@field(T, name)))));
}
} else {
// Non-exhaustive enums are basically integers. Treat them as such.
hasher.update("enum.non-exhaustive");
computeTypeHashInternal(hasher, Tag);
}
},
.Union => |un| {
const tag = un.tag_type orelse @compileError("Untagged unions are not supported!");
hasher.update("union");
computeTypeHashInternal(hasher, tag);
for (un.fields) |fld| {
computeTypeHashInternal(hasher, fld.field_type);
}
},
.Vector => |vec| {
hasher.update("vector");
hasher.update(&intToLittleEndianBytes(@as(u64, vec.len)));
computeTypeHashInternal(hasher, vec.child);
},
// Unsupported types:
.NoReturn,
.Type,
.ComptimeFloat,
.ComptimeInt,
.Undefined,
.Null,
.Fn,
.BoundFn,
.Opaque,
.Frame,
.AnyFrame,
.EnumLiteral,
=> @compileError("Unsupported type " ++ @typeName(T)),
}
}
fn validateTopLevelType(comptime T: type) void {
switch (@typeInfo(T)) {
// Unsupported top level types:
.ErrorSet,
.ErrorUnion,
=> @compileError("Unsupported top level type " ++ @typeName(T) ++ ". Wrap into struct to serialize these."),
else => {},
}
}
fn testSameHash(comptime T1: type, comptime T2: type) void {
const hash_1 = comptime computeTypeHash(T1);
const hash_2 = comptime computeTypeHash(T2);
if (comptime !std.mem.eql(u8, &hash_1, &hash_2))
@compileError("The computed hash for " ++ @typeName(T1) ++ " and " ++ @typeName(T2) ++ " does not match.");
}
test "type hasher basics" {
testSameHash(void, void);
testSameHash(bool, bool);
testSameHash(u1, u1);
testSameHash(u32, u32);
testSameHash(f32, f32);
testSameHash(f64, f64);
testSameHash(std.meta.Vector(4, u32), std.meta.Vector(4, u32));
testSameHash(usize, u64);
testSameHash([]const u8, []const u8);
testSameHash([]const u8, []u8);
testSameHash([]const u8, []u8);
testSameHash(?*struct { a: f32, b: u16 }, ?*const struct { hello: f32, lol: u16 });
testSameHash(enum { a, b, c }, enum { a, b, c });
testSameHash(enum(u8) { a, b, c }, enum(u8) { a, b, c });
testSameHash(enum(u8) { a, b, c, _ }, enum(u8) { c, b, a, _ });
testSameHash(enum(u8) { a = 1, b = 6, c = 9 }, enum(u8) { a = 1, b = 6, c = 9 });
testSameHash(enum(usize) { a, b, c }, enum(u64) { a, b, c });
testSameHash(enum(isize) { a, b, c }, enum(i64) { a, b, c });
testSameHash([5]std.meta.Vector(4, u32), [5]std.meta.Vector(4, u32));
testSameHash(union(enum) { a: u32, b: f32 }, union(enum) { a: u32, b: f32 });
testSameHash(error{ Foo, Bar }, error{ Foo, Bar });
testSameHash(error{ Foo, Bar }, error{ Bar, Foo });
testSameHash(error{ Foo, Bar }!void, error{ Bar, Foo }!void);
}
fn testSerialize(comptime T: type, value: T) !void {
var data = std.ArrayList(u8).init(std.testing.allocator);
defer data.deinit();
try serialize(data.writer(), T, value);
}
test "serialize basics" {
try testSerialize(void, {});
try testSerialize(bool, false);
try testSerialize(bool, true);
try testSerialize(u1, 0);
try testSerialize(u1, 1);
try testSerialize(u8, 0xFF);
try testSerialize(u32, 0xDEADBEEF);
try testSerialize(usize, 0xDEADBEEF);
try testSerialize(f16, std.math.pi);
try testSerialize(f32, std.math.pi);
try testSerialize(f64, std.math.pi);
try testSerialize(f80, std.math.pi);
try testSerialize(f128, std.math.pi);
try testSerialize([3]u8, "hi!".*);
try testSerialize([]const u8, "Hello, World!");
try testSerialize(*const [3]u8, "foo");
try testSerialize(enum { a, b, c }, .a);
try testSerialize(enum { a, b, c }, .b);
try testSerialize(enum { a, b, c }, .c);
try testSerialize(enum(u8) { a, b, c }, .a);
try testSerialize(enum(u8) { a, b, c }, .b);
try testSerialize(enum(u8) { a, b, c }, .c);
try testSerialize(enum(isize) { a, b, c }, .a);
try testSerialize(enum(isize) { a, b, c }, .b);
try testSerialize(enum(isize) { a, b, c }, .c);
try testSerialize(enum(usize) { a, b, c }, .a);
try testSerialize(enum(usize) { a, b, c }, .b);
try testSerialize(enum(usize) { a, b, c }, .c);
const TestEnum = enum(u8) { a, b, c, _ };
try testSerialize(TestEnum, .a);
try testSerialize(TestEnum, .b);
try testSerialize(TestEnum, .c);
try testSerialize(TestEnum, @intToEnum(TestEnum, 0xB1));
try testSerialize(struct { val: error{ Foo, Bar } }, .{ .val = error.Foo });
try testSerialize(struct { val: error{ Bar, Foo } }, .{ .val = error.Bar });
try testSerialize(struct { val: error{ Bar, Foo }!u32 }, .{ .val = error.Bar });
try testSerialize(struct { val: error{ Bar, Foo }!u32 }, .{ .val = 0xFF });
try testSerialize(union(enum) { a: f32, b: u32 }, .{ .a = 1.5 });
try testSerialize(union(enum) { a: f32, b: u32 }, .{ .b = 2.0 });
try testSerialize(?u32, null);
try testSerialize(?u32, 143);
}
fn testSerDesAlloc(comptime T: type, value: T) !void {
var data = std.ArrayList(u8).init(std.testing.allocator);
defer data.deinit();
try serialize(data.writer(), T, value);
var stream = std.io.fixedBufferStream(data.items);
var deserialized = try deserializeAlloc(stream.reader(), T, std.testing.allocator);
defer free(std.testing.allocator, T, &deserialized);
try std.testing.expectEqual(value, deserialized);
}
fn testSerDesPtrContentEquality(comptime T: type, value: T) !void {
var data = std.ArrayList(u8).init(std.testing.allocator);
defer data.deinit();
try serialize(data.writer(), T, value);
var stream = std.io.fixedBufferStream(data.items);
var deserialized = try deserializeAlloc(stream.reader(), T, std.testing.allocator);
defer free(std.testing.allocator, T, &deserialized);
try std.testing.expectEqual(value.*, deserialized.*);
}
fn testSerDesSliceContentEquality(comptime T: type, value: T) !void {
var data = std.ArrayList(u8).init(std.testing.allocator);
defer data.deinit();
try serialize(data.writer(), T, value);
var stream = std.io.fixedBufferStream(data.items);
var deserialized = try deserializeAlloc(stream.reader(), T, std.testing.allocator);
defer free(std.testing.allocator, T, &deserialized);
try std.testing.expectEqualSlices(std.meta.Child(T), value, deserialized);
}
test "ser/des" {
try testSerDesAlloc(void, {});
try testSerDesAlloc(bool, false);
try testSerDesAlloc(bool, true);
try testSerDesAlloc(u1, 0);
try testSerDesAlloc(u1, 1);
try testSerDesAlloc(u8, 0xFF);
try testSerDesAlloc(u32, 0xDEADBEEF);
try testSerDesAlloc(usize, 0xDEADBEEF);
try testSerDesAlloc(f16, std.math.pi);
try testSerDesAlloc(f32, std.math.pi);
try testSerDesAlloc(f64, std.math.pi);
try testSerDesAlloc(f80, std.math.pi);
try testSerDesAlloc(f128, std.math.pi);
try testSerDesAlloc([3]u8, "hi!".*);
try testSerDesSliceContentEquality([]const u8, "Hello, World!");
try testSerDesPtrContentEquality(*const [3]u8, "foo");
try testSerDesAlloc(enum { a, b, c }, .a);
try testSerDesAlloc(enum { a, b, c }, .b);
try testSerDesAlloc(enum { a, b, c }, .c);
try testSerDesAlloc(enum(u8) { a, b, c }, .a);
try testSerDesAlloc(enum(u8) { a, b, c }, .b);
try testSerDesAlloc(enum(u8) { a, b, c }, .c);
try testSerDesAlloc(enum(usize) { a, b, c }, .a);
try testSerDesAlloc(enum(usize) { a, b, c }, .b);
try testSerDesAlloc(enum(usize) { a, b, c }, .c);
try testSerDesAlloc(enum(isize) { a, b, c }, .a);
try testSerDesAlloc(enum(isize) { a, b, c }, .b);
try testSerDesAlloc(enum(isize) { a, b, c }, .c);
const TestEnum = enum(u8) { a, b, c, _ };
try testSerDesAlloc(TestEnum, .a);
try testSerDesAlloc(TestEnum, .b);
try testSerDesAlloc(TestEnum, .c);
try testSerDesAlloc(TestEnum, @intToEnum(TestEnum, 0xB1));
try testSerDesAlloc(struct { val: error{ Foo, Bar } }, .{ .val = error.Foo });
try testSerDesAlloc(struct { val: error{ Bar, Foo } }, .{ .val = error.Bar });
try testSerDesAlloc(struct { val: error{ Bar, Foo }!u32 }, .{ .val = error.Bar });
try testSerDesAlloc(struct { val: error{ Bar, Foo }!u32 }, .{ .val = 0xFF });
try testSerDesAlloc(union(enum) { a: f32, b: u32 }, .{ .a = 1.5 });
try testSerDesAlloc(union(enum) { a: f32, b: u32 }, .{ .b = 2.0 });
try testSerDesAlloc(?u32, null);
try testSerDesAlloc(?u32, 143);
} | s2s.zig |
const std = @import("std");
const expect = std.testing.expect;
const test_allocator = std.testing.allocator;
const Allocator = std.mem.Allocator;
const Syntax = struct {
const Self = @This();
allocator: Allocator,
lines: [][]const u8,
pub fn load(allocator: Allocator, str: []const u8) !Self {
var lines = std.ArrayList([]const u8).init(allocator);
defer lines.deinit();
var iter = std.mem.split(u8, str, "\n");
while (iter.next()) |line| {
if (line.len != 0) {
const trimmed = std.mem.trimRight(u8, line, "\n");
try lines.append(trimmed);
}
}
return Self{ .allocator = allocator, .lines = lines.toOwnedSlice() };
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.lines);
}
fn lineScore(self: Self, str: []const u8) !i64 {
var stack = std.ArrayList(u8).init(self.allocator);
defer stack.deinit();
for (str) |c| {
switch (c) {
'(' => {
try stack.append(')');
},
'[' => {
try stack.append(']');
},
'{' => {
try stack.append('}');
},
'<' => {
try stack.append('>');
},
')' => {
const v = stack.pop();
if (v != ')') return 3;
},
']' => {
const v = stack.pop();
if (v != ']') return 57;
},
'}' => {
const v = stack.pop();
if (v != '}') return 1197;
},
'>' => {
const v = stack.pop();
if (v != '>') return 25137;
},
else => unreachable,
}
}
return 0;
}
pub fn syntaxErrorScore(self: Self) !i64 {
var total: i64 = 0;
for (self.lines) |line| {
total += try self.lineScore(line);
}
return total;
}
fn completionScore(self: Self, str: []const u8) !?i64 {
var stack = std.ArrayList(u8).init(self.allocator);
defer stack.deinit();
for (str) |c| {
switch (c) {
'(' => {
try stack.append(')');
},
'[' => {
try stack.append(']');
},
'{' => {
try stack.append('}');
},
'<' => {
try stack.append('>');
},
')' => {
const v = stack.pop();
if (v != ')') return null;
},
']' => {
const v = stack.pop();
if (v != ']') return null;
},
'}' => {
const v = stack.pop();
if (v != '}') return null;
},
'>' => {
const v = stack.pop();
if (v != '>') return null;
},
else => unreachable,
}
}
var total: i64 = 0;
while (stack.items.len != 0) {
const v = stack.pop();
var s: i64 = 0;
s = switch (v) {
')' => 1,
']' => 2,
'}' => 3,
'>' => 4,
else => unreachable,
};
total = (total * 5) + s;
}
return total;
}
pub fn middleCompletionScore(self: Self) !i64 {
var scores = std.ArrayList(i64).init(self.allocator);
defer scores.deinit();
for (self.lines) |line| {
var s = try self.completionScore(line);
if (s != null) {
try scores.append(s.?);
}
}
std.sort.sort(i64, scores.items, {}, comptime std.sort.asc(i64));
const idx = (scores.items.len / 2);
return scores.items[idx];
}
};
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const str = @embedFile("../input.txt");
var s = try Syntax.load(allocator, str);
defer s.deinit();
const stdout = std.io.getStdOut().writer();
const part1 = try s.syntaxErrorScore();
try stdout.print("Part 1: {d}\n", .{part1});
const part2 = try s.middleCompletionScore();
try stdout.print("Part 2: {d}\n", .{part2});
}
test "part1 test" {
const str = @embedFile("../test.txt");
var s = try Syntax.load(test_allocator, str);
defer s.deinit();
const score = try s.syntaxErrorScore();
std.debug.print("\nScore={d}\n", .{score});
try expect(26397 == score);
}
test "part2 test" {
const str = @embedFile("../test.txt");
var s = try Syntax.load(test_allocator, str);
defer s.deinit();
const score = try s.middleCompletionScore();
std.debug.print("\nScore={d}\n", .{score});
try expect(288957 == score);
} | day10/src/main.zig |
const std = @import("std");
const pow = std.math.pow;
const Vector = std.meta.Vector;
const Random = std.rand.Random;
const zm = @import("zmath");
const Ray = @import("ray.zig").Ray;
const Hit = @import("ray.zig").Hit;
const ScatteredRay = @import("ray.zig").ScatteredRay;
fn randomInUnitSphere(rng: Random) Vector(4, f32) {
while (true) {
var vec = Vector(4, f32){ (rng.float(f32) - 0.5) * 2.0, (rng.float(f32) - 0.5) * 2.0, (rng.float(f32) - 0.5) * 2.0, 0 };
if (zm.lengthSq3(vec)[0] >= 1.0) continue;
return zm.normalize3(vec);
}
}
fn randomInUnitHemisphere(rng: Random, normal: Vector(4, f32)) Vector(4, f32) {
var inUnitSphere = randomInUnitSphere(rng);
if (zm.dot3(inUnitSphere, normal)[0] <= 0.0) {
return -inUnitSphere;
}
return inUnitSphere;
}
pub const Material = struct {
scatterFn: fn (*const Material, *const Hit, Ray, Random) ScatteredRay,
pub fn scatter(self: *const Material, hit: *const Hit, r: Ray, rng: Random) ScatteredRay {
return self.scatterFn(self, hit, r, rng);
}
};
pub const LambertianMat = struct {
color: Vector(3, f32),
material: Material,
pub fn init(color: Vector(3, f32)) LambertianMat {
return LambertianMat{ .color = color, .material = Material{ .scatterFn = scatter } };
}
pub fn scatter(material: *const Material, hit: *const Hit, _: Ray, rng: Random) ScatteredRay {
const self = @fieldParentPtr(LambertianMat, "material", material);
var newDir = hit.location + hit.normal + randomInUnitHemisphere(rng, hit.normal);
var scatteredRay = Ray{ .origin = hit.location, .dir = zm.normalize3(newDir) };
return ScatteredRay{ .ray = scatteredRay, .attenuation = self.color };
}
};
fn reflect(vec: Vector(4, f32), normal: Vector(4, f32)) Vector(4, f32) {
var a = 2.0 * zm.dot3(vec, normal)[0];
return vec - normal * @splat(4, a);
}
pub const MetalMat = struct {
color: Vector(3, f32),
roughness: f32,
material: Material,
pub fn init(color: Vector(3, f32), roughness: f32) MetalMat {
return MetalMat{ .color = color, .roughness = roughness, .material = Material{ .scatterFn = scatter } };
}
pub fn scatter(material: *const Material, hit: *const Hit, r: Ray, rng: Random) ScatteredRay {
const self = @fieldParentPtr(MetalMat, "material", material);
var newDir = reflect(r.dir, hit.normal) + @splat(4, self.roughness) * randomInUnitSphere(rng);
var scatteredRay = Ray{ .origin = hit.location, .dir = zm.normalize3(newDir) };
return ScatteredRay{ .ray = scatteredRay, .attenuation = self.color };
}
};
fn refract(vec: Vector(4, f32), normal: Vector(4, f32), refractionRatio: f32) Vector(4, f32) {
var cosTheta = zm.dot3(-vec, normal)[0];
if (cosTheta > 1.0) {
cosTheta = 1.0;
}
var a = @splat(4, refractionRatio) * (vec + (@splat(4, cosTheta) * normal));
var b = normal * -@splat(4, @sqrt(@fabs(1.0 - zm.lengthSq3(a)[0])));
return a + b;
}
pub const DielectricMat = struct {
color: Vector(3, f32),
refractionIndex: f32,
material: Material,
pub fn init(color: Vector(3, f32), refractionIndex: f32) DielectricMat {
return DielectricMat{ .color = color, .refractionIndex = refractionIndex, .material = Material{ .scatterFn = scatter } };
}
fn reflectance(cos: f32, refractionIndex: f32) f32 {
// Shlick's approximation
var r0 = (1.0 - refractionIndex) / (1.0 + refractionIndex);
r0 = r0 * r0;
return r0 + (1.0 - r0) * pow(f32, 1.0 - cos, 5.0);
}
pub fn scatter(material: *const Material, hit: *const Hit, r: Ray, rng: Random) ScatteredRay {
const self = @fieldParentPtr(DielectricMat, "material", material);
var refractionIndex = self.refractionIndex;
if (hit.hitFrontFace) {
refractionIndex = 1.0 / self.refractionIndex;
}
var cosTheta = zm.dot3(-r.dir, hit.normal)[0];
if (cosTheta > 1.0) {
cosTheta = 1.0;
}
var sinTheta = @sqrt(1.0 - cosTheta * cosTheta);
var newDir: Vector(4, f32) = undefined;
var cannotRefract = (refractionIndex * sinTheta) > 1.0;
if (cannotRefract or reflectance(cosTheta, refractionIndex) > rng.float(f32)) {
newDir = reflect(r.dir, hit.normal);
} else {
newDir = refract(r.dir, hit.normal, refractionIndex);
}
var scatteredRay = Ray{ .origin = hit.location, .dir = zm.normalize3(newDir) };
return ScatteredRay{ .ray = scatteredRay, .attenuation = self.color };
}
}; | src/materials.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const stdout = std.io.getStdOut().writer();
const stderr = std.io.getStdErr().writer();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
const States = enum {
initial,
maybeStartTagBlock,
scanningTag,
maybeEndTagBlock,
};
const State = union(States) {
initial: void,
maybeStartTagBlock: void,
scanningTag: usize,
maybeEndTagBlock: usize,
};
const Range = struct {
start: usize,
end: usize,
pub fn init(start: usize, end: usize) Range {
return .{ .start = start, .end = end };
}
};
fn scanContexts(contents: []const u8) ![]Range {
const file = contents;
var tags = std.ArrayList(Range).init(allocator);
var cur: usize = 0;
var state = State{ .initial = undefined };
while (cur < file.len) {
var c = file[cur];
cur += 1;
// TODO: Allow numbers!
switch (c) {
'\n' => {
switch (state) {
.initial => {},
.maybeStartTagBlock => {
state = State{ .initial = undefined };
},
.scanningTag => {
state = State{ .initial = undefined };
},
.maybeEndTagBlock => |v| {
try tags.append(Range.init(v, cur - 2));
state = State{ .initial = undefined };
},
}
},
':' => {
switch (state) {
.initial => {
state = State{ .maybeStartTagBlock = undefined };
},
.maybeStartTagBlock => {},
.scanningTag => |v| {
state = State{ .maybeEndTagBlock = v };
},
.maybeEndTagBlock => {},
}
},
'a'...'z', 'A'...'Z', '-', '_' => {
switch (state) {
.initial => {},
.maybeStartTagBlock => {
state = State{ .scanningTag = cur - 1 };
},
.scanningTag => {},
.maybeEndTagBlock => |v| {
try tags.append(Range.init(v, cur - 2));
state = State{ .scanningTag = cur - 1 };
},
}
},
else => {
// TODO: add case of numbers here?J
switch (state) {
.initial => {},
.maybeStartTagBlock => {
state = State{ .initial = undefined };
},
.scanningTag => {
// tar syntax error; abort!
state = State{ .initial = undefined };
},
.maybeEndTagBlock => |v| {
try tags.append(Range.init(v, cur - 2));
state = State{ .initial = undefined };
},
}
},
}
}
return tags.items;
}
fn scanContextsForFile(filename: []const u8) !void {
const file = try std.fs.cwd().readFileAlloc(allocator, filename, 1024 * 1024 * 1024);
var items = try scanContexts(file);
for (items) |range| {
try stdout.print("{s}\n", .{file[range.start..range.end]});
}
}
pub fn getNextArg(it: anytype) ![]u8 {
if (it.next(allocator)) |arg| {
var str = try arg;
return str;
} else {
return error.NoArg;
}
}
fn usage() !void {
try stderr.writeAll("Usage: cabined-scan [mode] [filename]\n\n");
try stderr.writeAll("Available modes: \n");
try stderr.writeAll("\ttags\n");
try stderr.writeAll("\tcontexts\n");
}
pub fn main() anyerror!void {
defer arena.deinit();
var argsIt = std.process.args();
_ = argsIt.skip();
var mode = getNextArg(&argsIt) catch {
try usage();
std.os.exit(1);
};
var filename = getNextArg(&argsIt) catch {
try usage();
std.os.exit(1);
};
if (std.mem.eql(u8, mode, "tags")) {
try stderr.writeAll("Not implemented yet!\n");
std.os.exit(1);
} else if (std.mem.eql(u8, mode, "contexts")) {
try scanContextsForFile(filename);
} else {
try usage();
std.os.exit(1);
}
}
const expect = std.testing.expect;
test "scanContexts" {
// TODO: this fails for ":tag:tag:tag:"
var text = " :tag:tag:tag: ";
var items = try scanContexts(text);
std.log.info("{}", .{items.len});
try expect(items.len == 3);
} | src/main.zig |
const std = @import("std");
const helper = @import("helper.zig");
const Allocator = std.mem.Allocator;
const HashMap = std.AutoHashMap;
const input = @embedFile("../inputs/day21.txt");
pub fn run(alloc: Allocator, stdout_: anytype) !void {
const nums = try parseInput(input);
const res1 = part1(nums);
const res2 = try part2(alloc, nums);
if (stdout_) |stdout| {
try stdout.print("Part 1: {}\n", .{res1});
try stdout.print("Part 2: {}\n", .{res2});
}
}
fn parseInput(inp: []const u8) ![2]i32 {
var tokens = tokenize(u8, inp, " \r\n");
var nums: [2]i32 = undefined;
for (nums) |*num| {
_ = tokens.next();
_ = tokens.next();
_ = tokens.next();
_ = tokens.next();
num.* = try parseInt(i32, tokens.next().?, 10);
}
return nums;
}
fn part1(nums: [2]i32) i32 {
var game = Game.init(nums[0], nums[1]);
while (game.players[0].score < 1000 and game.players[1].score < 1000) {
game.advance();
}
return game.players[game.turn].score * game.die.rolls;
}
const Game = struct {
die: Die,
players: [2]Player,
turn: usize = 0,
pub fn init(player1: i32, player2: i32) @This() {
return .{
.die = .{},
.players = .{
.{ .current_space = player1 },
.{ .current_space = player2 },
},
};
}
pub fn advance(self: *@This()) void {
const player = &self.players[self.turn];
player.advance(&self.die);
self.turn = 1 - self.turn;
}
};
const Die = struct {
current_face: i32 = 1,
rolls: i32 = 0,
pub fn roll(self: *@This()) i32 {
self.rolls += 1;
defer {
self.current_face = @mod(self.current_face + 1 - 1, 100) + 1;
}
return self.current_face;
}
};
const Player = struct {
current_space: i32,
score: i32 = 0,
pub fn advance(self: *@This(), die: *Die) void {
var sum: i32 = 0;
var i: usize = 0;
while (i < 3) : (i += 1) {
sum += die.roll();
}
self.advanceNum(sum);
}
pub fn advanceNum(self: *@This(), num: i32) void {
self.current_space = @mod(self.current_space + num - 1, 10) + 1;
self.score += self.current_space;
}
};
const RollValue = struct { value: i32, times: i32 };
const dice_roll_values: [7]RollValue = .{
RollValue{ .value = 3, .times = 1 },
RollValue{ .value = 4, .times = 3 },
RollValue{ .value = 5, .times = 6 },
RollValue{ .value = 6, .times = 7 },
RollValue{ .value = 7, .times = 6 },
RollValue{ .value = 8, .times = 3 },
RollValue{ .value = 9, .times = 1 },
}; // precalculated
const UMap = HashMap([2]Player, i64);
fn part2(alloc: Allocator, nums: [2]i32) !i64 {
var qgame = try QGame.init(alloc, nums);
defer qgame.deinit();
while (qgame.universes.count() > 0) {
try qgame.advance();
}
return std.math.max(qgame.wins[0], qgame.wins[1]);
}
const QGame = struct {
universes: UMap,
buffer: UMap,
wins: [2]i64,
turn: usize = 0,
pub fn init(alloc: Allocator, nums: [2]i32) !@This() {
var universes = UMap.init(alloc);
try universes.ensureTotalCapacity(10 * 10 * 21 * 21); // number of possible universes, ~44k
var buffer = UMap.init(alloc);
try buffer.ensureTotalCapacity(10 * 10 * 21 * 21);
try universes.put(.{
.{ .current_space = nums[0] },
.{ .current_space = nums[1] },
}, 1);
return @This(){
.universes = universes,
.buffer = buffer,
.wins = .{ 0, 0 },
};
}
pub fn advance(self: *@This()) !void {
self.buffer.clearRetainingCapacity();
var entries = self.universes.iterator();
while (entries.next()) |entry| {
for (dice_roll_values) |rollvalue| {
var key = entry.key_ptr.*;
key[self.turn].advanceNum(rollvalue.value);
const num = rollvalue.times * entry.value_ptr.*;
if (key[self.turn].score >= 21) {
self.wins[self.turn] += num;
} else {
var newentry = try self.buffer.getOrPutValue(key, 0);
newentry.value_ptr.* += num;
}
}
}
self.turn = 1 - self.turn;
std.mem.swap(UMap, &self.universes, &self.buffer);
}
pub fn deinit(self: *@This()) void {
self.universes.deinit();
self.buffer.deinit();
}
};
const eql = std.mem.eql;
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const count = std.mem.count;
const parseUnsigned = std.fmt.parseUnsigned;
const parseInt = std.fmt.parseInt;
const sort = std.sort.sort; | src/day21.zig |
const std = @import("std");
const fs = std.fs;
const ROWS: usize = 12;
const COLS: usize = 12;
const MIMG_ROWS = ROWS * (10 - 2);
const MIMG_COLS = COLS * (10 - 2);
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
const input = try fs.cwd().readFileAlloc(allocator, "data/input_20_1.txt", std.math.maxInt(usize));
var imgs = std.ArrayList(Image).init(allocator);
defer imgs.deinit();
{
var lines = std.mem.tokenize(input, "\n");
var img = Image{};
var li: usize = 0;
while (lines.next()) |raw_line| {
const line = std.mem.trim(u8, raw_line, " \r\n");
if (line.len == 0) {
try imgs.append(img);
continue;
}
if (std.mem.indexOf(u8, line, "Tile ")) |_| {
const id = std.mem.trim(u8, line["Tile ".len..], " :\r\n");
img.id = try std.fmt.parseInt(usize, id, 10);
li = 0;
}
else {
std.mem.copy(u8, img.data[li][0..], line);
li += 1;
}
}
if (li != 0)
try imgs.append(img);
}
var matrix: [ROWS][COLS]?Image = undefined;
for (matrix) |row, ri| {
for (row) |img, ii| {
matrix[ri][ii] = null;
}
}
{ // Find conrner
for (imgs.items) |img_i, index| {
var matched_side = [4]Side{Side.top, Side.top, Side.top, Side.top};
var matched_count: usize = 0;
for (imgs.items) |img_j| {
if (img_i.id == img_j.id) continue;
if (img_i.findMatch(&img_j)) |side| {
matched_side[matched_count] = side;
matched_count += 1;
}
}
if (matched_count == 2) {
switch (matched_side[0]) {
Side.top => {
switch (matched_side[1]) {
Side.right => { matrix[0][0] = img_i; },
Side.left => { matrix[0][0] = flipImageHorizontally(img_i); },
else => unreachable
}
},
Side.right => {
switch (matched_side[1]) {
Side.bottom => { matrix[0][0] = img_i; },
Side.top => { matrix[0][0] = flipImageVertically(img_i); },
else => unreachable
}
},
Side.bottom => {
switch (matched_side[1]) {
Side.right => { matrix[0][0] = img_i; },
Side.left => { matrix[0][0] = flipImageHorizontally(img_i); },
else => unreachable
}
},
Side.left => {
switch (matched_side[1]) {
Side.bottom => { matrix[0][0] = flipImageHorizontally(img_i); },
Side.top => { matrix[0][0] = rotateImage(img_i, 180); },
else => unreachable
}
}
}
imgs.items[index] = imgs.items[imgs.items.len - 1];
try imgs.resize(imgs.items.len - 1);
break;
}
}
}
{ // Insert all the other elements in the matrix
var y: usize = 0; while (y < ROWS) : (y += 1) {
var x: usize = 0; while (x < COLS) : (x += 1) {
if (x == 0 and y == 0) continue;
var index: usize = imgs.items.len;
var match_img: ?Image = null;
for (imgs.items) |img, img_index| {
if (x > 0) {
var match_left = matrix[y][x - 1].?.getCol(9)[0..];
if (eql(match_left, img.getCol(0)[0..])) {
match_img = img;
}
else if (eqlTranspose(match_left, img.getCol(0)[0..])) {
match_img = flipImageVertically(img);
}
else if (eqlTranspose(match_left, img.getRow(0)[0..])) {
match_img = rotateImage(img, 270);
}
else if (eql(match_left, img.getRow(0)[0..])) {
match_img = flipImageVertically(rotateImage(img, 270));
}
else if (eqlTranspose(match_left, img.getCol(9)[0..])) {
match_img = rotateImage(img, 180);
}
else if (eql(match_left, img.getCol(9)[0..])) {
match_img = flipImageHorizontally(img);
}
else if (eql(match_left, img.getRow(9)[0..])) {
match_img = rotateImage(img, 90);
}
else if (eqlTranspose(match_left, img.getRow(9)[0..])) {
match_img = flipImageVertically(rotateImage(img, 90));
}
if (match_img) |m| {
std.debug.assert(y == 0 or eql(matrix[y - 1][x].?.getRow(9)[0..], m.getRow(0)[0..]));
std.debug.assert(eql(match_left, m.getCol(0)[0..]));
index = img_index;
break;
}
}
else if (y > 0) {
var match_top = matrix[y - 1][x].?.getRow(9)[0..];
if (img_index == 47 and x == 0 and y == 4) {
var xxx: u32 = 32;
xxx = xxx;
}
if (eql(match_top, img.getRow(0)[0..])) {
match_img = img;
}
else if (eqlTranspose(match_top, img.getRow(0)[0..])) {
match_img = flipImageHorizontally(img);
}
else if (eql(match_top, img.getCol(0)[0..])) {
match_img = flipImageHorizontally(rotateImage(img, 90));
}
else if (eqlTranspose(match_top, img.getCol(0)[0..])) {
match_img = rotateImage(img, 90);
}
else if (eqlTranspose(match_top, img.getRow(9)[0..])) {
match_img = rotateImage(img, 180);
}
else if (eql(match_top, img.getRow(9)[0..])) {
match_img = flipImageVertically(img);
}
else if (eql(match_top, img.getCol(9)[0..])) {
match_img = rotateImage(img, 270);
}
else if (eqlTranspose(match_top, img.getCol(9)[0..])) {
match_img = flipImageHorizontally(rotateImage(img, 270));
}
if (match_img) |m| {
std.debug.assert(x == 0 or eql(matrix[y][x - 1].?.getCol(9)[0..], m.getCol(0)[0..]));
std.debug.assert(eql(match_top, m.getRow(0)[0..]));
index = img_index;
break;
}
}
}
//std.debug.print("assign matrix: [{}][{}]\n", .{y, x});
std.debug.assert(match_img != null);
matrix[y][x] = match_img.?;
imgs.items[index] = imgs.items[imgs.items.len - 1];
try imgs.resize(imgs.items.len - 1);
}
}
}
{
// Solution 1
const s1 = matrix[0][0].?.id * matrix[0][COLS - 1].?.id * matrix[ROWS - 1][0].?.id * matrix[ROWS - 1][COLS -1].?.id;
std.debug.print("Day 20 - Solution 1: {}\n", .{s1});
}
var monster_image = MonsterImg{};
{ var r: usize = 0; while (r < MIMG_ROWS) : (r += 1) {
var c: usize = 0; while (c < MIMG_COLS) : (c += 1) {
const img_x = @divFloor(c, 10-2);
const img_y = @divFloor(r, 10-2);
const px = 1 + (c - img_x * (10 - 2));
const py = 1 + (r - img_y * (10 - 2));
monster_image.data[r][c] = matrix[img_y][img_x].?.data[py][px];
}
}}
var sea_monster: [3][20]u8 = undefined;
std.mem.copy(u8, sea_monster[0][0..], " # "[0..]);
std.mem.copy(u8, sea_monster[1][0..], "# ## ## ###"[0..]);
std.mem.copy(u8, sea_monster[2][0..], " # # # # # # "[0..]);
var mimg = monster_image;
var next_transform: u32 = 0;
while (true) {
var monster_found: u32 = 0;
{ var r: usize = 0; while (r < (MIMG_ROWS - 3)) : (r += 1) {
{ var c: usize = 0; while (c < MIMG_COLS - 20) : (c += 1) {
var found = true;
outer: for (sea_monster) |sm_row, sm_row_index| {
for (sm_row) |v, sm_col_index| {
if (v == '#' and v != mimg.data[r + sm_row_index][c + sm_col_index]) {
found = false;
break :outer;
}
}
}
if (found) {
monster_found += 1;
for (sea_monster) |sm_row, sm_row_index| {
for (sm_row) |v, sm_col_index| {
if (v == '#') mimg.data[r + sm_row_index][c + sm_col_index] = 'O';
}
}
}
}}
}}
if (monster_found > 0) {
//mimg.print();
var count: u32 = 0;
for (mimg.data) |row| {
for (row) |v| {
if (v == '#') count += 1;
}
}
std.debug.print("Day 20 - Solution 2: {}\n", .{count});
return;
}
else {
if (next_transform == 0) {
mimg = flipMonsterImageH(mimg);
}
else if (next_transform == 1) {
mimg = flipMonsterImageV(mimg);
}
else {
mimg = rotateMonsterImage(mimg);
}
next_transform += 1;
if (next_transform > 2) next_transform = 0;
}
}
}
const Side = enum {
top, right, bottom, left
};
const Image = struct {
id: usize = 0,
data: [10][10]u8 = undefined,
const Self = @This();
pub fn print(self: * const Self) void {
std.debug.print("-- .id = {}, .data =\n", .{self.id});
for (self.data) |line| {
std.debug.print("{}\n", .{line});
}
}
pub fn rowHash(self: *const Self, row: usize) u64 {
return std.hash_map.hashString(self.data[row][0..]);
}
pub fn colHash(self: *const Self, col: usize) u64 {
var d: [10]u8 = undefined;
for (self.data) |row, i| { d[i] = row[col]; }
return std.hash_map.hashString(d[0..]);
}
pub fn getRow(self: *const Self, r: usize) [10]u8 {
var res: [10]u8 = undefined;
std.mem.copy(u8, res[0..], self.data[r][0..]);
return res;
}
pub fn getCol(self: *const Self, c: usize) [10]u8 {
var res: [10]u8 = undefined;
for (self.data) |row, i| { res[i] = row[c]; }
return res;
}
fn findMatch(a: *const Self, b: *const Self) ?Side {
if (a.id == 2311 and b.id == 3079) {
var x: u32 = 0;
x = x;
}
var asides = [4][10]u8{
a.getRow(0),
a.getCol(9),
a.getRow(9),
a.getCol(0),
};
var bsides = [4][10]u8{
b.getRow(0),
b.getCol(9),
b.getRow(9),
b.getCol(0),
};
for (asides) |aside, i| {
for (bsides) |bside| {
if (eql(aside[0..], bside[0..])) return @intToEnum(Side, @intCast(u2, i));
if (eqlTranspose(aside[0..], bside[0..])) return @intToEnum(Side, @intCast(u2, i));
}
}
return null;
}
};
fn eql(a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
fn eqlTranspose(a: []const u8, b: []const u8) bool {
for (a) |v, i| { if (b[b.len -1 - i] != v) return false; }
return true;
}
fn flipImageHorizontally(a: Image) Image {
var res = Image{};
res.id = a.id;
for (a.data) |row, ri| {
for (row) |v, ci| {
res.data[ri][9 - ci] = v;
}
}
return res;
}
fn flipImageVertically(a: Image) Image {
var res = Image{};
res.id = a.id;
for (a.data) |row, ri| {
for (row) |v, ci| {
res.data[9 - ri][ci] = v;
}
}
return res;
}
fn rotateImage(a: Image, amount: u32) Image {
const rot = @divFloor(amount, 90);
var res = Image{};
res.id = a.id;
switch (rot) {
0 => { res = a; },
1 => {
for (a.data) |row, ri| {
for (row) |v, ci| {
res.data[ci][9 - ri] = v;
}
}
},
2 => {
for (a.data) |row, ri| {
for (row) |v, ci| {
res.data[9 - ri][9 - ci] = v;
}
}
},
3 => {
for (a.data) |row, ri| {
for (row) |v, ci| {
res.data[9 - ci][ri] = v;
}
}
},
else => unreachable
}
return res;
}
const MonsterImg = struct {
data: [MIMG_ROWS][MIMG_COLS]u8 = undefined,
const Self = @This();
pub fn print(self: *const Self) void {
for (self.data) |row| {
std.debug.print("{}\n", .{row});
}
}
};
fn flipMonsterImageH(i: MonsterImg) MonsterImg {
var r = MonsterImg{};
for (i.data) |row, ri| {
for (row) |v, ci| {
r.data[ri][MIMG_COLS-1-ci] = v;
}
}
return r;
}
fn flipMonsterImageV(i: MonsterImg) MonsterImg {
var r = MonsterImg{};
for (i.data) |row, ri| {
for (row) |v, ci| {
r.data[MIMG_COLS-1-ri][ci] = v;
}
}
return r;
}
fn rotateMonsterImage(i: MonsterImg) MonsterImg {
var r = MonsterImg{};
for (i.data) |row, ri| {
for (row) |v, ci| {
r.data[ci][MIMG_COLS-1-ri] = v;
}
}
return r;
} | 2020/src/day_20.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/puzzle/day08.txt");
const patterns: [10][]const u8 = [_][]const u8{
"abcdeg", // 0
"ab", // 1
"acdfg", // 2
"abcdf", // 3
"abef", // 4
"bcdef", // 5
"bcdefg", // 6
"abd", // 7
"abcdefg", // 8
"abcdef", // 9
};
const Flags = [8]u64;
const Digit = struct {
const Self = @This();
str: []u8,
raw: []const u8,
value: u64 = 0,
flags: Flags = Flags{ 0, 0, 0, 0, 0, 0, 0, 0 },
flags_set: bool = false,
fn to_flags(self: *Self) Flags {
if (self.flags_set) {
return self.flags;
}
for (self.str) |letter| {
self.flags[letter - 'a'] = 1;
}
self.flags_set = true;
return self.flags;
}
fn equals(self: Self, other: []const u8) bool {
if (self.raw.len != other.len) return false;
return mem.eql(u8, self.raw, other);
}
};
fn flagsToSegment(flags: Flags) u64 {
for (flags) |flag, idx| {
if (flag != 0) {
return idx + 'a';
}
}
return 0;
}
fn setFlagsSegment(flags: *Flags, segment: u64) void {
flags[segment - 'a'] = 1;
}
fn unsetFlagsSegment(flags: *Flags, segment: u64) void {
flags[segment - 'a'] = 0;
}
fn segmentToFlags(segment: u64, dest: *Flags) void {
var idx = 0;
while (idx < 7) : (idx += 1) {
dest[idx] = 0;
}
dest[segment - 'a'] = 1;
}
fn flagsUnion(a: Flags, b: Flags, dest: *Flags) void {
var idx: usize = 0;
while (idx < 7) : (idx += 1) {
dest[idx] = a[idx] | b[idx];
}
}
fn flagsDiff(a: Flags, b: Flags, dest: *Flags) void {
var idx: usize = 0;
while (idx < 7) : (idx += 1) {
dest[idx] = 0;
if (a[idx] != 0 and b[idx] == 0) {
dest[idx] = 1;
}
}
}
fn strValue(str: []const u8, digits_set: []Digit) u64 {
for (digits_set) |digit| {
if (digit.equals(str)) {
return digit.value;
}
}
return 0;
}
fn lenCmp(context: void, a: Digit, b: Digit) bool {
return a.str.len < b.str.len;
}
pub fn main() !void {
var lines = tokenize(data, "\r\n");
var total_unique: u64 = 0;
var total_sum: u64 = 0;
while (lines.next()) |line| {
var segments = split(line, "|");
var digits_part = segments.next().?;
var test_vals_part = segments.next().?;
var digits_base_wods = tokenize(digits_part, " ");
var test_vals_wods = tokenize(test_vals_part, " ");
var digits_set = ArrayList(Digit).init(gpa);
defer {
for (digits_set.items) |digit| {
gpa.free(digit.str);
gpa.free(digit.raw);
}
digits_set.deinit();
}
try digits_set.ensureCapacity(10);
var idx: u64 = 0;
while (digits_base_wods.next()) |base| : (idx += 1) {
var w = gpa.alloc(u8, base.len) catch unreachable;
var wraw = gpa.alloc(u8, base.len) catch unreachable;
// w and wraw freed by Digits!
copy(u8, w, base);
sort(u8, w, {}, comptime asc(u8));
copy(u8, wraw, w);
try digits_set.append(Digit{ .str = w, .raw = wraw });
}
sort(Digit, digits_set.items, {}, lenCmp);
// digits order:
// 1
// 7
// 4
// 2, 3, 5
// 0, 6, 9
// 8
// segment counts:
// a = 8
// b = 6
// c = 8
// d = 7
// e = 4
// f = 9
// g = 7
var segment_counts: Flags = Flags{ 0, 0, 0, 0, 0, 0, 0, 0 };
var f: Flags = Flags{ 0, 0, 0, 0, 0, 0, 0, 0 };
var mapping: [8]u64 = [_]u64{ 0, 0, 0, 0, 0, 0, 0, 0 };
var mapping_inv: [128]u64 = [_]u64{0} ** 128;
var inv: Flags = Flags{ 0, 0, 0, 0, 0, 0, 0, 0 };
for (digits_set.items) |digit| {
for (digit.str) |letter| {
segment_counts[letter - 'a'] += 1;
}
}
for (segment_counts) |value, jdx| {
switch (value) {
4 => {
mapping[jdx] = 'e';
mapping_inv[mapping[jdx]] = jdx;
},
6 => {
mapping[jdx] = 'b';
mapping_inv[mapping[jdx]] = jdx;
},
9 => {
mapping[jdx] = 'f';
mapping_inv[mapping[jdx]] = jdx;
},
else => mapping[jdx] = 'x',
}
}
digits_set.items[0].value = 1;
digits_set.items[1].value = 7;
digits_set.items[2].value = 4;
digits_set.items[9].value = 8;
// Letter A
flagsDiff(digits_set.items[1].to_flags(), digits_set.items[2].to_flags(), &f);
var seg_a = flagsToSegment(f) - 'a';
mapping[seg_a] = 'a';
mapping_inv[seg_a] = seg_a;
// Letter D
flagsDiff(digits_set.items[2].to_flags(), digits_set.items[1].to_flags(), &f);
unsetFlagsSegment(&f, mapping_inv['b'] + 'a');
var seg_d = flagsToSegment(f) - 'a';
mapping[seg_d] = 'd';
mapping_inv[seg_d] = seg_d;
// for (mapping) |value| {
// print("{c}\n", .{@intCast(u8, value)});
// }
for (segment_counts) |value, jdx| {
if (mapping[jdx] != 'x') continue;
switch (value) {
7 => {
mapping[jdx] = 'g';
mapping_inv[mapping[jdx]] = jdx;
},
8 => {
mapping[jdx] = 'c';
mapping_inv[mapping[jdx]] = jdx;
},
else => mapping[jdx] = 'x',
}
}
for (digits_set.items) |digit, q| {
for (digit.str) |letter, jdx| {
digit.str[jdx] = @intCast(u8, mapping[letter - 'a']);
}
sort(u8, digit.str, {}, comptime asc(u8));
if (mem.eql(u8, digit.str, "cf")) {
digits_set.items[q].value = 1;
}
if (mem.eql(u8, digit.str, "acf")) {
digits_set.items[q].value = 7;
}
if (mem.eql(u8, digit.str, "bcdf")) {
digits_set.items[q].value = 4;
}
if (mem.eql(u8, digit.str, "abdfg")) {
digits_set.items[q].value = 5;
}
if (mem.eql(u8, digit.str, "acdfg")) {
digits_set.items[q].value = 3;
}
if (mem.eql(u8, digit.str, "acdeg")) {
digits_set.items[q].value = 2;
}
if (mem.eql(u8, digit.str, "abcdfg")) {
digits_set.items[q].value = 9;
}
if (mem.eql(u8, digit.str, "abdefg")) {
digits_set.items[q].value = 6;
}
if (mem.eql(u8, digit.str, "abcefg")) {
digits_set.items[q].value = 0;
}
if (mem.eql(u8, digit.str, "abcdefg")) {
digits_set.items[q].value = 8;
}
}
var number: u64 = 0;
while (test_vals_wods.next()) |x| {
var w = gpa.alloc(u8, x.len) catch unreachable;
defer gpa.free(w);
copy(u8, w, x);
sort(u8, w, {}, comptime asc(u8));
for (digits_set.items) |digit| {
if (digit.equals(w)) {
number = number * 10 + digit.value;
}
}
}
total_sum += number;
}
print("{}\n", .{total_sum});
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const copy = std.mem.copy;
const mem = std.mem;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc; | src/day08.zig |
const std = @import("std");
const j = @import("jzignet");
comptime {
const current_version = std.SemanticVersion.parse("0.9.0-dev.1678+7747bf07c") catch unreachable;
const comparison = @import("builtin").zig_version.order(current_version);
if (comparison == .lt) @compileError("Zig version must be at least as of 2021-11-18");
}
// Source Zig code
//=================
// This is a very simple Zig structure we will be using from Janet.
pub const ZigStruct = struct {
counter: u32,
pub fn add(self: *ZigStruct, a: u32) void {
self.counter += a;
}
};
// Wrapper code
//==============
// `ZigStruct` is wrapped into an "abstract type" which is a Janet concept
// for a generic value, it seems to map well to Zig structs.
const ZigStructAbstract = j.Abstract(ZigStruct);
const zig_struct_abstract_type = ZigStructAbstract.Type{ .name = "zig-struct" };
// Function with a standard signature which can be imported to Janet.
fn cfunInitStruct(argc: i32, argv: [*]const j.Janet) callconv(.C) j.Janet {
_ = argv;
// Check that the function receives no arguments.
j.fixArity(argc, 0);
// Allocate and create an abstract type.
const st_abstract = ZigStructAbstract.init(&zig_struct_abstract_type);
// Assign the allocated memory with our initialized struct.
st_abstract.ptr.* = ZigStruct{ .counter = 1 };
// Return the abstract as a Janet value.
return st_abstract.wrap();
}
// Function with a standard signature which can be imported to Janet.
fn cfunAdd(argc: i32, argv: [*]const j.Janet) callconv(.C) j.Janet {
// Check that the function receives exactly 2 arguments.
j.fixArity(argc, 2);
// Retrieve the abstract type from the first argument.
var st_abstract = j.getAbstract(argv, 0, ZigStruct, &zig_struct_abstract_type);
// Retrieve a natural number from the second argument.
const n = j.get(u32, argv, 1);
// Call the `add` function from `ZigStruct`. Notice that we need to reference `ptr`
// to get to the actual pointer for our struct, `st_abstract` is from Janet world.
st_abstract.ptr.add(n);
// Return nil.
return j.nil();
}
// Function with a standard signature which can be imported to Janet.
fn cfunGetCounter(argc: i32, argv: [*]const j.Janet) callconv(.C) j.Janet {
// Check that the function receives exactly 1 argument.
j.fixArity(argc, 1);
// Retrieve the abstract type from the first argument.
const st_abstract = j.getAbstract(argv, 0, ZigStruct, &zig_struct_abstract_type);
// Return the counter. Notice the use of `ptr` to get to the actual Zig pointer.
return j.wrap(u32, st_abstract.ptr.counter);
}
// Declare all the functions which will be imported to Janet.
const cfuns_zig = [_]j.Reg{
j.Reg{ .name = "init-struct", .cfun = cfunInitStruct },
j.Reg{ .name = "add", .cfun = cfunAdd },
j.Reg{ .name = "get-counter", .cfun = cfunGetCounter },
j.Reg.empty,
};
// C ABI code
//============
// **Exactly** this function must be exported from a static or dynamic library built by Zig.
// It tells the Janet version used for building this module.
export fn _janet_mod_config() j.BuildConfig {
return j.configCurrent();
}
// **Exactly** this function _name_ and _signature_ must be exported from Zig, but _body_
// can be different.
// In the body of this function you can do whatever you want, the main purpose
// is to modify the `env` parameter by importing functions and variables into it.
export fn _janet_init(env: *j.Environment) void {
// Import previously defined Zig functions into `env`.
env.cfuns("zig_module", &cfuns_zig);
}
// This function **must** mirror the `_janet_init` and the last part of the name
// must be **exactly** as specified in `project.janet`, `declare-native`:
// `:name "zig_module"` -> `janet_module_entry_zig_module` function name.
// It is used by static compilation.
export fn janet_module_entry_zig_module(env: *j.Environment) void {
// Import previously defined Zig functions into `env`.
env.cfuns("zig_module", &cfuns_zig);
}
// Testing
//=========
test "refAllDecls" {
std.testing.refAllDecls(@This());
} | src/main.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day17.txt");
const Input = struct {
x_min: i64,
x_max: i64,
y_min: i64,
y_max: i64,
pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() {
_ = allocator;
var nums = std.mem.tokenize(u8, input_text[15..], "., y=\r\n");
var input = Input{
.x_min = try parseInt(i64, nums.next().?, 10),
.x_max = try parseInt(i64, nums.next().?, 10),
.y_min = try parseInt(i64, nums.next().?, 10),
.y_max = try parseInt(i64, nums.next().?, 10),
};
errdefer input.deinit();
return input;
}
pub fn deinit(self: @This()) void {
_ = self;
}
};
fn hitsTargetArea(input: Input, x_vel: i64, y_vel: i64, y_max: ?*i64) bool {
var x: i64 = 0;
var y: i64 = 0;
var y_highest: i64 = 0;
var xv: i64 = x_vel;
var yv: i64 = y_vel;
while (x <= input.x_max and y >= input.y_min) {
x += xv;
y += yv;
y_highest = std.math.max(y_highest, y);
xv = if (xv > 0) xv - 1 else if (xv < 0) xv + 1 else 0;
yv -= 1;
if (x >= input.x_min and x <= input.x_max and y >= input.y_min and y <= input.y_max) {
if (y_max != null) {
y_max.?.* = y_highest;
}
return true;
}
}
return false;
}
fn triangleNumFloor(n: i64) i64 {
assert(n >= 1);
var sum: i64 = 0;
var tri: i64 = 0;
while (sum < n) {
tri += 1;
sum += tri;
}
return tri;
}
fn part1(input: Input) i64 {
const x_vel: i64 = triangleNumFloor(input.x_min);
const y_vel: i64 = -input.y_min - 1;
var y_max: i64 = undefined;
assert(hitsTargetArea(input, x_vel, y_vel, &y_max));
return y_max;
}
fn part2(input: Input) i64 {
const xv_min: i64 = triangleNumFloor(input.x_min);
const xv_max: i64 = input.x_max + 1;
const yv_min: i64 = input.y_min - 1;
const yv_max: i64 = -input.y_min - 1;
var hit_count: i64 = 0;
var yv = yv_min;
while (yv <= yv_max) : (yv += 1) {
var xv = xv_min;
while (xv <= xv_max) : (xv += 1) {
if (hitsTargetArea(input, xv, yv, null)) {
hit_count += 1;
}
}
}
return hit_count;
}
const test_data =
\\target area: x=20..30, y=-10..-5
;
const part1_test_solution: ?i64 = 45;
const part1_solution: ?i64 = 2850;
const part2_test_solution: ?i64 = 112;
const part2_solution: ?i64 = 1117;
// Just boilerplate below here, nothing to see
fn testPart1() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part1_test_solution) |solution| {
try std.testing.expectEqual(solution, part1(test_input));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part1_solution) |solution| {
try std.testing.expectEqual(solution, part1(input));
print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
fn testPart2() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part2_test_solution) |solution| {
try std.testing.expectEqual(solution, part2(test_input));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part2_solution) |solution| {
try std.testing.expectEqual(solution, part2(input));
print("part2 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
pub fn main() !void {
try testPart1();
try testPart2();
}
test "part1" {
try testPart1();
}
test "part2" {
try testPart2();
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const parseInt = std.fmt.parseInt;
const min = std.math.min;
const max = std.math.max;
const print = std.debug.print;
const expect = std.testing.expect;
const assert = std.debug.assert; | src/day17.zig |
const debugger_el = @import("build_options").debugger_el;
const proto = @import("proto");
const host = @import("host");
pub const Frame = proto.aarch64.ElFrame(debugger_el);
fn elReg(comptime prefix: []const u8, comptime el: comptime_int) []const u8 {
return prefix ++ "_EL" ++ [1]u8{'0' + el};
}
export fn int_handler() callconv(.Naked) noreturn {
asm volatile (
\\ MSR SPSel, #1
\\ STP X0, X1, [SP, #-0x10]!
\\ MOV X0, #0
\\ B common_handler
\\.global spx_handler
\\spx_handler:
\\ STP X0, X1, [SP, #-0x10]!
\\ MOV X0, #1
\\common_handler:
\\ STP X2, X3, [SP, #-0x10]!
\\ STP X4, X5, [SP, #-0x10]!
\\ STP X6, X7, [SP, #-0x10]!
\\ STP X8, X9, [SP, #-0x10]!
\\ STP X10, X11, [SP, #-0x10]!
\\ STP X12, X13, [SP, #-0x10]!
\\ STP X14, X15, [SP, #-0x10]!
\\ STP X16, X17, [SP, #-0x10]!
\\ STP X18, X19, [SP, #-0x10]!
\\ STP X20, X21, [SP, #-0x10]!
\\ STP X22, X23, [SP, #-0x10]!
\\ STP X24, X25, [SP, #-0x10]!
\\ STP X26, X27, [SP, #-0x10]!
\\ STP X28, X29, [SP, #-0x10]!
\\ MRS X1, SP_EL0
\\ STP X1, X30, [SP, #-0x10]!
\\ SUB SP, SP, %[frame_size_offset]
\\
\\ MOV X1, SP
\\.global branch_to_handle_interrupt
\\.extern __branch_to_handle_interrupt_value
\\branch_to_handle_interrupt:
\\ .4byte __branch_to_handle_interrupt_value // BL handle_interrupt
\\
\\ ADD SP, SP, %[frame_size_offset]
\\ LDP X1, X30, [SP], 0x10
\\ CBNZ X0, skip_because_spx
\\ MSR SP_EL0, X1
\\skip_because_spx:
\\ LDP X28, X29, [SP], 0x10
\\ LDP X26, X27, [SP], 0x10
\\ LDP X24, X25, [SP], 0x10
\\ LDP X22, X23, [SP], 0x10
\\ LDP X20, X21, [SP], 0x10
\\ LDP X18, X19, [SP], 0x10
\\ LDP X16, X17, [SP], 0x10
\\ LDP X14, X15, [SP], 0x10
\\ LDP X12, X13, [SP], 0x10
\\ LDP X10, X11, [SP], 0x10
\\ LDP X8, X9, [SP], 0x10
\\ LDP X6, X7, [SP], 0x10
\\ LDP X4, X5, [SP], 0x10
\\ LDP X2, X3, [SP], 0x10
\\ CMP X0, #0
\\ LDP X0, X1, [SP], 0x10
\\ B.NE eret_on_spx
\\ MSR SPSel, #0
\\eret_on_spx:
\\ ERET
\\
\\.global fatal_error
\\fatal_error:
\\ WFE
\\ B fatal_error
:
: [frame_size_offset] "i" (@as(u16, @offsetOf(Frame, "gpr")))
);
unreachable;
}
fn fillStruct(s_ptr: anytype) callconv(.Inline) void {
const T = @TypeOf(s_ptr.*);
inline for (@typeInfo(T).Struct.fields) |f| {
const value = asm ("MRS %[reg], " ++ f.name ++ "\n"
: [reg] "=r" (-> f.field_type)
);
@field(s_ptr.*, f.name) = value;
}
asm volatile ("" ::: "memory");
}
fn applyStruct(s: anytype) callconv(.Inline) void {
const T = @TypeOf(s);
// This copy is for better code generation (volatile asm writing to the MSRs clobber memory)
const copy = s;
inline for (@typeInfo(T).Struct.fields) |f| {
const value = @field(copy, f.name);
_ = asm volatile ("MSR " ++ f.name ++ ", %[reg]\n"
: [val] "=r" (-> u64)
: [reg] "r" (value)
);
}
}
pub fn resolveAddr(addr: u64, instr: u32) callconv(.Inline) u64 {
const instr_loc = asm volatile (
\\ ADR %[instr_loc], instr_loc
: [instr_loc] "=r" (-> u64)
);
return asm volatile ( // zig fmt: off
\\ STR W8, [%[instr_loc]]
\\ DC CVAU, %[instr_loc]
\\ DSB NSHST
\\ IC IVAU, %[instr_loc]
\\ DSB NSH
\\ ISB
\\instr_loc:
\\ BRK #0
\\ ISB
\\ MRS %[result], PAR_EL1
: [result] "=r" (-> u64)
: [instr] "{w8}" (instr)
, [instr_loc] "r" (instr_loc)
, [_] "{x0}" (addr)
// zig fmt: on
);
}
fn sendReg(comptime reg_name: []const u8) u64 {
const reg = asm volatile ("MRS %[out], " ++ reg_name
: [out] "=r" (-> u64)
);
host.callbacks.send_fn(@ptrCast([*:0]const u8, ®), 8);
return reg;
}
fn doOsLock() callconv(.Inline) void {
// OS lock time. Thanks.
const OSLSR_EL1 = asm volatile (
\\ MRS %[oslsr], OSLSR_EL1
: [oslsr] "=r" (-> u64)
);
const OSLM = @truncate(u2, OSLSR_EL1 & 1) | @truncate(u2, (OSLSR_EL1 >> 2) & 2);
const OSLK = @truncate(u1, OSLSR_EL1 >> 1);
switch (OSLM) {
0b00 => return, // OS Lock not implemented
0b10 => { // OS Lock implemented
if (OSLK == 0b1) { // OS lock is locked! Gotta unlock it for single stepping!
asm volatile (
\\ MSR OSLAR_EL1, %[zero]
:
: [zero] "r" (@as(u64, 0))
);
}
},
else => unreachable,
}
}
// If it's important that the debuggee cannot interface with
// debugger registers, enable this to trap all debugger registers
// that can be trapped if you're debugging a lower EL
const contain_debuggee = false;
fn setupDebuggerRegs() callconv(.Inline) void {
if (comptime (debugger_el >= 3)) {
asm volatile ("MSR MDCR_EL3, %[mdscr]"
:
// zig fmt: off
: [mdscr] "r" (@as(u64,
(if(comptime(contain_debuggee)) 0
| (1 << 6) // TPM
| (1 << 9) // TDA
| (1 << 10) // TDOSA
| (0b00 << 12) // NSPB
| (0b11 << 14) // SPD32
| (1 << 17) // SPME
| (1 << 18) // STE
| (1 << 19) // TTRF
| (1 << 20) // EDAD
| (1 << 21) // EPMAD
| (0 << 23) // SCCD
| (1 << 27) // TDCC
| (1 << 28) // MTPME
| (0 << 34) // MCCD
| (0 << 35) // MPMX
| (0 << 36) // EnPMSN
else 0
| (0 << 6) // TPM
| (0 << 9) // TDA
| (0 << 10) // TDOSA
| (0b11 << 12) // NSPB
| (0b11 << 14) // SPD32
| (1 << 17) // SPME
| (1 << 18) // STE
| (0 << 19) // TTRF
| (1 << 20) // EDAD
| (1 << 21) // EPMAD
| (0 << 23) // SCCD
| (0 << 27) // TDCC
| (1 << 28) // MTPME
| (0 << 34) // MCCD
| (0 << 35) // MPMX
| (1 << 36) // EnPMSN
)
| (0 << 16) // SDD
))
// zig fmt: on
);
}
if (comptime (debugger_el >= 2)) {
// @TODO `contain_debuggee`
}
if (comptime (debugger_el >= 1)) {
// @TODO `contain_debuggee`
const old_mdscr = asm volatile (
\\ MRS %[mdscr], MDSCR_EL1
: [mdscr] "=r" (-> u64)
);
// zig fmt: off
asm volatile (
\\MSR MDSCR_EL1, %[mdscr]
:
: [mdscr] "r" (old_mdscr
| (1 << 0) // SS, software step enable
| (1 << 13) // KDE, local kernel debug enable
| (1 << 15) // MDE, monitor debug events
)
);
// zig fmt: on
}
}
pub fn install() void {
const evt_base = asm volatile ("ADR %[reg], evt_base"
: [reg] "=r" (-> u64)
);
asm volatile ("MSR " ++ elReg("VBAR", debugger_el) ++ ", %[evt]"
:
: [evt] "r" (evt_base)
);
if(comptime(debugger_el < 3)) {
// We should only unlock the OS lock if
// we aren't on el3, as it's only needed for
// software stepping, and we can't do that in EL3
doOsLock();
}
setupDebuggerRegs();
// Enable debugging at ELd
asm volatile (
\\ MSR DAIFclr, #8
\\
);
// Trap into the debugger at the current EL
switch (debugger_el) {
1 => asm volatile (
\\ SVC #42069
),
2 => asm volatile (
\\ HVC #42069
),
3 => asm volatile (
\\ SMC #42069
),
else => @compileError("wtf"),
}
}
export fn handle_interrupt(was_in_curr_el_spx_context: u64, frame: *Frame) callconv(.C) u64 {
frame.header.current_el = debugger_el;
if (comptime (@hasField(Frame, "el1")))
fillStruct(&frame.el1);
if (comptime (@hasField(Frame, "el2")))
fillStruct(&frame.el2);
if (comptime (@hasField(Frame, "el3")))
fillStruct(&frame.el3);
if (was_in_curr_el_spx_context != 0) {
frame.gpr.SP = @ptrToInt(frame) + @sizeOf(Frame);
}
host.handle_interrupt(frame);
if (comptime (@hasField(Frame, "el3")))
applyStruct(frame.el3);
if (comptime (@hasField(Frame, "el2")))
applyStruct(frame.el2);
if (comptime (@hasField(Frame, "el1")))
applyStruct(frame.el1);
return was_in_curr_el_spx_context;
} | src/host/arch/aarch64/main.zig |
const std = @import("std");
const fs = std.fs;
const mem = std.mem;
const Builder = std.build.Builder;
const Pkg = std.build.Pkg;
const cwd = std.fs.cwd;
pub fn build(b: *Builder) !void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
// Open the build root as an iterable directory handle.
var build_root = try cwd().openDir(b.build_root, .{ .iterate = true });
defer build_root.close();
// Create a list containing each year present in the repo.
const Year = struct { str: []const u8, int: u32 };
var years: []const Year = blk: {
// Create an ArrayList to allocate space for the list of years.
var list = std.ArrayListUnmanaged(Year){};
// Populate the list of years based on directory names.
var iterator = build_root.iterate();
while (try iterator.next()) |item| {
if (item.kind == .Directory) {
const year = std.fmt.parseUnsigned(u32, item.name, 10) catch continue;
try list.append(b.allocator, .{
.str = b.dupe(item.name),
.int = year,
});
}
}
// Extract the years from the list and sort them in ascending order.
std.sort.sort(Year, list.items, {}, struct {
fn impl(_: void, l: Year, r: Year) bool {
return l.int < r.int;
}
}.impl);
break :blk list.items;
};
// Accept a filter over the years and days to execute. If no filter is
// provided, the latest day of the most recent year will be executed.
const filter = b.option([]const u8, "filter", "Filter the solutions to be executed");
if (filter == null and years.len > 0) {
years = years[(years.len - 1)..];
}
// Create a dependency listing made available to each puzzle solution.
const deps = try b.allocator.alloc(Pkg, 2);
deps[0] = .{
.name = "ctregex",
.path = b.pathFromRoot("deps/ctregex.zig/ctregex.zig"),
};
deps[1] = .{
.name = "util",
.path = b.pathFromRoot("util.zig"),
.dependencies = deps[0..1],
};
// Create a listing of the puzzle solutions to be filtered and run.
const Puzzle = struct { pkg: Pkg, day: u32 };
var puzzles = std.AutoArrayHashMapUnmanaged(u32, []const Puzzle){};
var num_puzzles: usize = 0;
for (years) |year| {
// Open the directory containing the year's solutions.
var year_dir = try build_root.openDir(year.str, .{ .iterate = true });
defer year_dir.close();
// Populate this year's list of puzzle solutions.
var list = std.ArrayListUnmanaged(Puzzle){};
var iterator = year_dir.iterate();
while (try iterator.next()) |item| {
if (item.kind == .File and mem.endsWith(u8, item.name, ".zig")) {
const name = item.name[0..(item.name.len - 4)];
const day = std.fmt.parseUnsigned(u32, name, 10) catch continue;
const entry = try list.addOne(b.allocator);
entry.* = Puzzle{
.pkg = Pkg{
.name = b.fmt("{}:{}", .{ year.str, name }),
.path = try fs.path.resolve(b.allocator, &[_][]const u8{
b.build_root,
year.str,
item.name,
}),
.dependencies = deps,
},
.day = day,
};
num_puzzles += 1;
}
}
// Sort the year's puzzles by day in ascending order.
if (list.items.len > 0) {
std.sort.sort(Puzzle, list.items, {}, struct {
fn impl(_: void, l: Puzzle, r: Puzzle) bool {
return l.day < r.day;
}
}.impl);
try puzzles.put(b.allocator, year.int, list.items);
}
}
// Generate the source of the main executable based on the files present.
const exe_src = b.addWriteFile("main.zig", blk: {
@setEvalBranchQuota(10_000);
var src = std.ArrayList(u8).init(b.allocator);
const writer = src.writer();
// Import std and ctregex, and define metadata structs.
try writer.writeAll(
\\const std = @import("std");
\\const util = @import("util");
\\
\\const Puzzle = struct {
\\ id: []const u8,
\\ pkg: type,
\\ day: u32,
\\ year: u32,
\\};
\\
\\
);
// If a filter is supplied, we run all puzzle solutions that match the filter.
// Otherwise, we run the latest puzzle solution from the most recent year.
if (filter) |filter_| {
try writer.print(
\\const puzzles = comptime blk: {{
\\ @setEvalBranchQuota(5000 * {1});
\\ const filter = "{0Z}";
\\ var latest_year: u32 = 0;
\\ var items: []const Puzzle = &[_]Puzzle{{}};
\\
, .{ filter_, num_puzzles });
// Attempt to match entries based on `year:entry` pattern, and fallback to
// just `year` pattern (which is accepted as a convenience feature).
for (puzzles.items()) |year| {
try writer.writeAll("\n");
for (year.value) |puzzle| {
try writer.print(
\\ if (util.isMatch(filter, "{0Z}")) {{
\\ latest_year = {2};
\\ items = items ++ [_]Puzzle{{.{{
\\ .id = "{0Z}",
\\ .pkg = @import("{0Z}"),
\\ .day = {1},
\\ .year = {2},
\\ }}}};
\\ }}
\\
, .{ puzzle.pkg.name, puzzle.day, year.key });
}
const newest = year.value[year.value.len - 1];
try writer.print(
\\ if (latest_year != {2} and util.isMatch(filter, "{2}")) {{
\\ items = items ++ [_]Puzzle{{.{{
\\ .id = "{0Z}",
\\ .pkg = @import("{0Z}"),
\\ .day = {1},
\\ .year = {2},
\\ }}}};
\\ }}
\\
, .{ newest.pkg.name, newest.day, year.key });
}
try writer.writeAll(" break :blk items;\n};\n");
} else {
if (puzzles.count() == 0) {
// We don't have any puzzles to run, so just use an empty slice.
try writer.writeAll("const puzzles: []const Puzzle = &[_]Puzzle{};\n");
} else {
// Puzzle entries are sorted in ascending order, so this is the latest entry.
const year = &puzzles.items()[0];
const newest = year.value[year.value.len - 1];
try writer.print(
\\const puzzles: []const Puzzle = &[_]Puzzle{{.{{
\\ .id = "{0Z}",
\\ .pkg = @import("{0Z}"),
\\ .day = {1},
\\ .year = {2},
\\}}}};
\\
, .{ newest.pkg.name, newest.day, year.key });
}
}
try writer.writeAll(
\\
\\pub fn main() u8 {
\\ var status: u8 = 0;
\\ const stdout = std.io.getStdOut().writer();
\\ var timer = std.time.Timer.start() catch return 1;
\\
\\ inline for (puzzles) |puzzle, i| {
\\ var gpa = std.heap.GeneralPurposeAllocator(.{}){};
\\ defer _ = gpa.deinit();
\\
\\ var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
\\ defer arena.deinit();
\\
\\ const utils = util.Utils{
\\ .arena = &arena.allocator,
\\ .gpa = &gpa.allocator,
\\ .out = stdout,
\\ };
\\
\\ if (i > 0) std.debug.print("\n", .{});
\\
\\ timer.reset();
\\ const result = puzzle.pkg.main(utils);
\\ var elapsed = timer.read();
\\
\\ switch (@typeInfo(@typeInfo(@TypeOf(puzzle.pkg.main)).Fn.return_type.?)) {
\\ .ErrorUnion => {
\\ if (result) |n| {
\\ comptime std.debug.assert(@TypeOf(n) == void);
\\ } else |err| {
\\ std.log.err("{}", .{@errorName(err)});
\\ if (@errorReturnTrace()) |trace| {
\\ std.debug.dumpStackTrace(trace.*);
\\ }
\\ status = 1;
\\ }
\\ },
\\ .Void => {},
\\ else => comptime unreachable,
\\ }
\\
\\ var fraction: ?u64 = null;
\\ var unit: []const u8 = "ns";
\\ if (elapsed > 1000) {
\\ fraction = elapsed % 1000;
\\ elapsed /= 1000;
\\ unit = "μs";
\\ }
\\ if (elapsed > 1000) {
\\ fraction = elapsed % 1000;
\\ elapsed /= 1000;
\\ unit = "ms";
\\ }
\\ if (elapsed > 1000) {
\\ fraction = elapsed % 1000;
\\ elapsed /= 1000;
\\ unit = "s";
\\ }
\\ std.debug.print("info: December {}, {} ({}", .{
\\ puzzle.day,
\\ puzzle.year,
\\ elapsed,
\\ });
\\ if (fraction) |f|
\\ std.debug.print(".{}", .{f});
\\ std.debug.print("{})\n", .{unit});
\\ }
\\ return status;
\\}
\\
);
break :blk src.items;
});
const exe = b.addExecutableFromWriteFileStep("advent-of-code", exe_src, "main.zig");
exe.addPackage(deps[1]);
for (puzzles.items()) |entry|
for (entry.value) |value|
exe.addPackage(value.pkg);
exe.setBuildMode(mode);
exe.setTarget(target);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args|
run_cmd.addArgs(args);
const run_step = b.step("run", "Build and run the application");
run_step.dependOn(&run_cmd.step);
} | build.zig |
const std = @import("std");
usingnamespace @import("itertools.zig");
const IsEqual = std.testing.expectEqual;
test "range" {
{
var range_iter = range(i32, .{ .start = 0, .end = 5, .step = 1 });
var total: i32 = 0;
while (range_iter.next()) |value| {
total += value;
}
try IsEqual(total, 10);
}
{
// missing fields, fine but dont iterate
var range_iter = range(i32, .{});
var total: i32 = 0;
while (range_iter.next()) |value| {
total += value;
}
try IsEqual(total, 0);
}
{
// missing fields, fine but dont iterate
var range_iter = range(i32, .{ .end = 10 });
var total: i32 = 0;
while (range_iter.next()) |value| {
total += value;
}
try IsEqual(total, 45);
}
{
var range_iter = range(i32, .{ .end = 10, .step = 2 });
var total: i32 = 0;
while (range_iter.next()) |value| {
total += value;
}
//2 + 4 + 6 + 8 = 20
try IsEqual(total, 20);
}
}
test "slice to iter" {
const arr = [_]u32{ 1, 2, 3 };
var iter = iterator(&arr);
try IsEqual(iter.next().?, 1);
try IsEqual(iter.next().?, 2);
try IsEqual(iter.next().?, 3);
try IsEqual(iter.next(), null);
}
fn double(a: i32) i32 {
return a * 2;
}
test "map" {
const arr = [_]i32{ 1, 2, 3 };
var iter = iterator(&arr).map(double);
try IsEqual(iter.next().?, 2);
try IsEqual(iter.next().?, 4);
try IsEqual(iter.next().?, 6);
try IsEqual(iter.next(), null);
}
fn odd(a: i32) bool {
return @mod(a, 2) == 1;
}
test "filter" {
const arr = [_]i32{ 1, 2, 3, 4, 5, 6 };
var iter = iterator(&arr).filter(odd);
try IsEqual(iter.next().?, 1);
try IsEqual(iter.next().?, 3);
try IsEqual(iter.next().?, 5);
try IsEqual(iter.next(), null);
}
fn sum(a: i32, b: i32) i32 {
return a + b;
}
test "reduce" {
const arr = [_]i32{ 1, 2, 3, 4, 5, 6 };
var iter = iterator(&arr).reduce(sum); // 21
try IsEqual(iter.next().?, 21);
try IsEqual(iter.next(), null);
}
test "fold" {
const arr = [_]i32{ 1, 2, 3, 4, 5, 6 };
var result = iterator(&arr).fold(10, sum); // 10 + 21, fold is eager
try IsEqual(result, 31);
}
test "zip" {
{
const arr = [_]i32{ 1, 2, 3 };
const arr2 = [_]i32{ 4, 5, 6 };
var iter = iterator(&arr).zip(&arr2);
try IsEqual(iter.next().?, pair(@as(i32, 1), @as(i32, 4)));
try IsEqual(iter.next().?, pair(@as(i32, 2), @as(i32, 5)));
try IsEqual(iter.next().?, pair(@as(i32, 3), @as(i32, 6)));
try IsEqual(iter.next(), null);
}
{
const arr = [_]i32{ 1, 2, 3 };
const arr2 = [_]i32{ 4, 5, 6 };
var iter = zip(&arr, &arr2);
try IsEqual(iter.next().?, pair(@as(i32, 1), @as(i32, 4)));
try IsEqual(iter.next().?, pair(@as(i32, 2), @as(i32, 5)));
try IsEqual(iter.next().?, pair(@as(i32, 3), @as(i32, 6)));
try IsEqual(iter.next(), null);
}
}
test "toArrayList" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var alloc = &gpa.allocator;
var array_list = try range(i32, .{ .end = 10, .step = 2 }).toArrayList(alloc);
try IsEqual(array_list.items[0], 0);
try IsEqual(array_list.items[1], 2);
try IsEqual(array_list.items[2], 4);
try IsEqual(array_list.items[3], 6);
try IsEqual(array_list.items[4], 8);
}
test "toAutoHashMap" {
// var gpa = std.heap.GeneralPurposeAllocator(.{}){};
// var alloc = &gpa.allocator;
// const key = [_]i32{ 1, 2, 3 };
// const value = [_][]const u8{ "One", "Two", "Three" };
// var dict = try zip(&key, &value).toAutoHashMap(alloc);
// how to properly test this ??
}
test "once" {
var iter = once(@as(i32, 10)).map(double);
try IsEqual(iter.next().?, 20);
try IsEqual(iter.next(), null);
}
fn printer(a: anytype) void {
std.debug.print("{}\n", .{a});
}
fn divBy10(a: i32) bool {
return @mod(a, 10) == 0;
}
test "multiple iterators" {
{
var result = range(i32, .{ .end = 100 }).map(double).filter(divBy10).fold(100, sum);
try IsEqual(result, 2000);
}
} | src/tests.zig |
const std = @import("std");
const errors = @import("errors.zig");
const fmt = std.fmt;
const data_types = @import("data_types.zig");
const parser = @import("parser.zig");
const StackNumberType = data_types.UsedNumberType;
const StackType = enum {
String,
Atom,
Number,
TokenList,
NumberList,
};
const StackItem = struct { item_type: StackType, data: union {
text: []const u8,
number: StackNumberType,
token_list: []parser.Token,
number_list: []StackNumberType,
} };
pub fn print(comptime format: []const u8, args: anytype) void {
const stdout = std.io.getStdOut().writer();
nosuspend stdout.print(format, args) catch return;
}
pub fn execute(alloc: std.mem.Allocator, tokens: []const parser.Token) anyerror!void {
var stack = Stack{};
try stack.init(alloc);
for (tokens) |t| {
try stack.execute_single_token(t);
}
}
// Everything beyond this is part of the `Stack` struct
const Stack = @This();
list: std.ArrayList(StackItem) = undefined,
variables: std.StringHashMap(StackItem) = undefined,
stack_allocator: std.mem.Allocator = undefined,
current_bracket_tokens: std.ArrayList(parser.Token) = undefined,
bracket_depth: u64 = 0,
scope_depth: u64 = 0,
return_flag: bool = false,
fn init(self: *Stack, alloc: std.mem.Allocator) !void {
self.stack_allocator = alloc;
self.list = try std.ArrayList(StackItem).initCapacity(alloc, 1024);
self.variables = std.StringHashMap(StackItem).init(alloc);
self.current_bracket_tokens = std.ArrayList(parser.Token).init(alloc);
}
fn item_is(_: *Stack, item: StackItem, required_type: StackType) bool {
return item.item_type == required_type;
}
fn create_numberlist(_: *Stack, value: []StackNumberType) StackItem {
return StackItem{ .item_type = .NumberList, .data = .{ .number_list = value } };
}
fn create_number(_: *Stack, value: StackNumberType) StackItem {
return StackItem{ .item_type = .Number, .data = .{ .number = value } };
}
fn create_string(_: *Stack, value: []const u8) StackItem {
return StackItem{ .item_type = .String, .data = .{ .text = value } };
}
fn create_atom(_: *Stack, value: []const u8) StackItem {
return StackItem{ .item_type = .Atom, .data = .{ .text = value } };
}
fn atom_to_type(_: *Stack, atom: StackItem) ?StackType {
if (atom.item_type != .Atom) @panic("atom_to_type called with wrong arguments");
const functions = std.ComptimeStringMap(StackType, .{
.{ "Atom", .Atom },
.{ "String", .String },
.{ "Number", .Number },
.{ "TokenList", .TokenList },
.{ "NumberList", .NumberList },
});
return functions.get(atom.data.text) orelse null;
}
fn execute_function(
self: *Stack,
name: []const u8,
) anyerror!void {
var possible_func: ?StackItem = undefined;
// Try find a global variable. This is simple as the name is not mangled.
possible_func = self.variables.get(name);
if (possible_func) |_| {} else {
if (self.scope_depth != 0) { // We can't have a local variable if we are in the global scope
// Try find a local variable.
// This is more complex as we need to modify the name by adding the scope_depth to the start
var key_string = std.ArrayList(u8).init(self.stack_allocator);
defer key_string.deinit();
var scope_as_str = try std.fmt.allocPrint(self.stack_allocator, "{}", .{self.scope_depth});
try key_string.appendSlice(scope_as_str); // Put the scope depth on the buffer first
try key_string.appendSlice(name); // And then the actual function name
const new_name = key_string.toOwnedSlice();
possible_func = self.variables.get(new_name);
}
if (possible_func) |_| {} else errors.executor_panic("Unknown function ", name); // Still don't have a function? Then it doesn't exist.
}
if (possible_func) |function_contents| {
switch (function_contents.item_type) {
.TokenList => {
var prog_pointer: i64 = 0;
// We loop like this so we can modify the `prog_pointer` and can jump back to the beginning of the function if and when we need to.
while (prog_pointer < function_contents.data.token_list.len) : (prog_pointer += 1) {
var tok = function_contents.data.token_list[@intCast(usize, prog_pointer)];
self.scope_depth += 1;
defer self.scope_depth -= 1;
if (tok.id == .Function) {
if (std.mem.eql(u8, tok.data.text, name)) {
// Executes on recursion
if (prog_pointer == function_contents.data.token_list.len - 1) {
// Executes on some forms of tail call recursion where the function name is the exact last token
prog_pointer = -1; // The for loop still increments by 1 so we need this to reset the prog_pointer to 0
continue;
}
}
}
try self.execute_single_token(tok);
if (self.return_flag) {
// If self.return_flag is active, the `return` keyword was used somewhere in the function which ignores all instructions after it is called.
// This needs to be reset before calling another function.
self.return_flag = false;
return;
}
}
},
else => {
// If it is not a TokenList, we don't need to bother looping as there is only one possible thing that can happen.
try self.append(function_contents);
},
}
} else unreachable;
}
fn append(self: *Stack, value: StackItem) !void {
try self.list.append(value);
}
// Bracket Depth tells us if we're inside a quote
// Scope Depth tells us if we're executing a quote
fn execute_single_token(
self: *Stack,
t: parser.Token,
) !void {
if (self.return_flag) return;
if (self.bracket_depth == 0) {
switch (t.id) {
.Eof => {
return;
},
.PreProcUse, .Comment => unreachable,
.BracketLeft => self.bracket_depth += 1,
.BracketRight => errors.panic("Brackets are not balanced. A left bracket must always precede a right one."),
.Number => try self.append(self.create_number(t.data.number)),
.String => try self.append(self.create_string(t.data.text)),
.Atom => try self.append(self.create_atom(t.data.text)),
.Function => try self.execute_function(t.data.text),
// zig fmt: off
.BuiltinAsType => try self.builtin_as_type(),
.BuiltinDefine => try self.builtin_define(),
.BuiltinDup => try self.builtin_dup(),
.BuiltinFor => try self.builtin_for(),
.BuiltinIf => try self.builtin_if(),
.BuiltinIfElse => try self.builtin_ifelse(),
.BuiltinLocalDefine => try self.builtin_local_define(),
.BuiltinPrint => try self.builtin_print(),
.BuiltinRange => try self.builtin_range(),
.BuiltinSwap => try self.builtin_swap(),
.BuiltinWhile => try self.builtin_while(),
.OperatorDivide => try self.operator_divide(),
.OperatorEqual => try self.operator_eq(),
.OperatorGreaterThan => try self.operator_gt(),
.OperatorGreaterThanOrEqual => try self.operator_gteq(),
.OperatorLessThan => try self.operator_lt(),
.OperatorLessThanOrEqual => try self.operator_lteq(),
.OperatorMinus => try self.operator_minus(),
.OperatorModulo => try self.operator_modulo(),
.OperatorMultiply => try self.operator_multiply(),
.OperatorNotEqual => try self.operator_neq(),
.OperatorPlus => try self.operator_plus(),
// zig fmt: on
.BuiltinRequireStack => {},
.BuiltinReturn => self.return_flag = true,
}
} else {
switch (t.id) {
.BracketLeft => {
self.bracket_depth += 1;
try self.current_bracket_tokens.append(t);
},
.BracketRight => {
self.bracket_depth -= 1;
if (self.bracket_depth == 0) {
try self.append(StackItem{
.item_type = .TokenList,
.data = .{
.token_list = self.current_bracket_tokens.toOwnedSlice(),
},
});
} else {
try self.current_bracket_tokens.append(t);
}
},
else => {
try self.current_bracket_tokens.append(t);
},
}
}
}
fn builtin_as_type(stack: *Stack) !void {
// Converting types to other types.
// This is a complex process as there are a lot of branches.
const result_type_atom = stack.list.pop();
const to_convert = stack.list.pop();
if (!stack.item_is(result_type_atom, .Atom)) {
errors.executor_panic("'as_type' expected type Atom as resulting type, got type ", result_type_atom.item_type);
}
const result_type = stack.atom_to_type(result_type_atom) orelse
errors.panic("Invalid type for 'astype' conversion. Expected one of `Atom` `String` `Number` `TokenList` `NumberList`. Perhaps you misspelt?");
const current_type = to_convert.item_type;
// Rules for conversion
// t = always
// ? = sometimes
// Atom =>
// String t
// String =>
// Atom ?
// Number ?
// NumberList t :: Get ASCII codes of string value
// Number =>
// String t
// TokenList =>
// NumberList ?
// NumberList =>
// TokenList t
// String t :: Convert back to string using ASCII values
var result: ?StackItem = null;
switch (current_type) {
.Atom => switch (result_type) {
.String => result = stack.create_string(to_convert.data.text),
else => {},
},
.String => switch (result_type) {
.Atom => {
// Check if the String is a valid Atom.
switch (to_convert.data.text[0]) {
'0'...'9' => errors.panic("Failed to convert type String to Atom. String starts with Number, this is invalid in an Atom."),
else => {},
}
for (to_convert.data.text) |n| {
if (!@import("lexer.zig").isIdentifier(n)) { // We may as well use the lexer function here, because it saves us writing another function just for the executor
errors.panic("Failed to convert type String to Atom. String does not conform to Atom naming requirements.");
}
}
result = stack.create_atom(to_convert.data.text);
},
.Number => {
result = stack.create_number(std.fmt.parseFloat(StackNumberType, to_convert.data.text) catch errors.panic("Failed to convert type String to Number. String is not a valid Number"));
},
.NumberList => {
// Strings are converted to `NumberList`s as the ASCII codes of their values.
var number_list = std.ArrayList(StackNumberType).init(stack.stack_allocator);
for (to_convert.data.text) |n| {
try number_list.append(@intToFloat(StackNumberType, n));
}
result = stack.create_numberlist(number_list.toOwnedSlice());
},
else => {},
},
.Number => switch (result_type) {
.String => result = stack.create_string(try std.fmt.allocPrint(stack.stack_allocator, "{d}", .{to_convert.data.number})),
else => {},
},
.TokenList => switch (result_type) {
.NumberList => {
// `TokenList`s are converted to `NumberList`s if they only contain `Number` tokens.
var number_list = std.ArrayList(StackNumberType).init(stack.stack_allocator);
for (to_convert.data.token_list) |t| {
if (t.id != .Number) errors.panic("Failed to convert type TokenList to NumberList. List contains more than just numbers");
try number_list.append(t.data.number);
}
result = stack.create_numberlist(number_list.toOwnedSlice());
},
else => {},
},
.NumberList => switch (result_type) {
.TokenList => {
// NumberLists are always converted back to TokenLists properly (unless something like OOM occurs in which case we cannot do anything reasonable and panic)
var token_list = std.ArrayList(parser.Token).init(stack.stack_allocator);
for (to_convert.data.number_list) |num| {
try token_list.append(parser.Token{ .id = .Number, .start = 0, .data = .{ .number = num } });
}
result = StackItem{ .item_type = .TokenList, .data = .{ .token_list = token_list.toOwnedSlice() } };
},
else => {},
},
}
if (result) |r| {
try stack.list.append(r);
} else {
errors.executor_panic("Unable to convert types ", .{ current_type, result_type });
}
}
fn builtin_define(stack: *Stack) !void {
// This function uses the keyword `global` but I'm not sure if I'm a fan so this may be converted back to the keyword `define` at some later date.
// Either that or `define` becomes global in global scope and local in local scope
const value = stack.list.pop();
const key = stack.list.pop();
if (!stack.item_is(key, .Atom)) {
errors.executor_panic("'define' expected type Atom as key, got type ", key.item_type);
}
// Defines a global variable. Will overwrite.
try stack.variables.put(try stack.stack_allocator.dupe(u8, key.data.text), value);
}
fn builtin_local_define(stack: *Stack) !void {
if (stack.scope_depth == 0) { // If we are in global scope
errors.panic("'local' only valid inside functions.");
}
const value = stack.list.pop();
const key = stack.list.pop();
if (!stack.item_is(key, .Atom)) {
errors.executor_panic("'local' expected type Atom as key, got type ", key.item_type);
}
// Mangles the name to add the scope value before the actual function name.
// We do this to allow functions to not overwrite global scope variables (but shadowing may become an error soon)
// as well as making functions lower down the call stack not overwrite ones higher up the call stack.
// Because functions are variables you are allowed to have local functions which are not exposed globally.
var key_string = std.ArrayList(u8).init(stack.stack_allocator);
defer key_string.deinit();
var scope_as_str = try std.fmt.allocPrint(stack.stack_allocator, "{}", .{stack.scope_depth});
try key_string.appendSlice(scope_as_str);
try key_string.appendSlice(key.data.text);
try stack.variables.put(key_string.toOwnedSlice(), value);
}
fn builtin_if(stack: *Stack) anyerror!void {
const clause = stack.list.pop();
const condition = stack.list.pop();
if (!stack.item_is(clause, .TokenList)) {
errors.executor_panic("'if' expected type TokenList as clause, got type ", clause.item_type);
}
if (!stack.item_is(condition, .Number)) {
errors.executor_panic("'if' expected type Float as condition, got type ", condition.item_type);
}
if (condition.data.number == 1) { // There are no booleans so `1` is effectively `true` and any other number is false
for (clause.data.token_list) |tok| {
try stack.execute_single_token(tok);
}
}
}
fn builtin_ifelse(stack: *Stack) anyerror!void {
const elseclause = stack.list.pop();
const ifclause = stack.list.pop();
const condition = stack.list.pop();
if (!stack.item_is(ifclause, .TokenList)) {
errors.executor_panic("'ifelse' expected type TokenList as first clause, got type ", ifclause.item_type);
}
if (!stack.item_is(elseclause, .TokenList)) {
errors.executor_panic("'ifelse' expected type TokenList as second clause, got type ", elseclause.item_type);
}
if (!stack.item_is(condition, .Number)) {
errors.executor_panic("'ifelse' expected type Number as condition, got type ", condition.item_type);
}
if (condition.data.number == 1) {
for (ifclause.data.token_list) |tok| {
try stack.execute_single_token(tok);
}
} else {
for (elseclause.data.token_list) |tok| {
try stack.execute_single_token(tok);
}
}
}
fn builtin_while(stack: *Stack) anyerror!void {
const clause = stack.list.pop();
const condition = stack.list.pop();
if (!stack.item_is(clause, .TokenList)) {
errors.executor_panic("'while' expected type TokenList as clause, got type ", clause.item_type);
}
if (!stack.item_is(condition, .TokenList)) {
errors.executor_panic("'while' expected type TokenList as condition, got type ", condition.item_type);
}
while (true) {
for (condition.data.token_list) |tok| {
try stack.execute_single_token(tok);
}
if (stack.list.pop().data.number == 0) {
break;
}
for (clause.data.token_list) |tok| {
try stack.execute_single_token(tok);
}
}
}
fn builtin_range(stack: *Stack) !void {
const end = stack.list.pop();
const start = stack.list.pop();
if (!stack.item_is(start, .Number)) {
errors.executor_panic("'range' expected type Number as start, got type ", start.item_type);
}
if (!stack.item_is(end, .Number)) {
errors.executor_panic("'range' expected type Number as end, got type ", end.item_type);
}
var i = start.data.number;
var number_list = std.ArrayList(StackNumberType).init(stack.stack_allocator);
while (i < end.data.number) : (i += 1) {
try number_list.append(i);
}
try stack.append(stack.create_numberlist(number_list.toOwnedSlice()));
}
fn builtin_for(stack: *Stack) anyerror!void {
const clause = stack.list.pop();
const var_name = stack.list.pop();
const list = stack.list.pop();
if (!stack.item_is(clause, .TokenList)) {
errors.executor_panic("'for' expected type TokenList as clause, got type ", clause.item_type);
}
if (!stack.item_is(var_name, .Atom)) {
errors.executor_panic("'for' expected type Atom as iterator variable, got type ", var_name.item_type);
}
if (!stack.item_is(list, .NumberList)) {
errors.executor_panic("'for' expected type NumberList as the list to iterate over, got type ", list.item_type);
}
switch (list.item_type) {
.NumberList => {
for (list.data.number_list) |fl| {
try stack.variables.put(var_name.data.text, stack.create_number(fl));
for (clause.data.token_list) |tok| {
try stack.execute_single_token(tok);
}
}
},
else => unreachable,
}
}
fn builtin_print(stack: *Stack) !void {
const top = stack.list.pop();
switch (top.item_type) {
.Atom, .String => {
print("{s}", .{top.data.text});
},
.Number => {
print("{d}", .{top.data.number});
},
.NumberList => {
print("[", .{});
for (top.data.number_list) |n| {
print("{d}, ", .{n});
}
print("]", .{});
},
else => {},
}
print("\n", .{});
}
fn builtin_dup(stack: *Stack) !void {
const top = stack.list.pop();
try stack.append(top);
try stack.append(top);
}
fn builtin_swap(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
try stack.append(a);
try stack.append(b);
}
//
// Arithmetic Operators
//
fn operator_plus(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
if (!(stack.item_is(a, .Number) and stack.item_is(b, .Number))) {
errors.executor_panic("Addition operator requires two numbers, got ", .{ b.item_type, a.item_type });
}
try stack.append(stack.create_number(b.data.number + a.data.number));
}
fn operator_minus(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
if (!(stack.item_is(a, .Number) and stack.item_is(b, .Number))) {
errors.executor_panic("Subtraction operator requires two numbers, got ", .{ b.item_type, a.item_type });
}
try stack.append(stack.create_number(b.data.number - a.data.number));
}
fn operator_divide(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
if (!(stack.item_is(a, .Number) and stack.item_is(b, .Number))) {
errors.executor_panic("Division operator requires two numbers, got ", .{ b.item_type, a.item_type });
}
try stack.append(stack.create_number(b.data.number / a.data.number));
}
fn operator_multiply(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
if (!(stack.item_is(a, .Number) and stack.item_is(b, .Number))) {
errors.executor_panic("Multiplication operator requires two numbers, got ", .{ b.item_type, a.item_type });
}
try stack.append(stack.create_number(b.data.number * a.data.number));
}
fn operator_modulo(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
if (!(stack.item_is(a, .Number) and stack.item_is(b, .Number))) {
errors.executor_panic("Modulus operator requires two numbers, got ", .{ b.item_type, a.item_type });
}
try stack.append(stack.create_number(@rem(b.data.number, a.data.number)));
}
//
// Boolean Operators
//
fn operator_eq(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
if (!(stack.item_is(a, .Number) and stack.item_is(b, .Number))) {
errors.executor_panic("Equality operator requires two numbers, got ", .{ b.item_type, a.item_type });
}
try stack.append(stack.create_number(@intToFloat(StackNumberType, @boolToInt(b.data.number == a.data.number))));
}
fn operator_neq(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
if (!(stack.item_is(a, .Number) and stack.item_is(b, .Number))) {
errors.executor_panic("Not equal to operator requires two numbers, got ", .{ b.item_type, a.item_type });
}
try stack.append(stack.create_number(@intToFloat(StackNumberType, @boolToInt(b.data.number != a.data.number))));
}
fn operator_lt(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
if (!(stack.item_is(a, .Number) and stack.item_is(b, .Number))) {
errors.executor_panic("Less than requires two numbers, got ", .{ b.item_type, a.item_type });
}
try stack.append(stack.create_number(@intToFloat(StackNumberType, @boolToInt(b.data.number < a.data.number))));
}
fn operator_gt(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
if (!(stack.item_is(a, .Number) and stack.item_is(b, .Number))) {
errors.executor_panic("Greater than requires two numbers, got ", .{ b.item_type, a.item_type });
}
try stack.append(stack.create_number(@intToFloat(StackNumberType, @boolToInt(b.data.number > a.data.number))));
}
fn operator_lteq(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
if (!(stack.item_is(a, .Number) and stack.item_is(b, .Number))) {
errors.executor_panic("Less than or equal operator requires two numbers, got ", .{ b.item_type, a.item_type });
}
try stack.append(stack.create_number(@intToFloat(StackNumberType, @boolToInt(b.data.number <= a.data.number))));
}
fn operator_gteq(stack: *Stack) !void {
const a = stack.list.pop();
const b = stack.list.pop();
if (!(stack.item_is(a, .Number) and stack.item_is(b, .Number))) {
errors.executor_panic("Greater than or equal operator requires two numbers, got ", .{ b.item_type, a.item_type });
}
try stack.append(stack.create_number(@intToFloat(StackNumberType, @boolToInt(b.data.number >= a.data.number))));
}
// TODO bitwise operations but that may require an int type | src/executor.zig |
const std = @import("std");
const core = @import("core");
const game_server = @import("../server/game_server.zig");
const SomeQueues = @import("../client/game_engine_client.zig").SomeQueues;
const Socket = core.protocol.Socket;
const Request = core.protocol.Request;
const Response = core.protocol.Response;
const allocator = std.heap.c_allocator;
const FdToQueueAdapter = struct {
socket: Socket,
send_thread: *std.Thread,
recv_thread: *std.Thread,
queues: *SomeQueues,
pub fn init(
self: *FdToQueueAdapter,
in_stream: std.fs.File.Reader,
out_stream: std.fs.File.Writer,
queues: *SomeQueues,
) !void {
self.socket = Socket.init(in_stream, out_stream);
self.queues = queues;
self.send_thread = try std.Thread.spawn(self, sendMain);
self.recv_thread = try std.Thread.spawn(self, recvMain);
}
pub fn wait(self: *FdToQueueAdapter) void {
self.send_thread.wait();
self.recv_thread.wait();
}
fn sendMain(self: *FdToQueueAdapter) void {
core.debug.nameThisThread("server send");
defer core.debug.unnameThisThread();
core.debug.thread_lifecycle.print("init", .{});
defer core.debug.thread_lifecycle.print("shutdown", .{});
while (true) {
const msg = self.queues.waitAndTakeResponse() orelse {
core.debug.thread_lifecycle.print("clean shutdown", .{});
break;
};
self.socket.out().write(msg) catch |err| {
@panic("TODO: proper error handling");
};
}
}
fn recvMain(self: *FdToQueueAdapter) void {
core.debug.nameThisThread("server recv");
defer core.debug.unnameThisThread();
core.debug.thread_lifecycle.print("init", .{});
defer core.debug.thread_lifecycle.print("shutdown", .{});
while (true) {
const msg = self.socket.in(allocator).read(Request) catch |err| {
switch (err) {
error.EndOfStream => {
core.debug.thread_lifecycle.print("clean shutdown", .{});
self.queues.closeRequests();
break;
},
else => @panic("TODO: proper error handling"),
}
};
self.queues.enqueueRequest(msg) catch |err| {
@panic("TODO: proper error handling");
};
}
}
};
pub fn main() anyerror!void {
core.debug.init();
core.debug.nameThisThread("server process");
defer core.debug.unnameThisThread();
core.debug.thread_lifecycle.print("init", .{});
defer core.debug.thread_lifecycle.print("shutdown", .{});
var queues: SomeQueues = undefined;
queues.init();
var adapter: FdToQueueAdapter = undefined;
try adapter.init(
std.io.getStdIn().reader(),
std.io.getStdOut().writer(),
&queues,
);
defer {
core.debug.thread_lifecycle.print("join adapter threads", .{});
adapter.wait();
}
return game_server.server_main(&queues);
} | src/server/server_main.zig |
const gpio = @import("../gpio.zig");
const cpu = @import("../cpu.zig");
// hacked from
// from https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTlib
// and the spec: https://www.gotronic.fr/pj-1052.pdf
// clang11? doesn't seem to like error unions...
// --> hack it for now
const HackError = enum(u8) {
OK,
BAD_CHECKSUM,
NO_CONNECTION,
NO_ACK,
INTERRUPTED,
};
pub const Readout = struct { humidity_x10: i16, temperature_x10: i16, err: HackError }; // fixedpoint values. divide by 10 for the actual flaot value
pub fn DHT22(comptime sensor_data_pin: u8) type {
return struct {
pub fn read() Readout {
const r = readSensor(sensor_data_pin);
if (r.err != .OK) { // HackError
return .{ .humidity_x10 = 0, .temperature_x10 = 0, .err = r.err };
}
return convertRawSensor(r.raw);
}
fn convertRawSensor(raw: u40) Readout {
var sensor: packed union { // little endian
raw: u40,
bytes: [5]u8,
values: packed struct {
checksum: u8,
temp: u15,
temp_sign: u1,
hum: u16,
},
} = .{ .raw = raw };
const checksum = sensor.bytes[4] +% sensor.bytes[1] +% sensor.bytes[2] +% sensor.bytes[3];
if (checksum != sensor.values.checksum)
return .{ .humidity_x10 = 0, .temperature_x10 = 0, .err = .BAD_CHECKSUM };
return Readout{
.humidity_x10 = @intCast(i16, sensor.values.hum),
.temperature_x10 = if (sensor.values.temp_sign != 0) -@as(i16, sensor.values.temp) else @as(i16, sensor.values.temp),
.err = .OK,
};
}
const TIMEOUT_100us = (100 * cpu.CPU_FREQ / 1_000_000) / 4; // ~4 cycles per loop
fn waitPinState(comptime pin: u8, state: gpio.PinState, timeout: u16) bool {
var loop_count: u16 = timeout;
while (loop_count > 0) : (loop_count -= 1) {
if (gpio.getPin(pin) == state)
return true;
}
return false;
}
fn readSensor(comptime pin: u8) struct { raw: u40 = 0, err: HackError = .OK } {
const wakeup_delay = 1;
const leading_zero_bits = 6;
// single wire protocol
// SEND THE QUERY and wait for the ACK
{
// "host pulls low >1ms"
gpio.setMode(pin, .output);
gpio.setPin(pin, .low);
cpu.delayMicroseconds(wakeup_delay * 1000); // 1ms
// "host pulls up and wait for sensor response"
gpio.setPin(pin, .high);
gpio.setMode(pin, .input_pullup);
if (!waitPinState(pin, .low, TIMEOUT_100us * 2)) return .{ .err = .NO_CONNECTION }; // 40+80us
if (!waitPinState(pin, .high, TIMEOUT_100us)) return .{ .err = .NO_ACK }; // 80us
if (!waitPinState(pin, .low, TIMEOUT_100us)) return .{ .err = .NO_ACK }; // 80us
}
// READ THE OUTPUT - 40 BITS
var zero_loop_len: u16 = TIMEOUT_100us / 4; // autocalibrate knowing there are leading zeros (not checked with an oscilloscope or anything)
var result: u40 = 0;
var bit_idx: u8 = 0;
while (bit_idx < 40) : (bit_idx += 1) {
if (!waitPinState(pin, .high, TIMEOUT_100us)) return .{ .err = .INTERRUPTED }; // 50us
// measure time to get low:
const duration = blk: {
var loop_count: u16 = TIMEOUT_100us;
while (loop_count > 0) : (loop_count -= 1) {
if (gpio.getPin(pin) == .low)
break :blk (TIMEOUT_100us - loop_count);
}
return .{ .err = .INTERRUPTED }; // 70us
};
if (bit_idx < leading_zero_bits) {
if (zero_loop_len < duration)
zero_loop_len = duration; // max observed time to get zero
} else {
const is_one = duration > zero_loop_len; // exceeded zero duration
result = (result << 1) | @boolToInt(is_one);
}
}
return .{ .raw = result };
}
};
} | src/lib/dht.zig |
// // ----------------------------------------------------------------------------
// // Second stage boot code
// // Copyright (c) 2019-2021 Raspberry Pi (Trading) Ltd.
// // SPDX-License-Identifier: BSD-3-Clause
// End of the original license notice.
// The long story about why I rewrite the bootloader in Zig:
// To make your program work on a RP2040, you must link it against the second stage
// bootloader, which prepares the MCU's XIP and the external flash to run your code
// at the best performance. Normally, the SDK will build and stick the bootloader
// binary to your executable in the SDK's build process. However, the SDK is
// developed to work with codes written in C/C++ language, and there is no simple way
// to integrate the build process with the Zig's build script (maybe I'm missing
// something). So I decided to write the same code as the bootloader in Zig to
// make the build process simple as all you have to do is to run `zig build`.
const regs = @import("rp2040_ras");
fn boot2_main() callconv(.Naked) noreturn {
asm volatile (
\\push {lr}
);
regs.PADS_QSPI.GPIO_QSPI_SCLK.write(.{ .DRIVE = 0x2, .SLEWFAST = 1 });
regs.PADS_QSPI.GPIO_QSPI_SD0.modify(.{ .SCHMITT = 0 });
const sd0 = regs.PADS_QSPI.GPIO_QSPI_SD0.read_raw();
regs.PADS_QSPI.GPIO_QSPI_SD1.write_raw(sd0);
regs.PADS_QSPI.GPIO_QSPI_SD2.write_raw(sd0);
regs.PADS_QSPI.GPIO_QSPI_SD3.write_raw(sd0);
regs.XIP_SSI.SSIENR.write(.{ .SSI_EN = 0 });
regs.XIP_SSI.BAUDR.write(.{ .SCKDV = 4 }); // TODO: Replace the parameter with a constant or a build option value.
regs.XIP_SSI.RX_SAMPLE_DLY.write(.{ .RSD = 1 });
regs.XIP_SSI.CTRLR0.write(.{ .DFS_32 = 7, .TMOD = 0 });
regs.XIP_SSI.SSIENR.write(.{ .SSI_EN = 1 });
if (read_flash_sreg(0x35) != 0x02) {
regs.XIP_SSI.DR0.write_raw(0x06);
wait_ssi_ready();
_ = regs.XIP_SSI.DR0.read_raw();
regs.XIP_SSI.DR0.write_raw(0x01);
regs.XIP_SSI.DR0.write_raw(0x00);
regs.XIP_SSI.DR0.write_raw(0x02);
wait_ssi_ready();
_ = regs.XIP_SSI.DR0.read_raw();
_ = regs.XIP_SSI.DR0.read_raw();
_ = regs.XIP_SSI.DR0.read_raw();
while (read_flash_sreg(0x05) & 1 == 0) {}
}
regs.XIP_SSI.SSIENR.write(.{ .SSI_EN = 0 });
regs.XIP_SSI.CTRLR0.write(.{ .SPI_FRF = 2, .DFS_32 = 31, .TMOD = 3 });
regs.XIP_SSI.CTRLR1.write(.{ .NDF = 0 });
regs.XIP_SSI.SPI_CTRLR0.write(.{ .ADDR_L = 8, .WAIT_CYCLES = 4, .INST_L = 2, .TRANS_TYPE = 1 });
regs.XIP_SSI.SSIENR.write(.{ .SSI_EN = 1 });
regs.XIP_SSI.DR0.write_raw(0xEB);
regs.XIP_SSI.DR0.write_raw(0xA0);
wait_ssi_ready();
regs.XIP_SSI.SSIENR.write(.{ .SSI_EN = 0 });
regs.XIP_SSI.SPI_CTRLR0.write(.{ .XIP_CMD = 0xA0, .ADDR_L = 8, .WAIT_CYCLES = 4, .INST_L = 0, .TRANS_TYPE = 2 });
regs.XIP_SSI.SSIENR.write(.{ .SSI_EN = 1 });
asm volatile (
\\ pop {r0}
\\ cmp r0, #0
\\ beq skip_return
\\ bx r0
\\ skip_return:
\\ ldr r0, =0x10000100
\\ ldr r1, =0xE000ED08
\\ str r0, [r1]
\\ ldmia r0, {r0, r1}
\\ msr msp, r0
\\ bx r1
);
while (true) {}
}
inline fn read_flash_sreg(cmd: u32) u32 {
regs.XIP_SSI.DR0.write_raw(cmd);
regs.XIP_SSI.DR0.write_raw(cmd);
wait_ssi_ready();
_ = regs.XIP_SSI.DR0.read_raw();
return regs.XIP_SSI.DR0.read_raw();
}
inline fn wait_ssi_ready() void {
while (regs.XIP_SSI.SR.read().TFE == 0) {}
while (regs.XIP_SSI.SR.read().BUSY != 0) {}
}
comptime {
@export(boot2_main, .{
.name = "_boot2_main",
.linkage = .Strong,
.section = ".boot2",
});
} | src/ipl/w25q080.zig |
const std = @import("std");
const vector = @import("vector.zig");
const Vec4 = Vec4;
const initPoint = vector.initPoint;
const initVector = vector.initVector;
const Mat4 = @import("matrix.zig").Mat4;
const Canvas = @import("canvas.zig").Canvas;
const Color = @import("color.zig").Color;
const canvasToPPM = @import("ppm.zig").canvasToPPM;
const Sphere = @import("sphere.zig").Sphere;
const Ray = @import("ray.zig").Ray;
const Material = @import("material.zig").Material;
const PointLight = @import("light.zig").PointLight;
const calc = @import("calc.zig");
const CanvasSize = 400;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var canvas = try Canvas.init(allocator, CanvasSize, CanvasSize);
defer canvas.deinit();
const material = Material{
.color = Color.init(1.0, 0.2, 1.0),
};
const shape = Sphere{
.transform = Mat4.identity(),
.material = material,
};
const origin = initPoint(0, 0, -5);
const wall_z = 10.0;
const wall_size: f64 = 7.0;
const pixel_size = wall_size / @intToFloat(f64, CanvasSize);
const half = 0.5 * wall_size;
const light = PointLight{
.intensity = Color.White,
.position = initPoint(-10, 10, -10),
};
var y: usize = 0;
while (y < canvas.height) : (y += 1) {
const world_y = half - @intToFloat(f64, y) * pixel_size;
var x: usize = 0;
while (x < canvas.height) : (x += 1) {
_ = 1;
const world_x = -half + @intToFloat(f64, x) * pixel_size;
const wall_pos = initPoint(world_x, world_y, wall_z);
const ray_dir = wall_pos.sub(origin).normalize();
const ray = Ray.init(origin, ray_dir);
var xs = try calc.intersectSphere(allocator, shape, ray);
defer xs.deinit();
const hit = xs.hit();
if (hit != null) {
const point = ray.position(hit.?.t);
const normal = calc.sphereNormalAt(hit.?.object, point);
const eye = ray_dir.negate();
const color = calc.lighting(
hit.?.object.material,
light,
point,
eye,
normal,
);
canvas.set(x, y, color);
}
}
}
const dir: std.fs.Dir = std.fs.cwd();
const file: std.fs.File = try dir.createFile("/tmp/result.ppm", .{});
defer file.close();
try canvasToPPM(canvas, file.writer());
} | draw_sphere.zig |
const std = @import("std");
const zgt = @import("zgt");
pub usingnamespace zgt.cross_platform;
// Short names to avoid writing 'zgt.' each time
const Button = zgt.Button;
const Margin = zgt.Margin;
const Expanded = zgt.Expanded;
const Row = zgt.Row;
const Allocator = std.mem.Allocator;
var computationLabel: zgt.Label_Impl = undefined;
var allocator: Allocator = undefined;
pub fn pressedKey(button: *zgt.Button_Impl) !void {
const buttonLabel = button.getLabel();
const labelText = computationLabel.getText();
// Concat the computation label with the first character of the button's label
var larger = try allocator.allocSentinel(u8, labelText.len + 1, 0); // allocate a null-terminated string one character longer than labelText
std.mem.copy(u8, larger, labelText); // copy labelText's contents to the newly allocated string
larger[labelText.len] = buttonLabel[0]; // finally, set the last letter
computationLabel.setText(larger); // and now we can put that as our new computation label text
allocator.free(larger);
}
pub fn erase(button: *zgt.Button_Impl) !void {
_ = button;
computationLabel.setText("");
}
fn findOperator(computation: []const u8, pos: usize) ?usize {
return std.mem.indexOfScalarPos(u8, computation, pos, '+')
orelse std.mem.indexOfScalarPos(u8, computation, pos, '-')
orelse std.mem.indexOfScalarPos(u8, computation, pos, '*')
orelse std.mem.indexOfScalarPos(u8, computation, pos, '/');
}
pub fn compute(button: *zgt.Button_Impl) !void {
_ = button;
const rawText = computationLabel.getText();
const computation = rawText;
const FloatType = f64;
var result: FloatType = 0;
var pos: usize = 0;
while (true) {
const op = findOperator(computation, pos);
if (op) |operator| {
const leftHand = computation[pos..operator];
const end = findOperator(computation, operator+1) orelse computation.len;
const rightHand = computation[operator+1..end];
const leftHandNum = std.fmt.parseFloat(FloatType, leftHand) catch std.math.nan(FloatType);
const rightHandNum = std.fmt.parseFloat(FloatType, rightHand) catch std.math.nan(FloatType);
if (pos == 0) result = leftHandNum;
switch (computation[operator]) {
'+' => result += rightHandNum,
'-' => result -= rightHandNum,
'*' => result *= rightHandNum,
'/' => result /= rightHandNum,
else => unreachable
}
pos = end;
} else {
if (pos == 0) {
result = std.fmt.parseFloat(FloatType, computation) catch std.math.nan(FloatType);
}
break;
}
}
const text = try std.fmt.allocPrintZ(allocator, "{d}", .{result});
computationLabel.setText(text);
}
pub fn main() !void {
try zgt.backend.init();
var gpa = std.heap.GeneralPurposeAllocator(.{}) {};
defer _ = gpa.deinit();
allocator = gpa.allocator();
var window = try zgt.Window.init();
computationLabel = zgt.Label(.{ .text = "", .alignment = .Left });
try window.set(zgt.Column(.{ .expand = .Fill }, .{
&computationLabel,
Expanded(Row(.{ .expand = .Fill }, .{
Margin(Button(.{ .label = "7", .onclick = pressedKey })),
Margin(Button(.{ .label = "8", .onclick = pressedKey })),
Margin(Button(.{ .label = "9", .onclick = pressedKey })),
Margin(Button(.{ .label = "+", .onclick = pressedKey })),
})),
Expanded(Row(.{ .expand = .Fill }, .{
Margin(Button(.{ .label = "4", .onclick = pressedKey })),
Margin(Button(.{ .label = "5", .onclick = pressedKey })),
Margin(Button(.{ .label = "6", .onclick = pressedKey })),
Margin(Button(.{ .label = "-", .onclick = pressedKey })),
})),
Expanded(Row(.{ .expand = .Fill }, .{
Margin(Button(.{ .label = "1", .onclick = pressedKey })),
Margin(Button(.{ .label = "2", .onclick = pressedKey })),
Margin(Button(.{ .label = "3", .onclick = pressedKey })),
Margin(Button(.{ .label = "*", .onclick = pressedKey })),
})),
Expanded(Row(.{ .expand = .Fill }, .{
Margin(Button(.{ .label = "/" , .onclick = pressedKey })),
Margin(Button(.{ .label = "0" , .onclick = pressedKey })),
Margin(Button(.{ .label = "CE", .onclick = erase })),
Margin(Button(.{ .label = "." , .onclick = pressedKey }))
})),
Expanded(Button(.{ .label = "=", .onclick = compute }))
}));
window.resize(400, 500);
window.show();
zgt.runEventLoop();
} | examples/calculator.zig |
const MachO = @This();
const std = @import("std");
const build_options = @import("build_options");
const builtin = @import("builtin");
const assert = std.debug.assert;
const fmt = std.fmt;
const fs = std.fs;
const log = std.log.scoped(.link);
const macho = std.macho;
const math = std.math;
const mem = std.mem;
const meta = std.meta;
const aarch64 = @import("../arch/aarch64/bits.zig");
const bind = @import("MachO/bind.zig");
const codegen = @import("../codegen.zig");
const link = @import("../link.zig");
const llvm_backend = @import("../codegen/llvm.zig");
const target_util = @import("../target.zig");
const trace = @import("../tracy.zig").trace;
const Air = @import("../Air.zig");
const Allocator = mem.Allocator;
const Archive = @import("MachO/Archive.zig");
const Atom = @import("MachO/Atom.zig");
const Cache = @import("../Cache.zig");
const CodeSignature = @import("MachO/CodeSignature.zig");
const Compilation = @import("../Compilation.zig");
const Dylib = @import("MachO/Dylib.zig");
const File = link.File;
const Object = @import("MachO/Object.zig");
const LibStub = @import("tapi.zig").LibStub;
const Liveness = @import("../Liveness.zig");
const LlvmObject = @import("../codegen/llvm.zig").Object;
const Module = @import("../Module.zig");
const StringIndexAdapter = std.hash_map.StringIndexAdapter;
const StringIndexContext = std.hash_map.StringIndexContext;
const Trie = @import("MachO/Trie.zig");
const Type = @import("../type.zig").Type;
const TypedValue = @import("../TypedValue.zig");
const Value = @import("../value.zig").Value;
pub const TextBlock = Atom;
pub const DebugSymbols = @import("MachO/DebugSymbols.zig");
pub const base_tag: File.Tag = File.Tag.macho;
base: File,
/// If this is not null, an object file is created by LLVM and linked with LLD afterwards.
llvm_object: ?*LlvmObject = null,
/// Debug symbols bundle (or dSym).
d_sym: ?DebugSymbols = null,
/// Page size is dependent on the target cpu architecture.
/// For x86_64 that's 4KB, whereas for aarch64, that's 16KB.
page_size: u16,
/// TODO Should we figure out embedding code signatures for other Apple platforms as part of the linker?
/// Or should this be a separate tool?
/// https://github.com/ziglang/zig/issues/9567
requires_adhoc_codesig: bool,
/// If true, the linker will preallocate several sections and segments before starting the linking
/// process. This is for example true for stage2 debug builds, however, this is false for stage1
/// and potentially stage2 release builds in the future.
needs_prealloc: bool = true,
/// We commit 0x1000 = 4096 bytes of space to the header and
/// the table of load commands. This should be plenty for any
/// potential future extensions.
header_pad: u16 = 0x1000,
/// The absolute address of the entry point.
entry_addr: ?u64 = null,
objects: std.ArrayListUnmanaged(Object) = .{},
archives: std.ArrayListUnmanaged(Archive) = .{},
dylibs: std.ArrayListUnmanaged(Dylib) = .{},
dylibs_map: std.StringHashMapUnmanaged(u16) = .{},
referenced_dylibs: std.AutoArrayHashMapUnmanaged(u16, void) = .{},
load_commands: std.ArrayListUnmanaged(macho.LoadCommand) = .{},
pagezero_segment_cmd_index: ?u16 = null,
text_segment_cmd_index: ?u16 = null,
data_const_segment_cmd_index: ?u16 = null,
data_segment_cmd_index: ?u16 = null,
linkedit_segment_cmd_index: ?u16 = null,
dyld_info_cmd_index: ?u16 = null,
symtab_cmd_index: ?u16 = null,
dysymtab_cmd_index: ?u16 = null,
dylinker_cmd_index: ?u16 = null,
data_in_code_cmd_index: ?u16 = null,
function_starts_cmd_index: ?u16 = null,
main_cmd_index: ?u16 = null,
dylib_id_cmd_index: ?u16 = null,
source_version_cmd_index: ?u16 = null,
build_version_cmd_index: ?u16 = null,
uuid_cmd_index: ?u16 = null,
code_signature_cmd_index: ?u16 = null,
// __TEXT segment sections
text_section_index: ?u16 = null,
stubs_section_index: ?u16 = null,
stub_helper_section_index: ?u16 = null,
text_const_section_index: ?u16 = null,
cstring_section_index: ?u16 = null,
ustring_section_index: ?u16 = null,
gcc_except_tab_section_index: ?u16 = null,
unwind_info_section_index: ?u16 = null,
eh_frame_section_index: ?u16 = null,
objc_methlist_section_index: ?u16 = null,
objc_methname_section_index: ?u16 = null,
objc_methtype_section_index: ?u16 = null,
objc_classname_section_index: ?u16 = null,
// __DATA_CONST segment sections
got_section_index: ?u16 = null,
mod_init_func_section_index: ?u16 = null,
mod_term_func_section_index: ?u16 = null,
data_const_section_index: ?u16 = null,
objc_cfstring_section_index: ?u16 = null,
objc_classlist_section_index: ?u16 = null,
objc_imageinfo_section_index: ?u16 = null,
// __DATA segment sections
tlv_section_index: ?u16 = null,
tlv_data_section_index: ?u16 = null,
tlv_bss_section_index: ?u16 = null,
tlv_ptrs_section_index: ?u16 = null,
la_symbol_ptr_section_index: ?u16 = null,
data_section_index: ?u16 = null,
bss_section_index: ?u16 = null,
objc_const_section_index: ?u16 = null,
objc_selrefs_section_index: ?u16 = null,
objc_classrefs_section_index: ?u16 = null,
objc_data_section_index: ?u16 = null,
rustc_section_index: ?u16 = null,
rustc_section_size: u64 = 0,
locals: std.ArrayListUnmanaged(macho.nlist_64) = .{},
globals: std.ArrayListUnmanaged(macho.nlist_64) = .{},
undefs: std.ArrayListUnmanaged(macho.nlist_64) = .{},
symbol_resolver: std.AutoHashMapUnmanaged(u32, SymbolWithLoc) = .{},
unresolved: std.AutoArrayHashMapUnmanaged(u32, enum {
none,
stub,
got,
}) = .{},
tentatives: std.AutoArrayHashMapUnmanaged(u32, void) = .{},
locals_free_list: std.ArrayListUnmanaged(u32) = .{},
globals_free_list: std.ArrayListUnmanaged(u32) = .{},
mh_execute_header_index: ?u32 = null,
dyld_stub_binder_index: ?u32 = null,
dyld_private_atom: ?*Atom = null,
stub_helper_preamble_atom: ?*Atom = null,
strtab: std.ArrayListUnmanaged(u8) = .{},
strtab_dir: std.HashMapUnmanaged(u32, void, StringIndexContext, std.hash_map.default_max_load_percentage) = .{},
tlv_ptr_entries: std.ArrayListUnmanaged(Entry) = .{},
tlv_ptr_entries_free_list: std.ArrayListUnmanaged(u32) = .{},
tlv_ptr_entries_table: std.AutoArrayHashMapUnmanaged(Atom.Relocation.Target, u32) = .{},
got_entries: std.ArrayListUnmanaged(Entry) = .{},
got_entries_free_list: std.ArrayListUnmanaged(u32) = .{},
got_entries_table: std.AutoArrayHashMapUnmanaged(Atom.Relocation.Target, u32) = .{},
stubs: std.ArrayListUnmanaged(*Atom) = .{},
stubs_free_list: std.ArrayListUnmanaged(u32) = .{},
stubs_table: std.AutoArrayHashMapUnmanaged(u32, u32) = .{},
error_flags: File.ErrorFlags = File.ErrorFlags{},
load_commands_dirty: bool = false,
sections_order_dirty: bool = false,
has_dices: bool = false,
has_stabs: bool = false,
/// A helper var to indicate if we are at the start of the incremental updates, or
/// already somewhere further along the update-and-run chain.
/// TODO once we add opening a prelinked output binary from file, this will become
/// obsolete as we will carry on where we left off.
cold_start: bool = false,
invalidate_relocs: bool = false,
section_ordinals: std.AutoArrayHashMapUnmanaged(MatchingSection, void) = .{},
/// A list of atoms that have surplus capacity. This list can have false
/// positives, as functions grow and shrink over time, only sometimes being added
/// or removed from the freelist.
///
/// An atom has surplus capacity when its overcapacity value is greater than
/// padToIdeal(minimum_atom_size). That is, when it has so
/// much extra capacity, that we could fit a small new symbol in it, itself with
/// ideal_capacity or more.
///
/// Ideal capacity is defined by size + (size / ideal_factor).
///
/// Overcapacity is measured by actual_capacity - ideal_capacity. Note that
/// overcapacity can be negative. A simple way to have negative overcapacity is to
/// allocate a fresh atom, which will have ideal capacity, and then grow it
/// by 1 byte. It will then have -1 overcapacity.
atom_free_lists: std.AutoHashMapUnmanaged(MatchingSection, std.ArrayListUnmanaged(*Atom)) = .{},
/// Pointer to the last allocated atom
atoms: std.AutoHashMapUnmanaged(MatchingSection, *Atom) = .{},
/// List of atoms that are owned directly by the linker.
/// Currently these are only atoms that are the result of linking
/// object files. Atoms which take part in incremental linking are
/// at present owned by Module.Decl.
/// TODO consolidate this.
managed_atoms: std.ArrayListUnmanaged(*Atom) = .{},
atom_by_index_table: std.AutoHashMapUnmanaged(u32, *Atom) = .{},
/// Table of unnamed constants associated with a parent `Decl`.
/// We store them here so that we can free the constants whenever the `Decl`
/// needs updating or is freed.
///
/// For example,
///
/// ```zig
/// const Foo = struct{
/// a: u8,
/// };
///
/// pub fn main() void {
/// var foo = Foo{ .a = 1 };
/// _ = foo;
/// }
/// ```
///
/// value assigned to label `foo` is an unnamed constant belonging/associated
/// with `Decl` `main`, and lives as long as that `Decl`.
unnamed_const_atoms: UnnamedConstTable = .{},
/// Table of Decls that are currently alive.
/// We store them here so that we can properly dispose of any allocated
/// memory within the atom in the incremental linker.
/// TODO consolidate this.
decls: std.AutoArrayHashMapUnmanaged(*Module.Decl, ?MatchingSection) = .{},
const Entry = struct {
target: Atom.Relocation.Target,
atom: *Atom,
};
const UnnamedConstTable = std.AutoHashMapUnmanaged(*Module.Decl, std.ArrayListUnmanaged(*Atom));
const PendingUpdate = union(enum) {
resolve_undef: u32,
add_stub_entry: u32,
add_got_entry: u32,
};
const SymbolWithLoc = struct {
// Table where the symbol can be found.
where: enum {
global,
undef,
},
where_index: u32,
local_sym_index: u32 = 0,
file: ?u16 = null, // null means Zig module
};
/// When allocating, the ideal_capacity is calculated by
/// actual_capacity + (actual_capacity / ideal_factor)
const ideal_factor = 4;
/// Default path to dyld
const default_dyld_path: [*:0]const u8 = "/usr/lib/dyld";
/// In order for a slice of bytes to be considered eligible to keep metadata pointing at
/// it as a possible place to put new symbols, it must have enough room for this many bytes
/// (plus extra for reserved capacity).
const minimum_text_block_size = 64;
pub const min_text_capacity = padToIdeal(minimum_text_block_size);
/// Virtual memory offset corresponds to the size of __PAGEZERO segment and start of
/// __TEXT segment.
const pagezero_vmsize: u64 = 0x100000000;
pub const Export = struct {
sym_index: ?u32 = null,
};
pub fn openPath(allocator: Allocator, options: link.Options) !*MachO {
assert(options.object_format == .macho);
const use_stage1 = build_options.is_stage1 and options.use_stage1;
if (use_stage1 or options.emit == null) {
return createEmpty(allocator, options);
}
const emit = options.emit.?;
const file = try emit.directory.handle.createFile(emit.sub_path, .{
.truncate = false,
.read = true,
.mode = link.determineMode(options),
});
errdefer file.close();
const self = try createEmpty(allocator, options);
errdefer {
self.base.file = null;
self.base.destroy();
}
self.base.file = file;
if (build_options.have_llvm and options.use_llvm and options.module != null) {
// TODO this intermediary_basename isn't enough; in the case of `zig build-exe`,
// we also want to put the intermediary object file in the cache while the
// main emit directory is the cwd.
self.llvm_object = try LlvmObject.create(allocator, options);
self.base.intermediary_basename = try std.fmt.allocPrint(allocator, "{s}{s}", .{
emit.sub_path, options.object_format.fileExt(options.target.cpu.arch),
});
}
if (options.output_mode == .Lib and
options.link_mode == .Static and self.base.intermediary_basename != null)
{
return self;
}
if (!options.strip and options.module != null) {
// Create dSYM bundle.
const dir = options.module.?.zig_cache_artifact_directory;
log.debug("creating {s}.dSYM bundle in {s}", .{ emit.sub_path, dir.path });
const d_sym_path = try fmt.allocPrint(
allocator,
"{s}.dSYM" ++ fs.path.sep_str ++ "Contents" ++ fs.path.sep_str ++ "Resources" ++ fs.path.sep_str ++ "DWARF",
.{emit.sub_path},
);
defer allocator.free(d_sym_path);
var d_sym_bundle = try dir.handle.makeOpenPath(d_sym_path, .{});
defer d_sym_bundle.close();
const d_sym_file = try d_sym_bundle.createFile(emit.sub_path, .{
.truncate = false,
.read = true,
});
self.d_sym = .{
.base = self,
.dwarf = link.File.Dwarf.init(allocator, .macho, options.target),
.file = d_sym_file,
};
}
// Index 0 is always a null symbol.
try self.locals.append(allocator, .{
.n_strx = 0,
.n_type = 0,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
try self.strtab.append(allocator, 0);
try self.populateMissingMetadata();
if (self.d_sym) |*d_sym| {
try d_sym.populateMissingMetadata(allocator);
}
return self;
}
pub fn createEmpty(gpa: Allocator, options: link.Options) !*MachO {
const cpu_arch = options.target.cpu.arch;
const os_tag = options.target.os.tag;
const abi = options.target.abi;
const page_size: u16 = if (cpu_arch == .aarch64) 0x4000 else 0x1000;
// Adhoc code signature is required when targeting aarch64-macos either directly or indirectly via the simulator
// ABI such as aarch64-ios-simulator, etc.
const requires_adhoc_codesig = cpu_arch == .aarch64 and (os_tag == .macos or abi == .simulator);
const use_stage1 = build_options.is_stage1 and options.use_stage1;
const needs_prealloc = !(use_stage1 or options.cache_mode == .whole);
const self = try gpa.create(MachO);
errdefer gpa.destroy(self);
self.* = .{
.base = .{
.tag = .macho,
.options = options,
.allocator = gpa,
.file = null,
},
.page_size = page_size,
.requires_adhoc_codesig = requires_adhoc_codesig,
.needs_prealloc = needs_prealloc,
};
const use_llvm = build_options.have_llvm and options.use_llvm;
if (use_llvm and !use_stage1) {
self.llvm_object = try LlvmObject.create(gpa, options);
}
return self;
}
pub fn flush(self: *MachO, comp: *Compilation) !void {
if (self.base.options.emit == null) {
if (build_options.have_llvm) {
if (self.llvm_object) |llvm_object| {
return try llvm_object.flushModule(comp);
}
}
return;
}
if (self.base.options.output_mode == .Lib and self.base.options.link_mode == .Static) {
if (build_options.have_llvm) {
return self.base.linkAsArchive(comp);
} else {
log.err("TODO: non-LLVM archiver for MachO object files", .{});
return error.TODOImplementWritingStaticLibFiles;
}
}
try self.flushModule(comp);
}
pub fn flushModule(self: *MachO, comp: *Compilation) !void {
const tracy = trace(@src());
defer tracy.end();
const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1;
if (!use_stage1 and self.base.options.output_mode == .Obj)
return self.flushObject(comp);
var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
const directory = self.base.options.emit.?.directory; // Just an alias to make it shorter to type.
const full_out_path = try directory.join(arena, &[_][]const u8{self.base.options.emit.?.sub_path});
// If there is no Zig code to compile, then we should skip flushing the output file because it
// will not be part of the linker line anyway.
const module_obj_path: ?[]const u8 = if (self.base.options.module) |module| blk: {
if (use_stage1) {
const obj_basename = try std.zig.binNameAlloc(arena, .{
.root_name = self.base.options.root_name,
.target = self.base.options.target,
.output_mode = .Obj,
});
switch (self.base.options.cache_mode) {
.incremental => break :blk try module.zig_cache_artifact_directory.join(
arena,
&[_][]const u8{obj_basename},
),
.whole => break :blk try fs.path.join(arena, &.{
fs.path.dirname(full_out_path).?, obj_basename,
}),
}
}
const obj_basename = self.base.intermediary_basename orelse break :blk null;
try self.flushObject(comp);
if (fs.path.dirname(full_out_path)) |dirname| {
break :blk try fs.path.join(arena, &.{ dirname, obj_basename });
} else {
break :blk obj_basename;
}
} else null;
const is_lib = self.base.options.output_mode == .Lib;
const is_dyn_lib = self.base.options.link_mode == .Dynamic and is_lib;
const is_exe_or_dyn_lib = is_dyn_lib or self.base.options.output_mode == .Exe;
const stack_size = self.base.options.stack_size_override orelse 0;
const allow_undef = is_dyn_lib and (self.base.options.allow_shlib_undefined orelse false);
const id_symlink_basename = "zld.id";
const cache_dir_handle = blk: {
if (use_stage1) {
break :blk directory.handle;
}
if (self.base.options.module) |module| {
break :blk module.zig_cache_artifact_directory.handle;
}
break :blk directory.handle;
};
var man: Cache.Manifest = undefined;
defer if (!self.base.options.disable_lld_caching) man.deinit();
var digest: [Cache.hex_digest_len]u8 = undefined;
var needs_full_relink = true;
cache: {
if (use_stage1 and self.base.options.disable_lld_caching) break :cache;
man = comp.cache_parent.obtain();
// We are about to obtain this lock, so here we give other processes a chance first.
self.base.releaseLock();
comptime assert(Compilation.link_hash_implementation_version == 2);
for (self.base.options.objects) |obj| {
_ = try man.addFile(obj.path, null);
man.hash.add(obj.must_link);
}
for (comp.c_object_table.keys()) |key| {
_ = try man.addFile(key.status.success.object_path, null);
}
try man.addOptionalFile(module_obj_path);
// We can skip hashing libc and libc++ components that we are in charge of building from Zig
// installation sources because they are always a product of the compiler version + target information.
man.hash.add(stack_size);
man.hash.addListOfBytes(self.base.options.lib_dirs);
man.hash.addListOfBytes(self.base.options.framework_dirs);
man.hash.addListOfBytes(self.base.options.frameworks);
man.hash.addListOfBytes(self.base.options.rpath_list);
if (is_dyn_lib) {
man.hash.addOptionalBytes(self.base.options.install_name);
man.hash.addOptional(self.base.options.version);
}
link.hashAddSystemLibs(&man.hash, self.base.options.system_libs);
man.hash.addOptionalBytes(self.base.options.sysroot);
// We don't actually care whether it's a cache hit or miss; we just need the digest and the lock.
_ = try man.hit();
digest = man.final();
var prev_digest_buf: [digest.len]u8 = undefined;
const prev_digest: []u8 = Cache.readSmallFile(
cache_dir_handle,
id_symlink_basename,
&prev_digest_buf,
) catch |err| blk: {
log.debug("MachO Zld new_digest={s} error: {s}", .{
std.fmt.fmtSliceHexLower(&digest),
@errorName(err),
});
// Handle this as a cache miss.
break :blk prev_digest_buf[0..0];
};
if (mem.eql(u8, prev_digest, &digest)) {
// Hot diggity dog! The output binary is already there.
if (use_stage1) {
log.debug("MachO Zld digest={s} match - skipping invocation", .{std.fmt.fmtSliceHexLower(&digest)});
self.base.lock = man.toOwnedLock();
return;
} else {
log.debug("MachO Zld digest={s} match", .{std.fmt.fmtSliceHexLower(&digest)});
if (!self.cold_start) {
log.debug(" no need to relink objects", .{});
needs_full_relink = false;
} else {
log.debug(" TODO parse prelinked binary and continue linking where we left off", .{});
// TODO until such time however, perform a full relink of objects.
needs_full_relink = true;
}
}
}
log.debug("MachO Zld prev_digest={s} new_digest={s}", .{
std.fmt.fmtSliceHexLower(prev_digest),
std.fmt.fmtSliceHexLower(&digest),
});
// We are about to change the output file to be different, so we invalidate the build hash now.
cache_dir_handle.deleteFile(id_symlink_basename) catch |err| switch (err) {
error.FileNotFound => {},
else => |e| return e,
};
}
if (self.base.options.output_mode == .Obj) {
// LLD's MachO driver does not support the equivalent of `-r` so we do a simple file copy
// here. TODO: think carefully about how we can avoid this redundant operation when doing
// build-obj. See also the corresponding TODO in linkAsArchive.
const the_object_path = blk: {
if (self.base.options.objects.len != 0) {
break :blk self.base.options.objects[0].path;
}
if (comp.c_object_table.count() != 0)
break :blk comp.c_object_table.keys()[0].status.success.object_path;
if (module_obj_path) |p|
break :blk p;
// TODO I think this is unreachable. Audit this situation when solving the above TODO
// regarding eliding redundant object -> object transformations.
return error.NoObjectsToLink;
};
// This can happen when using --enable-cache and using the stage1 backend. In this case
// we can skip the file copy.
if (!mem.eql(u8, the_object_path, full_out_path)) {
try fs.cwd().copyFile(the_object_path, fs.cwd(), full_out_path, .{});
}
} else {
if (use_stage1) {
const sub_path = self.base.options.emit.?.sub_path;
self.base.file = try cache_dir_handle.createFile(sub_path, .{
.truncate = true,
.read = true,
.mode = link.determineMode(self.base.options),
});
// Index 0 is always a null symbol.
try self.locals.append(self.base.allocator, .{
.n_strx = 0,
.n_type = 0,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
try self.strtab.append(self.base.allocator, 0);
try self.populateMissingMetadata();
}
var lib_not_found = false;
var framework_not_found = false;
if (needs_full_relink) {
for (self.objects.items) |*object| {
object.free(self.base.allocator, self);
object.deinit(self.base.allocator);
}
self.objects.clearRetainingCapacity();
for (self.archives.items) |*archive| {
archive.deinit(self.base.allocator);
}
self.archives.clearRetainingCapacity();
for (self.dylibs.items) |*dylib| {
dylib.deinit(self.base.allocator);
}
self.dylibs.clearRetainingCapacity();
self.dylibs_map.clearRetainingCapacity();
self.referenced_dylibs.clearRetainingCapacity();
{
var to_remove = std.ArrayList(u32).init(self.base.allocator);
defer to_remove.deinit();
var it = self.symbol_resolver.iterator();
while (it.next()) |entry| {
const key = entry.key_ptr.*;
const value = entry.value_ptr.*;
if (value.file != null) {
try to_remove.append(key);
}
}
for (to_remove.items) |key| {
if (self.symbol_resolver.fetchRemove(key)) |entry| {
const resolv = entry.value;
switch (resolv.where) {
.global => {
self.globals_free_list.append(self.base.allocator, resolv.where_index) catch {};
const sym = &self.globals.items[resolv.where_index];
sym.n_strx = 0;
sym.n_type = 0;
sym.n_value = 0;
},
.undef => {
const sym = &self.undefs.items[resolv.where_index];
sym.n_strx = 0;
sym.n_desc = 0;
},
}
if (self.got_entries_table.get(.{ .global = entry.key })) |i| {
self.got_entries_free_list.append(self.base.allocator, @intCast(u32, i)) catch {};
self.got_entries.items[i] = .{ .target = .{ .local = 0 }, .atom = undefined };
_ = self.got_entries_table.swapRemove(.{ .global = entry.key });
}
if (self.stubs_table.get(entry.key)) |i| {
self.stubs_free_list.append(self.base.allocator, @intCast(u32, i)) catch {};
self.stubs.items[i] = undefined;
_ = self.stubs_table.swapRemove(entry.key);
}
}
}
}
// Invalidate all relocs
// TODO we only need to invalidate the backlinks to the relinked atoms from
// the relocatable object files.
self.invalidate_relocs = true;
// Positional arguments to the linker such as object files and static archives.
var positionals = std.ArrayList([]const u8).init(arena);
try positionals.ensureUnusedCapacity(self.base.options.objects.len);
var must_link_archives = std.StringArrayHashMap(void).init(arena);
try must_link_archives.ensureUnusedCapacity(self.base.options.objects.len);
for (self.base.options.objects) |obj| {
if (must_link_archives.contains(obj.path)) continue;
if (obj.must_link) {
_ = must_link_archives.getOrPutAssumeCapacity(obj.path);
} else {
_ = positionals.appendAssumeCapacity(obj.path);
}
}
for (comp.c_object_table.keys()) |key| {
try positionals.append(key.status.success.object_path);
}
if (module_obj_path) |p| {
try positionals.append(p);
}
if (comp.compiler_rt_static_lib) |lib| {
try positionals.append(lib.full_object_path);
}
// libc++ dep
if (self.base.options.link_libcpp) {
try positionals.append(comp.libcxxabi_static_lib.?.full_object_path);
try positionals.append(comp.libcxx_static_lib.?.full_object_path);
}
// Shared and static libraries passed via `-l` flag.
var search_lib_names = std.ArrayList([]const u8).init(arena);
const system_libs = self.base.options.system_libs.keys();
for (system_libs) |link_lib| {
// By this time, we depend on these libs being dynamically linked libraries and not static libraries
// (the check for that needs to be earlier), but they could be full paths to .dylib files, in which
// case we want to avoid prepending "-l".
if (Compilation.classifyFileExt(link_lib) == .shared_library) {
try positionals.append(link_lib);
continue;
}
try search_lib_names.append(link_lib);
}
var lib_dirs = std.ArrayList([]const u8).init(arena);
for (self.base.options.lib_dirs) |dir| {
if (try resolveSearchDir(arena, dir, self.base.options.sysroot)) |search_dir| {
try lib_dirs.append(search_dir);
} else {
log.warn("directory not found for '-L{s}'", .{dir});
}
}
var libs = std.ArrayList([]const u8).init(arena);
for (search_lib_names.items) |lib_name| {
// Assume ld64 default: -search_paths_first
// Look in each directory for a dylib (stub first), and then for archive
// TODO implement alternative: -search_dylibs_first
for (&[_][]const u8{ ".tbd", ".dylib", ".a" }) |ext| {
if (try resolveLib(arena, lib_dirs.items, lib_name, ext)) |full_path| {
try libs.append(full_path);
break;
}
} else {
log.warn("library not found for '-l{s}'", .{lib_name});
lib_not_found = true;
}
}
if (lib_not_found) {
log.warn("Library search paths:", .{});
for (lib_dirs.items) |dir| {
log.warn(" {s}", .{dir});
}
}
// If we were given the sysroot, try to look there first for libSystem.B.{dylib, tbd}.
var libsystem_available = false;
if (self.base.options.sysroot != null) blk: {
// Try stub file first. If we hit it, then we're done as the stub file
// re-exports every single symbol definition.
if (try resolveLib(arena, lib_dirs.items, "System", ".tbd")) |full_path| {
try libs.append(full_path);
libsystem_available = true;
break :blk;
}
// If we didn't hit the stub file, try .dylib next. However, libSystem.dylib
// doesn't export libc.dylib which we'll need to resolve subsequently also.
if (try resolveLib(arena, lib_dirs.items, "System", ".dylib")) |libsystem_path| {
if (try resolveLib(arena, lib_dirs.items, "c", ".dylib")) |libc_path| {
try libs.append(libsystem_path);
try libs.append(libc_path);
libsystem_available = true;
break :blk;
}
}
}
if (!libsystem_available) {
const libsystem_name = try std.fmt.allocPrint(arena, "libSystem.{d}.tbd", .{
self.base.options.target.os.version_range.semver.min.major,
});
const full_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{
"libc", "darwin", libsystem_name,
});
try libs.append(full_path);
}
// frameworks
var framework_dirs = std.ArrayList([]const u8).init(arena);
for (self.base.options.framework_dirs) |dir| {
if (try resolveSearchDir(arena, dir, self.base.options.sysroot)) |search_dir| {
try framework_dirs.append(search_dir);
} else {
log.warn("directory not found for '-F{s}'", .{dir});
}
}
for (self.base.options.frameworks) |framework| {
for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| {
if (try resolveFramework(arena, framework_dirs.items, framework, ext)) |full_path| {
try libs.append(full_path);
break;
}
} else {
log.warn("framework not found for '-framework {s}'", .{framework});
framework_not_found = true;
}
}
if (framework_not_found) {
log.warn("Framework search paths:", .{});
for (framework_dirs.items) |dir| {
log.warn(" {s}", .{dir});
}
}
// rpaths
var rpath_table = std.StringArrayHashMap(void).init(arena);
for (self.base.options.rpath_list) |rpath| {
if (rpath_table.contains(rpath)) continue;
const cmdsize = @intCast(u32, mem.alignForwardGeneric(
u64,
@sizeOf(macho.rpath_command) + rpath.len + 1,
@sizeOf(u64),
));
var rpath_cmd = macho.emptyGenericCommandWithData(macho.rpath_command{
.cmdsize = cmdsize,
.path = @sizeOf(macho.rpath_command),
});
rpath_cmd.data = try self.base.allocator.alloc(u8, cmdsize - rpath_cmd.inner.path);
mem.set(u8, rpath_cmd.data, 0);
mem.copy(u8, rpath_cmd.data, rpath);
try self.load_commands.append(self.base.allocator, .{ .rpath = rpath_cmd });
try rpath_table.putNoClobber(rpath, {});
self.load_commands_dirty = true;
}
if (self.base.options.verbose_link) {
var argv = std.ArrayList([]const u8).init(arena);
try argv.append("zig");
try argv.append("ld");
if (is_exe_or_dyn_lib) {
try argv.append("-dynamic");
}
if (is_dyn_lib) {
try argv.append("-dylib");
if (self.base.options.install_name) |install_name| {
try argv.append("-install_name");
try argv.append(install_name);
}
}
if (self.base.options.sysroot) |syslibroot| {
try argv.append("-syslibroot");
try argv.append(syslibroot);
}
for (rpath_table.keys()) |rpath| {
try argv.append("-rpath");
try argv.append(rpath);
}
try argv.appendSlice(positionals.items);
try argv.append("-o");
try argv.append(full_out_path);
try argv.append("-lSystem");
try argv.append("-lc");
for (search_lib_names.items) |l_name| {
try argv.append(try std.fmt.allocPrint(arena, "-l{s}", .{l_name}));
}
for (self.base.options.lib_dirs) |lib_dir| {
try argv.append(try std.fmt.allocPrint(arena, "-L{s}", .{lib_dir}));
}
for (self.base.options.frameworks) |framework| {
try argv.append(try std.fmt.allocPrint(arena, "-framework {s}", .{framework}));
}
for (self.base.options.framework_dirs) |framework_dir| {
try argv.append(try std.fmt.allocPrint(arena, "-F{s}", .{framework_dir}));
}
if (allow_undef) {
try argv.append("-undefined");
try argv.append("dynamic_lookup");
}
for (must_link_archives.keys()) |lib| {
try argv.append(try std.fmt.allocPrint(arena, "-force_load {s}", .{lib}));
}
Compilation.dump_argv(argv.items);
}
var dependent_libs = std.fifo.LinearFifo(Dylib.Id, .Dynamic).init(self.base.allocator);
defer dependent_libs.deinit();
try self.parseInputFiles(positionals.items, self.base.options.sysroot, &dependent_libs);
try self.parseAndForceLoadStaticArchives(must_link_archives.keys());
try self.parseLibs(libs.items, self.base.options.sysroot, &dependent_libs);
try self.parseDependentLibs(self.base.options.sysroot, &dependent_libs);
}
try self.createMhExecuteHeaderAtom();
for (self.objects.items) |*object, object_id| {
if (object.analyzed) continue;
try self.resolveSymbolsInObject(@intCast(u16, object_id));
}
try self.resolveSymbolsInArchives();
try self.resolveDyldStubBinder();
try self.createDyldPrivateAtom();
try self.createStubHelperPreambleAtom();
try self.resolveSymbolsInDylibs();
try self.createDsoHandleAtom();
try self.addCodeSignatureLC();
{
var next_sym: usize = 0;
while (next_sym < self.unresolved.count()) {
const sym = &self.undefs.items[self.unresolved.keys()[next_sym]];
const sym_name = self.getString(sym.n_strx);
const resolv = self.symbol_resolver.get(sym.n_strx) orelse unreachable;
if (sym.discarded()) {
sym.* = .{
.n_strx = 0,
.n_type = macho.N_UNDF,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
};
_ = self.unresolved.swapRemove(resolv.where_index);
continue;
} else if (allow_undef) {
const n_desc = @bitCast(
u16,
macho.BIND_SPECIAL_DYLIB_FLAT_LOOKUP * @intCast(i16, macho.N_SYMBOL_RESOLVER),
);
// TODO allow_shlib_undefined is an ELF flag so figure out macOS specific flags too.
sym.n_type = macho.N_EXT;
sym.n_desc = n_desc;
_ = self.unresolved.swapRemove(resolv.where_index);
continue;
}
log.err("undefined reference to symbol '{s}'", .{sym_name});
if (resolv.file) |file| {
log.err(" first referenced in '{s}'", .{self.objects.items[file].name});
}
next_sym += 1;
}
}
if (self.unresolved.count() > 0) {
return error.UndefinedSymbolReference;
}
if (lib_not_found) {
return error.LibraryNotFound;
}
if (framework_not_found) {
return error.FrameworkNotFound;
}
try self.createTentativeDefAtoms();
try self.parseObjectsIntoAtoms();
if (use_stage1) {
try self.sortSections();
try self.allocateTextSegment();
try self.allocateDataConstSegment();
try self.allocateDataSegment();
self.allocateLinkeditSegment();
try self.allocateLocals();
}
try self.allocateGlobals();
if (build_options.enable_logging) {
self.logSymtab();
self.logSectionOrdinals();
}
if (use_stage1) {
try self.writeAllAtoms();
} else {
try self.writeAtoms();
}
if (self.rustc_section_index) |id| {
const seg = &self.load_commands.items[self.data_segment_cmd_index.?].segment;
const sect = &seg.sections.items[id];
sect.size = self.rustc_section_size;
}
try self.setEntryPoint();
try self.updateSectionOrdinals();
try self.writeLinkeditSegment();
if (self.d_sym) |*d_sym| {
// Flush debug symbols bundle.
try d_sym.flushModule(self.base.allocator, self.base.options);
}
if (self.requires_adhoc_codesig) {
// Preallocate space for the code signature.
// We need to do this at this stage so that we have the load commands with proper values
// written out to the file.
// The most important here is to have the correct vm and filesize of the __LINKEDIT segment
// where the code signature goes into.
try self.writeCodeSignaturePadding();
}
try self.writeLoadCommands();
try self.writeHeader();
if (self.entry_addr == null and self.base.options.output_mode == .Exe) {
log.debug("flushing. no_entry_point_found = true", .{});
self.error_flags.no_entry_point_found = true;
} else {
log.debug("flushing. no_entry_point_found = false", .{});
self.error_flags.no_entry_point_found = false;
}
assert(!self.load_commands_dirty);
if (self.requires_adhoc_codesig) {
try self.writeCodeSignature(); // code signing always comes last
}
if (build_options.enable_link_snapshots) {
if (self.base.options.enable_link_snapshots)
try self.snapshotState();
}
}
cache: {
if (use_stage1 and self.base.options.disable_lld_caching) break :cache;
// Update the file with the digest. If it fails we can continue; it only
// means that the next invocation will have an unnecessary cache miss.
Cache.writeSmallFile(cache_dir_handle, id_symlink_basename, &digest) catch |err| {
log.debug("failed to save linking hash digest file: {s}", .{@errorName(err)});
};
// Again failure here only means an unnecessary cache miss.
man.writeManifest() catch |err| {
log.debug("failed to write cache manifest when linking: {s}", .{@errorName(err)});
};
// We hang on to this lock so that the output file path can be used without
// other processes clobbering it.
self.base.lock = man.toOwnedLock();
}
self.cold_start = false;
}
pub fn flushObject(self: *MachO, comp: *Compilation) !void {
const tracy = trace(@src());
defer tracy.end();
if (build_options.have_llvm)
if (self.llvm_object) |llvm_object| return llvm_object.flushModule(comp);
return error.TODOImplementWritingObjFiles;
}
fn resolveSearchDir(
arena: Allocator,
dir: []const u8,
syslibroot: ?[]const u8,
) !?[]const u8 {
var candidates = std.ArrayList([]const u8).init(arena);
if (fs.path.isAbsolute(dir)) {
if (syslibroot) |root| {
const common_dir = if (builtin.os.tag == .windows) blk: {
// We need to check for disk designator and strip it out from dir path so
// that we can concat dir with syslibroot.
// TODO we should backport this mechanism to 'MachO.Dylib.parseDependentLibs()'
const disk_designator = fs.path.diskDesignatorWindows(dir);
if (mem.indexOf(u8, dir, disk_designator)) |where| {
break :blk dir[where + disk_designator.len ..];
}
break :blk dir;
} else dir;
const full_path = try fs.path.join(arena, &[_][]const u8{ root, common_dir });
try candidates.append(full_path);
}
}
try candidates.append(dir);
for (candidates.items) |candidate| {
// Verify that search path actually exists
var tmp = fs.cwd().openDir(candidate, .{}) catch |err| switch (err) {
error.FileNotFound => continue,
else => |e| return e,
};
defer tmp.close();
return candidate;
}
return null;
}
fn resolveLib(
arena: Allocator,
search_dirs: []const []const u8,
name: []const u8,
ext: []const u8,
) !?[]const u8 {
const search_name = try std.fmt.allocPrint(arena, "lib{s}{s}", .{ name, ext });
for (search_dirs) |dir| {
const full_path = try fs.path.join(arena, &[_][]const u8{ dir, search_name });
// Check if the file exists.
const tmp = fs.cwd().openFile(full_path, .{}) catch |err| switch (err) {
error.FileNotFound => continue,
else => |e| return e,
};
defer tmp.close();
return full_path;
}
return null;
}
fn resolveFramework(
arena: Allocator,
search_dirs: []const []const u8,
name: []const u8,
ext: []const u8,
) !?[]const u8 {
const search_name = try std.fmt.allocPrint(arena, "{s}{s}", .{ name, ext });
const prefix_path = try std.fmt.allocPrint(arena, "{s}.framework", .{name});
for (search_dirs) |dir| {
const full_path = try fs.path.join(arena, &[_][]const u8{ dir, prefix_path, search_name });
// Check if the file exists.
const tmp = fs.cwd().openFile(full_path, .{}) catch |err| switch (err) {
error.FileNotFound => continue,
else => |e| return e,
};
defer tmp.close();
return full_path;
}
return null;
}
fn parseObject(self: *MachO, path: []const u8) !bool {
const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) {
error.FileNotFound => return false,
else => |e| return e,
};
errdefer file.close();
const name = try self.base.allocator.dupe(u8, path);
errdefer self.base.allocator.free(name);
var object = Object{
.name = name,
.file = file,
};
object.parse(self.base.allocator, self.base.options.target) catch |err| switch (err) {
error.EndOfStream, error.NotObject => {
object.deinit(self.base.allocator);
return false;
},
else => |e| return e,
};
try self.objects.append(self.base.allocator, object);
return true;
}
fn parseArchive(self: *MachO, path: []const u8, force_load: bool) !bool {
const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) {
error.FileNotFound => return false,
else => |e| return e,
};
errdefer file.close();
const name = try self.base.allocator.dupe(u8, path);
errdefer self.base.allocator.free(name);
var archive = Archive{
.name = name,
.file = file,
};
archive.parse(self.base.allocator, self.base.options.target) catch |err| switch (err) {
error.EndOfStream, error.NotArchive => {
archive.deinit(self.base.allocator);
return false;
},
else => |e| return e,
};
if (force_load) {
defer archive.deinit(self.base.allocator);
// Get all offsets from the ToC
var offsets = std.AutoArrayHashMap(u32, void).init(self.base.allocator);
defer offsets.deinit();
for (archive.toc.values()) |offs| {
for (offs.items) |off| {
_ = try offsets.getOrPut(off);
}
}
for (offsets.keys()) |off| {
const object = try self.objects.addOne(self.base.allocator);
object.* = try archive.parseObject(self.base.allocator, self.base.options.target, off);
}
} else {
try self.archives.append(self.base.allocator, archive);
}
return true;
}
const ParseDylibError = error{
OutOfMemory,
EmptyStubFile,
MismatchedCpuArchitecture,
UnsupportedCpuArchitecture,
} || fs.File.OpenError || std.os.PReadError || Dylib.Id.ParseError;
const DylibCreateOpts = struct {
syslibroot: ?[]const u8,
dependent_libs: *std.fifo.LinearFifo(Dylib.Id, .Dynamic),
id: ?Dylib.Id = null,
is_dependent: bool = false,
};
pub fn parseDylib(self: *MachO, path: []const u8, opts: DylibCreateOpts) ParseDylibError!bool {
const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) {
error.FileNotFound => return false,
else => |e| return e,
};
errdefer file.close();
const name = try self.base.allocator.dupe(u8, path);
errdefer self.base.allocator.free(name);
var dylib = Dylib{
.name = name,
.file = file,
};
dylib.parse(self.base.allocator, self.base.options.target, opts.dependent_libs) catch |err| switch (err) {
error.EndOfStream, error.NotDylib => {
try file.seekTo(0);
var lib_stub = LibStub.loadFromFile(self.base.allocator, file) catch {
dylib.deinit(self.base.allocator);
return false;
};
defer lib_stub.deinit();
try dylib.parseFromStub(self.base.allocator, self.base.options.target, lib_stub, opts.dependent_libs);
},
else => |e| return e,
};
if (opts.id) |id| {
if (dylib.id.?.current_version < id.compatibility_version) {
log.warn("found dylib is incompatible with the required minimum version", .{});
log.warn(" dylib: {s}", .{id.name});
log.warn(" required minimum version: {}", .{id.compatibility_version});
log.warn(" dylib version: {}", .{dylib.id.?.current_version});
// TODO maybe this should be an error and facilitate auto-cleanup?
dylib.deinit(self.base.allocator);
return false;
}
}
const dylib_id = @intCast(u16, self.dylibs.items.len);
try self.dylibs.append(self.base.allocator, dylib);
try self.dylibs_map.putNoClobber(self.base.allocator, dylib.id.?.name, dylib_id);
if (!(opts.is_dependent or self.referenced_dylibs.contains(dylib_id))) {
try self.addLoadDylibLC(dylib_id);
try self.referenced_dylibs.putNoClobber(self.base.allocator, dylib_id, {});
}
return true;
}
fn parseInputFiles(self: *MachO, files: []const []const u8, syslibroot: ?[]const u8, dependent_libs: anytype) !void {
for (files) |file_name| {
const full_path = full_path: {
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined;
const path = try fs.realpath(file_name, &buffer);
break :full_path try self.base.allocator.dupe(u8, path);
};
defer self.base.allocator.free(full_path);
log.debug("parsing input file path '{s}'", .{full_path});
if (try self.parseObject(full_path)) continue;
if (try self.parseArchive(full_path, false)) continue;
if (try self.parseDylib(full_path, .{
.syslibroot = syslibroot,
.dependent_libs = dependent_libs,
})) continue;
log.warn("unknown filetype for positional input file: '{s}'", .{file_name});
}
}
fn parseAndForceLoadStaticArchives(self: *MachO, files: []const []const u8) !void {
for (files) |file_name| {
const full_path = full_path: {
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined;
const path = try fs.realpath(file_name, &buffer);
break :full_path try self.base.allocator.dupe(u8, path);
};
defer self.base.allocator.free(full_path);
log.debug("parsing and force loading static archive '{s}'", .{full_path});
if (try self.parseArchive(full_path, true)) continue;
log.warn("unknown filetype: expected static archive: '{s}'", .{file_name});
}
}
fn parseLibs(self: *MachO, libs: []const []const u8, syslibroot: ?[]const u8, dependent_libs: anytype) !void {
for (libs) |lib| {
log.debug("parsing lib path '{s}'", .{lib});
if (try self.parseDylib(lib, .{
.syslibroot = syslibroot,
.dependent_libs = dependent_libs,
})) continue;
if (try self.parseArchive(lib, false)) continue;
log.warn("unknown filetype for a library: '{s}'", .{lib});
}
}
fn parseDependentLibs(self: *MachO, syslibroot: ?[]const u8, dependent_libs: anytype) !void {
// At this point, we can now parse dependents of dylibs preserving the inclusion order of:
// 1) anything on the linker line is parsed first
// 2) afterwards, we parse dependents of the included dylibs
// TODO this should not be performed if the user specifies `-flat_namespace` flag.
// See ld64 manpages.
var arena_alloc = std.heap.ArenaAllocator.init(self.base.allocator);
const arena = arena_alloc.allocator();
defer arena_alloc.deinit();
while (dependent_libs.readItem()) |*id| {
defer id.deinit(self.base.allocator);
if (self.dylibs_map.contains(id.name)) continue;
const has_ext = blk: {
const basename = fs.path.basename(id.name);
break :blk mem.lastIndexOfScalar(u8, basename, '.') != null;
};
const extension = if (has_ext) fs.path.extension(id.name) else "";
const without_ext = if (has_ext) blk: {
const index = mem.lastIndexOfScalar(u8, id.name, '.') orelse unreachable;
break :blk id.name[0..index];
} else id.name;
for (&[_][]const u8{ extension, ".tbd" }) |ext| {
const with_ext = try std.fmt.allocPrint(arena, "{s}{s}", .{ without_ext, ext });
const full_path = if (syslibroot) |root| try fs.path.join(arena, &.{ root, with_ext }) else with_ext;
log.debug("trying dependency at fully resolved path {s}", .{full_path});
const did_parse_successfully = try self.parseDylib(full_path, .{
.id = id.*,
.syslibroot = syslibroot,
.is_dependent = true,
.dependent_libs = dependent_libs,
});
if (did_parse_successfully) break;
} else {
log.warn("unable to resolve dependency {s}", .{id.name});
}
}
}
pub const MatchingSection = struct {
seg: u16,
sect: u16,
};
pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSection {
const segname = sect.segName();
const sectname = sect.sectName();
const res: ?MatchingSection = blk: {
switch (sect.type_()) {
macho.S_4BYTE_LITERALS, macho.S_8BYTE_LITERALS, macho.S_16BYTE_LITERALS => {
if (self.text_const_section_index == null) {
self.text_const_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__const",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.text_const_section_index.?,
};
},
macho.S_CSTRING_LITERALS => {
if (mem.eql(u8, sectname, "__objc_methname")) {
// TODO it seems the common values within the sections in objects are deduplicated/merged
// on merging the sections' contents.
if (self.objc_methname_section_index == null) {
self.objc_methname_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__objc_methname",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.objc_methname_section_index.?,
};
} else if (mem.eql(u8, sectname, "__objc_methtype")) {
if (self.objc_methtype_section_index == null) {
self.objc_methtype_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__objc_methtype",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.objc_methtype_section_index.?,
};
} else if (mem.eql(u8, sectname, "__objc_classname")) {
if (self.objc_classname_section_index == null) {
self.objc_classname_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__objc_classname",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.objc_classname_section_index.?,
};
}
if (self.cstring_section_index == null) {
self.cstring_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__cstring",
sect.size,
sect.@"align",
.{
.flags = macho.S_CSTRING_LITERALS,
},
);
}
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.cstring_section_index.?,
};
},
macho.S_LITERAL_POINTERS => {
if (mem.eql(u8, segname, "__DATA") and mem.eql(u8, sectname, "__objc_selrefs")) {
if (self.objc_selrefs_section_index == null) {
self.objc_selrefs_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__objc_selrefs",
sect.size,
sect.@"align",
.{
.flags = macho.S_LITERAL_POINTERS,
},
);
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.objc_selrefs_section_index.?,
};
} else {
// TODO investigate
break :blk null;
}
},
macho.S_MOD_INIT_FUNC_POINTERS => {
if (self.mod_init_func_section_index == null) {
self.mod_init_func_section_index = try self.initSection(
self.data_const_segment_cmd_index.?,
"__mod_init_func",
sect.size,
sect.@"align",
.{
.flags = macho.S_MOD_INIT_FUNC_POINTERS,
},
);
}
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.mod_init_func_section_index.?,
};
},
macho.S_MOD_TERM_FUNC_POINTERS => {
if (self.mod_term_func_section_index == null) {
self.mod_term_func_section_index = try self.initSection(
self.data_const_segment_cmd_index.?,
"__mod_term_func",
sect.size,
sect.@"align",
.{
.flags = macho.S_MOD_TERM_FUNC_POINTERS,
},
);
}
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.mod_term_func_section_index.?,
};
},
macho.S_ZEROFILL => {
if (self.bss_section_index == null) {
self.bss_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__bss",
sect.size,
sect.@"align",
.{
.flags = macho.S_ZEROFILL,
},
);
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.bss_section_index.?,
};
},
macho.S_THREAD_LOCAL_VARIABLES => {
if (self.tlv_section_index == null) {
self.tlv_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__thread_vars",
sect.size,
sect.@"align",
.{
.flags = macho.S_THREAD_LOCAL_VARIABLES,
},
);
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.tlv_section_index.?,
};
},
macho.S_THREAD_LOCAL_VARIABLE_POINTERS => {
if (self.tlv_ptrs_section_index == null) {
self.tlv_ptrs_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__thread_ptrs",
sect.size,
sect.@"align",
.{
.flags = macho.S_THREAD_LOCAL_VARIABLE_POINTERS,
},
);
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.tlv_ptrs_section_index.?,
};
},
macho.S_THREAD_LOCAL_REGULAR => {
if (self.tlv_data_section_index == null) {
self.tlv_data_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__thread_data",
sect.size,
sect.@"align",
.{
.flags = macho.S_THREAD_LOCAL_REGULAR,
},
);
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.tlv_data_section_index.?,
};
},
macho.S_THREAD_LOCAL_ZEROFILL => {
if (self.tlv_bss_section_index == null) {
self.tlv_bss_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__thread_bss",
sect.size,
sect.@"align",
.{
.flags = macho.S_THREAD_LOCAL_ZEROFILL,
},
);
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.tlv_bss_section_index.?,
};
},
macho.S_COALESCED => {
if (mem.eql(u8, "__TEXT", segname) and mem.eql(u8, "__eh_frame", sectname)) {
// TODO I believe __eh_frame is currently part of __unwind_info section
// in the latest ld64 output.
if (self.eh_frame_section_index == null) {
self.eh_frame_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__eh_frame",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.eh_frame_section_index.?,
};
}
// TODO audit this: is this the right mapping?
if (self.data_const_section_index == null) {
self.data_const_section_index = try self.initSection(
self.data_const_segment_cmd_index.?,
"__const",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.data_const_section_index.?,
};
},
macho.S_REGULAR => {
if (sect.isCode()) {
if (self.text_section_index == null) {
self.text_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__text",
sect.size,
sect.@"align",
.{
.flags = macho.S_REGULAR |
macho.S_ATTR_PURE_INSTRUCTIONS |
macho.S_ATTR_SOME_INSTRUCTIONS,
},
);
}
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.text_section_index.?,
};
}
if (sect.isDebug()) {
// TODO debug attributes
if (mem.eql(u8, "__LD", segname) and mem.eql(u8, "__compact_unwind", sectname)) {
log.debug("TODO compact unwind section: type 0x{x}, name '{s},{s}'", .{
sect.flags, segname, sectname,
});
}
break :blk null;
}
if (mem.eql(u8, segname, "__TEXT")) {
if (mem.eql(u8, sectname, "__ustring")) {
if (self.ustring_section_index == null) {
self.ustring_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__ustring",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.ustring_section_index.?,
};
} else if (mem.eql(u8, sectname, "__gcc_except_tab")) {
if (self.gcc_except_tab_section_index == null) {
self.gcc_except_tab_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__gcc_except_tab",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.gcc_except_tab_section_index.?,
};
} else if (mem.eql(u8, sectname, "__objc_methlist")) {
if (self.objc_methlist_section_index == null) {
self.objc_methlist_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__objc_methlist",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.objc_methlist_section_index.?,
};
} else if (mem.eql(u8, sectname, "__rodata") or
mem.eql(u8, sectname, "__typelink") or
mem.eql(u8, sectname, "__itablink") or
mem.eql(u8, sectname, "__gosymtab") or
mem.eql(u8, sectname, "__gopclntab"))
{
if (self.data_const_section_index == null) {
self.data_const_section_index = try self.initSection(
self.data_const_segment_cmd_index.?,
"__const",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.data_const_section_index.?,
};
} else {
if (self.text_const_section_index == null) {
self.text_const_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__const",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.text_segment_cmd_index.?,
.sect = self.text_const_section_index.?,
};
}
}
if (mem.eql(u8, segname, "__DATA_CONST")) {
if (self.data_const_section_index == null) {
self.data_const_section_index = try self.initSection(
self.data_const_segment_cmd_index.?,
"__const",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.data_const_section_index.?,
};
}
if (mem.eql(u8, segname, "__DATA")) {
if (mem.eql(u8, sectname, "__const")) {
if (self.data_const_section_index == null) {
self.data_const_section_index = try self.initSection(
self.data_const_segment_cmd_index.?,
"__const",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.data_const_section_index.?,
};
} else if (mem.eql(u8, sectname, "__cfstring")) {
if (self.objc_cfstring_section_index == null) {
self.objc_cfstring_section_index = try self.initSection(
self.data_const_segment_cmd_index.?,
"__cfstring",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.objc_cfstring_section_index.?,
};
} else if (mem.eql(u8, sectname, "__objc_classlist")) {
if (self.objc_classlist_section_index == null) {
self.objc_classlist_section_index = try self.initSection(
self.data_const_segment_cmd_index.?,
"__objc_classlist",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.objc_classlist_section_index.?,
};
} else if (mem.eql(u8, sectname, "__objc_imageinfo")) {
if (self.objc_imageinfo_section_index == null) {
self.objc_imageinfo_section_index = try self.initSection(
self.data_const_segment_cmd_index.?,
"__objc_imageinfo",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.objc_imageinfo_section_index.?,
};
} else if (mem.eql(u8, sectname, "__objc_const")) {
if (self.objc_const_section_index == null) {
self.objc_const_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__objc_const",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.objc_const_section_index.?,
};
} else if (mem.eql(u8, sectname, "__objc_classrefs")) {
if (self.objc_classrefs_section_index == null) {
self.objc_classrefs_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__objc_classrefs",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.objc_classrefs_section_index.?,
};
} else if (mem.eql(u8, sectname, "__objc_data")) {
if (self.objc_data_section_index == null) {
self.objc_data_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__objc_data",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.objc_data_section_index.?,
};
} else if (mem.eql(u8, sectname, ".rustc")) {
if (self.rustc_section_index == null) {
self.rustc_section_index = try self.initSection(
self.data_segment_cmd_index.?,
".rustc",
sect.size,
sect.@"align",
.{},
);
// We need to preserve the section size for rustc to properly
// decompress the metadata.
self.rustc_section_size = sect.size;
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.rustc_section_index.?,
};
} else {
if (self.data_section_index == null) {
self.data_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__data",
sect.size,
sect.@"align",
.{},
);
}
break :blk .{
.seg = self.data_segment_cmd_index.?,
.sect = self.data_section_index.?,
};
}
}
if (mem.eql(u8, "__LLVM", segname) and mem.eql(u8, "__asm", sectname)) {
log.debug("TODO LLVM asm section: type 0x{x}, name '{s},{s}'", .{
sect.flags, segname, sectname,
});
}
break :blk null;
},
else => break :blk null,
}
};
return res;
}
pub fn createEmptyAtom(self: *MachO, local_sym_index: u32, size: u64, alignment: u32) !*Atom {
const size_usize = try math.cast(usize, size);
const atom = try self.base.allocator.create(Atom);
errdefer self.base.allocator.destroy(atom);
atom.* = Atom.empty;
atom.local_sym_index = local_sym_index;
atom.size = size;
atom.alignment = alignment;
try atom.code.resize(self.base.allocator, size_usize);
mem.set(u8, atom.code.items, 0);
try self.managed_atoms.append(self.base.allocator, atom);
return atom;
}
pub fn writeAtom(self: *MachO, atom: *Atom, match: MatchingSection) !void {
const seg = self.load_commands.items[match.seg].segment;
const sect = seg.sections.items[match.sect];
const sym = self.locals.items[atom.local_sym_index];
const file_offset = sect.offset + sym.n_value - sect.addr;
try atom.resolveRelocs(self);
log.debug("writing atom for symbol {s} at file offset 0x{x}", .{ self.getString(sym.n_strx), file_offset });
try self.base.file.?.pwriteAll(atom.code.items, file_offset);
}
fn allocateLocals(self: *MachO) !void {
var it = self.atoms.iterator();
while (it.next()) |entry| {
const match = entry.key_ptr.*;
var atom = entry.value_ptr.*;
while (atom.prev) |prev| {
atom = prev;
}
const n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1);
const seg = self.load_commands.items[match.seg].segment;
const sect = seg.sections.items[match.sect];
var base_vaddr = sect.addr;
log.debug("allocating local symbols in {s},{s}", .{ sect.segName(), sect.sectName() });
while (true) {
const alignment = try math.powi(u32, 2, atom.alignment);
base_vaddr = mem.alignForwardGeneric(u64, base_vaddr, alignment);
const sym = &self.locals.items[atom.local_sym_index];
sym.n_value = base_vaddr;
sym.n_sect = n_sect;
log.debug(" {d}: {s} allocated at 0x{x}", .{
atom.local_sym_index,
self.getString(sym.n_strx),
base_vaddr,
});
// Update each alias (if any)
for (atom.aliases.items) |index| {
const alias_sym = &self.locals.items[index];
alias_sym.n_value = base_vaddr;
alias_sym.n_sect = n_sect;
}
// Update each symbol contained within the atom
for (atom.contained.items) |sym_at_off| {
const contained_sym = &self.locals.items[sym_at_off.local_sym_index];
contained_sym.n_value = base_vaddr + sym_at_off.offset;
contained_sym.n_sect = n_sect;
}
base_vaddr += atom.size;
if (atom.next) |next| {
atom = next;
} else break;
}
}
}
fn shiftLocalsByOffset(self: *MachO, match: MatchingSection, offset: i64) !void {
var atom = self.atoms.get(match) orelse return;
while (true) {
const atom_sym = &self.locals.items[atom.local_sym_index];
atom_sym.n_value = @intCast(u64, @intCast(i64, atom_sym.n_value) + offset);
for (atom.aliases.items) |index| {
const alias_sym = &self.locals.items[index];
alias_sym.n_value = @intCast(u64, @intCast(i64, alias_sym.n_value) + offset);
}
for (atom.contained.items) |sym_at_off| {
const contained_sym = &self.locals.items[sym_at_off.local_sym_index];
contained_sym.n_value = @intCast(u64, @intCast(i64, contained_sym.n_value) + offset);
}
if (atom.prev) |prev| {
atom = prev;
} else break;
}
}
fn allocateGlobals(self: *MachO) !void {
log.debug("allocating global symbols", .{});
var sym_it = self.symbol_resolver.valueIterator();
while (sym_it.next()) |resolv| {
if (resolv.where != .global) continue;
assert(resolv.local_sym_index != 0);
const local_sym = self.locals.items[resolv.local_sym_index];
const sym = &self.globals.items[resolv.where_index];
sym.n_value = local_sym.n_value;
sym.n_sect = local_sym.n_sect;
log.debug(" {d}: {s} allocated at 0x{x}", .{
resolv.where_index,
self.getString(sym.n_strx),
local_sym.n_value,
});
}
}
fn writeAllAtoms(self: *MachO) !void {
var it = self.atoms.iterator();
while (it.next()) |entry| {
const match = entry.key_ptr.*;
const seg = self.load_commands.items[match.seg].segment;
const sect = seg.sections.items[match.sect];
var atom: *Atom = entry.value_ptr.*;
if (sect.flags == macho.S_ZEROFILL or sect.flags == macho.S_THREAD_LOCAL_ZEROFILL) continue;
var buffer = std.ArrayList(u8).init(self.base.allocator);
defer buffer.deinit();
try buffer.ensureTotalCapacity(try math.cast(usize, sect.size));
log.debug("writing atoms in {s},{s}", .{ sect.segName(), sect.sectName() });
while (atom.prev) |prev| {
atom = prev;
}
while (true) {
const atom_sym = self.locals.items[atom.local_sym_index];
const padding_size: usize = if (atom.next) |next| blk: {
const next_sym = self.locals.items[next.local_sym_index];
const size = next_sym.n_value - (atom_sym.n_value + atom.size);
break :blk try math.cast(usize, size);
} else 0;
log.debug(" (adding atom {s} to buffer: {})", .{ self.getString(atom_sym.n_strx), atom_sym });
try atom.resolveRelocs(self);
buffer.appendSliceAssumeCapacity(atom.code.items);
var i: usize = 0;
while (i < padding_size) : (i += 1) {
buffer.appendAssumeCapacity(0);
}
if (atom.next) |next| {
atom = next;
} else {
assert(buffer.items.len == sect.size);
log.debug(" (writing at file offset 0x{x})", .{sect.offset});
try self.base.file.?.pwriteAll(buffer.items, sect.offset);
break;
}
}
}
}
fn writePadding(self: *MachO, match: MatchingSection, size: usize, writer: anytype) !void {
const is_code = match.seg == self.text_segment_cmd_index.? and match.sect == self.text_section_index.?;
const min_alignment: u3 = if (!is_code)
1
else switch (self.base.options.target.cpu.arch) {
.aarch64 => @sizeOf(u32),
.x86_64 => @as(u3, 1),
else => unreachable,
};
const len = @divExact(size, min_alignment);
var i: usize = 0;
while (i < len) : (i += 1) {
if (!is_code) {
try writer.writeByte(0);
} else switch (self.base.options.target.cpu.arch) {
.aarch64 => {
const inst = aarch64.Instruction.nop();
try writer.writeIntLittle(u32, inst.toU32());
},
.x86_64 => {
try writer.writeByte(0x90);
},
else => unreachable,
}
}
}
fn writeAtoms(self: *MachO) !void {
var it = self.atoms.iterator();
while (it.next()) |entry| {
const match = entry.key_ptr.*;
const seg = self.load_commands.items[match.seg].segment;
const sect = seg.sections.items[match.sect];
var atom: *Atom = entry.value_ptr.*;
// TODO handle zerofill in stage2
// if (sect.flags == macho.S_ZEROFILL or sect.flags == macho.S_THREAD_LOCAL_ZEROFILL) continue;
log.debug("writing atoms in {s},{s}", .{ sect.segName(), sect.sectName() });
while (true) {
if (atom.dirty or self.invalidate_relocs) {
try self.writeAtom(atom, match);
atom.dirty = false;
}
if (atom.prev) |prev| {
atom = prev;
} else break;
}
}
}
pub fn createGotAtom(self: *MachO, target: Atom.Relocation.Target) !*Atom {
const local_sym_index = @intCast(u32, self.locals.items.len);
try self.locals.append(self.base.allocator, .{
.n_strx = 0,
.n_type = macho.N_SECT,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
const atom = try self.createEmptyAtom(local_sym_index, @sizeOf(u64), 3);
try atom.relocs.append(self.base.allocator, .{
.offset = 0,
.target = target,
.addend = 0,
.subtractor = null,
.pcrel = false,
.length = 3,
.@"type" = switch (self.base.options.target.cpu.arch) {
.aarch64 => @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_UNSIGNED),
.x86_64 => @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_UNSIGNED),
else => unreachable,
},
});
switch (target) {
.local => {
try atom.rebases.append(self.base.allocator, 0);
},
.global => |n_strx| {
try atom.bindings.append(self.base.allocator, .{
.n_strx = n_strx,
.offset = 0,
});
},
}
return atom;
}
pub fn createTlvPtrAtom(self: *MachO, target: Atom.Relocation.Target) !*Atom {
const local_sym_index = @intCast(u32, self.locals.items.len);
try self.locals.append(self.base.allocator, .{
.n_strx = 0,
.n_type = macho.N_SECT,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
const atom = try self.createEmptyAtom(local_sym_index, @sizeOf(u64), 3);
assert(target == .global);
try atom.bindings.append(self.base.allocator, .{
.n_strx = target.global,
.offset = 0,
});
return atom;
}
fn createDyldPrivateAtom(self: *MachO) !void {
if (self.dyld_private_atom != null) return;
const local_sym_index = @intCast(u32, self.locals.items.len);
const sym = try self.locals.addOne(self.base.allocator);
sym.* = .{
.n_strx = 0,
.n_type = macho.N_SECT,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
};
const atom = try self.createEmptyAtom(local_sym_index, @sizeOf(u64), 3);
self.dyld_private_atom = atom;
const match = MatchingSection{
.seg = self.data_segment_cmd_index.?,
.sect = self.data_section_index.?,
};
if (self.needs_prealloc) {
const vaddr = try self.allocateAtom(atom, @sizeOf(u64), 8, match);
log.debug("allocated {s} atom at 0x{x}", .{ self.getString(sym.n_strx), vaddr });
sym.n_value = vaddr;
} else try self.addAtomToSection(atom, match);
sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1);
}
fn createStubHelperPreambleAtom(self: *MachO) !void {
if (self.stub_helper_preamble_atom != null) return;
const arch = self.base.options.target.cpu.arch;
const size: u64 = switch (arch) {
.x86_64 => 15,
.aarch64 => 6 * @sizeOf(u32),
else => unreachable,
};
const alignment: u32 = switch (arch) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable,
};
const local_sym_index = @intCast(u32, self.locals.items.len);
const sym = try self.locals.addOne(self.base.allocator);
sym.* = .{
.n_strx = 0,
.n_type = macho.N_SECT,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
};
const atom = try self.createEmptyAtom(local_sym_index, size, alignment);
const dyld_private_sym_index = self.dyld_private_atom.?.local_sym_index;
switch (arch) {
.x86_64 => {
try atom.relocs.ensureUnusedCapacity(self.base.allocator, 2);
// lea %r11, [rip + disp]
atom.code.items[0] = 0x4c;
atom.code.items[1] = 0x8d;
atom.code.items[2] = 0x1d;
atom.relocs.appendAssumeCapacity(.{
.offset = 3,
.target = .{ .local = dyld_private_sym_index },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_SIGNED),
});
// push %r11
atom.code.items[7] = 0x41;
atom.code.items[8] = 0x53;
// jmp [rip + disp]
atom.code.items[9] = 0xff;
atom.code.items[10] = 0x25;
atom.relocs.appendAssumeCapacity(.{
.offset = 11,
.target = .{ .global = self.undefs.items[self.dyld_stub_binder_index.?].n_strx },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_GOT),
});
},
.aarch64 => {
try atom.relocs.ensureUnusedCapacity(self.base.allocator, 4);
// adrp x17, 0
mem.writeIntLittle(u32, atom.code.items[0..][0..4], aarch64.Instruction.adrp(.x17, 0).toU32());
atom.relocs.appendAssumeCapacity(.{
.offset = 0,
.target = .{ .local = dyld_private_sym_index },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_PAGE21),
});
// add x17, x17, 0
mem.writeIntLittle(u32, atom.code.items[4..][0..4], aarch64.Instruction.add(.x17, .x17, 0, false).toU32());
atom.relocs.appendAssumeCapacity(.{
.offset = 4,
.target = .{ .local = dyld_private_sym_index },
.addend = 0,
.subtractor = null,
.pcrel = false,
.length = 2,
.@"type" = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_PAGEOFF12),
});
// stp x16, x17, [sp, #-16]!
mem.writeIntLittle(u32, atom.code.items[8..][0..4], aarch64.Instruction.stp(
.x16,
.x17,
aarch64.Register.sp,
aarch64.Instruction.LoadStorePairOffset.pre_index(-16),
).toU32());
// adrp x16, 0
mem.writeIntLittle(u32, atom.code.items[12..][0..4], aarch64.Instruction.adrp(.x16, 0).toU32());
atom.relocs.appendAssumeCapacity(.{
.offset = 12,
.target = .{ .global = self.undefs.items[self.dyld_stub_binder_index.?].n_strx },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_GOT_LOAD_PAGE21),
});
// ldr x16, [x16, 0]
mem.writeIntLittle(u32, atom.code.items[16..][0..4], aarch64.Instruction.ldr(
.x16,
.x16,
aarch64.Instruction.LoadStoreOffset.imm(0),
).toU32());
atom.relocs.appendAssumeCapacity(.{
.offset = 16,
.target = .{ .global = self.undefs.items[self.dyld_stub_binder_index.?].n_strx },
.addend = 0,
.subtractor = null,
.pcrel = false,
.length = 2,
.@"type" = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_GOT_LOAD_PAGEOFF12),
});
// br x16
mem.writeIntLittle(u32, atom.code.items[20..][0..4], aarch64.Instruction.br(.x16).toU32());
},
else => unreachable,
}
self.stub_helper_preamble_atom = atom;
const match = MatchingSection{
.seg = self.text_segment_cmd_index.?,
.sect = self.stub_helper_section_index.?,
};
if (self.needs_prealloc) {
const alignment_pow_2 = try math.powi(u32, 2, atom.alignment);
const vaddr = try self.allocateAtom(atom, atom.size, alignment_pow_2, match);
log.debug("allocated {s} atom at 0x{x}", .{ self.getString(sym.n_strx), vaddr });
sym.n_value = vaddr;
} else try self.addAtomToSection(atom, match);
sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1);
}
pub fn createStubHelperAtom(self: *MachO) !*Atom {
const arch = self.base.options.target.cpu.arch;
const stub_size: u4 = switch (arch) {
.x86_64 => 10,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable,
};
const alignment: u2 = switch (arch) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable,
};
const local_sym_index = @intCast(u32, self.locals.items.len);
try self.locals.append(self.base.allocator, .{
.n_strx = 0,
.n_type = macho.N_SECT,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
const atom = try self.createEmptyAtom(local_sym_index, stub_size, alignment);
try atom.relocs.ensureTotalCapacity(self.base.allocator, 1);
switch (arch) {
.x86_64 => {
// pushq
atom.code.items[0] = 0x68;
// Next 4 bytes 1..4 are just a placeholder populated in `populateLazyBindOffsetsInStubHelper`.
// jmpq
atom.code.items[5] = 0xe9;
atom.relocs.appendAssumeCapacity(.{
.offset = 6,
.target = .{ .local = self.stub_helper_preamble_atom.?.local_sym_index },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_BRANCH),
});
},
.aarch64 => {
const literal = blk: {
const div_res = try math.divExact(u64, stub_size - @sizeOf(u32), 4);
break :blk try math.cast(u18, div_res);
};
// ldr w16, literal
mem.writeIntLittle(u32, atom.code.items[0..4], aarch64.Instruction.ldrLiteral(
.w16,
literal,
).toU32());
// b disp
mem.writeIntLittle(u32, atom.code.items[4..8], aarch64.Instruction.b(0).toU32());
atom.relocs.appendAssumeCapacity(.{
.offset = 4,
.target = .{ .local = self.stub_helper_preamble_atom.?.local_sym_index },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_BRANCH26),
});
// Next 4 bytes 8..12 are just a placeholder populated in `populateLazyBindOffsetsInStubHelper`.
},
else => unreachable,
}
return atom;
}
pub fn createLazyPointerAtom(self: *MachO, stub_sym_index: u32, n_strx: u32) !*Atom {
const local_sym_index = @intCast(u32, self.locals.items.len);
try self.locals.append(self.base.allocator, .{
.n_strx = 0,
.n_type = macho.N_SECT,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
const atom = try self.createEmptyAtom(local_sym_index, @sizeOf(u64), 3);
try atom.relocs.append(self.base.allocator, .{
.offset = 0,
.target = .{ .local = stub_sym_index },
.addend = 0,
.subtractor = null,
.pcrel = false,
.length = 3,
.@"type" = switch (self.base.options.target.cpu.arch) {
.aarch64 => @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_UNSIGNED),
.x86_64 => @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_UNSIGNED),
else => unreachable,
},
});
try atom.rebases.append(self.base.allocator, 0);
try atom.lazy_bindings.append(self.base.allocator, .{
.n_strx = n_strx,
.offset = 0,
});
return atom;
}
pub fn createStubAtom(self: *MachO, laptr_sym_index: u32) !*Atom {
const arch = self.base.options.target.cpu.arch;
const alignment: u2 = switch (arch) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable, // unhandled architecture type
};
const stub_size: u4 = switch (arch) {
.x86_64 => 6,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable, // unhandled architecture type
};
const local_sym_index = @intCast(u32, self.locals.items.len);
try self.locals.append(self.base.allocator, .{
.n_strx = 0,
.n_type = macho.N_SECT,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
const atom = try self.createEmptyAtom(local_sym_index, stub_size, alignment);
switch (arch) {
.x86_64 => {
// jmp
atom.code.items[0] = 0xff;
atom.code.items[1] = 0x25;
try atom.relocs.append(self.base.allocator, .{
.offset = 2,
.target = .{ .local = laptr_sym_index },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_BRANCH),
});
},
.aarch64 => {
try atom.relocs.ensureTotalCapacity(self.base.allocator, 2);
// adrp x16, pages
mem.writeIntLittle(u32, atom.code.items[0..4], aarch64.Instruction.adrp(.x16, 0).toU32());
atom.relocs.appendAssumeCapacity(.{
.offset = 0,
.target = .{ .local = laptr_sym_index },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_PAGE21),
});
// ldr x16, x16, offset
mem.writeIntLittle(u32, atom.code.items[4..8], aarch64.Instruction.ldr(
.x16,
.x16,
aarch64.Instruction.LoadStoreOffset.imm(0),
).toU32());
atom.relocs.appendAssumeCapacity(.{
.offset = 4,
.target = .{ .local = laptr_sym_index },
.addend = 0,
.subtractor = null,
.pcrel = false,
.length = 2,
.@"type" = @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_PAGEOFF12),
});
// br x16
mem.writeIntLittle(u32, atom.code.items[8..12], aarch64.Instruction.br(.x16).toU32());
},
else => unreachable,
}
return atom;
}
fn createTentativeDefAtoms(self: *MachO) !void {
if (self.tentatives.count() == 0) return;
// Convert any tentative definition into a regular symbol and allocate
// text blocks for each tentative definition.
while (self.tentatives.popOrNull()) |entry| {
const match = MatchingSection{
.seg = self.data_segment_cmd_index.?,
.sect = self.bss_section_index.?,
};
_ = try self.section_ordinals.getOrPut(self.base.allocator, match);
const global_sym = &self.globals.items[entry.key];
const size = global_sym.n_value;
const alignment = (global_sym.n_desc >> 8) & 0x0f;
global_sym.n_value = 0;
global_sym.n_desc = 0;
global_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1);
const local_sym_index = @intCast(u32, self.locals.items.len);
const local_sym = try self.locals.addOne(self.base.allocator);
local_sym.* = .{
.n_strx = global_sym.n_strx,
.n_type = macho.N_SECT,
.n_sect = global_sym.n_sect,
.n_desc = 0,
.n_value = 0,
};
const resolv = self.symbol_resolver.getPtr(local_sym.n_strx) orelse unreachable;
resolv.local_sym_index = local_sym_index;
const atom = try self.createEmptyAtom(local_sym_index, size, alignment);
if (self.needs_prealloc) {
const alignment_pow_2 = try math.powi(u32, 2, alignment);
const vaddr = try self.allocateAtom(atom, size, alignment_pow_2, match);
local_sym.n_value = vaddr;
global_sym.n_value = vaddr;
} else try self.addAtomToSection(atom, match);
}
}
fn createDsoHandleAtom(self: *MachO) !void {
if (self.strtab_dir.getKeyAdapted(@as([]const u8, "___dso_handle"), StringIndexAdapter{
.bytes = &self.strtab,
})) |n_strx| blk: {
const resolv = self.symbol_resolver.getPtr(n_strx) orelse break :blk;
if (resolv.where != .undef) break :blk;
const undef = &self.undefs.items[resolv.where_index];
const match: MatchingSection = .{
.seg = self.text_segment_cmd_index.?,
.sect = self.text_section_index.?,
};
const local_sym_index = @intCast(u32, self.locals.items.len);
var nlist = macho.nlist_64{
.n_strx = undef.n_strx,
.n_type = macho.N_SECT,
.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1),
.n_desc = 0,
.n_value = 0,
};
try self.locals.append(self.base.allocator, nlist);
const global_sym_index = @intCast(u32, self.globals.items.len);
nlist.n_type |= macho.N_EXT;
nlist.n_desc = macho.N_WEAK_DEF;
try self.globals.append(self.base.allocator, nlist);
assert(self.unresolved.swapRemove(resolv.where_index));
undef.* = .{
.n_strx = 0,
.n_type = macho.N_UNDF,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
};
resolv.* = .{
.where = .global,
.where_index = global_sym_index,
.local_sym_index = local_sym_index,
};
// We create an empty atom for this symbol.
// TODO perhaps we should special-case special symbols? Create a separate
// linked list of atoms?
const atom = try self.createEmptyAtom(local_sym_index, 0, 0);
if (self.needs_prealloc) {
const sym = &self.locals.items[local_sym_index];
const vaddr = try self.allocateAtom(atom, 0, 1, match);
sym.n_value = vaddr;
} else try self.addAtomToSection(atom, match);
}
}
fn resolveSymbolsInObject(self: *MachO, object_id: u16) !void {
const object = &self.objects.items[object_id];
log.debug("resolving symbols in '{s}'", .{object.name});
for (object.symtab.items) |sym, id| {
const sym_id = @intCast(u32, id);
const sym_name = object.getString(sym.n_strx);
if (sym.stab()) {
log.err("unhandled symbol type: stab", .{});
log.err(" symbol '{s}'", .{sym_name});
log.err(" first definition in '{s}'", .{object.name});
return error.UnhandledSymbolType;
}
if (sym.indr()) {
log.err("unhandled symbol type: indirect", .{});
log.err(" symbol '{s}'", .{sym_name});
log.err(" first definition in '{s}'", .{object.name});
return error.UnhandledSymbolType;
}
if (sym.abs()) {
log.err("unhandled symbol type: absolute", .{});
log.err(" symbol '{s}'", .{sym_name});
log.err(" first definition in '{s}'", .{object.name});
return error.UnhandledSymbolType;
}
if (sym.sect()) {
// Defined symbol regardless of scope lands in the locals symbol table.
const local_sym_index = @intCast(u32, self.locals.items.len);
try self.locals.append(self.base.allocator, .{
.n_strx = if (symbolIsTemp(sym, sym_name)) 0 else try self.makeString(sym_name),
.n_type = macho.N_SECT,
.n_sect = 0,
.n_desc = 0,
.n_value = sym.n_value,
});
try object.symbol_mapping.putNoClobber(self.base.allocator, sym_id, local_sym_index);
try object.reverse_symbol_mapping.putNoClobber(self.base.allocator, local_sym_index, sym_id);
// If the symbol's scope is not local aka translation unit, then we need work out
// if we should save the symbol as a global, or potentially flag the error.
if (!sym.ext()) continue;
const n_strx = try self.makeString(sym_name);
const local = self.locals.items[local_sym_index];
const resolv = self.symbol_resolver.getPtr(n_strx) orelse {
const global_sym_index = @intCast(u32, self.globals.items.len);
try self.globals.append(self.base.allocator, .{
.n_strx = n_strx,
.n_type = sym.n_type,
.n_sect = 0,
.n_desc = sym.n_desc,
.n_value = sym.n_value,
});
try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{
.where = .global,
.where_index = global_sym_index,
.local_sym_index = local_sym_index,
.file = object_id,
});
continue;
};
switch (resolv.where) {
.global => {
const global = &self.globals.items[resolv.where_index];
if (global.tentative()) {
assert(self.tentatives.swapRemove(resolv.where_index));
} else if (!(sym.weakDef() or sym.pext()) and !(global.weakDef() or global.pext())) {
log.err("symbol '{s}' defined multiple times", .{sym_name});
if (resolv.file) |file| {
log.err(" first definition in '{s}'", .{self.objects.items[file].name});
}
log.err(" next definition in '{s}'", .{object.name});
return error.MultipleSymbolDefinitions;
} else if (sym.weakDef() or sym.pext()) continue; // Current symbol is weak, so skip it.
// Otherwise, update the resolver and the global symbol.
global.n_type = sym.n_type;
resolv.local_sym_index = local_sym_index;
resolv.file = object_id;
continue;
},
.undef => {
const undef = &self.undefs.items[resolv.where_index];
undef.* = .{
.n_strx = 0,
.n_type = macho.N_UNDF,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
};
assert(self.unresolved.swapRemove(resolv.where_index));
},
}
const global_sym_index = @intCast(u32, self.globals.items.len);
try self.globals.append(self.base.allocator, .{
.n_strx = local.n_strx,
.n_type = sym.n_type,
.n_sect = 0,
.n_desc = sym.n_desc,
.n_value = sym.n_value,
});
resolv.* = .{
.where = .global,
.where_index = global_sym_index,
.local_sym_index = local_sym_index,
.file = object_id,
};
} else if (sym.tentative()) {
// Symbol is a tentative definition.
const n_strx = try self.makeString(sym_name);
const resolv = self.symbol_resolver.getPtr(n_strx) orelse {
const global_sym_index = @intCast(u32, self.globals.items.len);
try self.globals.append(self.base.allocator, .{
.n_strx = try self.makeString(sym_name),
.n_type = sym.n_type,
.n_sect = 0,
.n_desc = sym.n_desc,
.n_value = sym.n_value,
});
try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{
.where = .global,
.where_index = global_sym_index,
.file = object_id,
});
_ = try self.tentatives.getOrPut(self.base.allocator, global_sym_index);
continue;
};
switch (resolv.where) {
.global => {
const global = &self.globals.items[resolv.where_index];
if (!global.tentative()) continue;
if (global.n_value >= sym.n_value) continue;
global.n_desc = sym.n_desc;
global.n_value = sym.n_value;
resolv.file = object_id;
},
.undef => {
const undef = &self.undefs.items[resolv.where_index];
const global_sym_index = @intCast(u32, self.globals.items.len);
try self.globals.append(self.base.allocator, .{
.n_strx = undef.n_strx,
.n_type = sym.n_type,
.n_sect = 0,
.n_desc = sym.n_desc,
.n_value = sym.n_value,
});
_ = try self.tentatives.getOrPut(self.base.allocator, global_sym_index);
assert(self.unresolved.swapRemove(resolv.where_index));
resolv.* = .{
.where = .global,
.where_index = global_sym_index,
.file = object_id,
};
undef.* = .{
.n_strx = 0,
.n_type = macho.N_UNDF,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
};
},
}
} else {
// Symbol is undefined.
const n_strx = try self.makeString(sym_name);
if (self.symbol_resolver.contains(n_strx)) continue;
const undef_sym_index = @intCast(u32, self.undefs.items.len);
try self.undefs.append(self.base.allocator, .{
.n_strx = try self.makeString(sym_name),
.n_type = macho.N_UNDF,
.n_sect = 0,
.n_desc = sym.n_desc,
.n_value = 0,
});
try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{
.where = .undef,
.where_index = undef_sym_index,
.file = object_id,
});
try self.unresolved.putNoClobber(self.base.allocator, undef_sym_index, .none);
}
}
}
fn resolveSymbolsInArchives(self: *MachO) !void {
if (self.archives.items.len == 0) return;
var next_sym: usize = 0;
loop: while (next_sym < self.unresolved.count()) {
const sym = self.undefs.items[self.unresolved.keys()[next_sym]];
const sym_name = self.getString(sym.n_strx);
for (self.archives.items) |archive| {
// Check if the entry exists in a static archive.
const offsets = archive.toc.get(sym_name) orelse {
// No hit.
continue;
};
assert(offsets.items.len > 0);
const object_id = @intCast(u16, self.objects.items.len);
const object = try self.objects.addOne(self.base.allocator);
object.* = try archive.parseObject(self.base.allocator, self.base.options.target, offsets.items[0]);
try self.resolveSymbolsInObject(object_id);
continue :loop;
}
next_sym += 1;
}
}
fn resolveSymbolsInDylibs(self: *MachO) !void {
if (self.dylibs.items.len == 0) return;
var next_sym: usize = 0;
loop: while (next_sym < self.unresolved.count()) {
const sym = self.undefs.items[self.unresolved.keys()[next_sym]];
const sym_name = self.getString(sym.n_strx);
for (self.dylibs.items) |dylib, id| {
if (!dylib.symbols.contains(sym_name)) continue;
const dylib_id = @intCast(u16, id);
if (!self.referenced_dylibs.contains(dylib_id)) {
try self.addLoadDylibLC(dylib_id);
try self.referenced_dylibs.putNoClobber(self.base.allocator, dylib_id, {});
}
const ordinal = self.referenced_dylibs.getIndex(dylib_id) orelse unreachable;
const resolv = self.symbol_resolver.getPtr(sym.n_strx) orelse unreachable;
const undef = &self.undefs.items[resolv.where_index];
undef.n_type |= macho.N_EXT;
undef.n_desc = @intCast(u16, ordinal + 1) * macho.N_SYMBOL_RESOLVER;
if (self.unresolved.fetchSwapRemove(resolv.where_index)) |entry| outer_blk: {
switch (entry.value) {
.none => {},
.got => return error.TODOGotHint,
.stub => {
if (self.stubs_table.contains(sym.n_strx)) break :outer_blk;
const stub_helper_atom = blk: {
const match = MatchingSection{
.seg = self.text_segment_cmd_index.?,
.sect = self.stub_helper_section_index.?,
};
const atom = try self.createStubHelperAtom();
const atom_sym = &self.locals.items[atom.local_sym_index];
const alignment = try math.powi(u32, 2, atom.alignment);
const vaddr = try self.allocateAtom(atom, atom.size, alignment, match);
atom_sym.n_value = vaddr;
atom_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1);
break :blk atom;
};
const laptr_atom = blk: {
const match = MatchingSection{
.seg = self.data_segment_cmd_index.?,
.sect = self.la_symbol_ptr_section_index.?,
};
const atom = try self.createLazyPointerAtom(
stub_helper_atom.local_sym_index,
sym.n_strx,
);
const atom_sym = &self.locals.items[atom.local_sym_index];
const alignment = try math.powi(u32, 2, atom.alignment);
const vaddr = try self.allocateAtom(atom, atom.size, alignment, match);
atom_sym.n_value = vaddr;
atom_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1);
break :blk atom;
};
const stub_atom = blk: {
const match = MatchingSection{
.seg = self.text_segment_cmd_index.?,
.sect = self.stubs_section_index.?,
};
const atom = try self.createStubAtom(laptr_atom.local_sym_index);
const atom_sym = &self.locals.items[atom.local_sym_index];
const alignment = try math.powi(u32, 2, atom.alignment);
const vaddr = try self.allocateAtom(atom, atom.size, alignment, match);
atom_sym.n_value = vaddr;
atom_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1);
break :blk atom;
};
const stub_index = @intCast(u32, self.stubs.items.len);
try self.stubs.append(self.base.allocator, stub_atom);
try self.stubs_table.putNoClobber(self.base.allocator, sym.n_strx, stub_index);
},
}
}
continue :loop;
}
next_sym += 1;
}
}
fn createMhExecuteHeaderAtom(self: *MachO) !void {
if (self.mh_execute_header_index != null) return;
const match: MatchingSection = .{
.seg = self.text_segment_cmd_index.?,
.sect = self.text_section_index.?,
};
const seg = self.load_commands.items[match.seg].segment;
const sect = seg.sections.items[match.sect];
const n_strx = try self.makeString("__mh_execute_header");
const local_sym_index = @intCast(u32, self.locals.items.len);
var nlist = macho.nlist_64{
.n_strx = n_strx,
.n_type = macho.N_SECT,
.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1),
.n_desc = 0,
.n_value = sect.addr,
};
try self.locals.append(self.base.allocator, nlist);
self.mh_execute_header_index = local_sym_index;
if (self.symbol_resolver.getPtr(n_strx)) |resolv| {
const global = &self.globals.items[resolv.where_index];
if (!(global.weakDef() or !global.pext())) {
log.err("symbol '__mh_execute_header' defined multiple times", .{});
return error.MultipleSymbolDefinitions;
}
resolv.local_sym_index = local_sym_index;
} else {
const global_sym_index = @intCast(u32, self.globals.items.len);
nlist.n_type |= macho.N_EXT;
try self.globals.append(self.base.allocator, nlist);
try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{
.where = .global,
.where_index = global_sym_index,
.local_sym_index = local_sym_index,
.file = null,
});
}
// We always set the __mh_execute_header to point to the beginning of the __TEXT,__text section
const atom = try self.createEmptyAtom(local_sym_index, 0, 0);
if (self.atoms.get(match)) |last| {
var first = last;
while (first.prev) |prev| {
first = prev;
}
atom.next = first;
first.prev = atom;
} else {
try self.atoms.putNoClobber(self.base.allocator, match, atom);
}
}
fn resolveDyldStubBinder(self: *MachO) !void {
if (self.dyld_stub_binder_index != null) return;
const n_strx = try self.makeString("dyld_stub_binder");
const sym_index = @intCast(u32, self.undefs.items.len);
try self.undefs.append(self.base.allocator, .{
.n_strx = n_strx,
.n_type = macho.N_UNDF,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{
.where = .undef,
.where_index = sym_index,
});
const sym = &self.undefs.items[sym_index];
const sym_name = self.getString(n_strx);
for (self.dylibs.items) |dylib, id| {
if (!dylib.symbols.contains(sym_name)) continue;
const dylib_id = @intCast(u16, id);
if (!self.referenced_dylibs.contains(dylib_id)) {
try self.addLoadDylibLC(dylib_id);
try self.referenced_dylibs.putNoClobber(self.base.allocator, dylib_id, {});
}
const ordinal = self.referenced_dylibs.getIndex(dylib_id) orelse unreachable;
sym.n_type |= macho.N_EXT;
sym.n_desc = @intCast(u16, ordinal + 1) * macho.N_SYMBOL_RESOLVER;
self.dyld_stub_binder_index = sym_index;
break;
}
if (self.dyld_stub_binder_index == null) {
log.err("undefined reference to symbol '{s}'", .{sym_name});
return error.UndefinedSymbolReference;
}
// Add dyld_stub_binder as the final GOT entry.
const target = Atom.Relocation.Target{ .global = n_strx };
const atom = try self.createGotAtom(target);
const got_index = @intCast(u32, self.got_entries.items.len);
try self.got_entries.append(self.base.allocator, .{ .target = target, .atom = atom });
try self.got_entries_table.putNoClobber(self.base.allocator, target, got_index);
const match = MatchingSection{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.got_section_index.?,
};
const atom_sym = &self.locals.items[atom.local_sym_index];
if (self.needs_prealloc) {
const vaddr = try self.allocateAtom(atom, @sizeOf(u64), 8, match);
log.debug("allocated {s} atom at 0x{x}", .{ self.getString(sym.n_strx), vaddr });
atom_sym.n_value = vaddr;
} else try self.addAtomToSection(atom, match);
atom_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1);
}
fn parseObjectsIntoAtoms(self: *MachO) !void {
// TODO I need to see if I can simplify this logic, or perhaps split it into two functions:
// one for non-prealloc traditional path, and one for incremental prealloc path.
const tracy = trace(@src());
defer tracy.end();
var parsed_atoms = std.AutoArrayHashMap(MatchingSection, *Atom).init(self.base.allocator);
defer parsed_atoms.deinit();
var first_atoms = std.AutoArrayHashMap(MatchingSection, *Atom).init(self.base.allocator);
defer first_atoms.deinit();
var section_metadata = std.AutoHashMap(MatchingSection, struct {
size: u64,
alignment: u32,
}).init(self.base.allocator);
defer section_metadata.deinit();
for (self.objects.items) |*object| {
if (object.analyzed) continue;
try object.parseIntoAtoms(self.base.allocator, self);
var it = object.end_atoms.iterator();
while (it.next()) |entry| {
const match = entry.key_ptr.*;
var atom = entry.value_ptr.*;
while (atom.prev) |prev| {
atom = prev;
}
const first_atom = atom;
const seg = self.load_commands.items[match.seg].segment;
const sect = seg.sections.items[match.sect];
const metadata = try section_metadata.getOrPut(match);
if (!metadata.found_existing) {
metadata.value_ptr.* = .{
.size = sect.size,
.alignment = sect.@"align",
};
}
log.debug("{s},{s}", .{ sect.segName(), sect.sectName() });
while (true) {
const alignment = try math.powi(u32, 2, atom.alignment);
const curr_size = metadata.value_ptr.size;
const curr_size_aligned = mem.alignForwardGeneric(u64, curr_size, alignment);
metadata.value_ptr.size = curr_size_aligned + atom.size;
metadata.value_ptr.alignment = math.max(metadata.value_ptr.alignment, atom.alignment);
const sym = self.locals.items[atom.local_sym_index];
log.debug(" {s}: n_value=0x{x}, size=0x{x}, alignment=0x{x}", .{
self.getString(sym.n_strx),
sym.n_value,
atom.size,
atom.alignment,
});
if (atom.next) |next| {
atom = next;
} else break;
}
if (parsed_atoms.getPtr(match)) |last| {
last.*.next = first_atom;
first_atom.prev = last.*;
last.* = first_atom;
}
_ = try parsed_atoms.put(match, atom);
if (!first_atoms.contains(match)) {
try first_atoms.putNoClobber(match, first_atom);
}
}
object.analyzed = true;
}
var it = section_metadata.iterator();
while (it.next()) |entry| {
const match = entry.key_ptr.*;
const metadata = entry.value_ptr.*;
const seg = &self.load_commands.items[match.seg].segment;
const sect = &seg.sections.items[match.sect];
log.debug("{s},{s} => size: 0x{x}, alignment: 0x{x}", .{
sect.segName(),
sect.sectName(),
metadata.size,
metadata.alignment,
});
sect.@"align" = math.max(sect.@"align", metadata.alignment);
const needed_size = @intCast(u32, metadata.size);
if (self.needs_prealloc) {
try self.growSection(match, needed_size);
}
sect.size = needed_size;
}
for (&[_]?u16{
self.text_segment_cmd_index,
self.data_const_segment_cmd_index,
self.data_segment_cmd_index,
}) |maybe_seg_id| {
const seg_id = maybe_seg_id orelse continue;
const seg = self.load_commands.items[seg_id].segment;
for (seg.sections.items) |sect, sect_id| {
const match = MatchingSection{
.seg = seg_id,
.sect = @intCast(u16, sect_id),
};
if (!section_metadata.contains(match)) continue;
var base_vaddr = if (self.atoms.get(match)) |last| blk: {
const last_atom_sym = self.locals.items[last.local_sym_index];
break :blk last_atom_sym.n_value + last.size;
} else sect.addr;
if (self.atoms.getPtr(match)) |last| {
const first_atom = first_atoms.get(match).?;
last.*.next = first_atom;
first_atom.prev = last.*;
last.* = first_atom;
}
_ = try self.atoms.put(self.base.allocator, match, parsed_atoms.get(match).?);
if (!self.needs_prealloc) continue;
const n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1);
var atom = first_atoms.get(match).?;
while (true) {
const alignment = try math.powi(u32, 2, atom.alignment);
base_vaddr = mem.alignForwardGeneric(u64, base_vaddr, alignment);
const sym = &self.locals.items[atom.local_sym_index];
sym.n_value = base_vaddr;
sym.n_sect = n_sect;
log.debug(" {s}: start=0x{x}, end=0x{x}, size=0x{x}, alignment=0x{x}", .{
self.getString(sym.n_strx),
base_vaddr,
base_vaddr + atom.size,
atom.size,
atom.alignment,
});
// Update each alias (if any)
for (atom.aliases.items) |index| {
const alias_sym = &self.locals.items[index];
alias_sym.n_value = base_vaddr;
alias_sym.n_sect = n_sect;
}
// Update each symbol contained within the atom
for (atom.contained.items) |sym_at_off| {
const contained_sym = &self.locals.items[sym_at_off.local_sym_index];
contained_sym.n_value = base_vaddr + sym_at_off.offset;
contained_sym.n_sect = n_sect;
}
base_vaddr += atom.size;
if (atom.next) |next| {
atom = next;
} else break;
}
}
}
}
fn addLoadDylibLC(self: *MachO, id: u16) !void {
const dylib = self.dylibs.items[id];
const dylib_id = dylib.id orelse unreachable;
var dylib_cmd = try macho.createLoadDylibCommand(
self.base.allocator,
dylib_id.name,
dylib_id.timestamp,
dylib_id.current_version,
dylib_id.compatibility_version,
);
errdefer dylib_cmd.deinit(self.base.allocator);
try self.load_commands.append(self.base.allocator, .{ .dylib = dylib_cmd });
self.load_commands_dirty = true;
}
fn addCodeSignatureLC(self: *MachO) !void {
if (self.code_signature_cmd_index != null or !self.requires_adhoc_codesig) return;
self.code_signature_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.linkedit_data = .{
.cmd = .CODE_SIGNATURE,
.cmdsize = @sizeOf(macho.linkedit_data_command),
.dataoff = 0,
.datasize = 0,
},
});
self.load_commands_dirty = true;
}
fn setEntryPoint(self: *MachO) !void {
if (self.base.options.output_mode != .Exe) return;
// TODO we should respect the -entry flag passed in by the user to set a custom
// entrypoint. For now, assume default of `_main`.
const seg = self.load_commands.items[self.text_segment_cmd_index.?].segment;
const n_strx = self.strtab_dir.getKeyAdapted(@as([]const u8, "_main"), StringIndexAdapter{
.bytes = &self.strtab,
}) orelse {
log.err("'_main' export not found", .{});
return error.MissingMainEntrypoint;
};
const resolv = self.symbol_resolver.get(n_strx) orelse unreachable;
assert(resolv.where == .global);
const sym = self.globals.items[resolv.where_index];
const ec = &self.load_commands.items[self.main_cmd_index.?].main;
ec.entryoff = @intCast(u32, sym.n_value - seg.inner.vmaddr);
ec.stacksize = self.base.options.stack_size_override orelse 0;
self.entry_addr = sym.n_value;
self.load_commands_dirty = true;
}
pub fn deinit(self: *MachO) void {
if (build_options.have_llvm) {
if (self.llvm_object) |llvm_object| llvm_object.destroy(self.base.allocator);
}
if (self.d_sym) |*d_sym| {
d_sym.deinit(self.base.allocator);
}
self.section_ordinals.deinit(self.base.allocator);
self.tlv_ptr_entries.deinit(self.base.allocator);
self.tlv_ptr_entries_free_list.deinit(self.base.allocator);
self.tlv_ptr_entries_table.deinit(self.base.allocator);
self.got_entries.deinit(self.base.allocator);
self.got_entries_free_list.deinit(self.base.allocator);
self.got_entries_table.deinit(self.base.allocator);
self.stubs.deinit(self.base.allocator);
self.stubs_free_list.deinit(self.base.allocator);
self.stubs_table.deinit(self.base.allocator);
self.strtab_dir.deinit(self.base.allocator);
self.strtab.deinit(self.base.allocator);
self.undefs.deinit(self.base.allocator);
self.globals.deinit(self.base.allocator);
self.globals_free_list.deinit(self.base.allocator);
self.locals.deinit(self.base.allocator);
self.locals_free_list.deinit(self.base.allocator);
self.symbol_resolver.deinit(self.base.allocator);
self.unresolved.deinit(self.base.allocator);
self.tentatives.deinit(self.base.allocator);
for (self.objects.items) |*object| {
object.deinit(self.base.allocator);
}
self.objects.deinit(self.base.allocator);
for (self.archives.items) |*archive| {
archive.deinit(self.base.allocator);
}
self.archives.deinit(self.base.allocator);
for (self.dylibs.items) |*dylib| {
dylib.deinit(self.base.allocator);
}
self.dylibs.deinit(self.base.allocator);
self.dylibs_map.deinit(self.base.allocator);
self.referenced_dylibs.deinit(self.base.allocator);
for (self.load_commands.items) |*lc| {
lc.deinit(self.base.allocator);
}
self.load_commands.deinit(self.base.allocator);
for (self.managed_atoms.items) |atom| {
atom.deinit(self.base.allocator);
self.base.allocator.destroy(atom);
}
self.managed_atoms.deinit(self.base.allocator);
self.atoms.deinit(self.base.allocator);
{
var it = self.atom_free_lists.valueIterator();
while (it.next()) |free_list| {
free_list.deinit(self.base.allocator);
}
self.atom_free_lists.deinit(self.base.allocator);
}
for (self.decls.keys()) |decl| {
decl.link.macho.deinit(self.base.allocator);
}
self.decls.deinit(self.base.allocator);
{
var it = self.unnamed_const_atoms.valueIterator();
while (it.next()) |atoms| {
atoms.deinit(self.base.allocator);
}
self.unnamed_const_atoms.deinit(self.base.allocator);
}
self.atom_by_index_table.deinit(self.base.allocator);
}
pub fn closeFiles(self: MachO) void {
for (self.objects.items) |object| {
object.file.close();
}
for (self.archives.items) |archive| {
archive.file.close();
}
for (self.dylibs.items) |dylib| {
dylib.file.close();
}
}
fn freeAtom(self: *MachO, atom: *Atom, match: MatchingSection, owns_atom: bool) void {
log.debug("freeAtom {*}", .{atom});
if (!owns_atom) {
atom.deinit(self.base.allocator);
}
const free_list = self.atom_free_lists.getPtr(match).?;
var already_have_free_list_node = false;
{
var i: usize = 0;
// TODO turn free_list into a hash map
while (i < free_list.items.len) {
if (free_list.items[i] == atom) {
_ = free_list.swapRemove(i);
continue;
}
if (free_list.items[i] == atom.prev) {
already_have_free_list_node = true;
}
i += 1;
}
}
if (self.atoms.getPtr(match)) |last_atom| {
if (last_atom.* == atom) {
if (atom.prev) |prev| {
// TODO shrink the section size here
last_atom.* = prev;
} else {
_ = self.atoms.fetchRemove(match);
}
}
}
if (atom.prev) |prev| {
prev.next = atom.next;
if (!already_have_free_list_node and prev.freeListEligible(self.*)) {
// The free list is heuristics, it doesn't have to be perfect, so we can ignore
// the OOM here.
free_list.append(self.base.allocator, prev) catch {};
}
} else {
atom.prev = null;
}
if (atom.next) |next| {
next.prev = atom.prev;
} else {
atom.next = null;
}
if (self.d_sym) |*d_sym| {
d_sym.dwarf.freeAtom(&atom.dbg_info_atom);
}
}
fn shrinkAtom(self: *MachO, atom: *Atom, new_block_size: u64, match: MatchingSection) void {
_ = self;
_ = atom;
_ = new_block_size;
_ = match;
// TODO check the new capacity, and if it crosses the size threshold into a big enough
// capacity, insert a free list node for it.
}
fn growAtom(self: *MachO, atom: *Atom, new_atom_size: u64, alignment: u64, match: MatchingSection) !u64 {
const sym = self.locals.items[atom.local_sym_index];
const align_ok = mem.alignBackwardGeneric(u64, sym.n_value, alignment) == sym.n_value;
const need_realloc = !align_ok or new_atom_size > atom.capacity(self.*);
if (!need_realloc) return sym.n_value;
return self.allocateAtom(atom, new_atom_size, alignment, match);
}
fn allocateLocalSymbol(self: *MachO) !u32 {
try self.locals.ensureUnusedCapacity(self.base.allocator, 1);
const index = blk: {
if (self.locals_free_list.popOrNull()) |index| {
log.debug(" (reusing symbol index {d})", .{index});
break :blk index;
} else {
log.debug(" (allocating symbol index {d})", .{self.locals.items.len});
const index = @intCast(u32, self.locals.items.len);
_ = self.locals.addOneAssumeCapacity();
break :blk index;
}
};
self.locals.items[index] = .{
.n_strx = 0,
.n_type = 0,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
};
return index;
}
pub fn allocateGotEntry(self: *MachO, target: Atom.Relocation.Target) !u32 {
try self.got_entries.ensureUnusedCapacity(self.base.allocator, 1);
const index = blk: {
if (self.got_entries_free_list.popOrNull()) |index| {
log.debug(" (reusing GOT entry index {d})", .{index});
break :blk index;
} else {
log.debug(" (allocating GOT entry at index {d})", .{self.got_entries.items.len});
const index = @intCast(u32, self.got_entries.items.len);
_ = self.got_entries.addOneAssumeCapacity();
break :blk index;
}
};
self.got_entries.items[index] = .{
.target = target,
.atom = undefined,
};
try self.got_entries_table.putNoClobber(self.base.allocator, target, index);
return index;
}
pub fn allocateStubEntry(self: *MachO, n_strx: u32) !u32 {
try self.stubs.ensureUnusedCapacity(self.base.allocator, 1);
const index = blk: {
if (self.stubs_free_list.popOrNull()) |index| {
log.debug(" (reusing stub entry index {d})", .{index});
break :blk index;
} else {
log.debug(" (allocating stub entry at index {d})", .{self.stubs.items.len});
const index = @intCast(u32, self.stubs.items.len);
_ = self.stubs.addOneAssumeCapacity();
break :blk index;
}
};
self.stubs.items[index] = undefined;
try self.stubs_table.putNoClobber(self.base.allocator, n_strx, index);
return index;
}
pub fn allocateTlvPtrEntry(self: *MachO, target: Atom.Relocation.Target) !u32 {
try self.tlv_ptr_entries.ensureUnusedCapacity(self.base.allocator, 1);
const index = blk: {
if (self.tlv_ptr_entries_free_list.popOrNull()) |index| {
log.debug(" (reusing TLV ptr entry index {d})", .{index});
break :blk index;
} else {
log.debug(" (allocating TLV ptr entry at index {d})", .{self.tlv_ptr_entries.items.len});
const index = @intCast(u32, self.tlv_ptr_entries.items.len);
_ = self.tlv_ptr_entries.addOneAssumeCapacity();
break :blk index;
}
};
self.tlv_ptr_entries.items[index] = .{ .target = target, .atom = undefined };
try self.tlv_ptr_entries_table.putNoClobber(self.base.allocator, target, index);
return index;
}
pub fn allocateDeclIndexes(self: *MachO, decl: *Module.Decl) !void {
if (self.llvm_object) |_| return;
if (decl.link.macho.local_sym_index != 0) return;
decl.link.macho.local_sym_index = try self.allocateLocalSymbol();
try self.atom_by_index_table.putNoClobber(self.base.allocator, decl.link.macho.local_sym_index, &decl.link.macho);
try self.decls.putNoClobber(self.base.allocator, decl, null);
const got_target = .{ .local = decl.link.macho.local_sym_index };
const got_index = try self.allocateGotEntry(got_target);
const got_atom = try self.createGotAtom(got_target);
self.got_entries.items[got_index].atom = got_atom;
}
pub fn updateFunc(self: *MachO, module: *Module, func: *Module.Fn, air: Air, liveness: Liveness) !void {
if (build_options.skip_non_native and builtin.object_format != .macho) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
if (build_options.have_llvm) {
if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(module, func, air, liveness);
}
const tracy = trace(@src());
defer tracy.end();
const decl = func.owner_decl;
self.freeUnnamedConsts(decl);
// TODO clearing the code and relocs buffer should probably be orchestrated
// in a different, smarter, more automatic way somewhere else, in a more centralised
// way than this.
// If we don't clear the buffers here, we are up for some nasty surprises when
// this atom is reused later on and was not freed by freeAtom().
decl.link.macho.clearRetainingCapacity();
var code_buffer = std.ArrayList(u8).init(self.base.allocator);
defer code_buffer.deinit();
var debug_buffers_buf: link.File.Dwarf.DeclDebugBuffers = undefined;
const debug_buffers = if (self.d_sym) |*d_sym| blk: {
debug_buffers_buf = try d_sym.initDeclDebugInfo(module, decl);
break :blk &debug_buffers_buf;
} else null;
defer {
if (debug_buffers) |dbg| {
dbg.dbg_line_buffer.deinit();
dbg.dbg_info_buffer.deinit();
for (dbg.dbg_info_type_relocs.values()) |*value| {
value.relocs.deinit(self.base.allocator);
}
dbg.dbg_info_type_relocs.deinit(self.base.allocator);
}
}
const res = if (debug_buffers) |dbg|
try codegen.generateFunction(&self.base, decl.srcLoc(), func, air, liveness, &code_buffer, .{
.dwarf = .{
.dbg_line = &dbg.dbg_line_buffer,
.dbg_info = &dbg.dbg_info_buffer,
.dbg_info_type_relocs = &dbg.dbg_info_type_relocs,
},
})
else
try codegen.generateFunction(&self.base, decl.srcLoc(), func, air, liveness, &code_buffer, .none);
switch (res) {
.appended => {
try decl.link.macho.code.appendSlice(self.base.allocator, code_buffer.items);
},
.fail => |em| {
decl.analysis = .codegen_failure;
try module.failed_decls.put(module.gpa, decl, em);
return;
},
}
_ = try self.placeDecl(decl, decl.link.macho.code.items.len);
if (debug_buffers) |db| {
if (self.d_sym) |*d_sym| {
try d_sym.commitDeclDebugInfo(module, decl, db);
}
}
// Since we updated the vaddr and the size, each corresponding export symbol also
// needs to be updated.
const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
try self.updateDeclExports(module, decl, decl_exports);
}
pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl: *Module.Decl) !u32 {
var code_buffer = std.ArrayList(u8).init(self.base.allocator);
defer code_buffer.deinit();
const module = self.base.options.module.?;
const gop = try self.unnamed_const_atoms.getOrPut(self.base.allocator, decl);
if (!gop.found_existing) {
gop.value_ptr.* = .{};
}
const unnamed_consts = gop.value_ptr;
const decl_name = try decl.getFullyQualifiedName(self.base.allocator);
defer self.base.allocator.free(decl_name);
const name_str_index = blk: {
const index = unnamed_consts.items.len;
const name = try std.fmt.allocPrint(self.base.allocator, "__unnamed_{s}_{d}", .{ decl_name, index });
defer self.base.allocator.free(name);
break :blk try self.makeString(name);
};
const name = self.getString(name_str_index);
log.debug("allocating symbol indexes for {s}", .{name});
const required_alignment = typed_value.ty.abiAlignment(self.base.options.target);
const local_sym_index = try self.allocateLocalSymbol();
const atom = try self.createEmptyAtom(local_sym_index, @sizeOf(u64), math.log2(required_alignment));
try self.atom_by_index_table.putNoClobber(self.base.allocator, local_sym_index, atom);
const res = try codegen.generateSymbol(&self.base, decl.srcLoc(), typed_value, &code_buffer, .none, .{
.parent_atom_index = local_sym_index,
});
const code = switch (res) {
.externally_managed => |x| x,
.appended => code_buffer.items,
.fail => |em| {
decl.analysis = .codegen_failure;
try module.failed_decls.put(module.gpa, decl, em);
log.err("{s}", .{em.msg});
return error.AnalysisFail;
},
};
atom.code.clearRetainingCapacity();
try atom.code.appendSlice(self.base.allocator, code);
const match = try self.getMatchingSectionAtom(atom, decl_name, typed_value.ty, typed_value.val);
const addr = try self.allocateAtom(atom, code.len, required_alignment, match);
log.debug("allocated atom for {s} at 0x{x}", .{ name, addr });
log.debug(" (required alignment 0x{x})", .{required_alignment});
errdefer self.freeAtom(atom, match, true);
const symbol = &self.locals.items[atom.local_sym_index];
symbol.* = .{
.n_strx = name_str_index,
.n_type = macho.N_SECT,
.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).?) + 1,
.n_desc = 0,
.n_value = addr,
};
try unnamed_consts.append(self.base.allocator, atom);
return atom.local_sym_index;
}
pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void {
if (build_options.skip_non_native and builtin.object_format != .macho) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
if (build_options.have_llvm) {
if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl);
}
const tracy = trace(@src());
defer tracy.end();
if (decl.val.tag() == .extern_fn) {
return; // TODO Should we do more when front-end analyzed extern decl?
}
if (decl.val.castTag(.variable)) |payload| {
const variable = payload.data;
if (variable.is_extern) {
return; // TODO Should we do more when front-end analyzed extern decl?
}
}
var code_buffer = std.ArrayList(u8).init(self.base.allocator);
defer code_buffer.deinit();
var debug_buffers_buf: link.File.Dwarf.DeclDebugBuffers = undefined;
const debug_buffers = if (self.d_sym) |*d_sym| blk: {
debug_buffers_buf = try d_sym.initDeclDebugInfo(module, decl);
break :blk &debug_buffers_buf;
} else null;
defer {
if (debug_buffers) |dbg| {
dbg.dbg_line_buffer.deinit();
dbg.dbg_info_buffer.deinit();
for (dbg.dbg_info_type_relocs.values()) |*value| {
value.relocs.deinit(self.base.allocator);
}
dbg.dbg_info_type_relocs.deinit(self.base.allocator);
}
}
const decl_val = if (decl.val.castTag(.variable)) |payload| payload.data.init else decl.val;
const res = if (debug_buffers) |dbg|
try codegen.generateSymbol(&self.base, decl.srcLoc(), .{
.ty = decl.ty,
.val = decl_val,
}, &code_buffer, .{
.dwarf = .{
.dbg_line = &dbg.dbg_line_buffer,
.dbg_info = &dbg.dbg_info_buffer,
.dbg_info_type_relocs = &dbg.dbg_info_type_relocs,
},
}, .{
.parent_atom_index = decl.link.macho.local_sym_index,
})
else
try codegen.generateSymbol(&self.base, decl.srcLoc(), .{
.ty = decl.ty,
.val = decl_val,
}, &code_buffer, .none, .{
.parent_atom_index = decl.link.macho.local_sym_index,
});
const code = blk: {
switch (res) {
.externally_managed => |x| break :blk x,
.appended => {
// TODO clearing the code and relocs buffer should probably be orchestrated
// in a different, smarter, more automatic way somewhere else, in a more centralised
// way than this.
// If we don't clear the buffers here, we are up for some nasty surprises when
// this atom is reused later on and was not freed by freeAtom().
decl.link.macho.code.clearAndFree(self.base.allocator);
try decl.link.macho.code.appendSlice(self.base.allocator, code_buffer.items);
break :blk decl.link.macho.code.items;
},
.fail => |em| {
decl.analysis = .codegen_failure;
try module.failed_decls.put(module.gpa, decl, em);
return;
},
}
};
_ = try self.placeDecl(decl, code.len);
// Since we updated the vaddr and the size, each corresponding export symbol also
// needs to be updated.
const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
try self.updateDeclExports(module, decl, decl_exports);
}
/// Checks if the value, or any of its embedded values stores a pointer, and thus requires
/// a rebase opcode for the dynamic linker.
fn needsPointerRebase(ty: Type, val: Value) bool {
if (ty.zigTypeTag() == .Fn) {
return false;
}
if (val.pointerDecl()) |_| {
return true;
}
switch (ty.zigTypeTag()) {
.Fn => unreachable,
.Pointer => return true,
.Array, .Vector => {
if (ty.arrayLen() == 0) return false;
const elem_ty = ty.childType();
var elem_value_buf: Value.ElemValueBuffer = undefined;
const elem_val = val.elemValueBuffer(0, &elem_value_buf);
return needsPointerRebase(elem_ty, elem_val);
},
.Struct => {
const fields = ty.structFields().values();
if (fields.len == 0) return false;
if (val.castTag(.aggregate)) |payload| {
const field_values = payload.data;
for (field_values) |field_val, i| {
if (needsPointerRebase(fields[i].ty, field_val)) return true;
} else return false;
} else return false;
},
.Optional => {
if (val.castTag(.opt_payload)) |payload| {
const sub_val = payload.data;
var buffer: Type.Payload.ElemType = undefined;
const sub_ty = ty.optionalChild(&buffer);
return needsPointerRebase(sub_ty, sub_val);
} else return false;
},
.Union => {
const union_obj = val.cast(Value.Payload.Union).?.data;
const active_field_ty = ty.unionFieldType(union_obj.tag);
return needsPointerRebase(active_field_ty, union_obj.val);
},
.ErrorUnion => {
if (val.castTag(.eu_payload)) |payload| {
const payload_ty = ty.errorUnionPayload();
return needsPointerRebase(payload_ty, payload.data);
} else return false;
},
else => return false,
}
}
fn getMatchingSectionAtom(self: *MachO, atom: *Atom, name: []const u8, ty: Type, val: Value) !MatchingSection {
const code = atom.code.items;
const alignment = ty.abiAlignment(self.base.options.target);
const align_log_2 = math.log2(alignment);
const zig_ty = ty.zigTypeTag();
const mode = self.base.options.optimize_mode;
const match: MatchingSection = blk: {
// TODO finish and audit this function
if (val.isUndefDeep()) {
if (mode == .ReleaseFast or mode == .ReleaseSmall) {
break :blk MatchingSection{
.seg = self.data_segment_cmd_index.?,
.sect = self.bss_section_index.?,
};
} else {
break :blk MatchingSection{
.seg = self.data_segment_cmd_index.?,
.sect = self.data_section_index.?,
};
}
}
if (val.castTag(.variable)) |_| {
break :blk MatchingSection{
.seg = self.data_segment_cmd_index.?,
.sect = self.data_section_index.?,
};
}
if (needsPointerRebase(ty, val)) {
break :blk (try self.getMatchingSection(.{
.segname = makeStaticString("__DATA_CONST"),
.sectname = makeStaticString("__const"),
.size = code.len,
.@"align" = align_log_2,
})).?;
}
switch (zig_ty) {
.Fn => {
break :blk MatchingSection{
.seg = self.text_segment_cmd_index.?,
.sect = self.text_section_index.?,
};
},
.Array => {
if (val.tag() == .bytes) {
switch (ty.tag()) {
.array_u8_sentinel_0,
.const_slice_u8_sentinel_0,
.manyptr_const_u8_sentinel_0,
=> {
break :blk (try self.getMatchingSection(.{
.segname = makeStaticString("__TEXT"),
.sectname = makeStaticString("__cstring"),
.flags = macho.S_CSTRING_LITERALS,
.size = code.len,
.@"align" = align_log_2,
})).?;
},
else => {},
}
}
},
else => {},
}
break :blk (try self.getMatchingSection(.{
.segname = makeStaticString("__TEXT"),
.sectname = makeStaticString("__const"),
.size = code.len,
.@"align" = align_log_2,
})).?;
};
const seg = self.load_commands.items[match.seg].segment;
const sect = seg.sections.items[match.sect];
log.debug(" allocating atom '{s}' in '{s},{s}' ({d},{d})", .{
name,
sect.segName(),
sect.sectName(),
match.seg,
match.sect,
});
return match;
}
fn placeDecl(self: *MachO, decl: *Module.Decl, code_len: usize) !*macho.nlist_64 {
const required_alignment = decl.ty.abiAlignment(self.base.options.target);
assert(decl.link.macho.local_sym_index != 0); // Caller forgot to call allocateDeclIndexes()
const symbol = &self.locals.items[decl.link.macho.local_sym_index];
const sym_name = try decl.getFullyQualifiedName(self.base.allocator);
defer self.base.allocator.free(sym_name);
const decl_ptr = self.decls.getPtr(decl).?;
if (decl_ptr.* == null) {
decl_ptr.* = try self.getMatchingSectionAtom(&decl.link.macho, sym_name, decl.ty, decl.val);
}
const match = decl_ptr.*.?;
if (decl.link.macho.size != 0) {
const capacity = decl.link.macho.capacity(self.*);
const need_realloc = code_len > capacity or !mem.isAlignedGeneric(u64, symbol.n_value, required_alignment);
if (need_realloc) {
const vaddr = try self.growAtom(&decl.link.macho, code_len, required_alignment, match);
log.debug("growing {s} and moving from 0x{x} to 0x{x}", .{ sym_name, symbol.n_value, vaddr });
log.debug(" (required alignment 0x{x})", .{required_alignment});
symbol.n_value = vaddr;
} else if (code_len < decl.link.macho.size) {
self.shrinkAtom(&decl.link.macho, code_len, match);
}
decl.link.macho.size = code_len;
decl.link.macho.dirty = true;
symbol.n_strx = try self.makeString(sym_name);
symbol.n_type = macho.N_SECT;
symbol.n_sect = @intCast(u8, self.text_section_index.?) + 1;
symbol.n_desc = 0;
} else {
const name_str_index = try self.makeString(sym_name);
const addr = try self.allocateAtom(&decl.link.macho, code_len, required_alignment, match);
log.debug("allocated atom for {s} at 0x{x}", .{ sym_name, addr });
log.debug(" (required alignment 0x{x})", .{required_alignment});
errdefer self.freeAtom(&decl.link.macho, match, false);
symbol.* = .{
.n_strx = name_str_index,
.n_type = macho.N_SECT,
.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).?) + 1,
.n_desc = 0,
.n_value = addr,
};
const got_index = self.got_entries_table.get(.{ .local = decl.link.macho.local_sym_index }).?;
const got_atom = self.got_entries.items[got_index].atom;
const got_sym = &self.locals.items[got_atom.local_sym_index];
const vaddr = try self.allocateAtom(got_atom, @sizeOf(u64), 8, .{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.got_section_index.?,
});
got_sym.n_value = vaddr;
got_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(.{
.seg = self.data_const_segment_cmd_index.?,
.sect = self.got_section_index.?,
}).? + 1);
}
return symbol;
}
pub fn updateDeclLineNumber(self: *MachO, module: *Module, decl: *const Module.Decl) !void {
if (self.d_sym) |*d_sym| {
try d_sym.updateDeclLineNumber(module, decl);
}
}
pub fn updateDeclExports(
self: *MachO,
module: *Module,
decl: *Module.Decl,
exports: []const *Module.Export,
) !void {
if (build_options.skip_non_native and builtin.object_format != .macho) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
if (build_options.have_llvm) {
if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(module, decl, exports);
}
const tracy = trace(@src());
defer tracy.end();
try self.globals.ensureUnusedCapacity(self.base.allocator, exports.len);
if (decl.link.macho.local_sym_index == 0) return;
const decl_sym = &self.locals.items[decl.link.macho.local_sym_index];
for (exports) |exp| {
const exp_name = try std.fmt.allocPrint(self.base.allocator, "_{s}", .{exp.options.name});
defer self.base.allocator.free(exp_name);
if (exp.options.section) |section_name| {
if (!mem.eql(u8, section_name, "__text")) {
try module.failed_exports.putNoClobber(
module.gpa,
exp,
try Module.ErrorMsg.create(
self.base.allocator,
decl.srcLoc(),
"Unimplemented: ExportOptions.section",
.{},
),
);
continue;
}
}
if (exp.options.linkage == .LinkOnce) {
try module.failed_exports.putNoClobber(
module.gpa,
exp,
try Module.ErrorMsg.create(
self.base.allocator,
decl.srcLoc(),
"Unimplemented: GlobalLinkage.LinkOnce",
.{},
),
);
continue;
}
const is_weak = exp.options.linkage == .Internal or exp.options.linkage == .Weak;
const n_strx = try self.makeString(exp_name);
if (self.symbol_resolver.getPtr(n_strx)) |resolv| {
switch (resolv.where) {
.global => {
if (resolv.local_sym_index == decl.link.macho.local_sym_index) continue;
const sym = &self.globals.items[resolv.where_index];
if (sym.tentative()) {
assert(self.tentatives.swapRemove(resolv.where_index));
} else if (!is_weak and !(sym.weakDef() or sym.pext())) {
_ = try module.failed_exports.put(
module.gpa,
exp,
try Module.ErrorMsg.create(
self.base.allocator,
decl.srcLoc(),
\\LinkError: symbol '{s}' defined multiple times
\\ first definition in '{s}'
,
.{ exp_name, self.objects.items[resolv.file.?].name },
),
);
continue;
} else if (is_weak) continue; // Current symbol is weak, so skip it.
// Otherwise, update the resolver and the global symbol.
sym.n_type = macho.N_SECT | macho.N_EXT;
resolv.local_sym_index = decl.link.macho.local_sym_index;
resolv.file = null;
exp.link.macho.sym_index = resolv.where_index;
continue;
},
.undef => {
assert(self.unresolved.swapRemove(resolv.where_index));
_ = self.symbol_resolver.remove(n_strx);
},
}
}
var n_type: u8 = macho.N_SECT | macho.N_EXT;
var n_desc: u16 = 0;
switch (exp.options.linkage) {
.Internal => {
// Symbol should be hidden, or in MachO lingo, private extern.
// We should also mark the symbol as Weak: n_desc == N_WEAK_DEF.
// TODO work out when to add N_WEAK_REF.
n_type |= macho.N_PEXT;
n_desc |= macho.N_WEAK_DEF;
},
.Strong => {},
.Weak => {
// Weak linkage is specified as part of n_desc field.
// Symbol's n_type is like for a symbol with strong linkage.
n_desc |= macho.N_WEAK_DEF;
},
else => unreachable,
}
const global_sym_index = if (exp.link.macho.sym_index) |i| i else blk: {
const i = if (self.globals_free_list.popOrNull()) |i| i else inner: {
_ = self.globals.addOneAssumeCapacity();
break :inner @intCast(u32, self.globals.items.len - 1);
};
break :blk i;
};
const sym = &self.globals.items[global_sym_index];
sym.* = .{
.n_strx = try self.makeString(exp_name),
.n_type = n_type,
.n_sect = @intCast(u8, self.text_section_index.?) + 1,
.n_desc = n_desc,
.n_value = decl_sym.n_value,
};
exp.link.macho.sym_index = global_sym_index;
try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{
.where = .global,
.where_index = global_sym_index,
.local_sym_index = decl.link.macho.local_sym_index,
});
}
}
pub fn deleteExport(self: *MachO, exp: Export) void {
if (self.llvm_object) |_| return;
const sym_index = exp.sym_index orelse return;
self.globals_free_list.append(self.base.allocator, sym_index) catch {};
const global = &self.globals.items[sym_index];
log.debug("deleting export '{s}': {}", .{ self.getString(global.n_strx), global });
assert(self.symbol_resolver.remove(global.n_strx));
global.n_type = 0;
global.n_strx = 0;
global.n_value = 0;
}
fn freeUnnamedConsts(self: *MachO, decl: *Module.Decl) void {
log.debug("freeUnnamedConsts for decl {*}", .{decl});
const unnamed_consts = self.unnamed_const_atoms.getPtr(decl) orelse return;
for (unnamed_consts.items) |atom| {
self.freeAtom(atom, .{
.seg = self.text_segment_cmd_index.?,
.sect = self.text_const_section_index.?,
}, true);
self.locals_free_list.append(self.base.allocator, atom.local_sym_index) catch {};
self.locals.items[atom.local_sym_index].n_type = 0;
_ = self.atom_by_index_table.remove(atom.local_sym_index);
log.debug(" adding local symbol index {d} to free list", .{atom.local_sym_index});
atom.local_sym_index = 0;
}
unnamed_consts.clearAndFree(self.base.allocator);
}
pub fn freeDecl(self: *MachO, decl: *Module.Decl) void {
if (build_options.have_llvm) {
if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl);
}
log.debug("freeDecl {*}", .{decl});
const kv = self.decls.fetchSwapRemove(decl);
if (kv.?.value) |match| {
self.freeAtom(&decl.link.macho, match, false);
self.freeUnnamedConsts(decl);
}
// Appending to free lists is allowed to fail because the free lists are heuristics based anyway.
if (decl.link.macho.local_sym_index != 0) {
self.locals_free_list.append(self.base.allocator, decl.link.macho.local_sym_index) catch {};
// Try freeing GOT atom if this decl had one
if (self.got_entries_table.get(.{ .local = decl.link.macho.local_sym_index })) |got_index| {
self.got_entries_free_list.append(self.base.allocator, @intCast(u32, got_index)) catch {};
self.got_entries.items[got_index] = .{ .target = .{ .local = 0 }, .atom = undefined };
_ = self.got_entries_table.swapRemove(.{ .local = decl.link.macho.local_sym_index });
log.debug(" adding GOT index {d} to free list (target local@{d})", .{
got_index,
decl.link.macho.local_sym_index,
});
}
self.locals.items[decl.link.macho.local_sym_index].n_type = 0;
_ = self.atom_by_index_table.remove(decl.link.macho.local_sym_index);
log.debug(" adding local symbol index {d} to free list", .{decl.link.macho.local_sym_index});
decl.link.macho.local_sym_index = 0;
}
if (self.d_sym) |*d_sym| {
d_sym.dwarf.freeDecl(decl);
}
}
pub fn getDeclVAddr(self: *MachO, decl: *const Module.Decl, reloc_info: File.RelocInfo) !u64 {
assert(self.llvm_object == null);
assert(decl.link.macho.local_sym_index != 0);
const atom = self.atom_by_index_table.get(reloc_info.parent_atom_index).?;
try atom.relocs.append(self.base.allocator, .{
.offset = @intCast(u32, reloc_info.offset),
.target = .{ .local = decl.link.macho.local_sym_index },
.addend = reloc_info.addend,
.subtractor = null,
.pcrel = false,
.length = 3,
.@"type" = switch (self.base.options.target.cpu.arch) {
.aarch64 => @enumToInt(macho.reloc_type_arm64.ARM64_RELOC_UNSIGNED),
.x86_64 => @enumToInt(macho.reloc_type_x86_64.X86_64_RELOC_UNSIGNED),
else => unreachable,
},
});
try atom.rebases.append(self.base.allocator, reloc_info.offset);
return 0;
}
fn populateMissingMetadata(self: *MachO) !void {
const cpu_arch = self.base.options.target.cpu.arch;
if (self.pagezero_segment_cmd_index == null) {
self.pagezero_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.segment = .{
.inner = .{
.segname = makeStaticString("__PAGEZERO"),
.vmsize = pagezero_vmsize,
.cmdsize = @sizeOf(macho.segment_command_64),
},
},
});
self.load_commands_dirty = true;
}
if (self.text_segment_cmd_index == null) {
self.text_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
const needed_size = if (self.needs_prealloc) blk: {
const program_code_size_hint = self.base.options.program_code_size_hint;
const got_size_hint = @sizeOf(u64) * self.base.options.symbol_count_hint;
const ideal_size = self.header_pad + program_code_size_hint + got_size_hint;
const needed_size = mem.alignForwardGeneric(u64, padToIdeal(ideal_size), self.page_size);
log.debug("found __TEXT segment free space 0x{x} to 0x{x}", .{ 0, needed_size });
break :blk needed_size;
} else 0;
try self.load_commands.append(self.base.allocator, .{
.segment = .{
.inner = .{
.segname = makeStaticString("__TEXT"),
.vmaddr = pagezero_vmsize,
.vmsize = needed_size,
.filesize = needed_size,
.maxprot = macho.PROT.READ | macho.PROT.EXEC,
.initprot = macho.PROT.READ | macho.PROT.EXEC,
.cmdsize = @sizeOf(macho.segment_command_64),
},
},
});
self.load_commands_dirty = true;
}
if (self.text_section_index == null) {
const alignment: u2 = switch (cpu_arch) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable, // unhandled architecture type
};
const needed_size = if (self.needs_prealloc) self.base.options.program_code_size_hint else 0;
self.text_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__text",
needed_size,
alignment,
.{
.flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
},
);
}
if (self.stubs_section_index == null) {
const alignment: u2 = switch (cpu_arch) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable, // unhandled architecture type
};
const stub_size: u4 = switch (cpu_arch) {
.x86_64 => 6,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable, // unhandled architecture type
};
const needed_size = if (self.needs_prealloc) stub_size * self.base.options.symbol_count_hint else 0;
self.stubs_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__stubs",
needed_size,
alignment,
.{
.flags = macho.S_SYMBOL_STUBS | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
.reserved2 = stub_size,
},
);
}
if (self.stub_helper_section_index == null) {
const alignment: u2 = switch (cpu_arch) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable, // unhandled architecture type
};
const preamble_size: u6 = switch (cpu_arch) {
.x86_64 => 15,
.aarch64 => 6 * @sizeOf(u32),
else => unreachable,
};
const stub_size: u4 = switch (cpu_arch) {
.x86_64 => 10,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable,
};
const needed_size = if (self.needs_prealloc)
stub_size * self.base.options.symbol_count_hint + preamble_size
else
0;
self.stub_helper_section_index = try self.initSection(
self.text_segment_cmd_index.?,
"__stub_helper",
needed_size,
alignment,
.{
.flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
},
);
}
if (self.data_const_segment_cmd_index == null) {
self.data_const_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
var vmaddr: u64 = 0;
var fileoff: u64 = 0;
var needed_size: u64 = 0;
if (self.needs_prealloc) {
const address_and_offset = self.nextSegmentAddressAndOffset();
vmaddr = address_and_offset.address;
fileoff = address_and_offset.offset;
const ideal_size = @sizeOf(u64) * self.base.options.symbol_count_hint;
needed_size = mem.alignForwardGeneric(u64, padToIdeal(ideal_size), self.page_size);
log.debug("found __DATA_CONST segment free space 0x{x} to 0x{x}", .{
fileoff,
fileoff + needed_size,
});
}
try self.load_commands.append(self.base.allocator, .{
.segment = .{
.inner = .{
.segname = makeStaticString("__DATA_CONST"),
.vmaddr = vmaddr,
.vmsize = needed_size,
.fileoff = fileoff,
.filesize = needed_size,
.maxprot = macho.PROT.READ | macho.PROT.WRITE,
.initprot = macho.PROT.READ | macho.PROT.WRITE,
.cmdsize = @sizeOf(macho.segment_command_64),
},
},
});
self.load_commands_dirty = true;
}
if (self.got_section_index == null) {
const needed_size = if (self.needs_prealloc)
@sizeOf(u64) * self.base.options.symbol_count_hint
else
0;
const alignment: u16 = 3; // 2^3 = @sizeOf(u64)
self.got_section_index = try self.initSection(
self.data_const_segment_cmd_index.?,
"__got",
needed_size,
alignment,
.{
.flags = macho.S_NON_LAZY_SYMBOL_POINTERS,
},
);
}
if (self.data_segment_cmd_index == null) {
self.data_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
var vmaddr: u64 = 0;
var fileoff: u64 = 0;
var needed_size: u64 = 0;
if (self.needs_prealloc) {
const address_and_offset = self.nextSegmentAddressAndOffset();
vmaddr = address_and_offset.address;
fileoff = address_and_offset.offset;
const ideal_size = 2 * @sizeOf(u64) * self.base.options.symbol_count_hint;
needed_size = mem.alignForwardGeneric(u64, padToIdeal(ideal_size), self.page_size);
log.debug("found __DATA segment free space 0x{x} to 0x{x}", .{
fileoff,
fileoff + needed_size,
});
}
try self.load_commands.append(self.base.allocator, .{
.segment = .{
.inner = .{
.segname = makeStaticString("__DATA"),
.vmaddr = vmaddr,
.vmsize = needed_size,
.fileoff = fileoff,
.filesize = needed_size,
.maxprot = macho.PROT.READ | macho.PROT.WRITE,
.initprot = macho.PROT.READ | macho.PROT.WRITE,
.cmdsize = @sizeOf(macho.segment_command_64),
},
},
});
self.load_commands_dirty = true;
}
if (self.la_symbol_ptr_section_index == null) {
const needed_size = if (self.needs_prealloc)
@sizeOf(u64) * self.base.options.symbol_count_hint
else
0;
const alignment: u16 = 3; // 2^3 = @sizeOf(u64)
self.la_symbol_ptr_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__la_symbol_ptr",
needed_size,
alignment,
.{
.flags = macho.S_LAZY_SYMBOL_POINTERS,
},
);
}
if (self.data_section_index == null) {
const needed_size = if (self.needs_prealloc) @sizeOf(u64) * self.base.options.symbol_count_hint else 0;
const alignment: u16 = 3; // 2^3 = @sizeOf(u64)
self.data_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__data",
needed_size,
alignment,
.{},
);
}
if (self.tlv_section_index == null) {
const needed_size = if (self.needs_prealloc) @sizeOf(u64) * self.base.options.symbol_count_hint else 0;
const alignment: u16 = 3; // 2^3 = @sizeOf(u64)
self.tlv_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__thread_vars",
needed_size,
alignment,
.{
.flags = macho.S_THREAD_LOCAL_VARIABLES,
},
);
}
if (self.tlv_data_section_index == null) {
const needed_size = if (self.needs_prealloc) @sizeOf(u64) * self.base.options.symbol_count_hint else 0;
const alignment: u16 = 3; // 2^3 = @sizeOf(u64)
self.tlv_data_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__thread_data",
needed_size,
alignment,
.{
.flags = macho.S_THREAD_LOCAL_REGULAR,
},
);
}
if (self.tlv_bss_section_index == null) {
const needed_size = if (self.needs_prealloc) @sizeOf(u64) * self.base.options.symbol_count_hint else 0;
const alignment: u16 = 3; // 2^3 = @sizeOf(u64)
self.tlv_bss_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__thread_bss",
needed_size,
alignment,
.{
.flags = macho.S_THREAD_LOCAL_ZEROFILL,
},
);
}
if (self.bss_section_index == null) {
const needed_size = if (self.needs_prealloc) @sizeOf(u64) * self.base.options.symbol_count_hint else 0;
const alignment: u16 = 3; // 2^3 = @sizeOf(u64)
self.bss_section_index = try self.initSection(
self.data_segment_cmd_index.?,
"__bss",
needed_size,
alignment,
.{
.flags = macho.S_ZEROFILL,
},
);
}
if (self.linkedit_segment_cmd_index == null) {
self.linkedit_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
var vmaddr: u64 = 0;
var fileoff: u64 = 0;
if (self.needs_prealloc) {
const address_and_offset = self.nextSegmentAddressAndOffset();
vmaddr = address_and_offset.address;
fileoff = address_and_offset.offset;
log.debug("found __LINKEDIT segment free space at 0x{x}", .{fileoff});
}
try self.load_commands.append(self.base.allocator, .{
.segment = .{
.inner = .{
.segname = makeStaticString("__LINKEDIT"),
.vmaddr = vmaddr,
.fileoff = fileoff,
.maxprot = macho.PROT.READ,
.initprot = macho.PROT.READ,
.cmdsize = @sizeOf(macho.segment_command_64),
},
},
});
self.load_commands_dirty = true;
}
if (self.dyld_info_cmd_index == null) {
self.dyld_info_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.dyld_info_only = .{
.cmd = .DYLD_INFO_ONLY,
.cmdsize = @sizeOf(macho.dyld_info_command),
.rebase_off = 0,
.rebase_size = 0,
.bind_off = 0,
.bind_size = 0,
.weak_bind_off = 0,
.weak_bind_size = 0,
.lazy_bind_off = 0,
.lazy_bind_size = 0,
.export_off = 0,
.export_size = 0,
},
});
self.load_commands_dirty = true;
}
if (self.symtab_cmd_index == null) {
self.symtab_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.symtab = .{
.cmdsize = @sizeOf(macho.symtab_command),
.symoff = 0,
.nsyms = 0,
.stroff = 0,
.strsize = 0,
},
});
self.load_commands_dirty = true;
}
if (self.dysymtab_cmd_index == null) {
self.dysymtab_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.dysymtab = .{
.cmdsize = @sizeOf(macho.dysymtab_command),
.ilocalsym = 0,
.nlocalsym = 0,
.iextdefsym = 0,
.nextdefsym = 0,
.iundefsym = 0,
.nundefsym = 0,
.tocoff = 0,
.ntoc = 0,
.modtaboff = 0,
.nmodtab = 0,
.extrefsymoff = 0,
.nextrefsyms = 0,
.indirectsymoff = 0,
.nindirectsyms = 0,
.extreloff = 0,
.nextrel = 0,
.locreloff = 0,
.nlocrel = 0,
},
});
self.load_commands_dirty = true;
}
if (self.dylinker_cmd_index == null) {
self.dylinker_cmd_index = @intCast(u16, self.load_commands.items.len);
const cmdsize = @intCast(u32, mem.alignForwardGeneric(
u64,
@sizeOf(macho.dylinker_command) + mem.sliceTo(default_dyld_path, 0).len,
@sizeOf(u64),
));
var dylinker_cmd = macho.emptyGenericCommandWithData(macho.dylinker_command{
.cmd = .LOAD_DYLINKER,
.cmdsize = cmdsize,
.name = @sizeOf(macho.dylinker_command),
});
dylinker_cmd.data = try self.base.allocator.alloc(u8, cmdsize - dylinker_cmd.inner.name);
mem.set(u8, dylinker_cmd.data, 0);
mem.copy(u8, dylinker_cmd.data, mem.sliceTo(default_dyld_path, 0));
try self.load_commands.append(self.base.allocator, .{ .dylinker = dylinker_cmd });
self.load_commands_dirty = true;
}
if (self.main_cmd_index == null and self.base.options.output_mode == .Exe) {
self.main_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.main = .{
.cmdsize = @sizeOf(macho.entry_point_command),
.entryoff = 0x0,
.stacksize = 0,
},
});
self.load_commands_dirty = true;
}
if (self.dylib_id_cmd_index == null and self.base.options.output_mode == .Lib) {
self.dylib_id_cmd_index = @intCast(u16, self.load_commands.items.len);
const install_name = self.base.options.install_name orelse self.base.options.emit.?.sub_path;
const current_version = self.base.options.version orelse
std.builtin.Version{ .major = 1, .minor = 0, .patch = 0 };
const compat_version = self.base.options.compatibility_version orelse
std.builtin.Version{ .major = 1, .minor = 0, .patch = 0 };
var dylib_cmd = try macho.createLoadDylibCommand(
self.base.allocator,
install_name,
2,
current_version.major << 16 | current_version.minor << 8 | current_version.patch,
compat_version.major << 16 | compat_version.minor << 8 | compat_version.patch,
);
errdefer dylib_cmd.deinit(self.base.allocator);
dylib_cmd.inner.cmd = .ID_DYLIB;
try self.load_commands.append(self.base.allocator, .{ .dylib = dylib_cmd });
self.load_commands_dirty = true;
}
if (self.source_version_cmd_index == null) {
self.source_version_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.source_version = .{
.cmdsize = @sizeOf(macho.source_version_command),
.version = 0x0,
},
});
self.load_commands_dirty = true;
}
if (self.build_version_cmd_index == null) {
self.build_version_cmd_index = @intCast(u16, self.load_commands.items.len);
const cmdsize = @intCast(u32, mem.alignForwardGeneric(
u64,
@sizeOf(macho.build_version_command) + @sizeOf(macho.build_tool_version),
@sizeOf(u64),
));
const platform_version = blk: {
const ver = self.base.options.target.os.version_range.semver.min;
const platform_version = ver.major << 16 | ver.minor << 8;
break :blk platform_version;
};
const sdk_version = if (self.base.options.native_darwin_sdk) |sdk| blk: {
const ver = sdk.version;
const sdk_version = ver.major << 16 | ver.minor << 8;
break :blk sdk_version;
} else platform_version;
const is_simulator_abi = self.base.options.target.abi == .simulator;
var cmd = macho.emptyGenericCommandWithData(macho.build_version_command{
.cmdsize = cmdsize,
.platform = switch (self.base.options.target.os.tag) {
.macos => .MACOS,
.ios => if (is_simulator_abi) macho.PLATFORM.IOSSIMULATOR else macho.PLATFORM.IOS,
.watchos => if (is_simulator_abi) macho.PLATFORM.WATCHOSSIMULATOR else macho.PLATFORM.WATCHOS,
.tvos => if (is_simulator_abi) macho.PLATFORM.TVOSSIMULATOR else macho.PLATFORM.TVOS,
else => unreachable,
},
.minos = platform_version,
.sdk = sdk_version,
.ntools = 1,
});
const ld_ver = macho.build_tool_version{
.tool = .LD,
.version = 0x0,
};
cmd.data = try self.base.allocator.alloc(u8, cmdsize - @sizeOf(macho.build_version_command));
mem.set(u8, cmd.data, 0);
mem.copy(u8, cmd.data, mem.asBytes(&ld_ver));
try self.load_commands.append(self.base.allocator, .{ .build_version = cmd });
self.load_commands_dirty = true;
}
if (self.uuid_cmd_index == null) {
self.uuid_cmd_index = @intCast(u16, self.load_commands.items.len);
var uuid_cmd: macho.uuid_command = .{
.cmdsize = @sizeOf(macho.uuid_command),
.uuid = undefined,
};
std.crypto.random.bytes(&uuid_cmd.uuid);
try self.load_commands.append(self.base.allocator, .{ .uuid = uuid_cmd });
self.load_commands_dirty = true;
}
if (self.function_starts_cmd_index == null) {
self.function_starts_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.linkedit_data = .{
.cmd = .FUNCTION_STARTS,
.cmdsize = @sizeOf(macho.linkedit_data_command),
.dataoff = 0,
.datasize = 0,
},
});
self.load_commands_dirty = true;
}
if (self.data_in_code_cmd_index == null) {
self.data_in_code_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.linkedit_data = .{
.cmd = .DATA_IN_CODE,
.cmdsize = @sizeOf(macho.linkedit_data_command),
.dataoff = 0,
.datasize = 0,
},
});
self.load_commands_dirty = true;
}
self.cold_start = true;
}
fn allocateTextSegment(self: *MachO) !void {
const seg = &self.load_commands.items[self.text_segment_cmd_index.?].segment;
const base_vmaddr = self.load_commands.items[self.pagezero_segment_cmd_index.?].segment.inner.vmsize;
seg.inner.fileoff = 0;
seg.inner.vmaddr = base_vmaddr;
var sizeofcmds: u64 = 0;
for (self.load_commands.items) |lc| {
sizeofcmds += lc.cmdsize();
}
try self.allocateSegment(self.text_segment_cmd_index.?, @sizeOf(macho.mach_header_64) + sizeofcmds);
// Shift all sections to the back to minimize jump size between __TEXT and __DATA segments.
var min_alignment: u32 = 0;
for (seg.sections.items) |sect| {
const alignment = try math.powi(u32, 2, sect.@"align");
min_alignment = math.max(min_alignment, alignment);
}
assert(min_alignment > 0);
const last_sect_idx = seg.sections.items.len - 1;
const last_sect = seg.sections.items[last_sect_idx];
const shift: u32 = blk: {
const diff = seg.inner.filesize - last_sect.offset - last_sect.size;
const factor = @divTrunc(diff, min_alignment);
break :blk @intCast(u32, factor * min_alignment);
};
if (shift > 0) {
for (seg.sections.items) |*sect| {
sect.offset += shift;
sect.addr += shift;
}
}
}
fn allocateDataConstSegment(self: *MachO) !void {
const seg = &self.load_commands.items[self.data_const_segment_cmd_index.?].segment;
const text_seg = self.load_commands.items[self.text_segment_cmd_index.?].segment;
seg.inner.fileoff = text_seg.inner.fileoff + text_seg.inner.filesize;
seg.inner.vmaddr = text_seg.inner.vmaddr + text_seg.inner.vmsize;
try self.allocateSegment(self.data_const_segment_cmd_index.?, 0);
}
fn allocateDataSegment(self: *MachO) !void {
const seg = &self.load_commands.items[self.data_segment_cmd_index.?].segment;
const data_const_seg = self.load_commands.items[self.data_const_segment_cmd_index.?].segment;
seg.inner.fileoff = data_const_seg.inner.fileoff + data_const_seg.inner.filesize;
seg.inner.vmaddr = data_const_seg.inner.vmaddr + data_const_seg.inner.vmsize;
try self.allocateSegment(self.data_segment_cmd_index.?, 0);
}
fn allocateLinkeditSegment(self: *MachO) void {
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment;
const data_seg = self.load_commands.items[self.data_segment_cmd_index.?].segment;
seg.inner.fileoff = data_seg.inner.fileoff + data_seg.inner.filesize;
seg.inner.vmaddr = data_seg.inner.vmaddr + data_seg.inner.vmsize;
}
fn allocateSegment(self: *MachO, index: u16, offset: u64) !void {
const seg = &self.load_commands.items[index].segment;
// Allocate the sections according to their alignment at the beginning of the segment.
var start: u64 = offset;
for (seg.sections.items) |*sect, sect_id| {
const is_zerofill = sect.flags == macho.S_ZEROFILL or sect.flags == macho.S_THREAD_LOCAL_ZEROFILL;
const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1;
const alignment = try math.powi(u32, 2, sect.@"align");
const start_aligned = mem.alignForwardGeneric(u64, start, alignment);
// TODO handle zerofill sections in stage2
sect.offset = if (is_zerofill and use_stage1) 0 else @intCast(u32, seg.inner.fileoff + start_aligned);
sect.addr = seg.inner.vmaddr + start_aligned;
// Recalculate section size given the allocated start address
sect.size = if (self.atoms.get(.{
.seg = index,
.sect = @intCast(u16, sect_id),
})) |last_atom| blk: {
var atom = last_atom;
while (atom.prev) |prev| {
atom = prev;
}
var base_addr = sect.addr;
while (true) {
const atom_alignment = try math.powi(u32, 2, atom.alignment);
base_addr = mem.alignForwardGeneric(u64, base_addr, atom_alignment) + atom.size;
if (atom.next) |next| {
atom = next;
} else break;
}
break :blk base_addr - sect.addr;
} else 0;
start = start_aligned + sect.size;
if (!(is_zerofill and use_stage1)) {
seg.inner.filesize = start;
}
seg.inner.vmsize = start;
}
seg.inner.filesize = mem.alignForwardGeneric(u64, seg.inner.filesize, self.page_size);
seg.inner.vmsize = mem.alignForwardGeneric(u64, seg.inner.vmsize, self.page_size);
}
const InitSectionOpts = struct {
flags: u32 = macho.S_REGULAR,
reserved1: u32 = 0,
reserved2: u32 = 0,
};
fn initSection(
self: *MachO,
segment_id: u16,
sectname: []const u8,
size: u64,
alignment: u32,
opts: InitSectionOpts,
) !u16 {
const seg = &self.load_commands.items[segment_id].segment;
var sect = macho.section_64{
.sectname = makeStaticString(sectname),
.segname = seg.inner.segname,
.size = if (self.needs_prealloc) @intCast(u32, size) else 0,
.@"align" = alignment,
.flags = opts.flags,
.reserved1 = opts.reserved1,
.reserved2 = opts.reserved2,
};
if (self.needs_prealloc) {
const alignment_pow_2 = try math.powi(u32, 2, alignment);
const padding: ?u64 = if (segment_id == self.text_segment_cmd_index.?) self.header_pad else null;
const off = self.findFreeSpace(segment_id, alignment_pow_2, padding);
log.debug("allocating {s},{s} section from 0x{x} to 0x{x}", .{
sect.segName(),
sect.sectName(),
off,
off + size,
});
sect.addr = seg.inner.vmaddr + off - seg.inner.fileoff;
const is_zerofill = opts.flags == macho.S_ZEROFILL or opts.flags == macho.S_THREAD_LOCAL_ZEROFILL;
const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1;
// TODO handle zerofill in stage2
if (!(is_zerofill and use_stage1)) {
sect.offset = @intCast(u32, off);
}
}
const index = @intCast(u16, seg.sections.items.len);
try seg.sections.append(self.base.allocator, sect);
seg.inner.cmdsize += @sizeOf(macho.section_64);
seg.inner.nsects += 1;
const match = MatchingSection{
.seg = segment_id,
.sect = index,
};
_ = try self.section_ordinals.getOrPut(self.base.allocator, match);
try self.atom_free_lists.putNoClobber(self.base.allocator, match, .{});
self.load_commands_dirty = true;
self.sections_order_dirty = true;
return index;
}
fn findFreeSpace(self: MachO, segment_id: u16, alignment: u64, start: ?u64) u64 {
const seg = self.load_commands.items[segment_id].segment;
if (seg.sections.items.len == 0) {
return if (start) |v| v else seg.inner.fileoff;
}
const last_sect = seg.sections.items[seg.sections.items.len - 1];
const final_off = last_sect.offset + padToIdeal(last_sect.size);
return mem.alignForwardGeneric(u64, final_off, alignment);
}
fn growSegment(self: *MachO, seg_id: u16, new_size: u64) !void {
const seg = &self.load_commands.items[seg_id].segment;
const new_seg_size = mem.alignForwardGeneric(u64, new_size, self.page_size);
assert(new_seg_size > seg.inner.filesize);
const offset_amt = new_seg_size - seg.inner.filesize;
log.debug("growing segment {s} from 0x{x} to 0x{x}", .{
seg.inner.segname,
seg.inner.filesize,
new_seg_size,
});
seg.inner.filesize = new_seg_size;
seg.inner.vmsize = new_seg_size;
log.debug(" (new segment file offsets from 0x{x} to 0x{x} (in memory 0x{x} to 0x{x}))", .{
seg.inner.fileoff,
seg.inner.fileoff + seg.inner.filesize,
seg.inner.vmaddr,
seg.inner.vmaddr + seg.inner.vmsize,
});
var next: usize = seg_id + 1;
while (next < self.linkedit_segment_cmd_index.? + 1) : (next += 1) {
const next_seg = &self.load_commands.items[next].segment;
try MachO.copyRangeAllOverlappingAlloc(
self.base.allocator,
self.base.file.?,
next_seg.inner.fileoff,
next_seg.inner.fileoff + offset_amt,
try math.cast(usize, next_seg.inner.filesize),
);
next_seg.inner.fileoff += offset_amt;
next_seg.inner.vmaddr += offset_amt;
log.debug(" (new {s} segment file offsets from 0x{x} to 0x{x} (in memory 0x{x} to 0x{x}))", .{
next_seg.inner.segname,
next_seg.inner.fileoff,
next_seg.inner.fileoff + next_seg.inner.filesize,
next_seg.inner.vmaddr,
next_seg.inner.vmaddr + next_seg.inner.vmsize,
});
for (next_seg.sections.items) |*moved_sect, moved_sect_id| {
moved_sect.offset += @intCast(u32, offset_amt);
moved_sect.addr += offset_amt;
log.debug(" (new {s},{s} file offsets from 0x{x} to 0x{x} (in memory 0x{x} to 0x{x}))", .{
moved_sect.segName(),
moved_sect.sectName(),
moved_sect.offset,
moved_sect.offset + moved_sect.size,
moved_sect.addr,
moved_sect.addr + moved_sect.size,
});
try self.shiftLocalsByOffset(.{
.seg = @intCast(u16, next),
.sect = @intCast(u16, moved_sect_id),
}, @intCast(i64, offset_amt));
}
}
}
fn growSection(self: *MachO, match: MatchingSection, new_size: u32) !void {
const tracy = trace(@src());
defer tracy.end();
const seg = &self.load_commands.items[match.seg].segment;
const sect = &seg.sections.items[match.sect];
const alignment = try math.powi(u32, 2, sect.@"align");
const max_size = self.allocatedSize(match.seg, sect.offset);
const ideal_size = padToIdeal(new_size);
const needed_size = mem.alignForwardGeneric(u32, ideal_size, alignment);
if (needed_size > max_size) blk: {
log.debug(" (need to grow! needed 0x{x}, max 0x{x})", .{ needed_size, max_size });
if (match.sect == seg.sections.items.len - 1) {
// Last section, just grow segments
try self.growSegment(match.seg, seg.inner.filesize + needed_size - max_size);
break :blk;
}
// Need to move all sections below in file and address spaces.
const offset_amt = offset: {
const max_alignment = try self.getSectionMaxAlignment(match.seg, match.sect + 1);
break :offset mem.alignForwardGeneric(u64, needed_size - max_size, max_alignment);
};
// Before we commit to this, check if the segment needs to grow too.
// We assume that each section header is growing linearly with the increasing
// file offset / virtual memory address space.
const last_sect = seg.sections.items[seg.sections.items.len - 1];
const last_sect_off = last_sect.offset + last_sect.size;
const seg_off = seg.inner.fileoff + seg.inner.filesize;
if (last_sect_off + offset_amt > seg_off) {
// Need to grow segment first.
const spill_size = (last_sect_off + offset_amt) - seg_off;
try self.growSegment(match.seg, seg.inner.filesize + spill_size);
}
// We have enough space to expand within the segment, so move all sections by
// the required amount and update their header offsets.
const next_sect = seg.sections.items[match.sect + 1];
const total_size = last_sect_off - next_sect.offset;
try MachO.copyRangeAllOverlappingAlloc(
self.base.allocator,
self.base.file.?,
next_sect.offset,
next_sect.offset + offset_amt,
try math.cast(usize, total_size),
);
var next = match.sect + 1;
while (next < seg.sections.items.len) : (next += 1) {
const moved_sect = &seg.sections.items[next];
moved_sect.offset += @intCast(u32, offset_amt);
moved_sect.addr += offset_amt;
log.debug(" (new {s},{s} file offsets from 0x{x} to 0x{x} (in memory 0x{x} to 0x{x}))", .{
moved_sect.segName(),
moved_sect.sectName(),
moved_sect.offset,
moved_sect.offset + moved_sect.size,
moved_sect.addr,
moved_sect.addr + moved_sect.size,
});
try self.shiftLocalsByOffset(.{
.seg = match.seg,
.sect = next,
}, @intCast(i64, offset_amt));
}
}
}
fn allocatedSize(self: MachO, segment_id: u16, start: u64) u64 {
const seg = self.load_commands.items[segment_id].segment;
assert(start >= seg.inner.fileoff);
var min_pos: u64 = seg.inner.fileoff + seg.inner.filesize;
if (start > min_pos) return 0;
for (seg.sections.items) |section| {
if (section.offset <= start) continue;
if (section.offset < min_pos) min_pos = section.offset;
}
return min_pos - start;
}
fn getSectionMaxAlignment(self: *MachO, segment_id: u16, start_sect_id: u16) !u32 {
const seg = self.load_commands.items[segment_id].segment;
var max_alignment: u32 = 1;
var next = start_sect_id;
while (next < seg.sections.items.len) : (next += 1) {
const sect = seg.sections.items[next];
const alignment = try math.powi(u32, 2, sect.@"align");
max_alignment = math.max(max_alignment, alignment);
}
return max_alignment;
}
fn allocateAtom(self: *MachO, atom: *Atom, new_atom_size: u64, alignment: u64, match: MatchingSection) !u64 {
const tracy = trace(@src());
defer tracy.end();
const seg = &self.load_commands.items[match.seg].segment;
const sect = &seg.sections.items[match.sect];
var free_list = self.atom_free_lists.get(match).?;
const needs_padding = match.seg == self.text_segment_cmd_index.? and match.sect == self.text_section_index.?;
const new_atom_ideal_capacity = if (needs_padding) padToIdeal(new_atom_size) else new_atom_size;
// We use these to indicate our intention to update metadata, placing the new atom,
// and possibly removing a free list node.
// It would be simpler to do it inside the for loop below, but that would cause a
// problem if an error was returned later in the function. So this action
// is actually carried out at the end of the function, when errors are no longer possible.
var atom_placement: ?*Atom = null;
var free_list_removal: ?usize = null;
// First we look for an appropriately sized free list node.
// The list is unordered. We'll just take the first thing that works.
var vaddr = blk: {
var i: usize = 0;
while (i < free_list.items.len) {
const big_atom = free_list.items[i];
// We now have a pointer to a live atom that has too much capacity.
// Is it enough that we could fit this new atom?
const sym = self.locals.items[big_atom.local_sym_index];
const capacity = big_atom.capacity(self.*);
const ideal_capacity = if (needs_padding) padToIdeal(capacity) else capacity;
const ideal_capacity_end_vaddr = math.add(u64, sym.n_value, ideal_capacity) catch ideal_capacity;
const capacity_end_vaddr = sym.n_value + capacity;
const new_start_vaddr_unaligned = capacity_end_vaddr - new_atom_ideal_capacity;
const new_start_vaddr = mem.alignBackwardGeneric(u64, new_start_vaddr_unaligned, alignment);
if (new_start_vaddr < ideal_capacity_end_vaddr) {
// Additional bookkeeping here to notice if this free list node
// should be deleted because the atom that it points to has grown to take up
// more of the extra capacity.
if (!big_atom.freeListEligible(self.*)) {
_ = free_list.swapRemove(i);
} else {
i += 1;
}
continue;
}
// At this point we know that we will place the new atom here. But the
// remaining question is whether there is still yet enough capacity left
// over for there to still be a free list node.
const remaining_capacity = new_start_vaddr - ideal_capacity_end_vaddr;
const keep_free_list_node = remaining_capacity >= min_text_capacity;
// Set up the metadata to be updated, after errors are no longer possible.
atom_placement = big_atom;
if (!keep_free_list_node) {
free_list_removal = i;
}
break :blk new_start_vaddr;
} else if (self.atoms.get(match)) |last| {
const last_symbol = self.locals.items[last.local_sym_index];
const ideal_capacity = if (needs_padding) padToIdeal(last.size) else last.size;
const ideal_capacity_end_vaddr = last_symbol.n_value + ideal_capacity;
const new_start_vaddr = mem.alignForwardGeneric(u64, ideal_capacity_end_vaddr, alignment);
atom_placement = last;
break :blk new_start_vaddr;
} else {
break :blk mem.alignForwardGeneric(u64, sect.addr, alignment);
}
};
const expand_section = atom_placement == null or atom_placement.?.next == null;
if (expand_section) {
const needed_size = @intCast(u32, (vaddr + new_atom_size) - sect.addr);
try self.growSection(match, needed_size);
_ = try self.atoms.put(self.base.allocator, match, atom);
sect.size = needed_size;
self.load_commands_dirty = true;
}
const align_pow = @intCast(u32, math.log2(alignment));
if (sect.@"align" < align_pow) {
sect.@"align" = align_pow;
self.load_commands_dirty = true;
}
atom.size = new_atom_size;
atom.alignment = align_pow;
if (atom.prev) |prev| {
prev.next = atom.next;
}
if (atom.next) |next| {
next.prev = atom.prev;
}
if (atom_placement) |big_atom| {
atom.prev = big_atom;
atom.next = big_atom.next;
big_atom.next = atom;
} else {
atom.prev = null;
atom.next = null;
}
if (free_list_removal) |i| {
_ = free_list.swapRemove(i);
}
return vaddr;
}
fn addAtomToSection(self: *MachO, atom: *Atom, match: MatchingSection) !void {
if (self.atoms.getPtr(match)) |last| {
last.*.next = atom;
atom.prev = last.*;
last.* = atom;
} else {
try self.atoms.putNoClobber(self.base.allocator, match, atom);
}
}
pub fn addExternFn(self: *MachO, name: []const u8) !u32 {
const sym_name = try std.fmt.allocPrint(self.base.allocator, "_{s}", .{name});
defer self.base.allocator.free(sym_name);
const n_strx = try self.makeString(sym_name);
if (!self.symbol_resolver.contains(n_strx)) {
log.debug("adding new extern function '{s}'", .{sym_name});
const sym_index = @intCast(u32, self.undefs.items.len);
try self.undefs.append(self.base.allocator, .{
.n_strx = n_strx,
.n_type = macho.N_UNDF,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{
.where = .undef,
.where_index = sym_index,
});
try self.unresolved.putNoClobber(self.base.allocator, sym_index, .stub);
}
return n_strx;
}
const NextSegmentAddressAndOffset = struct {
address: u64,
offset: u64,
};
fn nextSegmentAddressAndOffset(self: *MachO) NextSegmentAddressAndOffset {
var prev_segment_idx: ?usize = null; // We use optional here for safety.
for (self.load_commands.items) |cmd, i| {
if (cmd == .segment) {
prev_segment_idx = i;
}
}
const prev_segment = self.load_commands.items[prev_segment_idx.?].segment;
const address = prev_segment.inner.vmaddr + prev_segment.inner.vmsize;
const offset = prev_segment.inner.fileoff + prev_segment.inner.filesize;
return .{
.address = address,
.offset = offset,
};
}
fn sortSections(self: *MachO) !void {
var text_index_mapping = std.AutoHashMap(u16, u16).init(self.base.allocator);
defer text_index_mapping.deinit();
var data_const_index_mapping = std.AutoHashMap(u16, u16).init(self.base.allocator);
defer data_const_index_mapping.deinit();
var data_index_mapping = std.AutoHashMap(u16, u16).init(self.base.allocator);
defer data_index_mapping.deinit();
{
// __TEXT segment
const seg = &self.load_commands.items[self.text_segment_cmd_index.?].segment;
var sections = seg.sections.toOwnedSlice(self.base.allocator);
defer self.base.allocator.free(sections);
try seg.sections.ensureTotalCapacity(self.base.allocator, sections.len);
const indices = &[_]*?u16{
&self.text_section_index,
&self.stubs_section_index,
&self.stub_helper_section_index,
&self.gcc_except_tab_section_index,
&self.cstring_section_index,
&self.ustring_section_index,
&self.text_const_section_index,
&self.objc_methlist_section_index,
&self.objc_methname_section_index,
&self.objc_methtype_section_index,
&self.objc_classname_section_index,
&self.eh_frame_section_index,
};
for (indices) |maybe_index| {
const new_index: u16 = if (maybe_index.*) |index| blk: {
const idx = @intCast(u16, seg.sections.items.len);
seg.sections.appendAssumeCapacity(sections[index]);
try text_index_mapping.putNoClobber(index, idx);
break :blk idx;
} else continue;
maybe_index.* = new_index;
}
}
{
// __DATA_CONST segment
const seg = &self.load_commands.items[self.data_const_segment_cmd_index.?].segment;
var sections = seg.sections.toOwnedSlice(self.base.allocator);
defer self.base.allocator.free(sections);
try seg.sections.ensureTotalCapacity(self.base.allocator, sections.len);
const indices = &[_]*?u16{
&self.got_section_index,
&self.mod_init_func_section_index,
&self.mod_term_func_section_index,
&self.data_const_section_index,
&self.objc_cfstring_section_index,
&self.objc_classlist_section_index,
&self.objc_imageinfo_section_index,
};
for (indices) |maybe_index| {
const new_index: u16 = if (maybe_index.*) |index| blk: {
const idx = @intCast(u16, seg.sections.items.len);
seg.sections.appendAssumeCapacity(sections[index]);
try data_const_index_mapping.putNoClobber(index, idx);
break :blk idx;
} else continue;
maybe_index.* = new_index;
}
}
{
// __DATA segment
const seg = &self.load_commands.items[self.data_segment_cmd_index.?].segment;
var sections = seg.sections.toOwnedSlice(self.base.allocator);
defer self.base.allocator.free(sections);
try seg.sections.ensureTotalCapacity(self.base.allocator, sections.len);
// __DATA segment
const indices = &[_]*?u16{
&self.rustc_section_index,
&self.la_symbol_ptr_section_index,
&self.objc_const_section_index,
&self.objc_selrefs_section_index,
&self.objc_classrefs_section_index,
&self.objc_data_section_index,
&self.data_section_index,
&self.tlv_section_index,
&self.tlv_ptrs_section_index,
&self.tlv_data_section_index,
&self.tlv_bss_section_index,
&self.bss_section_index,
};
for (indices) |maybe_index| {
const new_index: u16 = if (maybe_index.*) |index| blk: {
const idx = @intCast(u16, seg.sections.items.len);
seg.sections.appendAssumeCapacity(sections[index]);
try data_index_mapping.putNoClobber(index, idx);
break :blk idx;
} else continue;
maybe_index.* = new_index;
}
}
{
var transient: std.AutoHashMapUnmanaged(MatchingSection, *Atom) = .{};
try transient.ensureTotalCapacity(self.base.allocator, self.atoms.count());
var it = self.atoms.iterator();
while (it.next()) |entry| {
const old = entry.key_ptr.*;
const sect = if (old.seg == self.text_segment_cmd_index.?)
text_index_mapping.get(old.sect).?
else if (old.seg == self.data_const_segment_cmd_index.?)
data_const_index_mapping.get(old.sect).?
else
data_index_mapping.get(old.sect).?;
transient.putAssumeCapacityNoClobber(.{
.seg = old.seg,
.sect = sect,
}, entry.value_ptr.*);
}
self.atoms.clearAndFree(self.base.allocator);
self.atoms.deinit(self.base.allocator);
self.atoms = transient;
}
{
// Create new section ordinals.
self.section_ordinals.clearRetainingCapacity();
const text_seg = self.load_commands.items[self.text_segment_cmd_index.?].segment;
for (text_seg.sections.items) |_, sect_id| {
const res = self.section_ordinals.getOrPutAssumeCapacity(.{
.seg = self.text_segment_cmd_index.?,
.sect = @intCast(u16, sect_id),
});
assert(!res.found_existing);
}
const data_const_seg = self.load_commands.items[self.data_const_segment_cmd_index.?].segment;
for (data_const_seg.sections.items) |_, sect_id| {
const res = self.section_ordinals.getOrPutAssumeCapacity(.{
.seg = self.data_const_segment_cmd_index.?,
.sect = @intCast(u16, sect_id),
});
assert(!res.found_existing);
}
const data_seg = self.load_commands.items[self.data_segment_cmd_index.?].segment;
for (data_seg.sections.items) |_, sect_id| {
const res = self.section_ordinals.getOrPutAssumeCapacity(.{
.seg = self.data_segment_cmd_index.?,
.sect = @intCast(u16, sect_id),
});
assert(!res.found_existing);
}
}
self.sections_order_dirty = false;
}
fn updateSectionOrdinals(self: *MachO) !void {
if (!self.sections_order_dirty) return;
const tracy = trace(@src());
defer tracy.end();
var ordinal_remap = std.AutoHashMap(u8, u8).init(self.base.allocator);
defer ordinal_remap.deinit();
var ordinals: std.AutoArrayHashMapUnmanaged(MatchingSection, void) = .{};
var new_ordinal: u8 = 0;
for (self.load_commands.items) |lc, lc_id| {
if (lc != .segment) break;
for (lc.segment.sections.items) |_, sect_id| {
const match = MatchingSection{
.seg = @intCast(u16, lc_id),
.sect = @intCast(u16, sect_id),
};
const old_ordinal = @intCast(u8, self.section_ordinals.getIndex(match).? + 1);
new_ordinal += 1;
try ordinal_remap.putNoClobber(old_ordinal, new_ordinal);
try ordinals.putNoClobber(self.base.allocator, match, {});
}
}
for (self.locals.items) |*sym| {
if (sym.n_sect == 0) continue;
sym.n_sect = ordinal_remap.get(sym.n_sect).?;
}
for (self.globals.items) |*sym| {
sym.n_sect = ordinal_remap.get(sym.n_sect).?;
}
self.section_ordinals.deinit(self.base.allocator);
self.section_ordinals = ordinals;
}
fn writeDyldInfoData(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
var rebase_pointers = std.ArrayList(bind.Pointer).init(self.base.allocator);
defer rebase_pointers.deinit();
var bind_pointers = std.ArrayList(bind.Pointer).init(self.base.allocator);
defer bind_pointers.deinit();
var lazy_bind_pointers = std.ArrayList(bind.Pointer).init(self.base.allocator);
defer lazy_bind_pointers.deinit();
{
var it = self.atoms.iterator();
while (it.next()) |entry| {
const match = entry.key_ptr.*;
var atom: *Atom = entry.value_ptr.*;
if (match.seg == self.text_segment_cmd_index.?) continue; // __TEXT is non-writable
const seg = self.load_commands.items[match.seg].segment;
while (true) {
const sym = self.locals.items[atom.local_sym_index];
const base_offset = sym.n_value - seg.inner.vmaddr;
for (atom.rebases.items) |offset| {
try rebase_pointers.append(.{
.offset = base_offset + offset,
.segment_id = match.seg,
});
}
for (atom.bindings.items) |binding| {
const resolv = self.symbol_resolver.get(binding.n_strx).?;
switch (resolv.where) {
.global => {
// Turn into a rebase.
try rebase_pointers.append(.{
.offset = base_offset + binding.offset,
.segment_id = match.seg,
});
},
.undef => {
const bind_sym = self.undefs.items[resolv.where_index];
try bind_pointers.append(.{
.offset = binding.offset + base_offset,
.segment_id = match.seg,
.dylib_ordinal = @divExact(@bitCast(i16, bind_sym.n_desc), macho.N_SYMBOL_RESOLVER),
.name = self.getString(bind_sym.n_strx),
});
},
}
}
for (atom.lazy_bindings.items) |binding| {
const resolv = self.symbol_resolver.get(binding.n_strx).?;
switch (resolv.where) {
.global => {
// Turn into a rebase.
try rebase_pointers.append(.{
.offset = base_offset + binding.offset,
.segment_id = match.seg,
});
},
.undef => {
const bind_sym = self.undefs.items[resolv.where_index];
try lazy_bind_pointers.append(.{
.offset = binding.offset + base_offset,
.segment_id = match.seg,
.dylib_ordinal = @divExact(@bitCast(i16, bind_sym.n_desc), macho.N_SYMBOL_RESOLVER),
.name = self.getString(bind_sym.n_strx),
});
},
}
}
if (atom.prev) |prev| {
atom = prev;
} else break;
}
}
}
var trie: Trie = .{};
defer trie.deinit(self.base.allocator);
{
// TODO handle macho.EXPORT_SYMBOL_FLAGS_REEXPORT and macho.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER.
log.debug("generating export trie", .{});
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].segment;
const base_address = text_segment.inner.vmaddr;
for (self.globals.items) |sym| {
if (sym.n_type == 0) continue;
const sym_name = self.getString(sym.n_strx);
log.debug(" (putting '{s}' defined at 0x{x})", .{ sym_name, sym.n_value });
try trie.put(self.base.allocator, .{
.name = sym_name,
.vmaddr_offset = sym.n_value - base_address,
.export_flags = macho.EXPORT_SYMBOL_FLAGS_KIND_REGULAR,
});
}
try trie.finalize(self.base.allocator);
}
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment;
const dyld_info = &self.load_commands.items[self.dyld_info_cmd_index.?].dyld_info_only;
const rebase_size = try bind.rebaseInfoSize(rebase_pointers.items);
const bind_size = try bind.bindInfoSize(bind_pointers.items);
const lazy_bind_size = try bind.lazyBindInfoSize(lazy_bind_pointers.items);
const export_size = trie.size;
dyld_info.rebase_off = @intCast(u32, seg.inner.fileoff);
dyld_info.rebase_size = @intCast(u32, mem.alignForwardGeneric(u64, rebase_size, @alignOf(u64)));
seg.inner.filesize += dyld_info.rebase_size;
dyld_info.bind_off = dyld_info.rebase_off + dyld_info.rebase_size;
dyld_info.bind_size = @intCast(u32, mem.alignForwardGeneric(u64, bind_size, @alignOf(u64)));
seg.inner.filesize += dyld_info.bind_size;
dyld_info.lazy_bind_off = dyld_info.bind_off + dyld_info.bind_size;
dyld_info.lazy_bind_size = @intCast(u32, mem.alignForwardGeneric(u64, lazy_bind_size, @alignOf(u64)));
seg.inner.filesize += dyld_info.lazy_bind_size;
dyld_info.export_off = dyld_info.lazy_bind_off + dyld_info.lazy_bind_size;
dyld_info.export_size = @intCast(u32, mem.alignForwardGeneric(u64, export_size, @alignOf(u64)));
seg.inner.filesize += dyld_info.export_size;
const needed_size = dyld_info.rebase_size + dyld_info.bind_size + dyld_info.lazy_bind_size + dyld_info.export_size;
var buffer = try self.base.allocator.alloc(u8, needed_size);
defer self.base.allocator.free(buffer);
mem.set(u8, buffer, 0);
var stream = std.io.fixedBufferStream(buffer);
const writer = stream.writer();
try bind.writeRebaseInfo(rebase_pointers.items, writer);
try stream.seekBy(@intCast(i64, dyld_info.rebase_size) - @intCast(i64, rebase_size));
try bind.writeBindInfo(bind_pointers.items, writer);
try stream.seekBy(@intCast(i64, dyld_info.bind_size) - @intCast(i64, bind_size));
try bind.writeLazyBindInfo(lazy_bind_pointers.items, writer);
try stream.seekBy(@intCast(i64, dyld_info.lazy_bind_size) - @intCast(i64, lazy_bind_size));
_ = try trie.write(writer);
log.debug("writing dyld info from 0x{x} to 0x{x}", .{
dyld_info.rebase_off,
dyld_info.rebase_off + needed_size,
});
try self.base.file.?.pwriteAll(buffer, dyld_info.rebase_off);
try self.populateLazyBindOffsetsInStubHelper(
buffer[dyld_info.rebase_size + dyld_info.bind_size ..][0..dyld_info.lazy_bind_size],
);
self.load_commands_dirty = true;
}
fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void {
const last_atom = self.atoms.get(.{
.seg = self.text_segment_cmd_index.?,
.sect = self.stub_helper_section_index.?,
}) orelse return;
if (last_atom == self.stub_helper_preamble_atom.?) return;
var table = std.AutoHashMap(i64, *Atom).init(self.base.allocator);
defer table.deinit();
{
var stub_atom = last_atom;
var laptr_atom = self.atoms.get(.{
.seg = self.data_segment_cmd_index.?,
.sect = self.la_symbol_ptr_section_index.?,
}).?;
const base_addr = blk: {
const seg = self.load_commands.items[self.data_segment_cmd_index.?].segment;
break :blk seg.inner.vmaddr;
};
while (true) {
const laptr_off = blk: {
const sym = self.locals.items[laptr_atom.local_sym_index];
break :blk @intCast(i64, sym.n_value - base_addr);
};
try table.putNoClobber(laptr_off, stub_atom);
if (laptr_atom.prev) |prev| {
laptr_atom = prev;
stub_atom = stub_atom.prev.?;
} else break;
}
}
var stream = std.io.fixedBufferStream(buffer);
var reader = stream.reader();
var offsets = std.ArrayList(struct { sym_offset: i64, offset: u32 }).init(self.base.allocator);
try offsets.append(.{ .sym_offset = undefined, .offset = 0 });
defer offsets.deinit();
var valid_block = false;
while (true) {
const inst = reader.readByte() catch |err| switch (err) {
error.EndOfStream => break,
else => return err,
};
const opcode: u8 = inst & macho.BIND_OPCODE_MASK;
switch (opcode) {
macho.BIND_OPCODE_DO_BIND => {
valid_block = true;
},
macho.BIND_OPCODE_DONE => {
if (valid_block) {
const offset = try stream.getPos();
try offsets.append(.{ .sym_offset = undefined, .offset = @intCast(u32, offset) });
}
valid_block = false;
},
macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => {
var next = try reader.readByte();
while (next != @as(u8, 0)) {
next = try reader.readByte();
}
},
macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => {
var inserted = offsets.pop();
inserted.sym_offset = try std.leb.readILEB128(i64, reader);
try offsets.append(inserted);
},
macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB => {
_ = try std.leb.readULEB128(u64, reader);
},
macho.BIND_OPCODE_SET_ADDEND_SLEB => {
_ = try std.leb.readILEB128(i64, reader);
},
else => {},
}
}
const sect = blk: {
const seg = self.load_commands.items[self.text_segment_cmd_index.?].segment;
break :blk seg.sections.items[self.stub_helper_section_index.?];
};
const stub_offset: u4 = switch (self.base.options.target.cpu.arch) {
.x86_64 => 1,
.aarch64 => 2 * @sizeOf(u32),
else => unreachable,
};
var buf: [@sizeOf(u32)]u8 = undefined;
_ = offsets.pop();
while (offsets.popOrNull()) |bind_offset| {
const atom = table.get(bind_offset.sym_offset).?;
const sym = self.locals.items[atom.local_sym_index];
const file_offset = sect.offset + sym.n_value - sect.addr + stub_offset;
mem.writeIntLittle(u32, &buf, bind_offset.offset);
log.debug("writing lazy bind offset in stub helper of 0x{x} for symbol {s} at offset 0x{x}", .{
bind_offset.offset,
self.getString(sym.n_strx),
file_offset,
});
try self.base.file.?.pwriteAll(&buf, file_offset);
}
}
fn writeFunctionStarts(self: *MachO) !void {
var atom = self.atoms.get(.{
.seg = self.text_segment_cmd_index orelse return,
.sect = self.text_section_index orelse return,
}) orelse return;
const tracy = trace(@src());
defer tracy.end();
while (atom.prev) |prev| {
atom = prev;
}
var offsets = std.ArrayList(u32).init(self.base.allocator);
defer offsets.deinit();
const text_seg = self.load_commands.items[self.text_segment_cmd_index.?].segment;
var last_off: u32 = 0;
while (true) {
const atom_sym = self.locals.items[atom.local_sym_index];
if (atom_sym.n_strx != 0) blk: {
if (self.symbol_resolver.get(atom_sym.n_strx)) |resolv| {
assert(resolv.where == .global);
if (resolv.local_sym_index != atom.local_sym_index) break :blk;
}
const offset = @intCast(u32, atom_sym.n_value - text_seg.inner.vmaddr);
const diff = offset - last_off;
if (diff == 0) break :blk;
try offsets.append(diff);
last_off = offset;
}
for (atom.contained.items) |cont| {
const cont_sym = self.locals.items[cont.local_sym_index];
if (cont_sym.n_strx == 0) continue;
if (self.symbol_resolver.get(cont_sym.n_strx)) |resolv| {
assert(resolv.where == .global);
if (resolv.local_sym_index != cont.local_sym_index) continue;
}
const offset = @intCast(u32, cont_sym.n_value - text_seg.inner.vmaddr);
const diff = offset - last_off;
if (diff == 0) continue;
try offsets.append(diff);
last_off = offset;
}
if (atom.next) |next| {
atom = next;
} else break;
}
const max_size = @intCast(usize, offsets.items.len * @sizeOf(u64));
var buffer = try self.base.allocator.alloc(u8, max_size);
defer self.base.allocator.free(buffer);
mem.set(u8, buffer, 0);
var stream = std.io.fixedBufferStream(buffer);
var writer = stream.writer();
for (offsets.items) |offset| {
try std.leb.writeULEB128(writer, offset);
}
const needed_size = @intCast(u32, mem.alignForwardGeneric(u64, stream.pos, @sizeOf(u64)));
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment;
const fn_cmd = &self.load_commands.items[self.function_starts_cmd_index.?].linkedit_data;
fn_cmd.dataoff = @intCast(u32, seg.inner.fileoff + seg.inner.filesize);
fn_cmd.datasize = needed_size;
seg.inner.filesize += needed_size;
log.debug("writing function starts info from 0x{x} to 0x{x}", .{
fn_cmd.dataoff,
fn_cmd.dataoff + fn_cmd.datasize,
});
try self.base.file.?.pwriteAll(buffer[0..needed_size], fn_cmd.dataoff);
self.load_commands_dirty = true;
}
fn writeDices(self: *MachO) !void {
if (!self.has_dices) return;
const tracy = trace(@src());
defer tracy.end();
var buf = std.ArrayList(u8).init(self.base.allocator);
defer buf.deinit();
var atom: *Atom = self.atoms.get(.{
.seg = self.text_segment_cmd_index orelse return,
.sect = self.text_section_index orelse return,
}) orelse return;
while (atom.prev) |prev| {
atom = prev;
}
const text_seg = self.load_commands.items[self.text_segment_cmd_index.?].segment;
const text_sect = text_seg.sections.items[self.text_section_index.?];
while (true) {
if (atom.dices.items.len > 0) {
const sym = self.locals.items[atom.local_sym_index];
const base_off = try math.cast(u32, sym.n_value - text_sect.addr + text_sect.offset);
try buf.ensureUnusedCapacity(atom.dices.items.len * @sizeOf(macho.data_in_code_entry));
for (atom.dices.items) |dice| {
const rebased_dice = macho.data_in_code_entry{
.offset = base_off + dice.offset,
.length = dice.length,
.kind = dice.kind,
};
buf.appendSliceAssumeCapacity(mem.asBytes(&rebased_dice));
}
}
if (atom.next) |next| {
atom = next;
} else break;
}
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment;
const dice_cmd = &self.load_commands.items[self.data_in_code_cmd_index.?].linkedit_data;
const needed_size = @intCast(u32, buf.items.len);
dice_cmd.dataoff = @intCast(u32, seg.inner.fileoff + seg.inner.filesize);
dice_cmd.datasize = needed_size;
seg.inner.filesize += needed_size;
log.debug("writing data-in-code from 0x{x} to 0x{x}", .{
dice_cmd.dataoff,
dice_cmd.dataoff + dice_cmd.datasize,
});
try self.base.file.?.pwriteAll(buf.items, dice_cmd.dataoff);
self.load_commands_dirty = true;
}
fn writeSymbolTable(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment;
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].symtab;
symtab.symoff = @intCast(u32, seg.inner.fileoff + seg.inner.filesize);
var locals = std.ArrayList(macho.nlist_64).init(self.base.allocator);
defer locals.deinit();
for (self.locals.items) |sym| {
if (sym.n_strx == 0) continue;
if (self.symbol_resolver.get(sym.n_strx)) |_| continue;
try locals.append(sym);
}
// TODO How do we handle null global symbols in incremental context?
var undefs = std.ArrayList(macho.nlist_64).init(self.base.allocator);
defer undefs.deinit();
var undefs_table = std.AutoHashMap(u32, u32).init(self.base.allocator);
defer undefs_table.deinit();
try undefs.ensureTotalCapacity(self.undefs.items.len);
try undefs_table.ensureTotalCapacity(@intCast(u32, self.undefs.items.len));
for (self.undefs.items) |sym, i| {
if (sym.n_strx == 0) continue;
const new_index = @intCast(u32, undefs.items.len);
undefs.appendAssumeCapacity(sym);
undefs_table.putAssumeCapacityNoClobber(@intCast(u32, i), new_index);
}
if (self.has_stabs) {
for (self.objects.items) |object| {
if (object.debug_info == null) continue;
// Open scope
try locals.ensureUnusedCapacity(3);
locals.appendAssumeCapacity(.{
.n_strx = try self.makeString(object.tu_comp_dir.?),
.n_type = macho.N_SO,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
locals.appendAssumeCapacity(.{
.n_strx = try self.makeString(object.tu_name.?),
.n_type = macho.N_SO,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
locals.appendAssumeCapacity(.{
.n_strx = try self.makeString(object.name),
.n_type = macho.N_OSO,
.n_sect = 0,
.n_desc = 1,
.n_value = object.mtime orelse 0,
});
for (object.contained_atoms.items) |atom| {
if (atom.stab) |stab| {
const nlists = try stab.asNlists(atom.local_sym_index, self);
defer self.base.allocator.free(nlists);
try locals.appendSlice(nlists);
} else {
for (atom.contained.items) |sym_at_off| {
const stab = sym_at_off.stab orelse continue;
const nlists = try stab.asNlists(sym_at_off.local_sym_index, self);
defer self.base.allocator.free(nlists);
try locals.appendSlice(nlists);
}
}
}
// Close scope
try locals.append(.{
.n_strx = 0,
.n_type = macho.N_SO,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
}
}
const nlocals = locals.items.len;
const nexports = self.globals.items.len;
const nundefs = undefs.items.len;
const locals_off = symtab.symoff;
const locals_size = nlocals * @sizeOf(macho.nlist_64);
log.debug("writing local symbols from 0x{x} to 0x{x}", .{ locals_off, locals_size + locals_off });
try self.base.file.?.pwriteAll(mem.sliceAsBytes(locals.items), locals_off);
const exports_off = locals_off + locals_size;
const exports_size = nexports * @sizeOf(macho.nlist_64);
log.debug("writing exported symbols from 0x{x} to 0x{x}", .{ exports_off, exports_size + exports_off });
try self.base.file.?.pwriteAll(mem.sliceAsBytes(self.globals.items), exports_off);
const undefs_off = exports_off + exports_size;
const undefs_size = nundefs * @sizeOf(macho.nlist_64);
log.debug("writing undefined symbols from 0x{x} to 0x{x}", .{ undefs_off, undefs_size + undefs_off });
try self.base.file.?.pwriteAll(mem.sliceAsBytes(undefs.items), undefs_off);
symtab.nsyms = @intCast(u32, nlocals + nexports + nundefs);
seg.inner.filesize += locals_size + exports_size + undefs_size;
// Update dynamic symbol table.
const dysymtab = &self.load_commands.items[self.dysymtab_cmd_index.?].dysymtab;
dysymtab.nlocalsym = @intCast(u32, nlocals);
dysymtab.iextdefsym = dysymtab.nlocalsym;
dysymtab.nextdefsym = @intCast(u32, nexports);
dysymtab.iundefsym = dysymtab.nlocalsym + dysymtab.nextdefsym;
dysymtab.nundefsym = @intCast(u32, nundefs);
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].segment;
const stubs = &text_segment.sections.items[self.stubs_section_index.?];
const data_const_segment = &self.load_commands.items[self.data_const_segment_cmd_index.?].segment;
const got = &data_const_segment.sections.items[self.got_section_index.?];
const data_segment = &self.load_commands.items[self.data_segment_cmd_index.?].segment;
const la_symbol_ptr = &data_segment.sections.items[self.la_symbol_ptr_section_index.?];
const nstubs = @intCast(u32, self.stubs_table.keys().len);
const ngot_entries = @intCast(u32, self.got_entries_table.keys().len);
dysymtab.indirectsymoff = @intCast(u32, seg.inner.fileoff + seg.inner.filesize);
dysymtab.nindirectsyms = nstubs * 2 + ngot_entries;
const needed_size = dysymtab.nindirectsyms * @sizeOf(u32);
seg.inner.filesize += needed_size;
log.debug("writing indirect symbol table from 0x{x} to 0x{x}", .{
dysymtab.indirectsymoff,
dysymtab.indirectsymoff + needed_size,
});
var buf = try self.base.allocator.alloc(u8, needed_size);
defer self.base.allocator.free(buf);
var stream = std.io.fixedBufferStream(buf);
var writer = stream.writer();
stubs.reserved1 = 0;
for (self.stubs_table.keys()) |key| {
const resolv = self.symbol_resolver.get(key).?;
switch (resolv.where) {
.global => try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL),
.undef => try writer.writeIntLittle(u32, dysymtab.iundefsym + undefs_table.get(resolv.where_index).?),
}
}
got.reserved1 = nstubs;
for (self.got_entries_table.keys()) |key| {
switch (key) {
.local => try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL),
.global => |n_strx| {
const resolv = self.symbol_resolver.get(n_strx).?;
switch (resolv.where) {
.global => try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL),
.undef => try writer.writeIntLittle(u32, dysymtab.iundefsym + undefs_table.get(resolv.where_index).?),
}
},
}
}
la_symbol_ptr.reserved1 = got.reserved1 + ngot_entries;
for (self.stubs_table.keys()) |key| {
const resolv = self.symbol_resolver.get(key).?;
switch (resolv.where) {
.global => try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL),
.undef => try writer.writeIntLittle(u32, dysymtab.iundefsym + undefs_table.get(resolv.where_index).?),
}
}
try self.base.file.?.pwriteAll(buf, dysymtab.indirectsymoff);
self.load_commands_dirty = true;
}
fn writeStringTable(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment;
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].symtab;
symtab.stroff = @intCast(u32, seg.inner.fileoff + seg.inner.filesize);
symtab.strsize = @intCast(u32, mem.alignForwardGeneric(u64, self.strtab.items.len, @alignOf(u64)));
seg.inner.filesize += symtab.strsize;
log.debug("writing string table from 0x{x} to 0x{x}", .{ symtab.stroff, symtab.stroff + symtab.strsize });
try self.base.file.?.pwriteAll(self.strtab.items, symtab.stroff);
if (symtab.strsize > self.strtab.items.len) {
// This is potentially the last section, so we need to pad it out.
try self.base.file.?.pwriteAll(&[_]u8{0}, seg.inner.fileoff + seg.inner.filesize - 1);
}
self.load_commands_dirty = true;
}
fn writeLinkeditSegment(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment;
seg.inner.filesize = 0;
try self.writeDyldInfoData();
try self.writeFunctionStarts();
try self.writeDices();
try self.writeSymbolTable();
try self.writeStringTable();
seg.inner.vmsize = mem.alignForwardGeneric(u64, seg.inner.filesize, self.page_size);
}
fn writeCodeSignaturePadding(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const linkedit_segment = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment;
const code_sig_cmd = &self.load_commands.items[self.code_signature_cmd_index.?].linkedit_data;
// Code signature data has to be 16-bytes aligned for Apple tools to recognize the file
// https://github.com/opensource-apple/cctools/blob/fdb4825f303fd5c0751be524babd32958181b3ed/libstuff/checkout.c#L271
const fileoff = mem.alignForwardGeneric(u64, linkedit_segment.inner.fileoff + linkedit_segment.inner.filesize, 16);
const padding = fileoff - (linkedit_segment.inner.fileoff + linkedit_segment.inner.filesize);
const needed_size = CodeSignature.calcCodeSignaturePaddingSize(
self.base.options.emit.?.sub_path,
fileoff,
self.page_size,
);
code_sig_cmd.dataoff = @intCast(u32, fileoff);
code_sig_cmd.datasize = needed_size;
// Advance size of __LINKEDIT segment
linkedit_segment.inner.filesize += needed_size + padding;
if (linkedit_segment.inner.vmsize < linkedit_segment.inner.filesize) {
linkedit_segment.inner.vmsize = mem.alignForwardGeneric(u64, linkedit_segment.inner.filesize, self.page_size);
}
log.debug("writing code signature padding from 0x{x} to 0x{x}", .{ fileoff, fileoff + needed_size });
// Pad out the space. We need to do this to calculate valid hashes for everything in the file
// except for code signature data.
try self.base.file.?.pwriteAll(&[_]u8{0}, fileoff + needed_size - 1);
self.load_commands_dirty = true;
}
fn writeCodeSignature(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].segment;
const code_sig_cmd = self.load_commands.items[self.code_signature_cmd_index.?].linkedit_data;
var code_sig: CodeSignature = .{};
defer code_sig.deinit(self.base.allocator);
try code_sig.calcAdhocSignature(
self.base.allocator,
self.base.file.?,
self.base.options.emit.?.sub_path,
text_segment.inner,
code_sig_cmd,
self.base.options.output_mode,
self.page_size,
);
var buffer = try self.base.allocator.alloc(u8, code_sig.size());
defer self.base.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
try code_sig.write(stream.writer());
log.debug("writing code signature from 0x{x} to 0x{x}", .{ code_sig_cmd.dataoff, code_sig_cmd.dataoff + buffer.len });
try self.base.file.?.pwriteAll(buffer, code_sig_cmd.dataoff);
}
/// Writes all load commands and section headers.
fn writeLoadCommands(self: *MachO) !void {
if (!self.load_commands_dirty) return;
var sizeofcmds: u32 = 0;
for (self.load_commands.items) |lc| {
sizeofcmds += lc.cmdsize();
}
var buffer = try self.base.allocator.alloc(u8, sizeofcmds);
defer self.base.allocator.free(buffer);
var writer = std.io.fixedBufferStream(buffer).writer();
for (self.load_commands.items) |lc| {
try lc.write(writer);
}
const off = @sizeOf(macho.mach_header_64);
log.debug("writing {} load commands from 0x{x} to 0x{x}", .{ self.load_commands.items.len, off, off + sizeofcmds });
try self.base.file.?.pwriteAll(buffer, off);
self.load_commands_dirty = false;
}
/// Writes Mach-O file header.
fn writeHeader(self: *MachO) !void {
var header: macho.mach_header_64 = .{};
header.flags = macho.MH_NOUNDEFS | macho.MH_DYLDLINK | macho.MH_PIE | macho.MH_TWOLEVEL;
switch (self.base.options.target.cpu.arch) {
.aarch64 => {
header.cputype = macho.CPU_TYPE_ARM64;
header.cpusubtype = macho.CPU_SUBTYPE_ARM_ALL;
},
.x86_64 => {
header.cputype = macho.CPU_TYPE_X86_64;
header.cpusubtype = macho.CPU_SUBTYPE_X86_64_ALL;
},
else => return error.UnsupportedCpuArchitecture,
}
switch (self.base.options.output_mode) {
.Exe => {
header.filetype = macho.MH_EXECUTE;
},
.Lib => {
// By this point, it can only be a dylib.
header.filetype = macho.MH_DYLIB;
header.flags |= macho.MH_NO_REEXPORTED_DYLIBS;
},
else => unreachable,
}
if (self.tlv_section_index) |_| {
header.flags |= macho.MH_HAS_TLV_DESCRIPTORS;
}
header.ncmds = @intCast(u32, self.load_commands.items.len);
header.sizeofcmds = 0;
for (self.load_commands.items) |cmd| {
header.sizeofcmds += cmd.cmdsize();
}
log.debug("writing Mach-O header {}", .{header});
try self.base.file.?.pwriteAll(mem.asBytes(&header), 0);
}
pub fn padToIdeal(actual_size: anytype) @TypeOf(actual_size) {
// TODO https://github.com/ziglang/zig/issues/1284
return std.math.add(@TypeOf(actual_size), actual_size, actual_size / ideal_factor) catch
std.math.maxInt(@TypeOf(actual_size));
}
pub fn makeStaticString(bytes: []const u8) [16]u8 {
var buf = [_]u8{0} ** 16;
assert(bytes.len <= buf.len);
mem.copy(u8, &buf, bytes);
return buf;
}
pub fn makeString(self: *MachO, string: []const u8) !u32 {
const gop = try self.strtab_dir.getOrPutContextAdapted(self.base.allocator, @as([]const u8, string), StringIndexAdapter{
.bytes = &self.strtab,
}, StringIndexContext{
.bytes = &self.strtab,
});
if (gop.found_existing) {
const off = gop.key_ptr.*;
log.debug("reusing string '{s}' at offset 0x{x}", .{ string, off });
return off;
}
try self.strtab.ensureUnusedCapacity(self.base.allocator, string.len + 1);
const new_off = @intCast(u32, self.strtab.items.len);
log.debug("writing new string '{s}' at offset 0x{x}", .{ string, new_off });
self.strtab.appendSliceAssumeCapacity(string);
self.strtab.appendAssumeCapacity(0);
gop.key_ptr.* = new_off;
return new_off;
}
pub fn getString(self: MachO, off: u32) []const u8 {
assert(off < self.strtab.items.len);
return mem.sliceTo(@ptrCast([*:0]const u8, self.strtab.items.ptr + off), 0);
}
pub fn symbolIsTemp(sym: macho.nlist_64, sym_name: []const u8) bool {
if (!sym.sect()) return false;
if (sym.ext()) return false;
return mem.startsWith(u8, sym_name, "l") or mem.startsWith(u8, sym_name, "L");
}
pub fn findFirst(comptime T: type, haystack: []T, start: usize, predicate: anytype) usize {
if (!@hasDecl(@TypeOf(predicate), "predicate"))
@compileError("Predicate is required to define fn predicate(@This(), T) bool");
if (start == haystack.len) return start;
var i = start;
while (i < haystack.len) : (i += 1) {
if (predicate.predicate(haystack[i])) break;
}
return i;
}
fn snapshotState(self: *MachO) !void {
const emit = self.base.options.emit orelse {
log.debug("no emit directory found; skipping snapshot...", .{});
return;
};
const Snapshot = struct {
const Node = struct {
const Tag = enum {
section_start,
section_end,
atom_start,
atom_end,
relocation,
pub fn jsonStringify(
tag: Tag,
options: std.json.StringifyOptions,
out_stream: anytype,
) !void {
_ = options;
switch (tag) {
.section_start => try out_stream.writeAll("\"section_start\""),
.section_end => try out_stream.writeAll("\"section_end\""),
.atom_start => try out_stream.writeAll("\"atom_start\""),
.atom_end => try out_stream.writeAll("\"atom_end\""),
.relocation => try out_stream.writeAll("\"relocation\""),
}
}
};
const Payload = struct {
name: []const u8 = "",
aliases: [][]const u8 = &[0][]const u8{},
is_global: bool = false,
target: u64 = 0,
};
address: u64,
tag: Tag,
payload: Payload,
};
timestamp: i128,
nodes: []Node,
};
var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
const out_file = try emit.directory.handle.createFile("snapshots.json", .{
.truncate = self.cold_start,
.read = true,
});
defer out_file.close();
if (out_file.seekFromEnd(-1)) {
try out_file.writer().writeByte(',');
} else |err| switch (err) {
error.Unseekable => try out_file.writer().writeByte('['),
else => |e| return e,
}
var writer = out_file.writer();
var snapshot = Snapshot{
.timestamp = std.time.nanoTimestamp(),
.nodes = undefined,
};
var nodes = std.ArrayList(Snapshot.Node).init(arena);
for (self.section_ordinals.keys()) |key| {
const seg = self.load_commands.items[key.seg].segment;
const sect = seg.sections.items[key.sect];
const sect_name = try std.fmt.allocPrint(arena, "{s},{s}", .{ sect.segName(), sect.sectName() });
try nodes.append(.{
.address = sect.addr,
.tag = .section_start,
.payload = .{ .name = sect_name },
});
var atom: *Atom = self.atoms.get(key) orelse {
try nodes.append(.{
.address = sect.addr + sect.size,
.tag = .section_end,
.payload = .{},
});
continue;
};
while (atom.prev) |prev| {
atom = prev;
}
while (true) {
const atom_sym = self.locals.items[atom.local_sym_index];
const should_skip_atom: bool = blk: {
if (self.mh_execute_header_index) |index| {
if (index == atom.local_sym_index) break :blk true;
}
if (mem.eql(u8, self.getString(atom_sym.n_strx), "___dso_handle")) break :blk true;
break :blk false;
};
if (should_skip_atom) {
if (atom.next) |next| {
atom = next;
} else break;
continue;
}
var node = Snapshot.Node{
.address = atom_sym.n_value,
.tag = .atom_start,
.payload = .{
.name = self.getString(atom_sym.n_strx),
.is_global = self.symbol_resolver.contains(atom_sym.n_strx),
},
};
var aliases = std.ArrayList([]const u8).init(arena);
for (atom.aliases.items) |loc| {
try aliases.append(self.getString(self.locals.items[loc].n_strx));
}
node.payload.aliases = aliases.toOwnedSlice();
try nodes.append(node);
var relocs = try std.ArrayList(Snapshot.Node).initCapacity(arena, atom.relocs.items.len);
for (atom.relocs.items) |rel| {
const arch = self.base.options.target.cpu.arch;
const source_addr = blk: {
const sym = self.locals.items[atom.local_sym_index];
break :blk sym.n_value + rel.offset;
};
const target_addr = blk: {
const is_via_got = got: {
switch (arch) {
.aarch64 => break :got switch (@intToEnum(macho.reloc_type_arm64, rel.@"type")) {
.ARM64_RELOC_GOT_LOAD_PAGE21, .ARM64_RELOC_GOT_LOAD_PAGEOFF12 => true,
else => false,
},
.x86_64 => break :got switch (@intToEnum(macho.reloc_type_x86_64, rel.@"type")) {
.X86_64_RELOC_GOT, .X86_64_RELOC_GOT_LOAD => true,
else => false,
},
else => unreachable,
}
};
if (is_via_got) {
const got_index = self.got_entries_table.get(rel.target) orelse break :blk 0;
const got_atom = self.got_entries.items[got_index].atom;
break :blk self.locals.items[got_atom.local_sym_index].n_value;
}
switch (rel.target) {
.local => |sym_index| {
const sym = self.locals.items[sym_index];
const is_tlv = is_tlv: {
const source_sym = self.locals.items[atom.local_sym_index];
const match = self.section_ordinals.keys()[source_sym.n_sect - 1];
const match_seg = self.load_commands.items[match.seg].segment;
const match_sect = match_seg.sections.items[match.sect];
break :is_tlv match_sect.type_() == macho.S_THREAD_LOCAL_VARIABLES;
};
if (is_tlv) {
const match_seg = self.load_commands.items[self.data_segment_cmd_index.?].segment;
const base_address = inner: {
if (self.tlv_data_section_index) |i| {
break :inner match_seg.sections.items[i].addr;
} else if (self.tlv_bss_section_index) |i| {
break :inner match_seg.sections.items[i].addr;
} else unreachable;
};
break :blk sym.n_value - base_address;
}
break :blk sym.n_value;
},
.global => |n_strx| {
const resolv = self.symbol_resolver.get(n_strx).?;
switch (resolv.where) {
.global => break :blk self.globals.items[resolv.where_index].n_value,
.undef => {
if (self.stubs_table.get(n_strx)) |stub_index| {
const stub_atom = self.stubs.items[stub_index];
break :blk self.locals.items[stub_atom.local_sym_index].n_value;
}
break :blk 0;
},
}
},
}
};
relocs.appendAssumeCapacity(.{
.address = source_addr,
.tag = .relocation,
.payload = .{ .target = target_addr },
});
}
if (atom.contained.items.len == 0) {
try nodes.appendSlice(relocs.items);
} else {
// Need to reverse iteration order of relocs since by default for relocatable sources
// they come in reverse. For linking, this doesn't matter in any way, however, for
// arranging the memoryline for displaying it does.
std.mem.reverse(Snapshot.Node, relocs.items);
var next_i: usize = 0;
var last_rel: usize = 0;
while (next_i < atom.contained.items.len) : (next_i += 1) {
const loc = atom.contained.items[next_i];
const cont_sym = self.locals.items[loc.local_sym_index];
const cont_sym_name = self.getString(cont_sym.n_strx);
var contained_node = Snapshot.Node{
.address = cont_sym.n_value,
.tag = .atom_start,
.payload = .{
.name = cont_sym_name,
.is_global = self.symbol_resolver.contains(cont_sym.n_strx),
},
};
// Accumulate aliases
var inner_aliases = std.ArrayList([]const u8).init(arena);
while (true) {
if (next_i + 1 >= atom.contained.items.len) break;
const next_sym = self.locals.items[atom.contained.items[next_i + 1].local_sym_index];
if (next_sym.n_value != cont_sym.n_value) break;
const next_sym_name = self.getString(next_sym.n_strx);
if (self.symbol_resolver.contains(next_sym.n_strx)) {
try inner_aliases.append(contained_node.payload.name);
contained_node.payload.name = next_sym_name;
contained_node.payload.is_global = true;
} else try inner_aliases.append(next_sym_name);
next_i += 1;
}
const cont_size = if (next_i + 1 < atom.contained.items.len)
self.locals.items[atom.contained.items[next_i + 1].local_sym_index].n_value - cont_sym.n_value
else
atom_sym.n_value + atom.size - cont_sym.n_value;
contained_node.payload.aliases = inner_aliases.toOwnedSlice();
try nodes.append(contained_node);
for (relocs.items[last_rel..]) |rel| {
if (rel.address >= cont_sym.n_value + cont_size) {
break;
}
try nodes.append(rel);
last_rel += 1;
}
try nodes.append(.{
.address = cont_sym.n_value + cont_size,
.tag = .atom_end,
.payload = .{},
});
}
}
try nodes.append(.{
.address = atom_sym.n_value + atom.size,
.tag = .atom_end,
.payload = .{},
});
if (atom.next) |next| {
atom = next;
} else break;
}
try nodes.append(.{
.address = sect.addr + sect.size,
.tag = .section_end,
.payload = .{},
});
}
snapshot.nodes = nodes.toOwnedSlice();
try std.json.stringify(snapshot, .{}, writer);
try writer.writeByte(']');
}
fn logSymtab(self: MachO) void {
log.debug("locals:", .{});
for (self.locals.items) |sym, id| {
log.debug(" {d}: {s}: @{x} in {d}", .{ id, self.getString(sym.n_strx), sym.n_value, sym.n_sect });
}
log.debug("globals:", .{});
for (self.globals.items) |sym, id| {
log.debug(" {d}: {s}: @{x} in {d}", .{ id, self.getString(sym.n_strx), sym.n_value, sym.n_sect });
}
log.debug("undefs:", .{});
for (self.undefs.items) |sym, id| {
log.debug(" {d}: {s}: in {d}", .{ id, self.getString(sym.n_strx), sym.n_desc });
}
{
log.debug("resolver:", .{});
var it = self.symbol_resolver.iterator();
while (it.next()) |entry| {
log.debug(" {s} => {}", .{ self.getString(entry.key_ptr.*), entry.value_ptr.* });
}
}
log.debug("GOT entries:", .{});
for (self.got_entries_table.values()) |value| {
const key = self.got_entries.items[value].target;
const atom = self.got_entries.items[value].atom;
const n_value = self.locals.items[atom.local_sym_index].n_value;
switch (key) {
.local => |ndx| log.debug(" {d}: @{x}", .{ ndx, n_value }),
.global => |n_strx| log.debug(" {s}: @{x}", .{ self.getString(n_strx), n_value }),
}
}
log.debug("__thread_ptrs entries:", .{});
for (self.tlv_ptr_entries_table.values()) |value| {
const key = self.tlv_ptr_entries.items[value].target;
const atom = self.tlv_ptr_entries.items[value].atom;
const n_value = self.locals.items[atom.local_sym_index].n_value;
assert(key == .global);
log.debug(" {s}: @{x}", .{ self.getString(key.global), n_value });
}
log.debug("stubs:", .{});
for (self.stubs_table.keys()) |key| {
const value = self.stubs_table.get(key).?;
const atom = self.stubs.items[value];
const sym = self.locals.items[atom.local_sym_index];
log.debug(" {s}: @{x}", .{ self.getString(key), sym.n_value });
}
}
fn logSectionOrdinals(self: MachO) void {
for (self.section_ordinals.keys()) |match, i| {
const seg = self.load_commands.items[match.seg].segment;
const sect = seg.sections.items[match.sect];
log.debug("ord {d}: {d},{d} => {s},{s}", .{
i + 1,
match.seg,
match.sect,
sect.segName(),
sect.sectName(),
});
}
}
/// Since `os.copy_file_range` cannot be used when copying overlapping ranges within the same file,
/// and since `File.copyRangeAll` uses `os.copy_file_range` under-the-hood, we use heap allocated
/// buffers on all hosts except Linux (if `copy_file_range` syscall is available).
pub fn copyRangeAllOverlappingAlloc(
allocator: Allocator,
file: std.fs.File,
in_offset: u64,
out_offset: u64,
len: usize,
) !void {
const buf = try allocator.alloc(u8, len);
defer allocator.free(buf);
_ = try file.preadAll(buf, in_offset);
try file.pwriteAll(buf, out_offset);
} | src/link/MachO.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const json = std.json;
const builtin = std.builtin;
// probably only StrMgmt.copy should ever be used
// StrMgmt.move seems ill
// sex field's behaviour is not affected
pub const StrMgmt = enum {
copy, move, weak,
pub fn asText(comptime options: StrMgmt) switch (options) {
.copy => @TypeOf("copy"),
.move => @TypeOf("move"),
.weak => @TypeOf("weak"),
} {
return switch (options) {
.copy => "copy",
.move => "move",
.weak => "weak",
};
}
pub fn asEnumLiteral(comptime options: StrMgmt) @TypeOf(.enum_literal) {
return switch (options) {
.copy => .copy,
.move => .move,
.weak => .weak,
};
}
};
pub fn AOCheck(allocator: anytype, comptime options: StrMgmt) void {
switch (options) {
.copy => {
switch (@TypeOf(allocator)) {
Allocator => {},
@TypeOf(null) => @compileError("util: can't .copy w\\o allocator, did you mean .weak?"),
else => @compileError("util: nonexhaustive switch in AOCheck()"),
}
},
.move, .weak => {},
}
}
pub fn allocatorCapture(allocator: anytype) ?Allocator {
switch (@TypeOf(allocator)) {
Allocator => return allocator,
@TypeOf(null) => return null,
else => @compileError("util: nonexhaustive switch in allocatorCapture()"),
}
}
pub fn strCopyAlloc(from: []const u8, ator: Allocator) ![]u8 {
var res = try ator.alloc(u8, from.len);
for (from) |c, i| {
res[i] = c;
}
return res;
}
pub fn strEqual(lhs: []const u8, rhs: []const u8) bool {
if (lhs.len != rhs.len)
return false;
for (lhs) |c, i| {
if (c != rhs[i])
return false;
}
return true;
}
pub const MemoryError = error {
OutOfMemory,
};
pub const ToJsonError = MemoryError;
pub const ToJsonSettings = struct {
allow_overload: bool = true,
apply_arena: bool = true,
};
pub const ToJsonResult = struct {
value: json.Value,
arena: ?ArenaAllocator = null,
pub fn deinit(this: *ToJsonResult) void {
if (this.arena) |*_arena| {
_arena.deinit();
}
}
};
pub fn toJson(
arg: anytype,
ator: Allocator,
comptime settings: ToJsonSettings,
) ToJsonError!ToJsonResult {
const ArgType = @TypeOf(arg);
var res = ToJsonResult{
.value=undefined,
.arena=null,
};
errdefer res.deinit();
switch (@typeInfo(ArgType)) {
.Optional => {
if (arg) |value| {
res = try toJson(value, ator, settings);
} else {
res.value = .{.Null={}};
}
},
.Int => {
if (ArgType != u64 and @sizeOf(ArgType) <= 8) {
res.value = .{.Integer=@intCast(i64, arg)};
} else {
@compileError("can't turn " ++ @typeName(ArgType) ++ "into json.Integer");
}
},
.Float => {
if (ArgType != f128 and ArgType != c_longdouble) {
res.value = .{.Float=@floatCast(f64, arg)};
} else {
@compileError("can't turn " ++ @typeName(ArgType) ++ "into json.Float");
}
},
.Struct => {
if (@hasDecl(ArgType, "toJson") and settings.allow_overload) {
res = try arg.toJson(ator, settings);
} else {
res = try struct2json(
arg, ator,
.{
.allow_overload = true,
.apply_arena = settings.apply_arena,
},
);
}
},
.Array => |array_info| {
switch (array_info.child) {
u8 => {
res.value = .{.String=arg};
},
else => {
res = try array2json(arg, ator, settings);
},
}
},
.Pointer => |pointer_info| {
// TODO inspect pointer_info.size
switch (pointer_info.child) {
u8 => {
res.value = .{.String=arg};
},
else => {
res = try array2json(arg, ator, settings);
},
}
},
else => {
@compileError("util.toJson(): don't know what to do w/ " ++ @typeName(ArgType));
},
}
return res;
}
fn array2json(
arg: anytype,
_ator: Allocator,
comptime settings: ToJsonSettings,
) ToJsonError!ToJsonResult {
const ArgType = @TypeOf(arg);
// TODO make 2 if's 1
var res = ToJsonResult{
.value = undefined,
.arena = if (settings.apply_arena) ArenaAllocator.init(_ator) else null,
};
errdefer res.deinit();
var ator = if (res.arena) |*arena| arena.allocator() else _ator;
res.value = .{.Array=json.Array.init(ator)};
const settings_to_pass = ToJsonSettings{
.allow_overload = settings.allow_overload,
.apply_arena = false,
};
switch (@typeInfo(ArgType)) {
.Array, .Pointer => {
try res.value.Array.ensureUnusedCapacity(arg.len);
for (arg) |item| {
res.value.Array.appendAssumeCapacity(
(try toJson(item, ator, settings_to_pass)).value
);
}
},
else => {
@compileError("util.array2json(): " ++ @typeName(ArgType) ++ " is not array");
},
}
return res;
}
fn struct2json(
arg: anytype,
_ator: Allocator,
comptime settings: ToJsonSettings,
) ToJsonError!ToJsonResult {
const ArgType = @TypeOf(arg);
// TODO make 2 if's 1
var res = ToJsonResult{
.value = undefined,
.arena = if (settings.apply_arena) ArenaAllocator.init(_ator) else null,
};
errdefer res.deinit();
const ator = if (res.arena) |*arena| arena.allocator() else _ator;
res.value = .{.Object=json.ObjectMap.init(ator)};
const settings_to_pass = ToJsonSettings{
.allow_overload = settings.allow_overload, // must be true
.apply_arena = false,
};
switch (@typeInfo(ArgType)) {
.Struct => |struct_info| {
try res.value.Object.ensureUnusedCapacity(struct_info.fields.len);
inline for (struct_info.fields) |field| {
res.value.Object.putAssumeCapacityNoClobber(
field.name,
(try toJson(@field(arg, field.name), ator, settings_to_pass)).value,
);
}
},
else => {
@compileError("util.struct2json(): " ++ @typeName(ArgType) ++ " is not struct");
},
}
return res;
}
pub const EqualSettings = struct {
allow_overload: bool = true,
};
pub fn equal(
lhs: anytype,
rhs: anytype,
comptime settings: EqualSettings,
) bool {
const ArgType = @TypeOf(lhs);
switch (@typeInfo(ArgType)) {
.Optional => {
if (lhs) |lval| {
if (rhs) |rval| {
return equal(lval, rval, .{.allow_overload=true});
} else {
return false;
}
} else {
if (rhs) |_| {
return false;
} else {
return true;
}
}
},
.Int, .Float => {
return lhs == rhs;
},
.Struct => |struct_info| {
if (@hasDecl(ArgType, "equal") and settings.allow_overload) {
return lhs.equal(rhs, .{.allow_overload=true});
}
inline for (struct_info.fields) |field| {
const _lhs = @field(lhs, field.name);
const _rhs = @field(rhs, field.name);
if (!equal(_lhs, _rhs, .{.allow_overload=true})) {
std.debug.print("\n{s} field mismatch!\n", .{field.name});
// std.debug.print("\n{} != {}\n", .{_lhs, _rhs});
return false;
}
}
return true;
},
.Array => {
if (lhs.len != rhs.len) {
return false;
}
for (lhs) |_lhs, i| {
if (!equal(_lhs, rhs[i], settings)) {
return false;
}
}
return true;
},
.Pointer => |pointer_info| {
switch (pointer_info.size) {
.Slice => {
if (lhs.len != rhs.len) {
return false;
}
for (lhs) |_lhs, i| {
if (!equal(_lhs, rhs[i], settings)) {
return false;
}
}
return true;
},
else => {
return lhs == rhs;
},
}
},
else => {
@compileError("util.equal(): don't know what to do w/ " ++ @typeName(ArgType));
},
}
}
const testing = std.testing;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
const tator = testing.allocator;
const Struct = struct {
int: i64,
float: f64,
ss: SubStruct,
const SubStruct = struct {
int: i64,
float: f64,
pub fn toJson(self: SubStruct, ator: Allocator, comptime settings: ToJsonSettings) !ToJsonResult {
_ = settings;
var res = json.ObjectMap.init(ator);
errdefer res.deinit();
try res.put("int", @unionInit(json.Value, "Float", self.float));
try res.put("float", @unionInit(json.Value, "Integer", self.int));
return ToJsonResult{.value=.{.Object=res}, .arena=null};
}
};
};
const String = struct {
data: []const u8,
};
test "to json" {
var j_int = try toJson(@as(i64, 2), tator, .{});
try expectEqual(j_int.value.Integer, 2);
try expectEqual(j_int.arena, null);
var j_float = try toJson(@as(f64, 2.0), tator, .{});
try expectEqual(j_float.value.Float, 2.0);
try expectEqual(j_float.arena, null);
var s = Struct {
.int = 1, .float = 1.0,
.ss = .{
.int = 2, .float = 2.0,
},
};
var js = try toJson(s, tator, .{});
defer js.deinit();
_ = js;
try expectEqual(js.value.Object.get("ss").?.Object.get("int").?.Float, 2.0);
var o: ?i32 = 1;
var oo: ?i32 = null;
var j_o = try toJson(o, tator, .{});
var j_oo = try toJson(oo, tator, .{});
_ = j_o.value.Integer;
_ = j_oo.value.Null;
var string = String{.data = "string"};
var j_string = try toJson(string, tator, .{});
defer j_string.deinit();
try expect(strEqual(string.data, j_string.value.Object.get("data").?.String));
} | src/util.zig |
usingnamespace @import("../bits.zig");
pub fn syscall0(number: SYS) usize {
return asm volatile (
\\ syscall
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize)
: [number] "{$2}" (@enumToInt(number))
: "memory", "cc", "$7"
);
}
pub fn syscall_pipe(fd: *[2]i32) usize {
return asm volatile (
\\ .set noat
\\ .set noreorder
\\ syscall
\\ blez $7, 1f
\\ nop
\\ b 2f
\\ subu $2, $0, $2
\\ 1:
\\ sw $2, 0($4)
\\ sw $3, 4($4)
\\ 2:
: [ret] "={$2}" (-> usize)
: [number] "{$2}" (@enumToInt(SYS.pipe))
: "memory", "cc", "$7"
);
}
pub fn syscall1(number: SYS, arg1: usize) usize {
return asm volatile (
\\ syscall
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize)
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1)
: "memory", "cc", "$7"
);
}
pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize {
return asm volatile (
\\ syscall
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize)
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
[arg2] "{$5}" (arg2)
: "memory", "cc", "$7"
);
}
pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize {
return asm volatile (
\\ syscall
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize)
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
[arg2] "{$5}" (arg2),
[arg3] "{$6}" (arg3)
: "memory", "cc", "$7"
);
}
pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {
return asm volatile (
\\ syscall
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize)
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
[arg2] "{$5}" (arg2),
[arg3] "{$6}" (arg3),
[arg4] "{$7}" (arg4)
: "memory", "cc", "$7"
);
}
pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {
return asm volatile (
\\ .set noat
\\ subu $sp, $sp, 24
\\ sw %[arg5], 16($sp)
\\ syscall
\\ addu $sp, $sp, 24
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize)
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
[arg2] "{$5}" (arg2),
[arg3] "{$6}" (arg3),
[arg4] "{$7}" (arg4),
[arg5] "r" (arg5)
: "memory", "cc", "$7"
);
}
pub fn syscall6(
number: SYS,
arg1: usize,
arg2: usize,
arg3: usize,
arg4: usize,
arg5: usize,
arg6: usize,
) usize {
return asm volatile (
\\ .set noat
\\ subu $sp, $sp, 24
\\ sw %[arg5], 16($sp)
\\ sw %[arg6], 20($sp)
\\ syscall
\\ addu $sp, $sp, 24
\\ blez $7, 1f
\\ subu $2, $0, $2
\\ 1:
: [ret] "={$2}" (-> usize)
: [number] "{$2}" (@enumToInt(number)),
[arg1] "{$4}" (arg1),
[arg2] "{$5}" (arg2),
[arg3] "{$6}" (arg3),
[arg4] "{$7}" (arg4),
[arg5] "r" (arg5),
[arg6] "r" (arg6)
: "memory", "cc", "$7"
);
}
/// This matches the libc clone function.
pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: u32, arg: usize, ptid: *i32, tls: usize, ctid: *i32) usize;
pub fn restore() callconv(.Naked) void {
return asm volatile ("syscall"
:
: [number] "{$2}" (@enumToInt(SYS.sigreturn))
: "memory", "cc", "$7"
);
}
pub fn restore_rt() callconv(.Naked) void {
return asm volatile ("syscall"
:
: [number] "{$2}" (@enumToInt(SYS.rt_sigreturn))
: "memory", "cc", "$7"
);
} | lib/std/os/linux/mips.zig |
const std = @import("../../std.zig");
const debug = std.debug;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
/// Returns exp(z) scaled to avoid overflow.
pub fn ldexp_cexp(z: var, expt: i32) @typeOf(z) {
const T = @typeOf(z.re);
return switch (T) {
f32 => ldexp_cexp32(z, expt),
f64 => ldexp_cexp64(z, expt),
else => unreachable,
};
}
fn frexp_exp32(x: f32, expt: *i32) f32 {
const k = 235; // reduction constant
const kln2 = 162.88958740; // k * ln2
const exp_x = math.exp(x - kln2);
const hx = @bitCast(u32, exp_x);
// TODO zig should allow this cast implicitly because it should know the value is in range
expt.* = @intCast(i32, hx >> 23) - (0x7f + 127) + k;
return @bitCast(f32, (hx & 0x7fffff) | ((0x7f + 127) << 23));
}
fn ldexp_cexp32(z: Complex(f32), expt: i32) Complex(f32) {
var ex_expt: i32 = undefined;
const exp_x = frexp_exp32(z.re, &ex_expt);
const exptf = expt + ex_expt;
const half_expt1 = @divTrunc(exptf, 2);
const scale1 = @bitCast(f32, (0x7f + half_expt1) << 23);
const half_expt2 = exptf - half_expt1;
const scale2 = @bitCast(f32, (0x7f + half_expt2) << 23);
return Complex(f32).new(math.cos(z.im) * exp_x * scale1 * scale2, math.sin(z.im) * exp_x * scale1 * scale2);
}
fn frexp_exp64(x: f64, expt: *i32) f64 {
const k = 1799; // reduction constant
const kln2 = 1246.97177782734161156; // k * ln2
const exp_x = math.exp(x - kln2);
const fx = @bitCast(u64, x);
const hx = @intCast(u32, fx >> 32);
const lx = @truncate(u32, fx);
expt.* = @intCast(i32, hx >> 20) - (0x3ff + 1023) + k;
const high_word = (hx & 0xfffff) | ((0x3ff + 1023) << 20);
return @bitCast(f64, (@as(u64, high_word) << 32) | lx);
}
fn ldexp_cexp64(z: Complex(f64), expt: i32) Complex(f64) {
var ex_expt: i32 = undefined;
const exp_x = frexp_exp64(z.re, &ex_expt);
const exptf = @as(i64, expt + ex_expt);
const half_expt1 = @divTrunc(exptf, 2);
const scale1 = @bitCast(f64, (0x3ff + half_expt1) << 20);
const half_expt2 = exptf - half_expt1;
const scale2 = @bitCast(f64, (0x3ff + half_expt2) << 20);
return Complex(f64).new(
math.cos(z.im) * exp_x * scale1 * scale2,
math.sin(z.im) * exp_x * scale1 * scale2,
);
} | lib/std/math/complex/ldexp.zig |
const std = @import("std");
const liu = @import("liu");
const editor = @import("./editor.zig");
const util = @import("./util.zig");
const rows = util.rows;
const camera = util.camera;
const KeyCode = liu.gamescreen.KeyCode;
const Timer = liu.gamescreen.Timer;
const FrameInput = liu.gamescreen.FrameInput;
// https://youtu.be/SFKR5rZBu-8?t=2202
// https://stackoverflow.com/questions/22511158/how-to-profile-web-workers-in-chrome
const wasm = liu.wasm;
pub usingnamespace wasm;
pub const Vec2 = liu.Vec2;
pub const Vec3 = liu.Vec3;
pub const Vec4 = liu.Vec4;
pub const BBox = struct {
pos: Vec2,
width: f32,
height: f32,
const Overlap = struct {
result: bool,
x: bool,
y: bool,
};
pub fn overlap(self: @This(), other: @This()) Overlap {
const pos1 = self.pos + Vec2{ self.width, self.height };
const other_pos1 = other.pos + Vec2{ other.width, other.height };
const x = self.pos[0] < other_pos1[0] and other.pos[0] < pos1[0];
const y = self.pos[1] < other_pos1[1] and other.pos[1] < pos1[1];
return .{
.result = x and y,
.y = y,
.x = x,
};
}
pub fn renderRectVector(self: @This()) @Vector(4, i32) {
return @Vector(4, i32){
@floatToInt(i32, @floor(self.pos[0])),
@floatToInt(i32, @floor(self.pos[1])),
@floatToInt(i32, @ceil(self.width)),
@floatToInt(i32, @ceil(self.height)),
};
}
};
pub const ext = struct {
pub extern fn fillStyle(r: f32, g: f32, b: f32, a: f32) void;
pub extern fn strokeStyle(r: f32, g: f32, b: f32, a: f32) void;
pub extern fn fillRect(x: i32, y: i32, width: i32, height: i32) void;
pub extern fn strokeRect(x: i32, y: i32, width: i32, height: i32) void;
pub extern fn setFont(font: wasm.Obj) void;
pub extern fn fillText(text: wasm.Obj, x: i32, y: i32) void;
};
pub const RenderC = struct {
color: Vec4,
};
pub const PositionC = struct {
bbox: BBox,
};
pub const MoveC = struct {
velocity: Vec2,
};
pub const ForceC = struct {
accel: Vec2,
friction: f32,
is_airborne: bool = false,
};
pub const DecisionC = struct {
player: bool,
};
export fn init() void {
wasm.initIfNecessary();
initErr() catch @panic("meh");
wasm.post(.log, "WASM initialized!", .{});
}
const Registry = liu.ecs.Registry(&.{
PositionC,
MoveC,
RenderC,
DecisionC,
ForceC,
});
const norm_color: Vec4 = Vec4{ 0.3, 0.3, 0.3, 0.6 };
fn initErr() !void {
large_font = wasm.make.string(.manual, "bold 48px sans-serif");
med_font = wasm.make.string(.manual, "24px sans-serif");
small_font = wasm.make.string(.manual, "10px sans-serif");
level_download = wasm.make.string(.manual, "levelDownload");
try tools.appendSlice(Static, &.{
try editor.Tool.create(Static, editor.LineTool{}),
try editor.Tool.create(Static, editor.DrawTool{}),
try editor.Tool.create(Static, editor.ClickTool{}),
});
registry = try Registry.init(16, liu.Pages);
var i: u32 = 0;
while (i < 3) : (i += 1) {
var color = norm_color;
color[i] = 1;
const box = try registry.create("bar");
try registry.addComponent(box, PositionC{ .bbox = .{
.pos = Vec2{ @intToFloat(f32, i) + 5, 3 },
.width = 0.5,
.height = 2.75,
} });
try registry.addComponent(box, RenderC{
.color = color,
});
try registry.addComponent(box, MoveC{
.velocity = Vec2{ 0, 0 },
});
try registry.addComponent(box, DecisionC{ .player = true });
try registry.addComponent(box, ForceC{
.accel = Vec2{ 0, -14 },
.friction = 0.05,
});
}
const bump = try registry.create("bump");
try registry.addComponent(bump, PositionC{ .bbox = .{
.pos = Vec2{ 10, 4 },
.width = 1,
.height = 1,
} });
try registry.addComponent(bump, RenderC{
.color = Vec4{ 0.1, 0.5, 0.3, 1 },
});
const ground = try registry.create("ground");
try registry.addComponent(ground, PositionC{ .bbox = .{
.pos = Vec2{ 0, 0 },
.width = 100,
.height = 1,
} });
try registry.addComponent(ground, RenderC{
.color = Vec4{ 0.2, 0.5, 0.3, 1 },
});
}
var start_timer: Timer = undefined;
var static_storage: liu.Bump = liu.Bump.init(1024, liu.Pages);
const Static: std.mem.Allocator = static_storage.allocator();
var tools: std.ArrayListUnmanaged(editor.Tool) = .{};
var tool_index: u32 = 0;
pub var large_font: wasm.Obj = undefined;
pub var med_font: wasm.Obj = undefined;
pub var small_font: wasm.Obj = undefined;
pub var level_download: wasm.Obj = undefined;
pub var registry: Registry = undefined;
export fn uploadLevel(data: wasm.Obj) void {
const mark = liu.TempMark;
defer liu.TempMark = mark;
const asset_data = wasm.in.string(data, liu.Temp) catch {
wasm.delete(data);
wasm.post(.err, "Error reading string data", .{});
return;
};
editor.readFromAsset(asset_data) catch {
wasm.post(.err, "Error reading asset data", .{});
return;
};
}
export fn download() void {
const mark = liu.TempMark;
defer liu.TempMark = mark;
const text = editor.serializeLevel() catch return;
return wasm.post(level_download, "{s}", .{text});
}
export fn setInitialTime(timestamp: f64) void {
liu.gamescreen.init(timestamp);
start_timer = Timer.init();
}
export fn run(timestamp: f64) void {
var input = liu.gamescreen.frameStart(timestamp);
defer liu.gamescreen.frameCleanup();
{
const pos = input.mouse.pos;
const world_pos = camera.screenToWorldCoordinates(pos);
input.mouse.pos = world_pos;
camera.setDims(input.screen_dims[0], input.screen_dims[1]);
}
// Wait for a bit, because otherwise the world will start running
// before its visible
if (start_timer.elapsed() < 300) return;
const delta = input.delta;
if (delta > 66) return;
const mark = liu.TempMark;
defer liu.TempMark = mark;
const wasm_mark = wasm.watermark();
defer wasm.setWatermark(wasm_mark);
// Input
{
var diff = -input.mouse.scroll_tick[1];
if (input.key(.arrow_up).pressed) diff -= 1;
if (input.key(.arrow_down).pressed) diff += 1;
const new_index = newToolIndex(diff);
if (tool_index != new_index) {
tools.items[tool_index].reset();
tool_index = new_index;
} else {
// Run the tool on the next frame, let's not get ahead of ourselves
tools.items[tool_index].frame(input);
}
}
{
var view = registry.view(struct {
move_c: *MoveC,
decide_c: DecisionC,
force_c: ForceC,
});
while (view.next()) |elem| {
const move_c = elem.move_c;
if (!elem.decide_c.player) continue;
if (input.key(.key_s).pressed) {
move_c.velocity[1] -= 8;
}
if (input.key(.key_w).pressed) {
move_c.velocity[1] += 8;
}
if (elem.force_c.is_airborne) {
if (input.key(.key_a).pressed) {
move_c.velocity[0] -= 8;
}
if (input.key(.key_d).pressed) {
move_c.velocity[0] += 8;
}
} else {
if (input.key(.key_a).down) {
move_c.velocity[0] -= 8;
move_c.velocity[0] = std.math.clamp(move_c.velocity[0], -8, 0);
}
if (input.key(.key_d).down) {
move_c.velocity[0] += 8;
move_c.velocity[0] = std.math.clamp(move_c.velocity[0], 0, 8);
}
}
}
}
// Gameplay
// Collisions
{
var view = registry.view(struct {
pos_c: *PositionC,
move_c: *MoveC,
force_c: *ForceC,
});
const StableObject = struct {
pos_c: PositionC,
force_c: ?*const ForceC,
};
var stable = registry.view(StableObject);
while (view.next()) |elem| {
const pos_c = elem.pos_c;
const move_c = elem.move_c;
// move the thing
var new_bbox = pos_c.bbox;
new_bbox.pos = pos_c.bbox.pos + move_c.velocity * @splat(2, delta / 1000);
const bbox = pos_c.bbox;
elem.force_c.is_airborne = true;
stable.reset();
while (stable.next()) |solid| {
// No force component means it doesn't interact with gravity,
// so we'll think of it as a stable piece of the environment
if (solid.force_c != null) continue;
const found = solid.pos_c.bbox;
const overlap = new_bbox.overlap(found);
if (!overlap.result) continue;
const prev_overlap = bbox.overlap(found);
if (prev_overlap.x) {
if (bbox.pos[1] < found.pos[1]) {
new_bbox.pos[1] = found.pos[1] - bbox.height;
} else {
new_bbox.pos[1] = found.pos[1] + found.height;
elem.force_c.is_airborne = false;
}
move_c.velocity[1] = 0;
}
if (prev_overlap.y) {
if (bbox.pos[0] < found.pos[0]) {
new_bbox.pos[0] = found.pos[0] - bbox.width;
} else {
new_bbox.pos[0] = found.pos[0] + found.width;
}
move_c.velocity[0] = 0;
}
}
pos_c.bbox.pos = new_bbox.pos;
// const cam_pos0 = camera.pos;
// const cam_dims = Vec2{ camera.width, camera.height };
// const cam_pos1 = cam_pos0 + cam_dims;
// const new_x = std.math.clamp(pos_c.pos[0], cam_pos0[0], cam_pos1[0] - collision_c.width);
// if (new_x != pos_c.pos[0])
// move_c.velocity[0] = 0;
// pos_c.pos[0] = new_x;
// const new_y = std.math.clamp(pos_c.pos[1], cam_pos0[1], cam_pos1[1] - collision_c.height);
// if (new_y != pos_c.pos[1])
// move_c.velocity[1] = 0;
// pos_c.pos[1] = new_y;
}
}
{
var view = registry.view(struct {
move_c: *MoveC,
force_c: ForceC,
});
while (view.next()) |elem| {
const move = elem.move_c;
const force = elem.force_c;
// apply gravity
move.velocity += force.accel * @splat(2, delta / 1000);
// applies a friction force when mario hits the ground.
if (!force.is_airborne and move.velocity[0] != 0) {
// Friction is applied in the opposite direction of velocity
// You cannot gain speed in the opposite direction from friction
const friction: f32 = force.friction * delta;
if (move.velocity[0] > 0) {
move.velocity[0] = std.math.clamp(
move.velocity[0] - friction,
0,
std.math.inf(f32),
);
} else {
move.velocity[0] = std.math.clamp(
move.velocity[0] + friction,
-std.math.inf(f32),
0,
);
}
}
}
}
// Camera Lock
{
var view = registry.view(struct {
pos_c: PositionC,
decision_c: DecisionC,
});
while (view.next()) |elem| {
if (!elem.decision_c.player) continue;
util.moveCamera(elem.pos_c.bbox.pos);
break;
}
}
// Rendering
{
var view = registry.view(struct {
pos_c: *PositionC,
render: RenderC,
});
while (view.next()) |elem| {
const pos_c = elem.pos_c;
const render = elem.render;
const color = render.color;
ext.fillStyle(color[0], color[1], color[2], color[3]);
const bbox = camera.getScreenBoundingBox(pos_c.bbox);
const rect = bbox.renderRectVector();
ext.fillRect(rect[0], rect[1], rect[2], rect[3]);
}
}
// USER INTERFACE
renderDebugInfo(input);
}
fn newToolIndex(diff: i32) u32 {
const new_tool_index = @intCast(i32, tool_index) + diff;
const len = @intCast(i32, tools.items.len);
const index = @mod(new_tool_index, len);
const new_index = @intCast(u32, index);
return new_index;
}
pub fn renderDebugInfo(input: FrameInput) void {
{
ext.strokeStyle(0.1, 0.1, 0.1, 1);
const bbox = editor.unitSquareBBoxForPos(input.mouse.pos);
const screen_rect = camera.getScreenBoundingBox(bbox).renderRectVector();
ext.strokeRect(screen_rect[0], screen_rect[1], screen_rect[2], screen_rect[3]);
}
ext.fillStyle(0.5, 0.5, 0.5, 1);
ext.setFont(large_font);
{
const fps_text = wasm.out.string("FPS:");
const fps_val = wasm.out.fixedFloatPrint(1000 / input.delta, 2);
ext.fillText(fps_text, 5, 160);
ext.fillText(fps_val, 120, 160);
}
{
const tool_name = wasm.out.string(tools.items[tool_index].name);
ext.fillText(tool_name, 500, 75);
}
ext.setFont(med_font);
{
const prev_tool = wasm.out.string(tools.items[newToolIndex(-1)].name);
const next_tool = wasm.out.string(tools.items[newToolIndex(1)].name);
ext.fillText(prev_tool, 530, 25);
ext.fillText(next_tool, 530, 110);
}
ext.setFont(small_font);
var topY: i32 = 5;
for (rows) |row| {
var leftX = row.leftX;
for (row.keys) |key| {
const color: f32 = if (input.key(key).down) 0.3 else 0.5;
ext.fillStyle(color, color, color, 1);
ext.fillRect(leftX, topY, 30, 30);
ext.fillStyle(1, 1, 1, 1);
const s = &[_]u8{key.code()};
const letter = wasm.out.string(s);
ext.fillText(letter, leftX + 15, topY + 10);
leftX += 35;
}
topY += 35;
}
} | src/routes/erlang/erlang.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
const Cup = struct {
val: usize,
cw: *Cup,
ccw: *Cup,
alloc: std.mem.Allocator,
pub fn init(alloc: std.mem.Allocator, val: usize) *Cup {
var self = alloc.create(Cup) catch unreachable;
self.val = val;
self.cw = self;
self.ccw = self;
self.alloc = alloc;
return self;
}
pub fn deinit(c: *Cup) void {
var n = c.cw;
while (n != c) : (n = n.cw) {
c.alloc.destroy(n);
}
c.alloc.destroy(c);
}
pub fn insertAfter(c: *Cup, new: *Cup) void {
var last = new.ccw;
var next = c.cw;
c.cw = new;
last.cw = next;
new.ccw = c;
next.ccw = last;
}
pub fn pick(c: *Cup) *Cup {
var p1 = c.cw;
var p3 = p1.cw.cw;
var n = p3.cw;
// fix ring
c.cw = n;
n.ccw = c;
// fix pick ring
p1.ccw = p3;
p3.cw = p1;
return p1;
}
pub fn string(c: *Cup) []const u8 {
var l: usize = 1;
var n = c.cw;
while (n != c) : (n = n.cw) {
l += 1;
}
var res = c.alloc.alloc(u8, l) catch unreachable;
res[0] = @intCast(u8, c.val) + '0';
n = c.cw;
var i: usize = 1;
while (n != c) : (n = n.cw) {
res[i] = @intCast(u8, n.val) + '0';
i += 1;
}
return res;
}
pub fn part1string(c: *Cup) []const u8 {
var l: usize = 0;
var n = c.cw;
while (n != c) : (n = n.cw) {
l += 1;
}
var res = c.alloc.alloc(u8, l) catch unreachable;
var i: usize = 0;
n = c.cw;
while (n != c) : (n = n.cw) {
res[i] = @intCast(u8, n.val) + '0';
i += 1;
}
return res;
}
};
test "cup" {
var c1 = Cup.init(aoc.halloc, 1);
try aoc.assertEq(@as(usize, 1), c1.val);
try aoc.assertEq(c1, c1.cw);
try aoc.assertEq(c1, c1.ccw);
var c2 = Cup.init(aoc.halloc, 2);
try aoc.assertEq(@as(usize, 2), c2.val);
try aoc.assertEq(c2, c2.cw);
try aoc.assertEq(c2, c2.ccw);
c1.insertAfter(c2);
try aoc.assertEq(c2, c1.cw);
try aoc.assertEq(c2, c1.ccw);
try aoc.assertEq(c1, c2.cw);
try aoc.assertEq(c1, c2.ccw);
var i: usize = 3;
var c = c2;
while (i < 10) : (i += 1) {
c.insertAfter(Cup.init(aoc.halloc, i));
c = c.cw;
}
try aoc.assertStrEq("123456789", c1.string());
try aoc.assertStrEq("23456789", c1.part1string());
try aoc.assertStrEq("67891234", c2.cw.cw.cw.part1string());
}
const Game = struct {
init: []u8,
alloc: std.mem.Allocator,
debug: bool,
pub fn init(alloc: std.mem.Allocator, in: [][]const u8) !*Game {
var self = try alloc.create(Game);
self.alloc = alloc;
self.debug = true;
var l = in[0].len;
self.init = try alloc.alloc(u8, l);
var i: usize = 0;
while (i < l) : (i += 1) {
self.init[i] = in[0][i] - '0';
}
return self;
}
pub fn deinit(g: *Game) void {
g.alloc.free(g.init);
g.alloc.destroy(g);
}
pub fn play(g: *Game, moves: usize, max: usize) *Cup {
var map = g.alloc.alloc(*Cup, max + 1) catch unreachable; // ignore 0
var cur = Cup.init(g.alloc, g.init[0]);
map[g.init[0]] = cur;
var last = cur;
var i: usize = 1;
while (i < g.init.len) : (i += 1) {
var v = g.init[i];
var n = Cup.init(g.alloc, v);
map[v] = n;
last.insertAfter(n);
last = n;
}
i = 10;
while (i <= max) : (i += 1) {
var n = Cup.init(g.alloc, i);
map[i] = n;
last.insertAfter(n);
last = n;
}
var move: usize = 1;
while (move <= moves) : (move += 1) {
var pick = cur.pick();
var dst = cur.val;
while (true) {
dst -= 1;
if (dst == 0) {
dst = max;
}
if (dst != pick.val and
dst != pick.cw.val and dst != pick.cw.cw.val)
{
break;
}
}
var dcup = map[dst];
dcup.insertAfter(pick);
cur = cur.cw;
}
return map[1];
}
pub fn part1(g: *Game, moves: usize) []const u8 {
var c1 = g.play(moves, 9);
return c1.part1string();
}
pub fn part2(g: *Game, moves: usize, max: usize) usize {
var c1 = g.play(moves, max);
return c1.cw.val * c1.cw.cw.val;
}
};
test "part1" {
const test1 = aoc.readLines(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const inp = aoc.readLines(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
var gt = try Game.init(aoc.halloc, test1);
defer gt.deinit();
try aoc.assertStrEq("25467389", gt.part1(0));
try aoc.assertStrEq("54673289", gt.part1(1));
try aoc.assertStrEq("92658374", gt.part1(10));
try aoc.assertStrEq("67384529", gt.part1(100));
var g = try Game.init(aoc.halloc, inp);
defer g.deinit();
try aoc.assertStrEq("92736584", g.part1(10));
try aoc.assertStrEq("63598274", g.part1(50));
try aoc.assertStrEq("46978532", g.part1(100));
}
test "part2" {
const test1 = aoc.readLines(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const inp = aoc.readLines(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
var gt = try Game.init(aoc.halloc, test1);
defer gt.deinit();
try aoc.assertEq(@as(usize, 136), gt.part2(30, 20));
try aoc.assertEq(@as(usize, 54), gt.part2(100, 20));
try aoc.assertEq(@as(usize, 42), gt.part2(1000, 20));
try aoc.assertEq(@as(usize, 285), gt.part2(10000, 20));
try aoc.assertEq(@as(usize, 285), gt.part2(10001, 20));
try aoc.assertEq(@as(usize, 12), gt.part2(10, 1000000));
try aoc.assertEq(@as(usize, 12), gt.part2(100, 1000000));
try aoc.assertEq(@as(usize, 126), gt.part2(1000000, 1000000));
try aoc.assertEq(@as(usize, 32999175), gt.part2(2000000, 1000000));
try aoc.assertEq(@as(usize, 149245887792), gt.part2(10000000, 1000000));
var g = try Game.init(aoc.halloc, inp);
defer g.deinit();
try aoc.assertEq(@as(usize, 163035127721), g.part2(10000000, 1000000));
}
fn day23(inp: []const u8, bench: bool) anyerror!void {
const lines = aoc.readLines(aoc.halloc, inp);
defer aoc.halloc.free(lines);
var g = try Game.init(aoc.halloc, lines);
defer g.deinit();
var p1 = g.part1(100);
var p2 = g.part2(10000000, 1000000);
if (!bench) {
try aoc.print("Part 1: {s}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day23);
} | 2020/23/aoc.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
const Diag = struct {
bits: usize,
maxbit: usize,
nums: []usize,
allocator: std.mem.Allocator,
pub fn fromInput(allocator: std.mem.Allocator, inp: anytype) !*Diag {
var nums = try allocator.alloc(usize, inp.len);
var diag = try allocator.create(Diag);
diag.bits = inp[0].len - 1;
diag.maxbit = @intCast(usize, (@as(u64, 1) << @intCast(u6, diag.bits)));
for (inp) |line, i| {
nums[i] = try std.fmt.parseUnsigned(usize, line, 2);
}
diag.nums = nums;
diag.allocator = allocator;
return diag;
}
pub fn deinit(self: *Diag) void {
self.allocator.free(self.nums);
self.allocator.destroy(self);
}
pub fn part1(self: *Diag) usize {
const total = self.nums.len;
var gamma: usize = 0;
var bit = self.maxbit;
while (bit >= 1) : (bit /= 2) {
var c: usize = 0;
for (self.nums) |n| {
if (n & bit != 0) {
c += 1;
}
}
if (c * 2 > total) {
gamma += bit;
}
}
return gamma * (2 * self.maxbit - 1 ^ gamma);
}
pub fn match(self: *Diag, val: usize, mask: usize) usize {
for (self.nums) |n| {
if (n & mask == val) {
return n;
}
}
return 0;
}
pub fn reduce(self: *Diag, most: bool) usize {
var mask: usize = 0;
var val: usize = 0;
var bit = self.maxbit;
while (bit >= 1) : (bit /= 2) {
var c: usize = 0;
var total: usize = 0;
for (self.nums) |n| {
if (n & mask != val) {
continue;
}
total += 1;
if (n & bit != 0) {
c += 1;
}
}
if (total == 1) {
return self.match(val, mask);
}
if ((c * 2 >= total) == most) {
val += bit;
}
mask += bit;
}
return val;
}
pub fn part2(self: *Diag) usize {
return self.reduce(true) * self.reduce(false);
}
};
test "examples" {
const test1 = aoc.readLines(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const inp = aoc.readLines(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
var t = Diag.fromInput(aoc.talloc, test1) catch unreachable;
defer t.deinit();
var ti = Diag.fromInput(aoc.talloc, inp) catch unreachable;
defer ti.deinit();
try aoc.assertEq(@as(usize, 198), t.part1());
try aoc.assertEq(@as(usize, 749376), ti.part1());
try aoc.assertEq(@as(usize, 230), t.part2());
try aoc.assertEq(@as(usize, 2372923), ti.part2());
}
fn day03(inp: []const u8, bench: bool) anyerror!void {
var lines = aoc.readLines(aoc.halloc, inp);
defer aoc.halloc.free(lines);
var diag = try Diag.fromInput(aoc.halloc, lines);
defer diag.deinit();
var p1 = diag.part1();
var p2 = diag.part2();
if (!bench) {
try aoc.print("Part1: {}\nPart2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day03);
} | 2021/03/aoc.zig |
const Allocator = std.mem.Allocator;
const File = std.fs.File;
const FormatInterface = @import("../format_interface.zig").FormatInterface;
const ImageFormat = image.ImageFormat;
const ImageReader = image.ImageReader;
const ImageInfo = image.ImageInfo;
const ImageSeekStream = image.ImageSeekStream;
const PixelFormat = @import("../pixel_format.zig").PixelFormat;
const color = @import("../color.zig");
const errors = @import("../errors.zig");
const fs = std.fs;
const image = @import("../image.zig");
const io = std.io;
const mem = std.mem;
const path = std.fs.path;
const std = @import("std");
usingnamespace @import("../utils.zig");
const BitmapMagicHeader = [_]u8{ 'B', 'M' };
pub const BitmapFileHeader = packed struct {
magicHeader: [2]u8,
size: u32,
reserved: u32,
pixelOffset: u32,
};
pub const CompressionMethod = enum(u32) {
None = 0,
Rle8 = 1,
Rle4 = 2,
Bitfields = 3,
Jpeg = 4,
Png = 5,
AlphaBitFields = 6,
Cmyk = 11,
CmykRle8 = 12,
CmykRle4 = 13,
};
pub const BitmapColorSpace = enum(u32) {
CalibratedRgb = 0,
sRgb = toMagicNumberBig("sRGB"),
WindowsColorSpace = toMagicNumberBig("Win "),
ProfileLinked = toMagicNumberBig("LINK"),
ProfileEmbedded = toMagicNumberBig("MBED"),
};
pub const BitmapIntent = enum(u32) {
Business = 1,
Graphics = 2,
Images = 4,
AbsoluteColorimetric = 8,
};
pub const CieXyz = packed struct {
x: u32 = 0, // TODO: Use FXPT2DOT30
y: u32 = 0,
z: u32 = 0,
};
pub const CieXyzTriple = packed struct {
red: CieXyz = CieXyz{},
green: CieXyz = CieXyz{},
blue: CieXyz = CieXyz{},
};
pub const BitmapInfoHeaderWindows31 = packed struct {
headerSize: u32 = 0,
width: i32 = 0,
height: i32 = 0,
colorPlane: u16 = 0,
bitCount: u16 = 0,
compressionMethod: CompressionMethod = CompressionMethod.None,
imageRawSize: u32 = 0,
horizontalResolution: u32 = 0,
verticalResolution: u32 = 0,
paletteSize: u32 = 0,
importantColors: u32 = 0,
pub const HeaderSize = @sizeOf(@This());
};
pub const BitmapInfoHeaderV4 = packed struct {
headerSize: u32 = 0,
width: i32 = 0,
height: i32 = 0,
colorPlane: u16 = 0,
bitCount: u16 = 0,
compressionMethod: CompressionMethod = CompressionMethod.None,
imageRawSize: u32 = 0,
horizontalResolution: u32 = 0,
verticalResolution: u32 = 0,
paletteSize: u32 = 0,
importantColors: u32 = 0,
redMask: u32 = 0,
greenMask: u32 = 0,
blueMask: u32 = 0,
alphaMask: u32 = 0,
colorSpace: BitmapColorSpace = BitmapColorSpace.sRgb,
cieEndPoints: CieXyzTriple = CieXyzTriple{},
gammaRed: u32 = 0,
gammaGreen: u32 = 0,
gammaBlue: u32 = 0,
pub const HeaderSize = @sizeOf(@This());
};
pub const BitmapInfoHeaderV5 = packed struct {
headerSize: u32 = 0,
width: i32 = 0,
height: i32 = 0,
colorPlane: u16 = 0,
bitCount: u16 = 0,
compressionMethod: CompressionMethod = CompressionMethod.None,
imageRawSize: u32 = 0,
horizontalResolution: u32 = 0,
verticalResolution: u32 = 0,
paletteSize: u32 = 0,
importantColors: u32 = 0,
redMask: u32 = 0,
greenMask: u32 = 0,
blueMask: u32 = 0,
alphaMask: u32 = 0,
colorSpace: BitmapColorSpace = BitmapColorSpace.sRgb,
cieEndPoints: CieXyzTriple = CieXyzTriple{},
gammaRed: u32 = 0,
gammaGreen: u32 = 0,
gammaBlue: u32 = 0,
intent: BitmapIntent = BitmapIntent.Graphics,
profileData: u32 = 0,
profileSize: u32 = 0,
reserved: u32 = 0,
pub const HeaderSize = @sizeOf(@This());
};
pub const BitmapInfoHeader = union(enum) {
Windows31: BitmapInfoHeaderWindows31,
V4: BitmapInfoHeaderV4,
V5: BitmapInfoHeaderV5,
};
pub const Bitmap = struct {
fileHeader: BitmapFileHeader = undefined,
infoHeader: BitmapInfoHeader = undefined,
pixel_format: PixelFormat = undefined,
const Self = @This();
pub fn formatInterface() FormatInterface {
return FormatInterface{
.format = @ptrCast(FormatInterface.FormatFn, format),
.formatDetect = @ptrCast(FormatInterface.FormatDetectFn, formatDetect),
.readForImage = @ptrCast(FormatInterface.ReadForImageFn, readForImage),
.writeForImage = @ptrCast(FormatInterface.WriteForImageFn, writeForImage),
};
}
pub fn format() ImageFormat {
return ImageFormat.Bmp;
}
pub fn formatDetect(reader: ImageReader, seekStream: ImageSeekStream) !bool {
var magicNumberBuffer: [2]u8 = undefined;
_ = try reader.read(magicNumberBuffer[0..]);
if (std.mem.eql(u8, magicNumberBuffer[0..], BitmapMagicHeader[0..])) {
return true;
}
return false;
}
pub fn readForImage(allocator: *Allocator, reader: ImageReader, seekStream: ImageSeekStream, pixels: *?color.ColorStorage) !ImageInfo {
var bmp = Self{};
try bmp.read(allocator, reader, seekStream, pixels);
var imageInfo = ImageInfo{};
imageInfo.width = @intCast(usize, bmp.width());
imageInfo.height = @intCast(usize, bmp.height());
imageInfo.pixel_format = bmp.pixel_format;
return imageInfo;
}
pub fn writeForImage(allocator: *Allocator, write_stream: image.ImageWriterStream, seek_stream: ImageSeekStream, pixels: color.ColorStorage, save_info: image.ImageSaveInfo) !void {}
pub fn width(self: Self) i32 {
return switch (self.infoHeader) {
.Windows31 => |win31| {
return win31.width;
},
.V4 => |v4Header| {
return v4Header.width;
},
.V5 => |v5Header| {
return v5Header.width;
},
};
}
pub fn height(self: Self) i32 {
return switch (self.infoHeader) {
.Windows31 => |win31| {
return win31.height;
},
.V4 => |v4Header| {
return v4Header.height;
},
.V5 => |v5Header| {
return v5Header.height;
},
};
}
pub fn read(self: *Self, allocator: *Allocator, reader: ImageReader, seekStream: ImageSeekStream, pixelsOpt: *?color.ColorStorage) !void {
// Read file header
self.fileHeader = try readStructLittle(reader, BitmapFileHeader);
if (!mem.eql(u8, self.fileHeader.magicHeader[0..], BitmapMagicHeader[0..])) {
return errors.ImageError.InvalidMagicHeader;
}
// Read header size to figure out the header type, also TODO: Use PeekableStream when I understand how to use it
const currentHeaderPos = try seekStream.getPos();
var headerSize = try reader.readIntLittle(u32);
try seekStream.seekTo(currentHeaderPos);
// Read info header
self.infoHeader = switch (headerSize) {
BitmapInfoHeaderWindows31.HeaderSize => BitmapInfoHeader{ .Windows31 = try readStructLittle(reader, BitmapInfoHeaderWindows31) },
BitmapInfoHeaderV4.HeaderSize => BitmapInfoHeader{ .V4 = try readStructLittle(reader, BitmapInfoHeaderV4) },
BitmapInfoHeaderV5.HeaderSize => BitmapInfoHeader{ .V5 = try readStructLittle(reader, BitmapInfoHeaderV5) },
else => return errors.ImageError.UnsupportedBitmapType,
};
// Read pixel data
_ = switch (self.infoHeader) {
.V4 => |v4Header| {
const pixelWidth = v4Header.width;
const pixelHeight = v4Header.height;
self.pixel_format = try getPixelFormat(v4Header.bitCount, v4Header.compressionMethod);
pixelsOpt.* = try color.ColorStorage.init(allocator, self.pixel_format, @intCast(usize, pixelWidth * pixelHeight));
if (pixelsOpt.*) |*pixels| {
try readPixels(reader, pixelWidth, pixelHeight, self.pixel_format, pixels);
}
},
.V5 => |v5Header| {
const pixelWidth = v5Header.width;
const pixelHeight = v5Header.height;
self.pixel_format = try getPixelFormat(v5Header.bitCount, v5Header.compressionMethod);
pixelsOpt.* = try color.ColorStorage.init(allocator, self.pixel_format, @intCast(usize, pixelWidth * pixelHeight));
if (pixelsOpt.*) |*pixels| {
try readPixels(reader, pixelWidth, pixelHeight, self.pixel_format, pixels);
}
},
else => return errors.ImageError.UnsupportedBitmapType,
};
}
fn getPixelFormat(bitCount: u32, compression: CompressionMethod) !PixelFormat {
if (bitCount == 32 and compression == CompressionMethod.Bitfields) {
return PixelFormat.Argb32;
} else if (bitCount == 24 and compression == CompressionMethod.None) {
return PixelFormat.Rgb24;
} else {
return errors.ImageError.UnsupportedPixelFormat;
}
}
fn readPixels(reader: ImageReader, pixelWidth: i32, pixelHeight: i32, pixelFormat: PixelFormat, pixels: *color.ColorStorage) !void {
return switch (pixelFormat) {
PixelFormat.Rgb24 => {
return readPixelsInternal(pixels.Rgb24, reader, pixelWidth, pixelHeight);
},
PixelFormat.Argb32 => {
return readPixelsInternal(pixels.Argb32, reader, pixelWidth, pixelHeight);
},
else => {
return errors.ImageError.UnsupportedPixelFormat;
},
};
}
fn readPixelsInternal(pixels: anytype, reader: ImageReader, pixelWidth: i32, pixelHeight: i32) !void {
const ColorBufferType = @typeInfo(@TypeOf(pixels)).Pointer.child;
var x: i32 = 0;
var y: i32 = pixelHeight - 1;
while (y >= 0) : (y -= 1) {
const scanline = y * pixelWidth;
x = 0;
while (x < pixelWidth) : (x += 1) {
pixels[@intCast(usize, scanline + x)] = try readStructLittle(reader, ColorBufferType);
}
}
}
}; | src/formats/bmp.zig |
const std = @import("std");
const mem = std.mem;
const UppercaseLetter = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 65,
hi: u21 = 125217,
pub fn init(allocator: *mem.Allocator) !UppercaseLetter {
var instance = UppercaseLetter{
.allocator = allocator,
.array = try allocator.alloc(bool, 125153),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
index = 0;
while (index <= 25) : (index += 1) {
instance.array[index] = true;
}
index = 127;
while (index <= 149) : (index += 1) {
instance.array[index] = true;
}
index = 151;
while (index <= 157) : (index += 1) {
instance.array[index] = true;
}
instance.array[191] = true;
instance.array[193] = true;
instance.array[195] = true;
instance.array[197] = true;
instance.array[199] = true;
instance.array[201] = true;
instance.array[203] = true;
instance.array[205] = true;
instance.array[207] = true;
instance.array[209] = true;
instance.array[211] = true;
instance.array[213] = true;
instance.array[215] = true;
instance.array[217] = true;
instance.array[219] = true;
instance.array[221] = true;
instance.array[223] = true;
instance.array[225] = true;
instance.array[227] = true;
instance.array[229] = true;
instance.array[231] = true;
instance.array[233] = true;
instance.array[235] = true;
instance.array[237] = true;
instance.array[239] = true;
instance.array[241] = true;
instance.array[243] = true;
instance.array[245] = true;
instance.array[248] = true;
instance.array[250] = true;
instance.array[252] = true;
instance.array[254] = true;
instance.array[256] = true;
instance.array[258] = true;
instance.array[260] = true;
instance.array[262] = true;
instance.array[265] = true;
instance.array[267] = true;
instance.array[269] = true;
instance.array[271] = true;
instance.array[273] = true;
instance.array[275] = true;
instance.array[277] = true;
instance.array[279] = true;
instance.array[281] = true;
instance.array[283] = true;
instance.array[285] = true;
instance.array[287] = true;
instance.array[289] = true;
instance.array[291] = true;
instance.array[293] = true;
instance.array[295] = true;
instance.array[297] = true;
instance.array[299] = true;
instance.array[301] = true;
instance.array[303] = true;
instance.array[305] = true;
instance.array[307] = true;
instance.array[309] = true;
index = 311;
while (index <= 312) : (index += 1) {
instance.array[index] = true;
}
instance.array[314] = true;
instance.array[316] = true;
index = 320;
while (index <= 321) : (index += 1) {
instance.array[index] = true;
}
instance.array[323] = true;
index = 325;
while (index <= 326) : (index += 1) {
instance.array[index] = true;
}
index = 328;
while (index <= 330) : (index += 1) {
instance.array[index] = true;
}
index = 333;
while (index <= 336) : (index += 1) {
instance.array[index] = true;
}
index = 338;
while (index <= 339) : (index += 1) {
instance.array[index] = true;
}
index = 341;
while (index <= 343) : (index += 1) {
instance.array[index] = true;
}
index = 347;
while (index <= 348) : (index += 1) {
instance.array[index] = true;
}
index = 350;
while (index <= 351) : (index += 1) {
instance.array[index] = true;
}
instance.array[353] = true;
instance.array[355] = true;
index = 357;
while (index <= 358) : (index += 1) {
instance.array[index] = true;
}
instance.array[360] = true;
instance.array[363] = true;
index = 365;
while (index <= 366) : (index += 1) {
instance.array[index] = true;
}
index = 368;
while (index <= 370) : (index += 1) {
instance.array[index] = true;
}
instance.array[372] = true;
index = 374;
while (index <= 375) : (index += 1) {
instance.array[index] = true;
}
instance.array[379] = true;
instance.array[387] = true;
instance.array[390] = true;
instance.array[393] = true;
instance.array[396] = true;
instance.array[398] = true;
instance.array[400] = true;
instance.array[402] = true;
instance.array[404] = true;
instance.array[406] = true;
instance.array[408] = true;
instance.array[410] = true;
instance.array[413] = true;
instance.array[415] = true;
instance.array[417] = true;
instance.array[419] = true;
instance.array[421] = true;
instance.array[423] = true;
instance.array[425] = true;
instance.array[427] = true;
instance.array[429] = true;
instance.array[432] = true;
instance.array[435] = true;
index = 437;
while (index <= 439) : (index += 1) {
instance.array[index] = true;
}
instance.array[441] = true;
instance.array[443] = true;
instance.array[445] = true;
instance.array[447] = true;
instance.array[449] = true;
instance.array[451] = true;
instance.array[453] = true;
instance.array[455] = true;
instance.array[457] = true;
instance.array[459] = true;
instance.array[461] = true;
instance.array[463] = true;
instance.array[465] = true;
instance.array[467] = true;
instance.array[469] = true;
instance.array[471] = true;
instance.array[473] = true;
instance.array[475] = true;
instance.array[477] = true;
instance.array[479] = true;
instance.array[481] = true;
instance.array[483] = true;
instance.array[485] = true;
instance.array[487] = true;
instance.array[489] = true;
instance.array[491] = true;
instance.array[493] = true;
instance.array[495] = true;
instance.array[497] = true;
index = 505;
while (index <= 506) : (index += 1) {
instance.array[index] = true;
}
index = 508;
while (index <= 509) : (index += 1) {
instance.array[index] = true;
}
instance.array[512] = true;
index = 514;
while (index <= 517) : (index += 1) {
instance.array[index] = true;
}
instance.array[519] = true;
instance.array[521] = true;
instance.array[523] = true;
instance.array[525] = true;
instance.array[815] = true;
instance.array[817] = true;
instance.array[821] = true;
instance.array[830] = true;
instance.array[837] = true;
index = 839;
while (index <= 841) : (index += 1) {
instance.array[index] = true;
}
instance.array[843] = true;
index = 845;
while (index <= 846) : (index += 1) {
instance.array[index] = true;
}
index = 848;
while (index <= 864) : (index += 1) {
instance.array[index] = true;
}
index = 866;
while (index <= 874) : (index += 1) {
instance.array[index] = true;
}
instance.array[910] = true;
index = 913;
while (index <= 915) : (index += 1) {
instance.array[index] = true;
}
instance.array[919] = true;
instance.array[921] = true;
instance.array[923] = true;
instance.array[925] = true;
instance.array[927] = true;
instance.array[929] = true;
instance.array[931] = true;
instance.array[933] = true;
instance.array[935] = true;
instance.array[937] = true;
instance.array[939] = true;
instance.array[941] = true;
instance.array[947] = true;
instance.array[950] = true;
index = 952;
while (index <= 953) : (index += 1) {
instance.array[index] = true;
}
index = 956;
while (index <= 1006) : (index += 1) {
instance.array[index] = true;
}
instance.array[1055] = true;
instance.array[1057] = true;
instance.array[1059] = true;
instance.array[1061] = true;
instance.array[1063] = true;
instance.array[1065] = true;
instance.array[1067] = true;
instance.array[1069] = true;
instance.array[1071] = true;
instance.array[1073] = true;
instance.array[1075] = true;
instance.array[1077] = true;
instance.array[1079] = true;
instance.array[1081] = true;
instance.array[1083] = true;
instance.array[1085] = true;
instance.array[1087] = true;
instance.array[1097] = true;
instance.array[1099] = true;
instance.array[1101] = true;
instance.array[1103] = true;
instance.array[1105] = true;
instance.array[1107] = true;
instance.array[1109] = true;
instance.array[1111] = true;
instance.array[1113] = true;
instance.array[1115] = true;
instance.array[1117] = true;
instance.array[1119] = true;
instance.array[1121] = true;
instance.array[1123] = true;
instance.array[1125] = true;
instance.array[1127] = true;
instance.array[1129] = true;
instance.array[1131] = true;
instance.array[1133] = true;
instance.array[1135] = true;
instance.array[1137] = true;
instance.array[1139] = true;
instance.array[1141] = true;
instance.array[1143] = true;
instance.array[1145] = true;
instance.array[1147] = true;
instance.array[1149] = true;
index = 1151;
while (index <= 1152) : (index += 1) {
instance.array[index] = true;
}
instance.array[1154] = true;
instance.array[1156] = true;
instance.array[1158] = true;
instance.array[1160] = true;
instance.array[1162] = true;
instance.array[1164] = true;
instance.array[1167] = true;
instance.array[1169] = true;
instance.array[1171] = true;
instance.array[1173] = true;
instance.array[1175] = true;
instance.array[1177] = true;
instance.array[1179] = true;
instance.array[1181] = true;
instance.array[1183] = true;
instance.array[1185] = true;
instance.array[1187] = true;
instance.array[1189] = true;
instance.array[1191] = true;
instance.array[1193] = true;
instance.array[1195] = true;
instance.array[1197] = true;
instance.array[1199] = true;
instance.array[1201] = true;
instance.array[1203] = true;
instance.array[1205] = true;
instance.array[1207] = true;
instance.array[1209] = true;
instance.array[1211] = true;
instance.array[1213] = true;
instance.array[1215] = true;
instance.array[1217] = true;
instance.array[1219] = true;
instance.array[1221] = true;
instance.array[1223] = true;
instance.array[1225] = true;
instance.array[1227] = true;
instance.array[1229] = true;
instance.array[1231] = true;
instance.array[1233] = true;
instance.array[1235] = true;
instance.array[1237] = true;
instance.array[1239] = true;
instance.array[1241] = true;
instance.array[1243] = true;
instance.array[1245] = true;
instance.array[1247] = true;
instance.array[1249] = true;
instance.array[1251] = true;
instance.array[1253] = true;
instance.array[1255] = true;
instance.array[1257] = true;
instance.array[1259] = true;
instance.array[1261] = true;
index = 1264;
while (index <= 1301) : (index += 1) {
instance.array[index] = true;
}
index = 4191;
while (index <= 4228) : (index += 1) {
instance.array[index] = true;
}
instance.array[4230] = true;
instance.array[4236] = true;
index = 4959;
while (index <= 5044) : (index += 1) {
instance.array[index] = true;
}
index = 7247;
while (index <= 7289) : (index += 1) {
instance.array[index] = true;
}
index = 7292;
while (index <= 7294) : (index += 1) {
instance.array[index] = true;
}
instance.array[7615] = true;
instance.array[7617] = true;
instance.array[7619] = true;
instance.array[7621] = true;
instance.array[7623] = true;
instance.array[7625] = true;
instance.array[7627] = true;
instance.array[7629] = true;
instance.array[7631] = true;
instance.array[7633] = true;
instance.array[7635] = true;
instance.array[7637] = true;
instance.array[7639] = true;
instance.array[7641] = true;
instance.array[7643] = true;
instance.array[7645] = true;
instance.array[7647] = true;
instance.array[7649] = true;
instance.array[7651] = true;
instance.array[7653] = true;
instance.array[7655] = true;
instance.array[7657] = true;
instance.array[7659] = true;
instance.array[7661] = true;
instance.array[7663] = true;
instance.array[7665] = true;
instance.array[7667] = true;
instance.array[7669] = true;
instance.array[7671] = true;
instance.array[7673] = true;
instance.array[7675] = true;
instance.array[7677] = true;
instance.array[7679] = true;
instance.array[7681] = true;
instance.array[7683] = true;
instance.array[7685] = true;
instance.array[7687] = true;
instance.array[7689] = true;
instance.array[7691] = true;
instance.array[7693] = true;
instance.array[7695] = true;
instance.array[7697] = true;
instance.array[7699] = true;
instance.array[7701] = true;
instance.array[7703] = true;
instance.array[7705] = true;
instance.array[7707] = true;
instance.array[7709] = true;
instance.array[7711] = true;
instance.array[7713] = true;
instance.array[7715] = true;
instance.array[7717] = true;
instance.array[7719] = true;
instance.array[7721] = true;
instance.array[7723] = true;
instance.array[7725] = true;
instance.array[7727] = true;
instance.array[7729] = true;
instance.array[7731] = true;
instance.array[7733] = true;
instance.array[7735] = true;
instance.array[7737] = true;
instance.array[7739] = true;
instance.array[7741] = true;
instance.array[7743] = true;
instance.array[7745] = true;
instance.array[7747] = true;
instance.array[7749] = true;
instance.array[7751] = true;
instance.array[7753] = true;
instance.array[7755] = true;
instance.array[7757] = true;
instance.array[7759] = true;
instance.array[7761] = true;
instance.array[7763] = true;
instance.array[7773] = true;
instance.array[7775] = true;
instance.array[7777] = true;
instance.array[7779] = true;
instance.array[7781] = true;
instance.array[7783] = true;
instance.array[7785] = true;
instance.array[7787] = true;
instance.array[7789] = true;
instance.array[7791] = true;
instance.array[7793] = true;
instance.array[7795] = true;
instance.array[7797] = true;
instance.array[7799] = true;
instance.array[7801] = true;
instance.array[7803] = true;
instance.array[7805] = true;
instance.array[7807] = true;
instance.array[7809] = true;
instance.array[7811] = true;
instance.array[7813] = true;
instance.array[7815] = true;
instance.array[7817] = true;
instance.array[7819] = true;
instance.array[7821] = true;
instance.array[7823] = true;
instance.array[7825] = true;
instance.array[7827] = true;
instance.array[7829] = true;
instance.array[7831] = true;
instance.array[7833] = true;
instance.array[7835] = true;
instance.array[7837] = true;
instance.array[7839] = true;
instance.array[7841] = true;
instance.array[7843] = true;
instance.array[7845] = true;
instance.array[7847] = true;
instance.array[7849] = true;
instance.array[7851] = true;
instance.array[7853] = true;
instance.array[7855] = true;
instance.array[7857] = true;
instance.array[7859] = true;
instance.array[7861] = true;
instance.array[7863] = true;
instance.array[7865] = true;
instance.array[7867] = true;
instance.array[7869] = true;
index = 7879;
while (index <= 7886) : (index += 1) {
instance.array[index] = true;
}
index = 7895;
while (index <= 7900) : (index += 1) {
instance.array[index] = true;
}
index = 7911;
while (index <= 7918) : (index += 1) {
instance.array[index] = true;
}
index = 7927;
while (index <= 7934) : (index += 1) {
instance.array[index] = true;
}
index = 7943;
while (index <= 7948) : (index += 1) {
instance.array[index] = true;
}
instance.array[7960] = true;
instance.array[7962] = true;
instance.array[7964] = true;
instance.array[7966] = true;
index = 7975;
while (index <= 7982) : (index += 1) {
instance.array[index] = true;
}
index = 8055;
while (index <= 8058) : (index += 1) {
instance.array[index] = true;
}
index = 8071;
while (index <= 8074) : (index += 1) {
instance.array[index] = true;
}
index = 8087;
while (index <= 8090) : (index += 1) {
instance.array[index] = true;
}
index = 8103;
while (index <= 8107) : (index += 1) {
instance.array[index] = true;
}
index = 8119;
while (index <= 8122) : (index += 1) {
instance.array[index] = true;
}
instance.array[8385] = true;
instance.array[8390] = true;
index = 8394;
while (index <= 8396) : (index += 1) {
instance.array[index] = true;
}
index = 8399;
while (index <= 8401) : (index += 1) {
instance.array[index] = true;
}
instance.array[8404] = true;
index = 8408;
while (index <= 8412) : (index += 1) {
instance.array[index] = true;
}
instance.array[8419] = true;
instance.array[8421] = true;
instance.array[8423] = true;
index = 8425;
while (index <= 8428) : (index += 1) {
instance.array[index] = true;
}
index = 8431;
while (index <= 8434) : (index += 1) {
instance.array[index] = true;
}
index = 8445;
while (index <= 8446) : (index += 1) {
instance.array[index] = true;
}
instance.array[8452] = true;
instance.array[8514] = true;
index = 11199;
while (index <= 11245) : (index += 1) {
instance.array[index] = true;
}
instance.array[11295] = true;
index = 11297;
while (index <= 11299) : (index += 1) {
instance.array[index] = true;
}
instance.array[11302] = true;
instance.array[11304] = true;
instance.array[11306] = true;
index = 11308;
while (index <= 11311) : (index += 1) {
instance.array[index] = true;
}
instance.array[11313] = true;
instance.array[11316] = true;
index = 11325;
while (index <= 11327) : (index += 1) {
instance.array[index] = true;
}
instance.array[11329] = true;
instance.array[11331] = true;
instance.array[11333] = true;
instance.array[11335] = true;
instance.array[11337] = true;
instance.array[11339] = true;
instance.array[11341] = true;
instance.array[11343] = true;
instance.array[11345] = true;
instance.array[11347] = true;
instance.array[11349] = true;
instance.array[11351] = true;
instance.array[11353] = true;
instance.array[11355] = true;
instance.array[11357] = true;
instance.array[11359] = true;
instance.array[11361] = true;
instance.array[11363] = true;
instance.array[11365] = true;
instance.array[11367] = true;
instance.array[11369] = true;
instance.array[11371] = true;
instance.array[11373] = true;
instance.array[11375] = true;
instance.array[11377] = true;
instance.array[11379] = true;
instance.array[11381] = true;
instance.array[11383] = true;
instance.array[11385] = true;
instance.array[11387] = true;
instance.array[11389] = true;
instance.array[11391] = true;
instance.array[11393] = true;
instance.array[11395] = true;
instance.array[11397] = true;
instance.array[11399] = true;
instance.array[11401] = true;
instance.array[11403] = true;
instance.array[11405] = true;
instance.array[11407] = true;
instance.array[11409] = true;
instance.array[11411] = true;
instance.array[11413] = true;
instance.array[11415] = true;
instance.array[11417] = true;
instance.array[11419] = true;
instance.array[11421] = true;
instance.array[11423] = true;
instance.array[11425] = true;
instance.array[11434] = true;
instance.array[11436] = true;
instance.array[11441] = true;
instance.array[42495] = true;
instance.array[42497] = true;
instance.array[42499] = true;
instance.array[42501] = true;
instance.array[42503] = true;
instance.array[42505] = true;
instance.array[42507] = true;
instance.array[42509] = true;
instance.array[42511] = true;
instance.array[42513] = true;
instance.array[42515] = true;
instance.array[42517] = true;
instance.array[42519] = true;
instance.array[42521] = true;
instance.array[42523] = true;
instance.array[42525] = true;
instance.array[42527] = true;
instance.array[42529] = true;
instance.array[42531] = true;
instance.array[42533] = true;
instance.array[42535] = true;
instance.array[42537] = true;
instance.array[42539] = true;
instance.array[42559] = true;
instance.array[42561] = true;
instance.array[42563] = true;
instance.array[42565] = true;
instance.array[42567] = true;
instance.array[42569] = true;
instance.array[42571] = true;
instance.array[42573] = true;
instance.array[42575] = true;
instance.array[42577] = true;
instance.array[42579] = true;
instance.array[42581] = true;
instance.array[42583] = true;
instance.array[42585] = true;
instance.array[42721] = true;
instance.array[42723] = true;
instance.array[42725] = true;
instance.array[42727] = true;
instance.array[42729] = true;
instance.array[42731] = true;
instance.array[42733] = true;
instance.array[42737] = true;
instance.array[42739] = true;
instance.array[42741] = true;
instance.array[42743] = true;
instance.array[42745] = true;
instance.array[42747] = true;
instance.array[42749] = true;
instance.array[42751] = true;
instance.array[42753] = true;
instance.array[42755] = true;
instance.array[42757] = true;
instance.array[42759] = true;
instance.array[42761] = true;
instance.array[42763] = true;
instance.array[42765] = true;
instance.array[42767] = true;
instance.array[42769] = true;
instance.array[42771] = true;
instance.array[42773] = true;
instance.array[42775] = true;
instance.array[42777] = true;
instance.array[42779] = true;
instance.array[42781] = true;
instance.array[42783] = true;
instance.array[42785] = true;
instance.array[42787] = true;
instance.array[42789] = true;
instance.array[42791] = true;
instance.array[42793] = true;
instance.array[42795] = true;
instance.array[42797] = true;
instance.array[42808] = true;
instance.array[42810] = true;
index = 42812;
while (index <= 42813) : (index += 1) {
instance.array[index] = true;
}
instance.array[42815] = true;
instance.array[42817] = true;
instance.array[42819] = true;
instance.array[42821] = true;
instance.array[42826] = true;
instance.array[42828] = true;
instance.array[42831] = true;
instance.array[42833] = true;
instance.array[42837] = true;
instance.array[42839] = true;
instance.array[42841] = true;
instance.array[42843] = true;
instance.array[42845] = true;
instance.array[42847] = true;
instance.array[42849] = true;
instance.array[42851] = true;
instance.array[42853] = true;
instance.array[42855] = true;
index = 42857;
while (index <= 42861) : (index += 1) {
instance.array[index] = true;
}
index = 42863;
while (index <= 42867) : (index += 1) {
instance.array[index] = true;
}
instance.array[42869] = true;
instance.array[42871] = true;
instance.array[42873] = true;
instance.array[42875] = true;
instance.array[42877] = true;
instance.array[42881] = true;
index = 42883;
while (index <= 42886) : (index += 1) {
instance.array[index] = true;
}
instance.array[42888] = true;
instance.array[42932] = true;
index = 65248;
while (index <= 65273) : (index += 1) {
instance.array[index] = true;
}
index = 66495;
while (index <= 66534) : (index += 1) {
instance.array[index] = true;
}
index = 66671;
while (index <= 66706) : (index += 1) {
instance.array[index] = true;
}
index = 68671;
while (index <= 68721) : (index += 1) {
instance.array[index] = true;
}
index = 71775;
while (index <= 71806) : (index += 1) {
instance.array[index] = true;
}
index = 93695;
while (index <= 93726) : (index += 1) {
instance.array[index] = true;
}
index = 119743;
while (index <= 119768) : (index += 1) {
instance.array[index] = true;
}
index = 119795;
while (index <= 119820) : (index += 1) {
instance.array[index] = true;
}
index = 119847;
while (index <= 119872) : (index += 1) {
instance.array[index] = true;
}
instance.array[119899] = true;
index = 119901;
while (index <= 119902) : (index += 1) {
instance.array[index] = true;
}
instance.array[119905] = true;
index = 119908;
while (index <= 119909) : (index += 1) {
instance.array[index] = true;
}
index = 119912;
while (index <= 119915) : (index += 1) {
instance.array[index] = true;
}
index = 119917;
while (index <= 119924) : (index += 1) {
instance.array[index] = true;
}
index = 119951;
while (index <= 119976) : (index += 1) {
instance.array[index] = true;
}
index = 120003;
while (index <= 120004) : (index += 1) {
instance.array[index] = true;
}
index = 120006;
while (index <= 120009) : (index += 1) {
instance.array[index] = true;
}
index = 120012;
while (index <= 120019) : (index += 1) {
instance.array[index] = true;
}
index = 120021;
while (index <= 120027) : (index += 1) {
instance.array[index] = true;
}
index = 120055;
while (index <= 120056) : (index += 1) {
instance.array[index] = true;
}
index = 120058;
while (index <= 120061) : (index += 1) {
instance.array[index] = true;
}
index = 120063;
while (index <= 120067) : (index += 1) {
instance.array[index] = true;
}
instance.array[120069] = true;
index = 120073;
while (index <= 120079) : (index += 1) {
instance.array[index] = true;
}
index = 120107;
while (index <= 120132) : (index += 1) {
instance.array[index] = true;
}
index = 120159;
while (index <= 120184) : (index += 1) {
instance.array[index] = true;
}
index = 120211;
while (index <= 120236) : (index += 1) {
instance.array[index] = true;
}
index = 120263;
while (index <= 120288) : (index += 1) {
instance.array[index] = true;
}
index = 120315;
while (index <= 120340) : (index += 1) {
instance.array[index] = true;
}
index = 120367;
while (index <= 120392) : (index += 1) {
instance.array[index] = true;
}
index = 120423;
while (index <= 120447) : (index += 1) {
instance.array[index] = true;
}
index = 120481;
while (index <= 120505) : (index += 1) {
instance.array[index] = true;
}
index = 120539;
while (index <= 120563) : (index += 1) {
instance.array[index] = true;
}
index = 120597;
while (index <= 120621) : (index += 1) {
instance.array[index] = true;
}
index = 120655;
while (index <= 120679) : (index += 1) {
instance.array[index] = true;
}
instance.array[120713] = true;
index = 125119;
while (index <= 125152) : (index += 1) {
instance.array[index] = true;
}
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *UppercaseLetter) void {
self.allocator.free(self.array);
}
// isUppercaseLetter checks if cp is of the kind Uppercase_Letter.
pub fn isUppercaseLetter(self: UppercaseLetter, cp: u21) bool {
if (cp < self.lo or cp > self.hi) return false;
const index = cp - self.lo;
return if (index >= self.array.len) false else self.array[index];
} | src/components/autogen/DerivedGeneralCategory/UppercaseLetter.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const Target = std.Target;
const log = std.log.scoped(.codegen);
const spec = @import("spirv/spec.zig");
const Opcode = spec.Opcode;
const Module = @import("../Module.zig");
const Decl = Module.Decl;
const Type = @import("../type.zig").Type;
const Value = @import("../value.zig").Value;
const LazySrcLoc = Module.LazySrcLoc;
const ir = @import("../air.zig");
const Inst = ir.Inst;
pub const Word = u32;
pub const ResultId = u32;
pub const TypeMap = std.HashMap(Type, ResultId, Type.hash, Type.eql, std.hash_map.default_max_load_percentage);
pub const InstMap = std.AutoHashMap(*Inst, ResultId);
const IncomingBlock = struct {
src_label_id: ResultId,
break_value_id: ResultId,
};
pub const BlockMap = std.AutoHashMap(*Inst.Block, struct {
label_id: ResultId,
incoming_blocks: *std.ArrayListUnmanaged(IncomingBlock),
});
pub fn writeOpcode(code: *std.ArrayList(Word), opcode: Opcode, arg_count: u16) !void {
const word_count: Word = arg_count + 1;
try code.append((word_count << 16) | @enumToInt(opcode));
}
pub fn writeInstruction(code: *std.ArrayList(Word), opcode: Opcode, args: []const Word) !void {
try writeOpcode(code, opcode, @intCast(u16, args.len));
try code.appendSlice(args);
}
pub fn writeInstructionWithString(code: *std.ArrayList(Word), opcode: Opcode, args: []const Word, str: []const u8) !void {
// Str needs to be written zero-terminated, so we need to add one to the length.
const zero_terminated_len = str.len + 1;
const str_words = (zero_terminated_len + @sizeOf(Word) - 1) / @sizeOf(Word);
try writeOpcode(code, opcode, @intCast(u16, args.len + str_words));
try code.ensureUnusedCapacity(args.len + str_words);
code.appendSliceAssumeCapacity(args);
// TODO: Not actually sure whether this is correct for big-endian.
// See https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html#Literal
var i: usize = 0;
while (i < zero_terminated_len) : (i += @sizeOf(Word)) {
var word: Word = 0;
var j: usize = 0;
while (j < @sizeOf(Word) and i + j < str.len) : (j += 1) {
word |= @as(Word, str[i + j]) << @intCast(std.math.Log2Int(Word), j * std.meta.bitCount(u8));
}
code.appendAssumeCapacity(word);
}
}
/// This structure represents a SPIR-V (binary) module being compiled, and keeps track of all relevant information.
/// That includes the actual instructions, the current result-id bound, and data structures for querying result-id's
/// of data which needs to be persistent over different calls to Decl code generation.
pub const SPIRVModule = struct {
/// A general-purpose allocator which may be used to allocate temporary resources required for compilation.
gpa: *Allocator,
/// The parent module.
module: *Module,
/// SPIR-V instructions return result-ids. This variable holds the module-wide counter for these.
next_result_id: ResultId,
/// Code of the actual SPIR-V binary, divided into the relevant logical sections.
/// Note: To save some bytes, these could also be unmanaged, but since there is only one instance of SPIRVModule
/// and this removes some clutter in the rest of the backend, it's fine like this.
binary: struct {
/// OpCapability and OpExtension instructions (in that order).
capabilities_and_extensions: std.ArrayList(Word),
/// OpString, OpSourceExtension, OpSource, OpSourceContinued.
debug_strings: std.ArrayList(Word),
/// Type declaration instructions, constant instructions, global variable declarations, OpUndef instructions.
types_globals_constants: std.ArrayList(Word),
/// Regular functions.
fn_decls: std.ArrayList(Word),
},
/// Global type cache to reduce the amount of generated types.
types: TypeMap,
/// Cache for results of OpString instructions for module file names fed to OpSource.
/// Since OpString is pretty much only used for those, we don't need to keep track of all strings,
/// just the ones for OpLine. Note that OpLine needs the result of OpString, and not that of OpSource.
file_names: std.StringHashMap(ResultId),
pub fn init(gpa: *Allocator, module: *Module) SPIRVModule {
return .{
.gpa = gpa,
.module = module,
.next_result_id = 1, // 0 is an invalid SPIR-V result ID.
.binary = .{
.capabilities_and_extensions = std.ArrayList(Word).init(gpa),
.debug_strings = std.ArrayList(Word).init(gpa),
.types_globals_constants = std.ArrayList(Word).init(gpa),
.fn_decls = std.ArrayList(Word).init(gpa),
},
.types = TypeMap.init(gpa),
.file_names = std.StringHashMap(ResultId).init(gpa),
};
}
pub fn deinit(self: *SPIRVModule) void {
self.file_names.deinit();
self.types.deinit();
self.binary.fn_decls.deinit();
self.binary.types_globals_constants.deinit();
self.binary.debug_strings.deinit();
self.binary.capabilities_and_extensions.deinit();
}
pub fn allocResultId(self: *SPIRVModule) Word {
defer self.next_result_id += 1;
return self.next_result_id;
}
pub fn resultIdBound(self: *SPIRVModule) Word {
return self.next_result_id;
}
fn resolveSourceFileName(self: *SPIRVModule, decl: *Decl) !ResultId {
const path = decl.namespace.file_scope.sub_file_path;
const result = try self.file_names.getOrPut(path);
if (!result.found_existing) {
result.entry.value = self.allocResultId();
try writeInstructionWithString(&self.binary.debug_strings, .OpString, &[_]Word{result.entry.value}, path);
try writeInstruction(&self.binary.debug_strings, .OpSource, &[_]Word{
@enumToInt(spec.SourceLanguage.Unknown), // TODO: Register Zig source language.
0, // TODO: Zig version as u32?
result.entry.value,
});
}
return result.entry.value;
}
};
/// This structure is used to compile a declaration, and contains all relevant meta-information to deal with that.
pub const DeclGen = struct {
/// The SPIR-V module code should be put in.
spv: *SPIRVModule,
/// An array of function argument result-ids. Each index corresponds with the function argument of the same index.
args: std.ArrayList(ResultId),
/// A counter to keep track of how many `arg` instructions we've seen yet.
next_arg_index: u32,
/// A map keeping track of which instruction generated which result-id.
inst_results: InstMap,
/// We need to keep track of result ids for block labels, as well as the 'incoming' blocks for a block.
blocks: BlockMap,
/// The label of the SPIR-V block we are currently generating.
current_block_label_id: ResultId,
/// The actual instructions for this function. We need to declare all locals in the first block, and because we don't
/// know which locals there are going to be, we're just going to generate everything after the locals-section in this array.
/// Note: It will not contain OpFunction, OpFunctionParameter, OpVariable and the initial OpLabel. These will be generated
/// into spv.binary.fn_decls directly.
code: std.ArrayList(Word),
/// The decl we are currently generating code for.
decl: *Decl,
/// If `gen` returned `Error.AnalysisFail`, this contains an explanatory message. Memory is owned by
/// `module.gpa`.
error_msg: ?*Module.ErrorMsg,
/// Possible errors the `gen` function may return.
const Error = error{ AnalysisFail, OutOfMemory };
/// This structure is used to return information about a type typically used for arithmetic operations.
/// These types may either be integers, floats, or a vector of these. Most scalar operations also work on vectors,
/// so we can easily represent those as arithmetic types.
/// If the type is a scalar, 'inner type' refers to the scalar type. Otherwise, if its a vector, it refers
/// to the vector's element type.
const ArithmeticTypeInfo = struct {
/// A classification of the inner type.
const Class = enum {
/// A boolean.
bool,
/// A regular, **native**, integer.
/// This is only returned when the backend supports this int as a native type (when
/// the relevant capability is enabled).
integer,
/// A regular float. These are all required to be natively supported. Floating points for
/// which the relevant capability is not enabled are not emulated.
float,
/// An integer of a 'strange' size (which' bit size is not the same as its backing type. **Note**: this
/// may **also** include power-of-2 integers for which the relevant capability is not enabled), but still
/// within the limits of the largest natively supported integer type.
strange_integer,
/// An integer with more bits than the largest natively supported integer type.
composite_integer,
};
/// The number of bits in the inner type.
/// Note: this is the actual number of bits of the type, not the size of the backing integer.
bits: u16,
/// Whether the type is a vector.
is_vector: bool,
/// Whether the inner type is signed. Only relevant for integers.
signedness: std.builtin.Signedness,
/// A classification of the inner type. These scenarios
/// will all have to be handled slightly different.
class: Class,
};
/// Initialize the common resources of a DeclGen. Some fields are left uninitialized, only set when `gen` is called.
pub fn init(spv: *SPIRVModule) DeclGen {
return .{
.spv = spv,
.args = std.ArrayList(ResultId).init(spv.gpa),
.next_arg_index = undefined,
.inst_results = InstMap.init(spv.gpa),
.blocks = BlockMap.init(spv.gpa),
.current_block_label_id = undefined,
.code = std.ArrayList(Word).init(spv.gpa),
.decl = undefined,
.error_msg = undefined,
};
}
/// Generate the code for `decl`. If a reportable error occured during code generation,
/// a message is returned by this function. Callee owns the memory. If this function returns such
/// a reportable error, it is valid to be called again for a different decl.
pub fn gen(self: *DeclGen, decl: *Decl) !?*Module.ErrorMsg {
// Reset internal resources, we don't want to re-allocate these.
self.args.items.len = 0;
self.next_arg_index = 0;
self.inst_results.clearRetainingCapacity();
self.blocks.clearRetainingCapacity();
self.current_block_label_id = undefined;
self.code.items.len = 0;
self.decl = decl;
self.error_msg = null;
try self.genDecl();
return self.error_msg;
}
/// Free resources owned by the DeclGen.
pub fn deinit(self: *DeclGen) void {
self.args.deinit();
self.inst_results.deinit();
self.blocks.deinit();
self.code.deinit();
}
fn getTarget(self: *DeclGen) std.Target {
return self.spv.module.getTarget();
}
fn fail(self: *DeclGen, src: LazySrcLoc, comptime format: []const u8, args: anytype) Error {
@setCold(true);
const src_loc = src.toSrcLocWithDecl(self.decl);
self.error_msg = try Module.ErrorMsg.create(self.spv.module.gpa, src_loc, format, args);
return error.AnalysisFail;
}
fn resolve(self: *DeclGen, inst: *Inst) !ResultId {
if (inst.value()) |val| {
return self.genConstant(inst.src, inst.ty, val);
}
return self.inst_results.get(inst).?; // Instruction does not dominate all uses!
}
fn beginSPIRVBlock(self: *DeclGen, label_id: ResultId) !void {
try writeInstruction(&self.code, .OpLabel, &[_]Word{label_id});
self.current_block_label_id = label_id;
}
/// SPIR-V requires enabling specific integer sizes through capabilities, and so if they are not enabled, we need
/// to emulate them in other instructions/types. This function returns, given an integer bit width (signed or unsigned, sign
/// included), the width of the underlying type which represents it, given the enabled features for the current target.
/// If the result is `null`, the largest type the target platform supports natively is not able to perform computations using
/// that size. In this case, multiple elements of the largest type should be used.
/// The backing type will be chosen as the smallest supported integer larger or equal to it in number of bits.
/// The result is valid to be used with OpTypeInt.
/// TODO: The extension SPV_INTEL_arbitrary_precision_integers allows any integer size (at least up to 32 bits).
/// TODO: This probably needs an ABI-version as well (especially in combination with SPV_INTEL_arbitrary_precision_integers).
/// TODO: Should the result of this function be cached?
fn backingIntBits(self: *DeclGen, bits: u16) ?u16 {
const target = self.getTarget();
// The backend will never be asked to compiler a 0-bit integer, so we won't have to handle those in this function.
std.debug.assert(bits != 0);
// 8, 16 and 64-bit integers require the Int8, Int16 and Inr64 capabilities respectively.
// 32-bit integers are always supported (see spec, 2.16.1, Data rules).
const ints = [_]struct { bits: u16, feature: ?Target.spirv.Feature }{
.{ .bits = 8, .feature = .Int8 },
.{ .bits = 16, .feature = .Int16 },
.{ .bits = 32, .feature = null },
.{ .bits = 64, .feature = .Int64 },
};
for (ints) |int| {
const has_feature = if (int.feature) |feature|
Target.spirv.featureSetHas(target.cpu.features, feature)
else
true;
if (bits <= int.bits and has_feature) {
return int.bits;
}
}
return null;
}
/// Return the amount of bits in the largest supported integer type. This is either 32 (always supported), or 64 (if
/// the Int64 capability is enabled).
/// Note: The extension SPV_INTEL_arbitrary_precision_integers allows any integer size (at least up to 32 bits).
/// In theory that could also be used, but since the spec says that it only guarantees support up to 32-bit ints there
/// is no way of knowing whether those are actually supported.
/// TODO: Maybe this should be cached?
fn largestSupportedIntBits(self: *DeclGen) u16 {
const target = self.getTarget();
return if (Target.spirv.featureSetHas(target.cpu.features, .Int64))
64
else
32;
}
/// Checks whether the type is "composite int", an integer consisting of multiple native integers. These are represented by
/// arrays of largestSupportedIntBits().
/// Asserts `ty` is an integer.
fn isCompositeInt(self: *DeclGen, ty: Type) bool {
return self.backingIntBits(ty) == null;
}
fn arithmeticTypeInfo(self: *DeclGen, ty: Type) !ArithmeticTypeInfo {
const target = self.getTarget();
return switch (ty.zigTypeTag()) {
.Bool => ArithmeticTypeInfo{
.bits = 1, // Doesn't matter for this class.
.is_vector = false,
.signedness = .unsigned, // Technically, but doesn't matter for this class.
.class = .bool,
},
.Float => ArithmeticTypeInfo{
.bits = ty.floatBits(target),
.is_vector = false,
.signedness = .signed, // Technically, but doesn't matter for this class.
.class = .float,
},
.Int => blk: {
const int_info = ty.intInfo(target);
// TODO: Maybe it's useful to also return this value.
const maybe_backing_bits = self.backingIntBits(int_info.bits);
break :blk ArithmeticTypeInfo{ .bits = int_info.bits, .is_vector = false, .signedness = int_info.signedness, .class = if (maybe_backing_bits) |backing_bits|
if (backing_bits == int_info.bits)
ArithmeticTypeInfo.Class.integer
else
ArithmeticTypeInfo.Class.strange_integer
else
.composite_integer };
},
// As of yet, there is no vector support in the self-hosted compiler.
.Vector => self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement arithmeticTypeInfo for Vector", .{}),
// TODO: For which types is this the case?
else => self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement arithmeticTypeInfo for {}", .{ty}),
};
}
/// Generate a constant representing `val`.
/// TODO: Deduplication?
fn genConstant(self: *DeclGen, src: LazySrcLoc, ty: Type, val: Value) Error!ResultId {
const target = self.getTarget();
const code = &self.spv.binary.types_globals_constants;
const result_id = self.spv.allocResultId();
const result_type_id = try self.genType(src, ty);
if (val.isUndef()) {
try writeInstruction(code, .OpUndef, &[_]Word{ result_type_id, result_id });
return result_id;
}
switch (ty.zigTypeTag()) {
.Int => {
const int_info = ty.intInfo(target);
const backing_bits = self.backingIntBits(int_info.bits) orelse {
// Integers too big for any native type are represented as "composite integers": An array of largestSupportedIntBits.
return self.fail(src, "TODO: SPIR-V backend: implement composite int constants for {}", .{ty});
};
// We can just use toSignedInt/toUnsignedInt here as it returns u64 - a type large enough to hold any
// SPIR-V native type (up to i/u64 with Int64). If SPIR-V ever supports native ints of a larger size, this
// might need to be updated.
std.debug.assert(self.largestSupportedIntBits() <= std.meta.bitCount(u64));
var int_bits = if (ty.isSignedInt()) @bitCast(u64, val.toSignedInt()) else val.toUnsignedInt();
// Mask the low bits which make up the actual integer. This is to make sure that negative values
// only use the actual bits of the type.
// TODO: Should this be the backing type bits or the actual type bits?
int_bits &= (@as(u64, 1) << @intCast(u6, backing_bits)) - 1;
switch (backing_bits) {
0 => unreachable,
1...32 => try writeInstruction(code, .OpConstant, &[_]Word{
result_type_id,
result_id,
@truncate(u32, int_bits),
}),
33...64 => try writeInstruction(code, .OpConstant, &[_]Word{
result_type_id,
result_id,
@truncate(u32, int_bits),
@truncate(u32, int_bits >> @bitSizeOf(u32)),
}),
else => unreachable, // backing_bits is bounded by largestSupportedIntBits.
}
},
.Bool => {
const opcode: Opcode = if (val.toBool()) .OpConstantTrue else .OpConstantFalse;
try writeInstruction(code, opcode, &[_]Word{ result_type_id, result_id });
},
.Float => {
// At this point we are guaranteed that the target floating point type is supported, otherwise the function
// would have exited at genType(ty).
// f16 and f32 require one word of storage. f64 requires 2, low-order first.
switch (ty.floatBits(target)) {
16 => try writeInstruction(code, .OpConstant, &[_]Word{ result_type_id, result_id, @bitCast(u16, val.toFloat(f16)) }),
32 => try writeInstruction(code, .OpConstant, &[_]Word{ result_type_id, result_id, @bitCast(u32, val.toFloat(f32)) }),
64 => {
const float_bits = @bitCast(u64, val.toFloat(f64));
try writeInstruction(code, .OpConstant, &[_]Word{
result_type_id,
result_id,
@truncate(u32, float_bits),
@truncate(u32, float_bits >> @bitSizeOf(u32)),
});
},
128 => unreachable, // Filtered out in the call to genType.
// TODO: Insert case for long double when the layout for that is determined.
else => unreachable,
}
},
.Void => unreachable,
else => return self.fail(src, "TODO: SPIR-V backend: constant generation of type {}", .{ty}),
}
return result_id;
}
fn genType(self: *DeclGen, src: LazySrcLoc, ty: Type) Error!ResultId {
// We can't use getOrPut here so we can recursively generate types.
if (self.spv.types.get(ty)) |already_generated| {
return already_generated;
}
const target = self.getTarget();
const code = &self.spv.binary.types_globals_constants;
const result_id = self.spv.allocResultId();
switch (ty.zigTypeTag()) {
.Void => try writeInstruction(code, .OpTypeVoid, &[_]Word{result_id}),
.Bool => try writeInstruction(code, .OpTypeBool, &[_]Word{result_id}),
.Int => {
const int_info = ty.intInfo(target);
const backing_bits = self.backingIntBits(int_info.bits) orelse {
// Integers too big for any native type are represented as "composite integers": An array of largestSupportedIntBits.
return self.fail(src, "TODO: SPIR-V backend: implement composite int {}", .{ty});
};
// TODO: If backing_bits != int_info.bits, a duplicate type might be generated here.
try writeInstruction(code, .OpTypeInt, &[_]Word{
result_id,
backing_bits,
switch (int_info.signedness) {
.unsigned => 0,
.signed => 1,
},
});
},
.Float => {
// We can (and want) not really emulate floating points with other floating point types like with the integer types,
// so if the float is not supported, just return an error.
const bits = ty.floatBits(target);
const supported = switch (bits) {
16 => Target.spirv.featureSetHas(target.cpu.features, .Float16),
// 32-bit floats are always supported (see spec, 2.16.1, Data rules).
32 => true,
64 => Target.spirv.featureSetHas(target.cpu.features, .Float64),
else => false,
};
if (!supported) {
return self.fail(src, "Floating point width of {} bits is not supported for the current SPIR-V feature set", .{bits});
}
try writeInstruction(code, .OpTypeFloat, &[_]Word{ result_id, bits });
},
.Fn => {
// We only support zig-calling-convention functions, no varargs.
if (ty.fnCallingConvention() != .Unspecified)
return self.fail(src, "Unsupported calling convention for SPIR-V", .{});
if (ty.fnIsVarArgs())
return self.fail(src, "VarArgs unsupported for SPIR-V", .{});
// In order to avoid a temporary here, first generate all the required types and then simply look them up
// when generating the function type.
const params = ty.fnParamLen();
var i: usize = 0;
while (i < params) : (i += 1) {
_ = try self.genType(src, ty.fnParamType(i));
}
const return_type_id = try self.genType(src, ty.fnReturnType());
// result id + result type id + parameter type ids.
try writeOpcode(code, .OpTypeFunction, 2 + @intCast(u16, ty.fnParamLen()));
try code.appendSlice(&.{ result_id, return_type_id });
i = 0;
while (i < params) : (i += 1) {
const param_type_id = self.spv.types.get(ty.fnParamType(i)).?;
try code.append(param_type_id);
}
},
// When recursively generating a type, we cannot infer the pointer's storage class. See genPointerType.
.Pointer => return self.fail(src, "Cannot create pointer with unkown storage class", .{}),
.Vector => {
// Although not 100% the same, Zig vectors map quite neatly to SPIR-V vectors (including many integer and float operations
// which work on them), so simply use those.
// Note: SPIR-V vectors only support bools, ints and floats, so pointer vectors need to be supported another way.
// "composite integers" (larger than the largest supported native type) can probably be represented by an array of vectors.
// TODO: The SPIR-V spec mentions that vector sizes may be quite restricted! look into which we can use, and whether OpTypeVector
// is adequate at all for this.
// TODO: Vectors are not yet supported by the self-hosted compiler itself it seems.
return self.fail(src, "TODO: SPIR-V backend: implement type Vector", .{});
},
.Null,
.Undefined,
.EnumLiteral,
.ComptimeFloat,
.ComptimeInt,
.Type,
=> unreachable, // Must be const or comptime.
.BoundFn => unreachable, // this type will be deleted from the language.
else => |tag| return self.fail(src, "TODO: SPIR-V backend: implement type {}s", .{tag}),
}
try self.spv.types.putNoClobber(ty, result_id);
return result_id;
}
/// SPIR-V requires pointers to have a storage class (address space), and so we have a special function for that.
/// TODO: The result of this needs to be cached.
fn genPointerType(self: *DeclGen, src: LazySrcLoc, ty: Type, storage_class: spec.StorageClass) !ResultId {
std.debug.assert(ty.zigTypeTag() == .Pointer);
const code = &self.spv.binary.types_globals_constants;
const result_id = self.spv.allocResultId();
// TODO: There are many constraints which are ignored for now: We may only create pointers to certain types, and to other types
// if more capabilities are enabled. For example, we may only create pointers to f16 if Float16Buffer is enabled.
// These also relates to the pointer's address space.
const child_id = try self.genType(src, ty.elemType());
try writeInstruction(code, .OpTypePointer, &[_]Word{ result_id, @enumToInt(storage_class), child_id });
return result_id;
}
fn genDecl(self: *DeclGen) !void {
const decl = self.decl;
const result_id = decl.fn_link.spirv.id;
if (decl.val.castTag(.function)) |func_payload| {
std.debug.assert(decl.ty.zigTypeTag() == .Fn);
const prototype_id = try self.genType(.{ .node_offset = 0 }, decl.ty);
try writeInstruction(&self.spv.binary.fn_decls, .OpFunction, &[_]Word{
self.spv.types.get(decl.ty.fnReturnType()).?, // This type should be generated along with the prototype.
result_id,
@bitCast(Word, spec.FunctionControl{}), // TODO: We can set inline here if the type requires it.
prototype_id,
});
const params = decl.ty.fnParamLen();
var i: usize = 0;
try self.args.ensureCapacity(params);
while (i < params) : (i += 1) {
const param_type_id = self.spv.types.get(decl.ty.fnParamType(i)).?;
const arg_result_id = self.spv.allocResultId();
try writeInstruction(&self.spv.binary.fn_decls, .OpFunctionParameter, &[_]Word{ param_type_id, arg_result_id });
self.args.appendAssumeCapacity(arg_result_id);
}
// TODO: This could probably be done in a better way...
const root_block_id = self.spv.allocResultId();
// We need to generate the label directly in the fn_decls here because we're going to write the local variables after
// here. Since we're not generating in self.code, we're just going to bypass self.beginSPIRVBlock here.
try writeInstruction(&self.spv.binary.fn_decls, .OpLabel, &[_]Word{root_block_id});
self.current_block_label_id = root_block_id;
try self.genBody(func_payload.data.body);
// Append the actual code into the fn_decls section.
try self.spv.binary.fn_decls.appendSlice(self.code.items);
try writeInstruction(&self.spv.binary.fn_decls, .OpFunctionEnd, &[_]Word{});
} else {
return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: generate decl type {}", .{decl.ty.zigTypeTag()});
}
}
fn genBody(self: *DeclGen, body: ir.Body) Error!void {
for (body.instructions) |inst| {
try self.genInst(inst);
}
}
fn genInst(self: *DeclGen, inst: *Inst) !void {
const result_id = switch (inst.tag) {
.add, .addwrap => try self.genBinOp(inst.castTag(.add).?),
.sub, .subwrap => try self.genBinOp(inst.castTag(.sub).?),
.mul, .mulwrap => try self.genBinOp(inst.castTag(.mul).?),
.div => try self.genBinOp(inst.castTag(.div).?),
.bit_and => try self.genBinOp(inst.castTag(.bit_and).?),
.bit_or => try self.genBinOp(inst.castTag(.bit_or).?),
.xor => try self.genBinOp(inst.castTag(.xor).?),
.cmp_eq => try self.genCmp(inst.castTag(.cmp_eq).?),
.cmp_neq => try self.genCmp(inst.castTag(.cmp_neq).?),
.cmp_gt => try self.genCmp(inst.castTag(.cmp_gt).?),
.cmp_gte => try self.genCmp(inst.castTag(.cmp_gte).?),
.cmp_lt => try self.genCmp(inst.castTag(.cmp_lt).?),
.cmp_lte => try self.genCmp(inst.castTag(.cmp_lte).?),
.bool_and => try self.genBinOp(inst.castTag(.bool_and).?),
.bool_or => try self.genBinOp(inst.castTag(.bool_or).?),
.not => try self.genUnOp(inst.castTag(.not).?),
.alloc => try self.genAlloc(inst.castTag(.alloc).?),
.arg => self.genArg(),
.block => (try self.genBlock(inst.castTag(.block).?)) orelse return,
.br => return try self.genBr(inst.castTag(.br).?),
.br_void => return try self.genBrVoid(inst.castTag(.br_void).?),
// TODO: Breakpoints won't be supported in SPIR-V, but the compiler seems to insert them
// throughout the IR.
.breakpoint => return,
.condbr => return try self.genCondBr(inst.castTag(.condbr).?),
.constant => unreachable,
.dbg_stmt => return try self.genDbgStmt(inst.castTag(.dbg_stmt).?),
.load => try self.genLoad(inst.castTag(.load).?),
.loop => return try self.genLoop(inst.castTag(.loop).?),
.ret => return try self.genRet(inst.castTag(.ret).?),
.retvoid => return try self.genRetVoid(),
.store => return try self.genStore(inst.castTag(.store).?),
.unreach => return try self.genUnreach(),
else => return self.fail(inst.src, "TODO: SPIR-V backend: implement inst {s}", .{@tagName(inst.tag)}),
};
try self.inst_results.putNoClobber(inst, result_id);
}
fn genBinOp(self: *DeclGen, inst: *Inst.BinOp) !ResultId {
// TODO: Will lhs and rhs have the same type?
const lhs_id = try self.resolve(inst.lhs);
const rhs_id = try self.resolve(inst.rhs);
const result_id = self.spv.allocResultId();
const result_type_id = try self.genType(inst.base.src, inst.base.ty);
// TODO: Is the result the same as the argument types?
// This is supposed to be the case for SPIR-V.
std.debug.assert(inst.rhs.ty.eql(inst.lhs.ty));
std.debug.assert(inst.base.ty.tag() == .bool or inst.base.ty.eql(inst.lhs.ty));
// Binary operations are generally applicable to both scalar and vector operations in SPIR-V, but int and float
// versions of operations require different opcodes.
// For operations which produce bools, the information of inst.base.ty is not useful, so just pick either operand
// instead.
const info = try self.arithmeticTypeInfo(inst.lhs.ty);
if (info.class == .composite_integer) {
return self.fail(inst.base.src, "TODO: SPIR-V backend: binary operations for composite integers", .{});
} else if (info.class == .strange_integer) {
return self.fail(inst.base.src, "TODO: SPIR-V backend: binary operations for strange integers", .{});
}
const is_bool = info.class == .bool;
const is_float = info.class == .float;
const is_signed = info.signedness == .signed;
// **Note**: All these operations must be valid for vectors as well!
const opcode = switch (inst.base.tag) {
// The regular integer operations are all defined for wrapping. Since theyre only relevant for integers,
// we can just switch on both cases here.
.add, .addwrap => if (is_float) Opcode.OpFAdd else Opcode.OpIAdd,
.sub, .subwrap => if (is_float) Opcode.OpFSub else Opcode.OpISub,
.mul, .mulwrap => if (is_float) Opcode.OpFMul else Opcode.OpIMul,
// TODO: Trap if divisor is 0?
// TODO: Figure out of OpSDiv for unsigned/OpUDiv for signed does anything useful.
// => Those are probably for divTrunc and divFloor, though the compiler does not yet generate those.
// => TODO: Figure out how those work on the SPIR-V side.
// => TODO: Test these.
.div => if (is_float) Opcode.OpFDiv else if (is_signed) Opcode.OpSDiv else Opcode.OpUDiv,
// Only integer versions for these.
.bit_and => Opcode.OpBitwiseAnd,
.bit_or => Opcode.OpBitwiseOr,
.xor => Opcode.OpBitwiseXor,
// Bool -> bool operations.
.bool_and => Opcode.OpLogicalAnd,
.bool_or => Opcode.OpLogicalOr,
else => unreachable,
};
try writeInstruction(&self.code, opcode, &[_]Word{ result_type_id, result_id, lhs_id, rhs_id });
// TODO: Trap on overflow? Probably going to be annoying.
// TODO: Look into SPV_KHR_no_integer_wrap_decoration which provides NoSignedWrap/NoUnsignedWrap.
if (info.class != .strange_integer)
return result_id;
return self.fail(inst.base.src, "TODO: SPIR-V backend: strange integer operation mask", .{});
}
fn genCmp(self: *DeclGen, inst: *Inst.BinOp) !ResultId {
const lhs_id = try self.resolve(inst.lhs);
const rhs_id = try self.resolve(inst.rhs);
const result_id = self.spv.allocResultId();
const result_type_id = try self.genType(inst.base.src, inst.base.ty);
// All of these operations should be 2 equal types -> bool
std.debug.assert(inst.rhs.ty.eql(inst.lhs.ty));
std.debug.assert(inst.base.ty.tag() == .bool);
// Comparisons are generally applicable to both scalar and vector operations in SPIR-V, but int and float
// versions of operations require different opcodes.
// Since inst.base.ty is always bool and so not very useful, and because both arguments must be the same, just get the info
// from either of the operands.
const info = try self.arithmeticTypeInfo(inst.lhs.ty);
if (info.class == .composite_integer) {
return self.fail(inst.base.src, "TODO: SPIR-V backend: binary operations for composite integers", .{});
} else if (info.class == .strange_integer) {
return self.fail(inst.base.src, "TODO: SPIR-V backend: comparison for strange integers", .{});
}
const is_bool = info.class == .bool;
const is_float = info.class == .float;
const is_signed = info.signedness == .signed;
// **Note**: All these operations must be valid for vectors as well!
// For floating points, we generally want ordered operations (which return false if either operand is nan).
const opcode = switch (inst.base.tag) {
.cmp_eq => if (is_float) Opcode.OpFOrdEqual else if (is_bool) Opcode.OpLogicalEqual else Opcode.OpIEqual,
.cmp_neq => if (is_float) Opcode.OpFOrdNotEqual else if (is_bool) Opcode.OpLogicalNotEqual else Opcode.OpINotEqual,
// TODO: Verify that these OpFOrd type operations produce the right value.
// TODO: Is there a more fundamental difference between OpU and OpS operations here than just the type?
.cmp_gt => if (is_float) Opcode.OpFOrdGreaterThan else if (is_signed) Opcode.OpSGreaterThan else Opcode.OpUGreaterThan,
.cmp_gte => if (is_float) Opcode.OpFOrdGreaterThanEqual else if (is_signed) Opcode.OpSGreaterThanEqual else Opcode.OpUGreaterThanEqual,
.cmp_lt => if (is_float) Opcode.OpFOrdLessThan else if (is_signed) Opcode.OpSLessThan else Opcode.OpULessThan,
.cmp_lte => if (is_float) Opcode.OpFOrdLessThanEqual else if (is_signed) Opcode.OpSLessThanEqual else Opcode.OpULessThanEqual,
else => unreachable,
};
try writeInstruction(&self.code, opcode, &[_]Word{ result_type_id, result_id, lhs_id, rhs_id });
return result_id;
}
fn genUnOp(self: *DeclGen, inst: *Inst.UnOp) !ResultId {
const operand_id = try self.resolve(inst.operand);
const result_id = self.spv.allocResultId();
const result_type_id = try self.genType(inst.base.src, inst.base.ty);
const info = try self.arithmeticTypeInfo(inst.operand.ty);
const opcode = switch (inst.base.tag) {
// Bool -> bool
.not => Opcode.OpLogicalNot,
else => unreachable,
};
try writeInstruction(&self.code, opcode, &[_]Word{ result_type_id, result_id, operand_id });
return result_id;
}
fn genAlloc(self: *DeclGen, inst: *Inst.NoOp) !ResultId {
const storage_class = spec.StorageClass.Function;
const result_type_id = try self.genPointerType(inst.base.src, inst.base.ty, storage_class);
const result_id = self.spv.allocResultId();
// Rather than generating into code here, we're just going to generate directly into the fn_decls section so that
// variable declarations appear in the first block of the function.
try writeInstruction(&self.spv.binary.fn_decls, .OpVariable, &[_]Word{ result_type_id, result_id, @enumToInt(storage_class) });
return result_id;
}
fn genArg(self: *DeclGen) ResultId {
defer self.next_arg_index += 1;
return self.args.items[self.next_arg_index];
}
fn genBlock(self: *DeclGen, inst: *Inst.Block) !?ResultId {
// In IR, a block doesn't really define an entry point like a block, but more like a scope that breaks can jump out of and
// "return" a value from. This cannot be directly modelled in SPIR-V, so in a block instruction, we're going to split up
// the current block by first generating the code of the block, then a label, and then generate the rest of the current
// ir.Block in a different SPIR-V block.
const label_id = self.spv.allocResultId();
// 4 chosen as arbitrary initial capacity.
var incoming_blocks = try std.ArrayListUnmanaged(IncomingBlock).initCapacity(self.spv.gpa, 4);
try self.blocks.putNoClobber(inst, .{
.label_id = label_id,
.incoming_blocks = &incoming_blocks,
});
defer {
self.blocks.removeAssertDiscard(inst);
incoming_blocks.deinit(self.spv.gpa);
}
try self.genBody(inst.body);
try self.beginSPIRVBlock(label_id);
// If this block didn't produce a value, simply return here.
if (!inst.base.ty.hasCodeGenBits())
return null;
// Combine the result from the blocks using the Phi instruction.
const result_id = self.spv.allocResultId();
// TODO: OpPhi is limited in the types that it may produce, such as pointers. Figure out which other types
// are not allowed to be created from a phi node, and throw an error for those. For now, genType already throws
// an error for pointers.
const result_type_id = try self.genType(inst.base.src, inst.base.ty);
try writeOpcode(&self.code, .OpPhi, 2 + @intCast(u16, incoming_blocks.items.len * 2)); // result type + result + variable/parent...
for (incoming_blocks.items) |incoming| {
try self.code.appendSlice(&[_]Word{ incoming.break_value_id, incoming.src_label_id });
}
return result_id;
}
fn genBr(self: *DeclGen, inst: *Inst.Br) !void {
// TODO: This instruction needs to be the last in a block. Is that guaranteed?
const target = self.blocks.get(inst.block).?;
// TODO: For some reason, br is emitted with void parameters.
if (inst.operand.ty.hasCodeGenBits()) {
const operand_id = try self.resolve(inst.operand);
// current_block_label_id should not be undefined here, lest there is a br or br_void in the function's body.
try target.incoming_blocks.append(self.spv.gpa, .{
.src_label_id = self.current_block_label_id,
.break_value_id = operand_id
});
}
try writeInstruction(&self.code, .OpBranch, &[_]Word{target.label_id});
}
fn genBrVoid(self: *DeclGen, inst: *Inst.BrVoid) !void {
// TODO: This instruction needs to be the last in a block. Is that guaranteed?
const target = self.blocks.get(inst.block).?;
// Don't need to add this to the incoming block list, as there is no value to insert in the phi node anyway.
try writeInstruction(&self.code, .OpBranch, &[_]Word{target.label_id});
}
fn genCondBr(self: *DeclGen, inst: *Inst.CondBr) !void {
// TODO: This instruction needs to be the last in a block. Is that guaranteed?
const condition_id = try self.resolve(inst.condition);
// These will always generate a new SPIR-V block, since they are ir.Body and not ir.Block.
const then_label_id = self.spv.allocResultId();
const else_label_id = self.spv.allocResultId();
// TODO: We can generate OpSelectionMerge here if we know the target block that both of these will resolve to,
// but i don't know if those will always resolve to the same block.
try writeInstruction(&self.code, .OpBranchConditional, &[_]Word{
condition_id,
then_label_id,
else_label_id,
});
try self.beginSPIRVBlock(then_label_id);
try self.genBody(inst.then_body);
try self.beginSPIRVBlock(else_label_id);
try self.genBody(inst.else_body);
}
fn genDbgStmt(self: *DeclGen, inst: *Inst.DbgStmt) !void {
const src_fname_id = try self.spv.resolveSourceFileName(self.decl);
try writeInstruction(&self.code, .OpLine, &[_]Word{ src_fname_id, inst.line, inst.column });
}
fn genLoad(self: *DeclGen, inst: *Inst.UnOp) !ResultId {
const operand_id = try self.resolve(inst.operand);
const result_type_id = try self.genType(inst.base.src, inst.base.ty);
const result_id = self.spv.allocResultId();
const operands = if (inst.base.ty.isVolatilePtr())
&[_]Word{ result_type_id, result_id, operand_id, @bitCast(u32, spec.MemoryAccess{.Volatile = true}) }
else
&[_]Word{ result_type_id, result_id, operand_id};
try writeInstruction(&self.code, .OpLoad, operands);
return result_id;
}
fn genLoop(self: *DeclGen, inst: *Inst.Loop) !void {
// TODO: This instruction needs to be the last in a block. Is that guaranteed?
const loop_label_id = self.spv.allocResultId();
// Jump to the loop entry point
try writeInstruction(&self.code, .OpBranch, &[_]Word{ loop_label_id });
// TODO: Look into OpLoopMerge.
try self.beginSPIRVBlock(loop_label_id);
try self.genBody(inst.body);
try writeInstruction(&self.code, .OpBranch, &[_]Word{ loop_label_id });
}
fn genRet(self: *DeclGen, inst: *Inst.UnOp) !void {
const operand_id = try self.resolve(inst.operand);
// TODO: This instruction needs to be the last in a block. Is that guaranteed?
try writeInstruction(&self.code, .OpReturnValue, &[_]Word{operand_id});
}
fn genRetVoid(self: *DeclGen) !void {
// TODO: This instruction needs to be the last in a block. Is that guaranteed?
try writeInstruction(&self.code, .OpReturn, &[_]Word{});
}
fn genStore(self: *DeclGen, inst: *Inst.BinOp) !void {
const dst_ptr_id = try self.resolve(inst.lhs);
const src_val_id = try self.resolve(inst.rhs);
const operands = if (inst.lhs.ty.isVolatilePtr())
&[_]Word{ dst_ptr_id, src_val_id, @bitCast(u32, spec.MemoryAccess{.Volatile = true}) }
else
&[_]Word{ dst_ptr_id, src_val_id };
try writeInstruction(&self.code, .OpStore, operands);
}
fn genUnreach(self: *DeclGen) !void {
// TODO: This instruction needs to be the last in a block. Is that guaranteed?
try writeInstruction(&self.code, .OpUnreachable, &[_]Word{});
}
}; | src/codegen/spirv.zig |
const std = @import("std");
const cast = std.meta.cast;
const mode = std.builtin.mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels
// The type MontgomeryDomainFieldElement is a field element in the Montgomery domain.
// Bounds: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub const MontgomeryDomainFieldElement = [12]u32;
// The type NonMontgomeryDomainFieldElement is a field element NOT in the Montgomery domain.
// Bounds: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub const NonMontgomeryDomainFieldElement = [12]u32;
/// The function addcarryxU32 is an addition with carry.
///
/// Postconditions:
/// out1 = (arg1 + arg2 + arg3) mod 2^32
/// out2 = ⌊(arg1 + arg2 + arg3) / 2^32⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffff]
/// arg3: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [0x0 ~> 0x1]
inline fn addcarryxU32(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = ((cast(u64, arg1) + cast(u64, arg2)) + cast(u64, arg3));
const x2 = cast(u32, (x1 & cast(u64, 0xffffffff)));
const x3 = cast(u1, (x1 >> 32));
out1.* = x2;
out2.* = x3;
}
/// The function subborrowxU32 is a subtraction with borrow.
///
/// Postconditions:
/// out1 = (-arg1 + arg2 + -arg3) mod 2^32
/// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^32⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffff]
/// arg3: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [0x0 ~> 0x1]
inline fn subborrowxU32(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = ((cast(i64, arg2) - cast(i64, arg1)) - cast(i64, arg3));
const x2 = cast(i1, (x1 >> 32));
const x3 = cast(u32, (x1 & cast(i64, 0xffffffff)));
out1.* = x3;
out2.* = cast(u1, (cast(i2, 0x0) - cast(i2, x2)));
}
/// The function mulxU32 is a multiplication, returning the full double-width result.
///
/// Postconditions:
/// out1 = (arg1 * arg2) mod 2^32
/// out2 = ⌊arg1 * arg2 / 2^32⌋
///
/// Input Bounds:
/// arg1: [0x0 ~> 0xffffffff]
/// arg2: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [0x0 ~> 0xffffffff]
inline fn mulxU32(out1: *u32, out2: *u32, arg1: u32, arg2: u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (cast(u64, arg1) * cast(u64, arg2));
const x2 = cast(u32, (x1 & cast(u64, 0xffffffff)));
const x3 = cast(u32, (x1 >> 32));
out1.* = x2;
out2.* = x3;
}
/// The function cmovznzU32 is a single-word conditional move.
///
/// Postconditions:
/// out1 = (if arg1 = 0 then arg2 else arg3)
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [0x0 ~> 0xffffffff]
/// arg3: [0x0 ~> 0xffffffff]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
inline fn cmovznzU32(out1: *u32, arg1: u1, arg2: u32, arg3: u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (~(~arg1));
const x2 = cast(u32, (cast(i64, cast(i1, (cast(i2, 0x0) - cast(i2, x1)))) & cast(i64, 0xffffffff)));
const x3 = ((x2 & arg3) | ((~x2) & arg2));
out1.* = x3;
}
/// The function mul multiplies two field elements in the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
pub fn mul(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[1]);
const x2 = (arg1[2]);
const x3 = (arg1[3]);
const x4 = (arg1[4]);
const x5 = (arg1[5]);
const x6 = (arg1[6]);
const x7 = (arg1[7]);
const x8 = (arg1[8]);
const x9 = (arg1[9]);
const x10 = (arg1[10]);
const x11 = (arg1[11]);
const x12 = (arg1[0]);
var x13: u32 = undefined;
var x14: u32 = undefined;
mulxU32(&x13, &x14, x12, (arg2[11]));
var x15: u32 = undefined;
var x16: u32 = undefined;
mulxU32(&x15, &x16, x12, (arg2[10]));
var x17: u32 = undefined;
var x18: u32 = undefined;
mulxU32(&x17, &x18, x12, (arg2[9]));
var x19: u32 = undefined;
var x20: u32 = undefined;
mulxU32(&x19, &x20, x12, (arg2[8]));
var x21: u32 = undefined;
var x22: u32 = undefined;
mulxU32(&x21, &x22, x12, (arg2[7]));
var x23: u32 = undefined;
var x24: u32 = undefined;
mulxU32(&x23, &x24, x12, (arg2[6]));
var x25: u32 = undefined;
var x26: u32 = undefined;
mulxU32(&x25, &x26, x12, (arg2[5]));
var x27: u32 = undefined;
var x28: u32 = undefined;
mulxU32(&x27, &x28, x12, (arg2[4]));
var x29: u32 = undefined;
var x30: u32 = undefined;
mulxU32(&x29, &x30, x12, (arg2[3]));
var x31: u32 = undefined;
var x32: u32 = undefined;
mulxU32(&x31, &x32, x12, (arg2[2]));
var x33: u32 = undefined;
var x34: u32 = undefined;
mulxU32(&x33, &x34, x12, (arg2[1]));
var x35: u32 = undefined;
var x36: u32 = undefined;
mulxU32(&x35, &x36, x12, (arg2[0]));
var x37: u32 = undefined;
var x38: u1 = undefined;
addcarryxU32(&x37, &x38, 0x0, x36, x33);
var x39: u32 = undefined;
var x40: u1 = undefined;
addcarryxU32(&x39, &x40, x38, x34, x31);
var x41: u32 = undefined;
var x42: u1 = undefined;
addcarryxU32(&x41, &x42, x40, x32, x29);
var x43: u32 = undefined;
var x44: u1 = undefined;
addcarryxU32(&x43, &x44, x42, x30, x27);
var x45: u32 = undefined;
var x46: u1 = undefined;
addcarryxU32(&x45, &x46, x44, x28, x25);
var x47: u32 = undefined;
var x48: u1 = undefined;
addcarryxU32(&x47, &x48, x46, x26, x23);
var x49: u32 = undefined;
var x50: u1 = undefined;
addcarryxU32(&x49, &x50, x48, x24, x21);
var x51: u32 = undefined;
var x52: u1 = undefined;
addcarryxU32(&x51, &x52, x50, x22, x19);
var x53: u32 = undefined;
var x54: u1 = undefined;
addcarryxU32(&x53, &x54, x52, x20, x17);
var x55: u32 = undefined;
var x56: u1 = undefined;
addcarryxU32(&x55, &x56, x54, x18, x15);
var x57: u32 = undefined;
var x58: u1 = undefined;
addcarryxU32(&x57, &x58, x56, x16, x13);
const x59 = (cast(u32, x58) + x14);
var x60: u32 = undefined;
var x61: u32 = undefined;
mulxU32(&x60, &x61, x35, 0xffffffff);
var x62: u32 = undefined;
var x63: u32 = undefined;
mulxU32(&x62, &x63, x35, 0xffffffff);
var x64: u32 = undefined;
var x65: u32 = undefined;
mulxU32(&x64, &x65, x35, 0xffffffff);
var x66: u32 = undefined;
var x67: u32 = undefined;
mulxU32(&x66, &x67, x35, 0xffffffff);
var x68: u32 = undefined;
var x69: u32 = undefined;
mulxU32(&x68, &x69, x35, 0xffffffff);
var x70: u32 = undefined;
var x71: u32 = undefined;
mulxU32(&x70, &x71, x35, 0xffffffff);
var x72: u32 = undefined;
var x73: u32 = undefined;
mulxU32(&x72, &x73, x35, 0xffffffff);
var x74: u32 = undefined;
var x75: u32 = undefined;
mulxU32(&x74, &x75, x35, 0xfffffffe);
var x76: u32 = undefined;
var x77: u32 = undefined;
mulxU32(&x76, &x77, x35, 0xffffffff);
var x78: u32 = undefined;
var x79: u32 = undefined;
mulxU32(&x78, &x79, x35, 0xffffffff);
var x80: u32 = undefined;
var x81: u1 = undefined;
addcarryxU32(&x80, &x81, 0x0, x77, x74);
var x82: u32 = undefined;
var x83: u1 = undefined;
addcarryxU32(&x82, &x83, x81, x75, x72);
var x84: u32 = undefined;
var x85: u1 = undefined;
addcarryxU32(&x84, &x85, x83, x73, x70);
var x86: u32 = undefined;
var x87: u1 = undefined;
addcarryxU32(&x86, &x87, x85, x71, x68);
var x88: u32 = undefined;
var x89: u1 = undefined;
addcarryxU32(&x88, &x89, x87, x69, x66);
var x90: u32 = undefined;
var x91: u1 = undefined;
addcarryxU32(&x90, &x91, x89, x67, x64);
var x92: u32 = undefined;
var x93: u1 = undefined;
addcarryxU32(&x92, &x93, x91, x65, x62);
var x94: u32 = undefined;
var x95: u1 = undefined;
addcarryxU32(&x94, &x95, x93, x63, x60);
const x96 = (cast(u32, x95) + x61);
var x97: u32 = undefined;
var x98: u1 = undefined;
addcarryxU32(&x97, &x98, 0x0, x35, x78);
var x99: u32 = undefined;
var x100: u1 = undefined;
addcarryxU32(&x99, &x100, x98, x37, x79);
var x101: u32 = undefined;
var x102: u1 = undefined;
addcarryxU32(&x101, &x102, x100, x39, cast(u32, 0x0));
var x103: u32 = undefined;
var x104: u1 = undefined;
addcarryxU32(&x103, &x104, x102, x41, x76);
var x105: u32 = undefined;
var x106: u1 = undefined;
addcarryxU32(&x105, &x106, x104, x43, x80);
var x107: u32 = undefined;
var x108: u1 = undefined;
addcarryxU32(&x107, &x108, x106, x45, x82);
var x109: u32 = undefined;
var x110: u1 = undefined;
addcarryxU32(&x109, &x110, x108, x47, x84);
var x111: u32 = undefined;
var x112: u1 = undefined;
addcarryxU32(&x111, &x112, x110, x49, x86);
var x113: u32 = undefined;
var x114: u1 = undefined;
addcarryxU32(&x113, &x114, x112, x51, x88);
var x115: u32 = undefined;
var x116: u1 = undefined;
addcarryxU32(&x115, &x116, x114, x53, x90);
var x117: u32 = undefined;
var x118: u1 = undefined;
addcarryxU32(&x117, &x118, x116, x55, x92);
var x119: u32 = undefined;
var x120: u1 = undefined;
addcarryxU32(&x119, &x120, x118, x57, x94);
var x121: u32 = undefined;
var x122: u1 = undefined;
addcarryxU32(&x121, &x122, x120, x59, x96);
var x123: u32 = undefined;
var x124: u32 = undefined;
mulxU32(&x123, &x124, x1, (arg2[11]));
var x125: u32 = undefined;
var x126: u32 = undefined;
mulxU32(&x125, &x126, x1, (arg2[10]));
var x127: u32 = undefined;
var x128: u32 = undefined;
mulxU32(&x127, &x128, x1, (arg2[9]));
var x129: u32 = undefined;
var x130: u32 = undefined;
mulxU32(&x129, &x130, x1, (arg2[8]));
var x131: u32 = undefined;
var x132: u32 = undefined;
mulxU32(&x131, &x132, x1, (arg2[7]));
var x133: u32 = undefined;
var x134: u32 = undefined;
mulxU32(&x133, &x134, x1, (arg2[6]));
var x135: u32 = undefined;
var x136: u32 = undefined;
mulxU32(&x135, &x136, x1, (arg2[5]));
var x137: u32 = undefined;
var x138: u32 = undefined;
mulxU32(&x137, &x138, x1, (arg2[4]));
var x139: u32 = undefined;
var x140: u32 = undefined;
mulxU32(&x139, &x140, x1, (arg2[3]));
var x141: u32 = undefined;
var x142: u32 = undefined;
mulxU32(&x141, &x142, x1, (arg2[2]));
var x143: u32 = undefined;
var x144: u32 = undefined;
mulxU32(&x143, &x144, x1, (arg2[1]));
var x145: u32 = undefined;
var x146: u32 = undefined;
mulxU32(&x145, &x146, x1, (arg2[0]));
var x147: u32 = undefined;
var x148: u1 = undefined;
addcarryxU32(&x147, &x148, 0x0, x146, x143);
var x149: u32 = undefined;
var x150: u1 = undefined;
addcarryxU32(&x149, &x150, x148, x144, x141);
var x151: u32 = undefined;
var x152: u1 = undefined;
addcarryxU32(&x151, &x152, x150, x142, x139);
var x153: u32 = undefined;
var x154: u1 = undefined;
addcarryxU32(&x153, &x154, x152, x140, x137);
var x155: u32 = undefined;
var x156: u1 = undefined;
addcarryxU32(&x155, &x156, x154, x138, x135);
var x157: u32 = undefined;
var x158: u1 = undefined;
addcarryxU32(&x157, &x158, x156, x136, x133);
var x159: u32 = undefined;
var x160: u1 = undefined;
addcarryxU32(&x159, &x160, x158, x134, x131);
var x161: u32 = undefined;
var x162: u1 = undefined;
addcarryxU32(&x161, &x162, x160, x132, x129);
var x163: u32 = undefined;
var x164: u1 = undefined;
addcarryxU32(&x163, &x164, x162, x130, x127);
var x165: u32 = undefined;
var x166: u1 = undefined;
addcarryxU32(&x165, &x166, x164, x128, x125);
var x167: u32 = undefined;
var x168: u1 = undefined;
addcarryxU32(&x167, &x168, x166, x126, x123);
const x169 = (cast(u32, x168) + x124);
var x170: u32 = undefined;
var x171: u1 = undefined;
addcarryxU32(&x170, &x171, 0x0, x99, x145);
var x172: u32 = undefined;
var x173: u1 = undefined;
addcarryxU32(&x172, &x173, x171, x101, x147);
var x174: u32 = undefined;
var x175: u1 = undefined;
addcarryxU32(&x174, &x175, x173, x103, x149);
var x176: u32 = undefined;
var x177: u1 = undefined;
addcarryxU32(&x176, &x177, x175, x105, x151);
var x178: u32 = undefined;
var x179: u1 = undefined;
addcarryxU32(&x178, &x179, x177, x107, x153);
var x180: u32 = undefined;
var x181: u1 = undefined;
addcarryxU32(&x180, &x181, x179, x109, x155);
var x182: u32 = undefined;
var x183: u1 = undefined;
addcarryxU32(&x182, &x183, x181, x111, x157);
var x184: u32 = undefined;
var x185: u1 = undefined;
addcarryxU32(&x184, &x185, x183, x113, x159);
var x186: u32 = undefined;
var x187: u1 = undefined;
addcarryxU32(&x186, &x187, x185, x115, x161);
var x188: u32 = undefined;
var x189: u1 = undefined;
addcarryxU32(&x188, &x189, x187, x117, x163);
var x190: u32 = undefined;
var x191: u1 = undefined;
addcarryxU32(&x190, &x191, x189, x119, x165);
var x192: u32 = undefined;
var x193: u1 = undefined;
addcarryxU32(&x192, &x193, x191, x121, x167);
var x194: u32 = undefined;
var x195: u1 = undefined;
addcarryxU32(&x194, &x195, x193, cast(u32, x122), x169);
var x196: u32 = undefined;
var x197: u32 = undefined;
mulxU32(&x196, &x197, x170, 0xffffffff);
var x198: u32 = undefined;
var x199: u32 = undefined;
mulxU32(&x198, &x199, x170, 0xffffffff);
var x200: u32 = undefined;
var x201: u32 = undefined;
mulxU32(&x200, &x201, x170, 0xffffffff);
var x202: u32 = undefined;
var x203: u32 = undefined;
mulxU32(&x202, &x203, x170, 0xffffffff);
var x204: u32 = undefined;
var x205: u32 = undefined;
mulxU32(&x204, &x205, x170, 0xffffffff);
var x206: u32 = undefined;
var x207: u32 = undefined;
mulxU32(&x206, &x207, x170, 0xffffffff);
var x208: u32 = undefined;
var x209: u32 = undefined;
mulxU32(&x208, &x209, x170, 0xffffffff);
var x210: u32 = undefined;
var x211: u32 = undefined;
mulxU32(&x210, &x211, x170, 0xfffffffe);
var x212: u32 = undefined;
var x213: u32 = undefined;
mulxU32(&x212, &x213, x170, 0xffffffff);
var x214: u32 = undefined;
var x215: u32 = undefined;
mulxU32(&x214, &x215, x170, 0xffffffff);
var x216: u32 = undefined;
var x217: u1 = undefined;
addcarryxU32(&x216, &x217, 0x0, x213, x210);
var x218: u32 = undefined;
var x219: u1 = undefined;
addcarryxU32(&x218, &x219, x217, x211, x208);
var x220: u32 = undefined;
var x221: u1 = undefined;
addcarryxU32(&x220, &x221, x219, x209, x206);
var x222: u32 = undefined;
var x223: u1 = undefined;
addcarryxU32(&x222, &x223, x221, x207, x204);
var x224: u32 = undefined;
var x225: u1 = undefined;
addcarryxU32(&x224, &x225, x223, x205, x202);
var x226: u32 = undefined;
var x227: u1 = undefined;
addcarryxU32(&x226, &x227, x225, x203, x200);
var x228: u32 = undefined;
var x229: u1 = undefined;
addcarryxU32(&x228, &x229, x227, x201, x198);
var x230: u32 = undefined;
var x231: u1 = undefined;
addcarryxU32(&x230, &x231, x229, x199, x196);
const x232 = (cast(u32, x231) + x197);
var x233: u32 = undefined;
var x234: u1 = undefined;
addcarryxU32(&x233, &x234, 0x0, x170, x214);
var x235: u32 = undefined;
var x236: u1 = undefined;
addcarryxU32(&x235, &x236, x234, x172, x215);
var x237: u32 = undefined;
var x238: u1 = undefined;
addcarryxU32(&x237, &x238, x236, x174, cast(u32, 0x0));
var x239: u32 = undefined;
var x240: u1 = undefined;
addcarryxU32(&x239, &x240, x238, x176, x212);
var x241: u32 = undefined;
var x242: u1 = undefined;
addcarryxU32(&x241, &x242, x240, x178, x216);
var x243: u32 = undefined;
var x244: u1 = undefined;
addcarryxU32(&x243, &x244, x242, x180, x218);
var x245: u32 = undefined;
var x246: u1 = undefined;
addcarryxU32(&x245, &x246, x244, x182, x220);
var x247: u32 = undefined;
var x248: u1 = undefined;
addcarryxU32(&x247, &x248, x246, x184, x222);
var x249: u32 = undefined;
var x250: u1 = undefined;
addcarryxU32(&x249, &x250, x248, x186, x224);
var x251: u32 = undefined;
var x252: u1 = undefined;
addcarryxU32(&x251, &x252, x250, x188, x226);
var x253: u32 = undefined;
var x254: u1 = undefined;
addcarryxU32(&x253, &x254, x252, x190, x228);
var x255: u32 = undefined;
var x256: u1 = undefined;
addcarryxU32(&x255, &x256, x254, x192, x230);
var x257: u32 = undefined;
var x258: u1 = undefined;
addcarryxU32(&x257, &x258, x256, x194, x232);
const x259 = (cast(u32, x258) + cast(u32, x195));
var x260: u32 = undefined;
var x261: u32 = undefined;
mulxU32(&x260, &x261, x2, (arg2[11]));
var x262: u32 = undefined;
var x263: u32 = undefined;
mulxU32(&x262, &x263, x2, (arg2[10]));
var x264: u32 = undefined;
var x265: u32 = undefined;
mulxU32(&x264, &x265, x2, (arg2[9]));
var x266: u32 = undefined;
var x267: u32 = undefined;
mulxU32(&x266, &x267, x2, (arg2[8]));
var x268: u32 = undefined;
var x269: u32 = undefined;
mulxU32(&x268, &x269, x2, (arg2[7]));
var x270: u32 = undefined;
var x271: u32 = undefined;
mulxU32(&x270, &x271, x2, (arg2[6]));
var x272: u32 = undefined;
var x273: u32 = undefined;
mulxU32(&x272, &x273, x2, (arg2[5]));
var x274: u32 = undefined;
var x275: u32 = undefined;
mulxU32(&x274, &x275, x2, (arg2[4]));
var x276: u32 = undefined;
var x277: u32 = undefined;
mulxU32(&x276, &x277, x2, (arg2[3]));
var x278: u32 = undefined;
var x279: u32 = undefined;
mulxU32(&x278, &x279, x2, (arg2[2]));
var x280: u32 = undefined;
var x281: u32 = undefined;
mulxU32(&x280, &x281, x2, (arg2[1]));
var x282: u32 = undefined;
var x283: u32 = undefined;
mulxU32(&x282, &x283, x2, (arg2[0]));
var x284: u32 = undefined;
var x285: u1 = undefined;
addcarryxU32(&x284, &x285, 0x0, x283, x280);
var x286: u32 = undefined;
var x287: u1 = undefined;
addcarryxU32(&x286, &x287, x285, x281, x278);
var x288: u32 = undefined;
var x289: u1 = undefined;
addcarryxU32(&x288, &x289, x287, x279, x276);
var x290: u32 = undefined;
var x291: u1 = undefined;
addcarryxU32(&x290, &x291, x289, x277, x274);
var x292: u32 = undefined;
var x293: u1 = undefined;
addcarryxU32(&x292, &x293, x291, x275, x272);
var x294: u32 = undefined;
var x295: u1 = undefined;
addcarryxU32(&x294, &x295, x293, x273, x270);
var x296: u32 = undefined;
var x297: u1 = undefined;
addcarryxU32(&x296, &x297, x295, x271, x268);
var x298: u32 = undefined;
var x299: u1 = undefined;
addcarryxU32(&x298, &x299, x297, x269, x266);
var x300: u32 = undefined;
var x301: u1 = undefined;
addcarryxU32(&x300, &x301, x299, x267, x264);
var x302: u32 = undefined;
var x303: u1 = undefined;
addcarryxU32(&x302, &x303, x301, x265, x262);
var x304: u32 = undefined;
var x305: u1 = undefined;
addcarryxU32(&x304, &x305, x303, x263, x260);
const x306 = (cast(u32, x305) + x261);
var x307: u32 = undefined;
var x308: u1 = undefined;
addcarryxU32(&x307, &x308, 0x0, x235, x282);
var x309: u32 = undefined;
var x310: u1 = undefined;
addcarryxU32(&x309, &x310, x308, x237, x284);
var x311: u32 = undefined;
var x312: u1 = undefined;
addcarryxU32(&x311, &x312, x310, x239, x286);
var x313: u32 = undefined;
var x314: u1 = undefined;
addcarryxU32(&x313, &x314, x312, x241, x288);
var x315: u32 = undefined;
var x316: u1 = undefined;
addcarryxU32(&x315, &x316, x314, x243, x290);
var x317: u32 = undefined;
var x318: u1 = undefined;
addcarryxU32(&x317, &x318, x316, x245, x292);
var x319: u32 = undefined;
var x320: u1 = undefined;
addcarryxU32(&x319, &x320, x318, x247, x294);
var x321: u32 = undefined;
var x322: u1 = undefined;
addcarryxU32(&x321, &x322, x320, x249, x296);
var x323: u32 = undefined;
var x324: u1 = undefined;
addcarryxU32(&x323, &x324, x322, x251, x298);
var x325: u32 = undefined;
var x326: u1 = undefined;
addcarryxU32(&x325, &x326, x324, x253, x300);
var x327: u32 = undefined;
var x328: u1 = undefined;
addcarryxU32(&x327, &x328, x326, x255, x302);
var x329: u32 = undefined;
var x330: u1 = undefined;
addcarryxU32(&x329, &x330, x328, x257, x304);
var x331: u32 = undefined;
var x332: u1 = undefined;
addcarryxU32(&x331, &x332, x330, x259, x306);
var x333: u32 = undefined;
var x334: u32 = undefined;
mulxU32(&x333, &x334, x307, 0xffffffff);
var x335: u32 = undefined;
var x336: u32 = undefined;
mulxU32(&x335, &x336, x307, 0xffffffff);
var x337: u32 = undefined;
var x338: u32 = undefined;
mulxU32(&x337, &x338, x307, 0xffffffff);
var x339: u32 = undefined;
var x340: u32 = undefined;
mulxU32(&x339, &x340, x307, 0xffffffff);
var x341: u32 = undefined;
var x342: u32 = undefined;
mulxU32(&x341, &x342, x307, 0xffffffff);
var x343: u32 = undefined;
var x344: u32 = undefined;
mulxU32(&x343, &x344, x307, 0xffffffff);
var x345: u32 = undefined;
var x346: u32 = undefined;
mulxU32(&x345, &x346, x307, 0xffffffff);
var x347: u32 = undefined;
var x348: u32 = undefined;
mulxU32(&x347, &x348, x307, 0xfffffffe);
var x349: u32 = undefined;
var x350: u32 = undefined;
mulxU32(&x349, &x350, x307, 0xffffffff);
var x351: u32 = undefined;
var x352: u32 = undefined;
mulxU32(&x351, &x352, x307, 0xffffffff);
var x353: u32 = undefined;
var x354: u1 = undefined;
addcarryxU32(&x353, &x354, 0x0, x350, x347);
var x355: u32 = undefined;
var x356: u1 = undefined;
addcarryxU32(&x355, &x356, x354, x348, x345);
var x357: u32 = undefined;
var x358: u1 = undefined;
addcarryxU32(&x357, &x358, x356, x346, x343);
var x359: u32 = undefined;
var x360: u1 = undefined;
addcarryxU32(&x359, &x360, x358, x344, x341);
var x361: u32 = undefined;
var x362: u1 = undefined;
addcarryxU32(&x361, &x362, x360, x342, x339);
var x363: u32 = undefined;
var x364: u1 = undefined;
addcarryxU32(&x363, &x364, x362, x340, x337);
var x365: u32 = undefined;
var x366: u1 = undefined;
addcarryxU32(&x365, &x366, x364, x338, x335);
var x367: u32 = undefined;
var x368: u1 = undefined;
addcarryxU32(&x367, &x368, x366, x336, x333);
const x369 = (cast(u32, x368) + x334);
var x370: u32 = undefined;
var x371: u1 = undefined;
addcarryxU32(&x370, &x371, 0x0, x307, x351);
var x372: u32 = undefined;
var x373: u1 = undefined;
addcarryxU32(&x372, &x373, x371, x309, x352);
var x374: u32 = undefined;
var x375: u1 = undefined;
addcarryxU32(&x374, &x375, x373, x311, cast(u32, 0x0));
var x376: u32 = undefined;
var x377: u1 = undefined;
addcarryxU32(&x376, &x377, x375, x313, x349);
var x378: u32 = undefined;
var x379: u1 = undefined;
addcarryxU32(&x378, &x379, x377, x315, x353);
var x380: u32 = undefined;
var x381: u1 = undefined;
addcarryxU32(&x380, &x381, x379, x317, x355);
var x382: u32 = undefined;
var x383: u1 = undefined;
addcarryxU32(&x382, &x383, x381, x319, x357);
var x384: u32 = undefined;
var x385: u1 = undefined;
addcarryxU32(&x384, &x385, x383, x321, x359);
var x386: u32 = undefined;
var x387: u1 = undefined;
addcarryxU32(&x386, &x387, x385, x323, x361);
var x388: u32 = undefined;
var x389: u1 = undefined;
addcarryxU32(&x388, &x389, x387, x325, x363);
var x390: u32 = undefined;
var x391: u1 = undefined;
addcarryxU32(&x390, &x391, x389, x327, x365);
var x392: u32 = undefined;
var x393: u1 = undefined;
addcarryxU32(&x392, &x393, x391, x329, x367);
var x394: u32 = undefined;
var x395: u1 = undefined;
addcarryxU32(&x394, &x395, x393, x331, x369);
const x396 = (cast(u32, x395) + cast(u32, x332));
var x397: u32 = undefined;
var x398: u32 = undefined;
mulxU32(&x397, &x398, x3, (arg2[11]));
var x399: u32 = undefined;
var x400: u32 = undefined;
mulxU32(&x399, &x400, x3, (arg2[10]));
var x401: u32 = undefined;
var x402: u32 = undefined;
mulxU32(&x401, &x402, x3, (arg2[9]));
var x403: u32 = undefined;
var x404: u32 = undefined;
mulxU32(&x403, &x404, x3, (arg2[8]));
var x405: u32 = undefined;
var x406: u32 = undefined;
mulxU32(&x405, &x406, x3, (arg2[7]));
var x407: u32 = undefined;
var x408: u32 = undefined;
mulxU32(&x407, &x408, x3, (arg2[6]));
var x409: u32 = undefined;
var x410: u32 = undefined;
mulxU32(&x409, &x410, x3, (arg2[5]));
var x411: u32 = undefined;
var x412: u32 = undefined;
mulxU32(&x411, &x412, x3, (arg2[4]));
var x413: u32 = undefined;
var x414: u32 = undefined;
mulxU32(&x413, &x414, x3, (arg2[3]));
var x415: u32 = undefined;
var x416: u32 = undefined;
mulxU32(&x415, &x416, x3, (arg2[2]));
var x417: u32 = undefined;
var x418: u32 = undefined;
mulxU32(&x417, &x418, x3, (arg2[1]));
var x419: u32 = undefined;
var x420: u32 = undefined;
mulxU32(&x419, &x420, x3, (arg2[0]));
var x421: u32 = undefined;
var x422: u1 = undefined;
addcarryxU32(&x421, &x422, 0x0, x420, x417);
var x423: u32 = undefined;
var x424: u1 = undefined;
addcarryxU32(&x423, &x424, x422, x418, x415);
var x425: u32 = undefined;
var x426: u1 = undefined;
addcarryxU32(&x425, &x426, x424, x416, x413);
var x427: u32 = undefined;
var x428: u1 = undefined;
addcarryxU32(&x427, &x428, x426, x414, x411);
var x429: u32 = undefined;
var x430: u1 = undefined;
addcarryxU32(&x429, &x430, x428, x412, x409);
var x431: u32 = undefined;
var x432: u1 = undefined;
addcarryxU32(&x431, &x432, x430, x410, x407);
var x433: u32 = undefined;
var x434: u1 = undefined;
addcarryxU32(&x433, &x434, x432, x408, x405);
var x435: u32 = undefined;
var x436: u1 = undefined;
addcarryxU32(&x435, &x436, x434, x406, x403);
var x437: u32 = undefined;
var x438: u1 = undefined;
addcarryxU32(&x437, &x438, x436, x404, x401);
var x439: u32 = undefined;
var x440: u1 = undefined;
addcarryxU32(&x439, &x440, x438, x402, x399);
var x441: u32 = undefined;
var x442: u1 = undefined;
addcarryxU32(&x441, &x442, x440, x400, x397);
const x443 = (cast(u32, x442) + x398);
var x444: u32 = undefined;
var x445: u1 = undefined;
addcarryxU32(&x444, &x445, 0x0, x372, x419);
var x446: u32 = undefined;
var x447: u1 = undefined;
addcarryxU32(&x446, &x447, x445, x374, x421);
var x448: u32 = undefined;
var x449: u1 = undefined;
addcarryxU32(&x448, &x449, x447, x376, x423);
var x450: u32 = undefined;
var x451: u1 = undefined;
addcarryxU32(&x450, &x451, x449, x378, x425);
var x452: u32 = undefined;
var x453: u1 = undefined;
addcarryxU32(&x452, &x453, x451, x380, x427);
var x454: u32 = undefined;
var x455: u1 = undefined;
addcarryxU32(&x454, &x455, x453, x382, x429);
var x456: u32 = undefined;
var x457: u1 = undefined;
addcarryxU32(&x456, &x457, x455, x384, x431);
var x458: u32 = undefined;
var x459: u1 = undefined;
addcarryxU32(&x458, &x459, x457, x386, x433);
var x460: u32 = undefined;
var x461: u1 = undefined;
addcarryxU32(&x460, &x461, x459, x388, x435);
var x462: u32 = undefined;
var x463: u1 = undefined;
addcarryxU32(&x462, &x463, x461, x390, x437);
var x464: u32 = undefined;
var x465: u1 = undefined;
addcarryxU32(&x464, &x465, x463, x392, x439);
var x466: u32 = undefined;
var x467: u1 = undefined;
addcarryxU32(&x466, &x467, x465, x394, x441);
var x468: u32 = undefined;
var x469: u1 = undefined;
addcarryxU32(&x468, &x469, x467, x396, x443);
var x470: u32 = undefined;
var x471: u32 = undefined;
mulxU32(&x470, &x471, x444, 0xffffffff);
var x472: u32 = undefined;
var x473: u32 = undefined;
mulxU32(&x472, &x473, x444, 0xffffffff);
var x474: u32 = undefined;
var x475: u32 = undefined;
mulxU32(&x474, &x475, x444, 0xffffffff);
var x476: u32 = undefined;
var x477: u32 = undefined;
mulxU32(&x476, &x477, x444, 0xffffffff);
var x478: u32 = undefined;
var x479: u32 = undefined;
mulxU32(&x478, &x479, x444, 0xffffffff);
var x480: u32 = undefined;
var x481: u32 = undefined;
mulxU32(&x480, &x481, x444, 0xffffffff);
var x482: u32 = undefined;
var x483: u32 = undefined;
mulxU32(&x482, &x483, x444, 0xffffffff);
var x484: u32 = undefined;
var x485: u32 = undefined;
mulxU32(&x484, &x485, x444, 0xfffffffe);
var x486: u32 = undefined;
var x487: u32 = undefined;
mulxU32(&x486, &x487, x444, 0xffffffff);
var x488: u32 = undefined;
var x489: u32 = undefined;
mulxU32(&x488, &x489, x444, 0xffffffff);
var x490: u32 = undefined;
var x491: u1 = undefined;
addcarryxU32(&x490, &x491, 0x0, x487, x484);
var x492: u32 = undefined;
var x493: u1 = undefined;
addcarryxU32(&x492, &x493, x491, x485, x482);
var x494: u32 = undefined;
var x495: u1 = undefined;
addcarryxU32(&x494, &x495, x493, x483, x480);
var x496: u32 = undefined;
var x497: u1 = undefined;
addcarryxU32(&x496, &x497, x495, x481, x478);
var x498: u32 = undefined;
var x499: u1 = undefined;
addcarryxU32(&x498, &x499, x497, x479, x476);
var x500: u32 = undefined;
var x501: u1 = undefined;
addcarryxU32(&x500, &x501, x499, x477, x474);
var x502: u32 = undefined;
var x503: u1 = undefined;
addcarryxU32(&x502, &x503, x501, x475, x472);
var x504: u32 = undefined;
var x505: u1 = undefined;
addcarryxU32(&x504, &x505, x503, x473, x470);
const x506 = (cast(u32, x505) + x471);
var x507: u32 = undefined;
var x508: u1 = undefined;
addcarryxU32(&x507, &x508, 0x0, x444, x488);
var x509: u32 = undefined;
var x510: u1 = undefined;
addcarryxU32(&x509, &x510, x508, x446, x489);
var x511: u32 = undefined;
var x512: u1 = undefined;
addcarryxU32(&x511, &x512, x510, x448, cast(u32, 0x0));
var x513: u32 = undefined;
var x514: u1 = undefined;
addcarryxU32(&x513, &x514, x512, x450, x486);
var x515: u32 = undefined;
var x516: u1 = undefined;
addcarryxU32(&x515, &x516, x514, x452, x490);
var x517: u32 = undefined;
var x518: u1 = undefined;
addcarryxU32(&x517, &x518, x516, x454, x492);
var x519: u32 = undefined;
var x520: u1 = undefined;
addcarryxU32(&x519, &x520, x518, x456, x494);
var x521: u32 = undefined;
var x522: u1 = undefined;
addcarryxU32(&x521, &x522, x520, x458, x496);
var x523: u32 = undefined;
var x524: u1 = undefined;
addcarryxU32(&x523, &x524, x522, x460, x498);
var x525: u32 = undefined;
var x526: u1 = undefined;
addcarryxU32(&x525, &x526, x524, x462, x500);
var x527: u32 = undefined;
var x528: u1 = undefined;
addcarryxU32(&x527, &x528, x526, x464, x502);
var x529: u32 = undefined;
var x530: u1 = undefined;
addcarryxU32(&x529, &x530, x528, x466, x504);
var x531: u32 = undefined;
var x532: u1 = undefined;
addcarryxU32(&x531, &x532, x530, x468, x506);
const x533 = (cast(u32, x532) + cast(u32, x469));
var x534: u32 = undefined;
var x535: u32 = undefined;
mulxU32(&x534, &x535, x4, (arg2[11]));
var x536: u32 = undefined;
var x537: u32 = undefined;
mulxU32(&x536, &x537, x4, (arg2[10]));
var x538: u32 = undefined;
var x539: u32 = undefined;
mulxU32(&x538, &x539, x4, (arg2[9]));
var x540: u32 = undefined;
var x541: u32 = undefined;
mulxU32(&x540, &x541, x4, (arg2[8]));
var x542: u32 = undefined;
var x543: u32 = undefined;
mulxU32(&x542, &x543, x4, (arg2[7]));
var x544: u32 = undefined;
var x545: u32 = undefined;
mulxU32(&x544, &x545, x4, (arg2[6]));
var x546: u32 = undefined;
var x547: u32 = undefined;
mulxU32(&x546, &x547, x4, (arg2[5]));
var x548: u32 = undefined;
var x549: u32 = undefined;
mulxU32(&x548, &x549, x4, (arg2[4]));
var x550: u32 = undefined;
var x551: u32 = undefined;
mulxU32(&x550, &x551, x4, (arg2[3]));
var x552: u32 = undefined;
var x553: u32 = undefined;
mulxU32(&x552, &x553, x4, (arg2[2]));
var x554: u32 = undefined;
var x555: u32 = undefined;
mulxU32(&x554, &x555, x4, (arg2[1]));
var x556: u32 = undefined;
var x557: u32 = undefined;
mulxU32(&x556, &x557, x4, (arg2[0]));
var x558: u32 = undefined;
var x559: u1 = undefined;
addcarryxU32(&x558, &x559, 0x0, x557, x554);
var x560: u32 = undefined;
var x561: u1 = undefined;
addcarryxU32(&x560, &x561, x559, x555, x552);
var x562: u32 = undefined;
var x563: u1 = undefined;
addcarryxU32(&x562, &x563, x561, x553, x550);
var x564: u32 = undefined;
var x565: u1 = undefined;
addcarryxU32(&x564, &x565, x563, x551, x548);
var x566: u32 = undefined;
var x567: u1 = undefined;
addcarryxU32(&x566, &x567, x565, x549, x546);
var x568: u32 = undefined;
var x569: u1 = undefined;
addcarryxU32(&x568, &x569, x567, x547, x544);
var x570: u32 = undefined;
var x571: u1 = undefined;
addcarryxU32(&x570, &x571, x569, x545, x542);
var x572: u32 = undefined;
var x573: u1 = undefined;
addcarryxU32(&x572, &x573, x571, x543, x540);
var x574: u32 = undefined;
var x575: u1 = undefined;
addcarryxU32(&x574, &x575, x573, x541, x538);
var x576: u32 = undefined;
var x577: u1 = undefined;
addcarryxU32(&x576, &x577, x575, x539, x536);
var x578: u32 = undefined;
var x579: u1 = undefined;
addcarryxU32(&x578, &x579, x577, x537, x534);
const x580 = (cast(u32, x579) + x535);
var x581: u32 = undefined;
var x582: u1 = undefined;
addcarryxU32(&x581, &x582, 0x0, x509, x556);
var x583: u32 = undefined;
var x584: u1 = undefined;
addcarryxU32(&x583, &x584, x582, x511, x558);
var x585: u32 = undefined;
var x586: u1 = undefined;
addcarryxU32(&x585, &x586, x584, x513, x560);
var x587: u32 = undefined;
var x588: u1 = undefined;
addcarryxU32(&x587, &x588, x586, x515, x562);
var x589: u32 = undefined;
var x590: u1 = undefined;
addcarryxU32(&x589, &x590, x588, x517, x564);
var x591: u32 = undefined;
var x592: u1 = undefined;
addcarryxU32(&x591, &x592, x590, x519, x566);
var x593: u32 = undefined;
var x594: u1 = undefined;
addcarryxU32(&x593, &x594, x592, x521, x568);
var x595: u32 = undefined;
var x596: u1 = undefined;
addcarryxU32(&x595, &x596, x594, x523, x570);
var x597: u32 = undefined;
var x598: u1 = undefined;
addcarryxU32(&x597, &x598, x596, x525, x572);
var x599: u32 = undefined;
var x600: u1 = undefined;
addcarryxU32(&x599, &x600, x598, x527, x574);
var x601: u32 = undefined;
var x602: u1 = undefined;
addcarryxU32(&x601, &x602, x600, x529, x576);
var x603: u32 = undefined;
var x604: u1 = undefined;
addcarryxU32(&x603, &x604, x602, x531, x578);
var x605: u32 = undefined;
var x606: u1 = undefined;
addcarryxU32(&x605, &x606, x604, x533, x580);
var x607: u32 = undefined;
var x608: u32 = undefined;
mulxU32(&x607, &x608, x581, 0xffffffff);
var x609: u32 = undefined;
var x610: u32 = undefined;
mulxU32(&x609, &x610, x581, 0xffffffff);
var x611: u32 = undefined;
var x612: u32 = undefined;
mulxU32(&x611, &x612, x581, 0xffffffff);
var x613: u32 = undefined;
var x614: u32 = undefined;
mulxU32(&x613, &x614, x581, 0xffffffff);
var x615: u32 = undefined;
var x616: u32 = undefined;
mulxU32(&x615, &x616, x581, 0xffffffff);
var x617: u32 = undefined;
var x618: u32 = undefined;
mulxU32(&x617, &x618, x581, 0xffffffff);
var x619: u32 = undefined;
var x620: u32 = undefined;
mulxU32(&x619, &x620, x581, 0xffffffff);
var x621: u32 = undefined;
var x622: u32 = undefined;
mulxU32(&x621, &x622, x581, 0xfffffffe);
var x623: u32 = undefined;
var x624: u32 = undefined;
mulxU32(&x623, &x624, x581, 0xffffffff);
var x625: u32 = undefined;
var x626: u32 = undefined;
mulxU32(&x625, &x626, x581, 0xffffffff);
var x627: u32 = undefined;
var x628: u1 = undefined;
addcarryxU32(&x627, &x628, 0x0, x624, x621);
var x629: u32 = undefined;
var x630: u1 = undefined;
addcarryxU32(&x629, &x630, x628, x622, x619);
var x631: u32 = undefined;
var x632: u1 = undefined;
addcarryxU32(&x631, &x632, x630, x620, x617);
var x633: u32 = undefined;
var x634: u1 = undefined;
addcarryxU32(&x633, &x634, x632, x618, x615);
var x635: u32 = undefined;
var x636: u1 = undefined;
addcarryxU32(&x635, &x636, x634, x616, x613);
var x637: u32 = undefined;
var x638: u1 = undefined;
addcarryxU32(&x637, &x638, x636, x614, x611);
var x639: u32 = undefined;
var x640: u1 = undefined;
addcarryxU32(&x639, &x640, x638, x612, x609);
var x641: u32 = undefined;
var x642: u1 = undefined;
addcarryxU32(&x641, &x642, x640, x610, x607);
const x643 = (cast(u32, x642) + x608);
var x644: u32 = undefined;
var x645: u1 = undefined;
addcarryxU32(&x644, &x645, 0x0, x581, x625);
var x646: u32 = undefined;
var x647: u1 = undefined;
addcarryxU32(&x646, &x647, x645, x583, x626);
var x648: u32 = undefined;
var x649: u1 = undefined;
addcarryxU32(&x648, &x649, x647, x585, cast(u32, 0x0));
var x650: u32 = undefined;
var x651: u1 = undefined;
addcarryxU32(&x650, &x651, x649, x587, x623);
var x652: u32 = undefined;
var x653: u1 = undefined;
addcarryxU32(&x652, &x653, x651, x589, x627);
var x654: u32 = undefined;
var x655: u1 = undefined;
addcarryxU32(&x654, &x655, x653, x591, x629);
var x656: u32 = undefined;
var x657: u1 = undefined;
addcarryxU32(&x656, &x657, x655, x593, x631);
var x658: u32 = undefined;
var x659: u1 = undefined;
addcarryxU32(&x658, &x659, x657, x595, x633);
var x660: u32 = undefined;
var x661: u1 = undefined;
addcarryxU32(&x660, &x661, x659, x597, x635);
var x662: u32 = undefined;
var x663: u1 = undefined;
addcarryxU32(&x662, &x663, x661, x599, x637);
var x664: u32 = undefined;
var x665: u1 = undefined;
addcarryxU32(&x664, &x665, x663, x601, x639);
var x666: u32 = undefined;
var x667: u1 = undefined;
addcarryxU32(&x666, &x667, x665, x603, x641);
var x668: u32 = undefined;
var x669: u1 = undefined;
addcarryxU32(&x668, &x669, x667, x605, x643);
const x670 = (cast(u32, x669) + cast(u32, x606));
var x671: u32 = undefined;
var x672: u32 = undefined;
mulxU32(&x671, &x672, x5, (arg2[11]));
var x673: u32 = undefined;
var x674: u32 = undefined;
mulxU32(&x673, &x674, x5, (arg2[10]));
var x675: u32 = undefined;
var x676: u32 = undefined;
mulxU32(&x675, &x676, x5, (arg2[9]));
var x677: u32 = undefined;
var x678: u32 = undefined;
mulxU32(&x677, &x678, x5, (arg2[8]));
var x679: u32 = undefined;
var x680: u32 = undefined;
mulxU32(&x679, &x680, x5, (arg2[7]));
var x681: u32 = undefined;
var x682: u32 = undefined;
mulxU32(&x681, &x682, x5, (arg2[6]));
var x683: u32 = undefined;
var x684: u32 = undefined;
mulxU32(&x683, &x684, x5, (arg2[5]));
var x685: u32 = undefined;
var x686: u32 = undefined;
mulxU32(&x685, &x686, x5, (arg2[4]));
var x687: u32 = undefined;
var x688: u32 = undefined;
mulxU32(&x687, &x688, x5, (arg2[3]));
var x689: u32 = undefined;
var x690: u32 = undefined;
mulxU32(&x689, &x690, x5, (arg2[2]));
var x691: u32 = undefined;
var x692: u32 = undefined;
mulxU32(&x691, &x692, x5, (arg2[1]));
var x693: u32 = undefined;
var x694: u32 = undefined;
mulxU32(&x693, &x694, x5, (arg2[0]));
var x695: u32 = undefined;
var x696: u1 = undefined;
addcarryxU32(&x695, &x696, 0x0, x694, x691);
var x697: u32 = undefined;
var x698: u1 = undefined;
addcarryxU32(&x697, &x698, x696, x692, x689);
var x699: u32 = undefined;
var x700: u1 = undefined;
addcarryxU32(&x699, &x700, x698, x690, x687);
var x701: u32 = undefined;
var x702: u1 = undefined;
addcarryxU32(&x701, &x702, x700, x688, x685);
var x703: u32 = undefined;
var x704: u1 = undefined;
addcarryxU32(&x703, &x704, x702, x686, x683);
var x705: u32 = undefined;
var x706: u1 = undefined;
addcarryxU32(&x705, &x706, x704, x684, x681);
var x707: u32 = undefined;
var x708: u1 = undefined;
addcarryxU32(&x707, &x708, x706, x682, x679);
var x709: u32 = undefined;
var x710: u1 = undefined;
addcarryxU32(&x709, &x710, x708, x680, x677);
var x711: u32 = undefined;
var x712: u1 = undefined;
addcarryxU32(&x711, &x712, x710, x678, x675);
var x713: u32 = undefined;
var x714: u1 = undefined;
addcarryxU32(&x713, &x714, x712, x676, x673);
var x715: u32 = undefined;
var x716: u1 = undefined;
addcarryxU32(&x715, &x716, x714, x674, x671);
const x717 = (cast(u32, x716) + x672);
var x718: u32 = undefined;
var x719: u1 = undefined;
addcarryxU32(&x718, &x719, 0x0, x646, x693);
var x720: u32 = undefined;
var x721: u1 = undefined;
addcarryxU32(&x720, &x721, x719, x648, x695);
var x722: u32 = undefined;
var x723: u1 = undefined;
addcarryxU32(&x722, &x723, x721, x650, x697);
var x724: u32 = undefined;
var x725: u1 = undefined;
addcarryxU32(&x724, &x725, x723, x652, x699);
var x726: u32 = undefined;
var x727: u1 = undefined;
addcarryxU32(&x726, &x727, x725, x654, x701);
var x728: u32 = undefined;
var x729: u1 = undefined;
addcarryxU32(&x728, &x729, x727, x656, x703);
var x730: u32 = undefined;
var x731: u1 = undefined;
addcarryxU32(&x730, &x731, x729, x658, x705);
var x732: u32 = undefined;
var x733: u1 = undefined;
addcarryxU32(&x732, &x733, x731, x660, x707);
var x734: u32 = undefined;
var x735: u1 = undefined;
addcarryxU32(&x734, &x735, x733, x662, x709);
var x736: u32 = undefined;
var x737: u1 = undefined;
addcarryxU32(&x736, &x737, x735, x664, x711);
var x738: u32 = undefined;
var x739: u1 = undefined;
addcarryxU32(&x738, &x739, x737, x666, x713);
var x740: u32 = undefined;
var x741: u1 = undefined;
addcarryxU32(&x740, &x741, x739, x668, x715);
var x742: u32 = undefined;
var x743: u1 = undefined;
addcarryxU32(&x742, &x743, x741, x670, x717);
var x744: u32 = undefined;
var x745: u32 = undefined;
mulxU32(&x744, &x745, x718, 0xffffffff);
var x746: u32 = undefined;
var x747: u32 = undefined;
mulxU32(&x746, &x747, x718, 0xffffffff);
var x748: u32 = undefined;
var x749: u32 = undefined;
mulxU32(&x748, &x749, x718, 0xffffffff);
var x750: u32 = undefined;
var x751: u32 = undefined;
mulxU32(&x750, &x751, x718, 0xffffffff);
var x752: u32 = undefined;
var x753: u32 = undefined;
mulxU32(&x752, &x753, x718, 0xffffffff);
var x754: u32 = undefined;
var x755: u32 = undefined;
mulxU32(&x754, &x755, x718, 0xffffffff);
var x756: u32 = undefined;
var x757: u32 = undefined;
mulxU32(&x756, &x757, x718, 0xffffffff);
var x758: u32 = undefined;
var x759: u32 = undefined;
mulxU32(&x758, &x759, x718, 0xfffffffe);
var x760: u32 = undefined;
var x761: u32 = undefined;
mulxU32(&x760, &x761, x718, 0xffffffff);
var x762: u32 = undefined;
var x763: u32 = undefined;
mulxU32(&x762, &x763, x718, 0xffffffff);
var x764: u32 = undefined;
var x765: u1 = undefined;
addcarryxU32(&x764, &x765, 0x0, x761, x758);
var x766: u32 = undefined;
var x767: u1 = undefined;
addcarryxU32(&x766, &x767, x765, x759, x756);
var x768: u32 = undefined;
var x769: u1 = undefined;
addcarryxU32(&x768, &x769, x767, x757, x754);
var x770: u32 = undefined;
var x771: u1 = undefined;
addcarryxU32(&x770, &x771, x769, x755, x752);
var x772: u32 = undefined;
var x773: u1 = undefined;
addcarryxU32(&x772, &x773, x771, x753, x750);
var x774: u32 = undefined;
var x775: u1 = undefined;
addcarryxU32(&x774, &x775, x773, x751, x748);
var x776: u32 = undefined;
var x777: u1 = undefined;
addcarryxU32(&x776, &x777, x775, x749, x746);
var x778: u32 = undefined;
var x779: u1 = undefined;
addcarryxU32(&x778, &x779, x777, x747, x744);
const x780 = (cast(u32, x779) + x745);
var x781: u32 = undefined;
var x782: u1 = undefined;
addcarryxU32(&x781, &x782, 0x0, x718, x762);
var x783: u32 = undefined;
var x784: u1 = undefined;
addcarryxU32(&x783, &x784, x782, x720, x763);
var x785: u32 = undefined;
var x786: u1 = undefined;
addcarryxU32(&x785, &x786, x784, x722, cast(u32, 0x0));
var x787: u32 = undefined;
var x788: u1 = undefined;
addcarryxU32(&x787, &x788, x786, x724, x760);
var x789: u32 = undefined;
var x790: u1 = undefined;
addcarryxU32(&x789, &x790, x788, x726, x764);
var x791: u32 = undefined;
var x792: u1 = undefined;
addcarryxU32(&x791, &x792, x790, x728, x766);
var x793: u32 = undefined;
var x794: u1 = undefined;
addcarryxU32(&x793, &x794, x792, x730, x768);
var x795: u32 = undefined;
var x796: u1 = undefined;
addcarryxU32(&x795, &x796, x794, x732, x770);
var x797: u32 = undefined;
var x798: u1 = undefined;
addcarryxU32(&x797, &x798, x796, x734, x772);
var x799: u32 = undefined;
var x800: u1 = undefined;
addcarryxU32(&x799, &x800, x798, x736, x774);
var x801: u32 = undefined;
var x802: u1 = undefined;
addcarryxU32(&x801, &x802, x800, x738, x776);
var x803: u32 = undefined;
var x804: u1 = undefined;
addcarryxU32(&x803, &x804, x802, x740, x778);
var x805: u32 = undefined;
var x806: u1 = undefined;
addcarryxU32(&x805, &x806, x804, x742, x780);
const x807 = (cast(u32, x806) + cast(u32, x743));
var x808: u32 = undefined;
var x809: u32 = undefined;
mulxU32(&x808, &x809, x6, (arg2[11]));
var x810: u32 = undefined;
var x811: u32 = undefined;
mulxU32(&x810, &x811, x6, (arg2[10]));
var x812: u32 = undefined;
var x813: u32 = undefined;
mulxU32(&x812, &x813, x6, (arg2[9]));
var x814: u32 = undefined;
var x815: u32 = undefined;
mulxU32(&x814, &x815, x6, (arg2[8]));
var x816: u32 = undefined;
var x817: u32 = undefined;
mulxU32(&x816, &x817, x6, (arg2[7]));
var x818: u32 = undefined;
var x819: u32 = undefined;
mulxU32(&x818, &x819, x6, (arg2[6]));
var x820: u32 = undefined;
var x821: u32 = undefined;
mulxU32(&x820, &x821, x6, (arg2[5]));
var x822: u32 = undefined;
var x823: u32 = undefined;
mulxU32(&x822, &x823, x6, (arg2[4]));
var x824: u32 = undefined;
var x825: u32 = undefined;
mulxU32(&x824, &x825, x6, (arg2[3]));
var x826: u32 = undefined;
var x827: u32 = undefined;
mulxU32(&x826, &x827, x6, (arg2[2]));
var x828: u32 = undefined;
var x829: u32 = undefined;
mulxU32(&x828, &x829, x6, (arg2[1]));
var x830: u32 = undefined;
var x831: u32 = undefined;
mulxU32(&x830, &x831, x6, (arg2[0]));
var x832: u32 = undefined;
var x833: u1 = undefined;
addcarryxU32(&x832, &x833, 0x0, x831, x828);
var x834: u32 = undefined;
var x835: u1 = undefined;
addcarryxU32(&x834, &x835, x833, x829, x826);
var x836: u32 = undefined;
var x837: u1 = undefined;
addcarryxU32(&x836, &x837, x835, x827, x824);
var x838: u32 = undefined;
var x839: u1 = undefined;
addcarryxU32(&x838, &x839, x837, x825, x822);
var x840: u32 = undefined;
var x841: u1 = undefined;
addcarryxU32(&x840, &x841, x839, x823, x820);
var x842: u32 = undefined;
var x843: u1 = undefined;
addcarryxU32(&x842, &x843, x841, x821, x818);
var x844: u32 = undefined;
var x845: u1 = undefined;
addcarryxU32(&x844, &x845, x843, x819, x816);
var x846: u32 = undefined;
var x847: u1 = undefined;
addcarryxU32(&x846, &x847, x845, x817, x814);
var x848: u32 = undefined;
var x849: u1 = undefined;
addcarryxU32(&x848, &x849, x847, x815, x812);
var x850: u32 = undefined;
var x851: u1 = undefined;
addcarryxU32(&x850, &x851, x849, x813, x810);
var x852: u32 = undefined;
var x853: u1 = undefined;
addcarryxU32(&x852, &x853, x851, x811, x808);
const x854 = (cast(u32, x853) + x809);
var x855: u32 = undefined;
var x856: u1 = undefined;
addcarryxU32(&x855, &x856, 0x0, x783, x830);
var x857: u32 = undefined;
var x858: u1 = undefined;
addcarryxU32(&x857, &x858, x856, x785, x832);
var x859: u32 = undefined;
var x860: u1 = undefined;
addcarryxU32(&x859, &x860, x858, x787, x834);
var x861: u32 = undefined;
var x862: u1 = undefined;
addcarryxU32(&x861, &x862, x860, x789, x836);
var x863: u32 = undefined;
var x864: u1 = undefined;
addcarryxU32(&x863, &x864, x862, x791, x838);
var x865: u32 = undefined;
var x866: u1 = undefined;
addcarryxU32(&x865, &x866, x864, x793, x840);
var x867: u32 = undefined;
var x868: u1 = undefined;
addcarryxU32(&x867, &x868, x866, x795, x842);
var x869: u32 = undefined;
var x870: u1 = undefined;
addcarryxU32(&x869, &x870, x868, x797, x844);
var x871: u32 = undefined;
var x872: u1 = undefined;
addcarryxU32(&x871, &x872, x870, x799, x846);
var x873: u32 = undefined;
var x874: u1 = undefined;
addcarryxU32(&x873, &x874, x872, x801, x848);
var x875: u32 = undefined;
var x876: u1 = undefined;
addcarryxU32(&x875, &x876, x874, x803, x850);
var x877: u32 = undefined;
var x878: u1 = undefined;
addcarryxU32(&x877, &x878, x876, x805, x852);
var x879: u32 = undefined;
var x880: u1 = undefined;
addcarryxU32(&x879, &x880, x878, x807, x854);
var x881: u32 = undefined;
var x882: u32 = undefined;
mulxU32(&x881, &x882, x855, 0xffffffff);
var x883: u32 = undefined;
var x884: u32 = undefined;
mulxU32(&x883, &x884, x855, 0xffffffff);
var x885: u32 = undefined;
var x886: u32 = undefined;
mulxU32(&x885, &x886, x855, 0xffffffff);
var x887: u32 = undefined;
var x888: u32 = undefined;
mulxU32(&x887, &x888, x855, 0xffffffff);
var x889: u32 = undefined;
var x890: u32 = undefined;
mulxU32(&x889, &x890, x855, 0xffffffff);
var x891: u32 = undefined;
var x892: u32 = undefined;
mulxU32(&x891, &x892, x855, 0xffffffff);
var x893: u32 = undefined;
var x894: u32 = undefined;
mulxU32(&x893, &x894, x855, 0xffffffff);
var x895: u32 = undefined;
var x896: u32 = undefined;
mulxU32(&x895, &x896, x855, 0xfffffffe);
var x897: u32 = undefined;
var x898: u32 = undefined;
mulxU32(&x897, &x898, x855, 0xffffffff);
var x899: u32 = undefined;
var x900: u32 = undefined;
mulxU32(&x899, &x900, x855, 0xffffffff);
var x901: u32 = undefined;
var x902: u1 = undefined;
addcarryxU32(&x901, &x902, 0x0, x898, x895);
var x903: u32 = undefined;
var x904: u1 = undefined;
addcarryxU32(&x903, &x904, x902, x896, x893);
var x905: u32 = undefined;
var x906: u1 = undefined;
addcarryxU32(&x905, &x906, x904, x894, x891);
var x907: u32 = undefined;
var x908: u1 = undefined;
addcarryxU32(&x907, &x908, x906, x892, x889);
var x909: u32 = undefined;
var x910: u1 = undefined;
addcarryxU32(&x909, &x910, x908, x890, x887);
var x911: u32 = undefined;
var x912: u1 = undefined;
addcarryxU32(&x911, &x912, x910, x888, x885);
var x913: u32 = undefined;
var x914: u1 = undefined;
addcarryxU32(&x913, &x914, x912, x886, x883);
var x915: u32 = undefined;
var x916: u1 = undefined;
addcarryxU32(&x915, &x916, x914, x884, x881);
const x917 = (cast(u32, x916) + x882);
var x918: u32 = undefined;
var x919: u1 = undefined;
addcarryxU32(&x918, &x919, 0x0, x855, x899);
var x920: u32 = undefined;
var x921: u1 = undefined;
addcarryxU32(&x920, &x921, x919, x857, x900);
var x922: u32 = undefined;
var x923: u1 = undefined;
addcarryxU32(&x922, &x923, x921, x859, cast(u32, 0x0));
var x924: u32 = undefined;
var x925: u1 = undefined;
addcarryxU32(&x924, &x925, x923, x861, x897);
var x926: u32 = undefined;
var x927: u1 = undefined;
addcarryxU32(&x926, &x927, x925, x863, x901);
var x928: u32 = undefined;
var x929: u1 = undefined;
addcarryxU32(&x928, &x929, x927, x865, x903);
var x930: u32 = undefined;
var x931: u1 = undefined;
addcarryxU32(&x930, &x931, x929, x867, x905);
var x932: u32 = undefined;
var x933: u1 = undefined;
addcarryxU32(&x932, &x933, x931, x869, x907);
var x934: u32 = undefined;
var x935: u1 = undefined;
addcarryxU32(&x934, &x935, x933, x871, x909);
var x936: u32 = undefined;
var x937: u1 = undefined;
addcarryxU32(&x936, &x937, x935, x873, x911);
var x938: u32 = undefined;
var x939: u1 = undefined;
addcarryxU32(&x938, &x939, x937, x875, x913);
var x940: u32 = undefined;
var x941: u1 = undefined;
addcarryxU32(&x940, &x941, x939, x877, x915);
var x942: u32 = undefined;
var x943: u1 = undefined;
addcarryxU32(&x942, &x943, x941, x879, x917);
const x944 = (cast(u32, x943) + cast(u32, x880));
var x945: u32 = undefined;
var x946: u32 = undefined;
mulxU32(&x945, &x946, x7, (arg2[11]));
var x947: u32 = undefined;
var x948: u32 = undefined;
mulxU32(&x947, &x948, x7, (arg2[10]));
var x949: u32 = undefined;
var x950: u32 = undefined;
mulxU32(&x949, &x950, x7, (arg2[9]));
var x951: u32 = undefined;
var x952: u32 = undefined;
mulxU32(&x951, &x952, x7, (arg2[8]));
var x953: u32 = undefined;
var x954: u32 = undefined;
mulxU32(&x953, &x954, x7, (arg2[7]));
var x955: u32 = undefined;
var x956: u32 = undefined;
mulxU32(&x955, &x956, x7, (arg2[6]));
var x957: u32 = undefined;
var x958: u32 = undefined;
mulxU32(&x957, &x958, x7, (arg2[5]));
var x959: u32 = undefined;
var x960: u32 = undefined;
mulxU32(&x959, &x960, x7, (arg2[4]));
var x961: u32 = undefined;
var x962: u32 = undefined;
mulxU32(&x961, &x962, x7, (arg2[3]));
var x963: u32 = undefined;
var x964: u32 = undefined;
mulxU32(&x963, &x964, x7, (arg2[2]));
var x965: u32 = undefined;
var x966: u32 = undefined;
mulxU32(&x965, &x966, x7, (arg2[1]));
var x967: u32 = undefined;
var x968: u32 = undefined;
mulxU32(&x967, &x968, x7, (arg2[0]));
var x969: u32 = undefined;
var x970: u1 = undefined;
addcarryxU32(&x969, &x970, 0x0, x968, x965);
var x971: u32 = undefined;
var x972: u1 = undefined;
addcarryxU32(&x971, &x972, x970, x966, x963);
var x973: u32 = undefined;
var x974: u1 = undefined;
addcarryxU32(&x973, &x974, x972, x964, x961);
var x975: u32 = undefined;
var x976: u1 = undefined;
addcarryxU32(&x975, &x976, x974, x962, x959);
var x977: u32 = undefined;
var x978: u1 = undefined;
addcarryxU32(&x977, &x978, x976, x960, x957);
var x979: u32 = undefined;
var x980: u1 = undefined;
addcarryxU32(&x979, &x980, x978, x958, x955);
var x981: u32 = undefined;
var x982: u1 = undefined;
addcarryxU32(&x981, &x982, x980, x956, x953);
var x983: u32 = undefined;
var x984: u1 = undefined;
addcarryxU32(&x983, &x984, x982, x954, x951);
var x985: u32 = undefined;
var x986: u1 = undefined;
addcarryxU32(&x985, &x986, x984, x952, x949);
var x987: u32 = undefined;
var x988: u1 = undefined;
addcarryxU32(&x987, &x988, x986, x950, x947);
var x989: u32 = undefined;
var x990: u1 = undefined;
addcarryxU32(&x989, &x990, x988, x948, x945);
const x991 = (cast(u32, x990) + x946);
var x992: u32 = undefined;
var x993: u1 = undefined;
addcarryxU32(&x992, &x993, 0x0, x920, x967);
var x994: u32 = undefined;
var x995: u1 = undefined;
addcarryxU32(&x994, &x995, x993, x922, x969);
var x996: u32 = undefined;
var x997: u1 = undefined;
addcarryxU32(&x996, &x997, x995, x924, x971);
var x998: u32 = undefined;
var x999: u1 = undefined;
addcarryxU32(&x998, &x999, x997, x926, x973);
var x1000: u32 = undefined;
var x1001: u1 = undefined;
addcarryxU32(&x1000, &x1001, x999, x928, x975);
var x1002: u32 = undefined;
var x1003: u1 = undefined;
addcarryxU32(&x1002, &x1003, x1001, x930, x977);
var x1004: u32 = undefined;
var x1005: u1 = undefined;
addcarryxU32(&x1004, &x1005, x1003, x932, x979);
var x1006: u32 = undefined;
var x1007: u1 = undefined;
addcarryxU32(&x1006, &x1007, x1005, x934, x981);
var x1008: u32 = undefined;
var x1009: u1 = undefined;
addcarryxU32(&x1008, &x1009, x1007, x936, x983);
var x1010: u32 = undefined;
var x1011: u1 = undefined;
addcarryxU32(&x1010, &x1011, x1009, x938, x985);
var x1012: u32 = undefined;
var x1013: u1 = undefined;
addcarryxU32(&x1012, &x1013, x1011, x940, x987);
var x1014: u32 = undefined;
var x1015: u1 = undefined;
addcarryxU32(&x1014, &x1015, x1013, x942, x989);
var x1016: u32 = undefined;
var x1017: u1 = undefined;
addcarryxU32(&x1016, &x1017, x1015, x944, x991);
var x1018: u32 = undefined;
var x1019: u32 = undefined;
mulxU32(&x1018, &x1019, x992, 0xffffffff);
var x1020: u32 = undefined;
var x1021: u32 = undefined;
mulxU32(&x1020, &x1021, x992, 0xffffffff);
var x1022: u32 = undefined;
var x1023: u32 = undefined;
mulxU32(&x1022, &x1023, x992, 0xffffffff);
var x1024: u32 = undefined;
var x1025: u32 = undefined;
mulxU32(&x1024, &x1025, x992, 0xffffffff);
var x1026: u32 = undefined;
var x1027: u32 = undefined;
mulxU32(&x1026, &x1027, x992, 0xffffffff);
var x1028: u32 = undefined;
var x1029: u32 = undefined;
mulxU32(&x1028, &x1029, x992, 0xffffffff);
var x1030: u32 = undefined;
var x1031: u32 = undefined;
mulxU32(&x1030, &x1031, x992, 0xffffffff);
var x1032: u32 = undefined;
var x1033: u32 = undefined;
mulxU32(&x1032, &x1033, x992, 0xfffffffe);
var x1034: u32 = undefined;
var x1035: u32 = undefined;
mulxU32(&x1034, &x1035, x992, 0xffffffff);
var x1036: u32 = undefined;
var x1037: u32 = undefined;
mulxU32(&x1036, &x1037, x992, 0xffffffff);
var x1038: u32 = undefined;
var x1039: u1 = undefined;
addcarryxU32(&x1038, &x1039, 0x0, x1035, x1032);
var x1040: u32 = undefined;
var x1041: u1 = undefined;
addcarryxU32(&x1040, &x1041, x1039, x1033, x1030);
var x1042: u32 = undefined;
var x1043: u1 = undefined;
addcarryxU32(&x1042, &x1043, x1041, x1031, x1028);
var x1044: u32 = undefined;
var x1045: u1 = undefined;
addcarryxU32(&x1044, &x1045, x1043, x1029, x1026);
var x1046: u32 = undefined;
var x1047: u1 = undefined;
addcarryxU32(&x1046, &x1047, x1045, x1027, x1024);
var x1048: u32 = undefined;
var x1049: u1 = undefined;
addcarryxU32(&x1048, &x1049, x1047, x1025, x1022);
var x1050: u32 = undefined;
var x1051: u1 = undefined;
addcarryxU32(&x1050, &x1051, x1049, x1023, x1020);
var x1052: u32 = undefined;
var x1053: u1 = undefined;
addcarryxU32(&x1052, &x1053, x1051, x1021, x1018);
const x1054 = (cast(u32, x1053) + x1019);
var x1055: u32 = undefined;
var x1056: u1 = undefined;
addcarryxU32(&x1055, &x1056, 0x0, x992, x1036);
var x1057: u32 = undefined;
var x1058: u1 = undefined;
addcarryxU32(&x1057, &x1058, x1056, x994, x1037);
var x1059: u32 = undefined;
var x1060: u1 = undefined;
addcarryxU32(&x1059, &x1060, x1058, x996, cast(u32, 0x0));
var x1061: u32 = undefined;
var x1062: u1 = undefined;
addcarryxU32(&x1061, &x1062, x1060, x998, x1034);
var x1063: u32 = undefined;
var x1064: u1 = undefined;
addcarryxU32(&x1063, &x1064, x1062, x1000, x1038);
var x1065: u32 = undefined;
var x1066: u1 = undefined;
addcarryxU32(&x1065, &x1066, x1064, x1002, x1040);
var x1067: u32 = undefined;
var x1068: u1 = undefined;
addcarryxU32(&x1067, &x1068, x1066, x1004, x1042);
var x1069: u32 = undefined;
var x1070: u1 = undefined;
addcarryxU32(&x1069, &x1070, x1068, x1006, x1044);
var x1071: u32 = undefined;
var x1072: u1 = undefined;
addcarryxU32(&x1071, &x1072, x1070, x1008, x1046);
var x1073: u32 = undefined;
var x1074: u1 = undefined;
addcarryxU32(&x1073, &x1074, x1072, x1010, x1048);
var x1075: u32 = undefined;
var x1076: u1 = undefined;
addcarryxU32(&x1075, &x1076, x1074, x1012, x1050);
var x1077: u32 = undefined;
var x1078: u1 = undefined;
addcarryxU32(&x1077, &x1078, x1076, x1014, x1052);
var x1079: u32 = undefined;
var x1080: u1 = undefined;
addcarryxU32(&x1079, &x1080, x1078, x1016, x1054);
const x1081 = (cast(u32, x1080) + cast(u32, x1017));
var x1082: u32 = undefined;
var x1083: u32 = undefined;
mulxU32(&x1082, &x1083, x8, (arg2[11]));
var x1084: u32 = undefined;
var x1085: u32 = undefined;
mulxU32(&x1084, &x1085, x8, (arg2[10]));
var x1086: u32 = undefined;
var x1087: u32 = undefined;
mulxU32(&x1086, &x1087, x8, (arg2[9]));
var x1088: u32 = undefined;
var x1089: u32 = undefined;
mulxU32(&x1088, &x1089, x8, (arg2[8]));
var x1090: u32 = undefined;
var x1091: u32 = undefined;
mulxU32(&x1090, &x1091, x8, (arg2[7]));
var x1092: u32 = undefined;
var x1093: u32 = undefined;
mulxU32(&x1092, &x1093, x8, (arg2[6]));
var x1094: u32 = undefined;
var x1095: u32 = undefined;
mulxU32(&x1094, &x1095, x8, (arg2[5]));
var x1096: u32 = undefined;
var x1097: u32 = undefined;
mulxU32(&x1096, &x1097, x8, (arg2[4]));
var x1098: u32 = undefined;
var x1099: u32 = undefined;
mulxU32(&x1098, &x1099, x8, (arg2[3]));
var x1100: u32 = undefined;
var x1101: u32 = undefined;
mulxU32(&x1100, &x1101, x8, (arg2[2]));
var x1102: u32 = undefined;
var x1103: u32 = undefined;
mulxU32(&x1102, &x1103, x8, (arg2[1]));
var x1104: u32 = undefined;
var x1105: u32 = undefined;
mulxU32(&x1104, &x1105, x8, (arg2[0]));
var x1106: u32 = undefined;
var x1107: u1 = undefined;
addcarryxU32(&x1106, &x1107, 0x0, x1105, x1102);
var x1108: u32 = undefined;
var x1109: u1 = undefined;
addcarryxU32(&x1108, &x1109, x1107, x1103, x1100);
var x1110: u32 = undefined;
var x1111: u1 = undefined;
addcarryxU32(&x1110, &x1111, x1109, x1101, x1098);
var x1112: u32 = undefined;
var x1113: u1 = undefined;
addcarryxU32(&x1112, &x1113, x1111, x1099, x1096);
var x1114: u32 = undefined;
var x1115: u1 = undefined;
addcarryxU32(&x1114, &x1115, x1113, x1097, x1094);
var x1116: u32 = undefined;
var x1117: u1 = undefined;
addcarryxU32(&x1116, &x1117, x1115, x1095, x1092);
var x1118: u32 = undefined;
var x1119: u1 = undefined;
addcarryxU32(&x1118, &x1119, x1117, x1093, x1090);
var x1120: u32 = undefined;
var x1121: u1 = undefined;
addcarryxU32(&x1120, &x1121, x1119, x1091, x1088);
var x1122: u32 = undefined;
var x1123: u1 = undefined;
addcarryxU32(&x1122, &x1123, x1121, x1089, x1086);
var x1124: u32 = undefined;
var x1125: u1 = undefined;
addcarryxU32(&x1124, &x1125, x1123, x1087, x1084);
var x1126: u32 = undefined;
var x1127: u1 = undefined;
addcarryxU32(&x1126, &x1127, x1125, x1085, x1082);
const x1128 = (cast(u32, x1127) + x1083);
var x1129: u32 = undefined;
var x1130: u1 = undefined;
addcarryxU32(&x1129, &x1130, 0x0, x1057, x1104);
var x1131: u32 = undefined;
var x1132: u1 = undefined;
addcarryxU32(&x1131, &x1132, x1130, x1059, x1106);
var x1133: u32 = undefined;
var x1134: u1 = undefined;
addcarryxU32(&x1133, &x1134, x1132, x1061, x1108);
var x1135: u32 = undefined;
var x1136: u1 = undefined;
addcarryxU32(&x1135, &x1136, x1134, x1063, x1110);
var x1137: u32 = undefined;
var x1138: u1 = undefined;
addcarryxU32(&x1137, &x1138, x1136, x1065, x1112);
var x1139: u32 = undefined;
var x1140: u1 = undefined;
addcarryxU32(&x1139, &x1140, x1138, x1067, x1114);
var x1141: u32 = undefined;
var x1142: u1 = undefined;
addcarryxU32(&x1141, &x1142, x1140, x1069, x1116);
var x1143: u32 = undefined;
var x1144: u1 = undefined;
addcarryxU32(&x1143, &x1144, x1142, x1071, x1118);
var x1145: u32 = undefined;
var x1146: u1 = undefined;
addcarryxU32(&x1145, &x1146, x1144, x1073, x1120);
var x1147: u32 = undefined;
var x1148: u1 = undefined;
addcarryxU32(&x1147, &x1148, x1146, x1075, x1122);
var x1149: u32 = undefined;
var x1150: u1 = undefined;
addcarryxU32(&x1149, &x1150, x1148, x1077, x1124);
var x1151: u32 = undefined;
var x1152: u1 = undefined;
addcarryxU32(&x1151, &x1152, x1150, x1079, x1126);
var x1153: u32 = undefined;
var x1154: u1 = undefined;
addcarryxU32(&x1153, &x1154, x1152, x1081, x1128);
var x1155: u32 = undefined;
var x1156: u32 = undefined;
mulxU32(&x1155, &x1156, x1129, 0xffffffff);
var x1157: u32 = undefined;
var x1158: u32 = undefined;
mulxU32(&x1157, &x1158, x1129, 0xffffffff);
var x1159: u32 = undefined;
var x1160: u32 = undefined;
mulxU32(&x1159, &x1160, x1129, 0xffffffff);
var x1161: u32 = undefined;
var x1162: u32 = undefined;
mulxU32(&x1161, &x1162, x1129, 0xffffffff);
var x1163: u32 = undefined;
var x1164: u32 = undefined;
mulxU32(&x1163, &x1164, x1129, 0xffffffff);
var x1165: u32 = undefined;
var x1166: u32 = undefined;
mulxU32(&x1165, &x1166, x1129, 0xffffffff);
var x1167: u32 = undefined;
var x1168: u32 = undefined;
mulxU32(&x1167, &x1168, x1129, 0xffffffff);
var x1169: u32 = undefined;
var x1170: u32 = undefined;
mulxU32(&x1169, &x1170, x1129, 0xfffffffe);
var x1171: u32 = undefined;
var x1172: u32 = undefined;
mulxU32(&x1171, &x1172, x1129, 0xffffffff);
var x1173: u32 = undefined;
var x1174: u32 = undefined;
mulxU32(&x1173, &x1174, x1129, 0xffffffff);
var x1175: u32 = undefined;
var x1176: u1 = undefined;
addcarryxU32(&x1175, &x1176, 0x0, x1172, x1169);
var x1177: u32 = undefined;
var x1178: u1 = undefined;
addcarryxU32(&x1177, &x1178, x1176, x1170, x1167);
var x1179: u32 = undefined;
var x1180: u1 = undefined;
addcarryxU32(&x1179, &x1180, x1178, x1168, x1165);
var x1181: u32 = undefined;
var x1182: u1 = undefined;
addcarryxU32(&x1181, &x1182, x1180, x1166, x1163);
var x1183: u32 = undefined;
var x1184: u1 = undefined;
addcarryxU32(&x1183, &x1184, x1182, x1164, x1161);
var x1185: u32 = undefined;
var x1186: u1 = undefined;
addcarryxU32(&x1185, &x1186, x1184, x1162, x1159);
var x1187: u32 = undefined;
var x1188: u1 = undefined;
addcarryxU32(&x1187, &x1188, x1186, x1160, x1157);
var x1189: u32 = undefined;
var x1190: u1 = undefined;
addcarryxU32(&x1189, &x1190, x1188, x1158, x1155);
const x1191 = (cast(u32, x1190) + x1156);
var x1192: u32 = undefined;
var x1193: u1 = undefined;
addcarryxU32(&x1192, &x1193, 0x0, x1129, x1173);
var x1194: u32 = undefined;
var x1195: u1 = undefined;
addcarryxU32(&x1194, &x1195, x1193, x1131, x1174);
var x1196: u32 = undefined;
var x1197: u1 = undefined;
addcarryxU32(&x1196, &x1197, x1195, x1133, cast(u32, 0x0));
var x1198: u32 = undefined;
var x1199: u1 = undefined;
addcarryxU32(&x1198, &x1199, x1197, x1135, x1171);
var x1200: u32 = undefined;
var x1201: u1 = undefined;
addcarryxU32(&x1200, &x1201, x1199, x1137, x1175);
var x1202: u32 = undefined;
var x1203: u1 = undefined;
addcarryxU32(&x1202, &x1203, x1201, x1139, x1177);
var x1204: u32 = undefined;
var x1205: u1 = undefined;
addcarryxU32(&x1204, &x1205, x1203, x1141, x1179);
var x1206: u32 = undefined;
var x1207: u1 = undefined;
addcarryxU32(&x1206, &x1207, x1205, x1143, x1181);
var x1208: u32 = undefined;
var x1209: u1 = undefined;
addcarryxU32(&x1208, &x1209, x1207, x1145, x1183);
var x1210: u32 = undefined;
var x1211: u1 = undefined;
addcarryxU32(&x1210, &x1211, x1209, x1147, x1185);
var x1212: u32 = undefined;
var x1213: u1 = undefined;
addcarryxU32(&x1212, &x1213, x1211, x1149, x1187);
var x1214: u32 = undefined;
var x1215: u1 = undefined;
addcarryxU32(&x1214, &x1215, x1213, x1151, x1189);
var x1216: u32 = undefined;
var x1217: u1 = undefined;
addcarryxU32(&x1216, &x1217, x1215, x1153, x1191);
const x1218 = (cast(u32, x1217) + cast(u32, x1154));
var x1219: u32 = undefined;
var x1220: u32 = undefined;
mulxU32(&x1219, &x1220, x9, (arg2[11]));
var x1221: u32 = undefined;
var x1222: u32 = undefined;
mulxU32(&x1221, &x1222, x9, (arg2[10]));
var x1223: u32 = undefined;
var x1224: u32 = undefined;
mulxU32(&x1223, &x1224, x9, (arg2[9]));
var x1225: u32 = undefined;
var x1226: u32 = undefined;
mulxU32(&x1225, &x1226, x9, (arg2[8]));
var x1227: u32 = undefined;
var x1228: u32 = undefined;
mulxU32(&x1227, &x1228, x9, (arg2[7]));
var x1229: u32 = undefined;
var x1230: u32 = undefined;
mulxU32(&x1229, &x1230, x9, (arg2[6]));
var x1231: u32 = undefined;
var x1232: u32 = undefined;
mulxU32(&x1231, &x1232, x9, (arg2[5]));
var x1233: u32 = undefined;
var x1234: u32 = undefined;
mulxU32(&x1233, &x1234, x9, (arg2[4]));
var x1235: u32 = undefined;
var x1236: u32 = undefined;
mulxU32(&x1235, &x1236, x9, (arg2[3]));
var x1237: u32 = undefined;
var x1238: u32 = undefined;
mulxU32(&x1237, &x1238, x9, (arg2[2]));
var x1239: u32 = undefined;
var x1240: u32 = undefined;
mulxU32(&x1239, &x1240, x9, (arg2[1]));
var x1241: u32 = undefined;
var x1242: u32 = undefined;
mulxU32(&x1241, &x1242, x9, (arg2[0]));
var x1243: u32 = undefined;
var x1244: u1 = undefined;
addcarryxU32(&x1243, &x1244, 0x0, x1242, x1239);
var x1245: u32 = undefined;
var x1246: u1 = undefined;
addcarryxU32(&x1245, &x1246, x1244, x1240, x1237);
var x1247: u32 = undefined;
var x1248: u1 = undefined;
addcarryxU32(&x1247, &x1248, x1246, x1238, x1235);
var x1249: u32 = undefined;
var x1250: u1 = undefined;
addcarryxU32(&x1249, &x1250, x1248, x1236, x1233);
var x1251: u32 = undefined;
var x1252: u1 = undefined;
addcarryxU32(&x1251, &x1252, x1250, x1234, x1231);
var x1253: u32 = undefined;
var x1254: u1 = undefined;
addcarryxU32(&x1253, &x1254, x1252, x1232, x1229);
var x1255: u32 = undefined;
var x1256: u1 = undefined;
addcarryxU32(&x1255, &x1256, x1254, x1230, x1227);
var x1257: u32 = undefined;
var x1258: u1 = undefined;
addcarryxU32(&x1257, &x1258, x1256, x1228, x1225);
var x1259: u32 = undefined;
var x1260: u1 = undefined;
addcarryxU32(&x1259, &x1260, x1258, x1226, x1223);
var x1261: u32 = undefined;
var x1262: u1 = undefined;
addcarryxU32(&x1261, &x1262, x1260, x1224, x1221);
var x1263: u32 = undefined;
var x1264: u1 = undefined;
addcarryxU32(&x1263, &x1264, x1262, x1222, x1219);
const x1265 = (cast(u32, x1264) + x1220);
var x1266: u32 = undefined;
var x1267: u1 = undefined;
addcarryxU32(&x1266, &x1267, 0x0, x1194, x1241);
var x1268: u32 = undefined;
var x1269: u1 = undefined;
addcarryxU32(&x1268, &x1269, x1267, x1196, x1243);
var x1270: u32 = undefined;
var x1271: u1 = undefined;
addcarryxU32(&x1270, &x1271, x1269, x1198, x1245);
var x1272: u32 = undefined;
var x1273: u1 = undefined;
addcarryxU32(&x1272, &x1273, x1271, x1200, x1247);
var x1274: u32 = undefined;
var x1275: u1 = undefined;
addcarryxU32(&x1274, &x1275, x1273, x1202, x1249);
var x1276: u32 = undefined;
var x1277: u1 = undefined;
addcarryxU32(&x1276, &x1277, x1275, x1204, x1251);
var x1278: u32 = undefined;
var x1279: u1 = undefined;
addcarryxU32(&x1278, &x1279, x1277, x1206, x1253);
var x1280: u32 = undefined;
var x1281: u1 = undefined;
addcarryxU32(&x1280, &x1281, x1279, x1208, x1255);
var x1282: u32 = undefined;
var x1283: u1 = undefined;
addcarryxU32(&x1282, &x1283, x1281, x1210, x1257);
var x1284: u32 = undefined;
var x1285: u1 = undefined;
addcarryxU32(&x1284, &x1285, x1283, x1212, x1259);
var x1286: u32 = undefined;
var x1287: u1 = undefined;
addcarryxU32(&x1286, &x1287, x1285, x1214, x1261);
var x1288: u32 = undefined;
var x1289: u1 = undefined;
addcarryxU32(&x1288, &x1289, x1287, x1216, x1263);
var x1290: u32 = undefined;
var x1291: u1 = undefined;
addcarryxU32(&x1290, &x1291, x1289, x1218, x1265);
var x1292: u32 = undefined;
var x1293: u32 = undefined;
mulxU32(&x1292, &x1293, x1266, 0xffffffff);
var x1294: u32 = undefined;
var x1295: u32 = undefined;
mulxU32(&x1294, &x1295, x1266, 0xffffffff);
var x1296: u32 = undefined;
var x1297: u32 = undefined;
mulxU32(&x1296, &x1297, x1266, 0xffffffff);
var x1298: u32 = undefined;
var x1299: u32 = undefined;
mulxU32(&x1298, &x1299, x1266, 0xffffffff);
var x1300: u32 = undefined;
var x1301: u32 = undefined;
mulxU32(&x1300, &x1301, x1266, 0xffffffff);
var x1302: u32 = undefined;
var x1303: u32 = undefined;
mulxU32(&x1302, &x1303, x1266, 0xffffffff);
var x1304: u32 = undefined;
var x1305: u32 = undefined;
mulxU32(&x1304, &x1305, x1266, 0xffffffff);
var x1306: u32 = undefined;
var x1307: u32 = undefined;
mulxU32(&x1306, &x1307, x1266, 0xfffffffe);
var x1308: u32 = undefined;
var x1309: u32 = undefined;
mulxU32(&x1308, &x1309, x1266, 0xffffffff);
var x1310: u32 = undefined;
var x1311: u32 = undefined;
mulxU32(&x1310, &x1311, x1266, 0xffffffff);
var x1312: u32 = undefined;
var x1313: u1 = undefined;
addcarryxU32(&x1312, &x1313, 0x0, x1309, x1306);
var x1314: u32 = undefined;
var x1315: u1 = undefined;
addcarryxU32(&x1314, &x1315, x1313, x1307, x1304);
var x1316: u32 = undefined;
var x1317: u1 = undefined;
addcarryxU32(&x1316, &x1317, x1315, x1305, x1302);
var x1318: u32 = undefined;
var x1319: u1 = undefined;
addcarryxU32(&x1318, &x1319, x1317, x1303, x1300);
var x1320: u32 = undefined;
var x1321: u1 = undefined;
addcarryxU32(&x1320, &x1321, x1319, x1301, x1298);
var x1322: u32 = undefined;
var x1323: u1 = undefined;
addcarryxU32(&x1322, &x1323, x1321, x1299, x1296);
var x1324: u32 = undefined;
var x1325: u1 = undefined;
addcarryxU32(&x1324, &x1325, x1323, x1297, x1294);
var x1326: u32 = undefined;
var x1327: u1 = undefined;
addcarryxU32(&x1326, &x1327, x1325, x1295, x1292);
const x1328 = (cast(u32, x1327) + x1293);
var x1329: u32 = undefined;
var x1330: u1 = undefined;
addcarryxU32(&x1329, &x1330, 0x0, x1266, x1310);
var x1331: u32 = undefined;
var x1332: u1 = undefined;
addcarryxU32(&x1331, &x1332, x1330, x1268, x1311);
var x1333: u32 = undefined;
var x1334: u1 = undefined;
addcarryxU32(&x1333, &x1334, x1332, x1270, cast(u32, 0x0));
var x1335: u32 = undefined;
var x1336: u1 = undefined;
addcarryxU32(&x1335, &x1336, x1334, x1272, x1308);
var x1337: u32 = undefined;
var x1338: u1 = undefined;
addcarryxU32(&x1337, &x1338, x1336, x1274, x1312);
var x1339: u32 = undefined;
var x1340: u1 = undefined;
addcarryxU32(&x1339, &x1340, x1338, x1276, x1314);
var x1341: u32 = undefined;
var x1342: u1 = undefined;
addcarryxU32(&x1341, &x1342, x1340, x1278, x1316);
var x1343: u32 = undefined;
var x1344: u1 = undefined;
addcarryxU32(&x1343, &x1344, x1342, x1280, x1318);
var x1345: u32 = undefined;
var x1346: u1 = undefined;
addcarryxU32(&x1345, &x1346, x1344, x1282, x1320);
var x1347: u32 = undefined;
var x1348: u1 = undefined;
addcarryxU32(&x1347, &x1348, x1346, x1284, x1322);
var x1349: u32 = undefined;
var x1350: u1 = undefined;
addcarryxU32(&x1349, &x1350, x1348, x1286, x1324);
var x1351: u32 = undefined;
var x1352: u1 = undefined;
addcarryxU32(&x1351, &x1352, x1350, x1288, x1326);
var x1353: u32 = undefined;
var x1354: u1 = undefined;
addcarryxU32(&x1353, &x1354, x1352, x1290, x1328);
const x1355 = (cast(u32, x1354) + cast(u32, x1291));
var x1356: u32 = undefined;
var x1357: u32 = undefined;
mulxU32(&x1356, &x1357, x10, (arg2[11]));
var x1358: u32 = undefined;
var x1359: u32 = undefined;
mulxU32(&x1358, &x1359, x10, (arg2[10]));
var x1360: u32 = undefined;
var x1361: u32 = undefined;
mulxU32(&x1360, &x1361, x10, (arg2[9]));
var x1362: u32 = undefined;
var x1363: u32 = undefined;
mulxU32(&x1362, &x1363, x10, (arg2[8]));
var x1364: u32 = undefined;
var x1365: u32 = undefined;
mulxU32(&x1364, &x1365, x10, (arg2[7]));
var x1366: u32 = undefined;
var x1367: u32 = undefined;
mulxU32(&x1366, &x1367, x10, (arg2[6]));
var x1368: u32 = undefined;
var x1369: u32 = undefined;
mulxU32(&x1368, &x1369, x10, (arg2[5]));
var x1370: u32 = undefined;
var x1371: u32 = undefined;
mulxU32(&x1370, &x1371, x10, (arg2[4]));
var x1372: u32 = undefined;
var x1373: u32 = undefined;
mulxU32(&x1372, &x1373, x10, (arg2[3]));
var x1374: u32 = undefined;
var x1375: u32 = undefined;
mulxU32(&x1374, &x1375, x10, (arg2[2]));
var x1376: u32 = undefined;
var x1377: u32 = undefined;
mulxU32(&x1376, &x1377, x10, (arg2[1]));
var x1378: u32 = undefined;
var x1379: u32 = undefined;
mulxU32(&x1378, &x1379, x10, (arg2[0]));
var x1380: u32 = undefined;
var x1381: u1 = undefined;
addcarryxU32(&x1380, &x1381, 0x0, x1379, x1376);
var x1382: u32 = undefined;
var x1383: u1 = undefined;
addcarryxU32(&x1382, &x1383, x1381, x1377, x1374);
var x1384: u32 = undefined;
var x1385: u1 = undefined;
addcarryxU32(&x1384, &x1385, x1383, x1375, x1372);
var x1386: u32 = undefined;
var x1387: u1 = undefined;
addcarryxU32(&x1386, &x1387, x1385, x1373, x1370);
var x1388: u32 = undefined;
var x1389: u1 = undefined;
addcarryxU32(&x1388, &x1389, x1387, x1371, x1368);
var x1390: u32 = undefined;
var x1391: u1 = undefined;
addcarryxU32(&x1390, &x1391, x1389, x1369, x1366);
var x1392: u32 = undefined;
var x1393: u1 = undefined;
addcarryxU32(&x1392, &x1393, x1391, x1367, x1364);
var x1394: u32 = undefined;
var x1395: u1 = undefined;
addcarryxU32(&x1394, &x1395, x1393, x1365, x1362);
var x1396: u32 = undefined;
var x1397: u1 = undefined;
addcarryxU32(&x1396, &x1397, x1395, x1363, x1360);
var x1398: u32 = undefined;
var x1399: u1 = undefined;
addcarryxU32(&x1398, &x1399, x1397, x1361, x1358);
var x1400: u32 = undefined;
var x1401: u1 = undefined;
addcarryxU32(&x1400, &x1401, x1399, x1359, x1356);
const x1402 = (cast(u32, x1401) + x1357);
var x1403: u32 = undefined;
var x1404: u1 = undefined;
addcarryxU32(&x1403, &x1404, 0x0, x1331, x1378);
var x1405: u32 = undefined;
var x1406: u1 = undefined;
addcarryxU32(&x1405, &x1406, x1404, x1333, x1380);
var x1407: u32 = undefined;
var x1408: u1 = undefined;
addcarryxU32(&x1407, &x1408, x1406, x1335, x1382);
var x1409: u32 = undefined;
var x1410: u1 = undefined;
addcarryxU32(&x1409, &x1410, x1408, x1337, x1384);
var x1411: u32 = undefined;
var x1412: u1 = undefined;
addcarryxU32(&x1411, &x1412, x1410, x1339, x1386);
var x1413: u32 = undefined;
var x1414: u1 = undefined;
addcarryxU32(&x1413, &x1414, x1412, x1341, x1388);
var x1415: u32 = undefined;
var x1416: u1 = undefined;
addcarryxU32(&x1415, &x1416, x1414, x1343, x1390);
var x1417: u32 = undefined;
var x1418: u1 = undefined;
addcarryxU32(&x1417, &x1418, x1416, x1345, x1392);
var x1419: u32 = undefined;
var x1420: u1 = undefined;
addcarryxU32(&x1419, &x1420, x1418, x1347, x1394);
var x1421: u32 = undefined;
var x1422: u1 = undefined;
addcarryxU32(&x1421, &x1422, x1420, x1349, x1396);
var x1423: u32 = undefined;
var x1424: u1 = undefined;
addcarryxU32(&x1423, &x1424, x1422, x1351, x1398);
var x1425: u32 = undefined;
var x1426: u1 = undefined;
addcarryxU32(&x1425, &x1426, x1424, x1353, x1400);
var x1427: u32 = undefined;
var x1428: u1 = undefined;
addcarryxU32(&x1427, &x1428, x1426, x1355, x1402);
var x1429: u32 = undefined;
var x1430: u32 = undefined;
mulxU32(&x1429, &x1430, x1403, 0xffffffff);
var x1431: u32 = undefined;
var x1432: u32 = undefined;
mulxU32(&x1431, &x1432, x1403, 0xffffffff);
var x1433: u32 = undefined;
var x1434: u32 = undefined;
mulxU32(&x1433, &x1434, x1403, 0xffffffff);
var x1435: u32 = undefined;
var x1436: u32 = undefined;
mulxU32(&x1435, &x1436, x1403, 0xffffffff);
var x1437: u32 = undefined;
var x1438: u32 = undefined;
mulxU32(&x1437, &x1438, x1403, 0xffffffff);
var x1439: u32 = undefined;
var x1440: u32 = undefined;
mulxU32(&x1439, &x1440, x1403, 0xffffffff);
var x1441: u32 = undefined;
var x1442: u32 = undefined;
mulxU32(&x1441, &x1442, x1403, 0xffffffff);
var x1443: u32 = undefined;
var x1444: u32 = undefined;
mulxU32(&x1443, &x1444, x1403, 0xfffffffe);
var x1445: u32 = undefined;
var x1446: u32 = undefined;
mulxU32(&x1445, &x1446, x1403, 0xffffffff);
var x1447: u32 = undefined;
var x1448: u32 = undefined;
mulxU32(&x1447, &x1448, x1403, 0xffffffff);
var x1449: u32 = undefined;
var x1450: u1 = undefined;
addcarryxU32(&x1449, &x1450, 0x0, x1446, x1443);
var x1451: u32 = undefined;
var x1452: u1 = undefined;
addcarryxU32(&x1451, &x1452, x1450, x1444, x1441);
var x1453: u32 = undefined;
var x1454: u1 = undefined;
addcarryxU32(&x1453, &x1454, x1452, x1442, x1439);
var x1455: u32 = undefined;
var x1456: u1 = undefined;
addcarryxU32(&x1455, &x1456, x1454, x1440, x1437);
var x1457: u32 = undefined;
var x1458: u1 = undefined;
addcarryxU32(&x1457, &x1458, x1456, x1438, x1435);
var x1459: u32 = undefined;
var x1460: u1 = undefined;
addcarryxU32(&x1459, &x1460, x1458, x1436, x1433);
var x1461: u32 = undefined;
var x1462: u1 = undefined;
addcarryxU32(&x1461, &x1462, x1460, x1434, x1431);
var x1463: u32 = undefined;
var x1464: u1 = undefined;
addcarryxU32(&x1463, &x1464, x1462, x1432, x1429);
const x1465 = (cast(u32, x1464) + x1430);
var x1466: u32 = undefined;
var x1467: u1 = undefined;
addcarryxU32(&x1466, &x1467, 0x0, x1403, x1447);
var x1468: u32 = undefined;
var x1469: u1 = undefined;
addcarryxU32(&x1468, &x1469, x1467, x1405, x1448);
var x1470: u32 = undefined;
var x1471: u1 = undefined;
addcarryxU32(&x1470, &x1471, x1469, x1407, cast(u32, 0x0));
var x1472: u32 = undefined;
var x1473: u1 = undefined;
addcarryxU32(&x1472, &x1473, x1471, x1409, x1445);
var x1474: u32 = undefined;
var x1475: u1 = undefined;
addcarryxU32(&x1474, &x1475, x1473, x1411, x1449);
var x1476: u32 = undefined;
var x1477: u1 = undefined;
addcarryxU32(&x1476, &x1477, x1475, x1413, x1451);
var x1478: u32 = undefined;
var x1479: u1 = undefined;
addcarryxU32(&x1478, &x1479, x1477, x1415, x1453);
var x1480: u32 = undefined;
var x1481: u1 = undefined;
addcarryxU32(&x1480, &x1481, x1479, x1417, x1455);
var x1482: u32 = undefined;
var x1483: u1 = undefined;
addcarryxU32(&x1482, &x1483, x1481, x1419, x1457);
var x1484: u32 = undefined;
var x1485: u1 = undefined;
addcarryxU32(&x1484, &x1485, x1483, x1421, x1459);
var x1486: u32 = undefined;
var x1487: u1 = undefined;
addcarryxU32(&x1486, &x1487, x1485, x1423, x1461);
var x1488: u32 = undefined;
var x1489: u1 = undefined;
addcarryxU32(&x1488, &x1489, x1487, x1425, x1463);
var x1490: u32 = undefined;
var x1491: u1 = undefined;
addcarryxU32(&x1490, &x1491, x1489, x1427, x1465);
const x1492 = (cast(u32, x1491) + cast(u32, x1428));
var x1493: u32 = undefined;
var x1494: u32 = undefined;
mulxU32(&x1493, &x1494, x11, (arg2[11]));
var x1495: u32 = undefined;
var x1496: u32 = undefined;
mulxU32(&x1495, &x1496, x11, (arg2[10]));
var x1497: u32 = undefined;
var x1498: u32 = undefined;
mulxU32(&x1497, &x1498, x11, (arg2[9]));
var x1499: u32 = undefined;
var x1500: u32 = undefined;
mulxU32(&x1499, &x1500, x11, (arg2[8]));
var x1501: u32 = undefined;
var x1502: u32 = undefined;
mulxU32(&x1501, &x1502, x11, (arg2[7]));
var x1503: u32 = undefined;
var x1504: u32 = undefined;
mulxU32(&x1503, &x1504, x11, (arg2[6]));
var x1505: u32 = undefined;
var x1506: u32 = undefined;
mulxU32(&x1505, &x1506, x11, (arg2[5]));
var x1507: u32 = undefined;
var x1508: u32 = undefined;
mulxU32(&x1507, &x1508, x11, (arg2[4]));
var x1509: u32 = undefined;
var x1510: u32 = undefined;
mulxU32(&x1509, &x1510, x11, (arg2[3]));
var x1511: u32 = undefined;
var x1512: u32 = undefined;
mulxU32(&x1511, &x1512, x11, (arg2[2]));
var x1513: u32 = undefined;
var x1514: u32 = undefined;
mulxU32(&x1513, &x1514, x11, (arg2[1]));
var x1515: u32 = undefined;
var x1516: u32 = undefined;
mulxU32(&x1515, &x1516, x11, (arg2[0]));
var x1517: u32 = undefined;
var x1518: u1 = undefined;
addcarryxU32(&x1517, &x1518, 0x0, x1516, x1513);
var x1519: u32 = undefined;
var x1520: u1 = undefined;
addcarryxU32(&x1519, &x1520, x1518, x1514, x1511);
var x1521: u32 = undefined;
var x1522: u1 = undefined;
addcarryxU32(&x1521, &x1522, x1520, x1512, x1509);
var x1523: u32 = undefined;
var x1524: u1 = undefined;
addcarryxU32(&x1523, &x1524, x1522, x1510, x1507);
var x1525: u32 = undefined;
var x1526: u1 = undefined;
addcarryxU32(&x1525, &x1526, x1524, x1508, x1505);
var x1527: u32 = undefined;
var x1528: u1 = undefined;
addcarryxU32(&x1527, &x1528, x1526, x1506, x1503);
var x1529: u32 = undefined;
var x1530: u1 = undefined;
addcarryxU32(&x1529, &x1530, x1528, x1504, x1501);
var x1531: u32 = undefined;
var x1532: u1 = undefined;
addcarryxU32(&x1531, &x1532, x1530, x1502, x1499);
var x1533: u32 = undefined;
var x1534: u1 = undefined;
addcarryxU32(&x1533, &x1534, x1532, x1500, x1497);
var x1535: u32 = undefined;
var x1536: u1 = undefined;
addcarryxU32(&x1535, &x1536, x1534, x1498, x1495);
var x1537: u32 = undefined;
var x1538: u1 = undefined;
addcarryxU32(&x1537, &x1538, x1536, x1496, x1493);
const x1539 = (cast(u32, x1538) + x1494);
var x1540: u32 = undefined;
var x1541: u1 = undefined;
addcarryxU32(&x1540, &x1541, 0x0, x1468, x1515);
var x1542: u32 = undefined;
var x1543: u1 = undefined;
addcarryxU32(&x1542, &x1543, x1541, x1470, x1517);
var x1544: u32 = undefined;
var x1545: u1 = undefined;
addcarryxU32(&x1544, &x1545, x1543, x1472, x1519);
var x1546: u32 = undefined;
var x1547: u1 = undefined;
addcarryxU32(&x1546, &x1547, x1545, x1474, x1521);
var x1548: u32 = undefined;
var x1549: u1 = undefined;
addcarryxU32(&x1548, &x1549, x1547, x1476, x1523);
var x1550: u32 = undefined;
var x1551: u1 = undefined;
addcarryxU32(&x1550, &x1551, x1549, x1478, x1525);
var x1552: u32 = undefined;
var x1553: u1 = undefined;
addcarryxU32(&x1552, &x1553, x1551, x1480, x1527);
var x1554: u32 = undefined;
var x1555: u1 = undefined;
addcarryxU32(&x1554, &x1555, x1553, x1482, x1529);
var x1556: u32 = undefined;
var x1557: u1 = undefined;
addcarryxU32(&x1556, &x1557, x1555, x1484, x1531);
var x1558: u32 = undefined;
var x1559: u1 = undefined;
addcarryxU32(&x1558, &x1559, x1557, x1486, x1533);
var x1560: u32 = undefined;
var x1561: u1 = undefined;
addcarryxU32(&x1560, &x1561, x1559, x1488, x1535);
var x1562: u32 = undefined;
var x1563: u1 = undefined;
addcarryxU32(&x1562, &x1563, x1561, x1490, x1537);
var x1564: u32 = undefined;
var x1565: u1 = undefined;
addcarryxU32(&x1564, &x1565, x1563, x1492, x1539);
var x1566: u32 = undefined;
var x1567: u32 = undefined;
mulxU32(&x1566, &x1567, x1540, 0xffffffff);
var x1568: u32 = undefined;
var x1569: u32 = undefined;
mulxU32(&x1568, &x1569, x1540, 0xffffffff);
var x1570: u32 = undefined;
var x1571: u32 = undefined;
mulxU32(&x1570, &x1571, x1540, 0xffffffff);
var x1572: u32 = undefined;
var x1573: u32 = undefined;
mulxU32(&x1572, &x1573, x1540, 0xffffffff);
var x1574: u32 = undefined;
var x1575: u32 = undefined;
mulxU32(&x1574, &x1575, x1540, 0xffffffff);
var x1576: u32 = undefined;
var x1577: u32 = undefined;
mulxU32(&x1576, &x1577, x1540, 0xffffffff);
var x1578: u32 = undefined;
var x1579: u32 = undefined;
mulxU32(&x1578, &x1579, x1540, 0xffffffff);
var x1580: u32 = undefined;
var x1581: u32 = undefined;
mulxU32(&x1580, &x1581, x1540, 0xfffffffe);
var x1582: u32 = undefined;
var x1583: u32 = undefined;
mulxU32(&x1582, &x1583, x1540, 0xffffffff);
var x1584: u32 = undefined;
var x1585: u32 = undefined;
mulxU32(&x1584, &x1585, x1540, 0xffffffff);
var x1586: u32 = undefined;
var x1587: u1 = undefined;
addcarryxU32(&x1586, &x1587, 0x0, x1583, x1580);
var x1588: u32 = undefined;
var x1589: u1 = undefined;
addcarryxU32(&x1588, &x1589, x1587, x1581, x1578);
var x1590: u32 = undefined;
var x1591: u1 = undefined;
addcarryxU32(&x1590, &x1591, x1589, x1579, x1576);
var x1592: u32 = undefined;
var x1593: u1 = undefined;
addcarryxU32(&x1592, &x1593, x1591, x1577, x1574);
var x1594: u32 = undefined;
var x1595: u1 = undefined;
addcarryxU32(&x1594, &x1595, x1593, x1575, x1572);
var x1596: u32 = undefined;
var x1597: u1 = undefined;
addcarryxU32(&x1596, &x1597, x1595, x1573, x1570);
var x1598: u32 = undefined;
var x1599: u1 = undefined;
addcarryxU32(&x1598, &x1599, x1597, x1571, x1568);
var x1600: u32 = undefined;
var x1601: u1 = undefined;
addcarryxU32(&x1600, &x1601, x1599, x1569, x1566);
const x1602 = (cast(u32, x1601) + x1567);
var x1603: u32 = undefined;
var x1604: u1 = undefined;
addcarryxU32(&x1603, &x1604, 0x0, x1540, x1584);
var x1605: u32 = undefined;
var x1606: u1 = undefined;
addcarryxU32(&x1605, &x1606, x1604, x1542, x1585);
var x1607: u32 = undefined;
var x1608: u1 = undefined;
addcarryxU32(&x1607, &x1608, x1606, x1544, cast(u32, 0x0));
var x1609: u32 = undefined;
var x1610: u1 = undefined;
addcarryxU32(&x1609, &x1610, x1608, x1546, x1582);
var x1611: u32 = undefined;
var x1612: u1 = undefined;
addcarryxU32(&x1611, &x1612, x1610, x1548, x1586);
var x1613: u32 = undefined;
var x1614: u1 = undefined;
addcarryxU32(&x1613, &x1614, x1612, x1550, x1588);
var x1615: u32 = undefined;
var x1616: u1 = undefined;
addcarryxU32(&x1615, &x1616, x1614, x1552, x1590);
var x1617: u32 = undefined;
var x1618: u1 = undefined;
addcarryxU32(&x1617, &x1618, x1616, x1554, x1592);
var x1619: u32 = undefined;
var x1620: u1 = undefined;
addcarryxU32(&x1619, &x1620, x1618, x1556, x1594);
var x1621: u32 = undefined;
var x1622: u1 = undefined;
addcarryxU32(&x1621, &x1622, x1620, x1558, x1596);
var x1623: u32 = undefined;
var x1624: u1 = undefined;
addcarryxU32(&x1623, &x1624, x1622, x1560, x1598);
var x1625: u32 = undefined;
var x1626: u1 = undefined;
addcarryxU32(&x1625, &x1626, x1624, x1562, x1600);
var x1627: u32 = undefined;
var x1628: u1 = undefined;
addcarryxU32(&x1627, &x1628, x1626, x1564, x1602);
const x1629 = (cast(u32, x1628) + cast(u32, x1565));
var x1630: u32 = undefined;
var x1631: u1 = undefined;
subborrowxU32(&x1630, &x1631, 0x0, x1605, 0xffffffff);
var x1632: u32 = undefined;
var x1633: u1 = undefined;
subborrowxU32(&x1632, &x1633, x1631, x1607, cast(u32, 0x0));
var x1634: u32 = undefined;
var x1635: u1 = undefined;
subborrowxU32(&x1634, &x1635, x1633, x1609, cast(u32, 0x0));
var x1636: u32 = undefined;
var x1637: u1 = undefined;
subborrowxU32(&x1636, &x1637, x1635, x1611, 0xffffffff);
var x1638: u32 = undefined;
var x1639: u1 = undefined;
subborrowxU32(&x1638, &x1639, x1637, x1613, 0xfffffffe);
var x1640: u32 = undefined;
var x1641: u1 = undefined;
subborrowxU32(&x1640, &x1641, x1639, x1615, 0xffffffff);
var x1642: u32 = undefined;
var x1643: u1 = undefined;
subborrowxU32(&x1642, &x1643, x1641, x1617, 0xffffffff);
var x1644: u32 = undefined;
var x1645: u1 = undefined;
subborrowxU32(&x1644, &x1645, x1643, x1619, 0xffffffff);
var x1646: u32 = undefined;
var x1647: u1 = undefined;
subborrowxU32(&x1646, &x1647, x1645, x1621, 0xffffffff);
var x1648: u32 = undefined;
var x1649: u1 = undefined;
subborrowxU32(&x1648, &x1649, x1647, x1623, 0xffffffff);
var x1650: u32 = undefined;
var x1651: u1 = undefined;
subborrowxU32(&x1650, &x1651, x1649, x1625, 0xffffffff);
var x1652: u32 = undefined;
var x1653: u1 = undefined;
subborrowxU32(&x1652, &x1653, x1651, x1627, 0xffffffff);
var x1654: u32 = undefined;
var x1655: u1 = undefined;
subborrowxU32(&x1654, &x1655, x1653, x1629, cast(u32, 0x0));
var x1656: u32 = undefined;
cmovznzU32(&x1656, x1655, x1630, x1605);
var x1657: u32 = undefined;
cmovznzU32(&x1657, x1655, x1632, x1607);
var x1658: u32 = undefined;
cmovznzU32(&x1658, x1655, x1634, x1609);
var x1659: u32 = undefined;
cmovznzU32(&x1659, x1655, x1636, x1611);
var x1660: u32 = undefined;
cmovznzU32(&x1660, x1655, x1638, x1613);
var x1661: u32 = undefined;
cmovznzU32(&x1661, x1655, x1640, x1615);
var x1662: u32 = undefined;
cmovznzU32(&x1662, x1655, x1642, x1617);
var x1663: u32 = undefined;
cmovznzU32(&x1663, x1655, x1644, x1619);
var x1664: u32 = undefined;
cmovznzU32(&x1664, x1655, x1646, x1621);
var x1665: u32 = undefined;
cmovznzU32(&x1665, x1655, x1648, x1623);
var x1666: u32 = undefined;
cmovznzU32(&x1666, x1655, x1650, x1625);
var x1667: u32 = undefined;
cmovznzU32(&x1667, x1655, x1652, x1627);
out1[0] = x1656;
out1[1] = x1657;
out1[2] = x1658;
out1[3] = x1659;
out1[4] = x1660;
out1[5] = x1661;
out1[6] = x1662;
out1[7] = x1663;
out1[8] = x1664;
out1[9] = x1665;
out1[10] = x1666;
out1[11] = x1667;
}
/// The function square squares a field element in the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m
/// 0 ≤ eval out1 < m
///
pub fn square(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[1]);
const x2 = (arg1[2]);
const x3 = (arg1[3]);
const x4 = (arg1[4]);
const x5 = (arg1[5]);
const x6 = (arg1[6]);
const x7 = (arg1[7]);
const x8 = (arg1[8]);
const x9 = (arg1[9]);
const x10 = (arg1[10]);
const x11 = (arg1[11]);
const x12 = (arg1[0]);
var x13: u32 = undefined;
var x14: u32 = undefined;
mulxU32(&x13, &x14, x12, (arg1[11]));
var x15: u32 = undefined;
var x16: u32 = undefined;
mulxU32(&x15, &x16, x12, (arg1[10]));
var x17: u32 = undefined;
var x18: u32 = undefined;
mulxU32(&x17, &x18, x12, (arg1[9]));
var x19: u32 = undefined;
var x20: u32 = undefined;
mulxU32(&x19, &x20, x12, (arg1[8]));
var x21: u32 = undefined;
var x22: u32 = undefined;
mulxU32(&x21, &x22, x12, (arg1[7]));
var x23: u32 = undefined;
var x24: u32 = undefined;
mulxU32(&x23, &x24, x12, (arg1[6]));
var x25: u32 = undefined;
var x26: u32 = undefined;
mulxU32(&x25, &x26, x12, (arg1[5]));
var x27: u32 = undefined;
var x28: u32 = undefined;
mulxU32(&x27, &x28, x12, (arg1[4]));
var x29: u32 = undefined;
var x30: u32 = undefined;
mulxU32(&x29, &x30, x12, (arg1[3]));
var x31: u32 = undefined;
var x32: u32 = undefined;
mulxU32(&x31, &x32, x12, (arg1[2]));
var x33: u32 = undefined;
var x34: u32 = undefined;
mulxU32(&x33, &x34, x12, (arg1[1]));
var x35: u32 = undefined;
var x36: u32 = undefined;
mulxU32(&x35, &x36, x12, (arg1[0]));
var x37: u32 = undefined;
var x38: u1 = undefined;
addcarryxU32(&x37, &x38, 0x0, x36, x33);
var x39: u32 = undefined;
var x40: u1 = undefined;
addcarryxU32(&x39, &x40, x38, x34, x31);
var x41: u32 = undefined;
var x42: u1 = undefined;
addcarryxU32(&x41, &x42, x40, x32, x29);
var x43: u32 = undefined;
var x44: u1 = undefined;
addcarryxU32(&x43, &x44, x42, x30, x27);
var x45: u32 = undefined;
var x46: u1 = undefined;
addcarryxU32(&x45, &x46, x44, x28, x25);
var x47: u32 = undefined;
var x48: u1 = undefined;
addcarryxU32(&x47, &x48, x46, x26, x23);
var x49: u32 = undefined;
var x50: u1 = undefined;
addcarryxU32(&x49, &x50, x48, x24, x21);
var x51: u32 = undefined;
var x52: u1 = undefined;
addcarryxU32(&x51, &x52, x50, x22, x19);
var x53: u32 = undefined;
var x54: u1 = undefined;
addcarryxU32(&x53, &x54, x52, x20, x17);
var x55: u32 = undefined;
var x56: u1 = undefined;
addcarryxU32(&x55, &x56, x54, x18, x15);
var x57: u32 = undefined;
var x58: u1 = undefined;
addcarryxU32(&x57, &x58, x56, x16, x13);
const x59 = (cast(u32, x58) + x14);
var x60: u32 = undefined;
var x61: u32 = undefined;
mulxU32(&x60, &x61, x35, 0xffffffff);
var x62: u32 = undefined;
var x63: u32 = undefined;
mulxU32(&x62, &x63, x35, 0xffffffff);
var x64: u32 = undefined;
var x65: u32 = undefined;
mulxU32(&x64, &x65, x35, 0xffffffff);
var x66: u32 = undefined;
var x67: u32 = undefined;
mulxU32(&x66, &x67, x35, 0xffffffff);
var x68: u32 = undefined;
var x69: u32 = undefined;
mulxU32(&x68, &x69, x35, 0xffffffff);
var x70: u32 = undefined;
var x71: u32 = undefined;
mulxU32(&x70, &x71, x35, 0xffffffff);
var x72: u32 = undefined;
var x73: u32 = undefined;
mulxU32(&x72, &x73, x35, 0xffffffff);
var x74: u32 = undefined;
var x75: u32 = undefined;
mulxU32(&x74, &x75, x35, 0xfffffffe);
var x76: u32 = undefined;
var x77: u32 = undefined;
mulxU32(&x76, &x77, x35, 0xffffffff);
var x78: u32 = undefined;
var x79: u32 = undefined;
mulxU32(&x78, &x79, x35, 0xffffffff);
var x80: u32 = undefined;
var x81: u1 = undefined;
addcarryxU32(&x80, &x81, 0x0, x77, x74);
var x82: u32 = undefined;
var x83: u1 = undefined;
addcarryxU32(&x82, &x83, x81, x75, x72);
var x84: u32 = undefined;
var x85: u1 = undefined;
addcarryxU32(&x84, &x85, x83, x73, x70);
var x86: u32 = undefined;
var x87: u1 = undefined;
addcarryxU32(&x86, &x87, x85, x71, x68);
var x88: u32 = undefined;
var x89: u1 = undefined;
addcarryxU32(&x88, &x89, x87, x69, x66);
var x90: u32 = undefined;
var x91: u1 = undefined;
addcarryxU32(&x90, &x91, x89, x67, x64);
var x92: u32 = undefined;
var x93: u1 = undefined;
addcarryxU32(&x92, &x93, x91, x65, x62);
var x94: u32 = undefined;
var x95: u1 = undefined;
addcarryxU32(&x94, &x95, x93, x63, x60);
const x96 = (cast(u32, x95) + x61);
var x97: u32 = undefined;
var x98: u1 = undefined;
addcarryxU32(&x97, &x98, 0x0, x35, x78);
var x99: u32 = undefined;
var x100: u1 = undefined;
addcarryxU32(&x99, &x100, x98, x37, x79);
var x101: u32 = undefined;
var x102: u1 = undefined;
addcarryxU32(&x101, &x102, x100, x39, cast(u32, 0x0));
var x103: u32 = undefined;
var x104: u1 = undefined;
addcarryxU32(&x103, &x104, x102, x41, x76);
var x105: u32 = undefined;
var x106: u1 = undefined;
addcarryxU32(&x105, &x106, x104, x43, x80);
var x107: u32 = undefined;
var x108: u1 = undefined;
addcarryxU32(&x107, &x108, x106, x45, x82);
var x109: u32 = undefined;
var x110: u1 = undefined;
addcarryxU32(&x109, &x110, x108, x47, x84);
var x111: u32 = undefined;
var x112: u1 = undefined;
addcarryxU32(&x111, &x112, x110, x49, x86);
var x113: u32 = undefined;
var x114: u1 = undefined;
addcarryxU32(&x113, &x114, x112, x51, x88);
var x115: u32 = undefined;
var x116: u1 = undefined;
addcarryxU32(&x115, &x116, x114, x53, x90);
var x117: u32 = undefined;
var x118: u1 = undefined;
addcarryxU32(&x117, &x118, x116, x55, x92);
var x119: u32 = undefined;
var x120: u1 = undefined;
addcarryxU32(&x119, &x120, x118, x57, x94);
var x121: u32 = undefined;
var x122: u1 = undefined;
addcarryxU32(&x121, &x122, x120, x59, x96);
var x123: u32 = undefined;
var x124: u32 = undefined;
mulxU32(&x123, &x124, x1, (arg1[11]));
var x125: u32 = undefined;
var x126: u32 = undefined;
mulxU32(&x125, &x126, x1, (arg1[10]));
var x127: u32 = undefined;
var x128: u32 = undefined;
mulxU32(&x127, &x128, x1, (arg1[9]));
var x129: u32 = undefined;
var x130: u32 = undefined;
mulxU32(&x129, &x130, x1, (arg1[8]));
var x131: u32 = undefined;
var x132: u32 = undefined;
mulxU32(&x131, &x132, x1, (arg1[7]));
var x133: u32 = undefined;
var x134: u32 = undefined;
mulxU32(&x133, &x134, x1, (arg1[6]));
var x135: u32 = undefined;
var x136: u32 = undefined;
mulxU32(&x135, &x136, x1, (arg1[5]));
var x137: u32 = undefined;
var x138: u32 = undefined;
mulxU32(&x137, &x138, x1, (arg1[4]));
var x139: u32 = undefined;
var x140: u32 = undefined;
mulxU32(&x139, &x140, x1, (arg1[3]));
var x141: u32 = undefined;
var x142: u32 = undefined;
mulxU32(&x141, &x142, x1, (arg1[2]));
var x143: u32 = undefined;
var x144: u32 = undefined;
mulxU32(&x143, &x144, x1, (arg1[1]));
var x145: u32 = undefined;
var x146: u32 = undefined;
mulxU32(&x145, &x146, x1, (arg1[0]));
var x147: u32 = undefined;
var x148: u1 = undefined;
addcarryxU32(&x147, &x148, 0x0, x146, x143);
var x149: u32 = undefined;
var x150: u1 = undefined;
addcarryxU32(&x149, &x150, x148, x144, x141);
var x151: u32 = undefined;
var x152: u1 = undefined;
addcarryxU32(&x151, &x152, x150, x142, x139);
var x153: u32 = undefined;
var x154: u1 = undefined;
addcarryxU32(&x153, &x154, x152, x140, x137);
var x155: u32 = undefined;
var x156: u1 = undefined;
addcarryxU32(&x155, &x156, x154, x138, x135);
var x157: u32 = undefined;
var x158: u1 = undefined;
addcarryxU32(&x157, &x158, x156, x136, x133);
var x159: u32 = undefined;
var x160: u1 = undefined;
addcarryxU32(&x159, &x160, x158, x134, x131);
var x161: u32 = undefined;
var x162: u1 = undefined;
addcarryxU32(&x161, &x162, x160, x132, x129);
var x163: u32 = undefined;
var x164: u1 = undefined;
addcarryxU32(&x163, &x164, x162, x130, x127);
var x165: u32 = undefined;
var x166: u1 = undefined;
addcarryxU32(&x165, &x166, x164, x128, x125);
var x167: u32 = undefined;
var x168: u1 = undefined;
addcarryxU32(&x167, &x168, x166, x126, x123);
const x169 = (cast(u32, x168) + x124);
var x170: u32 = undefined;
var x171: u1 = undefined;
addcarryxU32(&x170, &x171, 0x0, x99, x145);
var x172: u32 = undefined;
var x173: u1 = undefined;
addcarryxU32(&x172, &x173, x171, x101, x147);
var x174: u32 = undefined;
var x175: u1 = undefined;
addcarryxU32(&x174, &x175, x173, x103, x149);
var x176: u32 = undefined;
var x177: u1 = undefined;
addcarryxU32(&x176, &x177, x175, x105, x151);
var x178: u32 = undefined;
var x179: u1 = undefined;
addcarryxU32(&x178, &x179, x177, x107, x153);
var x180: u32 = undefined;
var x181: u1 = undefined;
addcarryxU32(&x180, &x181, x179, x109, x155);
var x182: u32 = undefined;
var x183: u1 = undefined;
addcarryxU32(&x182, &x183, x181, x111, x157);
var x184: u32 = undefined;
var x185: u1 = undefined;
addcarryxU32(&x184, &x185, x183, x113, x159);
var x186: u32 = undefined;
var x187: u1 = undefined;
addcarryxU32(&x186, &x187, x185, x115, x161);
var x188: u32 = undefined;
var x189: u1 = undefined;
addcarryxU32(&x188, &x189, x187, x117, x163);
var x190: u32 = undefined;
var x191: u1 = undefined;
addcarryxU32(&x190, &x191, x189, x119, x165);
var x192: u32 = undefined;
var x193: u1 = undefined;
addcarryxU32(&x192, &x193, x191, x121, x167);
var x194: u32 = undefined;
var x195: u1 = undefined;
addcarryxU32(&x194, &x195, x193, cast(u32, x122), x169);
var x196: u32 = undefined;
var x197: u32 = undefined;
mulxU32(&x196, &x197, x170, 0xffffffff);
var x198: u32 = undefined;
var x199: u32 = undefined;
mulxU32(&x198, &x199, x170, 0xffffffff);
var x200: u32 = undefined;
var x201: u32 = undefined;
mulxU32(&x200, &x201, x170, 0xffffffff);
var x202: u32 = undefined;
var x203: u32 = undefined;
mulxU32(&x202, &x203, x170, 0xffffffff);
var x204: u32 = undefined;
var x205: u32 = undefined;
mulxU32(&x204, &x205, x170, 0xffffffff);
var x206: u32 = undefined;
var x207: u32 = undefined;
mulxU32(&x206, &x207, x170, 0xffffffff);
var x208: u32 = undefined;
var x209: u32 = undefined;
mulxU32(&x208, &x209, x170, 0xffffffff);
var x210: u32 = undefined;
var x211: u32 = undefined;
mulxU32(&x210, &x211, x170, 0xfffffffe);
var x212: u32 = undefined;
var x213: u32 = undefined;
mulxU32(&x212, &x213, x170, 0xffffffff);
var x214: u32 = undefined;
var x215: u32 = undefined;
mulxU32(&x214, &x215, x170, 0xffffffff);
var x216: u32 = undefined;
var x217: u1 = undefined;
addcarryxU32(&x216, &x217, 0x0, x213, x210);
var x218: u32 = undefined;
var x219: u1 = undefined;
addcarryxU32(&x218, &x219, x217, x211, x208);
var x220: u32 = undefined;
var x221: u1 = undefined;
addcarryxU32(&x220, &x221, x219, x209, x206);
var x222: u32 = undefined;
var x223: u1 = undefined;
addcarryxU32(&x222, &x223, x221, x207, x204);
var x224: u32 = undefined;
var x225: u1 = undefined;
addcarryxU32(&x224, &x225, x223, x205, x202);
var x226: u32 = undefined;
var x227: u1 = undefined;
addcarryxU32(&x226, &x227, x225, x203, x200);
var x228: u32 = undefined;
var x229: u1 = undefined;
addcarryxU32(&x228, &x229, x227, x201, x198);
var x230: u32 = undefined;
var x231: u1 = undefined;
addcarryxU32(&x230, &x231, x229, x199, x196);
const x232 = (cast(u32, x231) + x197);
var x233: u32 = undefined;
var x234: u1 = undefined;
addcarryxU32(&x233, &x234, 0x0, x170, x214);
var x235: u32 = undefined;
var x236: u1 = undefined;
addcarryxU32(&x235, &x236, x234, x172, x215);
var x237: u32 = undefined;
var x238: u1 = undefined;
addcarryxU32(&x237, &x238, x236, x174, cast(u32, 0x0));
var x239: u32 = undefined;
var x240: u1 = undefined;
addcarryxU32(&x239, &x240, x238, x176, x212);
var x241: u32 = undefined;
var x242: u1 = undefined;
addcarryxU32(&x241, &x242, x240, x178, x216);
var x243: u32 = undefined;
var x244: u1 = undefined;
addcarryxU32(&x243, &x244, x242, x180, x218);
var x245: u32 = undefined;
var x246: u1 = undefined;
addcarryxU32(&x245, &x246, x244, x182, x220);
var x247: u32 = undefined;
var x248: u1 = undefined;
addcarryxU32(&x247, &x248, x246, x184, x222);
var x249: u32 = undefined;
var x250: u1 = undefined;
addcarryxU32(&x249, &x250, x248, x186, x224);
var x251: u32 = undefined;
var x252: u1 = undefined;
addcarryxU32(&x251, &x252, x250, x188, x226);
var x253: u32 = undefined;
var x254: u1 = undefined;
addcarryxU32(&x253, &x254, x252, x190, x228);
var x255: u32 = undefined;
var x256: u1 = undefined;
addcarryxU32(&x255, &x256, x254, x192, x230);
var x257: u32 = undefined;
var x258: u1 = undefined;
addcarryxU32(&x257, &x258, x256, x194, x232);
const x259 = (cast(u32, x258) + cast(u32, x195));
var x260: u32 = undefined;
var x261: u32 = undefined;
mulxU32(&x260, &x261, x2, (arg1[11]));
var x262: u32 = undefined;
var x263: u32 = undefined;
mulxU32(&x262, &x263, x2, (arg1[10]));
var x264: u32 = undefined;
var x265: u32 = undefined;
mulxU32(&x264, &x265, x2, (arg1[9]));
var x266: u32 = undefined;
var x267: u32 = undefined;
mulxU32(&x266, &x267, x2, (arg1[8]));
var x268: u32 = undefined;
var x269: u32 = undefined;
mulxU32(&x268, &x269, x2, (arg1[7]));
var x270: u32 = undefined;
var x271: u32 = undefined;
mulxU32(&x270, &x271, x2, (arg1[6]));
var x272: u32 = undefined;
var x273: u32 = undefined;
mulxU32(&x272, &x273, x2, (arg1[5]));
var x274: u32 = undefined;
var x275: u32 = undefined;
mulxU32(&x274, &x275, x2, (arg1[4]));
var x276: u32 = undefined;
var x277: u32 = undefined;
mulxU32(&x276, &x277, x2, (arg1[3]));
var x278: u32 = undefined;
var x279: u32 = undefined;
mulxU32(&x278, &x279, x2, (arg1[2]));
var x280: u32 = undefined;
var x281: u32 = undefined;
mulxU32(&x280, &x281, x2, (arg1[1]));
var x282: u32 = undefined;
var x283: u32 = undefined;
mulxU32(&x282, &x283, x2, (arg1[0]));
var x284: u32 = undefined;
var x285: u1 = undefined;
addcarryxU32(&x284, &x285, 0x0, x283, x280);
var x286: u32 = undefined;
var x287: u1 = undefined;
addcarryxU32(&x286, &x287, x285, x281, x278);
var x288: u32 = undefined;
var x289: u1 = undefined;
addcarryxU32(&x288, &x289, x287, x279, x276);
var x290: u32 = undefined;
var x291: u1 = undefined;
addcarryxU32(&x290, &x291, x289, x277, x274);
var x292: u32 = undefined;
var x293: u1 = undefined;
addcarryxU32(&x292, &x293, x291, x275, x272);
var x294: u32 = undefined;
var x295: u1 = undefined;
addcarryxU32(&x294, &x295, x293, x273, x270);
var x296: u32 = undefined;
var x297: u1 = undefined;
addcarryxU32(&x296, &x297, x295, x271, x268);
var x298: u32 = undefined;
var x299: u1 = undefined;
addcarryxU32(&x298, &x299, x297, x269, x266);
var x300: u32 = undefined;
var x301: u1 = undefined;
addcarryxU32(&x300, &x301, x299, x267, x264);
var x302: u32 = undefined;
var x303: u1 = undefined;
addcarryxU32(&x302, &x303, x301, x265, x262);
var x304: u32 = undefined;
var x305: u1 = undefined;
addcarryxU32(&x304, &x305, x303, x263, x260);
const x306 = (cast(u32, x305) + x261);
var x307: u32 = undefined;
var x308: u1 = undefined;
addcarryxU32(&x307, &x308, 0x0, x235, x282);
var x309: u32 = undefined;
var x310: u1 = undefined;
addcarryxU32(&x309, &x310, x308, x237, x284);
var x311: u32 = undefined;
var x312: u1 = undefined;
addcarryxU32(&x311, &x312, x310, x239, x286);
var x313: u32 = undefined;
var x314: u1 = undefined;
addcarryxU32(&x313, &x314, x312, x241, x288);
var x315: u32 = undefined;
var x316: u1 = undefined;
addcarryxU32(&x315, &x316, x314, x243, x290);
var x317: u32 = undefined;
var x318: u1 = undefined;
addcarryxU32(&x317, &x318, x316, x245, x292);
var x319: u32 = undefined;
var x320: u1 = undefined;
addcarryxU32(&x319, &x320, x318, x247, x294);
var x321: u32 = undefined;
var x322: u1 = undefined;
addcarryxU32(&x321, &x322, x320, x249, x296);
var x323: u32 = undefined;
var x324: u1 = undefined;
addcarryxU32(&x323, &x324, x322, x251, x298);
var x325: u32 = undefined;
var x326: u1 = undefined;
addcarryxU32(&x325, &x326, x324, x253, x300);
var x327: u32 = undefined;
var x328: u1 = undefined;
addcarryxU32(&x327, &x328, x326, x255, x302);
var x329: u32 = undefined;
var x330: u1 = undefined;
addcarryxU32(&x329, &x330, x328, x257, x304);
var x331: u32 = undefined;
var x332: u1 = undefined;
addcarryxU32(&x331, &x332, x330, x259, x306);
var x333: u32 = undefined;
var x334: u32 = undefined;
mulxU32(&x333, &x334, x307, 0xffffffff);
var x335: u32 = undefined;
var x336: u32 = undefined;
mulxU32(&x335, &x336, x307, 0xffffffff);
var x337: u32 = undefined;
var x338: u32 = undefined;
mulxU32(&x337, &x338, x307, 0xffffffff);
var x339: u32 = undefined;
var x340: u32 = undefined;
mulxU32(&x339, &x340, x307, 0xffffffff);
var x341: u32 = undefined;
var x342: u32 = undefined;
mulxU32(&x341, &x342, x307, 0xffffffff);
var x343: u32 = undefined;
var x344: u32 = undefined;
mulxU32(&x343, &x344, x307, 0xffffffff);
var x345: u32 = undefined;
var x346: u32 = undefined;
mulxU32(&x345, &x346, x307, 0xffffffff);
var x347: u32 = undefined;
var x348: u32 = undefined;
mulxU32(&x347, &x348, x307, 0xfffffffe);
var x349: u32 = undefined;
var x350: u32 = undefined;
mulxU32(&x349, &x350, x307, 0xffffffff);
var x351: u32 = undefined;
var x352: u32 = undefined;
mulxU32(&x351, &x352, x307, 0xffffffff);
var x353: u32 = undefined;
var x354: u1 = undefined;
addcarryxU32(&x353, &x354, 0x0, x350, x347);
var x355: u32 = undefined;
var x356: u1 = undefined;
addcarryxU32(&x355, &x356, x354, x348, x345);
var x357: u32 = undefined;
var x358: u1 = undefined;
addcarryxU32(&x357, &x358, x356, x346, x343);
var x359: u32 = undefined;
var x360: u1 = undefined;
addcarryxU32(&x359, &x360, x358, x344, x341);
var x361: u32 = undefined;
var x362: u1 = undefined;
addcarryxU32(&x361, &x362, x360, x342, x339);
var x363: u32 = undefined;
var x364: u1 = undefined;
addcarryxU32(&x363, &x364, x362, x340, x337);
var x365: u32 = undefined;
var x366: u1 = undefined;
addcarryxU32(&x365, &x366, x364, x338, x335);
var x367: u32 = undefined;
var x368: u1 = undefined;
addcarryxU32(&x367, &x368, x366, x336, x333);
const x369 = (cast(u32, x368) + x334);
var x370: u32 = undefined;
var x371: u1 = undefined;
addcarryxU32(&x370, &x371, 0x0, x307, x351);
var x372: u32 = undefined;
var x373: u1 = undefined;
addcarryxU32(&x372, &x373, x371, x309, x352);
var x374: u32 = undefined;
var x375: u1 = undefined;
addcarryxU32(&x374, &x375, x373, x311, cast(u32, 0x0));
var x376: u32 = undefined;
var x377: u1 = undefined;
addcarryxU32(&x376, &x377, x375, x313, x349);
var x378: u32 = undefined;
var x379: u1 = undefined;
addcarryxU32(&x378, &x379, x377, x315, x353);
var x380: u32 = undefined;
var x381: u1 = undefined;
addcarryxU32(&x380, &x381, x379, x317, x355);
var x382: u32 = undefined;
var x383: u1 = undefined;
addcarryxU32(&x382, &x383, x381, x319, x357);
var x384: u32 = undefined;
var x385: u1 = undefined;
addcarryxU32(&x384, &x385, x383, x321, x359);
var x386: u32 = undefined;
var x387: u1 = undefined;
addcarryxU32(&x386, &x387, x385, x323, x361);
var x388: u32 = undefined;
var x389: u1 = undefined;
addcarryxU32(&x388, &x389, x387, x325, x363);
var x390: u32 = undefined;
var x391: u1 = undefined;
addcarryxU32(&x390, &x391, x389, x327, x365);
var x392: u32 = undefined;
var x393: u1 = undefined;
addcarryxU32(&x392, &x393, x391, x329, x367);
var x394: u32 = undefined;
var x395: u1 = undefined;
addcarryxU32(&x394, &x395, x393, x331, x369);
const x396 = (cast(u32, x395) + cast(u32, x332));
var x397: u32 = undefined;
var x398: u32 = undefined;
mulxU32(&x397, &x398, x3, (arg1[11]));
var x399: u32 = undefined;
var x400: u32 = undefined;
mulxU32(&x399, &x400, x3, (arg1[10]));
var x401: u32 = undefined;
var x402: u32 = undefined;
mulxU32(&x401, &x402, x3, (arg1[9]));
var x403: u32 = undefined;
var x404: u32 = undefined;
mulxU32(&x403, &x404, x3, (arg1[8]));
var x405: u32 = undefined;
var x406: u32 = undefined;
mulxU32(&x405, &x406, x3, (arg1[7]));
var x407: u32 = undefined;
var x408: u32 = undefined;
mulxU32(&x407, &x408, x3, (arg1[6]));
var x409: u32 = undefined;
var x410: u32 = undefined;
mulxU32(&x409, &x410, x3, (arg1[5]));
var x411: u32 = undefined;
var x412: u32 = undefined;
mulxU32(&x411, &x412, x3, (arg1[4]));
var x413: u32 = undefined;
var x414: u32 = undefined;
mulxU32(&x413, &x414, x3, (arg1[3]));
var x415: u32 = undefined;
var x416: u32 = undefined;
mulxU32(&x415, &x416, x3, (arg1[2]));
var x417: u32 = undefined;
var x418: u32 = undefined;
mulxU32(&x417, &x418, x3, (arg1[1]));
var x419: u32 = undefined;
var x420: u32 = undefined;
mulxU32(&x419, &x420, x3, (arg1[0]));
var x421: u32 = undefined;
var x422: u1 = undefined;
addcarryxU32(&x421, &x422, 0x0, x420, x417);
var x423: u32 = undefined;
var x424: u1 = undefined;
addcarryxU32(&x423, &x424, x422, x418, x415);
var x425: u32 = undefined;
var x426: u1 = undefined;
addcarryxU32(&x425, &x426, x424, x416, x413);
var x427: u32 = undefined;
var x428: u1 = undefined;
addcarryxU32(&x427, &x428, x426, x414, x411);
var x429: u32 = undefined;
var x430: u1 = undefined;
addcarryxU32(&x429, &x430, x428, x412, x409);
var x431: u32 = undefined;
var x432: u1 = undefined;
addcarryxU32(&x431, &x432, x430, x410, x407);
var x433: u32 = undefined;
var x434: u1 = undefined;
addcarryxU32(&x433, &x434, x432, x408, x405);
var x435: u32 = undefined;
var x436: u1 = undefined;
addcarryxU32(&x435, &x436, x434, x406, x403);
var x437: u32 = undefined;
var x438: u1 = undefined;
addcarryxU32(&x437, &x438, x436, x404, x401);
var x439: u32 = undefined;
var x440: u1 = undefined;
addcarryxU32(&x439, &x440, x438, x402, x399);
var x441: u32 = undefined;
var x442: u1 = undefined;
addcarryxU32(&x441, &x442, x440, x400, x397);
const x443 = (cast(u32, x442) + x398);
var x444: u32 = undefined;
var x445: u1 = undefined;
addcarryxU32(&x444, &x445, 0x0, x372, x419);
var x446: u32 = undefined;
var x447: u1 = undefined;
addcarryxU32(&x446, &x447, x445, x374, x421);
var x448: u32 = undefined;
var x449: u1 = undefined;
addcarryxU32(&x448, &x449, x447, x376, x423);
var x450: u32 = undefined;
var x451: u1 = undefined;
addcarryxU32(&x450, &x451, x449, x378, x425);
var x452: u32 = undefined;
var x453: u1 = undefined;
addcarryxU32(&x452, &x453, x451, x380, x427);
var x454: u32 = undefined;
var x455: u1 = undefined;
addcarryxU32(&x454, &x455, x453, x382, x429);
var x456: u32 = undefined;
var x457: u1 = undefined;
addcarryxU32(&x456, &x457, x455, x384, x431);
var x458: u32 = undefined;
var x459: u1 = undefined;
addcarryxU32(&x458, &x459, x457, x386, x433);
var x460: u32 = undefined;
var x461: u1 = undefined;
addcarryxU32(&x460, &x461, x459, x388, x435);
var x462: u32 = undefined;
var x463: u1 = undefined;
addcarryxU32(&x462, &x463, x461, x390, x437);
var x464: u32 = undefined;
var x465: u1 = undefined;
addcarryxU32(&x464, &x465, x463, x392, x439);
var x466: u32 = undefined;
var x467: u1 = undefined;
addcarryxU32(&x466, &x467, x465, x394, x441);
var x468: u32 = undefined;
var x469: u1 = undefined;
addcarryxU32(&x468, &x469, x467, x396, x443);
var x470: u32 = undefined;
var x471: u32 = undefined;
mulxU32(&x470, &x471, x444, 0xffffffff);
var x472: u32 = undefined;
var x473: u32 = undefined;
mulxU32(&x472, &x473, x444, 0xffffffff);
var x474: u32 = undefined;
var x475: u32 = undefined;
mulxU32(&x474, &x475, x444, 0xffffffff);
var x476: u32 = undefined;
var x477: u32 = undefined;
mulxU32(&x476, &x477, x444, 0xffffffff);
var x478: u32 = undefined;
var x479: u32 = undefined;
mulxU32(&x478, &x479, x444, 0xffffffff);
var x480: u32 = undefined;
var x481: u32 = undefined;
mulxU32(&x480, &x481, x444, 0xffffffff);
var x482: u32 = undefined;
var x483: u32 = undefined;
mulxU32(&x482, &x483, x444, 0xffffffff);
var x484: u32 = undefined;
var x485: u32 = undefined;
mulxU32(&x484, &x485, x444, 0xfffffffe);
var x486: u32 = undefined;
var x487: u32 = undefined;
mulxU32(&x486, &x487, x444, 0xffffffff);
var x488: u32 = undefined;
var x489: u32 = undefined;
mulxU32(&x488, &x489, x444, 0xffffffff);
var x490: u32 = undefined;
var x491: u1 = undefined;
addcarryxU32(&x490, &x491, 0x0, x487, x484);
var x492: u32 = undefined;
var x493: u1 = undefined;
addcarryxU32(&x492, &x493, x491, x485, x482);
var x494: u32 = undefined;
var x495: u1 = undefined;
addcarryxU32(&x494, &x495, x493, x483, x480);
var x496: u32 = undefined;
var x497: u1 = undefined;
addcarryxU32(&x496, &x497, x495, x481, x478);
var x498: u32 = undefined;
var x499: u1 = undefined;
addcarryxU32(&x498, &x499, x497, x479, x476);
var x500: u32 = undefined;
var x501: u1 = undefined;
addcarryxU32(&x500, &x501, x499, x477, x474);
var x502: u32 = undefined;
var x503: u1 = undefined;
addcarryxU32(&x502, &x503, x501, x475, x472);
var x504: u32 = undefined;
var x505: u1 = undefined;
addcarryxU32(&x504, &x505, x503, x473, x470);
const x506 = (cast(u32, x505) + x471);
var x507: u32 = undefined;
var x508: u1 = undefined;
addcarryxU32(&x507, &x508, 0x0, x444, x488);
var x509: u32 = undefined;
var x510: u1 = undefined;
addcarryxU32(&x509, &x510, x508, x446, x489);
var x511: u32 = undefined;
var x512: u1 = undefined;
addcarryxU32(&x511, &x512, x510, x448, cast(u32, 0x0));
var x513: u32 = undefined;
var x514: u1 = undefined;
addcarryxU32(&x513, &x514, x512, x450, x486);
var x515: u32 = undefined;
var x516: u1 = undefined;
addcarryxU32(&x515, &x516, x514, x452, x490);
var x517: u32 = undefined;
var x518: u1 = undefined;
addcarryxU32(&x517, &x518, x516, x454, x492);
var x519: u32 = undefined;
var x520: u1 = undefined;
addcarryxU32(&x519, &x520, x518, x456, x494);
var x521: u32 = undefined;
var x522: u1 = undefined;
addcarryxU32(&x521, &x522, x520, x458, x496);
var x523: u32 = undefined;
var x524: u1 = undefined;
addcarryxU32(&x523, &x524, x522, x460, x498);
var x525: u32 = undefined;
var x526: u1 = undefined;
addcarryxU32(&x525, &x526, x524, x462, x500);
var x527: u32 = undefined;
var x528: u1 = undefined;
addcarryxU32(&x527, &x528, x526, x464, x502);
var x529: u32 = undefined;
var x530: u1 = undefined;
addcarryxU32(&x529, &x530, x528, x466, x504);
var x531: u32 = undefined;
var x532: u1 = undefined;
addcarryxU32(&x531, &x532, x530, x468, x506);
const x533 = (cast(u32, x532) + cast(u32, x469));
var x534: u32 = undefined;
var x535: u32 = undefined;
mulxU32(&x534, &x535, x4, (arg1[11]));
var x536: u32 = undefined;
var x537: u32 = undefined;
mulxU32(&x536, &x537, x4, (arg1[10]));
var x538: u32 = undefined;
var x539: u32 = undefined;
mulxU32(&x538, &x539, x4, (arg1[9]));
var x540: u32 = undefined;
var x541: u32 = undefined;
mulxU32(&x540, &x541, x4, (arg1[8]));
var x542: u32 = undefined;
var x543: u32 = undefined;
mulxU32(&x542, &x543, x4, (arg1[7]));
var x544: u32 = undefined;
var x545: u32 = undefined;
mulxU32(&x544, &x545, x4, (arg1[6]));
var x546: u32 = undefined;
var x547: u32 = undefined;
mulxU32(&x546, &x547, x4, (arg1[5]));
var x548: u32 = undefined;
var x549: u32 = undefined;
mulxU32(&x548, &x549, x4, (arg1[4]));
var x550: u32 = undefined;
var x551: u32 = undefined;
mulxU32(&x550, &x551, x4, (arg1[3]));
var x552: u32 = undefined;
var x553: u32 = undefined;
mulxU32(&x552, &x553, x4, (arg1[2]));
var x554: u32 = undefined;
var x555: u32 = undefined;
mulxU32(&x554, &x555, x4, (arg1[1]));
var x556: u32 = undefined;
var x557: u32 = undefined;
mulxU32(&x556, &x557, x4, (arg1[0]));
var x558: u32 = undefined;
var x559: u1 = undefined;
addcarryxU32(&x558, &x559, 0x0, x557, x554);
var x560: u32 = undefined;
var x561: u1 = undefined;
addcarryxU32(&x560, &x561, x559, x555, x552);
var x562: u32 = undefined;
var x563: u1 = undefined;
addcarryxU32(&x562, &x563, x561, x553, x550);
var x564: u32 = undefined;
var x565: u1 = undefined;
addcarryxU32(&x564, &x565, x563, x551, x548);
var x566: u32 = undefined;
var x567: u1 = undefined;
addcarryxU32(&x566, &x567, x565, x549, x546);
var x568: u32 = undefined;
var x569: u1 = undefined;
addcarryxU32(&x568, &x569, x567, x547, x544);
var x570: u32 = undefined;
var x571: u1 = undefined;
addcarryxU32(&x570, &x571, x569, x545, x542);
var x572: u32 = undefined;
var x573: u1 = undefined;
addcarryxU32(&x572, &x573, x571, x543, x540);
var x574: u32 = undefined;
var x575: u1 = undefined;
addcarryxU32(&x574, &x575, x573, x541, x538);
var x576: u32 = undefined;
var x577: u1 = undefined;
addcarryxU32(&x576, &x577, x575, x539, x536);
var x578: u32 = undefined;
var x579: u1 = undefined;
addcarryxU32(&x578, &x579, x577, x537, x534);
const x580 = (cast(u32, x579) + x535);
var x581: u32 = undefined;
var x582: u1 = undefined;
addcarryxU32(&x581, &x582, 0x0, x509, x556);
var x583: u32 = undefined;
var x584: u1 = undefined;
addcarryxU32(&x583, &x584, x582, x511, x558);
var x585: u32 = undefined;
var x586: u1 = undefined;
addcarryxU32(&x585, &x586, x584, x513, x560);
var x587: u32 = undefined;
var x588: u1 = undefined;
addcarryxU32(&x587, &x588, x586, x515, x562);
var x589: u32 = undefined;
var x590: u1 = undefined;
addcarryxU32(&x589, &x590, x588, x517, x564);
var x591: u32 = undefined;
var x592: u1 = undefined;
addcarryxU32(&x591, &x592, x590, x519, x566);
var x593: u32 = undefined;
var x594: u1 = undefined;
addcarryxU32(&x593, &x594, x592, x521, x568);
var x595: u32 = undefined;
var x596: u1 = undefined;
addcarryxU32(&x595, &x596, x594, x523, x570);
var x597: u32 = undefined;
var x598: u1 = undefined;
addcarryxU32(&x597, &x598, x596, x525, x572);
var x599: u32 = undefined;
var x600: u1 = undefined;
addcarryxU32(&x599, &x600, x598, x527, x574);
var x601: u32 = undefined;
var x602: u1 = undefined;
addcarryxU32(&x601, &x602, x600, x529, x576);
var x603: u32 = undefined;
var x604: u1 = undefined;
addcarryxU32(&x603, &x604, x602, x531, x578);
var x605: u32 = undefined;
var x606: u1 = undefined;
addcarryxU32(&x605, &x606, x604, x533, x580);
var x607: u32 = undefined;
var x608: u32 = undefined;
mulxU32(&x607, &x608, x581, 0xffffffff);
var x609: u32 = undefined;
var x610: u32 = undefined;
mulxU32(&x609, &x610, x581, 0xffffffff);
var x611: u32 = undefined;
var x612: u32 = undefined;
mulxU32(&x611, &x612, x581, 0xffffffff);
var x613: u32 = undefined;
var x614: u32 = undefined;
mulxU32(&x613, &x614, x581, 0xffffffff);
var x615: u32 = undefined;
var x616: u32 = undefined;
mulxU32(&x615, &x616, x581, 0xffffffff);
var x617: u32 = undefined;
var x618: u32 = undefined;
mulxU32(&x617, &x618, x581, 0xffffffff);
var x619: u32 = undefined;
var x620: u32 = undefined;
mulxU32(&x619, &x620, x581, 0xffffffff);
var x621: u32 = undefined;
var x622: u32 = undefined;
mulxU32(&x621, &x622, x581, 0xfffffffe);
var x623: u32 = undefined;
var x624: u32 = undefined;
mulxU32(&x623, &x624, x581, 0xffffffff);
var x625: u32 = undefined;
var x626: u32 = undefined;
mulxU32(&x625, &x626, x581, 0xffffffff);
var x627: u32 = undefined;
var x628: u1 = undefined;
addcarryxU32(&x627, &x628, 0x0, x624, x621);
var x629: u32 = undefined;
var x630: u1 = undefined;
addcarryxU32(&x629, &x630, x628, x622, x619);
var x631: u32 = undefined;
var x632: u1 = undefined;
addcarryxU32(&x631, &x632, x630, x620, x617);
var x633: u32 = undefined;
var x634: u1 = undefined;
addcarryxU32(&x633, &x634, x632, x618, x615);
var x635: u32 = undefined;
var x636: u1 = undefined;
addcarryxU32(&x635, &x636, x634, x616, x613);
var x637: u32 = undefined;
var x638: u1 = undefined;
addcarryxU32(&x637, &x638, x636, x614, x611);
var x639: u32 = undefined;
var x640: u1 = undefined;
addcarryxU32(&x639, &x640, x638, x612, x609);
var x641: u32 = undefined;
var x642: u1 = undefined;
addcarryxU32(&x641, &x642, x640, x610, x607);
const x643 = (cast(u32, x642) + x608);
var x644: u32 = undefined;
var x645: u1 = undefined;
addcarryxU32(&x644, &x645, 0x0, x581, x625);
var x646: u32 = undefined;
var x647: u1 = undefined;
addcarryxU32(&x646, &x647, x645, x583, x626);
var x648: u32 = undefined;
var x649: u1 = undefined;
addcarryxU32(&x648, &x649, x647, x585, cast(u32, 0x0));
var x650: u32 = undefined;
var x651: u1 = undefined;
addcarryxU32(&x650, &x651, x649, x587, x623);
var x652: u32 = undefined;
var x653: u1 = undefined;
addcarryxU32(&x652, &x653, x651, x589, x627);
var x654: u32 = undefined;
var x655: u1 = undefined;
addcarryxU32(&x654, &x655, x653, x591, x629);
var x656: u32 = undefined;
var x657: u1 = undefined;
addcarryxU32(&x656, &x657, x655, x593, x631);
var x658: u32 = undefined;
var x659: u1 = undefined;
addcarryxU32(&x658, &x659, x657, x595, x633);
var x660: u32 = undefined;
var x661: u1 = undefined;
addcarryxU32(&x660, &x661, x659, x597, x635);
var x662: u32 = undefined;
var x663: u1 = undefined;
addcarryxU32(&x662, &x663, x661, x599, x637);
var x664: u32 = undefined;
var x665: u1 = undefined;
addcarryxU32(&x664, &x665, x663, x601, x639);
var x666: u32 = undefined;
var x667: u1 = undefined;
addcarryxU32(&x666, &x667, x665, x603, x641);
var x668: u32 = undefined;
var x669: u1 = undefined;
addcarryxU32(&x668, &x669, x667, x605, x643);
const x670 = (cast(u32, x669) + cast(u32, x606));
var x671: u32 = undefined;
var x672: u32 = undefined;
mulxU32(&x671, &x672, x5, (arg1[11]));
var x673: u32 = undefined;
var x674: u32 = undefined;
mulxU32(&x673, &x674, x5, (arg1[10]));
var x675: u32 = undefined;
var x676: u32 = undefined;
mulxU32(&x675, &x676, x5, (arg1[9]));
var x677: u32 = undefined;
var x678: u32 = undefined;
mulxU32(&x677, &x678, x5, (arg1[8]));
var x679: u32 = undefined;
var x680: u32 = undefined;
mulxU32(&x679, &x680, x5, (arg1[7]));
var x681: u32 = undefined;
var x682: u32 = undefined;
mulxU32(&x681, &x682, x5, (arg1[6]));
var x683: u32 = undefined;
var x684: u32 = undefined;
mulxU32(&x683, &x684, x5, (arg1[5]));
var x685: u32 = undefined;
var x686: u32 = undefined;
mulxU32(&x685, &x686, x5, (arg1[4]));
var x687: u32 = undefined;
var x688: u32 = undefined;
mulxU32(&x687, &x688, x5, (arg1[3]));
var x689: u32 = undefined;
var x690: u32 = undefined;
mulxU32(&x689, &x690, x5, (arg1[2]));
var x691: u32 = undefined;
var x692: u32 = undefined;
mulxU32(&x691, &x692, x5, (arg1[1]));
var x693: u32 = undefined;
var x694: u32 = undefined;
mulxU32(&x693, &x694, x5, (arg1[0]));
var x695: u32 = undefined;
var x696: u1 = undefined;
addcarryxU32(&x695, &x696, 0x0, x694, x691);
var x697: u32 = undefined;
var x698: u1 = undefined;
addcarryxU32(&x697, &x698, x696, x692, x689);
var x699: u32 = undefined;
var x700: u1 = undefined;
addcarryxU32(&x699, &x700, x698, x690, x687);
var x701: u32 = undefined;
var x702: u1 = undefined;
addcarryxU32(&x701, &x702, x700, x688, x685);
var x703: u32 = undefined;
var x704: u1 = undefined;
addcarryxU32(&x703, &x704, x702, x686, x683);
var x705: u32 = undefined;
var x706: u1 = undefined;
addcarryxU32(&x705, &x706, x704, x684, x681);
var x707: u32 = undefined;
var x708: u1 = undefined;
addcarryxU32(&x707, &x708, x706, x682, x679);
var x709: u32 = undefined;
var x710: u1 = undefined;
addcarryxU32(&x709, &x710, x708, x680, x677);
var x711: u32 = undefined;
var x712: u1 = undefined;
addcarryxU32(&x711, &x712, x710, x678, x675);
var x713: u32 = undefined;
var x714: u1 = undefined;
addcarryxU32(&x713, &x714, x712, x676, x673);
var x715: u32 = undefined;
var x716: u1 = undefined;
addcarryxU32(&x715, &x716, x714, x674, x671);
const x717 = (cast(u32, x716) + x672);
var x718: u32 = undefined;
var x719: u1 = undefined;
addcarryxU32(&x718, &x719, 0x0, x646, x693);
var x720: u32 = undefined;
var x721: u1 = undefined;
addcarryxU32(&x720, &x721, x719, x648, x695);
var x722: u32 = undefined;
var x723: u1 = undefined;
addcarryxU32(&x722, &x723, x721, x650, x697);
var x724: u32 = undefined;
var x725: u1 = undefined;
addcarryxU32(&x724, &x725, x723, x652, x699);
var x726: u32 = undefined;
var x727: u1 = undefined;
addcarryxU32(&x726, &x727, x725, x654, x701);
var x728: u32 = undefined;
var x729: u1 = undefined;
addcarryxU32(&x728, &x729, x727, x656, x703);
var x730: u32 = undefined;
var x731: u1 = undefined;
addcarryxU32(&x730, &x731, x729, x658, x705);
var x732: u32 = undefined;
var x733: u1 = undefined;
addcarryxU32(&x732, &x733, x731, x660, x707);
var x734: u32 = undefined;
var x735: u1 = undefined;
addcarryxU32(&x734, &x735, x733, x662, x709);
var x736: u32 = undefined;
var x737: u1 = undefined;
addcarryxU32(&x736, &x737, x735, x664, x711);
var x738: u32 = undefined;
var x739: u1 = undefined;
addcarryxU32(&x738, &x739, x737, x666, x713);
var x740: u32 = undefined;
var x741: u1 = undefined;
addcarryxU32(&x740, &x741, x739, x668, x715);
var x742: u32 = undefined;
var x743: u1 = undefined;
addcarryxU32(&x742, &x743, x741, x670, x717);
var x744: u32 = undefined;
var x745: u32 = undefined;
mulxU32(&x744, &x745, x718, 0xffffffff);
var x746: u32 = undefined;
var x747: u32 = undefined;
mulxU32(&x746, &x747, x718, 0xffffffff);
var x748: u32 = undefined;
var x749: u32 = undefined;
mulxU32(&x748, &x749, x718, 0xffffffff);
var x750: u32 = undefined;
var x751: u32 = undefined;
mulxU32(&x750, &x751, x718, 0xffffffff);
var x752: u32 = undefined;
var x753: u32 = undefined;
mulxU32(&x752, &x753, x718, 0xffffffff);
var x754: u32 = undefined;
var x755: u32 = undefined;
mulxU32(&x754, &x755, x718, 0xffffffff);
var x756: u32 = undefined;
var x757: u32 = undefined;
mulxU32(&x756, &x757, x718, 0xffffffff);
var x758: u32 = undefined;
var x759: u32 = undefined;
mulxU32(&x758, &x759, x718, 0xfffffffe);
var x760: u32 = undefined;
var x761: u32 = undefined;
mulxU32(&x760, &x761, x718, 0xffffffff);
var x762: u32 = undefined;
var x763: u32 = undefined;
mulxU32(&x762, &x763, x718, 0xffffffff);
var x764: u32 = undefined;
var x765: u1 = undefined;
addcarryxU32(&x764, &x765, 0x0, x761, x758);
var x766: u32 = undefined;
var x767: u1 = undefined;
addcarryxU32(&x766, &x767, x765, x759, x756);
var x768: u32 = undefined;
var x769: u1 = undefined;
addcarryxU32(&x768, &x769, x767, x757, x754);
var x770: u32 = undefined;
var x771: u1 = undefined;
addcarryxU32(&x770, &x771, x769, x755, x752);
var x772: u32 = undefined;
var x773: u1 = undefined;
addcarryxU32(&x772, &x773, x771, x753, x750);
var x774: u32 = undefined;
var x775: u1 = undefined;
addcarryxU32(&x774, &x775, x773, x751, x748);
var x776: u32 = undefined;
var x777: u1 = undefined;
addcarryxU32(&x776, &x777, x775, x749, x746);
var x778: u32 = undefined;
var x779: u1 = undefined;
addcarryxU32(&x778, &x779, x777, x747, x744);
const x780 = (cast(u32, x779) + x745);
var x781: u32 = undefined;
var x782: u1 = undefined;
addcarryxU32(&x781, &x782, 0x0, x718, x762);
var x783: u32 = undefined;
var x784: u1 = undefined;
addcarryxU32(&x783, &x784, x782, x720, x763);
var x785: u32 = undefined;
var x786: u1 = undefined;
addcarryxU32(&x785, &x786, x784, x722, cast(u32, 0x0));
var x787: u32 = undefined;
var x788: u1 = undefined;
addcarryxU32(&x787, &x788, x786, x724, x760);
var x789: u32 = undefined;
var x790: u1 = undefined;
addcarryxU32(&x789, &x790, x788, x726, x764);
var x791: u32 = undefined;
var x792: u1 = undefined;
addcarryxU32(&x791, &x792, x790, x728, x766);
var x793: u32 = undefined;
var x794: u1 = undefined;
addcarryxU32(&x793, &x794, x792, x730, x768);
var x795: u32 = undefined;
var x796: u1 = undefined;
addcarryxU32(&x795, &x796, x794, x732, x770);
var x797: u32 = undefined;
var x798: u1 = undefined;
addcarryxU32(&x797, &x798, x796, x734, x772);
var x799: u32 = undefined;
var x800: u1 = undefined;
addcarryxU32(&x799, &x800, x798, x736, x774);
var x801: u32 = undefined;
var x802: u1 = undefined;
addcarryxU32(&x801, &x802, x800, x738, x776);
var x803: u32 = undefined;
var x804: u1 = undefined;
addcarryxU32(&x803, &x804, x802, x740, x778);
var x805: u32 = undefined;
var x806: u1 = undefined;
addcarryxU32(&x805, &x806, x804, x742, x780);
const x807 = (cast(u32, x806) + cast(u32, x743));
var x808: u32 = undefined;
var x809: u32 = undefined;
mulxU32(&x808, &x809, x6, (arg1[11]));
var x810: u32 = undefined;
var x811: u32 = undefined;
mulxU32(&x810, &x811, x6, (arg1[10]));
var x812: u32 = undefined;
var x813: u32 = undefined;
mulxU32(&x812, &x813, x6, (arg1[9]));
var x814: u32 = undefined;
var x815: u32 = undefined;
mulxU32(&x814, &x815, x6, (arg1[8]));
var x816: u32 = undefined;
var x817: u32 = undefined;
mulxU32(&x816, &x817, x6, (arg1[7]));
var x818: u32 = undefined;
var x819: u32 = undefined;
mulxU32(&x818, &x819, x6, (arg1[6]));
var x820: u32 = undefined;
var x821: u32 = undefined;
mulxU32(&x820, &x821, x6, (arg1[5]));
var x822: u32 = undefined;
var x823: u32 = undefined;
mulxU32(&x822, &x823, x6, (arg1[4]));
var x824: u32 = undefined;
var x825: u32 = undefined;
mulxU32(&x824, &x825, x6, (arg1[3]));
var x826: u32 = undefined;
var x827: u32 = undefined;
mulxU32(&x826, &x827, x6, (arg1[2]));
var x828: u32 = undefined;
var x829: u32 = undefined;
mulxU32(&x828, &x829, x6, (arg1[1]));
var x830: u32 = undefined;
var x831: u32 = undefined;
mulxU32(&x830, &x831, x6, (arg1[0]));
var x832: u32 = undefined;
var x833: u1 = undefined;
addcarryxU32(&x832, &x833, 0x0, x831, x828);
var x834: u32 = undefined;
var x835: u1 = undefined;
addcarryxU32(&x834, &x835, x833, x829, x826);
var x836: u32 = undefined;
var x837: u1 = undefined;
addcarryxU32(&x836, &x837, x835, x827, x824);
var x838: u32 = undefined;
var x839: u1 = undefined;
addcarryxU32(&x838, &x839, x837, x825, x822);
var x840: u32 = undefined;
var x841: u1 = undefined;
addcarryxU32(&x840, &x841, x839, x823, x820);
var x842: u32 = undefined;
var x843: u1 = undefined;
addcarryxU32(&x842, &x843, x841, x821, x818);
var x844: u32 = undefined;
var x845: u1 = undefined;
addcarryxU32(&x844, &x845, x843, x819, x816);
var x846: u32 = undefined;
var x847: u1 = undefined;
addcarryxU32(&x846, &x847, x845, x817, x814);
var x848: u32 = undefined;
var x849: u1 = undefined;
addcarryxU32(&x848, &x849, x847, x815, x812);
var x850: u32 = undefined;
var x851: u1 = undefined;
addcarryxU32(&x850, &x851, x849, x813, x810);
var x852: u32 = undefined;
var x853: u1 = undefined;
addcarryxU32(&x852, &x853, x851, x811, x808);
const x854 = (cast(u32, x853) + x809);
var x855: u32 = undefined;
var x856: u1 = undefined;
addcarryxU32(&x855, &x856, 0x0, x783, x830);
var x857: u32 = undefined;
var x858: u1 = undefined;
addcarryxU32(&x857, &x858, x856, x785, x832);
var x859: u32 = undefined;
var x860: u1 = undefined;
addcarryxU32(&x859, &x860, x858, x787, x834);
var x861: u32 = undefined;
var x862: u1 = undefined;
addcarryxU32(&x861, &x862, x860, x789, x836);
var x863: u32 = undefined;
var x864: u1 = undefined;
addcarryxU32(&x863, &x864, x862, x791, x838);
var x865: u32 = undefined;
var x866: u1 = undefined;
addcarryxU32(&x865, &x866, x864, x793, x840);
var x867: u32 = undefined;
var x868: u1 = undefined;
addcarryxU32(&x867, &x868, x866, x795, x842);
var x869: u32 = undefined;
var x870: u1 = undefined;
addcarryxU32(&x869, &x870, x868, x797, x844);
var x871: u32 = undefined;
var x872: u1 = undefined;
addcarryxU32(&x871, &x872, x870, x799, x846);
var x873: u32 = undefined;
var x874: u1 = undefined;
addcarryxU32(&x873, &x874, x872, x801, x848);
var x875: u32 = undefined;
var x876: u1 = undefined;
addcarryxU32(&x875, &x876, x874, x803, x850);
var x877: u32 = undefined;
var x878: u1 = undefined;
addcarryxU32(&x877, &x878, x876, x805, x852);
var x879: u32 = undefined;
var x880: u1 = undefined;
addcarryxU32(&x879, &x880, x878, x807, x854);
var x881: u32 = undefined;
var x882: u32 = undefined;
mulxU32(&x881, &x882, x855, 0xffffffff);
var x883: u32 = undefined;
var x884: u32 = undefined;
mulxU32(&x883, &x884, x855, 0xffffffff);
var x885: u32 = undefined;
var x886: u32 = undefined;
mulxU32(&x885, &x886, x855, 0xffffffff);
var x887: u32 = undefined;
var x888: u32 = undefined;
mulxU32(&x887, &x888, x855, 0xffffffff);
var x889: u32 = undefined;
var x890: u32 = undefined;
mulxU32(&x889, &x890, x855, 0xffffffff);
var x891: u32 = undefined;
var x892: u32 = undefined;
mulxU32(&x891, &x892, x855, 0xffffffff);
var x893: u32 = undefined;
var x894: u32 = undefined;
mulxU32(&x893, &x894, x855, 0xffffffff);
var x895: u32 = undefined;
var x896: u32 = undefined;
mulxU32(&x895, &x896, x855, 0xfffffffe);
var x897: u32 = undefined;
var x898: u32 = undefined;
mulxU32(&x897, &x898, x855, 0xffffffff);
var x899: u32 = undefined;
var x900: u32 = undefined;
mulxU32(&x899, &x900, x855, 0xffffffff);
var x901: u32 = undefined;
var x902: u1 = undefined;
addcarryxU32(&x901, &x902, 0x0, x898, x895);
var x903: u32 = undefined;
var x904: u1 = undefined;
addcarryxU32(&x903, &x904, x902, x896, x893);
var x905: u32 = undefined;
var x906: u1 = undefined;
addcarryxU32(&x905, &x906, x904, x894, x891);
var x907: u32 = undefined;
var x908: u1 = undefined;
addcarryxU32(&x907, &x908, x906, x892, x889);
var x909: u32 = undefined;
var x910: u1 = undefined;
addcarryxU32(&x909, &x910, x908, x890, x887);
var x911: u32 = undefined;
var x912: u1 = undefined;
addcarryxU32(&x911, &x912, x910, x888, x885);
var x913: u32 = undefined;
var x914: u1 = undefined;
addcarryxU32(&x913, &x914, x912, x886, x883);
var x915: u32 = undefined;
var x916: u1 = undefined;
addcarryxU32(&x915, &x916, x914, x884, x881);
const x917 = (cast(u32, x916) + x882);
var x918: u32 = undefined;
var x919: u1 = undefined;
addcarryxU32(&x918, &x919, 0x0, x855, x899);
var x920: u32 = undefined;
var x921: u1 = undefined;
addcarryxU32(&x920, &x921, x919, x857, x900);
var x922: u32 = undefined;
var x923: u1 = undefined;
addcarryxU32(&x922, &x923, x921, x859, cast(u32, 0x0));
var x924: u32 = undefined;
var x925: u1 = undefined;
addcarryxU32(&x924, &x925, x923, x861, x897);
var x926: u32 = undefined;
var x927: u1 = undefined;
addcarryxU32(&x926, &x927, x925, x863, x901);
var x928: u32 = undefined;
var x929: u1 = undefined;
addcarryxU32(&x928, &x929, x927, x865, x903);
var x930: u32 = undefined;
var x931: u1 = undefined;
addcarryxU32(&x930, &x931, x929, x867, x905);
var x932: u32 = undefined;
var x933: u1 = undefined;
addcarryxU32(&x932, &x933, x931, x869, x907);
var x934: u32 = undefined;
var x935: u1 = undefined;
addcarryxU32(&x934, &x935, x933, x871, x909);
var x936: u32 = undefined;
var x937: u1 = undefined;
addcarryxU32(&x936, &x937, x935, x873, x911);
var x938: u32 = undefined;
var x939: u1 = undefined;
addcarryxU32(&x938, &x939, x937, x875, x913);
var x940: u32 = undefined;
var x941: u1 = undefined;
addcarryxU32(&x940, &x941, x939, x877, x915);
var x942: u32 = undefined;
var x943: u1 = undefined;
addcarryxU32(&x942, &x943, x941, x879, x917);
const x944 = (cast(u32, x943) + cast(u32, x880));
var x945: u32 = undefined;
var x946: u32 = undefined;
mulxU32(&x945, &x946, x7, (arg1[11]));
var x947: u32 = undefined;
var x948: u32 = undefined;
mulxU32(&x947, &x948, x7, (arg1[10]));
var x949: u32 = undefined;
var x950: u32 = undefined;
mulxU32(&x949, &x950, x7, (arg1[9]));
var x951: u32 = undefined;
var x952: u32 = undefined;
mulxU32(&x951, &x952, x7, (arg1[8]));
var x953: u32 = undefined;
var x954: u32 = undefined;
mulxU32(&x953, &x954, x7, (arg1[7]));
var x955: u32 = undefined;
var x956: u32 = undefined;
mulxU32(&x955, &x956, x7, (arg1[6]));
var x957: u32 = undefined;
var x958: u32 = undefined;
mulxU32(&x957, &x958, x7, (arg1[5]));
var x959: u32 = undefined;
var x960: u32 = undefined;
mulxU32(&x959, &x960, x7, (arg1[4]));
var x961: u32 = undefined;
var x962: u32 = undefined;
mulxU32(&x961, &x962, x7, (arg1[3]));
var x963: u32 = undefined;
var x964: u32 = undefined;
mulxU32(&x963, &x964, x7, (arg1[2]));
var x965: u32 = undefined;
var x966: u32 = undefined;
mulxU32(&x965, &x966, x7, (arg1[1]));
var x967: u32 = undefined;
var x968: u32 = undefined;
mulxU32(&x967, &x968, x7, (arg1[0]));
var x969: u32 = undefined;
var x970: u1 = undefined;
addcarryxU32(&x969, &x970, 0x0, x968, x965);
var x971: u32 = undefined;
var x972: u1 = undefined;
addcarryxU32(&x971, &x972, x970, x966, x963);
var x973: u32 = undefined;
var x974: u1 = undefined;
addcarryxU32(&x973, &x974, x972, x964, x961);
var x975: u32 = undefined;
var x976: u1 = undefined;
addcarryxU32(&x975, &x976, x974, x962, x959);
var x977: u32 = undefined;
var x978: u1 = undefined;
addcarryxU32(&x977, &x978, x976, x960, x957);
var x979: u32 = undefined;
var x980: u1 = undefined;
addcarryxU32(&x979, &x980, x978, x958, x955);
var x981: u32 = undefined;
var x982: u1 = undefined;
addcarryxU32(&x981, &x982, x980, x956, x953);
var x983: u32 = undefined;
var x984: u1 = undefined;
addcarryxU32(&x983, &x984, x982, x954, x951);
var x985: u32 = undefined;
var x986: u1 = undefined;
addcarryxU32(&x985, &x986, x984, x952, x949);
var x987: u32 = undefined;
var x988: u1 = undefined;
addcarryxU32(&x987, &x988, x986, x950, x947);
var x989: u32 = undefined;
var x990: u1 = undefined;
addcarryxU32(&x989, &x990, x988, x948, x945);
const x991 = (cast(u32, x990) + x946);
var x992: u32 = undefined;
var x993: u1 = undefined;
addcarryxU32(&x992, &x993, 0x0, x920, x967);
var x994: u32 = undefined;
var x995: u1 = undefined;
addcarryxU32(&x994, &x995, x993, x922, x969);
var x996: u32 = undefined;
var x997: u1 = undefined;
addcarryxU32(&x996, &x997, x995, x924, x971);
var x998: u32 = undefined;
var x999: u1 = undefined;
addcarryxU32(&x998, &x999, x997, x926, x973);
var x1000: u32 = undefined;
var x1001: u1 = undefined;
addcarryxU32(&x1000, &x1001, x999, x928, x975);
var x1002: u32 = undefined;
var x1003: u1 = undefined;
addcarryxU32(&x1002, &x1003, x1001, x930, x977);
var x1004: u32 = undefined;
var x1005: u1 = undefined;
addcarryxU32(&x1004, &x1005, x1003, x932, x979);
var x1006: u32 = undefined;
var x1007: u1 = undefined;
addcarryxU32(&x1006, &x1007, x1005, x934, x981);
var x1008: u32 = undefined;
var x1009: u1 = undefined;
addcarryxU32(&x1008, &x1009, x1007, x936, x983);
var x1010: u32 = undefined;
var x1011: u1 = undefined;
addcarryxU32(&x1010, &x1011, x1009, x938, x985);
var x1012: u32 = undefined;
var x1013: u1 = undefined;
addcarryxU32(&x1012, &x1013, x1011, x940, x987);
var x1014: u32 = undefined;
var x1015: u1 = undefined;
addcarryxU32(&x1014, &x1015, x1013, x942, x989);
var x1016: u32 = undefined;
var x1017: u1 = undefined;
addcarryxU32(&x1016, &x1017, x1015, x944, x991);
var x1018: u32 = undefined;
var x1019: u32 = undefined;
mulxU32(&x1018, &x1019, x992, 0xffffffff);
var x1020: u32 = undefined;
var x1021: u32 = undefined;
mulxU32(&x1020, &x1021, x992, 0xffffffff);
var x1022: u32 = undefined;
var x1023: u32 = undefined;
mulxU32(&x1022, &x1023, x992, 0xffffffff);
var x1024: u32 = undefined;
var x1025: u32 = undefined;
mulxU32(&x1024, &x1025, x992, 0xffffffff);
var x1026: u32 = undefined;
var x1027: u32 = undefined;
mulxU32(&x1026, &x1027, x992, 0xffffffff);
var x1028: u32 = undefined;
var x1029: u32 = undefined;
mulxU32(&x1028, &x1029, x992, 0xffffffff);
var x1030: u32 = undefined;
var x1031: u32 = undefined;
mulxU32(&x1030, &x1031, x992, 0xffffffff);
var x1032: u32 = undefined;
var x1033: u32 = undefined;
mulxU32(&x1032, &x1033, x992, 0xfffffffe);
var x1034: u32 = undefined;
var x1035: u32 = undefined;
mulxU32(&x1034, &x1035, x992, 0xffffffff);
var x1036: u32 = undefined;
var x1037: u32 = undefined;
mulxU32(&x1036, &x1037, x992, 0xffffffff);
var x1038: u32 = undefined;
var x1039: u1 = undefined;
addcarryxU32(&x1038, &x1039, 0x0, x1035, x1032);
var x1040: u32 = undefined;
var x1041: u1 = undefined;
addcarryxU32(&x1040, &x1041, x1039, x1033, x1030);
var x1042: u32 = undefined;
var x1043: u1 = undefined;
addcarryxU32(&x1042, &x1043, x1041, x1031, x1028);
var x1044: u32 = undefined;
var x1045: u1 = undefined;
addcarryxU32(&x1044, &x1045, x1043, x1029, x1026);
var x1046: u32 = undefined;
var x1047: u1 = undefined;
addcarryxU32(&x1046, &x1047, x1045, x1027, x1024);
var x1048: u32 = undefined;
var x1049: u1 = undefined;
addcarryxU32(&x1048, &x1049, x1047, x1025, x1022);
var x1050: u32 = undefined;
var x1051: u1 = undefined;
addcarryxU32(&x1050, &x1051, x1049, x1023, x1020);
var x1052: u32 = undefined;
var x1053: u1 = undefined;
addcarryxU32(&x1052, &x1053, x1051, x1021, x1018);
const x1054 = (cast(u32, x1053) + x1019);
var x1055: u32 = undefined;
var x1056: u1 = undefined;
addcarryxU32(&x1055, &x1056, 0x0, x992, x1036);
var x1057: u32 = undefined;
var x1058: u1 = undefined;
addcarryxU32(&x1057, &x1058, x1056, x994, x1037);
var x1059: u32 = undefined;
var x1060: u1 = undefined;
addcarryxU32(&x1059, &x1060, x1058, x996, cast(u32, 0x0));
var x1061: u32 = undefined;
var x1062: u1 = undefined;
addcarryxU32(&x1061, &x1062, x1060, x998, x1034);
var x1063: u32 = undefined;
var x1064: u1 = undefined;
addcarryxU32(&x1063, &x1064, x1062, x1000, x1038);
var x1065: u32 = undefined;
var x1066: u1 = undefined;
addcarryxU32(&x1065, &x1066, x1064, x1002, x1040);
var x1067: u32 = undefined;
var x1068: u1 = undefined;
addcarryxU32(&x1067, &x1068, x1066, x1004, x1042);
var x1069: u32 = undefined;
var x1070: u1 = undefined;
addcarryxU32(&x1069, &x1070, x1068, x1006, x1044);
var x1071: u32 = undefined;
var x1072: u1 = undefined;
addcarryxU32(&x1071, &x1072, x1070, x1008, x1046);
var x1073: u32 = undefined;
var x1074: u1 = undefined;
addcarryxU32(&x1073, &x1074, x1072, x1010, x1048);
var x1075: u32 = undefined;
var x1076: u1 = undefined;
addcarryxU32(&x1075, &x1076, x1074, x1012, x1050);
var x1077: u32 = undefined;
var x1078: u1 = undefined;
addcarryxU32(&x1077, &x1078, x1076, x1014, x1052);
var x1079: u32 = undefined;
var x1080: u1 = undefined;
addcarryxU32(&x1079, &x1080, x1078, x1016, x1054);
const x1081 = (cast(u32, x1080) + cast(u32, x1017));
var x1082: u32 = undefined;
var x1083: u32 = undefined;
mulxU32(&x1082, &x1083, x8, (arg1[11]));
var x1084: u32 = undefined;
var x1085: u32 = undefined;
mulxU32(&x1084, &x1085, x8, (arg1[10]));
var x1086: u32 = undefined;
var x1087: u32 = undefined;
mulxU32(&x1086, &x1087, x8, (arg1[9]));
var x1088: u32 = undefined;
var x1089: u32 = undefined;
mulxU32(&x1088, &x1089, x8, (arg1[8]));
var x1090: u32 = undefined;
var x1091: u32 = undefined;
mulxU32(&x1090, &x1091, x8, (arg1[7]));
var x1092: u32 = undefined;
var x1093: u32 = undefined;
mulxU32(&x1092, &x1093, x8, (arg1[6]));
var x1094: u32 = undefined;
var x1095: u32 = undefined;
mulxU32(&x1094, &x1095, x8, (arg1[5]));
var x1096: u32 = undefined;
var x1097: u32 = undefined;
mulxU32(&x1096, &x1097, x8, (arg1[4]));
var x1098: u32 = undefined;
var x1099: u32 = undefined;
mulxU32(&x1098, &x1099, x8, (arg1[3]));
var x1100: u32 = undefined;
var x1101: u32 = undefined;
mulxU32(&x1100, &x1101, x8, (arg1[2]));
var x1102: u32 = undefined;
var x1103: u32 = undefined;
mulxU32(&x1102, &x1103, x8, (arg1[1]));
var x1104: u32 = undefined;
var x1105: u32 = undefined;
mulxU32(&x1104, &x1105, x8, (arg1[0]));
var x1106: u32 = undefined;
var x1107: u1 = undefined;
addcarryxU32(&x1106, &x1107, 0x0, x1105, x1102);
var x1108: u32 = undefined;
var x1109: u1 = undefined;
addcarryxU32(&x1108, &x1109, x1107, x1103, x1100);
var x1110: u32 = undefined;
var x1111: u1 = undefined;
addcarryxU32(&x1110, &x1111, x1109, x1101, x1098);
var x1112: u32 = undefined;
var x1113: u1 = undefined;
addcarryxU32(&x1112, &x1113, x1111, x1099, x1096);
var x1114: u32 = undefined;
var x1115: u1 = undefined;
addcarryxU32(&x1114, &x1115, x1113, x1097, x1094);
var x1116: u32 = undefined;
var x1117: u1 = undefined;
addcarryxU32(&x1116, &x1117, x1115, x1095, x1092);
var x1118: u32 = undefined;
var x1119: u1 = undefined;
addcarryxU32(&x1118, &x1119, x1117, x1093, x1090);
var x1120: u32 = undefined;
var x1121: u1 = undefined;
addcarryxU32(&x1120, &x1121, x1119, x1091, x1088);
var x1122: u32 = undefined;
var x1123: u1 = undefined;
addcarryxU32(&x1122, &x1123, x1121, x1089, x1086);
var x1124: u32 = undefined;
var x1125: u1 = undefined;
addcarryxU32(&x1124, &x1125, x1123, x1087, x1084);
var x1126: u32 = undefined;
var x1127: u1 = undefined;
addcarryxU32(&x1126, &x1127, x1125, x1085, x1082);
const x1128 = (cast(u32, x1127) + x1083);
var x1129: u32 = undefined;
var x1130: u1 = undefined;
addcarryxU32(&x1129, &x1130, 0x0, x1057, x1104);
var x1131: u32 = undefined;
var x1132: u1 = undefined;
addcarryxU32(&x1131, &x1132, x1130, x1059, x1106);
var x1133: u32 = undefined;
var x1134: u1 = undefined;
addcarryxU32(&x1133, &x1134, x1132, x1061, x1108);
var x1135: u32 = undefined;
var x1136: u1 = undefined;
addcarryxU32(&x1135, &x1136, x1134, x1063, x1110);
var x1137: u32 = undefined;
var x1138: u1 = undefined;
addcarryxU32(&x1137, &x1138, x1136, x1065, x1112);
var x1139: u32 = undefined;
var x1140: u1 = undefined;
addcarryxU32(&x1139, &x1140, x1138, x1067, x1114);
var x1141: u32 = undefined;
var x1142: u1 = undefined;
addcarryxU32(&x1141, &x1142, x1140, x1069, x1116);
var x1143: u32 = undefined;
var x1144: u1 = undefined;
addcarryxU32(&x1143, &x1144, x1142, x1071, x1118);
var x1145: u32 = undefined;
var x1146: u1 = undefined;
addcarryxU32(&x1145, &x1146, x1144, x1073, x1120);
var x1147: u32 = undefined;
var x1148: u1 = undefined;
addcarryxU32(&x1147, &x1148, x1146, x1075, x1122);
var x1149: u32 = undefined;
var x1150: u1 = undefined;
addcarryxU32(&x1149, &x1150, x1148, x1077, x1124);
var x1151: u32 = undefined;
var x1152: u1 = undefined;
addcarryxU32(&x1151, &x1152, x1150, x1079, x1126);
var x1153: u32 = undefined;
var x1154: u1 = undefined;
addcarryxU32(&x1153, &x1154, x1152, x1081, x1128);
var x1155: u32 = undefined;
var x1156: u32 = undefined;
mulxU32(&x1155, &x1156, x1129, 0xffffffff);
var x1157: u32 = undefined;
var x1158: u32 = undefined;
mulxU32(&x1157, &x1158, x1129, 0xffffffff);
var x1159: u32 = undefined;
var x1160: u32 = undefined;
mulxU32(&x1159, &x1160, x1129, 0xffffffff);
var x1161: u32 = undefined;
var x1162: u32 = undefined;
mulxU32(&x1161, &x1162, x1129, 0xffffffff);
var x1163: u32 = undefined;
var x1164: u32 = undefined;
mulxU32(&x1163, &x1164, x1129, 0xffffffff);
var x1165: u32 = undefined;
var x1166: u32 = undefined;
mulxU32(&x1165, &x1166, x1129, 0xffffffff);
var x1167: u32 = undefined;
var x1168: u32 = undefined;
mulxU32(&x1167, &x1168, x1129, 0xffffffff);
var x1169: u32 = undefined;
var x1170: u32 = undefined;
mulxU32(&x1169, &x1170, x1129, 0xfffffffe);
var x1171: u32 = undefined;
var x1172: u32 = undefined;
mulxU32(&x1171, &x1172, x1129, 0xffffffff);
var x1173: u32 = undefined;
var x1174: u32 = undefined;
mulxU32(&x1173, &x1174, x1129, 0xffffffff);
var x1175: u32 = undefined;
var x1176: u1 = undefined;
addcarryxU32(&x1175, &x1176, 0x0, x1172, x1169);
var x1177: u32 = undefined;
var x1178: u1 = undefined;
addcarryxU32(&x1177, &x1178, x1176, x1170, x1167);
var x1179: u32 = undefined;
var x1180: u1 = undefined;
addcarryxU32(&x1179, &x1180, x1178, x1168, x1165);
var x1181: u32 = undefined;
var x1182: u1 = undefined;
addcarryxU32(&x1181, &x1182, x1180, x1166, x1163);
var x1183: u32 = undefined;
var x1184: u1 = undefined;
addcarryxU32(&x1183, &x1184, x1182, x1164, x1161);
var x1185: u32 = undefined;
var x1186: u1 = undefined;
addcarryxU32(&x1185, &x1186, x1184, x1162, x1159);
var x1187: u32 = undefined;
var x1188: u1 = undefined;
addcarryxU32(&x1187, &x1188, x1186, x1160, x1157);
var x1189: u32 = undefined;
var x1190: u1 = undefined;
addcarryxU32(&x1189, &x1190, x1188, x1158, x1155);
const x1191 = (cast(u32, x1190) + x1156);
var x1192: u32 = undefined;
var x1193: u1 = undefined;
addcarryxU32(&x1192, &x1193, 0x0, x1129, x1173);
var x1194: u32 = undefined;
var x1195: u1 = undefined;
addcarryxU32(&x1194, &x1195, x1193, x1131, x1174);
var x1196: u32 = undefined;
var x1197: u1 = undefined;
addcarryxU32(&x1196, &x1197, x1195, x1133, cast(u32, 0x0));
var x1198: u32 = undefined;
var x1199: u1 = undefined;
addcarryxU32(&x1198, &x1199, x1197, x1135, x1171);
var x1200: u32 = undefined;
var x1201: u1 = undefined;
addcarryxU32(&x1200, &x1201, x1199, x1137, x1175);
var x1202: u32 = undefined;
var x1203: u1 = undefined;
addcarryxU32(&x1202, &x1203, x1201, x1139, x1177);
var x1204: u32 = undefined;
var x1205: u1 = undefined;
addcarryxU32(&x1204, &x1205, x1203, x1141, x1179);
var x1206: u32 = undefined;
var x1207: u1 = undefined;
addcarryxU32(&x1206, &x1207, x1205, x1143, x1181);
var x1208: u32 = undefined;
var x1209: u1 = undefined;
addcarryxU32(&x1208, &x1209, x1207, x1145, x1183);
var x1210: u32 = undefined;
var x1211: u1 = undefined;
addcarryxU32(&x1210, &x1211, x1209, x1147, x1185);
var x1212: u32 = undefined;
var x1213: u1 = undefined;
addcarryxU32(&x1212, &x1213, x1211, x1149, x1187);
var x1214: u32 = undefined;
var x1215: u1 = undefined;
addcarryxU32(&x1214, &x1215, x1213, x1151, x1189);
var x1216: u32 = undefined;
var x1217: u1 = undefined;
addcarryxU32(&x1216, &x1217, x1215, x1153, x1191);
const x1218 = (cast(u32, x1217) + cast(u32, x1154));
var x1219: u32 = undefined;
var x1220: u32 = undefined;
mulxU32(&x1219, &x1220, x9, (arg1[11]));
var x1221: u32 = undefined;
var x1222: u32 = undefined;
mulxU32(&x1221, &x1222, x9, (arg1[10]));
var x1223: u32 = undefined;
var x1224: u32 = undefined;
mulxU32(&x1223, &x1224, x9, (arg1[9]));
var x1225: u32 = undefined;
var x1226: u32 = undefined;
mulxU32(&x1225, &x1226, x9, (arg1[8]));
var x1227: u32 = undefined;
var x1228: u32 = undefined;
mulxU32(&x1227, &x1228, x9, (arg1[7]));
var x1229: u32 = undefined;
var x1230: u32 = undefined;
mulxU32(&x1229, &x1230, x9, (arg1[6]));
var x1231: u32 = undefined;
var x1232: u32 = undefined;
mulxU32(&x1231, &x1232, x9, (arg1[5]));
var x1233: u32 = undefined;
var x1234: u32 = undefined;
mulxU32(&x1233, &x1234, x9, (arg1[4]));
var x1235: u32 = undefined;
var x1236: u32 = undefined;
mulxU32(&x1235, &x1236, x9, (arg1[3]));
var x1237: u32 = undefined;
var x1238: u32 = undefined;
mulxU32(&x1237, &x1238, x9, (arg1[2]));
var x1239: u32 = undefined;
var x1240: u32 = undefined;
mulxU32(&x1239, &x1240, x9, (arg1[1]));
var x1241: u32 = undefined;
var x1242: u32 = undefined;
mulxU32(&x1241, &x1242, x9, (arg1[0]));
var x1243: u32 = undefined;
var x1244: u1 = undefined;
addcarryxU32(&x1243, &x1244, 0x0, x1242, x1239);
var x1245: u32 = undefined;
var x1246: u1 = undefined;
addcarryxU32(&x1245, &x1246, x1244, x1240, x1237);
var x1247: u32 = undefined;
var x1248: u1 = undefined;
addcarryxU32(&x1247, &x1248, x1246, x1238, x1235);
var x1249: u32 = undefined;
var x1250: u1 = undefined;
addcarryxU32(&x1249, &x1250, x1248, x1236, x1233);
var x1251: u32 = undefined;
var x1252: u1 = undefined;
addcarryxU32(&x1251, &x1252, x1250, x1234, x1231);
var x1253: u32 = undefined;
var x1254: u1 = undefined;
addcarryxU32(&x1253, &x1254, x1252, x1232, x1229);
var x1255: u32 = undefined;
var x1256: u1 = undefined;
addcarryxU32(&x1255, &x1256, x1254, x1230, x1227);
var x1257: u32 = undefined;
var x1258: u1 = undefined;
addcarryxU32(&x1257, &x1258, x1256, x1228, x1225);
var x1259: u32 = undefined;
var x1260: u1 = undefined;
addcarryxU32(&x1259, &x1260, x1258, x1226, x1223);
var x1261: u32 = undefined;
var x1262: u1 = undefined;
addcarryxU32(&x1261, &x1262, x1260, x1224, x1221);
var x1263: u32 = undefined;
var x1264: u1 = undefined;
addcarryxU32(&x1263, &x1264, x1262, x1222, x1219);
const x1265 = (cast(u32, x1264) + x1220);
var x1266: u32 = undefined;
var x1267: u1 = undefined;
addcarryxU32(&x1266, &x1267, 0x0, x1194, x1241);
var x1268: u32 = undefined;
var x1269: u1 = undefined;
addcarryxU32(&x1268, &x1269, x1267, x1196, x1243);
var x1270: u32 = undefined;
var x1271: u1 = undefined;
addcarryxU32(&x1270, &x1271, x1269, x1198, x1245);
var x1272: u32 = undefined;
var x1273: u1 = undefined;
addcarryxU32(&x1272, &x1273, x1271, x1200, x1247);
var x1274: u32 = undefined;
var x1275: u1 = undefined;
addcarryxU32(&x1274, &x1275, x1273, x1202, x1249);
var x1276: u32 = undefined;
var x1277: u1 = undefined;
addcarryxU32(&x1276, &x1277, x1275, x1204, x1251);
var x1278: u32 = undefined;
var x1279: u1 = undefined;
addcarryxU32(&x1278, &x1279, x1277, x1206, x1253);
var x1280: u32 = undefined;
var x1281: u1 = undefined;
addcarryxU32(&x1280, &x1281, x1279, x1208, x1255);
var x1282: u32 = undefined;
var x1283: u1 = undefined;
addcarryxU32(&x1282, &x1283, x1281, x1210, x1257);
var x1284: u32 = undefined;
var x1285: u1 = undefined;
addcarryxU32(&x1284, &x1285, x1283, x1212, x1259);
var x1286: u32 = undefined;
var x1287: u1 = undefined;
addcarryxU32(&x1286, &x1287, x1285, x1214, x1261);
var x1288: u32 = undefined;
var x1289: u1 = undefined;
addcarryxU32(&x1288, &x1289, x1287, x1216, x1263);
var x1290: u32 = undefined;
var x1291: u1 = undefined;
addcarryxU32(&x1290, &x1291, x1289, x1218, x1265);
var x1292: u32 = undefined;
var x1293: u32 = undefined;
mulxU32(&x1292, &x1293, x1266, 0xffffffff);
var x1294: u32 = undefined;
var x1295: u32 = undefined;
mulxU32(&x1294, &x1295, x1266, 0xffffffff);
var x1296: u32 = undefined;
var x1297: u32 = undefined;
mulxU32(&x1296, &x1297, x1266, 0xffffffff);
var x1298: u32 = undefined;
var x1299: u32 = undefined;
mulxU32(&x1298, &x1299, x1266, 0xffffffff);
var x1300: u32 = undefined;
var x1301: u32 = undefined;
mulxU32(&x1300, &x1301, x1266, 0xffffffff);
var x1302: u32 = undefined;
var x1303: u32 = undefined;
mulxU32(&x1302, &x1303, x1266, 0xffffffff);
var x1304: u32 = undefined;
var x1305: u32 = undefined;
mulxU32(&x1304, &x1305, x1266, 0xffffffff);
var x1306: u32 = undefined;
var x1307: u32 = undefined;
mulxU32(&x1306, &x1307, x1266, 0xfffffffe);
var x1308: u32 = undefined;
var x1309: u32 = undefined;
mulxU32(&x1308, &x1309, x1266, 0xffffffff);
var x1310: u32 = undefined;
var x1311: u32 = undefined;
mulxU32(&x1310, &x1311, x1266, 0xffffffff);
var x1312: u32 = undefined;
var x1313: u1 = undefined;
addcarryxU32(&x1312, &x1313, 0x0, x1309, x1306);
var x1314: u32 = undefined;
var x1315: u1 = undefined;
addcarryxU32(&x1314, &x1315, x1313, x1307, x1304);
var x1316: u32 = undefined;
var x1317: u1 = undefined;
addcarryxU32(&x1316, &x1317, x1315, x1305, x1302);
var x1318: u32 = undefined;
var x1319: u1 = undefined;
addcarryxU32(&x1318, &x1319, x1317, x1303, x1300);
var x1320: u32 = undefined;
var x1321: u1 = undefined;
addcarryxU32(&x1320, &x1321, x1319, x1301, x1298);
var x1322: u32 = undefined;
var x1323: u1 = undefined;
addcarryxU32(&x1322, &x1323, x1321, x1299, x1296);
var x1324: u32 = undefined;
var x1325: u1 = undefined;
addcarryxU32(&x1324, &x1325, x1323, x1297, x1294);
var x1326: u32 = undefined;
var x1327: u1 = undefined;
addcarryxU32(&x1326, &x1327, x1325, x1295, x1292);
const x1328 = (cast(u32, x1327) + x1293);
var x1329: u32 = undefined;
var x1330: u1 = undefined;
addcarryxU32(&x1329, &x1330, 0x0, x1266, x1310);
var x1331: u32 = undefined;
var x1332: u1 = undefined;
addcarryxU32(&x1331, &x1332, x1330, x1268, x1311);
var x1333: u32 = undefined;
var x1334: u1 = undefined;
addcarryxU32(&x1333, &x1334, x1332, x1270, cast(u32, 0x0));
var x1335: u32 = undefined;
var x1336: u1 = undefined;
addcarryxU32(&x1335, &x1336, x1334, x1272, x1308);
var x1337: u32 = undefined;
var x1338: u1 = undefined;
addcarryxU32(&x1337, &x1338, x1336, x1274, x1312);
var x1339: u32 = undefined;
var x1340: u1 = undefined;
addcarryxU32(&x1339, &x1340, x1338, x1276, x1314);
var x1341: u32 = undefined;
var x1342: u1 = undefined;
addcarryxU32(&x1341, &x1342, x1340, x1278, x1316);
var x1343: u32 = undefined;
var x1344: u1 = undefined;
addcarryxU32(&x1343, &x1344, x1342, x1280, x1318);
var x1345: u32 = undefined;
var x1346: u1 = undefined;
addcarryxU32(&x1345, &x1346, x1344, x1282, x1320);
var x1347: u32 = undefined;
var x1348: u1 = undefined;
addcarryxU32(&x1347, &x1348, x1346, x1284, x1322);
var x1349: u32 = undefined;
var x1350: u1 = undefined;
addcarryxU32(&x1349, &x1350, x1348, x1286, x1324);
var x1351: u32 = undefined;
var x1352: u1 = undefined;
addcarryxU32(&x1351, &x1352, x1350, x1288, x1326);
var x1353: u32 = undefined;
var x1354: u1 = undefined;
addcarryxU32(&x1353, &x1354, x1352, x1290, x1328);
const x1355 = (cast(u32, x1354) + cast(u32, x1291));
var x1356: u32 = undefined;
var x1357: u32 = undefined;
mulxU32(&x1356, &x1357, x10, (arg1[11]));
var x1358: u32 = undefined;
var x1359: u32 = undefined;
mulxU32(&x1358, &x1359, x10, (arg1[10]));
var x1360: u32 = undefined;
var x1361: u32 = undefined;
mulxU32(&x1360, &x1361, x10, (arg1[9]));
var x1362: u32 = undefined;
var x1363: u32 = undefined;
mulxU32(&x1362, &x1363, x10, (arg1[8]));
var x1364: u32 = undefined;
var x1365: u32 = undefined;
mulxU32(&x1364, &x1365, x10, (arg1[7]));
var x1366: u32 = undefined;
var x1367: u32 = undefined;
mulxU32(&x1366, &x1367, x10, (arg1[6]));
var x1368: u32 = undefined;
var x1369: u32 = undefined;
mulxU32(&x1368, &x1369, x10, (arg1[5]));
var x1370: u32 = undefined;
var x1371: u32 = undefined;
mulxU32(&x1370, &x1371, x10, (arg1[4]));
var x1372: u32 = undefined;
var x1373: u32 = undefined;
mulxU32(&x1372, &x1373, x10, (arg1[3]));
var x1374: u32 = undefined;
var x1375: u32 = undefined;
mulxU32(&x1374, &x1375, x10, (arg1[2]));
var x1376: u32 = undefined;
var x1377: u32 = undefined;
mulxU32(&x1376, &x1377, x10, (arg1[1]));
var x1378: u32 = undefined;
var x1379: u32 = undefined;
mulxU32(&x1378, &x1379, x10, (arg1[0]));
var x1380: u32 = undefined;
var x1381: u1 = undefined;
addcarryxU32(&x1380, &x1381, 0x0, x1379, x1376);
var x1382: u32 = undefined;
var x1383: u1 = undefined;
addcarryxU32(&x1382, &x1383, x1381, x1377, x1374);
var x1384: u32 = undefined;
var x1385: u1 = undefined;
addcarryxU32(&x1384, &x1385, x1383, x1375, x1372);
var x1386: u32 = undefined;
var x1387: u1 = undefined;
addcarryxU32(&x1386, &x1387, x1385, x1373, x1370);
var x1388: u32 = undefined;
var x1389: u1 = undefined;
addcarryxU32(&x1388, &x1389, x1387, x1371, x1368);
var x1390: u32 = undefined;
var x1391: u1 = undefined;
addcarryxU32(&x1390, &x1391, x1389, x1369, x1366);
var x1392: u32 = undefined;
var x1393: u1 = undefined;
addcarryxU32(&x1392, &x1393, x1391, x1367, x1364);
var x1394: u32 = undefined;
var x1395: u1 = undefined;
addcarryxU32(&x1394, &x1395, x1393, x1365, x1362);
var x1396: u32 = undefined;
var x1397: u1 = undefined;
addcarryxU32(&x1396, &x1397, x1395, x1363, x1360);
var x1398: u32 = undefined;
var x1399: u1 = undefined;
addcarryxU32(&x1398, &x1399, x1397, x1361, x1358);
var x1400: u32 = undefined;
var x1401: u1 = undefined;
addcarryxU32(&x1400, &x1401, x1399, x1359, x1356);
const x1402 = (cast(u32, x1401) + x1357);
var x1403: u32 = undefined;
var x1404: u1 = undefined;
addcarryxU32(&x1403, &x1404, 0x0, x1331, x1378);
var x1405: u32 = undefined;
var x1406: u1 = undefined;
addcarryxU32(&x1405, &x1406, x1404, x1333, x1380);
var x1407: u32 = undefined;
var x1408: u1 = undefined;
addcarryxU32(&x1407, &x1408, x1406, x1335, x1382);
var x1409: u32 = undefined;
var x1410: u1 = undefined;
addcarryxU32(&x1409, &x1410, x1408, x1337, x1384);
var x1411: u32 = undefined;
var x1412: u1 = undefined;
addcarryxU32(&x1411, &x1412, x1410, x1339, x1386);
var x1413: u32 = undefined;
var x1414: u1 = undefined;
addcarryxU32(&x1413, &x1414, x1412, x1341, x1388);
var x1415: u32 = undefined;
var x1416: u1 = undefined;
addcarryxU32(&x1415, &x1416, x1414, x1343, x1390);
var x1417: u32 = undefined;
var x1418: u1 = undefined;
addcarryxU32(&x1417, &x1418, x1416, x1345, x1392);
var x1419: u32 = undefined;
var x1420: u1 = undefined;
addcarryxU32(&x1419, &x1420, x1418, x1347, x1394);
var x1421: u32 = undefined;
var x1422: u1 = undefined;
addcarryxU32(&x1421, &x1422, x1420, x1349, x1396);
var x1423: u32 = undefined;
var x1424: u1 = undefined;
addcarryxU32(&x1423, &x1424, x1422, x1351, x1398);
var x1425: u32 = undefined;
var x1426: u1 = undefined;
addcarryxU32(&x1425, &x1426, x1424, x1353, x1400);
var x1427: u32 = undefined;
var x1428: u1 = undefined;
addcarryxU32(&x1427, &x1428, x1426, x1355, x1402);
var x1429: u32 = undefined;
var x1430: u32 = undefined;
mulxU32(&x1429, &x1430, x1403, 0xffffffff);
var x1431: u32 = undefined;
var x1432: u32 = undefined;
mulxU32(&x1431, &x1432, x1403, 0xffffffff);
var x1433: u32 = undefined;
var x1434: u32 = undefined;
mulxU32(&x1433, &x1434, x1403, 0xffffffff);
var x1435: u32 = undefined;
var x1436: u32 = undefined;
mulxU32(&x1435, &x1436, x1403, 0xffffffff);
var x1437: u32 = undefined;
var x1438: u32 = undefined;
mulxU32(&x1437, &x1438, x1403, 0xffffffff);
var x1439: u32 = undefined;
var x1440: u32 = undefined;
mulxU32(&x1439, &x1440, x1403, 0xffffffff);
var x1441: u32 = undefined;
var x1442: u32 = undefined;
mulxU32(&x1441, &x1442, x1403, 0xffffffff);
var x1443: u32 = undefined;
var x1444: u32 = undefined;
mulxU32(&x1443, &x1444, x1403, 0xfffffffe);
var x1445: u32 = undefined;
var x1446: u32 = undefined;
mulxU32(&x1445, &x1446, x1403, 0xffffffff);
var x1447: u32 = undefined;
var x1448: u32 = undefined;
mulxU32(&x1447, &x1448, x1403, 0xffffffff);
var x1449: u32 = undefined;
var x1450: u1 = undefined;
addcarryxU32(&x1449, &x1450, 0x0, x1446, x1443);
var x1451: u32 = undefined;
var x1452: u1 = undefined;
addcarryxU32(&x1451, &x1452, x1450, x1444, x1441);
var x1453: u32 = undefined;
var x1454: u1 = undefined;
addcarryxU32(&x1453, &x1454, x1452, x1442, x1439);
var x1455: u32 = undefined;
var x1456: u1 = undefined;
addcarryxU32(&x1455, &x1456, x1454, x1440, x1437);
var x1457: u32 = undefined;
var x1458: u1 = undefined;
addcarryxU32(&x1457, &x1458, x1456, x1438, x1435);
var x1459: u32 = undefined;
var x1460: u1 = undefined;
addcarryxU32(&x1459, &x1460, x1458, x1436, x1433);
var x1461: u32 = undefined;
var x1462: u1 = undefined;
addcarryxU32(&x1461, &x1462, x1460, x1434, x1431);
var x1463: u32 = undefined;
var x1464: u1 = undefined;
addcarryxU32(&x1463, &x1464, x1462, x1432, x1429);
const x1465 = (cast(u32, x1464) + x1430);
var x1466: u32 = undefined;
var x1467: u1 = undefined;
addcarryxU32(&x1466, &x1467, 0x0, x1403, x1447);
var x1468: u32 = undefined;
var x1469: u1 = undefined;
addcarryxU32(&x1468, &x1469, x1467, x1405, x1448);
var x1470: u32 = undefined;
var x1471: u1 = undefined;
addcarryxU32(&x1470, &x1471, x1469, x1407, cast(u32, 0x0));
var x1472: u32 = undefined;
var x1473: u1 = undefined;
addcarryxU32(&x1472, &x1473, x1471, x1409, x1445);
var x1474: u32 = undefined;
var x1475: u1 = undefined;
addcarryxU32(&x1474, &x1475, x1473, x1411, x1449);
var x1476: u32 = undefined;
var x1477: u1 = undefined;
addcarryxU32(&x1476, &x1477, x1475, x1413, x1451);
var x1478: u32 = undefined;
var x1479: u1 = undefined;
addcarryxU32(&x1478, &x1479, x1477, x1415, x1453);
var x1480: u32 = undefined;
var x1481: u1 = undefined;
addcarryxU32(&x1480, &x1481, x1479, x1417, x1455);
var x1482: u32 = undefined;
var x1483: u1 = undefined;
addcarryxU32(&x1482, &x1483, x1481, x1419, x1457);
var x1484: u32 = undefined;
var x1485: u1 = undefined;
addcarryxU32(&x1484, &x1485, x1483, x1421, x1459);
var x1486: u32 = undefined;
var x1487: u1 = undefined;
addcarryxU32(&x1486, &x1487, x1485, x1423, x1461);
var x1488: u32 = undefined;
var x1489: u1 = undefined;
addcarryxU32(&x1488, &x1489, x1487, x1425, x1463);
var x1490: u32 = undefined;
var x1491: u1 = undefined;
addcarryxU32(&x1490, &x1491, x1489, x1427, x1465);
const x1492 = (cast(u32, x1491) + cast(u32, x1428));
var x1493: u32 = undefined;
var x1494: u32 = undefined;
mulxU32(&x1493, &x1494, x11, (arg1[11]));
var x1495: u32 = undefined;
var x1496: u32 = undefined;
mulxU32(&x1495, &x1496, x11, (arg1[10]));
var x1497: u32 = undefined;
var x1498: u32 = undefined;
mulxU32(&x1497, &x1498, x11, (arg1[9]));
var x1499: u32 = undefined;
var x1500: u32 = undefined;
mulxU32(&x1499, &x1500, x11, (arg1[8]));
var x1501: u32 = undefined;
var x1502: u32 = undefined;
mulxU32(&x1501, &x1502, x11, (arg1[7]));
var x1503: u32 = undefined;
var x1504: u32 = undefined;
mulxU32(&x1503, &x1504, x11, (arg1[6]));
var x1505: u32 = undefined;
var x1506: u32 = undefined;
mulxU32(&x1505, &x1506, x11, (arg1[5]));
var x1507: u32 = undefined;
var x1508: u32 = undefined;
mulxU32(&x1507, &x1508, x11, (arg1[4]));
var x1509: u32 = undefined;
var x1510: u32 = undefined;
mulxU32(&x1509, &x1510, x11, (arg1[3]));
var x1511: u32 = undefined;
var x1512: u32 = undefined;
mulxU32(&x1511, &x1512, x11, (arg1[2]));
var x1513: u32 = undefined;
var x1514: u32 = undefined;
mulxU32(&x1513, &x1514, x11, (arg1[1]));
var x1515: u32 = undefined;
var x1516: u32 = undefined;
mulxU32(&x1515, &x1516, x11, (arg1[0]));
var x1517: u32 = undefined;
var x1518: u1 = undefined;
addcarryxU32(&x1517, &x1518, 0x0, x1516, x1513);
var x1519: u32 = undefined;
var x1520: u1 = undefined;
addcarryxU32(&x1519, &x1520, x1518, x1514, x1511);
var x1521: u32 = undefined;
var x1522: u1 = undefined;
addcarryxU32(&x1521, &x1522, x1520, x1512, x1509);
var x1523: u32 = undefined;
var x1524: u1 = undefined;
addcarryxU32(&x1523, &x1524, x1522, x1510, x1507);
var x1525: u32 = undefined;
var x1526: u1 = undefined;
addcarryxU32(&x1525, &x1526, x1524, x1508, x1505);
var x1527: u32 = undefined;
var x1528: u1 = undefined;
addcarryxU32(&x1527, &x1528, x1526, x1506, x1503);
var x1529: u32 = undefined;
var x1530: u1 = undefined;
addcarryxU32(&x1529, &x1530, x1528, x1504, x1501);
var x1531: u32 = undefined;
var x1532: u1 = undefined;
addcarryxU32(&x1531, &x1532, x1530, x1502, x1499);
var x1533: u32 = undefined;
var x1534: u1 = undefined;
addcarryxU32(&x1533, &x1534, x1532, x1500, x1497);
var x1535: u32 = undefined;
var x1536: u1 = undefined;
addcarryxU32(&x1535, &x1536, x1534, x1498, x1495);
var x1537: u32 = undefined;
var x1538: u1 = undefined;
addcarryxU32(&x1537, &x1538, x1536, x1496, x1493);
const x1539 = (cast(u32, x1538) + x1494);
var x1540: u32 = undefined;
var x1541: u1 = undefined;
addcarryxU32(&x1540, &x1541, 0x0, x1468, x1515);
var x1542: u32 = undefined;
var x1543: u1 = undefined;
addcarryxU32(&x1542, &x1543, x1541, x1470, x1517);
var x1544: u32 = undefined;
var x1545: u1 = undefined;
addcarryxU32(&x1544, &x1545, x1543, x1472, x1519);
var x1546: u32 = undefined;
var x1547: u1 = undefined;
addcarryxU32(&x1546, &x1547, x1545, x1474, x1521);
var x1548: u32 = undefined;
var x1549: u1 = undefined;
addcarryxU32(&x1548, &x1549, x1547, x1476, x1523);
var x1550: u32 = undefined;
var x1551: u1 = undefined;
addcarryxU32(&x1550, &x1551, x1549, x1478, x1525);
var x1552: u32 = undefined;
var x1553: u1 = undefined;
addcarryxU32(&x1552, &x1553, x1551, x1480, x1527);
var x1554: u32 = undefined;
var x1555: u1 = undefined;
addcarryxU32(&x1554, &x1555, x1553, x1482, x1529);
var x1556: u32 = undefined;
var x1557: u1 = undefined;
addcarryxU32(&x1556, &x1557, x1555, x1484, x1531);
var x1558: u32 = undefined;
var x1559: u1 = undefined;
addcarryxU32(&x1558, &x1559, x1557, x1486, x1533);
var x1560: u32 = undefined;
var x1561: u1 = undefined;
addcarryxU32(&x1560, &x1561, x1559, x1488, x1535);
var x1562: u32 = undefined;
var x1563: u1 = undefined;
addcarryxU32(&x1562, &x1563, x1561, x1490, x1537);
var x1564: u32 = undefined;
var x1565: u1 = undefined;
addcarryxU32(&x1564, &x1565, x1563, x1492, x1539);
var x1566: u32 = undefined;
var x1567: u32 = undefined;
mulxU32(&x1566, &x1567, x1540, 0xffffffff);
var x1568: u32 = undefined;
var x1569: u32 = undefined;
mulxU32(&x1568, &x1569, x1540, 0xffffffff);
var x1570: u32 = undefined;
var x1571: u32 = undefined;
mulxU32(&x1570, &x1571, x1540, 0xffffffff);
var x1572: u32 = undefined;
var x1573: u32 = undefined;
mulxU32(&x1572, &x1573, x1540, 0xffffffff);
var x1574: u32 = undefined;
var x1575: u32 = undefined;
mulxU32(&x1574, &x1575, x1540, 0xffffffff);
var x1576: u32 = undefined;
var x1577: u32 = undefined;
mulxU32(&x1576, &x1577, x1540, 0xffffffff);
var x1578: u32 = undefined;
var x1579: u32 = undefined;
mulxU32(&x1578, &x1579, x1540, 0xffffffff);
var x1580: u32 = undefined;
var x1581: u32 = undefined;
mulxU32(&x1580, &x1581, x1540, 0xfffffffe);
var x1582: u32 = undefined;
var x1583: u32 = undefined;
mulxU32(&x1582, &x1583, x1540, 0xffffffff);
var x1584: u32 = undefined;
var x1585: u32 = undefined;
mulxU32(&x1584, &x1585, x1540, 0xffffffff);
var x1586: u32 = undefined;
var x1587: u1 = undefined;
addcarryxU32(&x1586, &x1587, 0x0, x1583, x1580);
var x1588: u32 = undefined;
var x1589: u1 = undefined;
addcarryxU32(&x1588, &x1589, x1587, x1581, x1578);
var x1590: u32 = undefined;
var x1591: u1 = undefined;
addcarryxU32(&x1590, &x1591, x1589, x1579, x1576);
var x1592: u32 = undefined;
var x1593: u1 = undefined;
addcarryxU32(&x1592, &x1593, x1591, x1577, x1574);
var x1594: u32 = undefined;
var x1595: u1 = undefined;
addcarryxU32(&x1594, &x1595, x1593, x1575, x1572);
var x1596: u32 = undefined;
var x1597: u1 = undefined;
addcarryxU32(&x1596, &x1597, x1595, x1573, x1570);
var x1598: u32 = undefined;
var x1599: u1 = undefined;
addcarryxU32(&x1598, &x1599, x1597, x1571, x1568);
var x1600: u32 = undefined;
var x1601: u1 = undefined;
addcarryxU32(&x1600, &x1601, x1599, x1569, x1566);
const x1602 = (cast(u32, x1601) + x1567);
var x1603: u32 = undefined;
var x1604: u1 = undefined;
addcarryxU32(&x1603, &x1604, 0x0, x1540, x1584);
var x1605: u32 = undefined;
var x1606: u1 = undefined;
addcarryxU32(&x1605, &x1606, x1604, x1542, x1585);
var x1607: u32 = undefined;
var x1608: u1 = undefined;
addcarryxU32(&x1607, &x1608, x1606, x1544, cast(u32, 0x0));
var x1609: u32 = undefined;
var x1610: u1 = undefined;
addcarryxU32(&x1609, &x1610, x1608, x1546, x1582);
var x1611: u32 = undefined;
var x1612: u1 = undefined;
addcarryxU32(&x1611, &x1612, x1610, x1548, x1586);
var x1613: u32 = undefined;
var x1614: u1 = undefined;
addcarryxU32(&x1613, &x1614, x1612, x1550, x1588);
var x1615: u32 = undefined;
var x1616: u1 = undefined;
addcarryxU32(&x1615, &x1616, x1614, x1552, x1590);
var x1617: u32 = undefined;
var x1618: u1 = undefined;
addcarryxU32(&x1617, &x1618, x1616, x1554, x1592);
var x1619: u32 = undefined;
var x1620: u1 = undefined;
addcarryxU32(&x1619, &x1620, x1618, x1556, x1594);
var x1621: u32 = undefined;
var x1622: u1 = undefined;
addcarryxU32(&x1621, &x1622, x1620, x1558, x1596);
var x1623: u32 = undefined;
var x1624: u1 = undefined;
addcarryxU32(&x1623, &x1624, x1622, x1560, x1598);
var x1625: u32 = undefined;
var x1626: u1 = undefined;
addcarryxU32(&x1625, &x1626, x1624, x1562, x1600);
var x1627: u32 = undefined;
var x1628: u1 = undefined;
addcarryxU32(&x1627, &x1628, x1626, x1564, x1602);
const x1629 = (cast(u32, x1628) + cast(u32, x1565));
var x1630: u32 = undefined;
var x1631: u1 = undefined;
subborrowxU32(&x1630, &x1631, 0x0, x1605, 0xffffffff);
var x1632: u32 = undefined;
var x1633: u1 = undefined;
subborrowxU32(&x1632, &x1633, x1631, x1607, cast(u32, 0x0));
var x1634: u32 = undefined;
var x1635: u1 = undefined;
subborrowxU32(&x1634, &x1635, x1633, x1609, cast(u32, 0x0));
var x1636: u32 = undefined;
var x1637: u1 = undefined;
subborrowxU32(&x1636, &x1637, x1635, x1611, 0xffffffff);
var x1638: u32 = undefined;
var x1639: u1 = undefined;
subborrowxU32(&x1638, &x1639, x1637, x1613, 0xfffffffe);
var x1640: u32 = undefined;
var x1641: u1 = undefined;
subborrowxU32(&x1640, &x1641, x1639, x1615, 0xffffffff);
var x1642: u32 = undefined;
var x1643: u1 = undefined;
subborrowxU32(&x1642, &x1643, x1641, x1617, 0xffffffff);
var x1644: u32 = undefined;
var x1645: u1 = undefined;
subborrowxU32(&x1644, &x1645, x1643, x1619, 0xffffffff);
var x1646: u32 = undefined;
var x1647: u1 = undefined;
subborrowxU32(&x1646, &x1647, x1645, x1621, 0xffffffff);
var x1648: u32 = undefined;
var x1649: u1 = undefined;
subborrowxU32(&x1648, &x1649, x1647, x1623, 0xffffffff);
var x1650: u32 = undefined;
var x1651: u1 = undefined;
subborrowxU32(&x1650, &x1651, x1649, x1625, 0xffffffff);
var x1652: u32 = undefined;
var x1653: u1 = undefined;
subborrowxU32(&x1652, &x1653, x1651, x1627, 0xffffffff);
var x1654: u32 = undefined;
var x1655: u1 = undefined;
subborrowxU32(&x1654, &x1655, x1653, x1629, cast(u32, 0x0));
var x1656: u32 = undefined;
cmovznzU32(&x1656, x1655, x1630, x1605);
var x1657: u32 = undefined;
cmovznzU32(&x1657, x1655, x1632, x1607);
var x1658: u32 = undefined;
cmovznzU32(&x1658, x1655, x1634, x1609);
var x1659: u32 = undefined;
cmovznzU32(&x1659, x1655, x1636, x1611);
var x1660: u32 = undefined;
cmovznzU32(&x1660, x1655, x1638, x1613);
var x1661: u32 = undefined;
cmovznzU32(&x1661, x1655, x1640, x1615);
var x1662: u32 = undefined;
cmovznzU32(&x1662, x1655, x1642, x1617);
var x1663: u32 = undefined;
cmovznzU32(&x1663, x1655, x1644, x1619);
var x1664: u32 = undefined;
cmovznzU32(&x1664, x1655, x1646, x1621);
var x1665: u32 = undefined;
cmovznzU32(&x1665, x1655, x1648, x1623);
var x1666: u32 = undefined;
cmovznzU32(&x1666, x1655, x1650, x1625);
var x1667: u32 = undefined;
cmovznzU32(&x1667, x1655, x1652, x1627);
out1[0] = x1656;
out1[1] = x1657;
out1[2] = x1658;
out1[3] = x1659;
out1[4] = x1660;
out1[5] = x1661;
out1[6] = x1662;
out1[7] = x1663;
out1[8] = x1664;
out1[9] = x1665;
out1[10] = x1666;
out1[11] = x1667;
}
/// The function add adds two field elements in the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
pub fn add(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
var x1: u32 = undefined;
var x2: u1 = undefined;
addcarryxU32(&x1, &x2, 0x0, (arg1[0]), (arg2[0]));
var x3: u32 = undefined;
var x4: u1 = undefined;
addcarryxU32(&x3, &x4, x2, (arg1[1]), (arg2[1]));
var x5: u32 = undefined;
var x6: u1 = undefined;
addcarryxU32(&x5, &x6, x4, (arg1[2]), (arg2[2]));
var x7: u32 = undefined;
var x8: u1 = undefined;
addcarryxU32(&x7, &x8, x6, (arg1[3]), (arg2[3]));
var x9: u32 = undefined;
var x10: u1 = undefined;
addcarryxU32(&x9, &x10, x8, (arg1[4]), (arg2[4]));
var x11: u32 = undefined;
var x12: u1 = undefined;
addcarryxU32(&x11, &x12, x10, (arg1[5]), (arg2[5]));
var x13: u32 = undefined;
var x14: u1 = undefined;
addcarryxU32(&x13, &x14, x12, (arg1[6]), (arg2[6]));
var x15: u32 = undefined;
var x16: u1 = undefined;
addcarryxU32(&x15, &x16, x14, (arg1[7]), (arg2[7]));
var x17: u32 = undefined;
var x18: u1 = undefined;
addcarryxU32(&x17, &x18, x16, (arg1[8]), (arg2[8]));
var x19: u32 = undefined;
var x20: u1 = undefined;
addcarryxU32(&x19, &x20, x18, (arg1[9]), (arg2[9]));
var x21: u32 = undefined;
var x22: u1 = undefined;
addcarryxU32(&x21, &x22, x20, (arg1[10]), (arg2[10]));
var x23: u32 = undefined;
var x24: u1 = undefined;
addcarryxU32(&x23, &x24, x22, (arg1[11]), (arg2[11]));
var x25: u32 = undefined;
var x26: u1 = undefined;
subborrowxU32(&x25, &x26, 0x0, x1, 0xffffffff);
var x27: u32 = undefined;
var x28: u1 = undefined;
subborrowxU32(&x27, &x28, x26, x3, cast(u32, 0x0));
var x29: u32 = undefined;
var x30: u1 = undefined;
subborrowxU32(&x29, &x30, x28, x5, cast(u32, 0x0));
var x31: u32 = undefined;
var x32: u1 = undefined;
subborrowxU32(&x31, &x32, x30, x7, 0xffffffff);
var x33: u32 = undefined;
var x34: u1 = undefined;
subborrowxU32(&x33, &x34, x32, x9, 0xfffffffe);
var x35: u32 = undefined;
var x36: u1 = undefined;
subborrowxU32(&x35, &x36, x34, x11, 0xffffffff);
var x37: u32 = undefined;
var x38: u1 = undefined;
subborrowxU32(&x37, &x38, x36, x13, 0xffffffff);
var x39: u32 = undefined;
var x40: u1 = undefined;
subborrowxU32(&x39, &x40, x38, x15, 0xffffffff);
var x41: u32 = undefined;
var x42: u1 = undefined;
subborrowxU32(&x41, &x42, x40, x17, 0xffffffff);
var x43: u32 = undefined;
var x44: u1 = undefined;
subborrowxU32(&x43, &x44, x42, x19, 0xffffffff);
var x45: u32 = undefined;
var x46: u1 = undefined;
subborrowxU32(&x45, &x46, x44, x21, 0xffffffff);
var x47: u32 = undefined;
var x48: u1 = undefined;
subborrowxU32(&x47, &x48, x46, x23, 0xffffffff);
var x49: u32 = undefined;
var x50: u1 = undefined;
subborrowxU32(&x49, &x50, x48, cast(u32, x24), cast(u32, 0x0));
var x51: u32 = undefined;
cmovznzU32(&x51, x50, x25, x1);
var x52: u32 = undefined;
cmovznzU32(&x52, x50, x27, x3);
var x53: u32 = undefined;
cmovznzU32(&x53, x50, x29, x5);
var x54: u32 = undefined;
cmovznzU32(&x54, x50, x31, x7);
var x55: u32 = undefined;
cmovznzU32(&x55, x50, x33, x9);
var x56: u32 = undefined;
cmovznzU32(&x56, x50, x35, x11);
var x57: u32 = undefined;
cmovznzU32(&x57, x50, x37, x13);
var x58: u32 = undefined;
cmovznzU32(&x58, x50, x39, x15);
var x59: u32 = undefined;
cmovznzU32(&x59, x50, x41, x17);
var x60: u32 = undefined;
cmovznzU32(&x60, x50, x43, x19);
var x61: u32 = undefined;
cmovznzU32(&x61, x50, x45, x21);
var x62: u32 = undefined;
cmovznzU32(&x62, x50, x47, x23);
out1[0] = x51;
out1[1] = x52;
out1[2] = x53;
out1[3] = x54;
out1[4] = x55;
out1[5] = x56;
out1[6] = x57;
out1[7] = x58;
out1[8] = x59;
out1[9] = x60;
out1[10] = x61;
out1[11] = x62;
}
/// The function sub subtracts two field elements in the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// 0 ≤ eval arg2 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m
/// 0 ≤ eval out1 < m
///
pub fn sub(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
var x1: u32 = undefined;
var x2: u1 = undefined;
subborrowxU32(&x1, &x2, 0x0, (arg1[0]), (arg2[0]));
var x3: u32 = undefined;
var x4: u1 = undefined;
subborrowxU32(&x3, &x4, x2, (arg1[1]), (arg2[1]));
var x5: u32 = undefined;
var x6: u1 = undefined;
subborrowxU32(&x5, &x6, x4, (arg1[2]), (arg2[2]));
var x7: u32 = undefined;
var x8: u1 = undefined;
subborrowxU32(&x7, &x8, x6, (arg1[3]), (arg2[3]));
var x9: u32 = undefined;
var x10: u1 = undefined;
subborrowxU32(&x9, &x10, x8, (arg1[4]), (arg2[4]));
var x11: u32 = undefined;
var x12: u1 = undefined;
subborrowxU32(&x11, &x12, x10, (arg1[5]), (arg2[5]));
var x13: u32 = undefined;
var x14: u1 = undefined;
subborrowxU32(&x13, &x14, x12, (arg1[6]), (arg2[6]));
var x15: u32 = undefined;
var x16: u1 = undefined;
subborrowxU32(&x15, &x16, x14, (arg1[7]), (arg2[7]));
var x17: u32 = undefined;
var x18: u1 = undefined;
subborrowxU32(&x17, &x18, x16, (arg1[8]), (arg2[8]));
var x19: u32 = undefined;
var x20: u1 = undefined;
subborrowxU32(&x19, &x20, x18, (arg1[9]), (arg2[9]));
var x21: u32 = undefined;
var x22: u1 = undefined;
subborrowxU32(&x21, &x22, x20, (arg1[10]), (arg2[10]));
var x23: u32 = undefined;
var x24: u1 = undefined;
subborrowxU32(&x23, &x24, x22, (arg1[11]), (arg2[11]));
var x25: u32 = undefined;
cmovznzU32(&x25, x24, cast(u32, 0x0), 0xffffffff);
var x26: u32 = undefined;
var x27: u1 = undefined;
addcarryxU32(&x26, &x27, 0x0, x1, x25);
var x28: u32 = undefined;
var x29: u1 = undefined;
addcarryxU32(&x28, &x29, x27, x3, cast(u32, 0x0));
var x30: u32 = undefined;
var x31: u1 = undefined;
addcarryxU32(&x30, &x31, x29, x5, cast(u32, 0x0));
var x32: u32 = undefined;
var x33: u1 = undefined;
addcarryxU32(&x32, &x33, x31, x7, x25);
var x34: u32 = undefined;
var x35: u1 = undefined;
addcarryxU32(&x34, &x35, x33, x9, (x25 & 0xfffffffe));
var x36: u32 = undefined;
var x37: u1 = undefined;
addcarryxU32(&x36, &x37, x35, x11, x25);
var x38: u32 = undefined;
var x39: u1 = undefined;
addcarryxU32(&x38, &x39, x37, x13, x25);
var x40: u32 = undefined;
var x41: u1 = undefined;
addcarryxU32(&x40, &x41, x39, x15, x25);
var x42: u32 = undefined;
var x43: u1 = undefined;
addcarryxU32(&x42, &x43, x41, x17, x25);
var x44: u32 = undefined;
var x45: u1 = undefined;
addcarryxU32(&x44, &x45, x43, x19, x25);
var x46: u32 = undefined;
var x47: u1 = undefined;
addcarryxU32(&x46, &x47, x45, x21, x25);
var x48: u32 = undefined;
var x49: u1 = undefined;
addcarryxU32(&x48, &x49, x47, x23, x25);
out1[0] = x26;
out1[1] = x28;
out1[2] = x30;
out1[3] = x32;
out1[4] = x34;
out1[5] = x36;
out1[6] = x38;
out1[7] = x40;
out1[8] = x42;
out1[9] = x44;
out1[10] = x46;
out1[11] = x48;
}
/// The function opp negates a field element in the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m
/// 0 ≤ eval out1 < m
///
pub fn opp(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
var x1: u32 = undefined;
var x2: u1 = undefined;
subborrowxU32(&x1, &x2, 0x0, cast(u32, 0x0), (arg1[0]));
var x3: u32 = undefined;
var x4: u1 = undefined;
subborrowxU32(&x3, &x4, x2, cast(u32, 0x0), (arg1[1]));
var x5: u32 = undefined;
var x6: u1 = undefined;
subborrowxU32(&x5, &x6, x4, cast(u32, 0x0), (arg1[2]));
var x7: u32 = undefined;
var x8: u1 = undefined;
subborrowxU32(&x7, &x8, x6, cast(u32, 0x0), (arg1[3]));
var x9: u32 = undefined;
var x10: u1 = undefined;
subborrowxU32(&x9, &x10, x8, cast(u32, 0x0), (arg1[4]));
var x11: u32 = undefined;
var x12: u1 = undefined;
subborrowxU32(&x11, &x12, x10, cast(u32, 0x0), (arg1[5]));
var x13: u32 = undefined;
var x14: u1 = undefined;
subborrowxU32(&x13, &x14, x12, cast(u32, 0x0), (arg1[6]));
var x15: u32 = undefined;
var x16: u1 = undefined;
subborrowxU32(&x15, &x16, x14, cast(u32, 0x0), (arg1[7]));
var x17: u32 = undefined;
var x18: u1 = undefined;
subborrowxU32(&x17, &x18, x16, cast(u32, 0x0), (arg1[8]));
var x19: u32 = undefined;
var x20: u1 = undefined;
subborrowxU32(&x19, &x20, x18, cast(u32, 0x0), (arg1[9]));
var x21: u32 = undefined;
var x22: u1 = undefined;
subborrowxU32(&x21, &x22, x20, cast(u32, 0x0), (arg1[10]));
var x23: u32 = undefined;
var x24: u1 = undefined;
subborrowxU32(&x23, &x24, x22, cast(u32, 0x0), (arg1[11]));
var x25: u32 = undefined;
cmovznzU32(&x25, x24, cast(u32, 0x0), 0xffffffff);
var x26: u32 = undefined;
var x27: u1 = undefined;
addcarryxU32(&x26, &x27, 0x0, x1, x25);
var x28: u32 = undefined;
var x29: u1 = undefined;
addcarryxU32(&x28, &x29, x27, x3, cast(u32, 0x0));
var x30: u32 = undefined;
var x31: u1 = undefined;
addcarryxU32(&x30, &x31, x29, x5, cast(u32, 0x0));
var x32: u32 = undefined;
var x33: u1 = undefined;
addcarryxU32(&x32, &x33, x31, x7, x25);
var x34: u32 = undefined;
var x35: u1 = undefined;
addcarryxU32(&x34, &x35, x33, x9, (x25 & 0xfffffffe));
var x36: u32 = undefined;
var x37: u1 = undefined;
addcarryxU32(&x36, &x37, x35, x11, x25);
var x38: u32 = undefined;
var x39: u1 = undefined;
addcarryxU32(&x38, &x39, x37, x13, x25);
var x40: u32 = undefined;
var x41: u1 = undefined;
addcarryxU32(&x40, &x41, x39, x15, x25);
var x42: u32 = undefined;
var x43: u1 = undefined;
addcarryxU32(&x42, &x43, x41, x17, x25);
var x44: u32 = undefined;
var x45: u1 = undefined;
addcarryxU32(&x44, &x45, x43, x19, x25);
var x46: u32 = undefined;
var x47: u1 = undefined;
addcarryxU32(&x46, &x47, x45, x21, x25);
var x48: u32 = undefined;
var x49: u1 = undefined;
addcarryxU32(&x48, &x49, x47, x23, x25);
out1[0] = x26;
out1[1] = x28;
out1[2] = x30;
out1[3] = x32;
out1[4] = x34;
out1[5] = x36;
out1[6] = x38;
out1[7] = x40;
out1[8] = x42;
out1[9] = x44;
out1[10] = x46;
out1[11] = x48;
}
/// The function fromMontgomery translates a field element out of the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval out1 mod m = (eval arg1 * ((2^32)⁻¹ mod m)^12) mod m
/// 0 ≤ eval out1 < m
///
pub fn fromMontgomery(out1: *NonMontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[0]);
var x2: u32 = undefined;
var x3: u32 = undefined;
mulxU32(&x2, &x3, x1, 0xffffffff);
var x4: u32 = undefined;
var x5: u32 = undefined;
mulxU32(&x4, &x5, x1, 0xffffffff);
var x6: u32 = undefined;
var x7: u32 = undefined;
mulxU32(&x6, &x7, x1, 0xffffffff);
var x8: u32 = undefined;
var x9: u32 = undefined;
mulxU32(&x8, &x9, x1, 0xffffffff);
var x10: u32 = undefined;
var x11: u32 = undefined;
mulxU32(&x10, &x11, x1, 0xffffffff);
var x12: u32 = undefined;
var x13: u32 = undefined;
mulxU32(&x12, &x13, x1, 0xffffffff);
var x14: u32 = undefined;
var x15: u32 = undefined;
mulxU32(&x14, &x15, x1, 0xffffffff);
var x16: u32 = undefined;
var x17: u32 = undefined;
mulxU32(&x16, &x17, x1, 0xfffffffe);
var x18: u32 = undefined;
var x19: u32 = undefined;
mulxU32(&x18, &x19, x1, 0xffffffff);
var x20: u32 = undefined;
var x21: u32 = undefined;
mulxU32(&x20, &x21, x1, 0xffffffff);
var x22: u32 = undefined;
var x23: u1 = undefined;
addcarryxU32(&x22, &x23, 0x0, x19, x16);
var x24: u32 = undefined;
var x25: u1 = undefined;
addcarryxU32(&x24, &x25, x23, x17, x14);
var x26: u32 = undefined;
var x27: u1 = undefined;
addcarryxU32(&x26, &x27, x25, x15, x12);
var x28: u32 = undefined;
var x29: u1 = undefined;
addcarryxU32(&x28, &x29, x27, x13, x10);
var x30: u32 = undefined;
var x31: u1 = undefined;
addcarryxU32(&x30, &x31, x29, x11, x8);
var x32: u32 = undefined;
var x33: u1 = undefined;
addcarryxU32(&x32, &x33, x31, x9, x6);
var x34: u32 = undefined;
var x35: u1 = undefined;
addcarryxU32(&x34, &x35, x33, x7, x4);
var x36: u32 = undefined;
var x37: u1 = undefined;
addcarryxU32(&x36, &x37, x35, x5, x2);
var x38: u32 = undefined;
var x39: u1 = undefined;
addcarryxU32(&x38, &x39, 0x0, x1, x20);
var x40: u32 = undefined;
var x41: u1 = undefined;
addcarryxU32(&x40, &x41, 0x0, (cast(u32, x39) + x21), (arg1[1]));
var x42: u32 = undefined;
var x43: u32 = undefined;
mulxU32(&x42, &x43, x40, 0xffffffff);
var x44: u32 = undefined;
var x45: u32 = undefined;
mulxU32(&x44, &x45, x40, 0xffffffff);
var x46: u32 = undefined;
var x47: u32 = undefined;
mulxU32(&x46, &x47, x40, 0xffffffff);
var x48: u32 = undefined;
var x49: u32 = undefined;
mulxU32(&x48, &x49, x40, 0xffffffff);
var x50: u32 = undefined;
var x51: u32 = undefined;
mulxU32(&x50, &x51, x40, 0xffffffff);
var x52: u32 = undefined;
var x53: u32 = undefined;
mulxU32(&x52, &x53, x40, 0xffffffff);
var x54: u32 = undefined;
var x55: u32 = undefined;
mulxU32(&x54, &x55, x40, 0xffffffff);
var x56: u32 = undefined;
var x57: u32 = undefined;
mulxU32(&x56, &x57, x40, 0xfffffffe);
var x58: u32 = undefined;
var x59: u32 = undefined;
mulxU32(&x58, &x59, x40, 0xffffffff);
var x60: u32 = undefined;
var x61: u32 = undefined;
mulxU32(&x60, &x61, x40, 0xffffffff);
var x62: u32 = undefined;
var x63: u1 = undefined;
addcarryxU32(&x62, &x63, 0x0, x59, x56);
var x64: u32 = undefined;
var x65: u1 = undefined;
addcarryxU32(&x64, &x65, x63, x57, x54);
var x66: u32 = undefined;
var x67: u1 = undefined;
addcarryxU32(&x66, &x67, x65, x55, x52);
var x68: u32 = undefined;
var x69: u1 = undefined;
addcarryxU32(&x68, &x69, x67, x53, x50);
var x70: u32 = undefined;
var x71: u1 = undefined;
addcarryxU32(&x70, &x71, x69, x51, x48);
var x72: u32 = undefined;
var x73: u1 = undefined;
addcarryxU32(&x72, &x73, x71, x49, x46);
var x74: u32 = undefined;
var x75: u1 = undefined;
addcarryxU32(&x74, &x75, x73, x47, x44);
var x76: u32 = undefined;
var x77: u1 = undefined;
addcarryxU32(&x76, &x77, x75, x45, x42);
var x78: u32 = undefined;
var x79: u1 = undefined;
addcarryxU32(&x78, &x79, 0x0, x40, x60);
var x80: u32 = undefined;
var x81: u1 = undefined;
addcarryxU32(&x80, &x81, x79, cast(u32, x41), x61);
var x82: u32 = undefined;
var x83: u1 = undefined;
addcarryxU32(&x82, &x83, x81, x18, cast(u32, 0x0));
var x84: u32 = undefined;
var x85: u1 = undefined;
addcarryxU32(&x84, &x85, x83, x22, x58);
var x86: u32 = undefined;
var x87: u1 = undefined;
addcarryxU32(&x86, &x87, x85, x24, x62);
var x88: u32 = undefined;
var x89: u1 = undefined;
addcarryxU32(&x88, &x89, x87, x26, x64);
var x90: u32 = undefined;
var x91: u1 = undefined;
addcarryxU32(&x90, &x91, x89, x28, x66);
var x92: u32 = undefined;
var x93: u1 = undefined;
addcarryxU32(&x92, &x93, x91, x30, x68);
var x94: u32 = undefined;
var x95: u1 = undefined;
addcarryxU32(&x94, &x95, x93, x32, x70);
var x96: u32 = undefined;
var x97: u1 = undefined;
addcarryxU32(&x96, &x97, x95, x34, x72);
var x98: u32 = undefined;
var x99: u1 = undefined;
addcarryxU32(&x98, &x99, x97, x36, x74);
var x100: u32 = undefined;
var x101: u1 = undefined;
addcarryxU32(&x100, &x101, x99, (cast(u32, x37) + x3), x76);
var x102: u32 = undefined;
var x103: u1 = undefined;
addcarryxU32(&x102, &x103, x101, cast(u32, 0x0), (cast(u32, x77) + x43));
var x104: u32 = undefined;
var x105: u1 = undefined;
addcarryxU32(&x104, &x105, 0x0, x80, (arg1[2]));
var x106: u32 = undefined;
var x107: u1 = undefined;
addcarryxU32(&x106, &x107, x105, x82, cast(u32, 0x0));
var x108: u32 = undefined;
var x109: u1 = undefined;
addcarryxU32(&x108, &x109, x107, x84, cast(u32, 0x0));
var x110: u32 = undefined;
var x111: u1 = undefined;
addcarryxU32(&x110, &x111, x109, x86, cast(u32, 0x0));
var x112: u32 = undefined;
var x113: u1 = undefined;
addcarryxU32(&x112, &x113, x111, x88, cast(u32, 0x0));
var x114: u32 = undefined;
var x115: u1 = undefined;
addcarryxU32(&x114, &x115, x113, x90, cast(u32, 0x0));
var x116: u32 = undefined;
var x117: u1 = undefined;
addcarryxU32(&x116, &x117, x115, x92, cast(u32, 0x0));
var x118: u32 = undefined;
var x119: u1 = undefined;
addcarryxU32(&x118, &x119, x117, x94, cast(u32, 0x0));
var x120: u32 = undefined;
var x121: u1 = undefined;
addcarryxU32(&x120, &x121, x119, x96, cast(u32, 0x0));
var x122: u32 = undefined;
var x123: u1 = undefined;
addcarryxU32(&x122, &x123, x121, x98, cast(u32, 0x0));
var x124: u32 = undefined;
var x125: u1 = undefined;
addcarryxU32(&x124, &x125, x123, x100, cast(u32, 0x0));
var x126: u32 = undefined;
var x127: u1 = undefined;
addcarryxU32(&x126, &x127, x125, x102, cast(u32, 0x0));
var x128: u32 = undefined;
var x129: u32 = undefined;
mulxU32(&x128, &x129, x104, 0xffffffff);
var x130: u32 = undefined;
var x131: u32 = undefined;
mulxU32(&x130, &x131, x104, 0xffffffff);
var x132: u32 = undefined;
var x133: u32 = undefined;
mulxU32(&x132, &x133, x104, 0xffffffff);
var x134: u32 = undefined;
var x135: u32 = undefined;
mulxU32(&x134, &x135, x104, 0xffffffff);
var x136: u32 = undefined;
var x137: u32 = undefined;
mulxU32(&x136, &x137, x104, 0xffffffff);
var x138: u32 = undefined;
var x139: u32 = undefined;
mulxU32(&x138, &x139, x104, 0xffffffff);
var x140: u32 = undefined;
var x141: u32 = undefined;
mulxU32(&x140, &x141, x104, 0xffffffff);
var x142: u32 = undefined;
var x143: u32 = undefined;
mulxU32(&x142, &x143, x104, 0xfffffffe);
var x144: u32 = undefined;
var x145: u32 = undefined;
mulxU32(&x144, &x145, x104, 0xffffffff);
var x146: u32 = undefined;
var x147: u32 = undefined;
mulxU32(&x146, &x147, x104, 0xffffffff);
var x148: u32 = undefined;
var x149: u1 = undefined;
addcarryxU32(&x148, &x149, 0x0, x145, x142);
var x150: u32 = undefined;
var x151: u1 = undefined;
addcarryxU32(&x150, &x151, x149, x143, x140);
var x152: u32 = undefined;
var x153: u1 = undefined;
addcarryxU32(&x152, &x153, x151, x141, x138);
var x154: u32 = undefined;
var x155: u1 = undefined;
addcarryxU32(&x154, &x155, x153, x139, x136);
var x156: u32 = undefined;
var x157: u1 = undefined;
addcarryxU32(&x156, &x157, x155, x137, x134);
var x158: u32 = undefined;
var x159: u1 = undefined;
addcarryxU32(&x158, &x159, x157, x135, x132);
var x160: u32 = undefined;
var x161: u1 = undefined;
addcarryxU32(&x160, &x161, x159, x133, x130);
var x162: u32 = undefined;
var x163: u1 = undefined;
addcarryxU32(&x162, &x163, x161, x131, x128);
var x164: u32 = undefined;
var x165: u1 = undefined;
addcarryxU32(&x164, &x165, 0x0, x104, x146);
var x166: u32 = undefined;
var x167: u1 = undefined;
addcarryxU32(&x166, &x167, x165, x106, x147);
var x168: u32 = undefined;
var x169: u1 = undefined;
addcarryxU32(&x168, &x169, x167, x108, cast(u32, 0x0));
var x170: u32 = undefined;
var x171: u1 = undefined;
addcarryxU32(&x170, &x171, x169, x110, x144);
var x172: u32 = undefined;
var x173: u1 = undefined;
addcarryxU32(&x172, &x173, x171, x112, x148);
var x174: u32 = undefined;
var x175: u1 = undefined;
addcarryxU32(&x174, &x175, x173, x114, x150);
var x176: u32 = undefined;
var x177: u1 = undefined;
addcarryxU32(&x176, &x177, x175, x116, x152);
var x178: u32 = undefined;
var x179: u1 = undefined;
addcarryxU32(&x178, &x179, x177, x118, x154);
var x180: u32 = undefined;
var x181: u1 = undefined;
addcarryxU32(&x180, &x181, x179, x120, x156);
var x182: u32 = undefined;
var x183: u1 = undefined;
addcarryxU32(&x182, &x183, x181, x122, x158);
var x184: u32 = undefined;
var x185: u1 = undefined;
addcarryxU32(&x184, &x185, x183, x124, x160);
var x186: u32 = undefined;
var x187: u1 = undefined;
addcarryxU32(&x186, &x187, x185, x126, x162);
var x188: u32 = undefined;
var x189: u1 = undefined;
addcarryxU32(&x188, &x189, x187, (cast(u32, x127) + cast(u32, x103)), (cast(u32, x163) + x129));
var x190: u32 = undefined;
var x191: u1 = undefined;
addcarryxU32(&x190, &x191, 0x0, x166, (arg1[3]));
var x192: u32 = undefined;
var x193: u1 = undefined;
addcarryxU32(&x192, &x193, x191, x168, cast(u32, 0x0));
var x194: u32 = undefined;
var x195: u1 = undefined;
addcarryxU32(&x194, &x195, x193, x170, cast(u32, 0x0));
var x196: u32 = undefined;
var x197: u1 = undefined;
addcarryxU32(&x196, &x197, x195, x172, cast(u32, 0x0));
var x198: u32 = undefined;
var x199: u1 = undefined;
addcarryxU32(&x198, &x199, x197, x174, cast(u32, 0x0));
var x200: u32 = undefined;
var x201: u1 = undefined;
addcarryxU32(&x200, &x201, x199, x176, cast(u32, 0x0));
var x202: u32 = undefined;
var x203: u1 = undefined;
addcarryxU32(&x202, &x203, x201, x178, cast(u32, 0x0));
var x204: u32 = undefined;
var x205: u1 = undefined;
addcarryxU32(&x204, &x205, x203, x180, cast(u32, 0x0));
var x206: u32 = undefined;
var x207: u1 = undefined;
addcarryxU32(&x206, &x207, x205, x182, cast(u32, 0x0));
var x208: u32 = undefined;
var x209: u1 = undefined;
addcarryxU32(&x208, &x209, x207, x184, cast(u32, 0x0));
var x210: u32 = undefined;
var x211: u1 = undefined;
addcarryxU32(&x210, &x211, x209, x186, cast(u32, 0x0));
var x212: u32 = undefined;
var x213: u1 = undefined;
addcarryxU32(&x212, &x213, x211, x188, cast(u32, 0x0));
var x214: u32 = undefined;
var x215: u32 = undefined;
mulxU32(&x214, &x215, x190, 0xffffffff);
var x216: u32 = undefined;
var x217: u32 = undefined;
mulxU32(&x216, &x217, x190, 0xffffffff);
var x218: u32 = undefined;
var x219: u32 = undefined;
mulxU32(&x218, &x219, x190, 0xffffffff);
var x220: u32 = undefined;
var x221: u32 = undefined;
mulxU32(&x220, &x221, x190, 0xffffffff);
var x222: u32 = undefined;
var x223: u32 = undefined;
mulxU32(&x222, &x223, x190, 0xffffffff);
var x224: u32 = undefined;
var x225: u32 = undefined;
mulxU32(&x224, &x225, x190, 0xffffffff);
var x226: u32 = undefined;
var x227: u32 = undefined;
mulxU32(&x226, &x227, x190, 0xffffffff);
var x228: u32 = undefined;
var x229: u32 = undefined;
mulxU32(&x228, &x229, x190, 0xfffffffe);
var x230: u32 = undefined;
var x231: u32 = undefined;
mulxU32(&x230, &x231, x190, 0xffffffff);
var x232: u32 = undefined;
var x233: u32 = undefined;
mulxU32(&x232, &x233, x190, 0xffffffff);
var x234: u32 = undefined;
var x235: u1 = undefined;
addcarryxU32(&x234, &x235, 0x0, x231, x228);
var x236: u32 = undefined;
var x237: u1 = undefined;
addcarryxU32(&x236, &x237, x235, x229, x226);
var x238: u32 = undefined;
var x239: u1 = undefined;
addcarryxU32(&x238, &x239, x237, x227, x224);
var x240: u32 = undefined;
var x241: u1 = undefined;
addcarryxU32(&x240, &x241, x239, x225, x222);
var x242: u32 = undefined;
var x243: u1 = undefined;
addcarryxU32(&x242, &x243, x241, x223, x220);
var x244: u32 = undefined;
var x245: u1 = undefined;
addcarryxU32(&x244, &x245, x243, x221, x218);
var x246: u32 = undefined;
var x247: u1 = undefined;
addcarryxU32(&x246, &x247, x245, x219, x216);
var x248: u32 = undefined;
var x249: u1 = undefined;
addcarryxU32(&x248, &x249, x247, x217, x214);
var x250: u32 = undefined;
var x251: u1 = undefined;
addcarryxU32(&x250, &x251, 0x0, x190, x232);
var x252: u32 = undefined;
var x253: u1 = undefined;
addcarryxU32(&x252, &x253, x251, x192, x233);
var x254: u32 = undefined;
var x255: u1 = undefined;
addcarryxU32(&x254, &x255, x253, x194, cast(u32, 0x0));
var x256: u32 = undefined;
var x257: u1 = undefined;
addcarryxU32(&x256, &x257, x255, x196, x230);
var x258: u32 = undefined;
var x259: u1 = undefined;
addcarryxU32(&x258, &x259, x257, x198, x234);
var x260: u32 = undefined;
var x261: u1 = undefined;
addcarryxU32(&x260, &x261, x259, x200, x236);
var x262: u32 = undefined;
var x263: u1 = undefined;
addcarryxU32(&x262, &x263, x261, x202, x238);
var x264: u32 = undefined;
var x265: u1 = undefined;
addcarryxU32(&x264, &x265, x263, x204, x240);
var x266: u32 = undefined;
var x267: u1 = undefined;
addcarryxU32(&x266, &x267, x265, x206, x242);
var x268: u32 = undefined;
var x269: u1 = undefined;
addcarryxU32(&x268, &x269, x267, x208, x244);
var x270: u32 = undefined;
var x271: u1 = undefined;
addcarryxU32(&x270, &x271, x269, x210, x246);
var x272: u32 = undefined;
var x273: u1 = undefined;
addcarryxU32(&x272, &x273, x271, x212, x248);
var x274: u32 = undefined;
var x275: u1 = undefined;
addcarryxU32(&x274, &x275, x273, (cast(u32, x213) + cast(u32, x189)), (cast(u32, x249) + x215));
var x276: u32 = undefined;
var x277: u1 = undefined;
addcarryxU32(&x276, &x277, 0x0, x252, (arg1[4]));
var x278: u32 = undefined;
var x279: u1 = undefined;
addcarryxU32(&x278, &x279, x277, x254, cast(u32, 0x0));
var x280: u32 = undefined;
var x281: u1 = undefined;
addcarryxU32(&x280, &x281, x279, x256, cast(u32, 0x0));
var x282: u32 = undefined;
var x283: u1 = undefined;
addcarryxU32(&x282, &x283, x281, x258, cast(u32, 0x0));
var x284: u32 = undefined;
var x285: u1 = undefined;
addcarryxU32(&x284, &x285, x283, x260, cast(u32, 0x0));
var x286: u32 = undefined;
var x287: u1 = undefined;
addcarryxU32(&x286, &x287, x285, x262, cast(u32, 0x0));
var x288: u32 = undefined;
var x289: u1 = undefined;
addcarryxU32(&x288, &x289, x287, x264, cast(u32, 0x0));
var x290: u32 = undefined;
var x291: u1 = undefined;
addcarryxU32(&x290, &x291, x289, x266, cast(u32, 0x0));
var x292: u32 = undefined;
var x293: u1 = undefined;
addcarryxU32(&x292, &x293, x291, x268, cast(u32, 0x0));
var x294: u32 = undefined;
var x295: u1 = undefined;
addcarryxU32(&x294, &x295, x293, x270, cast(u32, 0x0));
var x296: u32 = undefined;
var x297: u1 = undefined;
addcarryxU32(&x296, &x297, x295, x272, cast(u32, 0x0));
var x298: u32 = undefined;
var x299: u1 = undefined;
addcarryxU32(&x298, &x299, x297, x274, cast(u32, 0x0));
var x300: u32 = undefined;
var x301: u32 = undefined;
mulxU32(&x300, &x301, x276, 0xffffffff);
var x302: u32 = undefined;
var x303: u32 = undefined;
mulxU32(&x302, &x303, x276, 0xffffffff);
var x304: u32 = undefined;
var x305: u32 = undefined;
mulxU32(&x304, &x305, x276, 0xffffffff);
var x306: u32 = undefined;
var x307: u32 = undefined;
mulxU32(&x306, &x307, x276, 0xffffffff);
var x308: u32 = undefined;
var x309: u32 = undefined;
mulxU32(&x308, &x309, x276, 0xffffffff);
var x310: u32 = undefined;
var x311: u32 = undefined;
mulxU32(&x310, &x311, x276, 0xffffffff);
var x312: u32 = undefined;
var x313: u32 = undefined;
mulxU32(&x312, &x313, x276, 0xffffffff);
var x314: u32 = undefined;
var x315: u32 = undefined;
mulxU32(&x314, &x315, x276, 0xfffffffe);
var x316: u32 = undefined;
var x317: u32 = undefined;
mulxU32(&x316, &x317, x276, 0xffffffff);
var x318: u32 = undefined;
var x319: u32 = undefined;
mulxU32(&x318, &x319, x276, 0xffffffff);
var x320: u32 = undefined;
var x321: u1 = undefined;
addcarryxU32(&x320, &x321, 0x0, x317, x314);
var x322: u32 = undefined;
var x323: u1 = undefined;
addcarryxU32(&x322, &x323, x321, x315, x312);
var x324: u32 = undefined;
var x325: u1 = undefined;
addcarryxU32(&x324, &x325, x323, x313, x310);
var x326: u32 = undefined;
var x327: u1 = undefined;
addcarryxU32(&x326, &x327, x325, x311, x308);
var x328: u32 = undefined;
var x329: u1 = undefined;
addcarryxU32(&x328, &x329, x327, x309, x306);
var x330: u32 = undefined;
var x331: u1 = undefined;
addcarryxU32(&x330, &x331, x329, x307, x304);
var x332: u32 = undefined;
var x333: u1 = undefined;
addcarryxU32(&x332, &x333, x331, x305, x302);
var x334: u32 = undefined;
var x335: u1 = undefined;
addcarryxU32(&x334, &x335, x333, x303, x300);
var x336: u32 = undefined;
var x337: u1 = undefined;
addcarryxU32(&x336, &x337, 0x0, x276, x318);
var x338: u32 = undefined;
var x339: u1 = undefined;
addcarryxU32(&x338, &x339, x337, x278, x319);
var x340: u32 = undefined;
var x341: u1 = undefined;
addcarryxU32(&x340, &x341, x339, x280, cast(u32, 0x0));
var x342: u32 = undefined;
var x343: u1 = undefined;
addcarryxU32(&x342, &x343, x341, x282, x316);
var x344: u32 = undefined;
var x345: u1 = undefined;
addcarryxU32(&x344, &x345, x343, x284, x320);
var x346: u32 = undefined;
var x347: u1 = undefined;
addcarryxU32(&x346, &x347, x345, x286, x322);
var x348: u32 = undefined;
var x349: u1 = undefined;
addcarryxU32(&x348, &x349, x347, x288, x324);
var x350: u32 = undefined;
var x351: u1 = undefined;
addcarryxU32(&x350, &x351, x349, x290, x326);
var x352: u32 = undefined;
var x353: u1 = undefined;
addcarryxU32(&x352, &x353, x351, x292, x328);
var x354: u32 = undefined;
var x355: u1 = undefined;
addcarryxU32(&x354, &x355, x353, x294, x330);
var x356: u32 = undefined;
var x357: u1 = undefined;
addcarryxU32(&x356, &x357, x355, x296, x332);
var x358: u32 = undefined;
var x359: u1 = undefined;
addcarryxU32(&x358, &x359, x357, x298, x334);
var x360: u32 = undefined;
var x361: u1 = undefined;
addcarryxU32(&x360, &x361, x359, (cast(u32, x299) + cast(u32, x275)), (cast(u32, x335) + x301));
var x362: u32 = undefined;
var x363: u1 = undefined;
addcarryxU32(&x362, &x363, 0x0, x338, (arg1[5]));
var x364: u32 = undefined;
var x365: u1 = undefined;
addcarryxU32(&x364, &x365, x363, x340, cast(u32, 0x0));
var x366: u32 = undefined;
var x367: u1 = undefined;
addcarryxU32(&x366, &x367, x365, x342, cast(u32, 0x0));
var x368: u32 = undefined;
var x369: u1 = undefined;
addcarryxU32(&x368, &x369, x367, x344, cast(u32, 0x0));
var x370: u32 = undefined;
var x371: u1 = undefined;
addcarryxU32(&x370, &x371, x369, x346, cast(u32, 0x0));
var x372: u32 = undefined;
var x373: u1 = undefined;
addcarryxU32(&x372, &x373, x371, x348, cast(u32, 0x0));
var x374: u32 = undefined;
var x375: u1 = undefined;
addcarryxU32(&x374, &x375, x373, x350, cast(u32, 0x0));
var x376: u32 = undefined;
var x377: u1 = undefined;
addcarryxU32(&x376, &x377, x375, x352, cast(u32, 0x0));
var x378: u32 = undefined;
var x379: u1 = undefined;
addcarryxU32(&x378, &x379, x377, x354, cast(u32, 0x0));
var x380: u32 = undefined;
var x381: u1 = undefined;
addcarryxU32(&x380, &x381, x379, x356, cast(u32, 0x0));
var x382: u32 = undefined;
var x383: u1 = undefined;
addcarryxU32(&x382, &x383, x381, x358, cast(u32, 0x0));
var x384: u32 = undefined;
var x385: u1 = undefined;
addcarryxU32(&x384, &x385, x383, x360, cast(u32, 0x0));
var x386: u32 = undefined;
var x387: u32 = undefined;
mulxU32(&x386, &x387, x362, 0xffffffff);
var x388: u32 = undefined;
var x389: u32 = undefined;
mulxU32(&x388, &x389, x362, 0xffffffff);
var x390: u32 = undefined;
var x391: u32 = undefined;
mulxU32(&x390, &x391, x362, 0xffffffff);
var x392: u32 = undefined;
var x393: u32 = undefined;
mulxU32(&x392, &x393, x362, 0xffffffff);
var x394: u32 = undefined;
var x395: u32 = undefined;
mulxU32(&x394, &x395, x362, 0xffffffff);
var x396: u32 = undefined;
var x397: u32 = undefined;
mulxU32(&x396, &x397, x362, 0xffffffff);
var x398: u32 = undefined;
var x399: u32 = undefined;
mulxU32(&x398, &x399, x362, 0xffffffff);
var x400: u32 = undefined;
var x401: u32 = undefined;
mulxU32(&x400, &x401, x362, 0xfffffffe);
var x402: u32 = undefined;
var x403: u32 = undefined;
mulxU32(&x402, &x403, x362, 0xffffffff);
var x404: u32 = undefined;
var x405: u32 = undefined;
mulxU32(&x404, &x405, x362, 0xffffffff);
var x406: u32 = undefined;
var x407: u1 = undefined;
addcarryxU32(&x406, &x407, 0x0, x403, x400);
var x408: u32 = undefined;
var x409: u1 = undefined;
addcarryxU32(&x408, &x409, x407, x401, x398);
var x410: u32 = undefined;
var x411: u1 = undefined;
addcarryxU32(&x410, &x411, x409, x399, x396);
var x412: u32 = undefined;
var x413: u1 = undefined;
addcarryxU32(&x412, &x413, x411, x397, x394);
var x414: u32 = undefined;
var x415: u1 = undefined;
addcarryxU32(&x414, &x415, x413, x395, x392);
var x416: u32 = undefined;
var x417: u1 = undefined;
addcarryxU32(&x416, &x417, x415, x393, x390);
var x418: u32 = undefined;
var x419: u1 = undefined;
addcarryxU32(&x418, &x419, x417, x391, x388);
var x420: u32 = undefined;
var x421: u1 = undefined;
addcarryxU32(&x420, &x421, x419, x389, x386);
var x422: u32 = undefined;
var x423: u1 = undefined;
addcarryxU32(&x422, &x423, 0x0, x362, x404);
var x424: u32 = undefined;
var x425: u1 = undefined;
addcarryxU32(&x424, &x425, x423, x364, x405);
var x426: u32 = undefined;
var x427: u1 = undefined;
addcarryxU32(&x426, &x427, x425, x366, cast(u32, 0x0));
var x428: u32 = undefined;
var x429: u1 = undefined;
addcarryxU32(&x428, &x429, x427, x368, x402);
var x430: u32 = undefined;
var x431: u1 = undefined;
addcarryxU32(&x430, &x431, x429, x370, x406);
var x432: u32 = undefined;
var x433: u1 = undefined;
addcarryxU32(&x432, &x433, x431, x372, x408);
var x434: u32 = undefined;
var x435: u1 = undefined;
addcarryxU32(&x434, &x435, x433, x374, x410);
var x436: u32 = undefined;
var x437: u1 = undefined;
addcarryxU32(&x436, &x437, x435, x376, x412);
var x438: u32 = undefined;
var x439: u1 = undefined;
addcarryxU32(&x438, &x439, x437, x378, x414);
var x440: u32 = undefined;
var x441: u1 = undefined;
addcarryxU32(&x440, &x441, x439, x380, x416);
var x442: u32 = undefined;
var x443: u1 = undefined;
addcarryxU32(&x442, &x443, x441, x382, x418);
var x444: u32 = undefined;
var x445: u1 = undefined;
addcarryxU32(&x444, &x445, x443, x384, x420);
var x446: u32 = undefined;
var x447: u1 = undefined;
addcarryxU32(&x446, &x447, x445, (cast(u32, x385) + cast(u32, x361)), (cast(u32, x421) + x387));
var x448: u32 = undefined;
var x449: u1 = undefined;
addcarryxU32(&x448, &x449, 0x0, x424, (arg1[6]));
var x450: u32 = undefined;
var x451: u1 = undefined;
addcarryxU32(&x450, &x451, x449, x426, cast(u32, 0x0));
var x452: u32 = undefined;
var x453: u1 = undefined;
addcarryxU32(&x452, &x453, x451, x428, cast(u32, 0x0));
var x454: u32 = undefined;
var x455: u1 = undefined;
addcarryxU32(&x454, &x455, x453, x430, cast(u32, 0x0));
var x456: u32 = undefined;
var x457: u1 = undefined;
addcarryxU32(&x456, &x457, x455, x432, cast(u32, 0x0));
var x458: u32 = undefined;
var x459: u1 = undefined;
addcarryxU32(&x458, &x459, x457, x434, cast(u32, 0x0));
var x460: u32 = undefined;
var x461: u1 = undefined;
addcarryxU32(&x460, &x461, x459, x436, cast(u32, 0x0));
var x462: u32 = undefined;
var x463: u1 = undefined;
addcarryxU32(&x462, &x463, x461, x438, cast(u32, 0x0));
var x464: u32 = undefined;
var x465: u1 = undefined;
addcarryxU32(&x464, &x465, x463, x440, cast(u32, 0x0));
var x466: u32 = undefined;
var x467: u1 = undefined;
addcarryxU32(&x466, &x467, x465, x442, cast(u32, 0x0));
var x468: u32 = undefined;
var x469: u1 = undefined;
addcarryxU32(&x468, &x469, x467, x444, cast(u32, 0x0));
var x470: u32 = undefined;
var x471: u1 = undefined;
addcarryxU32(&x470, &x471, x469, x446, cast(u32, 0x0));
var x472: u32 = undefined;
var x473: u32 = undefined;
mulxU32(&x472, &x473, x448, 0xffffffff);
var x474: u32 = undefined;
var x475: u32 = undefined;
mulxU32(&x474, &x475, x448, 0xffffffff);
var x476: u32 = undefined;
var x477: u32 = undefined;
mulxU32(&x476, &x477, x448, 0xffffffff);
var x478: u32 = undefined;
var x479: u32 = undefined;
mulxU32(&x478, &x479, x448, 0xffffffff);
var x480: u32 = undefined;
var x481: u32 = undefined;
mulxU32(&x480, &x481, x448, 0xffffffff);
var x482: u32 = undefined;
var x483: u32 = undefined;
mulxU32(&x482, &x483, x448, 0xffffffff);
var x484: u32 = undefined;
var x485: u32 = undefined;
mulxU32(&x484, &x485, x448, 0xffffffff);
var x486: u32 = undefined;
var x487: u32 = undefined;
mulxU32(&x486, &x487, x448, 0xfffffffe);
var x488: u32 = undefined;
var x489: u32 = undefined;
mulxU32(&x488, &x489, x448, 0xffffffff);
var x490: u32 = undefined;
var x491: u32 = undefined;
mulxU32(&x490, &x491, x448, 0xffffffff);
var x492: u32 = undefined;
var x493: u1 = undefined;
addcarryxU32(&x492, &x493, 0x0, x489, x486);
var x494: u32 = undefined;
var x495: u1 = undefined;
addcarryxU32(&x494, &x495, x493, x487, x484);
var x496: u32 = undefined;
var x497: u1 = undefined;
addcarryxU32(&x496, &x497, x495, x485, x482);
var x498: u32 = undefined;
var x499: u1 = undefined;
addcarryxU32(&x498, &x499, x497, x483, x480);
var x500: u32 = undefined;
var x501: u1 = undefined;
addcarryxU32(&x500, &x501, x499, x481, x478);
var x502: u32 = undefined;
var x503: u1 = undefined;
addcarryxU32(&x502, &x503, x501, x479, x476);
var x504: u32 = undefined;
var x505: u1 = undefined;
addcarryxU32(&x504, &x505, x503, x477, x474);
var x506: u32 = undefined;
var x507: u1 = undefined;
addcarryxU32(&x506, &x507, x505, x475, x472);
var x508: u32 = undefined;
var x509: u1 = undefined;
addcarryxU32(&x508, &x509, 0x0, x448, x490);
var x510: u32 = undefined;
var x511: u1 = undefined;
addcarryxU32(&x510, &x511, x509, x450, x491);
var x512: u32 = undefined;
var x513: u1 = undefined;
addcarryxU32(&x512, &x513, x511, x452, cast(u32, 0x0));
var x514: u32 = undefined;
var x515: u1 = undefined;
addcarryxU32(&x514, &x515, x513, x454, x488);
var x516: u32 = undefined;
var x517: u1 = undefined;
addcarryxU32(&x516, &x517, x515, x456, x492);
var x518: u32 = undefined;
var x519: u1 = undefined;
addcarryxU32(&x518, &x519, x517, x458, x494);
var x520: u32 = undefined;
var x521: u1 = undefined;
addcarryxU32(&x520, &x521, x519, x460, x496);
var x522: u32 = undefined;
var x523: u1 = undefined;
addcarryxU32(&x522, &x523, x521, x462, x498);
var x524: u32 = undefined;
var x525: u1 = undefined;
addcarryxU32(&x524, &x525, x523, x464, x500);
var x526: u32 = undefined;
var x527: u1 = undefined;
addcarryxU32(&x526, &x527, x525, x466, x502);
var x528: u32 = undefined;
var x529: u1 = undefined;
addcarryxU32(&x528, &x529, x527, x468, x504);
var x530: u32 = undefined;
var x531: u1 = undefined;
addcarryxU32(&x530, &x531, x529, x470, x506);
var x532: u32 = undefined;
var x533: u1 = undefined;
addcarryxU32(&x532, &x533, x531, (cast(u32, x471) + cast(u32, x447)), (cast(u32, x507) + x473));
var x534: u32 = undefined;
var x535: u1 = undefined;
addcarryxU32(&x534, &x535, 0x0, x510, (arg1[7]));
var x536: u32 = undefined;
var x537: u1 = undefined;
addcarryxU32(&x536, &x537, x535, x512, cast(u32, 0x0));
var x538: u32 = undefined;
var x539: u1 = undefined;
addcarryxU32(&x538, &x539, x537, x514, cast(u32, 0x0));
var x540: u32 = undefined;
var x541: u1 = undefined;
addcarryxU32(&x540, &x541, x539, x516, cast(u32, 0x0));
var x542: u32 = undefined;
var x543: u1 = undefined;
addcarryxU32(&x542, &x543, x541, x518, cast(u32, 0x0));
var x544: u32 = undefined;
var x545: u1 = undefined;
addcarryxU32(&x544, &x545, x543, x520, cast(u32, 0x0));
var x546: u32 = undefined;
var x547: u1 = undefined;
addcarryxU32(&x546, &x547, x545, x522, cast(u32, 0x0));
var x548: u32 = undefined;
var x549: u1 = undefined;
addcarryxU32(&x548, &x549, x547, x524, cast(u32, 0x0));
var x550: u32 = undefined;
var x551: u1 = undefined;
addcarryxU32(&x550, &x551, x549, x526, cast(u32, 0x0));
var x552: u32 = undefined;
var x553: u1 = undefined;
addcarryxU32(&x552, &x553, x551, x528, cast(u32, 0x0));
var x554: u32 = undefined;
var x555: u1 = undefined;
addcarryxU32(&x554, &x555, x553, x530, cast(u32, 0x0));
var x556: u32 = undefined;
var x557: u1 = undefined;
addcarryxU32(&x556, &x557, x555, x532, cast(u32, 0x0));
var x558: u32 = undefined;
var x559: u32 = undefined;
mulxU32(&x558, &x559, x534, 0xffffffff);
var x560: u32 = undefined;
var x561: u32 = undefined;
mulxU32(&x560, &x561, x534, 0xffffffff);
var x562: u32 = undefined;
var x563: u32 = undefined;
mulxU32(&x562, &x563, x534, 0xffffffff);
var x564: u32 = undefined;
var x565: u32 = undefined;
mulxU32(&x564, &x565, x534, 0xffffffff);
var x566: u32 = undefined;
var x567: u32 = undefined;
mulxU32(&x566, &x567, x534, 0xffffffff);
var x568: u32 = undefined;
var x569: u32 = undefined;
mulxU32(&x568, &x569, x534, 0xffffffff);
var x570: u32 = undefined;
var x571: u32 = undefined;
mulxU32(&x570, &x571, x534, 0xffffffff);
var x572: u32 = undefined;
var x573: u32 = undefined;
mulxU32(&x572, &x573, x534, 0xfffffffe);
var x574: u32 = undefined;
var x575: u32 = undefined;
mulxU32(&x574, &x575, x534, 0xffffffff);
var x576: u32 = undefined;
var x577: u32 = undefined;
mulxU32(&x576, &x577, x534, 0xffffffff);
var x578: u32 = undefined;
var x579: u1 = undefined;
addcarryxU32(&x578, &x579, 0x0, x575, x572);
var x580: u32 = undefined;
var x581: u1 = undefined;
addcarryxU32(&x580, &x581, x579, x573, x570);
var x582: u32 = undefined;
var x583: u1 = undefined;
addcarryxU32(&x582, &x583, x581, x571, x568);
var x584: u32 = undefined;
var x585: u1 = undefined;
addcarryxU32(&x584, &x585, x583, x569, x566);
var x586: u32 = undefined;
var x587: u1 = undefined;
addcarryxU32(&x586, &x587, x585, x567, x564);
var x588: u32 = undefined;
var x589: u1 = undefined;
addcarryxU32(&x588, &x589, x587, x565, x562);
var x590: u32 = undefined;
var x591: u1 = undefined;
addcarryxU32(&x590, &x591, x589, x563, x560);
var x592: u32 = undefined;
var x593: u1 = undefined;
addcarryxU32(&x592, &x593, x591, x561, x558);
var x594: u32 = undefined;
var x595: u1 = undefined;
addcarryxU32(&x594, &x595, 0x0, x534, x576);
var x596: u32 = undefined;
var x597: u1 = undefined;
addcarryxU32(&x596, &x597, x595, x536, x577);
var x598: u32 = undefined;
var x599: u1 = undefined;
addcarryxU32(&x598, &x599, x597, x538, cast(u32, 0x0));
var x600: u32 = undefined;
var x601: u1 = undefined;
addcarryxU32(&x600, &x601, x599, x540, x574);
var x602: u32 = undefined;
var x603: u1 = undefined;
addcarryxU32(&x602, &x603, x601, x542, x578);
var x604: u32 = undefined;
var x605: u1 = undefined;
addcarryxU32(&x604, &x605, x603, x544, x580);
var x606: u32 = undefined;
var x607: u1 = undefined;
addcarryxU32(&x606, &x607, x605, x546, x582);
var x608: u32 = undefined;
var x609: u1 = undefined;
addcarryxU32(&x608, &x609, x607, x548, x584);
var x610: u32 = undefined;
var x611: u1 = undefined;
addcarryxU32(&x610, &x611, x609, x550, x586);
var x612: u32 = undefined;
var x613: u1 = undefined;
addcarryxU32(&x612, &x613, x611, x552, x588);
var x614: u32 = undefined;
var x615: u1 = undefined;
addcarryxU32(&x614, &x615, x613, x554, x590);
var x616: u32 = undefined;
var x617: u1 = undefined;
addcarryxU32(&x616, &x617, x615, x556, x592);
var x618: u32 = undefined;
var x619: u1 = undefined;
addcarryxU32(&x618, &x619, x617, (cast(u32, x557) + cast(u32, x533)), (cast(u32, x593) + x559));
var x620: u32 = undefined;
var x621: u1 = undefined;
addcarryxU32(&x620, &x621, 0x0, x596, (arg1[8]));
var x622: u32 = undefined;
var x623: u1 = undefined;
addcarryxU32(&x622, &x623, x621, x598, cast(u32, 0x0));
var x624: u32 = undefined;
var x625: u1 = undefined;
addcarryxU32(&x624, &x625, x623, x600, cast(u32, 0x0));
var x626: u32 = undefined;
var x627: u1 = undefined;
addcarryxU32(&x626, &x627, x625, x602, cast(u32, 0x0));
var x628: u32 = undefined;
var x629: u1 = undefined;
addcarryxU32(&x628, &x629, x627, x604, cast(u32, 0x0));
var x630: u32 = undefined;
var x631: u1 = undefined;
addcarryxU32(&x630, &x631, x629, x606, cast(u32, 0x0));
var x632: u32 = undefined;
var x633: u1 = undefined;
addcarryxU32(&x632, &x633, x631, x608, cast(u32, 0x0));
var x634: u32 = undefined;
var x635: u1 = undefined;
addcarryxU32(&x634, &x635, x633, x610, cast(u32, 0x0));
var x636: u32 = undefined;
var x637: u1 = undefined;
addcarryxU32(&x636, &x637, x635, x612, cast(u32, 0x0));
var x638: u32 = undefined;
var x639: u1 = undefined;
addcarryxU32(&x638, &x639, x637, x614, cast(u32, 0x0));
var x640: u32 = undefined;
var x641: u1 = undefined;
addcarryxU32(&x640, &x641, x639, x616, cast(u32, 0x0));
var x642: u32 = undefined;
var x643: u1 = undefined;
addcarryxU32(&x642, &x643, x641, x618, cast(u32, 0x0));
var x644: u32 = undefined;
var x645: u32 = undefined;
mulxU32(&x644, &x645, x620, 0xffffffff);
var x646: u32 = undefined;
var x647: u32 = undefined;
mulxU32(&x646, &x647, x620, 0xffffffff);
var x648: u32 = undefined;
var x649: u32 = undefined;
mulxU32(&x648, &x649, x620, 0xffffffff);
var x650: u32 = undefined;
var x651: u32 = undefined;
mulxU32(&x650, &x651, x620, 0xffffffff);
var x652: u32 = undefined;
var x653: u32 = undefined;
mulxU32(&x652, &x653, x620, 0xffffffff);
var x654: u32 = undefined;
var x655: u32 = undefined;
mulxU32(&x654, &x655, x620, 0xffffffff);
var x656: u32 = undefined;
var x657: u32 = undefined;
mulxU32(&x656, &x657, x620, 0xffffffff);
var x658: u32 = undefined;
var x659: u32 = undefined;
mulxU32(&x658, &x659, x620, 0xfffffffe);
var x660: u32 = undefined;
var x661: u32 = undefined;
mulxU32(&x660, &x661, x620, 0xffffffff);
var x662: u32 = undefined;
var x663: u32 = undefined;
mulxU32(&x662, &x663, x620, 0xffffffff);
var x664: u32 = undefined;
var x665: u1 = undefined;
addcarryxU32(&x664, &x665, 0x0, x661, x658);
var x666: u32 = undefined;
var x667: u1 = undefined;
addcarryxU32(&x666, &x667, x665, x659, x656);
var x668: u32 = undefined;
var x669: u1 = undefined;
addcarryxU32(&x668, &x669, x667, x657, x654);
var x670: u32 = undefined;
var x671: u1 = undefined;
addcarryxU32(&x670, &x671, x669, x655, x652);
var x672: u32 = undefined;
var x673: u1 = undefined;
addcarryxU32(&x672, &x673, x671, x653, x650);
var x674: u32 = undefined;
var x675: u1 = undefined;
addcarryxU32(&x674, &x675, x673, x651, x648);
var x676: u32 = undefined;
var x677: u1 = undefined;
addcarryxU32(&x676, &x677, x675, x649, x646);
var x678: u32 = undefined;
var x679: u1 = undefined;
addcarryxU32(&x678, &x679, x677, x647, x644);
var x680: u32 = undefined;
var x681: u1 = undefined;
addcarryxU32(&x680, &x681, 0x0, x620, x662);
var x682: u32 = undefined;
var x683: u1 = undefined;
addcarryxU32(&x682, &x683, x681, x622, x663);
var x684: u32 = undefined;
var x685: u1 = undefined;
addcarryxU32(&x684, &x685, x683, x624, cast(u32, 0x0));
var x686: u32 = undefined;
var x687: u1 = undefined;
addcarryxU32(&x686, &x687, x685, x626, x660);
var x688: u32 = undefined;
var x689: u1 = undefined;
addcarryxU32(&x688, &x689, x687, x628, x664);
var x690: u32 = undefined;
var x691: u1 = undefined;
addcarryxU32(&x690, &x691, x689, x630, x666);
var x692: u32 = undefined;
var x693: u1 = undefined;
addcarryxU32(&x692, &x693, x691, x632, x668);
var x694: u32 = undefined;
var x695: u1 = undefined;
addcarryxU32(&x694, &x695, x693, x634, x670);
var x696: u32 = undefined;
var x697: u1 = undefined;
addcarryxU32(&x696, &x697, x695, x636, x672);
var x698: u32 = undefined;
var x699: u1 = undefined;
addcarryxU32(&x698, &x699, x697, x638, x674);
var x700: u32 = undefined;
var x701: u1 = undefined;
addcarryxU32(&x700, &x701, x699, x640, x676);
var x702: u32 = undefined;
var x703: u1 = undefined;
addcarryxU32(&x702, &x703, x701, x642, x678);
var x704: u32 = undefined;
var x705: u1 = undefined;
addcarryxU32(&x704, &x705, x703, (cast(u32, x643) + cast(u32, x619)), (cast(u32, x679) + x645));
var x706: u32 = undefined;
var x707: u1 = undefined;
addcarryxU32(&x706, &x707, 0x0, x682, (arg1[9]));
var x708: u32 = undefined;
var x709: u1 = undefined;
addcarryxU32(&x708, &x709, x707, x684, cast(u32, 0x0));
var x710: u32 = undefined;
var x711: u1 = undefined;
addcarryxU32(&x710, &x711, x709, x686, cast(u32, 0x0));
var x712: u32 = undefined;
var x713: u1 = undefined;
addcarryxU32(&x712, &x713, x711, x688, cast(u32, 0x0));
var x714: u32 = undefined;
var x715: u1 = undefined;
addcarryxU32(&x714, &x715, x713, x690, cast(u32, 0x0));
var x716: u32 = undefined;
var x717: u1 = undefined;
addcarryxU32(&x716, &x717, x715, x692, cast(u32, 0x0));
var x718: u32 = undefined;
var x719: u1 = undefined;
addcarryxU32(&x718, &x719, x717, x694, cast(u32, 0x0));
var x720: u32 = undefined;
var x721: u1 = undefined;
addcarryxU32(&x720, &x721, x719, x696, cast(u32, 0x0));
var x722: u32 = undefined;
var x723: u1 = undefined;
addcarryxU32(&x722, &x723, x721, x698, cast(u32, 0x0));
var x724: u32 = undefined;
var x725: u1 = undefined;
addcarryxU32(&x724, &x725, x723, x700, cast(u32, 0x0));
var x726: u32 = undefined;
var x727: u1 = undefined;
addcarryxU32(&x726, &x727, x725, x702, cast(u32, 0x0));
var x728: u32 = undefined;
var x729: u1 = undefined;
addcarryxU32(&x728, &x729, x727, x704, cast(u32, 0x0));
var x730: u32 = undefined;
var x731: u32 = undefined;
mulxU32(&x730, &x731, x706, 0xffffffff);
var x732: u32 = undefined;
var x733: u32 = undefined;
mulxU32(&x732, &x733, x706, 0xffffffff);
var x734: u32 = undefined;
var x735: u32 = undefined;
mulxU32(&x734, &x735, x706, 0xffffffff);
var x736: u32 = undefined;
var x737: u32 = undefined;
mulxU32(&x736, &x737, x706, 0xffffffff);
var x738: u32 = undefined;
var x739: u32 = undefined;
mulxU32(&x738, &x739, x706, 0xffffffff);
var x740: u32 = undefined;
var x741: u32 = undefined;
mulxU32(&x740, &x741, x706, 0xffffffff);
var x742: u32 = undefined;
var x743: u32 = undefined;
mulxU32(&x742, &x743, x706, 0xffffffff);
var x744: u32 = undefined;
var x745: u32 = undefined;
mulxU32(&x744, &x745, x706, 0xfffffffe);
var x746: u32 = undefined;
var x747: u32 = undefined;
mulxU32(&x746, &x747, x706, 0xffffffff);
var x748: u32 = undefined;
var x749: u32 = undefined;
mulxU32(&x748, &x749, x706, 0xffffffff);
var x750: u32 = undefined;
var x751: u1 = undefined;
addcarryxU32(&x750, &x751, 0x0, x747, x744);
var x752: u32 = undefined;
var x753: u1 = undefined;
addcarryxU32(&x752, &x753, x751, x745, x742);
var x754: u32 = undefined;
var x755: u1 = undefined;
addcarryxU32(&x754, &x755, x753, x743, x740);
var x756: u32 = undefined;
var x757: u1 = undefined;
addcarryxU32(&x756, &x757, x755, x741, x738);
var x758: u32 = undefined;
var x759: u1 = undefined;
addcarryxU32(&x758, &x759, x757, x739, x736);
var x760: u32 = undefined;
var x761: u1 = undefined;
addcarryxU32(&x760, &x761, x759, x737, x734);
var x762: u32 = undefined;
var x763: u1 = undefined;
addcarryxU32(&x762, &x763, x761, x735, x732);
var x764: u32 = undefined;
var x765: u1 = undefined;
addcarryxU32(&x764, &x765, x763, x733, x730);
var x766: u32 = undefined;
var x767: u1 = undefined;
addcarryxU32(&x766, &x767, 0x0, x706, x748);
var x768: u32 = undefined;
var x769: u1 = undefined;
addcarryxU32(&x768, &x769, x767, x708, x749);
var x770: u32 = undefined;
var x771: u1 = undefined;
addcarryxU32(&x770, &x771, x769, x710, cast(u32, 0x0));
var x772: u32 = undefined;
var x773: u1 = undefined;
addcarryxU32(&x772, &x773, x771, x712, x746);
var x774: u32 = undefined;
var x775: u1 = undefined;
addcarryxU32(&x774, &x775, x773, x714, x750);
var x776: u32 = undefined;
var x777: u1 = undefined;
addcarryxU32(&x776, &x777, x775, x716, x752);
var x778: u32 = undefined;
var x779: u1 = undefined;
addcarryxU32(&x778, &x779, x777, x718, x754);
var x780: u32 = undefined;
var x781: u1 = undefined;
addcarryxU32(&x780, &x781, x779, x720, x756);
var x782: u32 = undefined;
var x783: u1 = undefined;
addcarryxU32(&x782, &x783, x781, x722, x758);
var x784: u32 = undefined;
var x785: u1 = undefined;
addcarryxU32(&x784, &x785, x783, x724, x760);
var x786: u32 = undefined;
var x787: u1 = undefined;
addcarryxU32(&x786, &x787, x785, x726, x762);
var x788: u32 = undefined;
var x789: u1 = undefined;
addcarryxU32(&x788, &x789, x787, x728, x764);
var x790: u32 = undefined;
var x791: u1 = undefined;
addcarryxU32(&x790, &x791, x789, (cast(u32, x729) + cast(u32, x705)), (cast(u32, x765) + x731));
var x792: u32 = undefined;
var x793: u1 = undefined;
addcarryxU32(&x792, &x793, 0x0, x768, (arg1[10]));
var x794: u32 = undefined;
var x795: u1 = undefined;
addcarryxU32(&x794, &x795, x793, x770, cast(u32, 0x0));
var x796: u32 = undefined;
var x797: u1 = undefined;
addcarryxU32(&x796, &x797, x795, x772, cast(u32, 0x0));
var x798: u32 = undefined;
var x799: u1 = undefined;
addcarryxU32(&x798, &x799, x797, x774, cast(u32, 0x0));
var x800: u32 = undefined;
var x801: u1 = undefined;
addcarryxU32(&x800, &x801, x799, x776, cast(u32, 0x0));
var x802: u32 = undefined;
var x803: u1 = undefined;
addcarryxU32(&x802, &x803, x801, x778, cast(u32, 0x0));
var x804: u32 = undefined;
var x805: u1 = undefined;
addcarryxU32(&x804, &x805, x803, x780, cast(u32, 0x0));
var x806: u32 = undefined;
var x807: u1 = undefined;
addcarryxU32(&x806, &x807, x805, x782, cast(u32, 0x0));
var x808: u32 = undefined;
var x809: u1 = undefined;
addcarryxU32(&x808, &x809, x807, x784, cast(u32, 0x0));
var x810: u32 = undefined;
var x811: u1 = undefined;
addcarryxU32(&x810, &x811, x809, x786, cast(u32, 0x0));
var x812: u32 = undefined;
var x813: u1 = undefined;
addcarryxU32(&x812, &x813, x811, x788, cast(u32, 0x0));
var x814: u32 = undefined;
var x815: u1 = undefined;
addcarryxU32(&x814, &x815, x813, x790, cast(u32, 0x0));
var x816: u32 = undefined;
var x817: u32 = undefined;
mulxU32(&x816, &x817, x792, 0xffffffff);
var x818: u32 = undefined;
var x819: u32 = undefined;
mulxU32(&x818, &x819, x792, 0xffffffff);
var x820: u32 = undefined;
var x821: u32 = undefined;
mulxU32(&x820, &x821, x792, 0xffffffff);
var x822: u32 = undefined;
var x823: u32 = undefined;
mulxU32(&x822, &x823, x792, 0xffffffff);
var x824: u32 = undefined;
var x825: u32 = undefined;
mulxU32(&x824, &x825, x792, 0xffffffff);
var x826: u32 = undefined;
var x827: u32 = undefined;
mulxU32(&x826, &x827, x792, 0xffffffff);
var x828: u32 = undefined;
var x829: u32 = undefined;
mulxU32(&x828, &x829, x792, 0xffffffff);
var x830: u32 = undefined;
var x831: u32 = undefined;
mulxU32(&x830, &x831, x792, 0xfffffffe);
var x832: u32 = undefined;
var x833: u32 = undefined;
mulxU32(&x832, &x833, x792, 0xffffffff);
var x834: u32 = undefined;
var x835: u32 = undefined;
mulxU32(&x834, &x835, x792, 0xffffffff);
var x836: u32 = undefined;
var x837: u1 = undefined;
addcarryxU32(&x836, &x837, 0x0, x833, x830);
var x838: u32 = undefined;
var x839: u1 = undefined;
addcarryxU32(&x838, &x839, x837, x831, x828);
var x840: u32 = undefined;
var x841: u1 = undefined;
addcarryxU32(&x840, &x841, x839, x829, x826);
var x842: u32 = undefined;
var x843: u1 = undefined;
addcarryxU32(&x842, &x843, x841, x827, x824);
var x844: u32 = undefined;
var x845: u1 = undefined;
addcarryxU32(&x844, &x845, x843, x825, x822);
var x846: u32 = undefined;
var x847: u1 = undefined;
addcarryxU32(&x846, &x847, x845, x823, x820);
var x848: u32 = undefined;
var x849: u1 = undefined;
addcarryxU32(&x848, &x849, x847, x821, x818);
var x850: u32 = undefined;
var x851: u1 = undefined;
addcarryxU32(&x850, &x851, x849, x819, x816);
var x852: u32 = undefined;
var x853: u1 = undefined;
addcarryxU32(&x852, &x853, 0x0, x792, x834);
var x854: u32 = undefined;
var x855: u1 = undefined;
addcarryxU32(&x854, &x855, x853, x794, x835);
var x856: u32 = undefined;
var x857: u1 = undefined;
addcarryxU32(&x856, &x857, x855, x796, cast(u32, 0x0));
var x858: u32 = undefined;
var x859: u1 = undefined;
addcarryxU32(&x858, &x859, x857, x798, x832);
var x860: u32 = undefined;
var x861: u1 = undefined;
addcarryxU32(&x860, &x861, x859, x800, x836);
var x862: u32 = undefined;
var x863: u1 = undefined;
addcarryxU32(&x862, &x863, x861, x802, x838);
var x864: u32 = undefined;
var x865: u1 = undefined;
addcarryxU32(&x864, &x865, x863, x804, x840);
var x866: u32 = undefined;
var x867: u1 = undefined;
addcarryxU32(&x866, &x867, x865, x806, x842);
var x868: u32 = undefined;
var x869: u1 = undefined;
addcarryxU32(&x868, &x869, x867, x808, x844);
var x870: u32 = undefined;
var x871: u1 = undefined;
addcarryxU32(&x870, &x871, x869, x810, x846);
var x872: u32 = undefined;
var x873: u1 = undefined;
addcarryxU32(&x872, &x873, x871, x812, x848);
var x874: u32 = undefined;
var x875: u1 = undefined;
addcarryxU32(&x874, &x875, x873, x814, x850);
var x876: u32 = undefined;
var x877: u1 = undefined;
addcarryxU32(&x876, &x877, x875, (cast(u32, x815) + cast(u32, x791)), (cast(u32, x851) + x817));
var x878: u32 = undefined;
var x879: u1 = undefined;
addcarryxU32(&x878, &x879, 0x0, x854, (arg1[11]));
var x880: u32 = undefined;
var x881: u1 = undefined;
addcarryxU32(&x880, &x881, x879, x856, cast(u32, 0x0));
var x882: u32 = undefined;
var x883: u1 = undefined;
addcarryxU32(&x882, &x883, x881, x858, cast(u32, 0x0));
var x884: u32 = undefined;
var x885: u1 = undefined;
addcarryxU32(&x884, &x885, x883, x860, cast(u32, 0x0));
var x886: u32 = undefined;
var x887: u1 = undefined;
addcarryxU32(&x886, &x887, x885, x862, cast(u32, 0x0));
var x888: u32 = undefined;
var x889: u1 = undefined;
addcarryxU32(&x888, &x889, x887, x864, cast(u32, 0x0));
var x890: u32 = undefined;
var x891: u1 = undefined;
addcarryxU32(&x890, &x891, x889, x866, cast(u32, 0x0));
var x892: u32 = undefined;
var x893: u1 = undefined;
addcarryxU32(&x892, &x893, x891, x868, cast(u32, 0x0));
var x894: u32 = undefined;
var x895: u1 = undefined;
addcarryxU32(&x894, &x895, x893, x870, cast(u32, 0x0));
var x896: u32 = undefined;
var x897: u1 = undefined;
addcarryxU32(&x896, &x897, x895, x872, cast(u32, 0x0));
var x898: u32 = undefined;
var x899: u1 = undefined;
addcarryxU32(&x898, &x899, x897, x874, cast(u32, 0x0));
var x900: u32 = undefined;
var x901: u1 = undefined;
addcarryxU32(&x900, &x901, x899, x876, cast(u32, 0x0));
var x902: u32 = undefined;
var x903: u32 = undefined;
mulxU32(&x902, &x903, x878, 0xffffffff);
var x904: u32 = undefined;
var x905: u32 = undefined;
mulxU32(&x904, &x905, x878, 0xffffffff);
var x906: u32 = undefined;
var x907: u32 = undefined;
mulxU32(&x906, &x907, x878, 0xffffffff);
var x908: u32 = undefined;
var x909: u32 = undefined;
mulxU32(&x908, &x909, x878, 0xffffffff);
var x910: u32 = undefined;
var x911: u32 = undefined;
mulxU32(&x910, &x911, x878, 0xffffffff);
var x912: u32 = undefined;
var x913: u32 = undefined;
mulxU32(&x912, &x913, x878, 0xffffffff);
var x914: u32 = undefined;
var x915: u32 = undefined;
mulxU32(&x914, &x915, x878, 0xffffffff);
var x916: u32 = undefined;
var x917: u32 = undefined;
mulxU32(&x916, &x917, x878, 0xfffffffe);
var x918: u32 = undefined;
var x919: u32 = undefined;
mulxU32(&x918, &x919, x878, 0xffffffff);
var x920: u32 = undefined;
var x921: u32 = undefined;
mulxU32(&x920, &x921, x878, 0xffffffff);
var x922: u32 = undefined;
var x923: u1 = undefined;
addcarryxU32(&x922, &x923, 0x0, x919, x916);
var x924: u32 = undefined;
var x925: u1 = undefined;
addcarryxU32(&x924, &x925, x923, x917, x914);
var x926: u32 = undefined;
var x927: u1 = undefined;
addcarryxU32(&x926, &x927, x925, x915, x912);
var x928: u32 = undefined;
var x929: u1 = undefined;
addcarryxU32(&x928, &x929, x927, x913, x910);
var x930: u32 = undefined;
var x931: u1 = undefined;
addcarryxU32(&x930, &x931, x929, x911, x908);
var x932: u32 = undefined;
var x933: u1 = undefined;
addcarryxU32(&x932, &x933, x931, x909, x906);
var x934: u32 = undefined;
var x935: u1 = undefined;
addcarryxU32(&x934, &x935, x933, x907, x904);
var x936: u32 = undefined;
var x937: u1 = undefined;
addcarryxU32(&x936, &x937, x935, x905, x902);
var x938: u32 = undefined;
var x939: u1 = undefined;
addcarryxU32(&x938, &x939, 0x0, x878, x920);
var x940: u32 = undefined;
var x941: u1 = undefined;
addcarryxU32(&x940, &x941, x939, x880, x921);
var x942: u32 = undefined;
var x943: u1 = undefined;
addcarryxU32(&x942, &x943, x941, x882, cast(u32, 0x0));
var x944: u32 = undefined;
var x945: u1 = undefined;
addcarryxU32(&x944, &x945, x943, x884, x918);
var x946: u32 = undefined;
var x947: u1 = undefined;
addcarryxU32(&x946, &x947, x945, x886, x922);
var x948: u32 = undefined;
var x949: u1 = undefined;
addcarryxU32(&x948, &x949, x947, x888, x924);
var x950: u32 = undefined;
var x951: u1 = undefined;
addcarryxU32(&x950, &x951, x949, x890, x926);
var x952: u32 = undefined;
var x953: u1 = undefined;
addcarryxU32(&x952, &x953, x951, x892, x928);
var x954: u32 = undefined;
var x955: u1 = undefined;
addcarryxU32(&x954, &x955, x953, x894, x930);
var x956: u32 = undefined;
var x957: u1 = undefined;
addcarryxU32(&x956, &x957, x955, x896, x932);
var x958: u32 = undefined;
var x959: u1 = undefined;
addcarryxU32(&x958, &x959, x957, x898, x934);
var x960: u32 = undefined;
var x961: u1 = undefined;
addcarryxU32(&x960, &x961, x959, x900, x936);
var x962: u32 = undefined;
var x963: u1 = undefined;
addcarryxU32(&x962, &x963, x961, (cast(u32, x901) + cast(u32, x877)), (cast(u32, x937) + x903));
var x964: u32 = undefined;
var x965: u1 = undefined;
subborrowxU32(&x964, &x965, 0x0, x940, 0xffffffff);
var x966: u32 = undefined;
var x967: u1 = undefined;
subborrowxU32(&x966, &x967, x965, x942, cast(u32, 0x0));
var x968: u32 = undefined;
var x969: u1 = undefined;
subborrowxU32(&x968, &x969, x967, x944, cast(u32, 0x0));
var x970: u32 = undefined;
var x971: u1 = undefined;
subborrowxU32(&x970, &x971, x969, x946, 0xffffffff);
var x972: u32 = undefined;
var x973: u1 = undefined;
subborrowxU32(&x972, &x973, x971, x948, 0xfffffffe);
var x974: u32 = undefined;
var x975: u1 = undefined;
subborrowxU32(&x974, &x975, x973, x950, 0xffffffff);
var x976: u32 = undefined;
var x977: u1 = undefined;
subborrowxU32(&x976, &x977, x975, x952, 0xffffffff);
var x978: u32 = undefined;
var x979: u1 = undefined;
subborrowxU32(&x978, &x979, x977, x954, 0xffffffff);
var x980: u32 = undefined;
var x981: u1 = undefined;
subborrowxU32(&x980, &x981, x979, x956, 0xffffffff);
var x982: u32 = undefined;
var x983: u1 = undefined;
subborrowxU32(&x982, &x983, x981, x958, 0xffffffff);
var x984: u32 = undefined;
var x985: u1 = undefined;
subborrowxU32(&x984, &x985, x983, x960, 0xffffffff);
var x986: u32 = undefined;
var x987: u1 = undefined;
subborrowxU32(&x986, &x987, x985, x962, 0xffffffff);
var x988: u32 = undefined;
var x989: u1 = undefined;
subborrowxU32(&x988, &x989, x987, cast(u32, x963), cast(u32, 0x0));
var x990: u32 = undefined;
cmovznzU32(&x990, x989, x964, x940);
var x991: u32 = undefined;
cmovznzU32(&x991, x989, x966, x942);
var x992: u32 = undefined;
cmovznzU32(&x992, x989, x968, x944);
var x993: u32 = undefined;
cmovznzU32(&x993, x989, x970, x946);
var x994: u32 = undefined;
cmovznzU32(&x994, x989, x972, x948);
var x995: u32 = undefined;
cmovznzU32(&x995, x989, x974, x950);
var x996: u32 = undefined;
cmovznzU32(&x996, x989, x976, x952);
var x997: u32 = undefined;
cmovznzU32(&x997, x989, x978, x954);
var x998: u32 = undefined;
cmovznzU32(&x998, x989, x980, x956);
var x999: u32 = undefined;
cmovznzU32(&x999, x989, x982, x958);
var x1000: u32 = undefined;
cmovznzU32(&x1000, x989, x984, x960);
var x1001: u32 = undefined;
cmovznzU32(&x1001, x989, x986, x962);
out1[0] = x990;
out1[1] = x991;
out1[2] = x992;
out1[3] = x993;
out1[4] = x994;
out1[5] = x995;
out1[6] = x996;
out1[7] = x997;
out1[8] = x998;
out1[9] = x999;
out1[10] = x1000;
out1[11] = x1001;
}
/// The function toMontgomery translates a field element into the Montgomery domain.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// eval (from_montgomery out1) mod m = eval arg1 mod m
/// 0 ≤ eval out1 < m
///
pub fn toMontgomery(out1: *MontgomeryDomainFieldElement, arg1: NonMontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[1]);
const x2 = (arg1[2]);
const x3 = (arg1[3]);
const x4 = (arg1[4]);
const x5 = (arg1[5]);
const x6 = (arg1[6]);
const x7 = (arg1[7]);
const x8 = (arg1[8]);
const x9 = (arg1[9]);
const x10 = (arg1[10]);
const x11 = (arg1[11]);
const x12 = (arg1[0]);
var x13: u32 = undefined;
var x14: u32 = undefined;
mulxU32(&x13, &x14, x12, 0x2);
var x15: u32 = undefined;
var x16: u32 = undefined;
mulxU32(&x15, &x16, x12, 0xfffffffe);
var x17: u32 = undefined;
var x18: u32 = undefined;
mulxU32(&x17, &x18, x12, 0x2);
var x19: u32 = undefined;
var x20: u32 = undefined;
mulxU32(&x19, &x20, x12, 0xfffffffe);
var x21: u32 = undefined;
var x22: u1 = undefined;
addcarryxU32(&x21, &x22, 0x0, cast(u32, cast(u1, x14)), x12);
var x23: u32 = undefined;
var x24: u32 = undefined;
mulxU32(&x23, &x24, x12, 0xffffffff);
var x25: u32 = undefined;
var x26: u32 = undefined;
mulxU32(&x25, &x26, x12, 0xffffffff);
var x27: u32 = undefined;
var x28: u32 = undefined;
mulxU32(&x27, &x28, x12, 0xffffffff);
var x29: u32 = undefined;
var x30: u32 = undefined;
mulxU32(&x29, &x30, x12, 0xffffffff);
var x31: u32 = undefined;
var x32: u32 = undefined;
mulxU32(&x31, &x32, x12, 0xffffffff);
var x33: u32 = undefined;
var x34: u32 = undefined;
mulxU32(&x33, &x34, x12, 0xffffffff);
var x35: u32 = undefined;
var x36: u32 = undefined;
mulxU32(&x35, &x36, x12, 0xffffffff);
var x37: u32 = undefined;
var x38: u32 = undefined;
mulxU32(&x37, &x38, x12, 0xfffffffe);
var x39: u32 = undefined;
var x40: u32 = undefined;
mulxU32(&x39, &x40, x12, 0xffffffff);
var x41: u32 = undefined;
var x42: u32 = undefined;
mulxU32(&x41, &x42, x12, 0xffffffff);
var x43: u32 = undefined;
var x44: u1 = undefined;
addcarryxU32(&x43, &x44, 0x0, x40, x37);
var x45: u32 = undefined;
var x46: u1 = undefined;
addcarryxU32(&x45, &x46, x44, x38, x35);
var x47: u32 = undefined;
var x48: u1 = undefined;
addcarryxU32(&x47, &x48, x46, x36, x33);
var x49: u32 = undefined;
var x50: u1 = undefined;
addcarryxU32(&x49, &x50, x48, x34, x31);
var x51: u32 = undefined;
var x52: u1 = undefined;
addcarryxU32(&x51, &x52, x50, x32, x29);
var x53: u32 = undefined;
var x54: u1 = undefined;
addcarryxU32(&x53, &x54, x52, x30, x27);
var x55: u32 = undefined;
var x56: u1 = undefined;
addcarryxU32(&x55, &x56, x54, x28, x25);
var x57: u32 = undefined;
var x58: u1 = undefined;
addcarryxU32(&x57, &x58, x56, x26, x23);
var x59: u32 = undefined;
var x60: u1 = undefined;
addcarryxU32(&x59, &x60, 0x0, x12, x41);
var x61: u32 = undefined;
var x62: u1 = undefined;
addcarryxU32(&x61, &x62, x60, x19, x42);
var x63: u32 = undefined;
var x64: u1 = undefined;
addcarryxU32(&x63, &x64, 0x0, x17, x39);
var x65: u32 = undefined;
var x66: u1 = undefined;
addcarryxU32(&x65, &x66, x64, cast(u32, cast(u1, x18)), x43);
var x67: u32 = undefined;
var x68: u1 = undefined;
addcarryxU32(&x67, &x68, x66, x15, x45);
var x69: u32 = undefined;
var x70: u1 = undefined;
addcarryxU32(&x69, &x70, x68, x16, x47);
var x71: u32 = undefined;
var x72: u1 = undefined;
addcarryxU32(&x71, &x72, x70, x13, x49);
var x73: u32 = undefined;
var x74: u1 = undefined;
addcarryxU32(&x73, &x74, x72, x21, x51);
var x75: u32 = undefined;
var x76: u1 = undefined;
addcarryxU32(&x75, &x76, x74, cast(u32, x22), x53);
var x77: u32 = undefined;
var x78: u1 = undefined;
addcarryxU32(&x77, &x78, x76, cast(u32, 0x0), x55);
var x79: u32 = undefined;
var x80: u1 = undefined;
addcarryxU32(&x79, &x80, x78, cast(u32, 0x0), x57);
var x81: u32 = undefined;
var x82: u1 = undefined;
addcarryxU32(&x81, &x82, x80, cast(u32, 0x0), (cast(u32, x58) + x24));
var x83: u32 = undefined;
var x84: u32 = undefined;
mulxU32(&x83, &x84, x1, 0x2);
var x85: u32 = undefined;
var x86: u32 = undefined;
mulxU32(&x85, &x86, x1, 0xfffffffe);
var x87: u32 = undefined;
var x88: u32 = undefined;
mulxU32(&x87, &x88, x1, 0x2);
var x89: u32 = undefined;
var x90: u32 = undefined;
mulxU32(&x89, &x90, x1, 0xfffffffe);
var x91: u32 = undefined;
var x92: u1 = undefined;
addcarryxU32(&x91, &x92, 0x0, cast(u32, cast(u1, x84)), x1);
var x93: u32 = undefined;
var x94: u1 = undefined;
addcarryxU32(&x93, &x94, 0x0, x61, x1);
var x95: u32 = undefined;
var x96: u1 = undefined;
addcarryxU32(&x95, &x96, x94, (cast(u32, x62) + x20), x89);
var x97: u32 = undefined;
var x98: u1 = undefined;
addcarryxU32(&x97, &x98, x96, x63, x90);
var x99: u32 = undefined;
var x100: u1 = undefined;
addcarryxU32(&x99, &x100, x98, x65, x87);
var x101: u32 = undefined;
var x102: u1 = undefined;
addcarryxU32(&x101, &x102, x100, x67, cast(u32, cast(u1, x88)));
var x103: u32 = undefined;
var x104: u1 = undefined;
addcarryxU32(&x103, &x104, x102, x69, x85);
var x105: u32 = undefined;
var x106: u1 = undefined;
addcarryxU32(&x105, &x106, x104, x71, x86);
var x107: u32 = undefined;
var x108: u1 = undefined;
addcarryxU32(&x107, &x108, x106, x73, x83);
var x109: u32 = undefined;
var x110: u1 = undefined;
addcarryxU32(&x109, &x110, x108, x75, x91);
var x111: u32 = undefined;
var x112: u1 = undefined;
addcarryxU32(&x111, &x112, x110, x77, cast(u32, x92));
var x113: u32 = undefined;
var x114: u1 = undefined;
addcarryxU32(&x113, &x114, x112, x79, cast(u32, 0x0));
var x115: u32 = undefined;
var x116: u1 = undefined;
addcarryxU32(&x115, &x116, x114, x81, cast(u32, 0x0));
var x117: u32 = undefined;
var x118: u32 = undefined;
mulxU32(&x117, &x118, x93, 0xffffffff);
var x119: u32 = undefined;
var x120: u32 = undefined;
mulxU32(&x119, &x120, x93, 0xffffffff);
var x121: u32 = undefined;
var x122: u32 = undefined;
mulxU32(&x121, &x122, x93, 0xffffffff);
var x123: u32 = undefined;
var x124: u32 = undefined;
mulxU32(&x123, &x124, x93, 0xffffffff);
var x125: u32 = undefined;
var x126: u32 = undefined;
mulxU32(&x125, &x126, x93, 0xffffffff);
var x127: u32 = undefined;
var x128: u32 = undefined;
mulxU32(&x127, &x128, x93, 0xffffffff);
var x129: u32 = undefined;
var x130: u32 = undefined;
mulxU32(&x129, &x130, x93, 0xffffffff);
var x131: u32 = undefined;
var x132: u32 = undefined;
mulxU32(&x131, &x132, x93, 0xfffffffe);
var x133: u32 = undefined;
var x134: u32 = undefined;
mulxU32(&x133, &x134, x93, 0xffffffff);
var x135: u32 = undefined;
var x136: u32 = undefined;
mulxU32(&x135, &x136, x93, 0xffffffff);
var x137: u32 = undefined;
var x138: u1 = undefined;
addcarryxU32(&x137, &x138, 0x0, x134, x131);
var x139: u32 = undefined;
var x140: u1 = undefined;
addcarryxU32(&x139, &x140, x138, x132, x129);
var x141: u32 = undefined;
var x142: u1 = undefined;
addcarryxU32(&x141, &x142, x140, x130, x127);
var x143: u32 = undefined;
var x144: u1 = undefined;
addcarryxU32(&x143, &x144, x142, x128, x125);
var x145: u32 = undefined;
var x146: u1 = undefined;
addcarryxU32(&x145, &x146, x144, x126, x123);
var x147: u32 = undefined;
var x148: u1 = undefined;
addcarryxU32(&x147, &x148, x146, x124, x121);
var x149: u32 = undefined;
var x150: u1 = undefined;
addcarryxU32(&x149, &x150, x148, x122, x119);
var x151: u32 = undefined;
var x152: u1 = undefined;
addcarryxU32(&x151, &x152, x150, x120, x117);
var x153: u32 = undefined;
var x154: u1 = undefined;
addcarryxU32(&x153, &x154, 0x0, x93, x135);
var x155: u32 = undefined;
var x156: u1 = undefined;
addcarryxU32(&x155, &x156, x154, x95, x136);
var x157: u32 = undefined;
var x158: u1 = undefined;
addcarryxU32(&x157, &x158, x156, x97, cast(u32, 0x0));
var x159: u32 = undefined;
var x160: u1 = undefined;
addcarryxU32(&x159, &x160, x158, x99, x133);
var x161: u32 = undefined;
var x162: u1 = undefined;
addcarryxU32(&x161, &x162, x160, x101, x137);
var x163: u32 = undefined;
var x164: u1 = undefined;
addcarryxU32(&x163, &x164, x162, x103, x139);
var x165: u32 = undefined;
var x166: u1 = undefined;
addcarryxU32(&x165, &x166, x164, x105, x141);
var x167: u32 = undefined;
var x168: u1 = undefined;
addcarryxU32(&x167, &x168, x166, x107, x143);
var x169: u32 = undefined;
var x170: u1 = undefined;
addcarryxU32(&x169, &x170, x168, x109, x145);
var x171: u32 = undefined;
var x172: u1 = undefined;
addcarryxU32(&x171, &x172, x170, x111, x147);
var x173: u32 = undefined;
var x174: u1 = undefined;
addcarryxU32(&x173, &x174, x172, x113, x149);
var x175: u32 = undefined;
var x176: u1 = undefined;
addcarryxU32(&x175, &x176, x174, x115, x151);
var x177: u32 = undefined;
var x178: u1 = undefined;
addcarryxU32(&x177, &x178, x176, (cast(u32, x116) + cast(u32, x82)), (cast(u32, x152) + x118));
var x179: u32 = undefined;
var x180: u32 = undefined;
mulxU32(&x179, &x180, x2, 0x2);
var x181: u32 = undefined;
var x182: u32 = undefined;
mulxU32(&x181, &x182, x2, 0xfffffffe);
var x183: u32 = undefined;
var x184: u32 = undefined;
mulxU32(&x183, &x184, x2, 0x2);
var x185: u32 = undefined;
var x186: u32 = undefined;
mulxU32(&x185, &x186, x2, 0xfffffffe);
var x187: u32 = undefined;
var x188: u1 = undefined;
addcarryxU32(&x187, &x188, 0x0, cast(u32, cast(u1, x180)), x2);
var x189: u32 = undefined;
var x190: u1 = undefined;
addcarryxU32(&x189, &x190, 0x0, x155, x2);
var x191: u32 = undefined;
var x192: u1 = undefined;
addcarryxU32(&x191, &x192, x190, x157, x185);
var x193: u32 = undefined;
var x194: u1 = undefined;
addcarryxU32(&x193, &x194, x192, x159, x186);
var x195: u32 = undefined;
var x196: u1 = undefined;
addcarryxU32(&x195, &x196, x194, x161, x183);
var x197: u32 = undefined;
var x198: u1 = undefined;
addcarryxU32(&x197, &x198, x196, x163, cast(u32, cast(u1, x184)));
var x199: u32 = undefined;
var x200: u1 = undefined;
addcarryxU32(&x199, &x200, x198, x165, x181);
var x201: u32 = undefined;
var x202: u1 = undefined;
addcarryxU32(&x201, &x202, x200, x167, x182);
var x203: u32 = undefined;
var x204: u1 = undefined;
addcarryxU32(&x203, &x204, x202, x169, x179);
var x205: u32 = undefined;
var x206: u1 = undefined;
addcarryxU32(&x205, &x206, x204, x171, x187);
var x207: u32 = undefined;
var x208: u1 = undefined;
addcarryxU32(&x207, &x208, x206, x173, cast(u32, x188));
var x209: u32 = undefined;
var x210: u1 = undefined;
addcarryxU32(&x209, &x210, x208, x175, cast(u32, 0x0));
var x211: u32 = undefined;
var x212: u1 = undefined;
addcarryxU32(&x211, &x212, x210, x177, cast(u32, 0x0));
var x213: u32 = undefined;
var x214: u32 = undefined;
mulxU32(&x213, &x214, x189, 0xffffffff);
var x215: u32 = undefined;
var x216: u32 = undefined;
mulxU32(&x215, &x216, x189, 0xffffffff);
var x217: u32 = undefined;
var x218: u32 = undefined;
mulxU32(&x217, &x218, x189, 0xffffffff);
var x219: u32 = undefined;
var x220: u32 = undefined;
mulxU32(&x219, &x220, x189, 0xffffffff);
var x221: u32 = undefined;
var x222: u32 = undefined;
mulxU32(&x221, &x222, x189, 0xffffffff);
var x223: u32 = undefined;
var x224: u32 = undefined;
mulxU32(&x223, &x224, x189, 0xffffffff);
var x225: u32 = undefined;
var x226: u32 = undefined;
mulxU32(&x225, &x226, x189, 0xffffffff);
var x227: u32 = undefined;
var x228: u32 = undefined;
mulxU32(&x227, &x228, x189, 0xfffffffe);
var x229: u32 = undefined;
var x230: u32 = undefined;
mulxU32(&x229, &x230, x189, 0xffffffff);
var x231: u32 = undefined;
var x232: u32 = undefined;
mulxU32(&x231, &x232, x189, 0xffffffff);
var x233: u32 = undefined;
var x234: u1 = undefined;
addcarryxU32(&x233, &x234, 0x0, x230, x227);
var x235: u32 = undefined;
var x236: u1 = undefined;
addcarryxU32(&x235, &x236, x234, x228, x225);
var x237: u32 = undefined;
var x238: u1 = undefined;
addcarryxU32(&x237, &x238, x236, x226, x223);
var x239: u32 = undefined;
var x240: u1 = undefined;
addcarryxU32(&x239, &x240, x238, x224, x221);
var x241: u32 = undefined;
var x242: u1 = undefined;
addcarryxU32(&x241, &x242, x240, x222, x219);
var x243: u32 = undefined;
var x244: u1 = undefined;
addcarryxU32(&x243, &x244, x242, x220, x217);
var x245: u32 = undefined;
var x246: u1 = undefined;
addcarryxU32(&x245, &x246, x244, x218, x215);
var x247: u32 = undefined;
var x248: u1 = undefined;
addcarryxU32(&x247, &x248, x246, x216, x213);
var x249: u32 = undefined;
var x250: u1 = undefined;
addcarryxU32(&x249, &x250, 0x0, x189, x231);
var x251: u32 = undefined;
var x252: u1 = undefined;
addcarryxU32(&x251, &x252, x250, x191, x232);
var x253: u32 = undefined;
var x254: u1 = undefined;
addcarryxU32(&x253, &x254, x252, x193, cast(u32, 0x0));
var x255: u32 = undefined;
var x256: u1 = undefined;
addcarryxU32(&x255, &x256, x254, x195, x229);
var x257: u32 = undefined;
var x258: u1 = undefined;
addcarryxU32(&x257, &x258, x256, x197, x233);
var x259: u32 = undefined;
var x260: u1 = undefined;
addcarryxU32(&x259, &x260, x258, x199, x235);
var x261: u32 = undefined;
var x262: u1 = undefined;
addcarryxU32(&x261, &x262, x260, x201, x237);
var x263: u32 = undefined;
var x264: u1 = undefined;
addcarryxU32(&x263, &x264, x262, x203, x239);
var x265: u32 = undefined;
var x266: u1 = undefined;
addcarryxU32(&x265, &x266, x264, x205, x241);
var x267: u32 = undefined;
var x268: u1 = undefined;
addcarryxU32(&x267, &x268, x266, x207, x243);
var x269: u32 = undefined;
var x270: u1 = undefined;
addcarryxU32(&x269, &x270, x268, x209, x245);
var x271: u32 = undefined;
var x272: u1 = undefined;
addcarryxU32(&x271, &x272, x270, x211, x247);
var x273: u32 = undefined;
var x274: u1 = undefined;
addcarryxU32(&x273, &x274, x272, (cast(u32, x212) + cast(u32, x178)), (cast(u32, x248) + x214));
var x275: u32 = undefined;
var x276: u32 = undefined;
mulxU32(&x275, &x276, x3, 0x2);
var x277: u32 = undefined;
var x278: u32 = undefined;
mulxU32(&x277, &x278, x3, 0xfffffffe);
var x279: u32 = undefined;
var x280: u32 = undefined;
mulxU32(&x279, &x280, x3, 0x2);
var x281: u32 = undefined;
var x282: u32 = undefined;
mulxU32(&x281, &x282, x3, 0xfffffffe);
var x283: u32 = undefined;
var x284: u1 = undefined;
addcarryxU32(&x283, &x284, 0x0, cast(u32, cast(u1, x276)), x3);
var x285: u32 = undefined;
var x286: u1 = undefined;
addcarryxU32(&x285, &x286, 0x0, x251, x3);
var x287: u32 = undefined;
var x288: u1 = undefined;
addcarryxU32(&x287, &x288, x286, x253, x281);
var x289: u32 = undefined;
var x290: u1 = undefined;
addcarryxU32(&x289, &x290, x288, x255, x282);
var x291: u32 = undefined;
var x292: u1 = undefined;
addcarryxU32(&x291, &x292, x290, x257, x279);
var x293: u32 = undefined;
var x294: u1 = undefined;
addcarryxU32(&x293, &x294, x292, x259, cast(u32, cast(u1, x280)));
var x295: u32 = undefined;
var x296: u1 = undefined;
addcarryxU32(&x295, &x296, x294, x261, x277);
var x297: u32 = undefined;
var x298: u1 = undefined;
addcarryxU32(&x297, &x298, x296, x263, x278);
var x299: u32 = undefined;
var x300: u1 = undefined;
addcarryxU32(&x299, &x300, x298, x265, x275);
var x301: u32 = undefined;
var x302: u1 = undefined;
addcarryxU32(&x301, &x302, x300, x267, x283);
var x303: u32 = undefined;
var x304: u1 = undefined;
addcarryxU32(&x303, &x304, x302, x269, cast(u32, x284));
var x305: u32 = undefined;
var x306: u1 = undefined;
addcarryxU32(&x305, &x306, x304, x271, cast(u32, 0x0));
var x307: u32 = undefined;
var x308: u1 = undefined;
addcarryxU32(&x307, &x308, x306, x273, cast(u32, 0x0));
var x309: u32 = undefined;
var x310: u32 = undefined;
mulxU32(&x309, &x310, x285, 0xffffffff);
var x311: u32 = undefined;
var x312: u32 = undefined;
mulxU32(&x311, &x312, x285, 0xffffffff);
var x313: u32 = undefined;
var x314: u32 = undefined;
mulxU32(&x313, &x314, x285, 0xffffffff);
var x315: u32 = undefined;
var x316: u32 = undefined;
mulxU32(&x315, &x316, x285, 0xffffffff);
var x317: u32 = undefined;
var x318: u32 = undefined;
mulxU32(&x317, &x318, x285, 0xffffffff);
var x319: u32 = undefined;
var x320: u32 = undefined;
mulxU32(&x319, &x320, x285, 0xffffffff);
var x321: u32 = undefined;
var x322: u32 = undefined;
mulxU32(&x321, &x322, x285, 0xffffffff);
var x323: u32 = undefined;
var x324: u32 = undefined;
mulxU32(&x323, &x324, x285, 0xfffffffe);
var x325: u32 = undefined;
var x326: u32 = undefined;
mulxU32(&x325, &x326, x285, 0xffffffff);
var x327: u32 = undefined;
var x328: u32 = undefined;
mulxU32(&x327, &x328, x285, 0xffffffff);
var x329: u32 = undefined;
var x330: u1 = undefined;
addcarryxU32(&x329, &x330, 0x0, x326, x323);
var x331: u32 = undefined;
var x332: u1 = undefined;
addcarryxU32(&x331, &x332, x330, x324, x321);
var x333: u32 = undefined;
var x334: u1 = undefined;
addcarryxU32(&x333, &x334, x332, x322, x319);
var x335: u32 = undefined;
var x336: u1 = undefined;
addcarryxU32(&x335, &x336, x334, x320, x317);
var x337: u32 = undefined;
var x338: u1 = undefined;
addcarryxU32(&x337, &x338, x336, x318, x315);
var x339: u32 = undefined;
var x340: u1 = undefined;
addcarryxU32(&x339, &x340, x338, x316, x313);
var x341: u32 = undefined;
var x342: u1 = undefined;
addcarryxU32(&x341, &x342, x340, x314, x311);
var x343: u32 = undefined;
var x344: u1 = undefined;
addcarryxU32(&x343, &x344, x342, x312, x309);
var x345: u32 = undefined;
var x346: u1 = undefined;
addcarryxU32(&x345, &x346, 0x0, x285, x327);
var x347: u32 = undefined;
var x348: u1 = undefined;
addcarryxU32(&x347, &x348, x346, x287, x328);
var x349: u32 = undefined;
var x350: u1 = undefined;
addcarryxU32(&x349, &x350, x348, x289, cast(u32, 0x0));
var x351: u32 = undefined;
var x352: u1 = undefined;
addcarryxU32(&x351, &x352, x350, x291, x325);
var x353: u32 = undefined;
var x354: u1 = undefined;
addcarryxU32(&x353, &x354, x352, x293, x329);
var x355: u32 = undefined;
var x356: u1 = undefined;
addcarryxU32(&x355, &x356, x354, x295, x331);
var x357: u32 = undefined;
var x358: u1 = undefined;
addcarryxU32(&x357, &x358, x356, x297, x333);
var x359: u32 = undefined;
var x360: u1 = undefined;
addcarryxU32(&x359, &x360, x358, x299, x335);
var x361: u32 = undefined;
var x362: u1 = undefined;
addcarryxU32(&x361, &x362, x360, x301, x337);
var x363: u32 = undefined;
var x364: u1 = undefined;
addcarryxU32(&x363, &x364, x362, x303, x339);
var x365: u32 = undefined;
var x366: u1 = undefined;
addcarryxU32(&x365, &x366, x364, x305, x341);
var x367: u32 = undefined;
var x368: u1 = undefined;
addcarryxU32(&x367, &x368, x366, x307, x343);
var x369: u32 = undefined;
var x370: u1 = undefined;
addcarryxU32(&x369, &x370, x368, (cast(u32, x308) + cast(u32, x274)), (cast(u32, x344) + x310));
var x371: u32 = undefined;
var x372: u32 = undefined;
mulxU32(&x371, &x372, x4, 0x2);
var x373: u32 = undefined;
var x374: u32 = undefined;
mulxU32(&x373, &x374, x4, 0xfffffffe);
var x375: u32 = undefined;
var x376: u32 = undefined;
mulxU32(&x375, &x376, x4, 0x2);
var x377: u32 = undefined;
var x378: u32 = undefined;
mulxU32(&x377, &x378, x4, 0xfffffffe);
var x379: u32 = undefined;
var x380: u1 = undefined;
addcarryxU32(&x379, &x380, 0x0, cast(u32, cast(u1, x372)), x4);
var x381: u32 = undefined;
var x382: u1 = undefined;
addcarryxU32(&x381, &x382, 0x0, x347, x4);
var x383: u32 = undefined;
var x384: u1 = undefined;
addcarryxU32(&x383, &x384, x382, x349, x377);
var x385: u32 = undefined;
var x386: u1 = undefined;
addcarryxU32(&x385, &x386, x384, x351, x378);
var x387: u32 = undefined;
var x388: u1 = undefined;
addcarryxU32(&x387, &x388, x386, x353, x375);
var x389: u32 = undefined;
var x390: u1 = undefined;
addcarryxU32(&x389, &x390, x388, x355, cast(u32, cast(u1, x376)));
var x391: u32 = undefined;
var x392: u1 = undefined;
addcarryxU32(&x391, &x392, x390, x357, x373);
var x393: u32 = undefined;
var x394: u1 = undefined;
addcarryxU32(&x393, &x394, x392, x359, x374);
var x395: u32 = undefined;
var x396: u1 = undefined;
addcarryxU32(&x395, &x396, x394, x361, x371);
var x397: u32 = undefined;
var x398: u1 = undefined;
addcarryxU32(&x397, &x398, x396, x363, x379);
var x399: u32 = undefined;
var x400: u1 = undefined;
addcarryxU32(&x399, &x400, x398, x365, cast(u32, x380));
var x401: u32 = undefined;
var x402: u1 = undefined;
addcarryxU32(&x401, &x402, x400, x367, cast(u32, 0x0));
var x403: u32 = undefined;
var x404: u1 = undefined;
addcarryxU32(&x403, &x404, x402, x369, cast(u32, 0x0));
var x405: u32 = undefined;
var x406: u32 = undefined;
mulxU32(&x405, &x406, x381, 0xffffffff);
var x407: u32 = undefined;
var x408: u32 = undefined;
mulxU32(&x407, &x408, x381, 0xffffffff);
var x409: u32 = undefined;
var x410: u32 = undefined;
mulxU32(&x409, &x410, x381, 0xffffffff);
var x411: u32 = undefined;
var x412: u32 = undefined;
mulxU32(&x411, &x412, x381, 0xffffffff);
var x413: u32 = undefined;
var x414: u32 = undefined;
mulxU32(&x413, &x414, x381, 0xffffffff);
var x415: u32 = undefined;
var x416: u32 = undefined;
mulxU32(&x415, &x416, x381, 0xffffffff);
var x417: u32 = undefined;
var x418: u32 = undefined;
mulxU32(&x417, &x418, x381, 0xffffffff);
var x419: u32 = undefined;
var x420: u32 = undefined;
mulxU32(&x419, &x420, x381, 0xfffffffe);
var x421: u32 = undefined;
var x422: u32 = undefined;
mulxU32(&x421, &x422, x381, 0xffffffff);
var x423: u32 = undefined;
var x424: u32 = undefined;
mulxU32(&x423, &x424, x381, 0xffffffff);
var x425: u32 = undefined;
var x426: u1 = undefined;
addcarryxU32(&x425, &x426, 0x0, x422, x419);
var x427: u32 = undefined;
var x428: u1 = undefined;
addcarryxU32(&x427, &x428, x426, x420, x417);
var x429: u32 = undefined;
var x430: u1 = undefined;
addcarryxU32(&x429, &x430, x428, x418, x415);
var x431: u32 = undefined;
var x432: u1 = undefined;
addcarryxU32(&x431, &x432, x430, x416, x413);
var x433: u32 = undefined;
var x434: u1 = undefined;
addcarryxU32(&x433, &x434, x432, x414, x411);
var x435: u32 = undefined;
var x436: u1 = undefined;
addcarryxU32(&x435, &x436, x434, x412, x409);
var x437: u32 = undefined;
var x438: u1 = undefined;
addcarryxU32(&x437, &x438, x436, x410, x407);
var x439: u32 = undefined;
var x440: u1 = undefined;
addcarryxU32(&x439, &x440, x438, x408, x405);
var x441: u32 = undefined;
var x442: u1 = undefined;
addcarryxU32(&x441, &x442, 0x0, x381, x423);
var x443: u32 = undefined;
var x444: u1 = undefined;
addcarryxU32(&x443, &x444, x442, x383, x424);
var x445: u32 = undefined;
var x446: u1 = undefined;
addcarryxU32(&x445, &x446, x444, x385, cast(u32, 0x0));
var x447: u32 = undefined;
var x448: u1 = undefined;
addcarryxU32(&x447, &x448, x446, x387, x421);
var x449: u32 = undefined;
var x450: u1 = undefined;
addcarryxU32(&x449, &x450, x448, x389, x425);
var x451: u32 = undefined;
var x452: u1 = undefined;
addcarryxU32(&x451, &x452, x450, x391, x427);
var x453: u32 = undefined;
var x454: u1 = undefined;
addcarryxU32(&x453, &x454, x452, x393, x429);
var x455: u32 = undefined;
var x456: u1 = undefined;
addcarryxU32(&x455, &x456, x454, x395, x431);
var x457: u32 = undefined;
var x458: u1 = undefined;
addcarryxU32(&x457, &x458, x456, x397, x433);
var x459: u32 = undefined;
var x460: u1 = undefined;
addcarryxU32(&x459, &x460, x458, x399, x435);
var x461: u32 = undefined;
var x462: u1 = undefined;
addcarryxU32(&x461, &x462, x460, x401, x437);
var x463: u32 = undefined;
var x464: u1 = undefined;
addcarryxU32(&x463, &x464, x462, x403, x439);
var x465: u32 = undefined;
var x466: u1 = undefined;
addcarryxU32(&x465, &x466, x464, (cast(u32, x404) + cast(u32, x370)), (cast(u32, x440) + x406));
var x467: u32 = undefined;
var x468: u32 = undefined;
mulxU32(&x467, &x468, x5, 0x2);
var x469: u32 = undefined;
var x470: u32 = undefined;
mulxU32(&x469, &x470, x5, 0xfffffffe);
var x471: u32 = undefined;
var x472: u32 = undefined;
mulxU32(&x471, &x472, x5, 0x2);
var x473: u32 = undefined;
var x474: u32 = undefined;
mulxU32(&x473, &x474, x5, 0xfffffffe);
var x475: u32 = undefined;
var x476: u1 = undefined;
addcarryxU32(&x475, &x476, 0x0, cast(u32, cast(u1, x468)), x5);
var x477: u32 = undefined;
var x478: u1 = undefined;
addcarryxU32(&x477, &x478, 0x0, x443, x5);
var x479: u32 = undefined;
var x480: u1 = undefined;
addcarryxU32(&x479, &x480, x478, x445, x473);
var x481: u32 = undefined;
var x482: u1 = undefined;
addcarryxU32(&x481, &x482, x480, x447, x474);
var x483: u32 = undefined;
var x484: u1 = undefined;
addcarryxU32(&x483, &x484, x482, x449, x471);
var x485: u32 = undefined;
var x486: u1 = undefined;
addcarryxU32(&x485, &x486, x484, x451, cast(u32, cast(u1, x472)));
var x487: u32 = undefined;
var x488: u1 = undefined;
addcarryxU32(&x487, &x488, x486, x453, x469);
var x489: u32 = undefined;
var x490: u1 = undefined;
addcarryxU32(&x489, &x490, x488, x455, x470);
var x491: u32 = undefined;
var x492: u1 = undefined;
addcarryxU32(&x491, &x492, x490, x457, x467);
var x493: u32 = undefined;
var x494: u1 = undefined;
addcarryxU32(&x493, &x494, x492, x459, x475);
var x495: u32 = undefined;
var x496: u1 = undefined;
addcarryxU32(&x495, &x496, x494, x461, cast(u32, x476));
var x497: u32 = undefined;
var x498: u1 = undefined;
addcarryxU32(&x497, &x498, x496, x463, cast(u32, 0x0));
var x499: u32 = undefined;
var x500: u1 = undefined;
addcarryxU32(&x499, &x500, x498, x465, cast(u32, 0x0));
var x501: u32 = undefined;
var x502: u32 = undefined;
mulxU32(&x501, &x502, x477, 0xffffffff);
var x503: u32 = undefined;
var x504: u32 = undefined;
mulxU32(&x503, &x504, x477, 0xffffffff);
var x505: u32 = undefined;
var x506: u32 = undefined;
mulxU32(&x505, &x506, x477, 0xffffffff);
var x507: u32 = undefined;
var x508: u32 = undefined;
mulxU32(&x507, &x508, x477, 0xffffffff);
var x509: u32 = undefined;
var x510: u32 = undefined;
mulxU32(&x509, &x510, x477, 0xffffffff);
var x511: u32 = undefined;
var x512: u32 = undefined;
mulxU32(&x511, &x512, x477, 0xffffffff);
var x513: u32 = undefined;
var x514: u32 = undefined;
mulxU32(&x513, &x514, x477, 0xffffffff);
var x515: u32 = undefined;
var x516: u32 = undefined;
mulxU32(&x515, &x516, x477, 0xfffffffe);
var x517: u32 = undefined;
var x518: u32 = undefined;
mulxU32(&x517, &x518, x477, 0xffffffff);
var x519: u32 = undefined;
var x520: u32 = undefined;
mulxU32(&x519, &x520, x477, 0xffffffff);
var x521: u32 = undefined;
var x522: u1 = undefined;
addcarryxU32(&x521, &x522, 0x0, x518, x515);
var x523: u32 = undefined;
var x524: u1 = undefined;
addcarryxU32(&x523, &x524, x522, x516, x513);
var x525: u32 = undefined;
var x526: u1 = undefined;
addcarryxU32(&x525, &x526, x524, x514, x511);
var x527: u32 = undefined;
var x528: u1 = undefined;
addcarryxU32(&x527, &x528, x526, x512, x509);
var x529: u32 = undefined;
var x530: u1 = undefined;
addcarryxU32(&x529, &x530, x528, x510, x507);
var x531: u32 = undefined;
var x532: u1 = undefined;
addcarryxU32(&x531, &x532, x530, x508, x505);
var x533: u32 = undefined;
var x534: u1 = undefined;
addcarryxU32(&x533, &x534, x532, x506, x503);
var x535: u32 = undefined;
var x536: u1 = undefined;
addcarryxU32(&x535, &x536, x534, x504, x501);
var x537: u32 = undefined;
var x538: u1 = undefined;
addcarryxU32(&x537, &x538, 0x0, x477, x519);
var x539: u32 = undefined;
var x540: u1 = undefined;
addcarryxU32(&x539, &x540, x538, x479, x520);
var x541: u32 = undefined;
var x542: u1 = undefined;
addcarryxU32(&x541, &x542, x540, x481, cast(u32, 0x0));
var x543: u32 = undefined;
var x544: u1 = undefined;
addcarryxU32(&x543, &x544, x542, x483, x517);
var x545: u32 = undefined;
var x546: u1 = undefined;
addcarryxU32(&x545, &x546, x544, x485, x521);
var x547: u32 = undefined;
var x548: u1 = undefined;
addcarryxU32(&x547, &x548, x546, x487, x523);
var x549: u32 = undefined;
var x550: u1 = undefined;
addcarryxU32(&x549, &x550, x548, x489, x525);
var x551: u32 = undefined;
var x552: u1 = undefined;
addcarryxU32(&x551, &x552, x550, x491, x527);
var x553: u32 = undefined;
var x554: u1 = undefined;
addcarryxU32(&x553, &x554, x552, x493, x529);
var x555: u32 = undefined;
var x556: u1 = undefined;
addcarryxU32(&x555, &x556, x554, x495, x531);
var x557: u32 = undefined;
var x558: u1 = undefined;
addcarryxU32(&x557, &x558, x556, x497, x533);
var x559: u32 = undefined;
var x560: u1 = undefined;
addcarryxU32(&x559, &x560, x558, x499, x535);
var x561: u32 = undefined;
var x562: u1 = undefined;
addcarryxU32(&x561, &x562, x560, (cast(u32, x500) + cast(u32, x466)), (cast(u32, x536) + x502));
var x563: u32 = undefined;
var x564: u32 = undefined;
mulxU32(&x563, &x564, x6, 0x2);
var x565: u32 = undefined;
var x566: u32 = undefined;
mulxU32(&x565, &x566, x6, 0xfffffffe);
var x567: u32 = undefined;
var x568: u32 = undefined;
mulxU32(&x567, &x568, x6, 0x2);
var x569: u32 = undefined;
var x570: u32 = undefined;
mulxU32(&x569, &x570, x6, 0xfffffffe);
var x571: u32 = undefined;
var x572: u1 = undefined;
addcarryxU32(&x571, &x572, 0x0, cast(u32, cast(u1, x564)), x6);
var x573: u32 = undefined;
var x574: u1 = undefined;
addcarryxU32(&x573, &x574, 0x0, x539, x6);
var x575: u32 = undefined;
var x576: u1 = undefined;
addcarryxU32(&x575, &x576, x574, x541, x569);
var x577: u32 = undefined;
var x578: u1 = undefined;
addcarryxU32(&x577, &x578, x576, x543, x570);
var x579: u32 = undefined;
var x580: u1 = undefined;
addcarryxU32(&x579, &x580, x578, x545, x567);
var x581: u32 = undefined;
var x582: u1 = undefined;
addcarryxU32(&x581, &x582, x580, x547, cast(u32, cast(u1, x568)));
var x583: u32 = undefined;
var x584: u1 = undefined;
addcarryxU32(&x583, &x584, x582, x549, x565);
var x585: u32 = undefined;
var x586: u1 = undefined;
addcarryxU32(&x585, &x586, x584, x551, x566);
var x587: u32 = undefined;
var x588: u1 = undefined;
addcarryxU32(&x587, &x588, x586, x553, x563);
var x589: u32 = undefined;
var x590: u1 = undefined;
addcarryxU32(&x589, &x590, x588, x555, x571);
var x591: u32 = undefined;
var x592: u1 = undefined;
addcarryxU32(&x591, &x592, x590, x557, cast(u32, x572));
var x593: u32 = undefined;
var x594: u1 = undefined;
addcarryxU32(&x593, &x594, x592, x559, cast(u32, 0x0));
var x595: u32 = undefined;
var x596: u1 = undefined;
addcarryxU32(&x595, &x596, x594, x561, cast(u32, 0x0));
var x597: u32 = undefined;
var x598: u32 = undefined;
mulxU32(&x597, &x598, x573, 0xffffffff);
var x599: u32 = undefined;
var x600: u32 = undefined;
mulxU32(&x599, &x600, x573, 0xffffffff);
var x601: u32 = undefined;
var x602: u32 = undefined;
mulxU32(&x601, &x602, x573, 0xffffffff);
var x603: u32 = undefined;
var x604: u32 = undefined;
mulxU32(&x603, &x604, x573, 0xffffffff);
var x605: u32 = undefined;
var x606: u32 = undefined;
mulxU32(&x605, &x606, x573, 0xffffffff);
var x607: u32 = undefined;
var x608: u32 = undefined;
mulxU32(&x607, &x608, x573, 0xffffffff);
var x609: u32 = undefined;
var x610: u32 = undefined;
mulxU32(&x609, &x610, x573, 0xffffffff);
var x611: u32 = undefined;
var x612: u32 = undefined;
mulxU32(&x611, &x612, x573, 0xfffffffe);
var x613: u32 = undefined;
var x614: u32 = undefined;
mulxU32(&x613, &x614, x573, 0xffffffff);
var x615: u32 = undefined;
var x616: u32 = undefined;
mulxU32(&x615, &x616, x573, 0xffffffff);
var x617: u32 = undefined;
var x618: u1 = undefined;
addcarryxU32(&x617, &x618, 0x0, x614, x611);
var x619: u32 = undefined;
var x620: u1 = undefined;
addcarryxU32(&x619, &x620, x618, x612, x609);
var x621: u32 = undefined;
var x622: u1 = undefined;
addcarryxU32(&x621, &x622, x620, x610, x607);
var x623: u32 = undefined;
var x624: u1 = undefined;
addcarryxU32(&x623, &x624, x622, x608, x605);
var x625: u32 = undefined;
var x626: u1 = undefined;
addcarryxU32(&x625, &x626, x624, x606, x603);
var x627: u32 = undefined;
var x628: u1 = undefined;
addcarryxU32(&x627, &x628, x626, x604, x601);
var x629: u32 = undefined;
var x630: u1 = undefined;
addcarryxU32(&x629, &x630, x628, x602, x599);
var x631: u32 = undefined;
var x632: u1 = undefined;
addcarryxU32(&x631, &x632, x630, x600, x597);
var x633: u32 = undefined;
var x634: u1 = undefined;
addcarryxU32(&x633, &x634, 0x0, x573, x615);
var x635: u32 = undefined;
var x636: u1 = undefined;
addcarryxU32(&x635, &x636, x634, x575, x616);
var x637: u32 = undefined;
var x638: u1 = undefined;
addcarryxU32(&x637, &x638, x636, x577, cast(u32, 0x0));
var x639: u32 = undefined;
var x640: u1 = undefined;
addcarryxU32(&x639, &x640, x638, x579, x613);
var x641: u32 = undefined;
var x642: u1 = undefined;
addcarryxU32(&x641, &x642, x640, x581, x617);
var x643: u32 = undefined;
var x644: u1 = undefined;
addcarryxU32(&x643, &x644, x642, x583, x619);
var x645: u32 = undefined;
var x646: u1 = undefined;
addcarryxU32(&x645, &x646, x644, x585, x621);
var x647: u32 = undefined;
var x648: u1 = undefined;
addcarryxU32(&x647, &x648, x646, x587, x623);
var x649: u32 = undefined;
var x650: u1 = undefined;
addcarryxU32(&x649, &x650, x648, x589, x625);
var x651: u32 = undefined;
var x652: u1 = undefined;
addcarryxU32(&x651, &x652, x650, x591, x627);
var x653: u32 = undefined;
var x654: u1 = undefined;
addcarryxU32(&x653, &x654, x652, x593, x629);
var x655: u32 = undefined;
var x656: u1 = undefined;
addcarryxU32(&x655, &x656, x654, x595, x631);
var x657: u32 = undefined;
var x658: u1 = undefined;
addcarryxU32(&x657, &x658, x656, (cast(u32, x596) + cast(u32, x562)), (cast(u32, x632) + x598));
var x659: u32 = undefined;
var x660: u32 = undefined;
mulxU32(&x659, &x660, x7, 0x2);
var x661: u32 = undefined;
var x662: u32 = undefined;
mulxU32(&x661, &x662, x7, 0xfffffffe);
var x663: u32 = undefined;
var x664: u32 = undefined;
mulxU32(&x663, &x664, x7, 0x2);
var x665: u32 = undefined;
var x666: u32 = undefined;
mulxU32(&x665, &x666, x7, 0xfffffffe);
var x667: u32 = undefined;
var x668: u1 = undefined;
addcarryxU32(&x667, &x668, 0x0, cast(u32, cast(u1, x660)), x7);
var x669: u32 = undefined;
var x670: u1 = undefined;
addcarryxU32(&x669, &x670, 0x0, x635, x7);
var x671: u32 = undefined;
var x672: u1 = undefined;
addcarryxU32(&x671, &x672, x670, x637, x665);
var x673: u32 = undefined;
var x674: u1 = undefined;
addcarryxU32(&x673, &x674, x672, x639, x666);
var x675: u32 = undefined;
var x676: u1 = undefined;
addcarryxU32(&x675, &x676, x674, x641, x663);
var x677: u32 = undefined;
var x678: u1 = undefined;
addcarryxU32(&x677, &x678, x676, x643, cast(u32, cast(u1, x664)));
var x679: u32 = undefined;
var x680: u1 = undefined;
addcarryxU32(&x679, &x680, x678, x645, x661);
var x681: u32 = undefined;
var x682: u1 = undefined;
addcarryxU32(&x681, &x682, x680, x647, x662);
var x683: u32 = undefined;
var x684: u1 = undefined;
addcarryxU32(&x683, &x684, x682, x649, x659);
var x685: u32 = undefined;
var x686: u1 = undefined;
addcarryxU32(&x685, &x686, x684, x651, x667);
var x687: u32 = undefined;
var x688: u1 = undefined;
addcarryxU32(&x687, &x688, x686, x653, cast(u32, x668));
var x689: u32 = undefined;
var x690: u1 = undefined;
addcarryxU32(&x689, &x690, x688, x655, cast(u32, 0x0));
var x691: u32 = undefined;
var x692: u1 = undefined;
addcarryxU32(&x691, &x692, x690, x657, cast(u32, 0x0));
var x693: u32 = undefined;
var x694: u32 = undefined;
mulxU32(&x693, &x694, x669, 0xffffffff);
var x695: u32 = undefined;
var x696: u32 = undefined;
mulxU32(&x695, &x696, x669, 0xffffffff);
var x697: u32 = undefined;
var x698: u32 = undefined;
mulxU32(&x697, &x698, x669, 0xffffffff);
var x699: u32 = undefined;
var x700: u32 = undefined;
mulxU32(&x699, &x700, x669, 0xffffffff);
var x701: u32 = undefined;
var x702: u32 = undefined;
mulxU32(&x701, &x702, x669, 0xffffffff);
var x703: u32 = undefined;
var x704: u32 = undefined;
mulxU32(&x703, &x704, x669, 0xffffffff);
var x705: u32 = undefined;
var x706: u32 = undefined;
mulxU32(&x705, &x706, x669, 0xffffffff);
var x707: u32 = undefined;
var x708: u32 = undefined;
mulxU32(&x707, &x708, x669, 0xfffffffe);
var x709: u32 = undefined;
var x710: u32 = undefined;
mulxU32(&x709, &x710, x669, 0xffffffff);
var x711: u32 = undefined;
var x712: u32 = undefined;
mulxU32(&x711, &x712, x669, 0xffffffff);
var x713: u32 = undefined;
var x714: u1 = undefined;
addcarryxU32(&x713, &x714, 0x0, x710, x707);
var x715: u32 = undefined;
var x716: u1 = undefined;
addcarryxU32(&x715, &x716, x714, x708, x705);
var x717: u32 = undefined;
var x718: u1 = undefined;
addcarryxU32(&x717, &x718, x716, x706, x703);
var x719: u32 = undefined;
var x720: u1 = undefined;
addcarryxU32(&x719, &x720, x718, x704, x701);
var x721: u32 = undefined;
var x722: u1 = undefined;
addcarryxU32(&x721, &x722, x720, x702, x699);
var x723: u32 = undefined;
var x724: u1 = undefined;
addcarryxU32(&x723, &x724, x722, x700, x697);
var x725: u32 = undefined;
var x726: u1 = undefined;
addcarryxU32(&x725, &x726, x724, x698, x695);
var x727: u32 = undefined;
var x728: u1 = undefined;
addcarryxU32(&x727, &x728, x726, x696, x693);
var x729: u32 = undefined;
var x730: u1 = undefined;
addcarryxU32(&x729, &x730, 0x0, x669, x711);
var x731: u32 = undefined;
var x732: u1 = undefined;
addcarryxU32(&x731, &x732, x730, x671, x712);
var x733: u32 = undefined;
var x734: u1 = undefined;
addcarryxU32(&x733, &x734, x732, x673, cast(u32, 0x0));
var x735: u32 = undefined;
var x736: u1 = undefined;
addcarryxU32(&x735, &x736, x734, x675, x709);
var x737: u32 = undefined;
var x738: u1 = undefined;
addcarryxU32(&x737, &x738, x736, x677, x713);
var x739: u32 = undefined;
var x740: u1 = undefined;
addcarryxU32(&x739, &x740, x738, x679, x715);
var x741: u32 = undefined;
var x742: u1 = undefined;
addcarryxU32(&x741, &x742, x740, x681, x717);
var x743: u32 = undefined;
var x744: u1 = undefined;
addcarryxU32(&x743, &x744, x742, x683, x719);
var x745: u32 = undefined;
var x746: u1 = undefined;
addcarryxU32(&x745, &x746, x744, x685, x721);
var x747: u32 = undefined;
var x748: u1 = undefined;
addcarryxU32(&x747, &x748, x746, x687, x723);
var x749: u32 = undefined;
var x750: u1 = undefined;
addcarryxU32(&x749, &x750, x748, x689, x725);
var x751: u32 = undefined;
var x752: u1 = undefined;
addcarryxU32(&x751, &x752, x750, x691, x727);
var x753: u32 = undefined;
var x754: u1 = undefined;
addcarryxU32(&x753, &x754, x752, (cast(u32, x692) + cast(u32, x658)), (cast(u32, x728) + x694));
var x755: u32 = undefined;
var x756: u32 = undefined;
mulxU32(&x755, &x756, x8, 0x2);
var x757: u32 = undefined;
var x758: u32 = undefined;
mulxU32(&x757, &x758, x8, 0xfffffffe);
var x759: u32 = undefined;
var x760: u32 = undefined;
mulxU32(&x759, &x760, x8, 0x2);
var x761: u32 = undefined;
var x762: u32 = undefined;
mulxU32(&x761, &x762, x8, 0xfffffffe);
var x763: u32 = undefined;
var x764: u1 = undefined;
addcarryxU32(&x763, &x764, 0x0, cast(u32, cast(u1, x756)), x8);
var x765: u32 = undefined;
var x766: u1 = undefined;
addcarryxU32(&x765, &x766, 0x0, x731, x8);
var x767: u32 = undefined;
var x768: u1 = undefined;
addcarryxU32(&x767, &x768, x766, x733, x761);
var x769: u32 = undefined;
var x770: u1 = undefined;
addcarryxU32(&x769, &x770, x768, x735, x762);
var x771: u32 = undefined;
var x772: u1 = undefined;
addcarryxU32(&x771, &x772, x770, x737, x759);
var x773: u32 = undefined;
var x774: u1 = undefined;
addcarryxU32(&x773, &x774, x772, x739, cast(u32, cast(u1, x760)));
var x775: u32 = undefined;
var x776: u1 = undefined;
addcarryxU32(&x775, &x776, x774, x741, x757);
var x777: u32 = undefined;
var x778: u1 = undefined;
addcarryxU32(&x777, &x778, x776, x743, x758);
var x779: u32 = undefined;
var x780: u1 = undefined;
addcarryxU32(&x779, &x780, x778, x745, x755);
var x781: u32 = undefined;
var x782: u1 = undefined;
addcarryxU32(&x781, &x782, x780, x747, x763);
var x783: u32 = undefined;
var x784: u1 = undefined;
addcarryxU32(&x783, &x784, x782, x749, cast(u32, x764));
var x785: u32 = undefined;
var x786: u1 = undefined;
addcarryxU32(&x785, &x786, x784, x751, cast(u32, 0x0));
var x787: u32 = undefined;
var x788: u1 = undefined;
addcarryxU32(&x787, &x788, x786, x753, cast(u32, 0x0));
var x789: u32 = undefined;
var x790: u32 = undefined;
mulxU32(&x789, &x790, x765, 0xffffffff);
var x791: u32 = undefined;
var x792: u32 = undefined;
mulxU32(&x791, &x792, x765, 0xffffffff);
var x793: u32 = undefined;
var x794: u32 = undefined;
mulxU32(&x793, &x794, x765, 0xffffffff);
var x795: u32 = undefined;
var x796: u32 = undefined;
mulxU32(&x795, &x796, x765, 0xffffffff);
var x797: u32 = undefined;
var x798: u32 = undefined;
mulxU32(&x797, &x798, x765, 0xffffffff);
var x799: u32 = undefined;
var x800: u32 = undefined;
mulxU32(&x799, &x800, x765, 0xffffffff);
var x801: u32 = undefined;
var x802: u32 = undefined;
mulxU32(&x801, &x802, x765, 0xffffffff);
var x803: u32 = undefined;
var x804: u32 = undefined;
mulxU32(&x803, &x804, x765, 0xfffffffe);
var x805: u32 = undefined;
var x806: u32 = undefined;
mulxU32(&x805, &x806, x765, 0xffffffff);
var x807: u32 = undefined;
var x808: u32 = undefined;
mulxU32(&x807, &x808, x765, 0xffffffff);
var x809: u32 = undefined;
var x810: u1 = undefined;
addcarryxU32(&x809, &x810, 0x0, x806, x803);
var x811: u32 = undefined;
var x812: u1 = undefined;
addcarryxU32(&x811, &x812, x810, x804, x801);
var x813: u32 = undefined;
var x814: u1 = undefined;
addcarryxU32(&x813, &x814, x812, x802, x799);
var x815: u32 = undefined;
var x816: u1 = undefined;
addcarryxU32(&x815, &x816, x814, x800, x797);
var x817: u32 = undefined;
var x818: u1 = undefined;
addcarryxU32(&x817, &x818, x816, x798, x795);
var x819: u32 = undefined;
var x820: u1 = undefined;
addcarryxU32(&x819, &x820, x818, x796, x793);
var x821: u32 = undefined;
var x822: u1 = undefined;
addcarryxU32(&x821, &x822, x820, x794, x791);
var x823: u32 = undefined;
var x824: u1 = undefined;
addcarryxU32(&x823, &x824, x822, x792, x789);
var x825: u32 = undefined;
var x826: u1 = undefined;
addcarryxU32(&x825, &x826, 0x0, x765, x807);
var x827: u32 = undefined;
var x828: u1 = undefined;
addcarryxU32(&x827, &x828, x826, x767, x808);
var x829: u32 = undefined;
var x830: u1 = undefined;
addcarryxU32(&x829, &x830, x828, x769, cast(u32, 0x0));
var x831: u32 = undefined;
var x832: u1 = undefined;
addcarryxU32(&x831, &x832, x830, x771, x805);
var x833: u32 = undefined;
var x834: u1 = undefined;
addcarryxU32(&x833, &x834, x832, x773, x809);
var x835: u32 = undefined;
var x836: u1 = undefined;
addcarryxU32(&x835, &x836, x834, x775, x811);
var x837: u32 = undefined;
var x838: u1 = undefined;
addcarryxU32(&x837, &x838, x836, x777, x813);
var x839: u32 = undefined;
var x840: u1 = undefined;
addcarryxU32(&x839, &x840, x838, x779, x815);
var x841: u32 = undefined;
var x842: u1 = undefined;
addcarryxU32(&x841, &x842, x840, x781, x817);
var x843: u32 = undefined;
var x844: u1 = undefined;
addcarryxU32(&x843, &x844, x842, x783, x819);
var x845: u32 = undefined;
var x846: u1 = undefined;
addcarryxU32(&x845, &x846, x844, x785, x821);
var x847: u32 = undefined;
var x848: u1 = undefined;
addcarryxU32(&x847, &x848, x846, x787, x823);
var x849: u32 = undefined;
var x850: u1 = undefined;
addcarryxU32(&x849, &x850, x848, (cast(u32, x788) + cast(u32, x754)), (cast(u32, x824) + x790));
var x851: u32 = undefined;
var x852: u32 = undefined;
mulxU32(&x851, &x852, x9, 0x2);
var x853: u32 = undefined;
var x854: u32 = undefined;
mulxU32(&x853, &x854, x9, 0xfffffffe);
var x855: u32 = undefined;
var x856: u32 = undefined;
mulxU32(&x855, &x856, x9, 0x2);
var x857: u32 = undefined;
var x858: u32 = undefined;
mulxU32(&x857, &x858, x9, 0xfffffffe);
var x859: u32 = undefined;
var x860: u1 = undefined;
addcarryxU32(&x859, &x860, 0x0, cast(u32, cast(u1, x852)), x9);
var x861: u32 = undefined;
var x862: u1 = undefined;
addcarryxU32(&x861, &x862, 0x0, x827, x9);
var x863: u32 = undefined;
var x864: u1 = undefined;
addcarryxU32(&x863, &x864, x862, x829, x857);
var x865: u32 = undefined;
var x866: u1 = undefined;
addcarryxU32(&x865, &x866, x864, x831, x858);
var x867: u32 = undefined;
var x868: u1 = undefined;
addcarryxU32(&x867, &x868, x866, x833, x855);
var x869: u32 = undefined;
var x870: u1 = undefined;
addcarryxU32(&x869, &x870, x868, x835, cast(u32, cast(u1, x856)));
var x871: u32 = undefined;
var x872: u1 = undefined;
addcarryxU32(&x871, &x872, x870, x837, x853);
var x873: u32 = undefined;
var x874: u1 = undefined;
addcarryxU32(&x873, &x874, x872, x839, x854);
var x875: u32 = undefined;
var x876: u1 = undefined;
addcarryxU32(&x875, &x876, x874, x841, x851);
var x877: u32 = undefined;
var x878: u1 = undefined;
addcarryxU32(&x877, &x878, x876, x843, x859);
var x879: u32 = undefined;
var x880: u1 = undefined;
addcarryxU32(&x879, &x880, x878, x845, cast(u32, x860));
var x881: u32 = undefined;
var x882: u1 = undefined;
addcarryxU32(&x881, &x882, x880, x847, cast(u32, 0x0));
var x883: u32 = undefined;
var x884: u1 = undefined;
addcarryxU32(&x883, &x884, x882, x849, cast(u32, 0x0));
var x885: u32 = undefined;
var x886: u32 = undefined;
mulxU32(&x885, &x886, x861, 0xffffffff);
var x887: u32 = undefined;
var x888: u32 = undefined;
mulxU32(&x887, &x888, x861, 0xffffffff);
var x889: u32 = undefined;
var x890: u32 = undefined;
mulxU32(&x889, &x890, x861, 0xffffffff);
var x891: u32 = undefined;
var x892: u32 = undefined;
mulxU32(&x891, &x892, x861, 0xffffffff);
var x893: u32 = undefined;
var x894: u32 = undefined;
mulxU32(&x893, &x894, x861, 0xffffffff);
var x895: u32 = undefined;
var x896: u32 = undefined;
mulxU32(&x895, &x896, x861, 0xffffffff);
var x897: u32 = undefined;
var x898: u32 = undefined;
mulxU32(&x897, &x898, x861, 0xffffffff);
var x899: u32 = undefined;
var x900: u32 = undefined;
mulxU32(&x899, &x900, x861, 0xfffffffe);
var x901: u32 = undefined;
var x902: u32 = undefined;
mulxU32(&x901, &x902, x861, 0xffffffff);
var x903: u32 = undefined;
var x904: u32 = undefined;
mulxU32(&x903, &x904, x861, 0xffffffff);
var x905: u32 = undefined;
var x906: u1 = undefined;
addcarryxU32(&x905, &x906, 0x0, x902, x899);
var x907: u32 = undefined;
var x908: u1 = undefined;
addcarryxU32(&x907, &x908, x906, x900, x897);
var x909: u32 = undefined;
var x910: u1 = undefined;
addcarryxU32(&x909, &x910, x908, x898, x895);
var x911: u32 = undefined;
var x912: u1 = undefined;
addcarryxU32(&x911, &x912, x910, x896, x893);
var x913: u32 = undefined;
var x914: u1 = undefined;
addcarryxU32(&x913, &x914, x912, x894, x891);
var x915: u32 = undefined;
var x916: u1 = undefined;
addcarryxU32(&x915, &x916, x914, x892, x889);
var x917: u32 = undefined;
var x918: u1 = undefined;
addcarryxU32(&x917, &x918, x916, x890, x887);
var x919: u32 = undefined;
var x920: u1 = undefined;
addcarryxU32(&x919, &x920, x918, x888, x885);
var x921: u32 = undefined;
var x922: u1 = undefined;
addcarryxU32(&x921, &x922, 0x0, x861, x903);
var x923: u32 = undefined;
var x924: u1 = undefined;
addcarryxU32(&x923, &x924, x922, x863, x904);
var x925: u32 = undefined;
var x926: u1 = undefined;
addcarryxU32(&x925, &x926, x924, x865, cast(u32, 0x0));
var x927: u32 = undefined;
var x928: u1 = undefined;
addcarryxU32(&x927, &x928, x926, x867, x901);
var x929: u32 = undefined;
var x930: u1 = undefined;
addcarryxU32(&x929, &x930, x928, x869, x905);
var x931: u32 = undefined;
var x932: u1 = undefined;
addcarryxU32(&x931, &x932, x930, x871, x907);
var x933: u32 = undefined;
var x934: u1 = undefined;
addcarryxU32(&x933, &x934, x932, x873, x909);
var x935: u32 = undefined;
var x936: u1 = undefined;
addcarryxU32(&x935, &x936, x934, x875, x911);
var x937: u32 = undefined;
var x938: u1 = undefined;
addcarryxU32(&x937, &x938, x936, x877, x913);
var x939: u32 = undefined;
var x940: u1 = undefined;
addcarryxU32(&x939, &x940, x938, x879, x915);
var x941: u32 = undefined;
var x942: u1 = undefined;
addcarryxU32(&x941, &x942, x940, x881, x917);
var x943: u32 = undefined;
var x944: u1 = undefined;
addcarryxU32(&x943, &x944, x942, x883, x919);
var x945: u32 = undefined;
var x946: u1 = undefined;
addcarryxU32(&x945, &x946, x944, (cast(u32, x884) + cast(u32, x850)), (cast(u32, x920) + x886));
var x947: u32 = undefined;
var x948: u32 = undefined;
mulxU32(&x947, &x948, x10, 0x2);
var x949: u32 = undefined;
var x950: u32 = undefined;
mulxU32(&x949, &x950, x10, 0xfffffffe);
var x951: u32 = undefined;
var x952: u32 = undefined;
mulxU32(&x951, &x952, x10, 0x2);
var x953: u32 = undefined;
var x954: u32 = undefined;
mulxU32(&x953, &x954, x10, 0xfffffffe);
var x955: u32 = undefined;
var x956: u1 = undefined;
addcarryxU32(&x955, &x956, 0x0, cast(u32, cast(u1, x948)), x10);
var x957: u32 = undefined;
var x958: u1 = undefined;
addcarryxU32(&x957, &x958, 0x0, x923, x10);
var x959: u32 = undefined;
var x960: u1 = undefined;
addcarryxU32(&x959, &x960, x958, x925, x953);
var x961: u32 = undefined;
var x962: u1 = undefined;
addcarryxU32(&x961, &x962, x960, x927, x954);
var x963: u32 = undefined;
var x964: u1 = undefined;
addcarryxU32(&x963, &x964, x962, x929, x951);
var x965: u32 = undefined;
var x966: u1 = undefined;
addcarryxU32(&x965, &x966, x964, x931, cast(u32, cast(u1, x952)));
var x967: u32 = undefined;
var x968: u1 = undefined;
addcarryxU32(&x967, &x968, x966, x933, x949);
var x969: u32 = undefined;
var x970: u1 = undefined;
addcarryxU32(&x969, &x970, x968, x935, x950);
var x971: u32 = undefined;
var x972: u1 = undefined;
addcarryxU32(&x971, &x972, x970, x937, x947);
var x973: u32 = undefined;
var x974: u1 = undefined;
addcarryxU32(&x973, &x974, x972, x939, x955);
var x975: u32 = undefined;
var x976: u1 = undefined;
addcarryxU32(&x975, &x976, x974, x941, cast(u32, x956));
var x977: u32 = undefined;
var x978: u1 = undefined;
addcarryxU32(&x977, &x978, x976, x943, cast(u32, 0x0));
var x979: u32 = undefined;
var x980: u1 = undefined;
addcarryxU32(&x979, &x980, x978, x945, cast(u32, 0x0));
var x981: u32 = undefined;
var x982: u32 = undefined;
mulxU32(&x981, &x982, x957, 0xffffffff);
var x983: u32 = undefined;
var x984: u32 = undefined;
mulxU32(&x983, &x984, x957, 0xffffffff);
var x985: u32 = undefined;
var x986: u32 = undefined;
mulxU32(&x985, &x986, x957, 0xffffffff);
var x987: u32 = undefined;
var x988: u32 = undefined;
mulxU32(&x987, &x988, x957, 0xffffffff);
var x989: u32 = undefined;
var x990: u32 = undefined;
mulxU32(&x989, &x990, x957, 0xffffffff);
var x991: u32 = undefined;
var x992: u32 = undefined;
mulxU32(&x991, &x992, x957, 0xffffffff);
var x993: u32 = undefined;
var x994: u32 = undefined;
mulxU32(&x993, &x994, x957, 0xffffffff);
var x995: u32 = undefined;
var x996: u32 = undefined;
mulxU32(&x995, &x996, x957, 0xfffffffe);
var x997: u32 = undefined;
var x998: u32 = undefined;
mulxU32(&x997, &x998, x957, 0xffffffff);
var x999: u32 = undefined;
var x1000: u32 = undefined;
mulxU32(&x999, &x1000, x957, 0xffffffff);
var x1001: u32 = undefined;
var x1002: u1 = undefined;
addcarryxU32(&x1001, &x1002, 0x0, x998, x995);
var x1003: u32 = undefined;
var x1004: u1 = undefined;
addcarryxU32(&x1003, &x1004, x1002, x996, x993);
var x1005: u32 = undefined;
var x1006: u1 = undefined;
addcarryxU32(&x1005, &x1006, x1004, x994, x991);
var x1007: u32 = undefined;
var x1008: u1 = undefined;
addcarryxU32(&x1007, &x1008, x1006, x992, x989);
var x1009: u32 = undefined;
var x1010: u1 = undefined;
addcarryxU32(&x1009, &x1010, x1008, x990, x987);
var x1011: u32 = undefined;
var x1012: u1 = undefined;
addcarryxU32(&x1011, &x1012, x1010, x988, x985);
var x1013: u32 = undefined;
var x1014: u1 = undefined;
addcarryxU32(&x1013, &x1014, x1012, x986, x983);
var x1015: u32 = undefined;
var x1016: u1 = undefined;
addcarryxU32(&x1015, &x1016, x1014, x984, x981);
var x1017: u32 = undefined;
var x1018: u1 = undefined;
addcarryxU32(&x1017, &x1018, 0x0, x957, x999);
var x1019: u32 = undefined;
var x1020: u1 = undefined;
addcarryxU32(&x1019, &x1020, x1018, x959, x1000);
var x1021: u32 = undefined;
var x1022: u1 = undefined;
addcarryxU32(&x1021, &x1022, x1020, x961, cast(u32, 0x0));
var x1023: u32 = undefined;
var x1024: u1 = undefined;
addcarryxU32(&x1023, &x1024, x1022, x963, x997);
var x1025: u32 = undefined;
var x1026: u1 = undefined;
addcarryxU32(&x1025, &x1026, x1024, x965, x1001);
var x1027: u32 = undefined;
var x1028: u1 = undefined;
addcarryxU32(&x1027, &x1028, x1026, x967, x1003);
var x1029: u32 = undefined;
var x1030: u1 = undefined;
addcarryxU32(&x1029, &x1030, x1028, x969, x1005);
var x1031: u32 = undefined;
var x1032: u1 = undefined;
addcarryxU32(&x1031, &x1032, x1030, x971, x1007);
var x1033: u32 = undefined;
var x1034: u1 = undefined;
addcarryxU32(&x1033, &x1034, x1032, x973, x1009);
var x1035: u32 = undefined;
var x1036: u1 = undefined;
addcarryxU32(&x1035, &x1036, x1034, x975, x1011);
var x1037: u32 = undefined;
var x1038: u1 = undefined;
addcarryxU32(&x1037, &x1038, x1036, x977, x1013);
var x1039: u32 = undefined;
var x1040: u1 = undefined;
addcarryxU32(&x1039, &x1040, x1038, x979, x1015);
var x1041: u32 = undefined;
var x1042: u1 = undefined;
addcarryxU32(&x1041, &x1042, x1040, (cast(u32, x980) + cast(u32, x946)), (cast(u32, x1016) + x982));
var x1043: u32 = undefined;
var x1044: u32 = undefined;
mulxU32(&x1043, &x1044, x11, 0x2);
var x1045: u32 = undefined;
var x1046: u32 = undefined;
mulxU32(&x1045, &x1046, x11, 0xfffffffe);
var x1047: u32 = undefined;
var x1048: u32 = undefined;
mulxU32(&x1047, &x1048, x11, 0x2);
var x1049: u32 = undefined;
var x1050: u32 = undefined;
mulxU32(&x1049, &x1050, x11, 0xfffffffe);
var x1051: u32 = undefined;
var x1052: u1 = undefined;
addcarryxU32(&x1051, &x1052, 0x0, cast(u32, cast(u1, x1044)), x11);
var x1053: u32 = undefined;
var x1054: u1 = undefined;
addcarryxU32(&x1053, &x1054, 0x0, x1019, x11);
var x1055: u32 = undefined;
var x1056: u1 = undefined;
addcarryxU32(&x1055, &x1056, x1054, x1021, x1049);
var x1057: u32 = undefined;
var x1058: u1 = undefined;
addcarryxU32(&x1057, &x1058, x1056, x1023, x1050);
var x1059: u32 = undefined;
var x1060: u1 = undefined;
addcarryxU32(&x1059, &x1060, x1058, x1025, x1047);
var x1061: u32 = undefined;
var x1062: u1 = undefined;
addcarryxU32(&x1061, &x1062, x1060, x1027, cast(u32, cast(u1, x1048)));
var x1063: u32 = undefined;
var x1064: u1 = undefined;
addcarryxU32(&x1063, &x1064, x1062, x1029, x1045);
var x1065: u32 = undefined;
var x1066: u1 = undefined;
addcarryxU32(&x1065, &x1066, x1064, x1031, x1046);
var x1067: u32 = undefined;
var x1068: u1 = undefined;
addcarryxU32(&x1067, &x1068, x1066, x1033, x1043);
var x1069: u32 = undefined;
var x1070: u1 = undefined;
addcarryxU32(&x1069, &x1070, x1068, x1035, x1051);
var x1071: u32 = undefined;
var x1072: u1 = undefined;
addcarryxU32(&x1071, &x1072, x1070, x1037, cast(u32, x1052));
var x1073: u32 = undefined;
var x1074: u1 = undefined;
addcarryxU32(&x1073, &x1074, x1072, x1039, cast(u32, 0x0));
var x1075: u32 = undefined;
var x1076: u1 = undefined;
addcarryxU32(&x1075, &x1076, x1074, x1041, cast(u32, 0x0));
var x1077: u32 = undefined;
var x1078: u32 = undefined;
mulxU32(&x1077, &x1078, x1053, 0xffffffff);
var x1079: u32 = undefined;
var x1080: u32 = undefined;
mulxU32(&x1079, &x1080, x1053, 0xffffffff);
var x1081: u32 = undefined;
var x1082: u32 = undefined;
mulxU32(&x1081, &x1082, x1053, 0xffffffff);
var x1083: u32 = undefined;
var x1084: u32 = undefined;
mulxU32(&x1083, &x1084, x1053, 0xffffffff);
var x1085: u32 = undefined;
var x1086: u32 = undefined;
mulxU32(&x1085, &x1086, x1053, 0xffffffff);
var x1087: u32 = undefined;
var x1088: u32 = undefined;
mulxU32(&x1087, &x1088, x1053, 0xffffffff);
var x1089: u32 = undefined;
var x1090: u32 = undefined;
mulxU32(&x1089, &x1090, x1053, 0xffffffff);
var x1091: u32 = undefined;
var x1092: u32 = undefined;
mulxU32(&x1091, &x1092, x1053, 0xfffffffe);
var x1093: u32 = undefined;
var x1094: u32 = undefined;
mulxU32(&x1093, &x1094, x1053, 0xffffffff);
var x1095: u32 = undefined;
var x1096: u32 = undefined;
mulxU32(&x1095, &x1096, x1053, 0xffffffff);
var x1097: u32 = undefined;
var x1098: u1 = undefined;
addcarryxU32(&x1097, &x1098, 0x0, x1094, x1091);
var x1099: u32 = undefined;
var x1100: u1 = undefined;
addcarryxU32(&x1099, &x1100, x1098, x1092, x1089);
var x1101: u32 = undefined;
var x1102: u1 = undefined;
addcarryxU32(&x1101, &x1102, x1100, x1090, x1087);
var x1103: u32 = undefined;
var x1104: u1 = undefined;
addcarryxU32(&x1103, &x1104, x1102, x1088, x1085);
var x1105: u32 = undefined;
var x1106: u1 = undefined;
addcarryxU32(&x1105, &x1106, x1104, x1086, x1083);
var x1107: u32 = undefined;
var x1108: u1 = undefined;
addcarryxU32(&x1107, &x1108, x1106, x1084, x1081);
var x1109: u32 = undefined;
var x1110: u1 = undefined;
addcarryxU32(&x1109, &x1110, x1108, x1082, x1079);
var x1111: u32 = undefined;
var x1112: u1 = undefined;
addcarryxU32(&x1111, &x1112, x1110, x1080, x1077);
var x1113: u32 = undefined;
var x1114: u1 = undefined;
addcarryxU32(&x1113, &x1114, 0x0, x1053, x1095);
var x1115: u32 = undefined;
var x1116: u1 = undefined;
addcarryxU32(&x1115, &x1116, x1114, x1055, x1096);
var x1117: u32 = undefined;
var x1118: u1 = undefined;
addcarryxU32(&x1117, &x1118, x1116, x1057, cast(u32, 0x0));
var x1119: u32 = undefined;
var x1120: u1 = undefined;
addcarryxU32(&x1119, &x1120, x1118, x1059, x1093);
var x1121: u32 = undefined;
var x1122: u1 = undefined;
addcarryxU32(&x1121, &x1122, x1120, x1061, x1097);
var x1123: u32 = undefined;
var x1124: u1 = undefined;
addcarryxU32(&x1123, &x1124, x1122, x1063, x1099);
var x1125: u32 = undefined;
var x1126: u1 = undefined;
addcarryxU32(&x1125, &x1126, x1124, x1065, x1101);
var x1127: u32 = undefined;
var x1128: u1 = undefined;
addcarryxU32(&x1127, &x1128, x1126, x1067, x1103);
var x1129: u32 = undefined;
var x1130: u1 = undefined;
addcarryxU32(&x1129, &x1130, x1128, x1069, x1105);
var x1131: u32 = undefined;
var x1132: u1 = undefined;
addcarryxU32(&x1131, &x1132, x1130, x1071, x1107);
var x1133: u32 = undefined;
var x1134: u1 = undefined;
addcarryxU32(&x1133, &x1134, x1132, x1073, x1109);
var x1135: u32 = undefined;
var x1136: u1 = undefined;
addcarryxU32(&x1135, &x1136, x1134, x1075, x1111);
var x1137: u32 = undefined;
var x1138: u1 = undefined;
addcarryxU32(&x1137, &x1138, x1136, (cast(u32, x1076) + cast(u32, x1042)), (cast(u32, x1112) + x1078));
var x1139: u32 = undefined;
var x1140: u1 = undefined;
subborrowxU32(&x1139, &x1140, 0x0, x1115, 0xffffffff);
var x1141: u32 = undefined;
var x1142: u1 = undefined;
subborrowxU32(&x1141, &x1142, x1140, x1117, cast(u32, 0x0));
var x1143: u32 = undefined;
var x1144: u1 = undefined;
subborrowxU32(&x1143, &x1144, x1142, x1119, cast(u32, 0x0));
var x1145: u32 = undefined;
var x1146: u1 = undefined;
subborrowxU32(&x1145, &x1146, x1144, x1121, 0xffffffff);
var x1147: u32 = undefined;
var x1148: u1 = undefined;
subborrowxU32(&x1147, &x1148, x1146, x1123, 0xfffffffe);
var x1149: u32 = undefined;
var x1150: u1 = undefined;
subborrowxU32(&x1149, &x1150, x1148, x1125, 0xffffffff);
var x1151: u32 = undefined;
var x1152: u1 = undefined;
subborrowxU32(&x1151, &x1152, x1150, x1127, 0xffffffff);
var x1153: u32 = undefined;
var x1154: u1 = undefined;
subborrowxU32(&x1153, &x1154, x1152, x1129, 0xffffffff);
var x1155: u32 = undefined;
var x1156: u1 = undefined;
subborrowxU32(&x1155, &x1156, x1154, x1131, 0xffffffff);
var x1157: u32 = undefined;
var x1158: u1 = undefined;
subborrowxU32(&x1157, &x1158, x1156, x1133, 0xffffffff);
var x1159: u32 = undefined;
var x1160: u1 = undefined;
subborrowxU32(&x1159, &x1160, x1158, x1135, 0xffffffff);
var x1161: u32 = undefined;
var x1162: u1 = undefined;
subborrowxU32(&x1161, &x1162, x1160, x1137, 0xffffffff);
var x1163: u32 = undefined;
var x1164: u1 = undefined;
subborrowxU32(&x1163, &x1164, x1162, cast(u32, x1138), cast(u32, 0x0));
var x1165: u32 = undefined;
cmovznzU32(&x1165, x1164, x1139, x1115);
var x1166: u32 = undefined;
cmovznzU32(&x1166, x1164, x1141, x1117);
var x1167: u32 = undefined;
cmovznzU32(&x1167, x1164, x1143, x1119);
var x1168: u32 = undefined;
cmovznzU32(&x1168, x1164, x1145, x1121);
var x1169: u32 = undefined;
cmovznzU32(&x1169, x1164, x1147, x1123);
var x1170: u32 = undefined;
cmovznzU32(&x1170, x1164, x1149, x1125);
var x1171: u32 = undefined;
cmovznzU32(&x1171, x1164, x1151, x1127);
var x1172: u32 = undefined;
cmovznzU32(&x1172, x1164, x1153, x1129);
var x1173: u32 = undefined;
cmovznzU32(&x1173, x1164, x1155, x1131);
var x1174: u32 = undefined;
cmovznzU32(&x1174, x1164, x1157, x1133);
var x1175: u32 = undefined;
cmovznzU32(&x1175, x1164, x1159, x1135);
var x1176: u32 = undefined;
cmovznzU32(&x1176, x1164, x1161, x1137);
out1[0] = x1165;
out1[1] = x1166;
out1[2] = x1167;
out1[3] = x1168;
out1[4] = x1169;
out1[5] = x1170;
out1[6] = x1171;
out1[7] = x1172;
out1[8] = x1173;
out1[9] = x1174;
out1[10] = x1175;
out1[11] = x1176;
}
/// The function nonzero outputs a single non-zero word if the input is non-zero and zero otherwise.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
pub fn nonzero(out1: *u32, arg1: [12]u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | ((arg1[3]) | ((arg1[4]) | ((arg1[5]) | ((arg1[6]) | ((arg1[7]) | ((arg1[8]) | ((arg1[9]) | ((arg1[10]) | (arg1[11]))))))))))));
out1.* = x1;
}
/// The function selectznz is a multi-limb conditional select.
///
/// Postconditions:
/// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3)
///
/// Input Bounds:
/// arg1: [0x0 ~> 0x1]
/// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn selectznz(out1: *[12]u32, arg1: u1, arg2: [12]u32, arg3: [12]u32) void {
@setRuntimeSafety(mode == .Debug);
var x1: u32 = undefined;
cmovznzU32(&x1, arg1, (arg2[0]), (arg3[0]));
var x2: u32 = undefined;
cmovznzU32(&x2, arg1, (arg2[1]), (arg3[1]));
var x3: u32 = undefined;
cmovznzU32(&x3, arg1, (arg2[2]), (arg3[2]));
var x4: u32 = undefined;
cmovznzU32(&x4, arg1, (arg2[3]), (arg3[3]));
var x5: u32 = undefined;
cmovznzU32(&x5, arg1, (arg2[4]), (arg3[4]));
var x6: u32 = undefined;
cmovznzU32(&x6, arg1, (arg2[5]), (arg3[5]));
var x7: u32 = undefined;
cmovznzU32(&x7, arg1, (arg2[6]), (arg3[6]));
var x8: u32 = undefined;
cmovznzU32(&x8, arg1, (arg2[7]), (arg3[7]));
var x9: u32 = undefined;
cmovznzU32(&x9, arg1, (arg2[8]), (arg3[8]));
var x10: u32 = undefined;
cmovznzU32(&x10, arg1, (arg2[9]), (arg3[9]));
var x11: u32 = undefined;
cmovznzU32(&x11, arg1, (arg2[10]), (arg3[10]));
var x12: u32 = undefined;
cmovznzU32(&x12, arg1, (arg2[11]), (arg3[11]));
out1[0] = x1;
out1[1] = x2;
out1[2] = x3;
out1[3] = x4;
out1[4] = x5;
out1[5] = x6;
out1[6] = x7;
out1[7] = x8;
out1[8] = x9;
out1[9] = x10;
out1[10] = x11;
out1[11] = x12;
}
/// The function toBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order.
///
/// Preconditions:
/// 0 ≤ eval arg1 < m
/// Postconditions:
/// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..47]
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
pub fn toBytes(out1: *[48]u8, arg1: [12]u32) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (arg1[11]);
const x2 = (arg1[10]);
const x3 = (arg1[9]);
const x4 = (arg1[8]);
const x5 = (arg1[7]);
const x6 = (arg1[6]);
const x7 = (arg1[5]);
const x8 = (arg1[4]);
const x9 = (arg1[3]);
const x10 = (arg1[2]);
const x11 = (arg1[1]);
const x12 = (arg1[0]);
const x13 = cast(u8, (x12 & cast(u32, 0xff)));
const x14 = (x12 >> 8);
const x15 = cast(u8, (x14 & cast(u32, 0xff)));
const x16 = (x14 >> 8);
const x17 = cast(u8, (x16 & cast(u32, 0xff)));
const x18 = cast(u8, (x16 >> 8));
const x19 = cast(u8, (x11 & cast(u32, 0xff)));
const x20 = (x11 >> 8);
const x21 = cast(u8, (x20 & cast(u32, 0xff)));
const x22 = (x20 >> 8);
const x23 = cast(u8, (x22 & cast(u32, 0xff)));
const x24 = cast(u8, (x22 >> 8));
const x25 = cast(u8, (x10 & cast(u32, 0xff)));
const x26 = (x10 >> 8);
const x27 = cast(u8, (x26 & cast(u32, 0xff)));
const x28 = (x26 >> 8);
const x29 = cast(u8, (x28 & cast(u32, 0xff)));
const x30 = cast(u8, (x28 >> 8));
const x31 = cast(u8, (x9 & cast(u32, 0xff)));
const x32 = (x9 >> 8);
const x33 = cast(u8, (x32 & cast(u32, 0xff)));
const x34 = (x32 >> 8);
const x35 = cast(u8, (x34 & cast(u32, 0xff)));
const x36 = cast(u8, (x34 >> 8));
const x37 = cast(u8, (x8 & cast(u32, 0xff)));
const x38 = (x8 >> 8);
const x39 = cast(u8, (x38 & cast(u32, 0xff)));
const x40 = (x38 >> 8);
const x41 = cast(u8, (x40 & cast(u32, 0xff)));
const x42 = cast(u8, (x40 >> 8));
const x43 = cast(u8, (x7 & cast(u32, 0xff)));
const x44 = (x7 >> 8);
const x45 = cast(u8, (x44 & cast(u32, 0xff)));
const x46 = (x44 >> 8);
const x47 = cast(u8, (x46 & cast(u32, 0xff)));
const x48 = cast(u8, (x46 >> 8));
const x49 = cast(u8, (x6 & cast(u32, 0xff)));
const x50 = (x6 >> 8);
const x51 = cast(u8, (x50 & cast(u32, 0xff)));
const x52 = (x50 >> 8);
const x53 = cast(u8, (x52 & cast(u32, 0xff)));
const x54 = cast(u8, (x52 >> 8));
const x55 = cast(u8, (x5 & cast(u32, 0xff)));
const x56 = (x5 >> 8);
const x57 = cast(u8, (x56 & cast(u32, 0xff)));
const x58 = (x56 >> 8);
const x59 = cast(u8, (x58 & cast(u32, 0xff)));
const x60 = cast(u8, (x58 >> 8));
const x61 = cast(u8, (x4 & cast(u32, 0xff)));
const x62 = (x4 >> 8);
const x63 = cast(u8, (x62 & cast(u32, 0xff)));
const x64 = (x62 >> 8);
const x65 = cast(u8, (x64 & cast(u32, 0xff)));
const x66 = cast(u8, (x64 >> 8));
const x67 = cast(u8, (x3 & cast(u32, 0xff)));
const x68 = (x3 >> 8);
const x69 = cast(u8, (x68 & cast(u32, 0xff)));
const x70 = (x68 >> 8);
const x71 = cast(u8, (x70 & cast(u32, 0xff)));
const x72 = cast(u8, (x70 >> 8));
const x73 = cast(u8, (x2 & cast(u32, 0xff)));
const x74 = (x2 >> 8);
const x75 = cast(u8, (x74 & cast(u32, 0xff)));
const x76 = (x74 >> 8);
const x77 = cast(u8, (x76 & cast(u32, 0xff)));
const x78 = cast(u8, (x76 >> 8));
const x79 = cast(u8, (x1 & cast(u32, 0xff)));
const x80 = (x1 >> 8);
const x81 = cast(u8, (x80 & cast(u32, 0xff)));
const x82 = (x80 >> 8);
const x83 = cast(u8, (x82 & cast(u32, 0xff)));
const x84 = cast(u8, (x82 >> 8));
out1[0] = x13;
out1[1] = x15;
out1[2] = x17;
out1[3] = x18;
out1[4] = x19;
out1[5] = x21;
out1[6] = x23;
out1[7] = x24;
out1[8] = x25;
out1[9] = x27;
out1[10] = x29;
out1[11] = x30;
out1[12] = x31;
out1[13] = x33;
out1[14] = x35;
out1[15] = x36;
out1[16] = x37;
out1[17] = x39;
out1[18] = x41;
out1[19] = x42;
out1[20] = x43;
out1[21] = x45;
out1[22] = x47;
out1[23] = x48;
out1[24] = x49;
out1[25] = x51;
out1[26] = x53;
out1[27] = x54;
out1[28] = x55;
out1[29] = x57;
out1[30] = x59;
out1[31] = x60;
out1[32] = x61;
out1[33] = x63;
out1[34] = x65;
out1[35] = x66;
out1[36] = x67;
out1[37] = x69;
out1[38] = x71;
out1[39] = x72;
out1[40] = x73;
out1[41] = x75;
out1[42] = x77;
out1[43] = x78;
out1[44] = x79;
out1[45] = x81;
out1[46] = x83;
out1[47] = x84;
}
/// The function fromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order.
///
/// Preconditions:
/// 0 ≤ bytes_eval arg1 < m
/// Postconditions:
/// eval out1 mod m = bytes_eval arg1 mod m
/// 0 ≤ eval out1 < m
///
/// Input Bounds:
/// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn fromBytes(out1: *[12]u32, arg1: [48]u8) void {
@setRuntimeSafety(mode == .Debug);
const x1 = (cast(u32, (arg1[47])) << 24);
const x2 = (cast(u32, (arg1[46])) << 16);
const x3 = (cast(u32, (arg1[45])) << 8);
const x4 = (arg1[44]);
const x5 = (cast(u32, (arg1[43])) << 24);
const x6 = (cast(u32, (arg1[42])) << 16);
const x7 = (cast(u32, (arg1[41])) << 8);
const x8 = (arg1[40]);
const x9 = (cast(u32, (arg1[39])) << 24);
const x10 = (cast(u32, (arg1[38])) << 16);
const x11 = (cast(u32, (arg1[37])) << 8);
const x12 = (arg1[36]);
const x13 = (cast(u32, (arg1[35])) << 24);
const x14 = (cast(u32, (arg1[34])) << 16);
const x15 = (cast(u32, (arg1[33])) << 8);
const x16 = (arg1[32]);
const x17 = (cast(u32, (arg1[31])) << 24);
const x18 = (cast(u32, (arg1[30])) << 16);
const x19 = (cast(u32, (arg1[29])) << 8);
const x20 = (arg1[28]);
const x21 = (cast(u32, (arg1[27])) << 24);
const x22 = (cast(u32, (arg1[26])) << 16);
const x23 = (cast(u32, (arg1[25])) << 8);
const x24 = (arg1[24]);
const x25 = (cast(u32, (arg1[23])) << 24);
const x26 = (cast(u32, (arg1[22])) << 16);
const x27 = (cast(u32, (arg1[21])) << 8);
const x28 = (arg1[20]);
const x29 = (cast(u32, (arg1[19])) << 24);
const x30 = (cast(u32, (arg1[18])) << 16);
const x31 = (cast(u32, (arg1[17])) << 8);
const x32 = (arg1[16]);
const x33 = (cast(u32, (arg1[15])) << 24);
const x34 = (cast(u32, (arg1[14])) << 16);
const x35 = (cast(u32, (arg1[13])) << 8);
const x36 = (arg1[12]);
const x37 = (cast(u32, (arg1[11])) << 24);
const x38 = (cast(u32, (arg1[10])) << 16);
const x39 = (cast(u32, (arg1[9])) << 8);
const x40 = (arg1[8]);
const x41 = (cast(u32, (arg1[7])) << 24);
const x42 = (cast(u32, (arg1[6])) << 16);
const x43 = (cast(u32, (arg1[5])) << 8);
const x44 = (arg1[4]);
const x45 = (cast(u32, (arg1[3])) << 24);
const x46 = (cast(u32, (arg1[2])) << 16);
const x47 = (cast(u32, (arg1[1])) << 8);
const x48 = (arg1[0]);
const x49 = (x47 + cast(u32, x48));
const x50 = (x46 + x49);
const x51 = (x45 + x50);
const x52 = (x43 + cast(u32, x44));
const x53 = (x42 + x52);
const x54 = (x41 + x53);
const x55 = (x39 + cast(u32, x40));
const x56 = (x38 + x55);
const x57 = (x37 + x56);
const x58 = (x35 + cast(u32, x36));
const x59 = (x34 + x58);
const x60 = (x33 + x59);
const x61 = (x31 + cast(u32, x32));
const x62 = (x30 + x61);
const x63 = (x29 + x62);
const x64 = (x27 + cast(u32, x28));
const x65 = (x26 + x64);
const x66 = (x25 + x65);
const x67 = (x23 + cast(u32, x24));
const x68 = (x22 + x67);
const x69 = (x21 + x68);
const x70 = (x19 + cast(u32, x20));
const x71 = (x18 + x70);
const x72 = (x17 + x71);
const x73 = (x15 + cast(u32, x16));
const x74 = (x14 + x73);
const x75 = (x13 + x74);
const x76 = (x11 + cast(u32, x12));
const x77 = (x10 + x76);
const x78 = (x9 + x77);
const x79 = (x7 + cast(u32, x8));
const x80 = (x6 + x79);
const x81 = (x5 + x80);
const x82 = (x3 + cast(u32, x4));
const x83 = (x2 + x82);
const x84 = (x1 + x83);
out1[0] = x51;
out1[1] = x54;
out1[2] = x57;
out1[3] = x60;
out1[4] = x63;
out1[5] = x66;
out1[6] = x69;
out1[7] = x72;
out1[8] = x75;
out1[9] = x78;
out1[10] = x81;
out1[11] = x84;
}
/// The function setOne returns the field element one in the Montgomery domain.
///
/// Postconditions:
/// eval (from_montgomery out1) mod m = 1 mod m
/// 0 ≤ eval out1 < m
///
pub fn setOne(out1: *MontgomeryDomainFieldElement) void {
@setRuntimeSafety(mode == .Debug);
out1[0] = cast(u32, 0x1);
out1[1] = 0xffffffff;
out1[2] = 0xffffffff;
out1[3] = cast(u32, 0x0);
out1[4] = cast(u32, 0x1);
out1[5] = cast(u32, 0x0);
out1[6] = cast(u32, 0x0);
out1[7] = cast(u32, 0x0);
out1[8] = cast(u32, 0x0);
out1[9] = cast(u32, 0x0);
out1[10] = cast(u32, 0x0);
out1[11] = cast(u32, 0x0);
}
/// The function msat returns the saturated representation of the prime modulus.
///
/// Postconditions:
/// twos_complement_eval out1 = m
/// 0 ≤ eval out1 < m
///
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn msat(out1: *[13]u32) void {
@setRuntimeSafety(mode == .Debug);
out1[0] = 0xffffffff;
out1[1] = cast(u32, 0x0);
out1[2] = cast(u32, 0x0);
out1[3] = 0xffffffff;
out1[4] = 0xfffffffe;
out1[5] = 0xffffffff;
out1[6] = 0xffffffff;
out1[7] = 0xffffffff;
out1[8] = 0xffffffff;
out1[9] = 0xffffffff;
out1[10] = 0xffffffff;
out1[11] = 0xffffffff;
out1[12] = cast(u32, 0x0);
}
/// The function divstep computes a divstep.
///
/// Preconditions:
/// 0 ≤ eval arg4 < m
/// 0 ≤ eval arg5 < m
/// Postconditions:
/// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1)
/// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2)
/// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋)
/// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m)
/// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m)
/// 0 ≤ eval out5 < m
/// 0 ≤ eval out5 < m
/// 0 ≤ eval out2 < m
/// 0 ≤ eval out3 < m
///
/// Input Bounds:
/// arg1: [0x0 ~> 0xffffffff]
/// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// arg5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// Output Bounds:
/// out1: [0x0 ~> 0xffffffff]
/// out2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// out3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// out4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
/// out5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn divstep(out1: *u32, out2: *[13]u32, out3: *[13]u32, out4: *[12]u32, out5: *[12]u32, arg1: u32, arg2: [13]u32, arg3: [13]u32, arg4: [12]u32, arg5: [12]u32) void {
@setRuntimeSafety(mode == .Debug);
var x1: u32 = undefined;
var x2: u1 = undefined;
addcarryxU32(&x1, &x2, 0x0, (~arg1), cast(u32, 0x1));
const x3 = (cast(u1, (x1 >> 31)) & cast(u1, ((arg3[0]) & cast(u32, 0x1))));
var x4: u32 = undefined;
var x5: u1 = undefined;
addcarryxU32(&x4, &x5, 0x0, (~arg1), cast(u32, 0x1));
var x6: u32 = undefined;
cmovznzU32(&x6, x3, arg1, x4);
var x7: u32 = undefined;
cmovznzU32(&x7, x3, (arg2[0]), (arg3[0]));
var x8: u32 = undefined;
cmovznzU32(&x8, x3, (arg2[1]), (arg3[1]));
var x9: u32 = undefined;
cmovznzU32(&x9, x3, (arg2[2]), (arg3[2]));
var x10: u32 = undefined;
cmovznzU32(&x10, x3, (arg2[3]), (arg3[3]));
var x11: u32 = undefined;
cmovznzU32(&x11, x3, (arg2[4]), (arg3[4]));
var x12: u32 = undefined;
cmovznzU32(&x12, x3, (arg2[5]), (arg3[5]));
var x13: u32 = undefined;
cmovznzU32(&x13, x3, (arg2[6]), (arg3[6]));
var x14: u32 = undefined;
cmovznzU32(&x14, x3, (arg2[7]), (arg3[7]));
var x15: u32 = undefined;
cmovznzU32(&x15, x3, (arg2[8]), (arg3[8]));
var x16: u32 = undefined;
cmovznzU32(&x16, x3, (arg2[9]), (arg3[9]));
var x17: u32 = undefined;
cmovznzU32(&x17, x3, (arg2[10]), (arg3[10]));
var x18: u32 = undefined;
cmovznzU32(&x18, x3, (arg2[11]), (arg3[11]));
var x19: u32 = undefined;
cmovznzU32(&x19, x3, (arg2[12]), (arg3[12]));
var x20: u32 = undefined;
var x21: u1 = undefined;
addcarryxU32(&x20, &x21, 0x0, cast(u32, 0x1), (~(arg2[0])));
var x22: u32 = undefined;
var x23: u1 = undefined;
addcarryxU32(&x22, &x23, x21, cast(u32, 0x0), (~(arg2[1])));
var x24: u32 = undefined;
var x25: u1 = undefined;
addcarryxU32(&x24, &x25, x23, cast(u32, 0x0), (~(arg2[2])));
var x26: u32 = undefined;
var x27: u1 = undefined;
addcarryxU32(&x26, &x27, x25, cast(u32, 0x0), (~(arg2[3])));
var x28: u32 = undefined;
var x29: u1 = undefined;
addcarryxU32(&x28, &x29, x27, cast(u32, 0x0), (~(arg2[4])));
var x30: u32 = undefined;
var x31: u1 = undefined;
addcarryxU32(&x30, &x31, x29, cast(u32, 0x0), (~(arg2[5])));
var x32: u32 = undefined;
var x33: u1 = undefined;
addcarryxU32(&x32, &x33, x31, cast(u32, 0x0), (~(arg2[6])));
var x34: u32 = undefined;
var x35: u1 = undefined;
addcarryxU32(&x34, &x35, x33, cast(u32, 0x0), (~(arg2[7])));
var x36: u32 = undefined;
var x37: u1 = undefined;
addcarryxU32(&x36, &x37, x35, cast(u32, 0x0), (~(arg2[8])));
var x38: u32 = undefined;
var x39: u1 = undefined;
addcarryxU32(&x38, &x39, x37, cast(u32, 0x0), (~(arg2[9])));
var x40: u32 = undefined;
var x41: u1 = undefined;
addcarryxU32(&x40, &x41, x39, cast(u32, 0x0), (~(arg2[10])));
var x42: u32 = undefined;
var x43: u1 = undefined;
addcarryxU32(&x42, &x43, x41, cast(u32, 0x0), (~(arg2[11])));
var x44: u32 = undefined;
var x45: u1 = undefined;
addcarryxU32(&x44, &x45, x43, cast(u32, 0x0), (~(arg2[12])));
var x46: u32 = undefined;
cmovznzU32(&x46, x3, (arg3[0]), x20);
var x47: u32 = undefined;
cmovznzU32(&x47, x3, (arg3[1]), x22);
var x48: u32 = undefined;
cmovznzU32(&x48, x3, (arg3[2]), x24);
var x49: u32 = undefined;
cmovznzU32(&x49, x3, (arg3[3]), x26);
var x50: u32 = undefined;
cmovznzU32(&x50, x3, (arg3[4]), x28);
var x51: u32 = undefined;
cmovznzU32(&x51, x3, (arg3[5]), x30);
var x52: u32 = undefined;
cmovznzU32(&x52, x3, (arg3[6]), x32);
var x53: u32 = undefined;
cmovznzU32(&x53, x3, (arg3[7]), x34);
var x54: u32 = undefined;
cmovznzU32(&x54, x3, (arg3[8]), x36);
var x55: u32 = undefined;
cmovznzU32(&x55, x3, (arg3[9]), x38);
var x56: u32 = undefined;
cmovznzU32(&x56, x3, (arg3[10]), x40);
var x57: u32 = undefined;
cmovznzU32(&x57, x3, (arg3[11]), x42);
var x58: u32 = undefined;
cmovznzU32(&x58, x3, (arg3[12]), x44);
var x59: u32 = undefined;
cmovznzU32(&x59, x3, (arg4[0]), (arg5[0]));
var x60: u32 = undefined;
cmovznzU32(&x60, x3, (arg4[1]), (arg5[1]));
var x61: u32 = undefined;
cmovznzU32(&x61, x3, (arg4[2]), (arg5[2]));
var x62: u32 = undefined;
cmovznzU32(&x62, x3, (arg4[3]), (arg5[3]));
var x63: u32 = undefined;
cmovznzU32(&x63, x3, (arg4[4]), (arg5[4]));
var x64: u32 = undefined;
cmovznzU32(&x64, x3, (arg4[5]), (arg5[5]));
var x65: u32 = undefined;
cmovznzU32(&x65, x3, (arg4[6]), (arg5[6]));
var x66: u32 = undefined;
cmovznzU32(&x66, x3, (arg4[7]), (arg5[7]));
var x67: u32 = undefined;
cmovznzU32(&x67, x3, (arg4[8]), (arg5[8]));
var x68: u32 = undefined;
cmovznzU32(&x68, x3, (arg4[9]), (arg5[9]));
var x69: u32 = undefined;
cmovznzU32(&x69, x3, (arg4[10]), (arg5[10]));
var x70: u32 = undefined;
cmovznzU32(&x70, x3, (arg4[11]), (arg5[11]));
var x71: u32 = undefined;
var x72: u1 = undefined;
addcarryxU32(&x71, &x72, 0x0, x59, x59);
var x73: u32 = undefined;
var x74: u1 = undefined;
addcarryxU32(&x73, &x74, x72, x60, x60);
var x75: u32 = undefined;
var x76: u1 = undefined;
addcarryxU32(&x75, &x76, x74, x61, x61);
var x77: u32 = undefined;
var x78: u1 = undefined;
addcarryxU32(&x77, &x78, x76, x62, x62);
var x79: u32 = undefined;
var x80: u1 = undefined;
addcarryxU32(&x79, &x80, x78, x63, x63);
var x81: u32 = undefined;
var x82: u1 = undefined;
addcarryxU32(&x81, &x82, x80, x64, x64);
var x83: u32 = undefined;
var x84: u1 = undefined;
addcarryxU32(&x83, &x84, x82, x65, x65);
var x85: u32 = undefined;
var x86: u1 = undefined;
addcarryxU32(&x85, &x86, x84, x66, x66);
var x87: u32 = undefined;
var x88: u1 = undefined;
addcarryxU32(&x87, &x88, x86, x67, x67);
var x89: u32 = undefined;
var x90: u1 = undefined;
addcarryxU32(&x89, &x90, x88, x68, x68);
var x91: u32 = undefined;
var x92: u1 = undefined;
addcarryxU32(&x91, &x92, x90, x69, x69);
var x93: u32 = undefined;
var x94: u1 = undefined;
addcarryxU32(&x93, &x94, x92, x70, x70);
var x95: u32 = undefined;
var x96: u1 = undefined;
subborrowxU32(&x95, &x96, 0x0, x71, 0xffffffff);
var x97: u32 = undefined;
var x98: u1 = undefined;
subborrowxU32(&x97, &x98, x96, x73, cast(u32, 0x0));
var x99: u32 = undefined;
var x100: u1 = undefined;
subborrowxU32(&x99, &x100, x98, x75, cast(u32, 0x0));
var x101: u32 = undefined;
var x102: u1 = undefined;
subborrowxU32(&x101, &x102, x100, x77, 0xffffffff);
var x103: u32 = undefined;
var x104: u1 = undefined;
subborrowxU32(&x103, &x104, x102, x79, 0xfffffffe);
var x105: u32 = undefined;
var x106: u1 = undefined;
subborrowxU32(&x105, &x106, x104, x81, 0xffffffff);
var x107: u32 = undefined;
var x108: u1 = undefined;
subborrowxU32(&x107, &x108, x106, x83, 0xffffffff);
var x109: u32 = undefined;
var x110: u1 = undefined;
subborrowxU32(&x109, &x110, x108, x85, 0xffffffff);
var x111: u32 = undefined;
var x112: u1 = undefined;
subborrowxU32(&x111, &x112, x110, x87, 0xffffffff);
var x113: u32 = undefined;
var x114: u1 = undefined;
subborrowxU32(&x113, &x114, x112, x89, 0xffffffff);
var x115: u32 = undefined;
var x116: u1 = undefined;
subborrowxU32(&x115, &x116, x114, x91, 0xffffffff);
var x117: u32 = undefined;
var x118: u1 = undefined;
subborrowxU32(&x117, &x118, x116, x93, 0xffffffff);
var x119: u32 = undefined;
var x120: u1 = undefined;
subborrowxU32(&x119, &x120, x118, cast(u32, x94), cast(u32, 0x0));
const x121 = (arg4[11]);
const x122 = (arg4[10]);
const x123 = (arg4[9]);
const x124 = (arg4[8]);
const x125 = (arg4[7]);
const x126 = (arg4[6]);
const x127 = (arg4[5]);
const x128 = (arg4[4]);
const x129 = (arg4[3]);
const x130 = (arg4[2]);
const x131 = (arg4[1]);
const x132 = (arg4[0]);
var x133: u32 = undefined;
var x134: u1 = undefined;
subborrowxU32(&x133, &x134, 0x0, cast(u32, 0x0), x132);
var x135: u32 = undefined;
var x136: u1 = undefined;
subborrowxU32(&x135, &x136, x134, cast(u32, 0x0), x131);
var x137: u32 = undefined;
var x138: u1 = undefined;
subborrowxU32(&x137, &x138, x136, cast(u32, 0x0), x130);
var x139: u32 = undefined;
var x140: u1 = undefined;
subborrowxU32(&x139, &x140, x138, cast(u32, 0x0), x129);
var x141: u32 = undefined;
var x142: u1 = undefined;
subborrowxU32(&x141, &x142, x140, cast(u32, 0x0), x128);
var x143: u32 = undefined;
var x144: u1 = undefined;
subborrowxU32(&x143, &x144, x142, cast(u32, 0x0), x127);
var x145: u32 = undefined;
var x146: u1 = undefined;
subborrowxU32(&x145, &x146, x144, cast(u32, 0x0), x126);
var x147: u32 = undefined;
var x148: u1 = undefined;
subborrowxU32(&x147, &x148, x146, cast(u32, 0x0), x125);
var x149: u32 = undefined;
var x150: u1 = undefined;
subborrowxU32(&x149, &x150, x148, cast(u32, 0x0), x124);
var x151: u32 = undefined;
var x152: u1 = undefined;
subborrowxU32(&x151, &x152, x150, cast(u32, 0x0), x123);
var x153: u32 = undefined;
var x154: u1 = undefined;
subborrowxU32(&x153, &x154, x152, cast(u32, 0x0), x122);
var x155: u32 = undefined;
var x156: u1 = undefined;
subborrowxU32(&x155, &x156, x154, cast(u32, 0x0), x121);
var x157: u32 = undefined;
cmovznzU32(&x157, x156, cast(u32, 0x0), 0xffffffff);
var x158: u32 = undefined;
var x159: u1 = undefined;
addcarryxU32(&x158, &x159, 0x0, x133, x157);
var x160: u32 = undefined;
var x161: u1 = undefined;
addcarryxU32(&x160, &x161, x159, x135, cast(u32, 0x0));
var x162: u32 = undefined;
var x163: u1 = undefined;
addcarryxU32(&x162, &x163, x161, x137, cast(u32, 0x0));
var x164: u32 = undefined;
var x165: u1 = undefined;
addcarryxU32(&x164, &x165, x163, x139, x157);
var x166: u32 = undefined;
var x167: u1 = undefined;
addcarryxU32(&x166, &x167, x165, x141, (x157 & 0xfffffffe));
var x168: u32 = undefined;
var x169: u1 = undefined;
addcarryxU32(&x168, &x169, x167, x143, x157);
var x170: u32 = undefined;
var x171: u1 = undefined;
addcarryxU32(&x170, &x171, x169, x145, x157);
var x172: u32 = undefined;
var x173: u1 = undefined;
addcarryxU32(&x172, &x173, x171, x147, x157);
var x174: u32 = undefined;
var x175: u1 = undefined;
addcarryxU32(&x174, &x175, x173, x149, x157);
var x176: u32 = undefined;
var x177: u1 = undefined;
addcarryxU32(&x176, &x177, x175, x151, x157);
var x178: u32 = undefined;
var x179: u1 = undefined;
addcarryxU32(&x178, &x179, x177, x153, x157);
var x180: u32 = undefined;
var x181: u1 = undefined;
addcarryxU32(&x180, &x181, x179, x155, x157);
var x182: u32 = undefined;
cmovznzU32(&x182, x3, (arg5[0]), x158);
var x183: u32 = undefined;
cmovznzU32(&x183, x3, (arg5[1]), x160);
var x184: u32 = undefined;
cmovznzU32(&x184, x3, (arg5[2]), x162);
var x185: u32 = undefined;
cmovznzU32(&x185, x3, (arg5[3]), x164);
var x186: u32 = undefined;
cmovznzU32(&x186, x3, (arg5[4]), x166);
var x187: u32 = undefined;
cmovznzU32(&x187, x3, (arg5[5]), x168);
var x188: u32 = undefined;
cmovznzU32(&x188, x3, (arg5[6]), x170);
var x189: u32 = undefined;
cmovznzU32(&x189, x3, (arg5[7]), x172);
var x190: u32 = undefined;
cmovznzU32(&x190, x3, (arg5[8]), x174);
var x191: u32 = undefined;
cmovznzU32(&x191, x3, (arg5[9]), x176);
var x192: u32 = undefined;
cmovznzU32(&x192, x3, (arg5[10]), x178);
var x193: u32 = undefined;
cmovznzU32(&x193, x3, (arg5[11]), x180);
const x194 = cast(u1, (x46 & cast(u32, 0x1)));
var x195: u32 = undefined;
cmovznzU32(&x195, x194, cast(u32, 0x0), x7);
var x196: u32 = undefined;
cmovznzU32(&x196, x194, cast(u32, 0x0), x8);
var x197: u32 = undefined;
cmovznzU32(&x197, x194, cast(u32, 0x0), x9);
var x198: u32 = undefined;
cmovznzU32(&x198, x194, cast(u32, 0x0), x10);
var x199: u32 = undefined;
cmovznzU32(&x199, x194, cast(u32, 0x0), x11);
var x200: u32 = undefined;
cmovznzU32(&x200, x194, cast(u32, 0x0), x12);
var x201: u32 = undefined;
cmovznzU32(&x201, x194, cast(u32, 0x0), x13);
var x202: u32 = undefined;
cmovznzU32(&x202, x194, cast(u32, 0x0), x14);
var x203: u32 = undefined;
cmovznzU32(&x203, x194, cast(u32, 0x0), x15);
var x204: u32 = undefined;
cmovznzU32(&x204, x194, cast(u32, 0x0), x16);
var x205: u32 = undefined;
cmovznzU32(&x205, x194, cast(u32, 0x0), x17);
var x206: u32 = undefined;
cmovznzU32(&x206, x194, cast(u32, 0x0), x18);
var x207: u32 = undefined;
cmovznzU32(&x207, x194, cast(u32, 0x0), x19);
var x208: u32 = undefined;
var x209: u1 = undefined;
addcarryxU32(&x208, &x209, 0x0, x46, x195);
var x210: u32 = undefined;
var x211: u1 = undefined;
addcarryxU32(&x210, &x211, x209, x47, x196);
var x212: u32 = undefined;
var x213: u1 = undefined;
addcarryxU32(&x212, &x213, x211, x48, x197);
var x214: u32 = undefined;
var x215: u1 = undefined;
addcarryxU32(&x214, &x215, x213, x49, x198);
var x216: u32 = undefined;
var x217: u1 = undefined;
addcarryxU32(&x216, &x217, x215, x50, x199);
var x218: u32 = undefined;
var x219: u1 = undefined;
addcarryxU32(&x218, &x219, x217, x51, x200);
var x220: u32 = undefined;
var x221: u1 = undefined;
addcarryxU32(&x220, &x221, x219, x52, x201);
var x222: u32 = undefined;
var x223: u1 = undefined;
addcarryxU32(&x222, &x223, x221, x53, x202);
var x224: u32 = undefined;
var x225: u1 = undefined;
addcarryxU32(&x224, &x225, x223, x54, x203);
var x226: u32 = undefined;
var x227: u1 = undefined;
addcarryxU32(&x226, &x227, x225, x55, x204);
var x228: u32 = undefined;
var x229: u1 = undefined;
addcarryxU32(&x228, &x229, x227, x56, x205);
var x230: u32 = undefined;
var x231: u1 = undefined;
addcarryxU32(&x230, &x231, x229, x57, x206);
var x232: u32 = undefined;
var x233: u1 = undefined;
addcarryxU32(&x232, &x233, x231, x58, x207);
var x234: u32 = undefined;
cmovznzU32(&x234, x194, cast(u32, 0x0), x59);
var x235: u32 = undefined;
cmovznzU32(&x235, x194, cast(u32, 0x0), x60);
var x236: u32 = undefined;
cmovznzU32(&x236, x194, cast(u32, 0x0), x61);
var x237: u32 = undefined;
cmovznzU32(&x237, x194, cast(u32, 0x0), x62);
var x238: u32 = undefined;
cmovznzU32(&x238, x194, cast(u32, 0x0), x63);
var x239: u32 = undefined;
cmovznzU32(&x239, x194, cast(u32, 0x0), x64);
var x240: u32 = undefined;
cmovznzU32(&x240, x194, cast(u32, 0x0), x65);
var x241: u32 = undefined;
cmovznzU32(&x241, x194, cast(u32, 0x0), x66);
var x242: u32 = undefined;
cmovznzU32(&x242, x194, cast(u32, 0x0), x67);
var x243: u32 = undefined;
cmovznzU32(&x243, x194, cast(u32, 0x0), x68);
var x244: u32 = undefined;
cmovznzU32(&x244, x194, cast(u32, 0x0), x69);
var x245: u32 = undefined;
cmovznzU32(&x245, x194, cast(u32, 0x0), x70);
var x246: u32 = undefined;
var x247: u1 = undefined;
addcarryxU32(&x246, &x247, 0x0, x182, x234);
var x248: u32 = undefined;
var x249: u1 = undefined;
addcarryxU32(&x248, &x249, x247, x183, x235);
var x250: u32 = undefined;
var x251: u1 = undefined;
addcarryxU32(&x250, &x251, x249, x184, x236);
var x252: u32 = undefined;
var x253: u1 = undefined;
addcarryxU32(&x252, &x253, x251, x185, x237);
var x254: u32 = undefined;
var x255: u1 = undefined;
addcarryxU32(&x254, &x255, x253, x186, x238);
var x256: u32 = undefined;
var x257: u1 = undefined;
addcarryxU32(&x256, &x257, x255, x187, x239);
var x258: u32 = undefined;
var x259: u1 = undefined;
addcarryxU32(&x258, &x259, x257, x188, x240);
var x260: u32 = undefined;
var x261: u1 = undefined;
addcarryxU32(&x260, &x261, x259, x189, x241);
var x262: u32 = undefined;
var x263: u1 = undefined;
addcarryxU32(&x262, &x263, x261, x190, x242);
var x264: u32 = undefined;
var x265: u1 = undefined;
addcarryxU32(&x264, &x265, x263, x191, x243);
var x266: u32 = undefined;
var x267: u1 = undefined;
addcarryxU32(&x266, &x267, x265, x192, x244);
var x268: u32 = undefined;
var x269: u1 = undefined;
addcarryxU32(&x268, &x269, x267, x193, x245);
var x270: u32 = undefined;
var x271: u1 = undefined;
subborrowxU32(&x270, &x271, 0x0, x246, 0xffffffff);
var x272: u32 = undefined;
var x273: u1 = undefined;
subborrowxU32(&x272, &x273, x271, x248, cast(u32, 0x0));
var x274: u32 = undefined;
var x275: u1 = undefined;
subborrowxU32(&x274, &x275, x273, x250, cast(u32, 0x0));
var x276: u32 = undefined;
var x277: u1 = undefined;
subborrowxU32(&x276, &x277, x275, x252, 0xffffffff);
var x278: u32 = undefined;
var x279: u1 = undefined;
subborrowxU32(&x278, &x279, x277, x254, 0xfffffffe);
var x280: u32 = undefined;
var x281: u1 = undefined;
subborrowxU32(&x280, &x281, x279, x256, 0xffffffff);
var x282: u32 = undefined;
var x283: u1 = undefined;
subborrowxU32(&x282, &x283, x281, x258, 0xffffffff);
var x284: u32 = undefined;
var x285: u1 = undefined;
subborrowxU32(&x284, &x285, x283, x260, 0xffffffff);
var x286: u32 = undefined;
var x287: u1 = undefined;
subborrowxU32(&x286, &x287, x285, x262, 0xffffffff);
var x288: u32 = undefined;
var x289: u1 = undefined;
subborrowxU32(&x288, &x289, x287, x264, 0xffffffff);
var x290: u32 = undefined;
var x291: u1 = undefined;
subborrowxU32(&x290, &x291, x289, x266, 0xffffffff);
var x292: u32 = undefined;
var x293: u1 = undefined;
subborrowxU32(&x292, &x293, x291, x268, 0xffffffff);
var x294: u32 = undefined;
var x295: u1 = undefined;
subborrowxU32(&x294, &x295, x293, cast(u32, x269), cast(u32, 0x0));
var x296: u32 = undefined;
var x297: u1 = undefined;
addcarryxU32(&x296, &x297, 0x0, x6, cast(u32, 0x1));
const x298 = ((x208 >> 1) | ((x210 << 31) & 0xffffffff));
const x299 = ((x210 >> 1) | ((x212 << 31) & 0xffffffff));
const x300 = ((x212 >> 1) | ((x214 << 31) & 0xffffffff));
const x301 = ((x214 >> 1) | ((x216 << 31) & 0xffffffff));
const x302 = ((x216 >> 1) | ((x218 << 31) & 0xffffffff));
const x303 = ((x218 >> 1) | ((x220 << 31) & 0xffffffff));
const x304 = ((x220 >> 1) | ((x222 << 31) & 0xffffffff));
const x305 = ((x222 >> 1) | ((x224 << 31) & 0xffffffff));
const x306 = ((x224 >> 1) | ((x226 << 31) & 0xffffffff));
const x307 = ((x226 >> 1) | ((x228 << 31) & 0xffffffff));
const x308 = ((x228 >> 1) | ((x230 << 31) & 0xffffffff));
const x309 = ((x230 >> 1) | ((x232 << 31) & 0xffffffff));
const x310 = ((x232 & 0x80000000) | (x232 >> 1));
var x311: u32 = undefined;
cmovznzU32(&x311, x120, x95, x71);
var x312: u32 = undefined;
cmovznzU32(&x312, x120, x97, x73);
var x313: u32 = undefined;
cmovznzU32(&x313, x120, x99, x75);
var x314: u32 = undefined;
cmovznzU32(&x314, x120, x101, x77);
var x315: u32 = undefined;
cmovznzU32(&x315, x120, x103, x79);
var x316: u32 = undefined;
cmovznzU32(&x316, x120, x105, x81);
var x317: u32 = undefined;
cmovznzU32(&x317, x120, x107, x83);
var x318: u32 = undefined;
cmovznzU32(&x318, x120, x109, x85);
var x319: u32 = undefined;
cmovznzU32(&x319, x120, x111, x87);
var x320: u32 = undefined;
cmovznzU32(&x320, x120, x113, x89);
var x321: u32 = undefined;
cmovznzU32(&x321, x120, x115, x91);
var x322: u32 = undefined;
cmovznzU32(&x322, x120, x117, x93);
var x323: u32 = undefined;
cmovznzU32(&x323, x295, x270, x246);
var x324: u32 = undefined;
cmovznzU32(&x324, x295, x272, x248);
var x325: u32 = undefined;
cmovznzU32(&x325, x295, x274, x250);
var x326: u32 = undefined;
cmovznzU32(&x326, x295, x276, x252);
var x327: u32 = undefined;
cmovznzU32(&x327, x295, x278, x254);
var x328: u32 = undefined;
cmovznzU32(&x328, x295, x280, x256);
var x329: u32 = undefined;
cmovznzU32(&x329, x295, x282, x258);
var x330: u32 = undefined;
cmovznzU32(&x330, x295, x284, x260);
var x331: u32 = undefined;
cmovznzU32(&x331, x295, x286, x262);
var x332: u32 = undefined;
cmovznzU32(&x332, x295, x288, x264);
var x333: u32 = undefined;
cmovznzU32(&x333, x295, x290, x266);
var x334: u32 = undefined;
cmovznzU32(&x334, x295, x292, x268);
out1.* = x296;
out2[0] = x7;
out2[1] = x8;
out2[2] = x9;
out2[3] = x10;
out2[4] = x11;
out2[5] = x12;
out2[6] = x13;
out2[7] = x14;
out2[8] = x15;
out2[9] = x16;
out2[10] = x17;
out2[11] = x18;
out2[12] = x19;
out3[0] = x298;
out3[1] = x299;
out3[2] = x300;
out3[3] = x301;
out3[4] = x302;
out3[5] = x303;
out3[6] = x304;
out3[7] = x305;
out3[8] = x306;
out3[9] = x307;
out3[10] = x308;
out3[11] = x309;
out3[12] = x310;
out4[0] = x311;
out4[1] = x312;
out4[2] = x313;
out4[3] = x314;
out4[4] = x315;
out4[5] = x316;
out4[6] = x317;
out4[7] = x318;
out4[8] = x319;
out4[9] = x320;
out4[10] = x321;
out4[11] = x322;
out5[0] = x323;
out5[1] = x324;
out5[2] = x325;
out5[3] = x326;
out5[4] = x327;
out5[5] = x328;
out5[6] = x329;
out5[7] = x330;
out5[8] = x331;
out5[9] = x332;
out5[10] = x333;
out5[11] = x334;
}
/// The function divstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form).
///
/// Postconditions:
/// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if ⌊log2 m⌋ + 1 < 46 then ⌊(49 * (⌊log2 m⌋ + 1) + 80) / 17⌋ else ⌊(49 * (⌊log2 m⌋ + 1) + 57) / 17⌋)
/// 0 ≤ eval out1 < m
///
/// Output Bounds:
/// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]]
pub fn divstepPrecomp(out1: *[12]u32) void {
@setRuntimeSafety(mode == .Debug);
out1[0] = 0xfff18fff;
out1[1] = 0xfff69400;
out1[2] = 0xffffd3ff;
out1[3] = 0x2b7fe;
out1[4] = 0xfffe97ff;
out1[5] = 0xfffedbff;
out1[6] = 0x2fff;
out1[7] = 0x28400;
out1[8] = 0x50400;
out1[9] = 0x60400;
out1[10] = 0x38000;
out1[11] = 0xfffc4800;
} | fiat-zig/src/p384_32.zig |
pub const XTRIM = struct {
key: []const u8,
strategy: Strategy,
/// Instantiates a new XTRIM command.
pub fn init(key: []const u8, strategy: Strategy) XTRIM {
return .{ .key = key, .strategy = strategy };
}
/// Validates if the command is syntactically correct.
pub fn validate(self: XTRIM) !void {
if (self.key.len == 0) return error.EmptyKeyName;
}
pub const RedisCommand = struct {
pub fn serialize(self: XTRIM, comptime rootSerializer: type, msg: anytype) !void {
return rootSerializer.serializeCommand(msg, .{ "XTRIM", self.key, self.strategy });
}
};
pub const Strategy = union(enum) {
MaxLen: struct {
precise: bool = false,
count: u64,
},
pub const RedisArguments = struct {
pub fn count(self: Strategy) usize {
switch (self) {
.MaxLen => |m| if (!m.precise) {
return 3;
} else {
return 2;
},
}
}
pub fn serialize(self: Strategy, comptime rootSerializer: type, msg: anytype) !void {
switch (self) {
.MaxLen => |m| {
try rootSerializer.serializeArgument(msg, []const u8, "MAXLEN");
if (!m.precise) try rootSerializer.serializeArgument(msg, []const u8, "~");
try rootSerializer.serializeArgument(msg, u64, m.count);
},
}
}
};
};
};
test "basic usage" {
const cmd = XTRIM.init("mykey", XTRIM.Strategy{ .MaxLen = .{ .count = 10 } });
}
test "serializer" {
const std = @import("std");
const serializer = @import("../../serializer.zig").CommandSerializer;
var correctBuf: [1000]u8 = undefined;
var correctMsg = std.io.fixedBufferStream(correctBuf[0..]);
var testBuf: [1000]u8 = undefined;
var testMsg = std.io.fixedBufferStream(testBuf[0..]);
{
correctMsg.reset();
testMsg.reset();
try serializer.serializeCommand(
testMsg.outStream(),
XTRIM.init("mykey", XTRIM.Strategy{ .MaxLen = .{ .count = 30 } }),
);
try serializer.serializeCommand(
correctMsg.outStream(),
.{ "XTRIM", "mykey", "MAXLEN", "~", 30 },
);
std.testing.expectEqualSlices(u8, correctMsg.getWritten(), testMsg.getWritten());
}
} | src/commands/streams/xtrim.zig |
const std = @import("std");
const win = std.os.windows;
const W = std.unicode.utf8ToUtf16LeStringLiteral;
const vk = @import("vk_codes.zig");
const DWORD = win.DWORD;
const ULONG_PTR = win.ULONG_PTR;
const HWND = win.HWND;
const WINAPI = win.WINAPI;
const HANDLE = win.HANDLE;
const WPARAM = win.WPARAM;
const LPARAM = win.LPARAM;
const LRESULT = win.LRESULT;
const HMODULE = win.HMODULE;
const BOOL = win.BOOL;
const INVALID_HANDLE_VALUE = win.INVALID_HANDLE_VALUE;
const WH_KEYBOARD_LL = 13;
const HHOOK = HANDLE;
// typedef LRESULT (CALLBACK *HOOKPROC) (int code, WPARAM wParam, LPARAM lParam)
const HOOKPROC = fn (nCode: c_int, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT;
extern "kernel32" fn GetConsoleWindow() callconv(WINAPI) ?HWND;
extern "user32" fn SetWindowsHookExW(idHook: c_int, lpfn: HOOKPROC, hmod: ?HMODULE, dwThreadId: DWORD) callconv(WINAPI) ?HHOOK;
extern "user32" fn UnhookWindowsHookEx(hhk: ?HHOOK) callconv(WINAPI) BOOL;
extern "user32" fn CallNextHookEx(hhk: HHOOK, nCode: c_int, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT;
const KBDLLHOOKSTRUCT = extern struct {
vkCode: DWORD,
scanCode: DWORD,
flags: DWORD,
time: DWORD,
dwExtraInfo: ULONG_PTR,
};
var global_hook: HHOOK = INVALID_HANDLE_VALUE;
pub fn main() anyerror!void {
if (SetWindowsHookExW(WH_KEYBOARD_LL, LowLevelKeyboardProc, win.kernel32.GetModuleHandleW(null), 0)) |hook| {
global_hook = hook;
}
if (global_hook == INVALID_HANDLE_VALUE) {
std.log.emerg("failed to install hook.", .{});
return error.HookInstallFailed;
}
if (GetConsoleWindow()) |console_window| {
_ = win.user32.ShowWindow(console_window, win.user32.SW_HIDE);
}
std.log.info("hook is installed.", .{});
defer _ = UnhookWindowsHookEx(global_hook);
_ = try win.user32.messageBoxW(null, W("Zum Beenden auf 'OK' drücken"), W("Kindersicherung"), win.user32.MB_OK | win.user32.MB_ICONINFORMATION);
}
export fn LowLevelKeyboardProc(nCode: c_int, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT {
if (nCode >= 0) {
if (@intToPtr(?*KBDLLHOOKSTRUCT, @bitCast(usize, lParam))) |keyboard| {
std.log.debug("KB: {}", .{keyboard.*});
var allow = switch (keyboard.vkCode) {
vk.VK_BACK => true,
vk.VK_SPACE => true,
vk.VK_LEFT, vk.VK_UP, vk.VK_RIGHT, vk.VK_DOWN => true,
0x30...0x39 => true, // 0-9
0x41...0x5A => true, // A-Z
vk.VK_NUMPAD0...vk.VK_NUMPAD9 => true, // Numpad 0-9
vk.VK_ADD => true,
vk.VK_MULTIPLY => true,
vk.VK_SEPARATOR => true,
vk.VK_SUBTRACT => true,
vk.VK_DECIMAL => true,
vk.VK_DIVIDE => true,
vk.VK_SHIFT, vk.VK_LSHIFT, vk.VK_RSHIFT => true,
0xBA...0xF5 => true, // OEM specific
vk.VK_OEM_CLEAR => true,
else => false,
};
if (!allow) {
std.log.notice("INTERCEPT", .{});
return 1;
}
}
}
return CallNextHookEx(global_hook, nCode, wParam, lParam);
} | src/main.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const AutoHashMap = std.AutoHashMap;
const PriorityQueue = std.PriorityQueue;
const StringHashMap = std.StringHashMap;
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const trim = std.mem.trim;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/puzzle/day25.txt");
// const data = @embedFile("../data/test/day25.txt");
const Map = struct {
data: ArrayList(u8),
width: usize = 0,
height: usize = 0,
temp_allocator: *Allocator,
fn init(allocator: *Allocator, temp_allocator: *Allocator) Map {
return .{
.data = ArrayList(u8).init(allocator),
.temp_allocator = temp_allocator,
};
}
fn readLine(self: *Map, str: []const u8) void {
self.height += 1;
self.width = str.len;
self.data.ensureUnusedCapacity(str.len) catch unreachable;
var arena = self.data.unusedCapacitySlice();
self.data.items.len += str.len;
std.mem.copy(u8, arena, str);
}
fn deinit(self: *Map) void {
self.data.deinit();
}
fn printMap(self: *Map) void {
var row_idx: usize = 0;
while (row_idx < self.height) : (row_idx += 1) {
var r1 = row_idx * self.width;
var r2 = (row_idx + 1) * self.width;
print("{s}\n", .{self.data.items[r1..r2]});
}
print("\n", .{});
}
fn advance(self: *Map) bool {
var new_state = self.temp_allocator.alloc(u8, self.data.items.len) catch unreachable;
defer self.temp_allocator.free(new_state);
std.mem.copy(u8, new_state, self.data.items);
var moved = false;
for (self.data.items) |cell, idx| {
if (cell == '>') {
var x = idx / self.width;
var y = idx % self.width;
var new_y = (y + 1) % self.width;
var new_idx = x * self.width + new_y;
if (self.data.items[new_idx] == '.') {
new_state[idx] = '.';
new_state[new_idx] = '>';
moved = true;
}
}
}
if (moved) {
std.mem.copy(u8, self.data.items, new_state);
}
for (self.data.items) |cell, idx| {
if (cell == 'v') {
var x = idx / self.width;
var y = idx % self.width;
var new_x = (x + 1) % self.height;
var new_idx = new_x * self.width + y;
if (self.data.items[new_idx] == '.') {
new_state[idx] = '.';
new_state[new_idx] = 'v';
moved = true;
}
}
}
if (moved) {
std.mem.copy(u8, self.data.items, new_state);
}
return moved;
}
};
pub fn main() !void {
var map = Map.init(gpa, gpa);
defer map.deinit();
var lines = tokenize(data, "\n\r");
while (lines.next()) |line| {
map.readLine(line);
}
map.printMap();
var iterations: u64 = 1;
while (map.advance()) {
iterations += 1;
}
map.printMap();
print("{}\n", .{iterations});
} | src/day25.zig |
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const mem = std.mem;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
test "arrays" {
var array: [5]u32 = undefined;
var i: u32 = 0;
while (i < 5) {
array[i] = i + 1;
i = array[i];
}
i = 0;
var accumulator = @as(u32, 0);
while (i < 5) {
accumulator += array[i];
i += 1;
}
try expect(accumulator == 15);
try expect(getArrayLen(&array) == 5);
}
fn getArrayLen(a: []const u32) usize {
return a.len;
}
test "array init with mult" {
const a = 'a';
var i: [8]u8 = [2]u8{ a, 'b' } ** 4;
try expect(std.mem.eql(u8, &i, "abababab"));
var j: [4]u8 = [1]u8{'a'} ** 4;
try expect(std.mem.eql(u8, &j, "aaaa"));
}
test "array literal with explicit type" {
const hex_mult: [4]u16 = .{ 4096, 256, 16, 1 };
try expect(hex_mult.len == 4);
try expect(hex_mult[1] == 256);
}
test "array literal with inferred length" {
const hex_mult = [_]u16{ 4096, 256, 16, 1 };
try expect(hex_mult.len == 4);
try expect(hex_mult[1] == 256);
}
test "array dot len const expr" {
try expect(comptime x: {
break :x some_array.len == 4;
});
}
const ArrayDotLenConstExpr = struct {
y: [some_array.len]u8,
};
const some_array = [_]u8{ 0, 1, 2, 3 };
test "array literal with specified size" {
var array = [2]u8{ 1, 2 };
try expect(array[0] == 1);
try expect(array[1] == 2);
}
test "array len field" {
var arr = [4]u8{ 0, 0, 0, 0 };
var ptr = &arr;
try expect(arr.len == 4);
comptime try expect(arr.len == 4);
try expect(ptr.len == 4);
comptime try expect(ptr.len == 4);
}
test "array with sentinels" {
const S = struct {
fn doTheTest(is_ct: bool) !void {
if (is_ct or builtin.zig_is_stage2) {
var zero_sized: [0:0xde]u8 = [_:0xde]u8{};
// Stage1 test coverage disabled at runtime because of
// https://github.com/ziglang/zig/issues/4372
try expect(zero_sized[0] == 0xde);
var reinterpreted = @ptrCast(*[1]u8, &zero_sized);
try expect(reinterpreted[0] == 0xde);
}
var arr: [3:0x55]u8 = undefined;
// Make sure the sentinel pointer is pointing after the last element.
if (!is_ct) {
const sentinel_ptr = @ptrToInt(&arr[3]);
const last_elem_ptr = @ptrToInt(&arr[2]);
try expect((sentinel_ptr - last_elem_ptr) == 1);
}
// Make sure the sentinel is writeable.
arr[3] = 0x55;
}
};
try S.doTheTest(false);
comptime try S.doTheTest(true);
}
test "void arrays" {
var array: [4]void = undefined;
array[0] = void{};
array[1] = array[2];
try expect(@sizeOf(@TypeOf(array)) == 0);
try expect(array.len == 4);
} | test/behavior/array.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const int = i64;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day08.txt");
fn segmentMask(str: []const u8) u7 {
var set = std.StaticBitSet(7).initEmpty();
for (str) |chr| {
set.set(chr - 'a');
}
return set.mask;
}
pub fn main() !void {
var part1: int = 0;
var part2: int = 0;
var lines = tokenize(u8, data, "\r\n");
while (lines.next()) |line| {
if (line.len == 0) { continue; }
var parts = tokenize(u8, line, " |");
var four: u7 = undefined;
var seven: u7 = undefined;
var i: usize = 0;
while (i < 10) : (i += 1) {
const str = parts.next().?;
if (str.len == 4) four = segmentMask(str);
if (str.len == 3) seven = segmentMask(str);
}
i = 0;
var num: int = 0;
while (i < 4) : (i += 1) {
const str = parts.next().?;
const digit: int = switch (str.len) {
2 => blk: { part1 += 1; break :blk @as(int, 1); },
3 => blk: { part1 += 1; break :blk @as(int, 7); },
4 => blk: { part1 += 1; break :blk @as(int, 4); },
7 => blk: { part1 += 1; break :blk @as(int, 8); },
5 => blk: {
const mask = segmentMask(str);
break :blk if (mask & seven == seven) @as(int, 3)
else if (@popCount(u7, mask & four) == 3) @as(int, 5)
else @as(int, 2);
},
6 => blk: {
const mask = segmentMask(str);
break :blk if (mask & four == four) @as(int, 9)
else if (mask & seven == seven) @as(int, 0)
else @as(int, 6);
},
else => unreachable,
};
num = num * 10 + digit;
}
part2 += @intCast(int, num);
assert(parts.next() == null);
}
print("part1={}, part2={}\n", .{part1, part2});
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const eql = std.mem.eql;
const parseEnum = std.meta.stringToEnum;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc; | src/day08.zig |
const std = @import("std");
const Location = @import("Location.zig");
const GenericToken = @import("token.zig").Token;
pub const Matcher = fn (str: []const u8) ?usize;
pub fn Pattern(comptime TokenType: type) type {
return struct {
const Self = @This();
type: TokenType,
match: Matcher,
pub fn create(token_type: TokenType, match: Matcher) Self {
return Self{
.type = token_type,
.match = match,
};
}
};
}
pub fn Tokenizer(comptime TokenTypeT: type, comptime patterns: []const Pattern(TokenTypeT)) type {
return struct {
const Self = @This();
pub const Token = GenericToken(TokenTypeT);
pub const TokenType = TokenTypeT;
pub const State = struct {
offset: usize,
location: Location,
};
pub const Error = NextError;
source: []const u8,
offset: usize,
current_location: Location,
pub fn init(source: []const u8) Self {
return Self{
.source = source,
.offset = 0,
.current_location = Location{
.source = null,
.line = 1,
.column = 1,
},
};
}
pub fn saveState(self: Self) State {
return State{
.offset = self.offset,
.location = self.current_location,
};
}
pub fn restoreState(self: *Self, state: State) void {
self.offset = state.offset;
self.current_location = state.location;
}
pub const NextError = error{UnexpectedCharacter};
pub fn next(self: *Self) NextError!?Token {
const rest = self.source[self.offset..];
if (rest.len == 0)
return null;
const maybe_token = for (patterns) |pat| {
if (pat.match(rest)) |len| {
if (len > 0) {
break Token{
.location = self.current_location,
.text = rest[0..len],
.type = pat.type,
};
}
}
} else null;
if (maybe_token) |token| {
self.offset += token.text.len;
self.current_location.adavance(token.text);
return token;
} else {
return error.UnexpectedCharacter;
}
}
};
}
pub const matchers = struct {
/// Matches the literal `text`.
pub fn literal(comptime text: []const u8) Matcher {
return struct {
fn match(str: []const u8) ?usize {
return if (std.mem.startsWith(u8, str, text))
text.len
else
null;
}
}.match;
}
/// Matches any "word" that is "text\b"
pub fn word(comptime text: []const u8) Matcher {
return struct {
fn match(input: []const u8) ?usize {
if (std.mem.startsWith(u8, input, text)) {
if (text.len == input.len)
return text.len;
const c = input[text.len];
if (std.ascii.isAlNum(c) or (c == '_')) // matches regex \w\W
return null;
return text.len;
}
return null;
}
}.match;
}
/// Takes characters while they are any of the given `chars`.
pub fn takeAnyOf(comptime chars: []const u8) Matcher {
return struct {
fn match(str: []const u8) ?usize {
for (str) |c, i| {
if (std.mem.indexOfScalar(u8, chars, c) == null) {
return i;
}
}
return str.len;
}
}.match;
}
/// Takes characters while they are any of the given `chars`.
pub fn takeAnyOfIgnoreCase(comptime chars: []const u8) Matcher {
const lower_chars = comptime blk: {
comptime var buffer: [chars.len]u8 = undefined;
break :blk std.ascii.lowerString(&buffer, chars);
};
return struct {
fn match(str: []const u8) ?usize {
for (str) |c, i| {
const lc = std.ascii.toLower(c);
if (std.mem.indexOfScalar(u8, lower_chars, lc) == null) {
return i;
}
}
return str.len;
}
}.match;
}
pub fn withPrefix(comptime prefix: []const u8, comptime matcher: Matcher) Matcher {
return struct {
fn match(str: []const u8) ?usize {
if (!std.mem.startsWith(u8, str, prefix))
return null;
const pattern_len = matcher(str[prefix.len..]) orelse return null;
return prefix.len + pattern_len;
}
}.match;
}
/// Concats several matchers into a single one that matches a sequence of all patterns
pub fn sequenceOf(comptime list: anytype) Matcher {
const sequence: [list.len]Matcher = list;
if (sequence.len == 0)
@compileError("Empty sequence not allowed!");
return struct {
fn match(input: []const u8) ?usize {
var total_len: usize = 0;
for (sequence) |seq_match| {
const len = seq_match(input[total_len..]) orelse return null;
if (len == 0)
return null;
total_len += len;
}
return total_len;
}
}.match;
}
// pre-shipped typical patterns
pub fn identifier(str: []const u8) ?usize {
const first_char = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const all_chars = first_char ++ "0123456789";
for (str) |c, i| {
if (std.mem.indexOfScalar(u8, if (i > 0) all_chars else first_char, c) == null) {
return i;
}
}
return str.len;
}
pub fn whitespace(str: []const u8) ?usize {
for (str) |c, i| {
if (!std.ascii.isSpace(c))
return i;
}
return str.len;
}
pub fn linefeed(str: []const u8) ?usize {
if (std.mem.startsWith(u8, str, "\r\n"))
return 2;
if (std.mem.startsWith(u8, str, "\n"))
return 1;
return null;
}
pub fn numberOfBase(comptime base: comptime_int) Matcher {
return takeAnyOfIgnoreCase("0123456789ABCDEF"[0..base]);
}
pub const hexadecimalNumber = numberOfBase(16);
pub const decimalNumber = numberOfBase(10);
pub const octalNumber = numberOfBase(8);
pub const binaryNumber = numberOfBase(2);
};
const TestTokenType = enum {
number,
identifier,
keyword,
whitespace,
};
const TestPattern = Pattern(TestTokenType);
const TestTokenizer = Tokenizer(TestTokenType, &[_]TestPattern{
TestPattern.create(.number, matchers.takeAnyOf("0123456789")),
TestPattern.create(.keyword, matchers.literal("while")),
TestPattern.create(.identifier, matchers.takeAnyOf("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")),
TestPattern.create(.whitespace, matchers.takeAnyOf(" \r\n\t")),
});
test "simple tokenization" {
var tokenizer = TestTokenizer.init(
\\10hellowhile10while
);
const number0 = (try tokenizer.next()) orelse return error.MissingToken;
const identifier = (try tokenizer.next()) orelse return error.MissingToken;
const number1 = (try tokenizer.next()) orelse return error.MissingToken;
const keyword = (try tokenizer.next()) orelse return error.MissingToken;
if ((try tokenizer.next()) != null)
return error.TooManyTokens;
try std.testing.expectEqual(TestTokenType.number, number0.type);
try std.testing.expectEqual(TestTokenType.identifier, identifier.type);
try std.testing.expectEqual(TestTokenType.number, number1.type);
try std.testing.expectEqual(TestTokenType.keyword, keyword.type);
try std.testing.expectEqualStrings("10", number0.text);
try std.testing.expectEqualStrings("hellowhile", identifier.text);
try std.testing.expectEqualStrings("10", number1.text);
try std.testing.expectEqualStrings("while", keyword.text);
try std.testing.expectEqual(Location{ .source = null, .line = 1, .column = 1 }, number0.location);
try std.testing.expectEqual(Location{ .source = null, .line = 1, .column = 3 }, identifier.location);
try std.testing.expectEqual(Location{ .source = null, .line = 1, .column = 13 }, number1.location);
try std.testing.expectEqual(Location{ .source = null, .line = 1, .column = 15 }, keyword.location);
}
test "invalid character" {
var tokenizer = TestTokenizer.init(
\\hello!
);
const identifier = (try tokenizer.next()) orelse return error.MissingToken;
try std.testing.expectEqual(TestTokenType.identifier, identifier.type);
try std.testing.expectEqualStrings("hello", identifier.text);
try std.testing.expectEqual(Location{ .source = null, .line = 1, .column = 1 }, identifier.location);
try std.testing.expectError(error.UnexpectedCharacter, tokenizer.next());
}
test "save/restore tokenization" {
var tokenizer = TestTokenizer.init(
\\hello
\\world
);
const id0 = (try tokenizer.next()) orelse return error.MissingToken;
var state = tokenizer.saveState();
const ws0 = (try tokenizer.next()) orelse return error.MissingToken;
tokenizer.restoreState(state);
const ws1 = (try tokenizer.next()) orelse return error.MissingToken;
const id1 = (try tokenizer.next()) orelse return error.MissingToken;
if ((try tokenizer.next()) != null)
return error.TooManyTokens;
try std.testing.expectEqual(TestTokenType.identifier, id0.type);
try std.testing.expectEqual(TestTokenType.whitespace, ws0.type);
try std.testing.expectEqual(TestTokenType.whitespace, ws1.type);
try std.testing.expectEqual(TestTokenType.identifier, id1.type);
try std.testing.expectEqualStrings("hello", id0.text);
try std.testing.expectEqualStrings("\n", ws0.text);
try std.testing.expectEqualStrings("\n", ws1.text);
try std.testing.expectEqualStrings("world", id1.text);
try std.testing.expectEqual(Location{ .source = null, .line = 1, .column = 1 }, id0.location);
try std.testing.expectEqual(Location{ .source = null, .line = 1, .column = 6 }, ws0.location);
try std.testing.expectEqual(Location{ .source = null, .line = 1, .column = 6 }, ws1.location);
try std.testing.expectEqual(Location{ .source = null, .line = 2, .column = 1 }, id1.location);
}
fn testMatcher(match: Matcher, good: []const []const u8, bad: []const []const u8) !void {
for (good) |str| {
const v = match(str) orelse {
std.log.err("Didn't match pattern '{s}'", .{str});
return error.MissedGoodPattern;
};
if (v == 0) {
std.log.err("Didn't match pattern '{s}'", .{str});
return error.MissedGoodPattern;
}
}
for (bad) |str| {
const v = match(str);
if (v != null and v.? > 0) {
std.log.err("Matched pattern '{s}'", .{str});
return error.MissedBadPattern;
}
}
}
test "premade patterns" {
try testMatcher(
matchers.literal("hello"),
&[_][]const u8{ "hello", "hellobar", "hello_bar" },
&[_][]const u8{ "gello", "foobar", " hello " },
);
try testMatcher(
matchers.word("hello"),
&[_][]const u8{ "hello", "hello bar" },
&[_][]const u8{ "hellobar", "hello_bar", "gello", "foobar", " hello " },
);
try testMatcher(
comptime matchers.withPrefix("foo_", matchers.word("hello")),
&[_][]const u8{ "foo_hello", "foo_hello bar" },
&[_][]const u8{ "foo_hellobar", "foo_hello_bar", "hello", "gello", "foobar", " hello " },
);
try testMatcher(
comptime matchers.takeAnyOf("abc"),
&[_][]const u8{ "a", "b", "c", "abc", "a x", "b x", "c x", "abcabcabcabc" },
&[_][]const u8{ "xabc", "xa", "xb", " aaa", "x asd", " x " },
);
try testMatcher(
comptime matchers.takeAnyOfIgnoreCase("abc"),
&[_][]const u8{ "a", "b", "c", "abc", "a x", "b x", "c x", "abcabcabcabc", "A", "B", "C", "ABC", "A X", "B X", "C X", "ABCABCABCABC" },
&[_][]const u8{ "xabc", "xa", "xb", " aaa", "x asd", " x ", "XABC", "XA", "XB", " AAA", "X ASD", " X " },
);
try testMatcher(
matchers.identifier,
&[_][]const u8{ "foo", "Foo", "hello_bar", "_bar", "he11o" },
&[_][]const u8{ "10foo", "!", " foo " },
);
try testMatcher(
matchers.whitespace,
&[_][]const u8{ " ", " a", "\r", "\n", "\t" },
&[_][]const u8{ "10foo", "!", "foo " },
);
try testMatcher(
matchers.linefeed,
&[_][]const u8{ "\n", "\r\n", "\nfoo", "\r\nbar" },
&[_][]const u8{ "\r\r\n", "!", " " },
);
try testMatcher(
matchers.decimalNumber,
&[_][]const u8{ "10", "99", "1234567890" },
&[_][]const u8{ "a", "b", " 123 " },
);
try testMatcher(
matchers.binaryNumber,
&[_][]const u8{ "10", "01", "1100101" },
&[_][]const u8{ "2", "3", " 01 " },
);
try testMatcher(
comptime matchers.sequenceOf(.{ matchers.decimalNumber, matchers.literal("."), matchers.decimalNumber }),
&[_][]const u8{ "10.0", "1.0", "0.01234" },
&[_][]const u8{ ".1", "1", "10", ".1234", "10." },
);
} | src/tokenizer.zig |
const std = @import("std");
const curses = @import("curses.zig");
pub const KeyBinding = struct { key: []const u8, help: []const u8 };
const Wrapper = struct {
s: []const u8,
maxlen: usize,
fn nextLine(self: *Wrapper) ?[]const u8 {
if (self.s.len == 0) {
return null;
}
var line = if (std.mem.indexOfScalar(u8, self.s, '\n')) |i| self.s[0..i] else self.s;
if (line.len > self.maxlen) {
line = line[0..self.maxlen];
if (std.mem.lastIndexOfScalar(u8, line, ' ')) |i| {
line = line[0..i];
}
}
if (self.s.len > line.len and (self.s[line.len] == '\n' or self.s[line.len] == ' ')) {
self.s = self.s[line.len+1..];
} else {
self.s = self.s[line.len..];
}
return line;
}
};
// if you modify this, make sure that it fits on an 80x24 standard-sized terminal!
const text_with_single_newlines =
\\The goal is to open all squares that don't contain mines, but none of the squares that contain
\\mines. When you have opened a square, the number of the square indicates how many mines there
\\are in the 8 other squares around the opened square (aka "neighbor squares"). The game ends
\\when all non-mine squares are opened (you win), or a mine square is opened (you lose).
\\
\\You can flag the mines to keep track of them more easily (but you don't need to). This has no
\\effect on winning or losing; the flagging is meant to be nothing more than a handy way to keep
\\track of the mines you have already found.
\\
\\Flagging the mines can make playing the game a lot easier. For example, if you have opened a
\\square and it shows the number 3, and you have flagged exactly 3 of its neighbors, then you
\\can open all other neighbors because they can't contain mines. This is how the "d" key works.
;
// does nothing to \n\n repeated, but replaces single \n with spaces
fn removeSingleNewlines(s: []const u8, allocator: *std.mem.Allocator) ![]u8 {
var result = std.ArrayList(u8).init(allocator);
errdefer result.deinit();
var i: usize = 0;
while (i < s.len) {
if (i+1 < s.len and s[i] == '\n' and s[i+1] == '\n') {
try result.append('\n');
try result.append('\n');
i += 2;
} else if (s[i] == '\n') {
try result.append(' ');
i += 1;
} else {
try result.append(s[i]);
i += 1;
}
}
return result.toOwnedSlice();
}
fn incrementY(window: curses.Window, y: *u16) !void {
y.* += 1;
if (y.* >= window.getmaxy()) {
return error.TerminalIsTooSmall;
}
}
fn drawText(window: curses.Window, key_bindings: []const KeyBinding, allocator: *std.mem.Allocator) !void {
try window.erase();
var maxlen: u16 = 0;
for (key_bindings) |kb| {
maxlen = std.math.max(maxlen, @intCast(u16, kb.key.len));
}
var y: u16 = 0;
try window.mvaddstr(y, 0, "Key Bindings:");
try incrementY(window, &y);
for (key_bindings) |kb| {
try window.mvaddstr(y, 2, kb.key);
try window.mvaddstr(y, 2 + maxlen + 2, kb.help);
try incrementY(window, &y);
}
try incrementY(window, &y);
{
const text = try removeSingleNewlines(text_with_single_newlines, allocator);
defer allocator.free(text);
var wrapper = Wrapper{ .s = text, .maxlen = window.getmaxx() };
while (wrapper.nextLine()) |line| {
try window.mvaddstr(y, 0, line);
try incrementY(window, &y);
}
}
try window.attron(curses.A_STANDOUT);
try window.mvaddstr(window.getmaxy() - 1, 0, "Press q to quit this help...");
try window.attroff(curses.A_STANDOUT);
}
// returns true if ok, false if help message didn't fit on the terminal
pub fn show(window: curses.Window, key_bindings: []const KeyBinding, allocator: *std.mem.Allocator) !bool {
while (true) {
drawText(window, key_bindings, allocator) catch |err| switch(err) {
error.TerminalIsTooSmall => return false, // it might be playable even if help doesn't fit
else => return err,
};
switch (try window.getch()) {
'Q', 'q' => return true,
else => {},
}
}
} | src/help.zig |
const std = @import("std");
const range = @import("range").range;
// // the naïve recursive implementation
// pub fn leven(comptime T: type, a: []const T, b: []const T) usize {
// if (b.len == 0) return a.len;
// if (a.len == 0) return b.len;
// if (a[0] == b[0]) return leven(T, a[1..], b[1..]);
// return 1 + std.math.min3(
// leven(T, a[1..], b),
// leven(T, a, b[1..]),
// leven(T, a[1..], b[1..]),
// );
// }
pub fn leven(comptime T: type, alloc: std.mem.Allocator, a: []const T, b: []const T, max: ?usize) !usize {
if (std.mem.eql(T, a, b)) return 0;
var left = a;
var right = b;
if (left.len > right.len) {
left = b;
right = a;
}
var ll = left.len;
var rl = right.len;
if (max != null and rl - ll >= max.?) {
return max.?;
}
{
const sl = suffixLen(T, a, b);
ll -= sl;
rl -= sl;
}
const start = prefixLen(T, a, b);
ll -= start;
rl -= start;
if (ll == 0) return rl;
var result: usize = 0;
const charCodeCache = try alloc.alloc(T, ll);
defer alloc.free(charCodeCache);
const array = try alloc.alloc(usize, ll);
defer alloc.free(array);
for (range(ll)) |_, i| {
charCodeCache[i] = left[start + i];
array[i] = i + 1;
}
for (range(rl)) |_, j| {
const bCharCode = right[start + j];
var temp = j;
result = j + 1;
for (range(ll)) |_, i| {
const temp2 = if (bCharCode == charCodeCache[i]) temp else temp + 1;
temp = array[i];
array[i] = if (temp > result) (if (temp2 > result) result + 1 else temp2) else (if (temp2 > temp) temp + 1 else temp2);
result = array[i];
}
}
if (max != null and result >= max.?) return max.?;
return result;
}
fn prefixLen(comptime T: type, a: []const T, b: []const T) usize {
if (a.len == 0 or b.len == 0) return 0;
var i: usize = 0;
while (a[i] == b[i]) : (i += 1) {}
return i;
}
fn suffixLen(comptime T: type, a: []const T, b: []const T) usize {
if (a.len == 0 or b.len == 0) return 0;
var i: usize = 0;
while (a[a.len - 1 - i] == b[b.len - 1 - i]) : (i += 1) {}
return i;
} | src/lib.zig |
const std = @import("std");
const warn = std.debug.print;
const Allocator = std.mem.Allocator;
var allocator: *Allocator = undefined;
const ipc = @import("./ipc/epoll.zig");
const config = @import("./config.zig");
const c = @cImport({
@cInclude("unistd.h");
@cInclude("pthread.h");
@cInclude("sys/epoll.h");
});
pub const Actor = struct { thread_id: c.pthread_t, client: *ipc.Client, payload: *CommandVerb, recvback: fn (*Command) void };
pub const Command = packed struct { id: u16, verb: *const CommandVerb, actor: *Actor };
pub const CommandVerb = packed union { login: *config.LoginInfo, http: *config.HttpInfo, column: *config.ColumnInfo, auth: *config.ColumnAuth, idle: u16 };
var actors: std.ArrayList(Actor) = undefined;
pub fn init(myAllocator: *Allocator) !void {
allocator = myAllocator;
actors = std.ArrayList(Actor).init(allocator);
try ipc.init();
}
pub fn create(
startFn: fn (?*anyopaque) callconv(.C) ?*anyopaque,
startParams: *CommandVerb,
recvback: fn (*Command) void,
) !*Actor {
var actor = try allocator.create(Actor);
actor.client = ipc.newClient(allocator);
actor.payload = startParams; //unused
ipc.dial(actor.client, "");
actor.recvback = recvback;
//ipc.register(actor.client, recvback);
const null_pattr = @intToPtr([*c]const c.union_pthread_attr_t, 0);
var terr = c.pthread_create(&actor.thread_id, null_pattr, startFn, actor);
if (terr == 0) {
warn("created thread#{}\n", .{actor.thread_id});
actors.append(actor.*);
return actor;
} else {
warn("ERROR thread {} {}\n", .{ terr, actor });
}
return error.BadValue;
}
pub fn signal(actor: *Actor, command: *Command) void {
command.actor = actor; // fill in the command
const command_addr_bytes = @ptrCast(*const [@sizeOf(*Command)]u8, &command);
warn("signaling from tid {x} command bytes {x} len{} {}\n", .{ actor.thread_id, command_addr_bytes, command_addr_bytes.len, command });
ipc.send(actor.client, command_addr_bytes);
}
pub fn destroy(actor: *Actor) void {
warn("thread.destroy {}\n", actor);
}
pub fn self() c.pthread_t {
return c.pthread_self();
}
pub fn wait() void {
var client = ipc.wait();
var bufArray = [_]u8{0} ** 16; // arbitrary receive buffer
const buf: []u8 = ipc.read(client, bufArray[0..]);
if (buf.len == 0) {
// todo: skip read() and pass ptr with event_data
warn("thread.wait ipc.read no socket payload! DEFLECTED!\n", .{});
} else {
const b8: *[@sizeOf(usize)]u8 = @ptrCast(*[@sizeOf(usize)]u8, buf.ptr);
var command: *Command = std.mem.bytesAsValue(*Command, b8).*;
for (actors.items) |actor| { // todo: hashtable
if (actor.client == client) {
actor.recvback(command);
break;
}
}
}
}
pub fn join(jthread: c.pthread_t, joinret: *?*anyopaque) c_int {
//pub extern fn pthread_join(__th: pthread_t, __thread_return: ?[*](?*c_void)) c_int;
return c.pthread_join(jthread, @ptrCast(?[*]?*anyopaque, joinret)); //expected type '?[*]?*c_void' / void **value_ptr
} | src/thread.zig |
const std = @import("std");
const builtin = @import("builtin");
const zbox = @import("zbox");
const Channel = @import("utils/channel.zig").Channel;
const Chat = @import("Chat.zig");
const main = @import("main.zig");
const senseUrl = @import("./utils/url.zig").sense;
const GlobalEventUnion = main.Event;
const BorkConfig = main.BorkConfig;
const ziglyph = @import("ziglyph");
// We expose directly the event type produced by zbox
pub const Event = zbox.Event;
pub const getSize = zbox.size;
pub const TerminalMessage = struct {
chat_message: Chat.Message,
buffer: zbox.Buffer,
is_selected: bool = false,
};
pub const InteractiveElement = union(enum) {
none,
afk,
subscriber_badge: *TerminalMessage,
username: *TerminalMessage,
chat_message: *TerminalMessage,
event_message: *TerminalMessage,
button: union(enum) {
// Message buttons
del: *TerminalMessage,
},
};
const AfkMessage = struct {
const height: usize = 5;
title: []const u8,
target_time: i64,
reason: []const u8,
last_updated: i64,
buffer: zbox.Buffer,
pub fn deinit(afk: *@This(), alloc: std.mem.Allocator) void {
alloc.free(afk.reason);
alloc.free(afk.title);
afk.buffer.deinit();
}
pub fn needsToAnimate(afk: @This()) bool {
return afk.last_updated != std.time.timestamp();
}
pub fn render(afk: *@This(), alloc: std.mem.Allocator, output_width: usize) !void {
const size_changed = output_width != afk.buffer.width;
const needs_update = size_changed or afk.needsToAnimate();
if (size_changed) {
std.log.debug("must realloc afk message!", .{});
afk.buffer.deinit();
afk.buffer = try zbox.Buffer.init(
alloc,
height,
output_width,
);
afk.buffer.fill(.{ .interactive_element = .afk });
Box.draw(.single, &afk.buffer, 0, 0, afk.buffer.width - 1, height);
}
if (needs_update) {
const now = std.time.timestamp();
const remaining = std.math.max(0, afk.target_time - now);
const human_readable_remaining = try renderCountdown(remaining, alloc);
defer alloc.free(human_readable_remaining);
std.log.debug("must rerender msg!", .{});
var cur = afk.buffer.cursorAt(1, 1);
cur.interactive_element = .afk;
const top_text = switch (afk.title.len) {
0 => "AFK",
else => if (afk.title.len <= afk.buffer.width - 2)
afk.title
else
afk.title[0 .. afk.buffer.width - 2],
};
const top_column = try std.math.divCeil(usize, afk.buffer.width - top_text.len, 2);
cur.row_num = 1;
cur.col_num = top_column;
try cur.writer().writeAll(top_text);
const time_column = try std.math.divCeil(usize, afk.buffer.width - (human_readable_remaining.len + 8), 2);
cur.row_num = 2;
cur.col_num = time_column;
try cur.writer().print("--- {s} ---", .{
human_readable_remaining,
});
const bottom_text = switch (afk.reason.len) {
0 => "⏰",
else => if (afk.reason.len <= afk.buffer.width - 2)
afk.reason
else
afk.reason[0 .. afk.buffer.width - 2],
};
const bottom_column = switch (afk.reason.len) {
0 => try std.math.divCeil(usize, afk.buffer.width - 2 - 1, 2),
else => std.math.max(1, try std.math.divCeil(usize, afk.buffer.width - bottom_text.len, 2)),
};
cur.row_num = 3;
cur.col_num = bottom_column;
try cur.writer().writeAll(bottom_text);
afk.last_updated = now;
}
}
fn renderCountdown(icd: i64, alloc: std.mem.Allocator) ![]const u8 {
const cd = @intCast(usize, icd);
const h = @divTrunc(cd, 60 * 60);
const m = @divTrunc(@mod(cd, 60 * 60), 60);
const s = @mod(cd, 60);
return std.fmt.allocPrint(alloc, "{:0>2}h{:0>2}m{:0>2}s", .{ h, m, s });
}
};
// This global is used by the WINCH handler.
var mainLoopChannel: ?*Channel(GlobalEventUnion) = null;
const EmoteCache = std.AutoHashMap(u32, void);
// State
config: BorkConfig,
allocator: std.mem.Allocator,
ch: *Channel(GlobalEventUnion),
output: zbox.Buffer,
chatBuf: zbox.Buffer,
overlayBuf: zbox.Buffer,
active_interaction: InteractiveElement = .none,
emote_cache: EmoteCache,
ctrlc_pressed: bool = false,
afk_message: ?AfkMessage = null,
// Static config
// The message is padded on each line
// by 6 spaces (HH:MM )
// 123456
const padding = 6;
var emulator: enum { kitty, other } = undefined;
const Self = @This();
var done_init = false;
var terminal_inited = false;
var notifs: @Frame(notifyDisplayEvents) = undefined;
pub fn init(alloc: std.mem.Allocator, ch: *Channel(GlobalEventUnion), config: BorkConfig) !Self {
{
if (done_init) @panic("Terminal should only be initialized once, like a singleton.");
done_init = true;
std.log.debug("init terminal!", .{});
}
// Sense the terminal *emulator* we're running in.
{
// We're interested in sensing:
// - Kitty
const name = std.os.getenv("TERM") orelse std.os.getenv("TERM_PROGRAM") orelse "";
if (std.mem.eql(u8, name, "xterm-kitty")) {
emulator = .kitty;
zbox.is_kitty = true;
} else {
emulator = .other;
}
std.log.debug("emulator = {}!", .{emulator});
}
// Initialize zbox
try zbox.init(alloc);
_ = @atomicRmw(bool, &terminal_inited, .Xchg, true, .SeqCst);
errdefer zbox.deinit();
errdefer _ = @atomicRmw(bool, &terminal_inited, .Xchg, false, .SeqCst);
// die on ctrl+C
// try zbox.handleSignalInput();
try zbox.cursorHide();
// 144fps repaints
{
// TODO: debug why some resizings corrupt everything irreversibly;
// in the meantime users can press R to repaint everything.
std.os.sigaction(std.os.SIG.WINCH, &std.os.Sigaction{
.handler = .{ .handler = winchHandler },
.mask = switch (builtin.os.tag) {
.macos => 0,
.linux => std.os.empty_sigset,
.windows => @compileError(":3"),
else => @compileError("os not supported"),
},
.flags = 0,
}, null);
}
// Init main buffer
var size = try zbox.size();
var output = try zbox.Buffer.init(alloc, size.height, size.width);
errdefer output.deinit();
// Setup the buffer for chat history
var chatBuf = try zbox.Buffer.init(alloc, size.height - 2, size.width - 2);
errdefer chatBuf.deinit();
var overlayBuf = try zbox.Buffer.init(alloc, size.height - 2, size.width - 2);
errdefer overlayBuf.deinit();
notifs = async notifyDisplayEvents(ch, config.remote);
mainLoopChannel = ch;
return Self{
.config = config,
.allocator = alloc,
.ch = ch,
.chatBuf = chatBuf,
.output = output,
.overlayBuf = overlayBuf,
.emote_cache = EmoteCache.init(alloc),
};
}
pub fn toggleCtrlCMessage(self: *Self, new: bool) !bool {
if (self.ctrlc_pressed == new) return false;
if (new) {
try std.event.Loop.instance.?.runDetached(
self.allocator,
disableCtrlCMessage,
.{self},
);
}
self.ctrlc_pressed = new;
return true;
}
fn disableCtrlCMessage(self: *Self) void {
std.time.sleep(3 * std.time.ns_per_s);
self.ch.put(GlobalEventUnion{ .display = .disableCtrlCMessage });
}
// handles window resize
fn winchHandler(_: c_int) callconv(.C) void {
if (mainLoopChannel) |ch| {
ch.tryPut(GlobalEventUnion{ .display = .dirty }) catch {
// We toss away the notification if the channel is full.
};
}
}
// This function allocates a TerminalMessage and returns a pointer
// to the chat message field. Later, when rendering the application,
// we'll use @fieldParentPointer() to "navigate up" to the full
// scruture from the linked list that Chat keeps.
pub fn prepareMessage(self: *Self, chatMsg: Chat.Message) !*Chat.Message {
var term_msg = try self.allocator.create(TerminalMessage);
term_msg.* = switch (chatMsg.kind) {
.raid,
.resub,
.sub,
.sub_gift,
.sub_mistery_gift,
=> .{
.chat_message = chatMsg,
.is_selected = true,
.buffer = try zbox.Buffer.init(
self.allocator,
2,
self.chatBuf.width,
),
},
.chat => |m| .{
.chat_message = chatMsg,
.is_selected = m.is_highlighted,
.buffer = try zbox.Buffer.init(
self.allocator,
1,
self.chatBuf.width - padding,
),
},
.line => .{
.chat_message = chatMsg,
.buffer = try zbox.Buffer.init(
self.allocator,
1,
self.chatBuf.width - padding,
),
},
};
try self.renderMessage(term_msg);
return &term_msg.chat_message;
}
fn setCellToEmote(cell: *zbox.Cell, emote_idx: u32) void {
cell.* = .{
.emote_idx = emote_idx,
};
}
// NOTE: callers must clear the buffer when necessary (when size changes)
fn renderMessage(self: *Self, msg: *TerminalMessage) !void {
var cursor = msg.buffer.wrappedCursorAt(0, 0).writer();
cursor.context.attribs = .{
.normal = true,
};
std.log.debug("started rendering msg!", .{});
switch (msg.chat_message.kind) {
// else => {
// std.log.debug("TODO(renderMessage): implement rendering for {}", .{@tagName(msg.chat_message.kind)});
// },
.line => {},
.raid => |g| {
msg.buffer.fill(.{
.interactive_element = .{
.event_message = msg,
},
});
cursor.context.interactive_element = .{
.event_message = msg,
};
cursor.context.attribs = .{
.feint = true,
};
// Top line
{
const top_message_fmt = "«{s}»";
const top_message_args = .{g.display_name};
cursor.context.col_num = @divTrunc(msg.buffer.width + 2 - std.fmt.count(
top_message_fmt,
top_message_args,
), 2);
try cursor.print(top_message_fmt, top_message_args);
}
// Bottom line
{
const message_fmt = "🚨 raiding with {d} people 🚨";
const message_args = .{g.count};
cursor.context.row_num = 1;
cursor.context.col_num = @divTrunc(msg.buffer.width + 4 - std.fmt.count(
message_fmt,
message_args,
), 2);
try cursor.print(message_fmt, message_args);
}
},
.resub => |r| {
msg.buffer.fill(.{
.interactive_element = .{
.event_message = msg,
},
});
cursor.context.interactive_element = .{
.event_message = msg,
};
cursor.context.attribs = .{
.feint = true,
};
const tier = switch (r.tier) {
.prime => "Prime",
.t1 => "T1",
.t2 => "T2",
.t3 => "T3",
};
// Top line
{
const message_fmt = "«{s}»";
const message_args = .{r.display_name};
cursor.context.col_num = @divTrunc(msg.buffer.width + 2 - std.fmt.count(
message_fmt,
message_args,
), 2);
try cursor.print(message_fmt, message_args);
}
// Bottom line
{
const message_fmt = "🎉 {d}mo {s} resub! 🎉";
const message_args = .{ r.count, tier };
cursor.context.row_num = 1;
cursor.context.col_num = @divTrunc(msg.buffer.width + 4 - std.fmt.count(
message_fmt,
message_args,
), 2);
try cursor.print(message_fmt, message_args);
}
},
.sub => |s| {
msg.buffer.fill(.{
.interactive_element = .{
.event_message = msg,
},
});
cursor.context.interactive_element = .{
.event_message = msg,
};
cursor.context.attribs = .{
.feint = true,
};
const tier = switch (s.tier) {
.prime => "Prime",
.t1 => "T1",
.t2 => "T2",
.t3 => "T3",
};
// Top line
{
const message_fmt = "«{s}»";
const message_args = .{s.display_name};
cursor.context.col_num = @divTrunc(msg.buffer.width + 2 - std.fmt.count(
message_fmt,
message_args,
), 2);
try cursor.print(message_fmt, message_args);
}
// Bottom line
{
const message_fmt = "🎊 is now a {s} sub! 🎊";
const message_args = .{tier};
cursor.context.row_num = 1;
cursor.context.col_num = @divTrunc(msg.buffer.width + 4 - std.fmt.count(
message_fmt,
message_args,
), 2);
try cursor.print(message_fmt, message_args);
}
},
.sub_gift => |g| {
msg.buffer.fill(.{
.interactive_element = .{
.event_message = msg,
},
});
cursor.context.interactive_element = .{
.event_message = msg,
};
cursor.context.attribs = .{
.feint = true,
};
const tier = switch (g.tier) {
.prime => "Prime",
.t1 => "T1",
.t2 => "T2",
.t3 => "T3",
};
// Top line
{
const message_fmt = "«{s}» 🎁 a {d}mo";
const message_args = .{ g.sender_display_name, g.months };
cursor.context.col_num = @divTrunc(msg.buffer.width + 4 - std.fmt.count(
message_fmt,
message_args,
), 2);
try cursor.print(message_fmt, message_args);
}
// Bottom line
{
const message_fmt = "{s} Sub to «{s}»";
const message_args = .{ tier, g.recipient_display_name };
cursor.context.row_num = 1;
cursor.context.col_num = @divTrunc(msg.buffer.width + 2 - std.fmt.count(
message_fmt,
message_args,
), 2);
try cursor.print(message_fmt, message_args);
}
},
.sub_mistery_gift => |g| {
msg.buffer.fill(.{
.interactive_element = .{
.event_message = msg,
},
});
cursor.context.interactive_element = .{
.event_message = msg,
};
cursor.context.attribs = .{
.feint = true,
};
const tier = switch (g.tier) {
.prime => "Prime",
.t1 => "T1",
.t2 => "T2",
.t3 => "T3",
};
// todo: fallback when there's not enough space
// Top line
{
const top_message_fmt = "«{s}»";
const top_message_args = .{g.display_name};
cursor.context.col_num = @divTrunc(msg.buffer.width + 2 - std.fmt.count(
top_message_fmt,
top_message_args,
), 2);
try cursor.print(top_message_fmt, top_message_args);
}
// Bottom line
{
const message_fmt = "🎁 Gifted x{d} {s} Subs! 🎁";
const message_args = .{
g.count,
tier,
};
cursor.context.row_num = 1;
cursor.context.col_num = @divTrunc(msg.buffer.width + 4 - std.fmt.count(
message_fmt,
message_args,
), 2);
try cursor.print(message_fmt, message_args);
}
},
.chat => |c| {
// Async emote image data transmission
{
var term_writer = zbox.term.getWriter();
for (c.emotes) |e| {
if (e.img_data) |img| {
const entry = try self.emote_cache.getOrPut(e.idx);
if (!entry.found_existing) {
const single_chunk = img.len <= 4096;
if (single_chunk) {
std.log.debug("single chunk!", .{});
try term_writer.print(
"\x1b_Gf=100,t=d,a=t,i={d};{s}\x1b\\",
.{ e.idx, img },
);
} else {
var cur: usize = 4096;
// send first chunk
try term_writer.print(
"\x1b_Gf=100,i={d},m=1;{s}\x1b\\",
.{ e.idx, img[0..cur] },
);
// send remaining chunks
while (cur < img.len) : (cur += 4096) {
const end = std.math.min(cur + 4096, img.len);
const m = if (end == img.len) "0" else "1";
// <ESC>_Gs=100,v=30,m=1;<encoded pixel data first chunk><ESC>\
// <ESC>_Gm=1;<encoded pixel data second chunk><ESC>\
// <ESC>_Gm=0;<encoded pixel data last chunk><ESC>\
try term_writer.print(
"\x1b_Gm={s};{s}\x1b\\",
.{ m, img[cur..end] },
);
}
}
}
} else {
// TODO: display placeholder or something
}
}
}
msg.buffer.fill(.{
.interactive_element = .{
.chat_message = msg,
},
});
cursor.context.interactive_element = .{
.chat_message = msg,
};
const action_preamble = "\x01ACTION ";
if (std.mem.startsWith(u8, c.text, action_preamble) and
std.mem.endsWith(u8, c.text, "\x01"))
{
cursor.context.attribs = .{ .fg_cyan = true };
try printWordWrap(
self.allocator,
"*",
&[0]Chat.Message.Emote{},
&msg.buffer,
cursor,
);
cursor.context.attribs = .{ .feint = true };
try printWordWrap(
self.allocator,
c.text[action_preamble.len .. c.text.len - 1],
c.emotes,
&msg.buffer,
cursor,
);
cursor.context.attribs = .{ .fg_cyan = true };
try printWordWrap(
self.allocator,
"*",
&[0]Chat.Message.Emote{},
&msg.buffer,
cursor,
);
} else {
try printWordWrap(
self.allocator,
c.text,
c.emotes,
&msg.buffer,
cursor,
);
}
},
}
std.log.debug("done rendering msg!", .{});
}
fn printWordWrap(
allocator: std.mem.Allocator,
text: []const u8,
emotes: []const Chat.Message.Emote,
buffer: *zbox.Buffer,
cursor: zbox.Buffer.Writer,
) !void {
const width = buffer.width;
var height = buffer.height; // TODO: do we really need to track this?
var it = std.mem.tokenize(u8, text, " ");
var emote_array_idx: usize = 0;
var codepoints: usize = 0;
while (it.next()) |word| : (codepoints += 1) { // we add the space, twitch removes extra spaces
std.log.debug("word: [{s}]", .{word});
const word_len = try std.unicode.utf8CountCodepoints(word);
codepoints += word_len;
const word_width = @intCast(usize, try ziglyph.display_width.strWidth(
allocator,
word,
.half,
));
if (emulator == .kitty and emote_array_idx < emotes.len and
emotes[emote_array_idx].end == codepoints - 1)
{
const emote = emotes[emote_array_idx].idx; //@embedFile("../kappa.txt"); // ; //
const emote_len = 2;
emote_array_idx += 1;
if (emote_len <= width - cursor.context.col_num) {
// emote fits in this row
setCellToEmote(buffer.cellRef(
cursor.context.row_num,
cursor.context.col_num,
), emote);
cursor.context.col_num += 2;
} else {
// emote doesn't fit, let's add a line for it.
height += 1;
try buffer.resize(height, width);
cursor.context.col_num = 2;
cursor.context.row_num += 1;
setCellToEmote(buffer.cellRef(
cursor.context.row_num,
0,
), emote);
}
} else {
if (word_width >= width) {
// a link or a very big word
const is_link = senseUrl(word);
// How many rows considering that we might be on a row
// with something already written on it?
const rows = blk: {
const len = word_width + cursor.context.col_num;
const rows = @divTrunc(len, width) + if (len % width == 0)
@as(usize, 0)
else
@as(usize, 1);
break :blk rows;
};
// Ensure we have enough rows
const missing_rows: isize = @intCast(isize, cursor.context.row_num + rows) - @intCast(isize, height);
if (missing_rows > 0) {
height = height + @intCast(usize, missing_rows);
try buffer.resize(height, width);
}
// Write the word, make use of the wrapping cursor
// add link markers if necessary
if (is_link) {
// ignore enclosing parens
var start: usize = 0;
var end: usize = word.len;
const url = url: {
if (word[0] == '(') {
start = 1;
if (word[word.len - 1] == ')') {
end = word.len - 1;
}
}
break :url word[start..end];
};
if (start != 0) try cursor.writeAll("(");
cursor.context.link = url;
try cursor.writeAll(url[0..1]);
cursor.context.link = null;
try cursor.writeAll(url[1 .. url.len - 1]);
cursor.context.is_link_end = true;
try cursor.writeAll(url[url.len - 1 ..]);
cursor.context.is_link_end = false;
if (end != word.len) try cursor.writeAll(")");
} else {
try cursor.writeAll(word);
}
} else if (word_width <= width - cursor.context.col_num) {
// word fits in this row
try cursor.writeAll(word);
} else {
// word fits the width (i.e. it shouldn't be broken up)
// but it doesn't fit, let's add a line for it.
height += 1;
try buffer.resize(height, width);
// Add a newline if we're not at the end
if (cursor.context.col_num < width) try cursor.writeAll("\n");
try cursor.writeAll(word);
}
}
// If we're not at the end of the line, add a space
if (cursor.context.col_num < width) {
try cursor.writeAll(" ");
}
}
}
// pub fn startTicking(ch: *Channel(GlobalEventUnion)) void {
// const cooldown = 5;
// var chaos_cooldown: isize = -1;
// var last_size: @TypeOf(zbox.size()) = undefined;
// while (true) {
// std.time.sleep(100 * std.time.ns_per_ms);
// if (@atomicRmw(bool, &dirty, .Xchg, false, .SeqCst)) {
// // Flag was true, term is being resized
// ch.put(GlobalEventUnion{ .display = .chaos });
// if (chaos_cooldown > -1) {
// std.log.debug("ko, restarting", .{});
// }
// chaos_cooldown = cooldown;
// last_size = zbox.size();
// } else if (chaos_cooldown > -1) {
// var new_size = zbox.size();
// if (std.meta.eql(new_size, last_size)) {
// if (chaos_cooldown == 0) {
// ch.put(GlobalEventUnion{ .display = .calm });
// }
// chaos_cooldown -= 1;
// } else {
// last_size = new_size;
// chaos_cooldown = cooldown;
// std.log.debug("ko, restarting", .{});
// }
// }
// }
// }
pub fn notifyDisplayEvents(ch: *Channel(GlobalEventUnion), remote_enabled: bool) !void {
defer std.log.debug("notfyDisplayEvents returning", .{});
std.event.Loop.instance.?.yield();
while (true) {
if (try zbox.nextEvent()) |event| {
ch.put(GlobalEventUnion{ .display = event });
if (!remote_enabled and event == .CTRL_C) return;
}
}
}
pub fn deinit(self: *Self) void {
std.log.debug("deinit terminal!", .{});
zbox.cursorShow() catch {};
zbox.clear() catch {};
self.output.deinit();
zbox.deinit();
std.log.debug("done cleaning term", .{});
// Why is this causing a crash?
// await notifs catch {};
// std.log.debug("done await", .{});
}
pub fn panic() void {
if (@atomicRmw(bool, &terminal_inited, .Xchg, false, .SeqCst)) {
zbox.deinit();
}
}
pub fn sizeChanged(self: *Self) !void {
std.log.debug("resizing!", .{});
const size = try zbox.size();
if (size.width != self.output.width or size.height != self.output.height) {
try self.output.resize(size.height, size.width);
const chatBufSize: usize = size.height - 2 - if (self.config.afk_position != .hover and self.afk_message != null) AfkMessage.height else 0;
try self.chatBuf.resize(chatBufSize, size.width - 2);
try self.overlayBuf.resize(chatBufSize, size.width - 2);
self.output.clear();
try zbox.term.clear();
try zbox.term.flush();
}
}
pub fn renderChat(self: *Self, chat: *Chat) !void {
std.log.debug("render!", .{});
// TODO: this is a very inefficient way of using Kitty
if (emulator == .kitty) {
try zbox.term.send("\x1b_Ga=d\x1b\\");
}
// Paint the AFK message (if any)
{
if (self.afk_message) |*afk| {
try afk.render(self.allocator, self.chatBuf.width);
}
}
// Add top bar
{
const emoji_column = @divTrunc(self.output.width, 2) - 1; // TODO: test this math lmao
const top_bar_row = if (self.config.afk_position == .top and self.afk_message != null)
AfkMessage.height
else
0;
var i: usize = 1;
while (i < self.output.width - 1) : (i += 1) {
self.output.cellRef(top_bar_row, i).* = .{
.char = ' ',
.attribs = .{ .bg_blue = true },
};
}
var cur = self.output.cursorAt(top_bar_row, emoji_column - 4);
cur.attribs = .{
.fg_black = true,
.bg_blue = true,
};
// try cur.writer().writeAll("Zig");
// cur.col_num = emoji_column + 2;
// try cur.writer().writeAll("b0rk");
self.output.cellRef(top_bar_row, emoji_column).* = .{
.char = '⚡',
.attribs = .{
.fg_yellow = true,
.bg_blue = true,
},
};
}
// Render the chat history
{
// NOTE: chat history is rendered bottom-up, starting from the newest
// message visible at the bottom, going up to the oldest.
self.chatBuf.clear();
self.overlayBuf.fill(.{
.is_transparent = true,
});
var row = self.chatBuf.height;
var i: usize = 0;
var message = chat.bottom_message;
while (message) |m| : (message = m.prev) {
// Break if we dont' have more space
if (row == 0) break;
i += 1;
// TODO: do something when the terminal has less than `padding` columns?
const padded_width = self.chatBuf.width - padding;
var term_message = @fieldParentPtr(TerminalMessage, "chat_message", m);
// write it
switch (m.kind) {
// else => {
// std.log.debug("TODO: implement rendering for {}", .{@tagName(m.kind)});
// },
.raid,
.resub,
.sub,
.sub_gift,
.sub_mistery_gift,
=> {
// re-render the message if width changed in the meantime
if (self.chatBuf.width != term_message.buffer.width) {
std.log.debug("must rerender msg!", .{});
term_message.buffer.deinit();
term_message.buffer = try zbox.Buffer.init(self.allocator, 2, self.chatBuf.width);
try self.renderMessage(term_message);
}
const msg_height = term_message.buffer.height;
self.chatBuf.blit(
term_message.buffer,
@intCast(isize, row) - @intCast(isize, msg_height),
0,
);
// If the message is selected, time to invert everything!
if (term_message.is_selected) {
var rx: usize = row - std.math.min(msg_height, row);
while (rx < row) : (rx += 1) {
var cx: usize = 0;
while (cx < self.chatBuf.width) : (cx += 1) {
self.chatBuf.cellRef(rx, cx).attribs.reverse = true;
}
}
}
row -= std.math.min(msg_height, row);
},
.line => {
// Update the row position
row -= 1;
// NOTE: since line takes only one row and we break when row == 0,
// we don't have to check for space.
var col: usize = 1;
var cursor = self.chatBuf.cursorAt(row, col).writer();
while (col < self.chatBuf.width - 1) : (col += 1) {
try cursor.print("-", .{});
}
const msg = "[RECONNECTED]";
if (self.chatBuf.width > msg.len) {
var column = @divTrunc(self.chatBuf.width, 2) + (self.chatBuf.width % 2) - @divTrunc(msg.len, 2) - (msg.len % 2); // TODO: test this math lmao
try self.chatBuf.cursorAt(row, column).writer().writeAll(msg);
}
},
.chat => |c| {
// re-render the message if width changed in the meantime
if (padded_width != term_message.buffer.width) {
std.log.debug("must rerender msg!", .{});
term_message.buffer.deinit();
term_message.buffer = try zbox.Buffer.init(self.allocator, 1, padded_width);
try self.renderMessage(term_message);
}
// Update the row position
// NOTE: row stops at zero, but we want to blit at
// negative coordinates if we have to.
const msg_height = term_message.buffer.height;
self.chatBuf.blit(
term_message.buffer,
@intCast(isize, row) - @intCast(isize, msg_height),
padding,
);
// If the message is selected, time to invert everything!
if (term_message.is_selected) {
var rx: usize = row - std.math.min(msg_height, row);
while (rx < row) : (rx += 1) {
var cx: usize = padding - 1;
while (cx < self.chatBuf.width) : (cx += 1) {
self.chatBuf.cellRef(rx, cx).attribs.reverse = true;
}
}
}
row -= std.math.min(msg_height, row);
// Do we have space for the nickname?
blk: {
if (row > 0) {
if (m.prev) |prev| {
if (std.mem.eql(u8, m.login_name, prev.login_name)) {
const prev_time = prev.time;
if (std.meta.eql(prev_time, m.time)) {
var cur = self.chatBuf.cursorAt(row, 0);
cur.attribs = .{
.fg_blue = true,
};
try cur.writer().writeAll(" >>");
} else {
var cur = self.chatBuf.cursorAt(row, 0);
cur.attribs = .{
.feint = true,
};
try cur.writer().writeAll(&m.time);
}
break :blk;
}
}
row -= 1;
var nick = c.display_name[0..std.math.min(self.chatBuf.width - 5, c.display_name.len)];
var cur = self.chatBuf.cursorAt(row, 0);
cur.attribs = .{
.bold = true,
};
// Time
{
try cur.writer().print(
"{s} ",
.{m.time},
);
}
// Nickname
var nickname_end_col: usize = undefined;
{
var nick_left = "«";
var nick_right = "»";
var highligh_nick = false;
switch (self.active_interaction) {
else => {},
.username => |tm| {
if (tm == term_message) {
highligh_nick = true;
nick_right = "«";
nick_left = "»";
}
},
}
cur.attribs = .{
.fg_yellow = true,
.reverse = highligh_nick,
};
cur.interactive_element = .{
.username = term_message,
};
try cur.writer().print("{s}", .{nick_left});
{
cur.attribs = .{
.fg_yellow = highligh_nick,
.reverse = highligh_nick,
};
try cur.writer().print("{s}", .{nick});
nickname_end_col = cur.col_num;
}
cur.attribs = .{
.fg_yellow = true,
.reverse = highligh_nick,
};
try cur.writer().print("{s}", .{nick_right});
cur.interactive_element = .none;
}
// Badges
const badges_width: usize = if (c.is_mod) 4 else 3;
if (c.sub_months > 0 and
!std.mem.eql(u8, self.config.nick, m.login_name))
{
var sub_cur = self.chatBuf.cursorAt(
cur.row_num,
self.chatBuf.width - badges_width,
);
try sub_cur.writer().print("[", .{});
// Subscriber badge
{
sub_cur.interactive_element = .{
.subscriber_badge = term_message,
};
if (c.is_founder) {
sub_cur.attribs = .{
.fg_yellow = true,
};
}
try sub_cur.writer().print("S", .{});
sub_cur.interactive_element = .none;
sub_cur.attribs = .{};
}
// Mod badge
if (c.is_mod) {
// sub_cur.interactive_element = .none;
// TODO: interactive element for mods
try sub_cur.writer().print("M", .{});
sub_cur.interactive_element = .none;
}
try sub_cur.writer().print("]", .{});
}
switch (self.active_interaction) {
else => {},
.subscriber_badge => |tm| {
if (tm == term_message) {
try renderSubBadgeOverlay(
c.sub_months,
&self.overlayBuf,
if (cur.row_num >= 3)
cur.row_num - 3
else
0,
badges_width,
);
}
},
.username => |_| {
// if (tm == term_message) {
// try renderUserActionsOverlay(
// c,
// &self.overlayBuf,
// cur.row_num,
// nickname_end_col + 1,
// );
// }
},
}
}
}
},
}
}
}
// Render the bottom bar
{
const width = self.output.width - 1;
const bottom_bar_row = self.output.height - 1 - if (self.config.afk_position == .bottom and self.afk_message != null)
AfkMessage.height
else
0;
// The temporary CTRLC message has higher priority
// than all other messages.
if (self.ctrlc_pressed) {
const msg = "run `./bork quit`";
if (width > msg.len) {
var column = @divTrunc(width, 2) + (width % 2) - @divTrunc(msg.len, 2) - (msg.len % 2); // TODO: test this math lmao
try self.output.cursorAt(bottom_bar_row, column).writer().writeAll(msg);
}
var i: usize = 1;
while (i < width) : (i += 1) {
self.output.cellRef(bottom_bar_row, i).attribs = .{
.bg_white = true,
.fg_red = true,
};
}
} else if (chat.disconnected) {
const msg = "DISCONNECTED";
if (width > msg.len) {
var column = @divTrunc(width, 2) + (width % 2) - @divTrunc(msg.len, 2) - (msg.len % 2); // TODO: test this math lmao
try self.output.cursorAt(bottom_bar_row, column).writer().writeAll(msg);
}
var i: usize = 1;
while (i < width) : (i += 1) {
self.output.cellRef(bottom_bar_row, i).attribs = .{
.bg_red = true,
.fg_black = true,
};
}
} else if (chat.last_message == chat.bottom_message) {
var i: usize = 1;
while (i < width) : (i += 1) {
self.output.cellRef(bottom_bar_row, i).* = .{
.char = ' ',
.attribs = .{ .bg_blue = true },
};
}
} else {
const msg = "DETACHED";
var column: usize = 0;
if (width > msg.len) {
column = @divTrunc(width, 2) + (width % 2) - @divTrunc(msg.len, 2) - (msg.len % 2); // TODO: test this math lmao
try self.output.cursorAt(bottom_bar_row, column).writer().writeAll(msg);
}
var i: usize = 1;
while (i < width) : (i += 1) {
var cell = self.output.cellRef(bottom_bar_row, i);
cell.attribs = .{
.bg_yellow = true,
.fg_black = true,
// TODO: why is bold messing around with fg?
// .bold = true,
};
if (i < column or i >= column + msg.len) {
cell.char = ' ';
}
}
}
}
const chat_buf_row: usize = 1 + if (self.config.afk_position == .top and self.afk_message != null) AfkMessage.height else 0;
const afk_message_row: usize = switch (self.config.afk_position) {
.top => 0,
.hover => @divTrunc(@intCast(usize, self.output.height) - @intCast(usize, AfkMessage.height), 2),
.bottom => self.output.height - AfkMessage.height,
};
self.output.blit(self.chatBuf, @intCast(isize, chat_buf_row), 1);
self.output.blit(self.overlayBuf, @intCast(isize, chat_buf_row), 1);
if (self.afk_message) |afk| self.output.blit(afk.buffer, @intCast(isize, afk_message_row), 1);
try zbox.push(self.output);
std.log.debug("render completed!", .{});
}
pub fn handleClick(self: *Self, row: usize, col: usize) !bool {
// Find the element that was clicked,
// do the corresponding action.
const cell = zbox.front.cellRef(
std.math.min(row, zbox.front.height - 1),
std.math.min(col, zbox.front.width - 1),
);
std.log.debug("cell clicked: {s}", .{@tagName(cell.interactive_element)});
if (self.active_interaction == .none and
cell.interactive_element == .none)
{
return false;
}
var old_action = self.active_interaction;
self.active_interaction = if (std.meta.eql(
self.active_interaction,
cell.interactive_element,
))
.none
else
cell.interactive_element;
// Special rule when going from username to chat_message.
// This makes clicking on a message disable the username selection
// without immediately triggering the single-message selection.
if (old_action == .username) {
switch (self.active_interaction) {
else => {},
.chat_message => |tm| {
if (tm.is_selected) {
self.active_interaction = .none;
}
},
}
}
if (!std.meta.eql(old_action, self.active_interaction)) {
// Perform element-specific cleanup for the old element
switch (old_action) {
.none, .button, .subscriber_badge, .event_message, .afk => {},
.chat_message => |tm| {
tm.is_selected = false;
},
.username => |tm| {
// Username elements can't point to .line messages
tm.is_selected = false;
const name = tm.chat_message.login_name;
var next = tm.chat_message.next;
while (next) |n| : (next = n.next) {
switch (n.kind) {
else => break,
.chat => {
if (!std.mem.eql(u8, n.login_name, name)) break;
var term_message = @fieldParentPtr(TerminalMessage, "chat_message", n);
term_message.is_selected = false;
},
}
}
},
}
// Perform element-specific setup for the new element
switch (self.active_interaction) {
.none, .button, .subscriber_badge => {},
.afk => {
if (self.afk_message) |*afk| {
afk.deinit(self.allocator);
self.afk_message = null;
// Restore the original chatBufSize when closing
// a non-hovering afk box.
if (self.config.afk_position != .hover) {
const chatBufSize: usize = self.output.height - 2;
try self.chatBuf.resize(chatBufSize, self.output.width - 2);
try self.overlayBuf.resize(chatBufSize, self.output.width - 2);
}
}
},
.chat_message => |tm| {
// If the message came in highlighted we must clear
// it and also clear the active interaction.
if (tm.is_selected) {
tm.is_selected = false;
self.active_interaction = .none;
} else {
tm.is_selected = true;
}
},
.event_message => |tm| {
tm.is_selected = false;
if (tm.chat_message.kind == .sub_mistery_gift) {
var next = tm.chat_message.next;
while (next) |n| : (next = n.next) {
switch (n.kind) {
else => break,
.sub_gift => |_| {
var term_message = @fieldParentPtr(TerminalMessage, "chat_message", n);
term_message.is_selected = false;
},
}
}
}
},
.username => |tm| {
// Username elements can't point to .line messages
tm.is_selected = true;
const name = tm.chat_message.login_name;
var next = tm.chat_message.next;
while (next) |n| : (next = n.next) {
switch (n.kind) {
else => break,
.chat => {
if (!std.mem.eql(u8, n.login_name, name)) break;
var term_message = @fieldParentPtr(TerminalMessage, "chat_message", n);
term_message.is_selected = true;
},
}
}
},
}
}
return true;
}
pub fn clearActiveInteraction(self: *Self, all_or_name: ?[]const u8) void {
if (all_or_name) |name| {
const msg_name = switch (self.active_interaction) {
.subscriber_badge => |m| m.chat_message.login_name,
.username => |m| m.chat_message.login_name,
.chat_message => |m| m.chat_message.login_name,
.event_message => |m| m.chat_message.login_name,
else => return,
};
if (!std.mem.eql(u8, name, msg_name)) {
return;
}
}
self.active_interaction = .none;
}
fn renderSubBadgeOverlay(months: usize, buf: *zbox.Buffer, row: usize, badges_width: usize) !void {
const fmt = " Sub for {d} months ";
const fmt_len = std.fmt.count(fmt, .{months});
const space_needed = (fmt_len + badges_width + 1);
if (space_needed >= buf.width) return;
const left = buf.width - space_needed;
var cur = buf.cursorAt(row + 1, left);
try cur.writer().print(fmt, .{months});
while (cur.col_num < buf.width - badges_width) {
try cur.writer().print(" ", .{});
}
Box.draw(.double, buf, row, left - 1, fmt_len + 1, 3);
}
fn renderUserActionsOverlay(
_: Chat.Message.Comment,
buf: *zbox.Buffer,
row: usize,
col: usize,
) !void {
if (row <= 4 or buf.width - col <= 5) return;
Box.draw(.single, buf, row - 4, col + 1, 4, 5);
const btns = .{
.{ "BAN", "fg_red" },
.{ "MOD", "fg_yellow" },
.{ "VIP", "fg_blue" },
};
var cur: zbox.Buffer.WriteCursor = undefined;
inline for (btns) |button, i| {
cur = buf.cursorAt(row - 3 + i, col + 2);
@field(cur.attribs, button[1]) = true;
try cur.writer().print(button[0], .{});
}
cur.row_num += 1;
cur.col_num = col;
cur.attribs = .{};
try cur.writer().print("─┺", .{});
// var cur: zbox.Buffer.WriteCursor = undefined;
// inline for (btns) |button, i| {
// cur = buf.cursorAt(row - 3 + i, 1);
// @field(cur.attribs, button[1]) = true;
// try cur.writer().print(button[0], .{});
// }
// cur.row_num += 1;
// cur.attribs = .{};
// try cur.writer().print("┹─", .{});
}
fn renderMessageActionsOverlay(
_: Chat.Message.Comment,
buf: *zbox.Buffer,
row: usize,
) !void {
Box.draw(.single, buf, row - 4, 0, 4, 5);
const btns = .{
.{ "DEL", "fg_red" },
.{ "PIN", "fg_blue" },
};
var cur: zbox.Buffer.WriteCursor = undefined;
inline for (btns) |button, i| {
cur = buf.cursorAt(row - 3 + i, 1);
@field(cur.attribs, button[1]) = true;
try cur.writer().print(button[0], .{});
}
cur.row_num += 1;
cur.attribs = .{};
try cur.writer().print("┹─", .{});
}
const Box = struct {
// 0 1 2 3 4 5
const double = [6]u21{ '╔', '╗', '╚', '╝', '═', '║' };
const single = [6]u21{ '┏', '┓', '┗', '┛', '━', '┃' };
fn draw(comptime set: @Type(.EnumLiteral), buf: *zbox.Buffer, row: usize, col: usize, width: usize, height: usize) void {
const char_set = @field(Box, @tagName(set));
{
var i: usize = col;
while (i < col + width) : (i += 1) {
buf.cellRef(row, i).* = .{ .char = char_set[4] };
buf.cellRef(row + height - 1, i).* = .{ .char = char_set[4] };
}
}
{
var i: usize = row;
while (i < row + height - 1) : (i += 1) {
buf.cellRef(i, col).* = .{ .char = char_set[5] };
buf.cellRef(i, col + width).* = .{ .char = char_set[5] };
}
}
buf.cellRef(row, col).* = .{ .char = char_set[0] };
buf.cellRef(row, col + width).* = .{ .char = char_set[1] };
buf.cellRef(row + height - 1, col).* = .{ .char = char_set[2] };
buf.cellRef(row + height - 1, col + width).* = .{ .char = char_set[3] };
}
};
// Called by the main event loop every update to ask us if
// we need to repaint. Useful for driving animations.
pub fn needAnimationFrame(self: *Self) bool {
return if (self.afk_message) |afk| afk.needsToAnimate() else false;
}
pub fn setAfkMessage(self: *Self, target_time: i64, reason: []const u8, title: []const u8) !void {
std.log.debug("afk: {d}, {s}", .{ target_time, reason });
if (self.afk_message) |*old| {
old.deinit(self.allocator);
} else {
// Shrink chatBuf if the position is not hovering
// (since there was no afk message showing before)
if (self.config.afk_position != .hover) {
const chatBufSize: usize = self.output.height - 2 - AfkMessage.height;
try self.chatBuf.resize(chatBufSize, self.output.width - 2);
try self.overlayBuf.resize(chatBufSize, self.output.width - 2);
}
}
self.afk_message = .{
.title = title,
.reason = reason,
.target_time = target_time,
.last_updated = 0,
.buffer = try zbox.Buffer.init(self.allocator, 0, 0),
};
} | src/Terminal.zig |
const std = @import("std");
const assert = std.debug.assert;
const IO_Uring = std.os.linux.IO_Uring;
const io_uring_cqe = std.os.linux.io_uring_cqe;
/// Using non-blocking io_uring, write a page, fsync the write, then read the page back in.
/// Rinse and repeat to iterate across a large file.
///
/// Note that this is all non-blocking, but with a pure single-threaded event loop, something that
/// is not otherwise possible on Linux for cached I/O.
///
/// There are several io_uring optimizations that we don't take advantage of here:
/// * SQPOLL to eliminate submission syscalls entirely.
/// * Registered file descriptors to eliminate atomic file referencing in the kernel.
/// * Registered buffers to eliminate page mapping in the kernel.
/// * Finegrained submission, at present we simply submit a batch of events then wait for a batch.
/// We could also submit a batch of events, and then submit partial batches as events complete.
pub fn main() !void {
if (std.builtin.os.tag != .linux) return error.LinuxRequired;
const size: usize = 256 * 1024 * 1024;
const page: usize = 4096;
const runs: usize = 5;
const path = "file_io_uring";
const file = try std.fs.cwd().createFile(path, .{ .read = true, .truncate = true });
defer file.close();
defer std.fs.cwd().deleteFile(path) catch {};
const fd = file.handle;
var buffer_w = [_]u8{1} ** page;
var buffer_r = [_]u8{0} ** page;
const event_w = 1;
const event_f = 2;
const event_r = 3;
var cqes: [512]io_uring_cqe = undefined;
var ring = try IO_Uring.init(cqes.len, 0);
var run: usize = 0;
while (run < runs) : (run += 1) {
var start = std.time.milliTimestamp();
var pages: usize = 0;
var syscalls: usize = 0;
var offset_submitted: usize = 0;
var offset_completed: usize = 0;
event_loop: while (true) {
// Consume groups of completed events:
const count = try ring.copy_cqes(cqes[0..], 0);
var i: usize = 0;
while (i < count) : (i += 1) {
const cqe = cqes[i];
switch (cqe.user_data) {
event_w => assert(cqe.res == page),
event_f => assert(cqe.res == 0),
event_r => {
assert(cqe.res == page);
pages += 1;
offset_completed += page;
if (offset_completed >= size) {
assert(offset_completed == offset_submitted);
break :event_loop;
}
},
else => {
std.debug.print("ERROR {}\n", .{cqe});
std.os.exit(1);
},
}
}
// Enqueue groups of read/fsync/write calls within the event loop:
var events: u32 = 0;
while (offset_submitted < size and events + 3 <= cqes.len) {
var w = try ring.write(event_w, fd, buffer_w[0..], offset_submitted);
w.flags |= std.os.linux.IOSQE_IO_LINK;
var f = try ring.fsync(event_f, fd, 0);
f.flags |= std.os.linux.IOSQE_IO_LINK;
var r = try ring.read(event_r, fd, buffer_r[0..], offset_submitted);
offset_submitted += page;
events += 3;
}
// Up until now, we have only appended to the SQ ring buffer, but without any syscalls.
// Now submit and wait for these groups of events with a single syscall.
// If we used SQPOLL, we wouldn't need this syscall to submit, only to wait, which
// `copy_cqes(N)` also supports. At present, `copy_cqes(0)` above does not wait because
// we do that here using `submit_and_wait(N)`.
_ = try ring.submit_and_wait(events);
syscalls += 1;
}
std.debug.print("fs io_uring: write({})/fsync/read({}) * {} pages = {} syscalls: {}ms\n", .{
page,
page,
pages,
syscalls,
std.time.milliTimestamp() - start,
});
}
} | demos/io_uring/fs_io_uring.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
fn ActiveSpots(comptime C: type) type { return std.AutoHashMap(C, void); }
pub fn Conway(comptime C: type) type {
return struct {
const Self = @This();
allocator: Allocator,
active_spots: ActiveSpots(C),
pub fn init(allocator: Allocator) Self {
return .{
.allocator = allocator,
.active_spots = ActiveSpots(C).init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.active_spots.deinit();
}
pub fn stepIterator(self: *Self) ConwayIterator(C) {
var prev_active_spots = self.active_spots;
self.active_spots = ActiveSpots(C).init(self.allocator);
return ConwayIterator(C).init(self.allocator, prev_active_spots, &self.active_spots);
}
};
}
pub fn ConwayIterator(comptime C: type) type {
return struct {
const Stage = union (enum) {
not_started: void,
iterate_active: ActiveSpots(C).KeyIterator,
iterate_inactive: ActiveSpots(C).KeyIterator,
done: void,
};
const Self = @This();
prev_active_spots: ActiveSpots(C),
next_active_spots: *ActiveSpots(C),
inactive_spots: ActiveSpots(C),
stage: Stage = .{ .not_started = {} },
coord: C = undefined,
active: bool = undefined,
active_neighbors: u8 = undefined,
fn init(allocator: Allocator, prev_active_spots: ActiveSpots(C), next_active_spots: *ActiveSpots(C)) Self {
return .{
.prev_active_spots = prev_active_spots,
.next_active_spots = next_active_spots,
.inactive_spots = ActiveSpots(C).init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.prev_active_spots.deinit();
self.inactive_spots.deinit();
}
pub fn next(self: *Self) !bool {
while (true) {
switch (self.stage) {
.not_started => {
self.stage = .{ .iterate_active = self.prev_active_spots.keyIterator() };
continue;
},
.iterate_active => |*iter| {
if (iter.next()) |coord| {
return self.iterateActive(coord.*);
}
self.stage = .{ .iterate_inactive = self.inactive_spots.keyIterator() };
continue;
},
.iterate_inactive => |*iter| {
if (iter.next()) |coord| {
return self.iterateInactive(coord.*);
}
self.stage = .{ .done = {} };
continue;
},
.done => return false,
}
}
}
pub fn setActive(self: *Self, active: bool) !void {
if (active) {
try self.next_active_spots.put(self.coord, {});
}
else if (self.stage == .iterate_inactive) {
try self.inactive_spots.put(self.coord, {});
}
}
fn iterateActive(self: *Self, coord: C) !bool {
self.coord = coord;
self.active = true;
self.active_neighbors = 0;
var neighbors = coord.neighbors(false);
while (neighbors.next()) |neighbor| {
if (self.prev_active_spots.contains(neighbor)) {
self.active_neighbors += 1;
}
else {
try self.inactive_spots.put(neighbor, {});
}
}
return true;
}
fn iterateInactive(self: *Self, coord: C) bool {
self.coord = coord;
self.active = false;
self.active_neighbors = 0;
var neighbors = coord.neighbors(false);
while (neighbors.next()) |neighbor| {
if (self.prev_active_spots.contains(neighbor)) {
self.active_neighbors += 1;
}
}
return true;
}
};
} | src/main/zig/lib/conway.zig |
const std = @import("std");
const meta = std.meta;
const print = std.debug.print;
const Needle = @import("needle.zig").Needle;
const call_fn_with_union_type = @import("needle.zig").call_fn_with_union_type;
const testing = std.testing;
pub fn parseStringForType(string: []const u8) !Needle {
if (string.len == 0) return error.EmptyStringProvided;
const Subtype = enum {
uint,
int,
float,
string,
};
const head = string[0];
const subtype = switch (head) {
's' => Subtype.string,
'i' => Subtype.int,
'u' => Subtype.uint,
'f' => Subtype.float,
else => return error.InvalidTypeHint,
};
switch (subtype) {
.string => return Needle{ .string = undefined },
.int, .uint, .float => {
if (string.len == 1) return error.NoBitAmountProvided;
const bits = std.fmt.parseInt(u8, string[1..], 10) catch return error.InvalidBitNumber;
return switch (subtype) {
.string => unreachable,
.int => switch (bits) {
8 => Needle{ .i8 = undefined },
16 => Needle{ .i16 = undefined },
32 => Needle{ .i32 = undefined },
64 => Needle{ .i64 = undefined },
128 => Needle{ .i128 = undefined },
else => error.InvalidBitCountForInt,
},
.uint => switch (bits) {
8 => Needle{ .u8 = undefined },
16 => Needle{ .u16 = undefined },
32 => Needle{ .u32 = undefined },
64 => Needle{ .u64 = undefined },
128 => Needle{ .u128 = undefined },
else => error.InvalidBitCountForUInt,
},
.float => switch (bits) {
16 => Needle{ .f16 = undefined },
32 => Needle{ .f32 = undefined },
64 => Needle{ .f64 = undefined },
128 => Needle{ .f128 = undefined },
else => error.InvalidBitCountForFloat,
},
};
},
}
}
pub fn askUserForType() Needle {
if (getStdin()) |string| {
return parseStringForType(string) catch return askUserForType();
} else {
print("try again\n", .{});
return askUserForType();
}
}
var user_value_buffer = [_]u8{0} ** 128;
/// Asks user for input, expecting it to conform to a specific type.
/// However, this is a type chosen at runtime instead of comptime.
/// Thus, we have to go about this in a roundabout fashion.
/// Eventually, we return the bytes representing the input value for the requested type.
/// The bytes returned are global to this module and are not owned by the caller.
pub fn askUserForValue(needle: *Needle) ![]u8 {
print("Please enter value for {s} ", .{std.meta.tagName(needle.*)});
call_fn_with_union_type(needle.*, void, printMinMax, .{});
print("> ", .{});
const maybe_input = getStdin();
var buffer = user_value_buffer[0..];
if (maybe_input) |input| {
switch (needle.*) {
.string => {
return input;
},
else => {
return try stringToType(input, needle);
},
}
} else {
return error.NoInputGiven;
}
}
/// Prints the minimum and maximum value a type can be.
fn printMinMax(comptime T: type) void {
switch (@typeInfo(T)) {
.Int => {
const min = std.math.minInt(T);
const max = std.math.maxInt(T);
print("between {} and {} ", .{ min, max });
},
.Float => {
const min_max = switch (T) {
f16 => .{ std.math.f16_min, std.math.f16_max },
f32 => .{ std.math.f32_min, std.math.f32_max },
f64 => .{ std.math.f64_min, std.math.f64_max },
f128 => .{ std.math.f128_min, std.math.f128_max },
else => unreachable,
};
print("{} and {}", .{ min_max[0], min_max[1] });
},
else => {},
}
}
/// Reads string as a specified type.
/// Sets the needle's value to that result.
/// Reinterprets result as bytes, which then get returned.
/// Returned bytes are simply another representation of the needle data.
/// Therefore, they will change as the needle does, and they do not need to be free'd.
pub fn stringToType(string: []const u8, needle: *Needle) std.fmt.ParseIntError![]u8 {
return try call_fn_with_union_type(needle.*, std.fmt.ParseIntError![]u8, stringToType_internal, .{ string, needle });
}
/// Internal implementation of stringToType.
/// Must be split into separate function because we are calling it with a comptime type derived from a given union type.
fn stringToType_internal(comptime T: type, string: []const u8, needle: *Needle) std.fmt.ParseIntError![]u8 {
const tn = @tagName(needle.*);
const result = switch (@typeInfo(T)) {
.Int => |i| try std.fmt.parseInt(T, string, 10),
.Float => |f| try std.fmt.parseFloat(T, string),
// Would prefer to have the 'Void' case handled by our 'else' clause.
// However, it gives compile errors in zig 0.7.1.
.Void => unreachable,
else => @compileError("Function called with invalid type " ++ @typeName(T)),
};
inline for (@typeInfo(Needle).Union.fields) |field| {
if (field.field_type == T) {
needle.* = @unionInit(Needle, field.name, result);
return std.mem.asBytes(&@field(needle, field.name));
}
}
@compileError(@typeName(T) ++ " is not a member of the given union " ++ @typeName(@TypeOf(needle.*)));
}
test "string to type" {
var needle = Needle{ .u8 = 0 };
// Invalid strings.
try testing.expectError(error.Overflow, stringToType("-100", &needle));
try testing.expectError(error.Overflow, stringToType("256", &needle));
try testing.expectError(error.InvalidCharacter, stringToType("100 ", &needle));
// Valid string.
var byte_repr = try stringToType("255", &needle);
try testing.expect(std.mem.eql(u8, byte_repr, &[_]u8{0xff}));
// Prove function changes needle value.
try testing.expectEqual(needle.u8, 255);
// stringToType returns an array backed by the needle itself.
needle = Needle{ .i16 = 0 };
byte_repr = try stringToType("-1000", &needle);
// Sanity check.
var input_needle_value: i16 = -1000;
try testing.expectEqual(needle.i16, input_needle_value);
var expected_bytes = std.mem.asBytes(&input_needle_value);
// Establish expected byte representation.
try testing.expect(std.mem.eql(u8, byte_repr, expected_bytes));
// Prove byte_repr is backed by needle, even as needle changes.
needle.i16 += 1;
try testing.expectEqual(needle.i16, -999);
// We have modified needle only, yet byte_repr will change as well.
try testing.expect(!std.mem.eql(u8, byte_repr, expected_bytes));
}
var stdin_buffer = [_]u8{0} ** 100;
pub fn getStdin() ?[]u8 {
const stdin = std.io.getStdIn();
var read_bytes = stdin.read(stdin_buffer[0..]) catch return null;
if (read_bytes == 0) return null;
if (stdin_buffer[0] == 0 or stdin_buffer[0] == '\n') return null;
if (stdin_buffer[read_bytes - 1] == '\n') read_bytes -= 1;
return stdin_buffer[0..read_bytes];
} | src/input.zig |
const std = @import("std");
const Parser = @import("parser.zig").Parser;
const nodes = @import("nodes.zig");
const scanners = @import("scanners.zig");
const strings = @import("strings.zig");
pub fn matches(allocator: *std.mem.Allocator, line: []const u8) !bool {
var r = try row(allocator, line);
var result = r != null;
if (r) |v| freeNested(allocator, v);
return result;
}
pub fn freeNested(allocator: *std.mem.Allocator, v: [][]u8) void {
for (v) |e|
allocator.free(e);
allocator.free(v);
}
fn row(allocator: *std.mem.Allocator, line: []const u8) !?[][]u8 {
const len = line.len;
var v = std.ArrayList([]u8).init(allocator);
errdefer freeNested(allocator, v.toOwnedSlice());
var offset: usize = 0;
if (len > 0 and line[0] == '|')
offset += 1;
while (true) {
const cell_matched = (try scanners.tableCell(line[offset..])) orelse 0;
var pipe_matched = (try scanners.tableCellEnd(line[offset + cell_matched ..])) orelse 0;
if (cell_matched > 0 or pipe_matched > 0) {
var cell = try unescapePipes(allocator, line[offset .. offset + cell_matched]);
strings.trimIt(&cell);
try v.append(cell.toOwnedSlice());
}
offset += cell_matched + pipe_matched;
if (pipe_matched == 0) {
pipe_matched = (try scanners.tableRowEnd(line[offset..])) orelse 0;
offset += pipe_matched;
}
if (!((cell_matched > 0 or pipe_matched > 0) and offset < len)) {
break;
}
}
if (offset != len or v.items.len == 0) {
freeNested(allocator, v.toOwnedSlice());
return null;
} else {
return v.toOwnedSlice();
}
}
pub fn tryOpeningBlock(parser: *Parser, container: *nodes.AstNode, line: []const u8, replace: *bool) !?*nodes.AstNode {
return switch (container.data.value) {
.Paragraph => try tryOpeningHeader(parser, container, line, replace),
.Table => |aligns| tryOpeningRow(parser, container, aligns, line, replace),
else => null,
};
}
fn tryOpeningHeader(parser: *Parser, container: *nodes.AstNode, line: []const u8, replace: *bool) !?*nodes.AstNode {
if ((try scanners.tableStart(line[parser.first_nonspace..])) == null) {
replace.* = false;
return container;
}
const header_row = (try row(parser.allocator, container.data.content.items)) orelse {
replace.* = false;
return container;
};
defer freeNested(parser.allocator, header_row);
const marker_row = (try row(parser.allocator, line[parser.first_nonspace..])).?;
defer freeNested(parser.allocator, marker_row);
if (header_row.len != marker_row.len) {
replace.* = false;
return container;
}
var alignments = try parser.allocator.alloc(nodes.TableAlignment, marker_row.len);
errdefer parser.allocator.free(alignments);
for (marker_row) |cell, i| {
const left = cell.len > 0 and cell[0] == ':';
const right = cell.len > 0 and cell[cell.len - 1] == ':';
alignments[i] = if (left and right)
nodes.TableAlignment.Center
else if (left)
nodes.TableAlignment.Left
else if (right)
nodes.TableAlignment.Right
else
nodes.TableAlignment.None;
}
var table = try nodes.AstNode.create(parser.allocator, .{
.value = .{ .Table = alignments },
.start_line = parser.line_number,
.content = std.ArrayList(u8).init(parser.allocator),
});
container.append(table);
var header = try parser.addChild(table, .{ .TableRow = .Header });
for (header_row) |header_str| {
var header_cell = try parser.addChild(header, .TableCell);
try header_cell.data.content.appendSlice(header_str);
}
const offset = line.len - 1 - parser.offset;
parser.advanceOffset(line, offset, false);
replace.* = true;
return table;
}
fn tryOpeningRow(parser: *Parser, container: *nodes.AstNode, aligns: []nodes.TableAlignment, line: []const u8, replace: *bool) !?*nodes.AstNode {
if (parser.blank)
return null;
const this_row = (try row(parser.allocator, line[parser.first_nonspace..])).?;
defer freeNested(parser.allocator, this_row);
const new_row = try parser.addChild(container, .{ .TableRow = .Body });
var i: usize = 0;
while (i < std.math.min(aligns.len, this_row.len)) : (i += 1) {
var cell = try parser.addChild(new_row, .TableCell);
try cell.data.content.appendSlice(this_row[i]);
}
while (i < aligns.len) : (i += 1) {
_ = try parser.addChild(new_row, .TableCell);
}
const offset = line.len - 1 - parser.offset;
parser.advanceOffset(line, offset, false);
replace.* = false;
return new_row;
}
fn unescapePipes(allocator: *std.mem.Allocator, string: []const u8) !std.ArrayList(u8) {
var v = try std.ArrayList(u8).initCapacity(allocator, string.len);
for (string) |c, i| {
if (c == '\\' and i + 1 < string.len and string[i + 1] == '|') {
continue;
} else {
try v.append(c);
}
}
return v;
} | src/table.zig |
const std = @import("std");
const png = @import("types.zig");
const imgio = @import("../../io.zig");
const utils = @import("../../utils.zig");
const color = @import("../../color.zig");
const PixelStorage = @import("../../pixel_storage.zig").PixelStorage;
const PixelFormat = @import("../../pixel_format.zig").PixelFormat;
const bigToNative = std.mem.bigToNative;
const ImageReader = imgio.ImageReader;
const ImageParsingError = png.ImageParsingError;
const mem = std.mem;
const File = std.fs.File;
const Crc32 = std.hash.Crc32;
const Allocator = std.mem.Allocator;
const RawFileReader = imgio.FileReader;
const RawBufferReader = imgio.BufferReader;
// Png specification: http://www.libpng.org/pub/png/spec/iso/index-object.html
pub const FileReader = Reader(true);
pub const BufferReader = Reader(false);
const ProfData = struct {
name: []const u8 = &[_]u8{},
count: u32 = 0,
dur: u64 = 0,
};
var prof_data_list = [_]ProfData{.{}} ** 113;
// To measure some function just add these two lines to its start:
// var timer = std.time.Timer.start() catch unreachable;
// defer measure(@src().fn_name, timer.read());
fn measure(comptime name: []const u8, dur: u64) void {
const index = Crc32.hash(name) % prof_data_list.len;
if (prof_data_list[index].name.len > 0 and prof_data_list[index].name[0] != name[0]) return;
prof_data_list[index].name = name;
prof_data_list[index].count += 1;
prof_data_list[index].dur += dur;
}
pub fn printProfData() void {
for (prof_data_list) |prof_data| {
if (prof_data.count == 0) continue;
std.debug.print("{s} => x{} {s}\n", .{ prof_data.name, prof_data.count, std.fmt.fmtDuration(prof_data.dur) });
}
}
pub fn fromFile(file: File) FileReader {
return .{
.raw_reader = RawFileReader.init(file),
};
}
pub fn fromMemory(buffer: []const u8) BufferReader {
return .{
.raw_reader = RawBufferReader.init(buffer),
};
}
fn Reader(comptime is_from_file: bool) type {
const RawReader = if (is_from_file) RawFileReader else RawBufferReader;
const Common = struct {
pub fn processChunk(processors: []ReaderProcessor, id: u32, chunk_process_data: *ChunkProcessData) ImageParsingError!void {
const l = id & 0xff;
// Critical chunks are already processed but we can still notify any number of processors about them
var processed = l >= 'A' and l <= 'Z';
for (processors) |*processor| {
if (processor.id == id) {
const new_format = try processor.processChunk(chunk_process_data);
std.debug.assert(new_format.getPixelStride() >= chunk_process_data.current_format.getPixelStride());
chunk_process_data.current_format = new_format;
if (!processed) {
// For non critical chunks we only allow one processor so we break after the first one
processed = true;
break;
}
}
}
// If noone loaded this chunk we need to skip over it
if (!processed) {
_ = try chunk_process_data.raw_reader.seekBy(@intCast(i64, chunk_process_data.chunk_length + 4));
}
}
};
// Provides reader interface for Zlib stream that knows to read consecutive IDAT chunks.
const IDatChunksReader = struct {
raw_reader: *RawReader,
processors: []ReaderProcessor,
chunk_process_data: *ChunkProcessData,
remaining_chunk_length: u32,
crc: Crc32,
const Self = @This();
fn init(
reader: *RawReader,
processors: []ReaderProcessor,
chunk_process_data: *ChunkProcessData,
) Self {
var crc = Crc32.init();
crc.update("IDAT");
return .{
.raw_reader = reader,
.processors = processors,
.chunk_process_data = chunk_process_data,
.remaining_chunk_length = chunk_process_data.chunk_length,
.crc = crc,
};
}
fn read(self: *Self, dest: []u8) ImageParsingError!usize {
if (self.remaining_chunk_length == 0) return 0;
const new_dest = dest;
var to_read = new_dest.len;
if (to_read > self.remaining_chunk_length) to_read = self.remaining_chunk_length;
const read_count = try self.raw_reader.read(new_dest[0..to_read]);
self.remaining_chunk_length -= @intCast(u32, read_count);
self.crc.update(new_dest[0..read_count]);
if (self.remaining_chunk_length == 0) {
// First read and check CRC of just finished chunk
const expected_crc = try self.raw_reader.readIntBig(u32);
if (self.crc.final() != expected_crc) return error.InvalidData;
try Common.processChunk(self.processors, png.HeaderData.chunk_type_id, self.chunk_process_data);
self.crc = Crc32.init();
self.crc.update("IDAT");
// Try to load the next IDAT chunk
const chunk = try self.raw_reader.readStruct(png.ChunkHeader);
if (chunk.type == std.mem.bytesToValue(u32, "IDAT")) {
self.remaining_chunk_length = chunk.length();
} else {
// Return to the start of the next chunk so code in main struct can read it
try self.raw_reader.seekBy(-@sizeOf(png.ChunkHeader));
}
}
return read_count;
}
};
const IDATReader = std.io.Reader(*IDatChunksReader, ImageParsingError, IDatChunksReader.read);
// =========== Main Png reader struct start here ===========
return struct {
raw_reader: RawReader,
const Self = @This();
pub fn loadHeader(self: *Self) ImageParsingError!png.HeaderData {
const sig = try self.raw_reader.readNoAlloc(png.magic_header.len);
if (!mem.eql(u8, sig[0..], png.magic_header)) return error.InvalidData;
const chunk = try self.raw_reader.readStruct(png.ChunkHeader);
if (chunk.type != png.HeaderData.chunk_type_id) return error.InvalidData;
if (chunk.length() != @sizeOf(png.HeaderData)) return error.InvalidData;
const header = (try self.raw_reader.readStruct(png.HeaderData));
if (!header.isValid()) return error.InvalidData;
const expected_crc = try self.raw_reader.readIntBig(u32);
var crc = Crc32.init();
crc.update(png.HeaderData.chunk_type);
crc.update(mem.asBytes(header));
const actual_crc = crc.final();
if (expected_crc != actual_crc) return error.InvalidData;
return header.*;
}
/// Loads the png image using the given allocator and options.
/// The options allow you to pass in a custom allocator for temporary allocations.
/// By default it will use a fixed buffer on stack for temporary allocations.
/// You can also pass in an array of chunk processors. You can use def_processors
/// array if you want to use these default set of processors:
/// 1. tRNS processor that decodes the tRNS chunk if it exists into an alpha channel
/// 2. PLTE processor that decodes the indexed image with a palette into a RGB image.
/// If you want default processors with default temp allocator you can just pass
/// predefined def_options. If you just pass .{} no processors will be used.
pub fn load(self: *Self, allocator: Allocator, options: ReaderOptions) ImageParsingError!PixelStorage {
const header = try self.loadHeader();
return try self.loadWithHeader(&header, allocator, options);
}
/// Loads the png image for which the header has already been loaded.
/// For options param description look at the load method docs.
pub fn loadWithHeader(
self: *Self,
header: *const png.HeaderData,
allocator: Allocator,
options: ReaderOptions,
) ImageParsingError!PixelStorage {
var opts = options;
var tmp_allocator = options.temp_allocator;
var fb_allocator = std.heap.FixedBufferAllocator.init(try tmp_allocator.alloc(u8, required_temp_bytes));
defer tmp_allocator.free(fb_allocator.buffer);
opts.temp_allocator = fb_allocator.allocator();
return try doLoad(self, header, allocator, &opts);
}
fn asU32(str: *const [4:0]u8) u32 {
return std.mem.bytesToValue(u32, str);
}
fn doLoad(
self: *Self,
header: *const png.HeaderData,
allocator: Allocator,
options: *const ReaderOptions,
) ImageParsingError!PixelStorage {
var palette: []color.Rgb24 = &[_]color.Rgb24{};
var data_found = false;
var result: PixelStorage = undefined;
var chunk_process_data = ChunkProcessData{
.raw_reader = ImageReader.wrap(&self.raw_reader),
.chunk_length = @sizeOf(png.HeaderData),
.current_format = header.getPixelFormat(),
.header = header,
.temp_allocator = options.temp_allocator,
};
try Common.processChunk(options.processors, png.HeaderData.chunk_type_id, &chunk_process_data);
while (true) {
const chunk = try self.raw_reader.readStruct(png.ChunkHeader);
switch (chunk.type) {
asU32("IHDR") => {
return error.InvalidData; // We already processed IHDR so another one is an error
},
asU32("IEND") => {
if (!data_found) return error.InvalidData;
_ = try self.raw_reader.readInt(u32); // Read and ignore the crc
chunk_process_data.chunk_length = chunk.length();
try Common.processChunk(options.processors, chunk.type, &chunk_process_data);
return result;
},
asU32("IDAT") => {
if (data_found) return error.InvalidData;
if (header.color_type == .indexed and palette.len == 0) return error.InvalidData;
chunk_process_data.chunk_length = chunk.length();
result = try self.readAllData(header, palette, allocator, options, &chunk_process_data);
data_found = true;
},
asU32("PLTE") => {
if (!header.allowsPalette()) return error.InvalidData;
if (palette.len > 0) return error.InvalidData;
// We ignore if tRNS is already found
const chunk_length = chunk.length();
if (chunk_length % 3 != 0) return error.InvalidData;
const length = chunk_length / 3;
if (length > header.maxPaletteSize()) return error.InvalidData;
if (data_found) {
// If IDAT was already processed we skip and ignore this palette
_ = try self.raw_reader.readNoAlloc(chunk_length + @sizeOf(u32));
} else {
if (!is_from_file) {
const palette_bytes = try self.raw_reader.readNoAlloc(chunk_length);
palette = std.mem.bytesAsSlice(png.PaletteType, palette_bytes);
} else {
palette = try options.temp_allocator.alloc(color.Rgb24, length);
const filled = try self.raw_reader.read(mem.sliceAsBytes(palette));
if (filled != palette.len * @sizeOf(color.Rgb24)) return error.EndOfStream;
}
const expected_crc = try self.raw_reader.readIntBig(u32);
var crc = Crc32.init();
crc.update("PLTE");
crc.update(mem.sliceAsBytes(palette));
const actual_crc = crc.final();
if (expected_crc != actual_crc) return error.InvalidData;
chunk_process_data.chunk_length = chunk_length;
try Common.processChunk(options.processors, chunk.type, &chunk_process_data);
}
},
else => {
chunk_process_data.chunk_length = chunk.length();
try Common.processChunk(options.processors, chunk.type, &chunk_process_data);
},
}
}
}
fn readAllData(
self: *Self,
header: *const png.HeaderData,
palette: []color.Rgb24,
allocator: Allocator,
options: *const ReaderOptions,
chunk_process_data: *ChunkProcessData,
) ImageParsingError!PixelStorage {
const native_endian = comptime @import("builtin").cpu.arch.endian();
const is_little_endian = native_endian == .Little;
const width = header.width();
const height = header.height();
const channel_count = header.channelCount();
const dest_format = chunk_process_data.current_format;
var result = try PixelStorage.init(allocator, dest_format, width * height);
errdefer result.deinit(allocator);
var idat_chunks_reader = IDatChunksReader.init(&self.raw_reader, options.processors, chunk_process_data);
var idat_reader: IDATReader = .{ .context = &idat_chunks_reader };
var decompressStream = std.compress.zlib.zlibStream(options.temp_allocator, idat_reader) catch return error.InvalidData;
if (palette.len > 0) {
var dest_palette = if (result.getPallete()) |res_palette|
res_palette
else
try options.temp_allocator.alloc(color.Rgba32, palette.len);
for (palette) |entry, n| {
dest_palette[n] = entry.toRgba32();
}
try processPalette(options, dest_palette);
}
var dest = result.pixelsAsBytes();
// For defiltering we need to keep two rows in memory so we allocate space for that
const filter_stride = (header.bit_depth + 7) / 8 * channel_count; // 1 to 8 bytes
const line_bytes = header.lineBytes();
const virtual_line_bytes = line_bytes + filter_stride;
const result_line_bytes = @intCast(u32, dest.len / height);
var tmpbytes = 2 * virtual_line_bytes;
// For deinterlacing we also need one temporary row of resulting pixels
if (header.interlace_method == .adam7) tmpbytes += result_line_bytes;
var tmp_allocator = if (tmpbytes < 128 * 1024) options.temp_allocator else allocator;
var tmp_buffer = try tmp_allocator.alloc(u8, tmpbytes);
defer tmp_allocator.free(tmp_buffer);
mem.set(u8, tmp_buffer, 0);
var prev_row = tmp_buffer[0..virtual_line_bytes];
var current_row = tmp_buffer[virtual_line_bytes .. 2 * virtual_line_bytes];
const pixel_stride = @intCast(u8, result_line_bytes / width);
std.debug.assert(pixel_stride == dest_format.getPixelStride());
var process_row_data = RowProcessData{
.dest_row = undefined,
.src_format = header.getPixelFormat(),
.dest_format = dest_format,
.header = header,
.temp_allocator = options.temp_allocator,
};
if (header.interlace_method == .none) {
var i: u32 = 0;
while (i < height) : (i += 1) {
var loaded = decompressStream.read(current_row[filter_stride - 1 ..]) catch return error.InvalidData;
var filled = loaded;
while (loaded > 0 and filled != line_bytes + 1) {
loaded = decompressStream.read(current_row[filter_stride - 1 + filled ..]) catch return error.InvalidData;
filled += loaded;
}
if (filled != line_bytes + 1) return error.EndOfStream;
try defilter(current_row, prev_row, filter_stride);
process_row_data.dest_row = dest[0..result_line_bytes];
dest = dest[result_line_bytes..];
spreadRowData(
process_row_data.dest_row,
current_row[filter_stride..],
header.bit_depth,
channel_count,
pixel_stride,
is_little_endian,
);
const result_format = try processRow(options.processors, &process_row_data);
if (result_format != dest_format) return error.InvalidData;
const tmp = prev_row;
prev_row = current_row;
current_row = tmp;
}
} else {
const start_x = [7]u8{ 0, 4, 0, 2, 0, 1, 0 };
const start_y = [7]u8{ 0, 0, 4, 0, 2, 0, 1 };
const xinc = [7]u8{ 8, 8, 4, 4, 2, 2, 1 };
const yinc = [7]u8{ 8, 8, 8, 4, 4, 2, 2 };
const pass_width = [7]u32{
(width + 7) / 8,
(width + 3) / 8,
(width + 3) / 4,
(width + 1) / 4,
(width + 1) / 2,
width / 2,
width,
};
const pass_height = [7]u32{
(height + 7) / 8,
(height + 7) / 8,
(height + 3) / 8,
(height + 3) / 4,
(height + 1) / 4,
(height + 1) / 2,
height / 2,
};
const pixel_bits = header.pixelBits();
const deinterlace_bit_depth: u8 = if (header.bit_depth <= 8) 8 else 16;
var dest_row = tmp_buffer[virtual_line_bytes * 2 ..];
var pass: u32 = 0;
while (pass < 7) : (pass += 1) {
if (pass_width[pass] == 0 or pass_height[pass] == 0) continue;
const pass_bytes = (pixel_bits * pass_width[pass] + 7) / 8;
const pass_length = pass_bytes + filter_stride;
const result_pass_line_bytes = pixel_stride * pass_width[pass];
const deinterlace_stride = xinc[pass] * pixel_stride;
mem.set(u8, prev_row, 0);
const destx = start_x[pass] * pixel_stride;
var desty = start_y[pass];
var y: u32 = 0;
while (y < pass_height[pass]) : (y += 1) {
var loaded = decompressStream.read(current_row[filter_stride - 1 .. pass_length]) catch return error.InvalidData;
var filled = loaded;
while (loaded > 0 and filled != pass_bytes + 1) {
loaded = decompressStream.read(current_row[filter_stride - 1 + filled ..]) catch return error.InvalidData;
filled += loaded;
}
if (filled != pass_bytes + 1) return error.EndOfStream;
try defilter(current_row[0..pass_length], prev_row[0..pass_length], filter_stride);
process_row_data.dest_row = dest_row[0..result_pass_line_bytes];
spreadRowData(
process_row_data.dest_row,
current_row[filter_stride..],
header.bit_depth,
channel_count,
pixel_stride,
false,
);
const result_format = try processRow(options.processors, &process_row_data);
if (result_format != dest_format) return error.InvalidData;
const line_start_adr = desty * result_line_bytes;
const start_byte = line_start_adr + destx;
const end_byte = line_start_adr + result_line_bytes;
spreadRowData(
dest[start_byte..end_byte],
process_row_data.dest_row,
deinterlace_bit_depth,
channel_count,
deinterlace_stride,
is_little_endian,
);
desty += yinc[pass];
const tmp = prev_row;
prev_row = current_row;
current_row = tmp;
}
}
}
// Just make sure zip stream gets to its end
var buf: [8]u8 = undefined;
var shouldBeZero = decompressStream.read(buf[0..]) catch return error.InvalidData;
std.debug.assert(shouldBeZero == 0);
return result;
}
fn processPalette(options: *const ReaderOptions, palette: []color.Rgba32) ImageParsingError!void {
var process_data = PaletteProcessData{ .palette = palette, .temp_allocator = options.temp_allocator };
for (options.processors) |*processor| {
try processor.processPalette(&process_data);
}
}
fn defilter(current_row: []u8, prev_row: []u8, filter_stride: u8) ImageParsingError!void {
const filter_byte = current_row[filter_stride - 1];
if (filter_byte > @enumToInt(png.FilterType.paeth)) return error.InvalidData;
const filter = @intToEnum(png.FilterType, filter_byte);
current_row[filter_stride - 1] = 0;
var x: u32 = filter_stride;
switch (filter) {
.none => {},
.sub => while (x < current_row.len) : (x += 1) {
current_row[x] +%= current_row[x - filter_stride];
},
.up => while (x < current_row.len) : (x += 1) {
current_row[x] +%= prev_row[x];
},
.average => while (x < current_row.len) : (x += 1) {
current_row[x] +%= @truncate(u8, (@intCast(u32, current_row[x - filter_stride]) + @intCast(u32, prev_row[x])) / 2);
},
.paeth => while (x < current_row.len) : (x += 1) {
const a = current_row[x - filter_stride];
const b = prev_row[x];
const c = prev_row[x - filter_stride];
var pa: i32 = @intCast(i32, b) - c;
var pb: i32 = @intCast(i32, a) - c;
var pc: i32 = pa + pb;
if (pa < 0) pa = -pa;
if (pb < 0) pb = -pb;
if (pc < 0) pc = -pc;
// zig fmt: off
current_row[x] +%= if (pa <= pb and pa <= pc) a
else if (pb <= pc) b
else c;
// zig fmt: on
},
}
}
fn spreadRowData(
dest_row: []u8,
current_row: []u8,
bit_depth: u8,
channel_count: u8,
pixel_stride: u8,
comptime byteswap: bool,
) void {
var pix: u32 = 0;
var src_pix: u32 = 0;
const result_line_bytes = dest_row.len;
switch (bit_depth) {
1, 2, 4 => {
while (pix < result_line_bytes) {
// color_type must be Grayscale or Indexed
var shift = @intCast(i4, 8 - bit_depth);
var mask = @as(u8, 0xff) << @intCast(u3, shift);
while (shift >= 0 and pix < result_line_bytes) : (shift -= @intCast(i4, bit_depth)) {
dest_row[pix] = (current_row[src_pix] & mask) >> @intCast(u3, shift);
pix += pixel_stride;
mask >>= @intCast(u3, bit_depth);
}
src_pix += 1;
}
},
8 => {
while (pix < result_line_bytes) : (pix += pixel_stride) {
var c: u32 = 0;
while (c < channel_count) : (c += 1) {
dest_row[pix + c] = current_row[src_pix + c];
}
src_pix += channel_count;
}
},
16 => {
var current_row16 = mem.bytesAsSlice(u16, current_row);
var dest_row16 = mem.bytesAsSlice(u16, dest_row);
const pixel_stride16 = pixel_stride / 2;
src_pix /= 2;
while (pix < dest_row16.len) : (pix += pixel_stride16) {
var c: u32 = 0;
while (c < channel_count) : (c += 1) {
// This is a comptime if so it is not executed in every loop
dest_row16[pix + c] = if (byteswap) @byteSwap(u16, current_row16[src_pix + c]) else current_row16[src_pix + c];
}
src_pix += channel_count;
}
},
else => unreachable,
}
}
fn processRow(processors: []ReaderProcessor, process_data: *RowProcessData) ImageParsingError!PixelFormat {
const starting_format = process_data.src_format;
var result_format = starting_format;
for (processors) |*processor| {
result_format = try processor.processDataRow(process_data);
process_data.src_format = result_format;
}
process_data.src_format = starting_format;
return result_format;
}
};
}
pub const ChunkProcessData = struct {
raw_reader: imgio.ImageReader,
chunk_length: u32,
current_format: PixelFormat,
header: *const png.HeaderData,
temp_allocator: Allocator,
};
pub const PaletteProcessData = struct {
palette: []color.Rgba32,
temp_allocator: Allocator,
};
pub const RowProcessData = struct {
dest_row: []u8,
src_format: PixelFormat,
dest_format: PixelFormat,
header: *const png.HeaderData,
temp_allocator: Allocator,
};
pub const ReaderProcessor = struct {
id: u32,
context: *anyopaque,
vtable: *const VTable,
const VTable = struct {
chunk_processor: ?fn (context: *anyopaque, data: *ChunkProcessData) ImageParsingError!PixelFormat,
palette_processor: ?fn (context: *anyopaque, data: *PaletteProcessData) ImageParsingError!void,
data_row_processor: ?fn (context: *anyopaque, data: *RowProcessData) ImageParsingError!PixelFormat,
};
const Self = @This();
pub inline fn processChunk(self: *Self, data: *ChunkProcessData) ImageParsingError!PixelFormat {
return if (self.vtable.chunk_processor) |cp| cp(self.context, data) else data.current_format;
}
pub inline fn processPalette(self: *Self, data: *PaletteProcessData) ImageParsingError!void {
if (self.vtable.palette_processor) |pp| try pp(self.context, data);
}
pub inline fn processDataRow(self: *Self, data: *RowProcessData) ImageParsingError!PixelFormat {
return if (self.vtable.data_row_processor) |drp| drp(self.context, data) else data.dest_format;
}
pub fn init(
id: *const [4]u8,
context: anytype,
comptime chunkProcessorFn: ?fn (ptr: @TypeOf(context), data: *ChunkProcessData) ImageParsingError!PixelFormat,
comptime paletteProcessorFn: ?fn (ptr: @TypeOf(context), data: *PaletteProcessData) ImageParsingError!void,
comptime dataRowProcessorFn: ?fn (ptr: @TypeOf(context), data: *RowProcessData) ImageParsingError!PixelFormat,
) Self {
const Ptr = @TypeOf(context);
const ptr_info = @typeInfo(Ptr);
std.debug.assert(ptr_info == .Pointer); // Must be a pointer
std.debug.assert(ptr_info.Pointer.size == .One); // Must be a single-item pointer
const alignment = ptr_info.Pointer.alignment;
const gen = struct {
fn chunkProcessor(ptr: *anyopaque, data: *ChunkProcessData) ImageParsingError!PixelFormat {
const self = @ptrCast(Ptr, @alignCast(alignment, ptr));
return @call(.{ .modifier = .always_inline }, chunkProcessorFn.?, .{ self, data });
}
fn paletteProcessor(ptr: *anyopaque, data: *PaletteProcessData) ImageParsingError!void {
const self = @ptrCast(Ptr, @alignCast(alignment, ptr));
return @call(.{ .modifier = .always_inline }, paletteProcessorFn.?, .{ self, data });
}
fn dataRowProcessor(ptr: *anyopaque, data: *RowProcessData) ImageParsingError!PixelFormat {
const self = @ptrCast(Ptr, @alignCast(alignment, ptr));
return @call(.{ .modifier = .always_inline }, dataRowProcessorFn.?, .{ self, data });
}
const vtable = VTable{
.chunk_processor = if (chunkProcessorFn == null) null else chunkProcessor,
.palette_processor = if (paletteProcessorFn == null) null else paletteProcessor,
.data_row_processor = if (dataRowProcessorFn == null) null else dataRowProcessor,
};
};
return .{
.id = std.mem.bytesToValue(u32, id),
.context = context,
.vtable = &gen.vtable,
};
}
};
pub const TrnsProcessor = struct {
const Self = @This();
const TRNSData = union(enum) { unset: void, gray: u16, rgb: color.Rgb48, index_alpha: []u8 };
trns_data: TRNSData = .unset,
processed: bool = false,
pub fn processor(self: *Self) ReaderProcessor {
return ReaderProcessor.init(
"tRNS",
self,
processChunk,
processPalette,
processDataRow,
);
}
pub fn processChunk(self: *Self, data: *ChunkProcessData) ImageParsingError!PixelFormat {
// We will allow multiple tRNS chunks and load the first one
// We ignore if we encounter this chunk with color_type that already has alpha
var result_format = data.current_format;
if (self.processed) {
try data.raw_reader.seekBy(data.chunk_length + @sizeOf(u32)); // Skip invalid
return result_format;
}
switch (result_format) {
.grayscale1, .grayscale2, .grayscale4, .grayscale8, .grayscale16 => {
if (data.chunk_length == 2) {
self.trns_data = .{ .gray = try data.raw_reader.readIntBig(u16) };
result_format = if (result_format == .grayscale16) .grayscale16Alpha else .grayscale8Alpha;
} else {
try data.raw_reader.seekBy(data.chunk_length); // Skip invalid
}
},
.index1, .index2, .index4, .index8, .index16 => {
if (data.chunk_length <= data.header.maxPaletteSize()) {
self.trns_data = .{ .index_alpha = try data.temp_allocator.alloc(u8, data.chunk_length) };
const filled = try data.raw_reader.read(self.trns_data.index_alpha);
if (filled != self.trns_data.index_alpha.len) return error.EndOfStream;
} else {
try data.raw_reader.seekBy(data.chunk_length); // Skip invalid
}
},
.rgb24, .rgb48 => {
if (data.chunk_length == @sizeOf(color.Rgb48)) {
self.trns_data = .{ .rgb = (try data.raw_reader.readStruct(color.Rgb48)).* };
result_format = if (result_format == .rgb48) .rgba64 else .rgba32;
} else {
try data.raw_reader.seekBy(data.chunk_length); // Skip invalid
}
},
else => try data.raw_reader.seekBy(data.chunk_length), // Skip invalid
}
// Read but ignore Crc since this is not critical chunk
try data.raw_reader.seekBy(@sizeOf(u32));
return result_format;
}
pub fn processPalette(self: *Self, data: *PaletteProcessData) ImageParsingError!void {
self.processed = true;
switch (self.trns_data) {
.index_alpha => |index_alpha| {
for (index_alpha) |alpha, i| {
data.palette[i].a = alpha;
}
},
.unset => return,
else => unreachable,
}
}
pub fn processDataRow(self: *Self, data: *RowProcessData) ImageParsingError!PixelFormat {
self.processed = true;
if (data.src_format.isIndex() or self.trns_data == .unset) return data.src_format;
var pixel_stride: u8 = switch (data.dest_format) {
.grayscale8Alpha, .grayscale16Alpha => 2,
.rgba32, .bgra32 => 4,
.rgba64 => 8,
else => return data.src_format,
};
var pixel_pos: u32 = 0;
switch (self.trns_data) {
.gray => |gray_alpha| {
switch (data.src_format) {
.grayscale1, .grayscale2, .grayscale4, .grayscale8 => {
while (pixel_pos + 1 < data.dest_row.len) : (pixel_pos += pixel_stride) {
data.dest_row[pixel_pos + 1] = (data.dest_row[pixel_pos] ^ @truncate(u8, gray_alpha)) *| 255;
}
return .grayscale8Alpha;
},
.grayscale16 => {
var dest = std.mem.bytesAsSlice(u16, data.dest_row);
while (pixel_pos + 1 < dest.len) : (pixel_pos += pixel_stride) {
dest[pixel_pos + 1] = (data.dest_row[pixel_pos] ^ gray_alpha) *| 65535;
}
return .grayscale16Alpha;
},
else => unreachable,
}
},
.rgb => |tr_color| {
switch (data.src_format) {
.rgb24 => {
var dest = std.mem.bytesAsSlice(color.Rgba32, data.dest_row);
pixel_stride /= 4;
while (pixel_pos < dest.len) : (pixel_pos += pixel_stride) {
var val = dest[pixel_pos];
val.a = if (val.r == tr_color.r and val.g == tr_color.g and val.b == tr_color.b) 0 else 255;
dest[pixel_pos] = val;
}
return .rgba32;
},
.rgb48 => {
var dest = std.mem.bytesAsSlice(color.Rgba64, data.dest_row);
pixel_stride = 1;
while (pixel_pos < dest.len) : (pixel_pos += pixel_stride) {
var val = dest[pixel_pos];
val.a = if (val.r == tr_color.r and val.g == tr_color.g and val.b == tr_color.b) 0 else 65535;
dest[pixel_pos] = val;
}
return .rgba64;
},
else => unreachable,
}
},
else => unreachable,
}
return data.src_format;
}
};
pub const PlteProcessor = struct {
const Self = @This();
palette: []color.Rgba32 = undefined,
processed: bool = false,
pub fn processor(self: *Self) ReaderProcessor {
return ReaderProcessor.init(
"PLTE",
self,
processChunk,
processPalette,
processDataRow,
);
}
pub fn processChunk(self: *Self, data: *ChunkProcessData) ImageParsingError!PixelFormat {
// This is critical chunk so it is already read and there is no need to read it here
var result_format = data.current_format;
if (self.processed or !result_format.isIndex()) {
self.processed = true;
return result_format;
}
return .rgba32;
}
pub fn processPalette(self: *Self, data: *PaletteProcessData) ImageParsingError!void {
self.processed = true;
self.palette = data.palette;
}
pub fn processDataRow(self: *Self, data: *RowProcessData) ImageParsingError!PixelFormat {
self.processed = true;
if (!data.src_format.isIndex() or self.palette.len == 0) return data.src_format;
var pixel_stride: u8 = switch (data.dest_format) {
.rgba32, .bgra32 => 4,
.rgba64 => 8,
else => return data.src_format,
};
var pixel_pos: u32 = 0;
switch (data.src_format) {
.index1, .index2, .index4, .index8 => {
while (pixel_pos + 3 < data.dest_row.len) : (pixel_pos += pixel_stride) {
const index = data.dest_row[pixel_pos];
const entry = self.palette[index];
data.dest_row[pixel_pos] = entry.r;
data.dest_row[pixel_pos + 1] = entry.g;
data.dest_row[pixel_pos + 2] = entry.b;
data.dest_row[pixel_pos + 3] = entry.a;
}
},
.index16 => {
while (pixel_pos + 3 < data.dest_row.len) : (pixel_pos += pixel_stride) {
//const index_buf: [2]u8 = .{data.dest_row[pixel_pos], data.dest_row[pixel_pos + 1]};
const index = std.mem.bytesToValue(u16, &[2]u8{ data.dest_row[pixel_pos], data.dest_row[pixel_pos + 1] });
const entry = self.palette[index];
data.dest_row[pixel_pos] = entry.r;
data.dest_row[pixel_pos + 1] = entry.g;
data.dest_row[pixel_pos + 2] = entry.b;
data.dest_row[pixel_pos + 3] = entry.a;
}
},
else => unreachable,
}
return .rgba32;
}
};
/// The options you need to pass to PNG reader. If you want default options
/// with buffer for temporary allocations on the stack and default set of
/// processors just use this:
/// var def_options = DefOptions{};
/// png_reader.load(main_allocator, def_options.get());
/// Note that application can define its own DefPngOptions in the root file
/// and all the code that uses DefOptions will actually use that.
pub const ReaderOptions = struct {
/// Allocator for temporary allocations. The consant required_temp_bytes defines
/// the maximum bytes that will be allocated from it. Some temp allocations depend
/// on image size so they will use the main allocator since we can't guarantee
/// they are bounded. They will be allocated after the destination image to
/// reduce memory fragmentation and freed internally.
temp_allocator: Allocator,
/// Default is no processors so they are not even compiled in if not used.
/// If you want a default set of processors create a DefProcessors object
/// call get() on it and pass that here.
/// Note that application can define its own DefPngProcessors and all the
/// code that uses DefProcessors will actually use that.
processors: []ReaderProcessor = &[_]ReaderProcessor{},
pub fn init(temp_allocator: Allocator) ReaderOptions {
return .{ .temp_allocator = temp_allocator };
}
pub fn initWithProcessors(temp_allocator: Allocator, processors: []ReaderProcessor) ReaderOptions {
return .{ .temp_allocator = temp_allocator, .processors = processors };
}
};
// decompressor.zig:294 claims to use up to 300KiB from provided allocator but when
// testing with huge png file it used 760KiB.
// Original zlib claims it only needs 44KiB so next task is to rewrite zig's zlib :).
pub const required_temp_bytes = 800 * 1024;
const root = @import("root");
/// Applications can override this by defining DefPngProcessors struct in their root source file.
pub const DefProcessors = if (@hasDecl(root, "DefPngProcessors"))
root.DefPngProcessors
else
struct {
trns_processor: TrnsProcessor = .{},
plte_processor: PlteProcessor = .{},
processors_buffer: [2]ReaderProcessor = undefined,
const Self = @This();
pub fn get(self: *Self) []ReaderProcessor {
self.processors_buffer[0] = self.trns_processor.processor();
self.processors_buffer[1] = self.plte_processor.processor();
return self.processors_buffer[0..];
}
};
/// Applications can override this by defining DefPngOptions struct in their root source file.
pub const DefOptions = if (@hasDecl(root, "DefPngOptions"))
root.DefPngOptions
else
struct {
def_processors: DefProcessors = .{},
tmp_buffer: [required_temp_bytes]u8 = undefined,
fb_allocator: std.heap.FixedBufferAllocator = undefined,
const Self = @This();
pub fn get(self: *Self) ReaderOptions {
self.fb_allocator = std.heap.FixedBufferAllocator.init(self.tmp_buffer[0..]);
return .{ .temp_allocator = self.fb_allocator.allocator(), .processors = self.def_processors.get() };
}
};
// ********************* TESTS *********************
const expectError = std.testing.expectError;
const valid_header_buf = png.magic_header ++ "\x00\x00\x00\x0d" ++ png.HeaderData.chunk_type ++
"\x00\x00\x00\xff\x00\x00\x00\x75\x08\x06\x00\x00\x01\xf6\x24\x07\xe2";
test "testDefilter" {
var buffer = [_]u8{ 0, 1, 2, 3, 0, 5, 6, 7 };
// Start with none filter
var current_row: []u8 = buffer[4..];
var prev_row: []u8 = buffer[0..4];
var filter_stride: u8 = 1;
try testFilter(png.FilterType.none, current_row, prev_row, filter_stride, &[_]u8{ 0, 5, 6, 7 });
try testFilter(png.FilterType.sub, current_row, prev_row, filter_stride, &[_]u8{ 0, 5, 11, 18 });
try testFilter(png.FilterType.up, current_row, prev_row, filter_stride, &[_]u8{ 0, 6, 13, 21 });
try testFilter(png.FilterType.average, current_row, prev_row, filter_stride, &[_]u8{ 0, 6, 17, 31 });
try testFilter(png.FilterType.paeth, current_row, prev_row, filter_stride, &[_]u8{ 0, 7, 24, 55 });
var buffer16 = [_]u8{ 0, 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 8, 9, 10, 11, 12, 13, 14 };
current_row = buffer16[9..];
prev_row = buffer16[0..9];
filter_stride = 2;
try testFilter(png.FilterType.none, current_row, prev_row, filter_stride, &[_]u8{ 0, 0, 8, 9, 10, 11, 12, 13, 14 });
try testFilter(png.FilterType.sub, current_row, prev_row, filter_stride, &[_]u8{ 0, 0, 8, 9, 18, 20, 30, 33, 44 });
try testFilter(png.FilterType.up, current_row, prev_row, filter_stride, &[_]u8{ 0, 0, 9, 11, 21, 24, 35, 39, 51 });
try testFilter(png.FilterType.average, current_row, prev_row, filter_stride, &[_]u8{ 0, 0, 9, 12, 27, 32, 51, 58, 80 });
try testFilter(png.FilterType.paeth, current_row, prev_row, filter_stride, &[_]u8{ 0, 0, 10, 14, 37, 46, 88, 104, 168 });
}
fn testFilter(filter_type: png.FilterType, current_row: []u8, prev_row: []u8, filter_stride: u8, expected: []const u8) !void {
const expectEqualSlices = std.testing.expectEqualSlices;
current_row[filter_stride - 1] = @enumToInt(filter_type);
try BufferReader.defilter(current_row, prev_row, filter_stride);
try expectEqualSlices(u8, expected, current_row);
}
test "spreadRowData" {
var channel_count: u8 = 1;
var bit_depth: u8 = 1;
// 16 destination bytes, filter byte and two more bytes of current_row
var dest_buffer = [_]u8{0} ** 32;
var cur_buffer = [_]u8{ 0, 0, 0, 0, 0xa5, 0x7c, 0x39, 0xf2, 0x5b, 0x15, 0x78, 0xd1 };
var dest_row: []u8 = dest_buffer[0..16];
var current_row: []u8 = cur_buffer[3..6];
var filter_stride: u8 = 1;
var pixel_stride: u8 = 1;
const expectEqualSlices = std.testing.expectEqualSlices;
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, false);
try expectEqualSlices(u8, &[_]u8{ 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0 }, dest_row);
dest_row = dest_buffer[0..32];
pixel_stride = 2;
std.mem.set(u8, dest_row, 0);
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, false);
try expectEqualSlices(u8, &[_]u8{ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0 }, dest_row);
bit_depth = 2;
pixel_stride = 1;
dest_row = dest_buffer[0..8];
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, false);
try expectEqualSlices(u8, &[_]u8{ 2, 2, 1, 1, 1, 3, 3, 0 }, dest_row);
dest_row = dest_buffer[0..16];
pixel_stride = 2;
std.mem.set(u8, dest_row, 0);
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, false);
try expectEqualSlices(u8, &[_]u8{ 2, 0, 2, 0, 1, 0, 1, 0, 1, 0, 3, 0, 3, 0, 0, 0 }, dest_row);
bit_depth = 4;
pixel_stride = 1;
dest_row = dest_buffer[0..4];
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, false);
try expectEqualSlices(u8, &[_]u8{ 0xa, 0x5, 0x7, 0xc }, dest_row);
dest_row = dest_buffer[0..8];
pixel_stride = 2;
std.mem.set(u8, dest_row, 0);
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, false);
try expectEqualSlices(u8, &[_]u8{ 0xa, 0, 0x5, 0, 0x7, 0, 0xc, 0 }, dest_row);
bit_depth = 8;
pixel_stride = 1;
dest_row = dest_buffer[0..2];
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, false);
try expectEqualSlices(u8, &[_]u8{ 0xa5, 0x7c }, dest_row);
dest_row = dest_buffer[0..4];
pixel_stride = 2;
std.mem.set(u8, dest_row, 0);
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, false);
try expectEqualSlices(u8, &[_]u8{ 0xa5, 0, 0x7c, 0 }, dest_row);
channel_count = 2; // grayscale_alpha
bit_depth = 8;
current_row = cur_buffer[2..8];
dest_row = dest_buffer[0..4];
filter_stride = 2;
pixel_stride = 2;
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, false);
try expectEqualSlices(u8, &[_]u8{ 0xa5, 0x7c, 0x39, 0xf2 }, dest_row);
dest_row = dest_buffer[0..8];
std.mem.set(u8, dest_row, 0);
pixel_stride = 4;
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, false);
try expectEqualSlices(u8, &[_]u8{ 0xa5, 0x7c, 0, 0, 0x39, 0xf2, 0, 0 }, dest_row);
bit_depth = 16;
current_row = cur_buffer[0..12];
dest_row = dest_buffer[0..8];
filter_stride = 4;
pixel_stride = 4;
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, true);
try expectEqualSlices(u8, &[_]u8{ 0x7c, 0xa5, 0xf2, 0x39, 0x15, 0x5b, 0xd1, 0x78 }, dest_row);
channel_count = 3;
bit_depth = 8;
current_row = cur_buffer[1..10];
dest_row = dest_buffer[0..8];
std.mem.set(u8, dest_row, 0);
filter_stride = 3;
pixel_stride = 4;
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, false);
try expectEqualSlices(u8, &[_]u8{ 0xa5, 0x7c, 0x39, 0, 0xf2, 0x5b, 0x15, 0 }, dest_row);
channel_count = 4;
bit_depth = 16;
var cbuffer16 = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0xa5, 0x7c, 0x39, 0xf2, 0x5b, 0x15, 0x78, 0xd1 };
current_row = cbuffer16[0..];
dest_row = dest_buffer[0..8];
std.mem.set(u8, dest_row, 0);
filter_stride = 8;
pixel_stride = 8;
BufferReader.spreadRowData(dest_row, current_row[filter_stride..], bit_depth, channel_count, pixel_stride, true);
try expectEqualSlices(u8, &[_]u8{ 0x7c, 0xa5, 0xf2, 0x39, 0x15, 0x5b, 0xd1, 0x78 }, dest_row);
}
test "loadHeader_valid" {
const expectEqual = std.testing.expectEqual;
var reader = fromMemory(valid_header_buf[0..]);
var header = try reader.loadHeader();
try expectEqual(@as(u32, 0xff), header.width());
try expectEqual(@as(u32, 0x75), header.height());
try expectEqual(@as(u8, 8), header.bit_depth);
try expectEqual(png.ColorType.rgba_color, header.color_type);
try expectEqual(png.CompressionMethod.deflate, header.compression_method);
try expectEqual(png.FilterMethod.adaptive, header.filter_method);
try expectEqual(png.InterlaceMethod.adam7, header.interlace_method);
}
test "loadHeader_empty" {
const buf: [0]u8 = undefined;
var reader = fromMemory(buf[0..]);
try expectError(error.EndOfStream, reader.loadHeader());
}
test "loadHeader_badSig" {
const buf = "asdsdasdasdsads";
var reader = fromMemory(buf[0..]);
try expectError(error.InvalidData, reader.loadHeader());
}
test "loadHeader_badChunk" {
const buf = png.magic_header ++ "\x00\x00\x01\x0d" ++ png.HeaderData.chunk_type ++ "asad";
var reader = fromMemory(buf[0..]);
try expectError(error.InvalidData, reader.loadHeader());
}
test "loadHeader_shortHeader" {
const buf = png.magic_header ++ "\x00\x00\x00\x0d" ++ png.HeaderData.chunk_type ++ "asad";
var reader = fromMemory(buf[0..]);
try expectError(error.EndOfStream, reader.loadHeader());
}
test "loadHeader_invalidHeaderData" {
var buf: [valid_header_buf.len]u8 = undefined;
std.mem.copy(u8, buf[0..], valid_header_buf[0..]);
var pos = png.magic_header.len + @sizeOf(png.ChunkHeader);
try testHeaderWithInvalidValue(buf[0..], pos, 0xf0); // width highest bit is 1
pos += 3;
try testHeaderWithInvalidValue(buf[0..], pos, 0x00); // width is 0
pos += 1;
try testHeaderWithInvalidValue(buf[0..], pos, 0xf0); // height highest bit is 1
pos += 3;
try testHeaderWithInvalidValue(buf[0..], pos, 0x00); // height is 0
pos += 1;
try testHeaderWithInvalidValue(buf[0..], pos, 0x00); // invalid bit depth
try testHeaderWithInvalidValue(buf[0..], pos, 0x07); // invalid bit depth
try testHeaderWithInvalidValue(buf[0..], pos, 0x03); // invalid bit depth
try testHeaderWithInvalidValue(buf[0..], pos, 0x04); // invalid bit depth for rgba color type
try testHeaderWithInvalidValue(buf[0..], pos, 0x02); // invalid bit depth for rgba color type
try testHeaderWithInvalidValue(buf[0..], pos, 0x01); // invalid bit depth for rgba color type
pos += 1;
try testHeaderWithInvalidValue(buf[0..], pos, 0x01); // invalid color type
try testHeaderWithInvalidValue(buf[0..], pos, 0x05);
try testHeaderWithInvalidValue(buf[0..], pos, 0x07);
pos += 1;
try testHeaderWithInvalidValue(buf[0..], pos, 0x01); // invalid compression method
pos += 1;
try testHeaderWithInvalidValue(buf[0..], pos, 0x01); // invalid filter method
pos += 1;
try testHeaderWithInvalidValue(buf[0..], pos, 0x02); // invalid interlace method
}
fn testHeaderWithInvalidValue(buf: []u8, pos: usize, val: u8) !void {
var orig = buf[pos];
buf[pos] = val;
var reader = fromMemory(buf[0..]);
try expectError(error.InvalidData, reader.loadHeader());
buf[pos] = orig;
}
test "official test suite" {
try testWithDir("../ziggyimg-tests/fixtures/png/");
}
// Useful to quickly test performance on full dir of images
pub fn testWithDir(directory: []const u8) !void {
var testdir = std.fs.cwd().openDir(directory, .{ .access_sub_paths = false, .iterate = true, .no_follow = true }) catch null;
if (testdir) |*dir| {
defer dir.close();
var it = dir.iterate();
std.debug.print("\n", .{});
while (try it.next()) |entry| {
if (entry.kind != .File or !std.mem.eql(u8, std.fs.path.extension(entry.name), ".png")) continue;
std.debug.print("Testing file {s}\n", .{entry.name});
var tst_file = try dir.openFile(entry.name, .{ .mode = .read_only });
defer tst_file.close();
var reader = fromFile(tst_file);
if (entry.name[0] == 'x' and entry.name[2] != 't' and entry.name[2] != 's') {
try std.testing.expectError(error.InvalidData, reader.loadHeader());
continue;
}
var def_options = DefOptions{};
var header = try reader.loadHeader();
if (entry.name[0] == 'x') {
try std.testing.expectError(error.InvalidData, reader.loadWithHeader(&header, std.testing.allocator, def_options.get()));
continue;
}
var result = try reader.loadWithHeader(&header, std.testing.allocator, def_options.get());
defer result.deinit(std.testing.allocator);
var result_bytes = result.pixelsAsBytes();
var md5_val = [_]u8{0} ** 16;
std.crypto.hash.Md5.hash(result_bytes, &md5_val, .{});
var tst_data_name: [13]u8 = undefined;
std.mem.copy(u8, tst_data_name[0..9], entry.name[0..9]);
std.mem.copy(u8, tst_data_name[9..12], "tsd");
// Read test data and check with it
if (dir.openFile(tst_data_name[0..12], .{ .mode = .read_only })) |tdata| {
defer tdata.close();
var treader = tdata.reader();
var expected_md5 = [_]u8{0} ** 16;
var read_buffer = [_]u8{0} ** 50;
var str_format = try treader.readUntilDelimiter(read_buffer[0..], '\n');
var expected_pixel_format = std.meta.stringToEnum(PixelFormat, str_format).?;
var str_md5 = try treader.readUntilDelimiterOrEof(read_buffer[0..], '\n');
_ = try std.fmt.hexToBytes(expected_md5[0..], str_md5.?);
try std.testing.expectEqualSlices(u8, expected_md5[0..], md5_val[0..]);
try std.testing.expectEqual(expected_pixel_format, std.meta.activeTag(result));
} else |_| {
// If there is no test data assume test is correct and write it out
try writeTestData(dir, tst_data_name[0..12], &result, md5_val[0..]);
}
// Write Raw bytes
// std.mem.copy(u8, tst_data_name[9..13], "data");
// var rawoutput = try dir.createFile(tst_data_name[0..], .{});
// defer rawoutput.close();
// try rawoutput.writeAll(result_bytes);
}
}
}
fn writeTestData(dir: *std.fs.Dir, tst_data_name: []const u8, result: *PixelStorage, md5_val: []const u8) !void {
var toutput = try dir.createFile(tst_data_name, .{});
defer toutput.close();
var writer = toutput.writer();
try writer.print("{s}\n{s}", .{ @tagName(result.*), std.fmt.fmtSliceHexUpper(md5_val) });
} | src/formats/png/reader.zig |
const std = @import("std");
const zang = @import("zang");
const zangscript = @import("zangscript");
const common = @import("common.zig");
const c = @import("common/c.zig");
const modules = @import("modules.zig");
pub const AUDIO_FORMAT: zang.AudioFormat = .signed16_lsb;
pub const AUDIO_SAMPLE_RATE = 44100;
pub const AUDIO_BUFFER_SIZE = 1024;
pub const DESCRIPTION =
\\example_script_runtime_mono
\\
\\Play a scripted sound module with the keyboard.
\\
\\Press Enter to reload the script.
;
const a4 = 440.0;
const polyphony = 8;
const custom_builtin_package = zangscript.BuiltinPackage{
.zig_package_name = "_custom0",
.zig_import_path = "examples/modules.zig",
.builtins = &[_]zangscript.BuiltinModule{
zangscript.getBuiltinModule(modules.FilteredSawtoothInstrument),
},
.enums = &[_]zangscript.BuiltinEnum{},
};
const builtin_packages = [_]zangscript.BuiltinPackage{
zangscript.zang_builtin_package,
custom_builtin_package,
};
var error_buffer: [8000]u8 = undefined;
pub const MainModule = struct {
// FIXME (must be at least as many outputs/temps are used in the script)
// to fix this i would have to change the interface of all example MainModules to be something more dynamic
pub const num_outputs = 1;
pub const num_temps = 20;
pub const output_audio = common.AudioOut{ .mono = 0 };
pub const output_visualize = 0;
const filename = "examples/script.txt";
const module_name = "Instrument";
const Params = struct {
sample_rate: f32,
freq: zang.ConstantOrBuffer,
note_on: bool,
};
allocator: *std.mem.Allocator,
contents: []const u8,
script: *zangscript.CompiledScript,
key: ?i32,
module: *zangscript.ModuleBase,
idgen: zang.IdGenerator,
trigger: zang.Trigger(Params),
iq: zang.Notes(Params).ImpulseQueue,
pub fn init(out_script_error: *?[]const u8) !MainModule {
var allocator = std.heap.page_allocator;
const contents = std.fs.cwd().readFileAlloc(allocator, filename, 16 * 1024 * 1024) catch |err| {
out_script_error.* = "couldn't open file: " ++ filename;
return err;
};
errdefer allocator.free(contents);
var errors_stream: std.io.StreamSource = .{ .buffer = std.io.fixedBufferStream(&error_buffer) };
var script = zangscript.compile(allocator, .{
.builtin_packages = &builtin_packages,
.source = .{ .filename = filename, .contents = contents },
.errors_out = errors_stream.outStream(),
.errors_color = false,
}) catch |err| {
// StreamSource api flaw, see https://github.com/ziglang/zig/issues/5338
const fbs = switch (errors_stream) {
.buffer => |*f| f,
else => unreachable,
};
out_script_error.* = fbs.getWritten();
return err;
};
errdefer script.deinit();
var script_ptr = allocator.create(zangscript.CompiledScript) catch |err| {
out_script_error.* = "out of memory";
return err;
};
errdefer allocator.destroy(script_ptr);
script_ptr.* = script;
const module_index = for (script.exported_modules) |em| {
if (std.mem.eql(u8, em.name, module_name)) break em.module_index;
} else {
out_script_error.* = "module \"" ++ module_name ++ "\" not found";
return error.ModuleNotFound;
};
var module = try zangscript.initModule(script_ptr, module_index, &builtin_packages, allocator);
errdefer module.deinit();
return MainModule{
.allocator = allocator,
.contents = contents,
.script = script_ptr,
.key = null,
.module = module,
.idgen = zang.IdGenerator.init(),
.trigger = zang.Trigger(Params).init(),
.iq = zang.Notes(Params).ImpulseQueue.init(),
};
}
pub fn deinit(self: *MainModule) void {
self.module.deinit();
self.script.deinit();
self.allocator.destroy(self.script);
self.allocator.free(self.contents);
}
pub fn paint(self: *MainModule, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32) void {
var ctr = self.trigger.counter(span, self.iq.consume());
while (self.trigger.next(&ctr)) |result| {
const params = self.module.makeParams(Params, result.params) orelse return;
// script modules zero out their output before writing, so i need a temp to accumulate the outputs
zang.zero(result.span, temps[0]);
self.module.paint(
result.span,
temps[0..1],
temps[1 .. self.module.num_temps + 1],
result.note_id_changed,
¶ms,
);
zang.addInto(result.span, outputs[0], temps[0]);
}
}
pub fn keyEvent(self: *MainModule, key: i32, down: bool, impulse_frame: usize) bool {
if (common.getKeyRelFreq(key)) |rel_freq| {
if (down or (if (self.key) |nh| nh == key else false)) {
self.key = if (down) key else null;
self.iq.push(impulse_frame, self.idgen.nextId(), .{
.sample_rate = AUDIO_SAMPLE_RATE,
.freq = zang.constant(a4 * rel_freq),
.note_on = down,
});
}
}
return true;
}
}; | examples/example_script_runtime_mono.zig |
const std = @import("std");
const ray = @import("translate-c/raylib_all.zig");
const ArrayList = std.ArrayList;
const EnvItem = struct { rect: ray.Rectangle, blocking: bool, color: ray.Color };
const Player = struct {
const G = 400;
const hor_speed = 200.0;
const jump_speed = 350.0;
position: ray.Vector2,
speed: f32,
can_jump: bool,
pub fn updatePlayer(self: *@This(), envItems: []EnvItem, delta: f32) void {
if (ray.IsKeyDown(ray.KEY_LEFT)) {
self.position.x -= hor_speed * delta;
}
if (ray.IsKeyDown(ray.KEY_RIGHT)) {
self.position.x += hor_speed * delta;
}
if (ray.IsKeyDown(ray.KEY_SPACE) and self.can_jump) {
self.speed = -jump_speed;
self.can_jump = false;
}
var hitObstacle = false;
for (envItems) |item| {
if (item.blocking and item.rect.x <= self.position.x and
item.rect.x + item.rect.width >= self.position.x and
item.rect.y >= self.position.y and
item.rect.y < self.position.y + self.speed * delta)
{
hitObstacle = true;
self.speed = 0.0;
self.position.y = item.rect.y;
}
}
if (!hitObstacle) {
self.position.y += self.speed * delta;
self.speed += G * delta;
self.can_jump = false;
} else {
self.can_jump = true;
}
}
};
const CameraMode = enum {
center,
inside,
smooth,
bound,
};
pub fn updateCameraCenter(camera: *ray.Camera2D, player: Player, width: f32, height: f32) void {
camera.offset = ray.Vector2{ .x = width / 2.0, .y = height / 2.0 };
camera.target = player.position;
}
pub fn updateCameraCenterInsideMap(
camera: *ray.Camera2D,
player: Player,
envItems: []EnvItem,
width: f32,
height: f32,
) void {
camera.target = player.position;
camera.offset = ray.Vector2{ .x = width / 2.0, .y = height / 2.0 };
var minX: f32 = 1000;
var minY: f32 = 1000;
var maxX: f32 = -1000;
var maxY: f32 = -1000;
for (envItems) |ei| {
minX = std.math.min(ei.rect.x, minX);
maxX = std.math.max(ei.rect.x + ei.rect.width, maxX);
minY = std.math.min(ei.rect.y, minY);
maxY = std.math.max(ei.rect.y + ei.rect.height, maxY);
}
var max = ray.GetWorldToScreen2D(ray.Vector2{ .x = maxX, .y = maxY }, camera.*);
var min = ray.GetWorldToScreen2D(ray.Vector2{ .x = minX, .y = minY }, camera.*);
if (max.x < width) camera.offset.x = width - (max.x - width / 2);
if (max.y < height) camera.offset.y = height - (max.y - height / 2);
if (min.x > 0) camera.offset.x = width / 2 - min.x;
if (min.y > 0) camera.offset.y = height / 2 - min.y;
}
pub fn updateCameraCenterSmoothFollow(
camera: *ray.Camera2D,
player: Player,
delta: f32,
width: f32,
height: f32,
) void {
const minSpeed = 30;
const minEffectLength = 10;
const fractionSpeed = 0.8;
camera.offset = ray.Vector2{ .x = width / 2.0, .y = height / 2.0 };
const diff = ray.Vector2Subtract(player.position, camera.target);
const length = ray.Vector2Length(diff);
if (length > minEffectLength) {
const speed = std.math.max(fractionSpeed * length, minSpeed);
camera.target = ray.Vector2Add(camera.target, ray.Vector2Scale(diff, speed * delta / length));
}
}
pub fn updateCameraPlayerBoundsPush(camera: *ray.Camera2D, player: Player, width: f32, height: f32) void {
const bbox = ray.Vector2{ .x = 0.2, .y = 0.2 };
const bboxWorldMin = ray.GetScreenToWorld2D(ray.Vector2{
.x = (1 - bbox.x) * 0.5 * width,
.y = (1 - bbox.y) * 0.5 * height,
}, camera.*);
const bboxWorldMax = ray.GetScreenToWorld2D(ray.Vector2{
.x = (1 + bbox.x) * 0.5 * width,
.y = (1 + bbox.y) * 0.5 * height,
}, camera.*);
camera.offset = ray.Vector2{ .x = (1 - bbox.x) * 0.5 * width, .y = (1 - bbox.y) * 0.5 * height };
if (player.position.x < bboxWorldMin.x) camera.target.x = player.position.x;
if (player.position.y < bboxWorldMin.y) camera.target.y = player.position.y;
if (player.position.x > bboxWorldMax.x) camera.target.x = bboxWorldMin.x + (player.position.x - bboxWorldMax.x);
if (player.position.y > bboxWorldMax.y) camera.target.y = bboxWorldMin.y + (player.position.y - bboxWorldMax.y);
}
pub fn main() anyerror!void {
// Initialization
//--------------------------------------------------------------------------------------
const screenWidth = 800;
const screenHeight = 450;
ray.InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera platformer");
defer ray.CloseWindow();
var player = Player{ .position = ray.Vector2{ .x = 400, .y = 200 }, .speed = 0, .can_jump = false };
var envItems = ArrayList(EnvItem).init(std.testing.allocator);
try envItems.append(EnvItem{
.rect = ray.Rectangle{ .x = 0, .y = 0, .width = 1000, .height = 1000 },
.blocking = false,
.color = ray.LIGHTGRAY,
});
try envItems.append(EnvItem{
.rect = ray.Rectangle{ .x = 0, .y = 400, .width = 1000, .height = 200 },
.blocking = true,
.color = ray.GRAY,
});
try envItems.append(EnvItem{
.rect = ray.Rectangle{ .x = 300, .y = 200, .width = 400, .height = 10 },
.blocking = true,
.color = ray.GRAY,
});
try envItems.append(EnvItem{
.rect = ray.Rectangle{ .x = 650, .y = 300, .width = 100, .height = 10 },
.blocking = true,
.color = ray.GRAY,
});
var camera = ray.Camera2D{
.target = player.position,
.offset = ray.Vector2{ .x = screenWidth / 2.0, .y = screenHeight / 2.0 },
.rotation = 0,
.zoom = 1,
};
var cam_mode = CameraMode.center;
ray.SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!ray.WindowShouldClose()) {
// Update
//----------------------------------------------------------------------------------
const deltaTime = ray.GetFrameTime();
player.updatePlayer(envItems.items, deltaTime);
camera.zoom += ray.GetMouseWheelMove() * 0.05;
if (camera.zoom > 3.0) {
camera.zoom = 3.0;
} else if (camera.zoom < 0.25) camera.zoom = 0.25;
if (ray.IsKeyPressed(ray.KEY_R)) {
camera.zoom = 1.0;
player.position = ray.Vector2{ .x = 400, .y = 280 };
}
if (ray.IsKeyPressed(ray.KEY_C)) {
cam_mode = @intToEnum(CameraMode, @enumToInt(cam_mode) +% 1);
}
switch (cam_mode) {
.center => updateCameraCenter(&camera, player, screenWidth, screenHeight),
.inside => updateCameraCenterInsideMap(&camera, player, envItems.items, screenWidth, screenHeight),
.smooth => updateCameraCenterSmoothFollow(&camera, player, deltaTime, screenWidth, screenHeight),
.bound => updateCameraPlayerBoundsPush(&camera, player, screenWidth, screenHeight),
}
// Draw
//----------------------------------------------------------------------------------
ray.BeginDrawing();
ray.ClearBackground(ray.LIGHTGRAY);
ray.BeginMode2D(camera);
for (envItems.items) |item| {
ray.DrawRectangleRec(item.rect, item.color);
}
const playerRect = ray.Rectangle{
.x = player.position.x - 20,
.y = player.position.y - 40,
.width = 40,
.height = 40,
};
ray.DrawRectangleRec(playerRect, ray.RED);
ray.EndMode2D();
ray.DrawText("Controls:", 20, 20, 10, ray.BLACK);
ray.DrawText("- Right/Left to move", 40, 40, 10, ray.DARKGRAY);
ray.DrawText("- Space to jump", 40, 60, 10, ray.DARKGRAY);
ray.DrawText("- Mouse Wheel to Zoom in-out, R to reset zoom", 40, 80, 10, ray.DARKGRAY);
ray.DrawText("- C to change camera mode", 40, 100, 10, ray.DARKGRAY);
ray.DrawText("Current camera mode:", 20, 120, 10, ray.BLACK);
switch (cam_mode) {
.center => ray.DrawText("Camera Center", 40, 140, 10, ray.DARKGRAY),
.inside => ray.DrawText("Camera Center Inside Map", 40, 140, 10, ray.DARKGRAY),
.smooth => ray.DrawText("Camera Smooth Follow Player Center", 40, 140, 10, ray.DARKGRAY),
.bound => ray.DrawText("Player push camera on getting too close to screen edge", 40, 140, 10, ray.DARKGRAY),
}
ray.EndDrawing();
}
} | src/examples/2d_camera_flatformer.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day03.txt");
pub fn main() !void {
// create list
var list = std.ArrayList(u12).init(gpa);
defer list.deinit();
// parse data and append to list
{
var iter = tokenize(u8, data, "\n\r");
while(iter.next()) |line| {
const n = try parseInt(u12, line, 2);
try list.append(n);
}
}
{ // Part 1
// sum the bits of each position
// the number of 1 bits is the sum
// the number of 0 bits it the array length minus the sum
var sums = [_]u32{0} ** 12;
for (list.items) |n| {
var j: u4 = 0;
for (sums) |*sum| {
sum.* += (n >> j) & 1;
j += 1;
}
}
//print("{d}\n", .{sums});
var gamma: u12 = undefined;
for (sums) |sum, j| {
if (list.items.len/2 > sum) {
gamma |= @as(u12,1) << @truncate(u4, j);
} else {
gamma &= ~(@as(u12,1) << @truncate(u4, j));
}
}
const answer : u32 = @as(u32, gamma) * @as(u32, ~gamma);
print("{d}\n", .{answer});
}
{ // Part 2
const num1: u32 = filter1(list.items, 11)[0];
const num2: u32 = filter2(list.items, 11)[0];
print("{d}\n", .{num1*num2});
}
}
// recursively remove the elements from the slice based on the bit criteria
fn filter1 (numbers: []u12, bit: u4) []u12 {
var nums = numbers;
assert (nums.len > 0);
sort(u12, nums, {}, comptime asc(u12));
// count the number of zeros and the number of ones at the given bit
const count_ones = blk: {
var count: u32 = 0;
for (nums) |n| {
count += 1 & (n >> bit);
}
break :blk count;
};
const count_zeros = nums.len - count_ones;
// use the counts to determine which side of array to keep
if (count_ones >= count_zeros) {
nums = nums[count_zeros..nums.len];
} else {
nums = nums[0..(nums.len-count_ones)];
}
assert (nums.len > 0);
if (nums.len == 1) {
return nums;
} else {
return filter1(nums, bit-1);
}
}
fn filter2 (numbers: []u12, bit: u4) []u12 {
var nums = numbers;
assert (nums.len > 0);
sort(u12, nums, {}, comptime asc(u12));
// count the number of zeros and the number of ones at the given bit
const count_ones = blk: {
var count: u32 = 0;
for (nums) |n| {
count += 1 & (n >> bit);
}
break :blk count;
};
const count_zeros = nums.len - count_ones;
// use the counts to determine which side of array to keep
if (count_ones < count_zeros) {
nums = nums[count_zeros..nums.len];
} else {
nums = nums[0..(nums.len-count_ones)];
}
assert (nums.len > 0);
if (nums.len == 1) {
return nums;
} else {
return filter2(nums, bit-1);
}
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc; | src/day03.zig |
const std = @import("std");
const assert = std.debug.assert;
pub const FT_LOAD_DEFAULT = 0x0;
pub const FT_LOAD_NO_SCALE = ( 1 << 0 );
pub const FT_LOAD_NO_HINTING = ( 1 << 1 );
pub const FT_LOAD_RENDER = ( 1 << 2 );
pub const FT_LOAD_NO_BITMAP = ( 1 << 3 );
pub const FT_LOAD_VERTICAL_LAYOUT = ( 1 << 4 );
pub const FT_LOAD_FORCE_AUTOHINT = ( 1 << 5 );
pub const FT_LOAD_CROP_BITMAP = ( 1 << 6 );
pub const FT_LOAD_PEDANTIC = ( 1 << 7 );
pub const FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH =( 1 << 9 );
pub const FT_LOAD_NO_RECURSE = ( 1 << 10 );
pub const FT_LOAD_IGNORE_TRANSFORM = ( 1 << 11 );
pub const FT_LOAD_MONOCHROME = ( 1 << 12 );
pub const FT_LOAD_LINEAR_DESIGN = ( 1 << 13 );
pub const FT_LOAD_NO_AUTOHINT = ( 1 << 15 );
pub const FT_LOAD_COLOR = ( 1 << 20 );
pub const FT_LOAD_COMPUTE_METRICS = ( 1 << 21 );
pub const FT_LOAD_BITMAP_METRICS_ONLY = ( 1 << 22 );
pub const FT_LOAD_ADVANCE_ONLY = ( 1 << 8 );
pub const FT_LOAD_SBITS_ONLY = ( 1 << 14 );
pub fn fixed26_6(whole26: u26, frac6: u6) FT_F26Dot6 {
return @intCast(FT_F26Dot6, (whole26 << 6) | frac6);
}
pub fn f64_fixed26_6(v: f64) FT_F26Dot6 {
return @floatToInt(FT_F26Dot6, v * @intToFloat(f64, 0x40));
}
test "fixed26_6" {
assert(0x40 == fixed26_6(1, 0));
assert(fixed26_6(1, 0) == f64_fixed26_6(1.0));
assert(fixed26_6(1, 0x20) == f64_fixed26_6(1.5));
assert(fixed26_6(2, 0) == f64_fixed26_6(2));
}
pub fn fixed16_16(whole16: u16, frac16: u16) FT_Fixed {
return @intCast(FT_Fixed, (@intCast(u32, whole16) << 16) | @intCast(u32, frac16));
}
pub fn f64_fixed16_16(v: f64) FT_Fixed {
return @floatToInt(FT_Fixed, v * @intToFloat(f64, 0x10000));
}
test "fixed16_16" {
assert(0x10000 == fixed16_16(1, 0));
assert(fixed16_16(1, 0) == f64_fixed16_16(1.0));
assert(fixed16_16(1, 0x8000) == f64_fixed16_16(1.5));
assert(fixed16_16(2, 0) == f64_fixed16_16(2));
}
fn FT_LOAD_TARGET_(x: var) @typeOf(x) {
return (x & 0xF ) << 16;
}
pub const FT_LOAD_TARGET_NORMAL = FT_LOAD_TARGET_( @enumToInt(FT_RENDER_MODE_NORMAL) );
pub const FT_LOAD_TARGET_MONO = FT_LOAD_TARGET_( @enumToInt(FT_RENDER_MODE_MONO) );
pub const FT_LOAD_TARGET_LCD = FT_LOAD_TARGET_( @enumToInt(FT_RENDER_MODE_LCD) );
pub const FT_LOAD_TARGET_LCD_V = FT_LOAD_TARGET_( @enumToInt(FT_RENDER_MODE_LCD_V) );
pub fn FT_LOAD_TARGET_MODE(x: var) @typeOf(x) {
return (x >> 16) & 0xF;
}
test "FT_LOAD_TARGET_MODE" {
assert(FT_LOAD_TARGET_MODE(FT_LOAD_TARGET_NORMAL) == @enumToInt(FT_RENDER_MODE_NORMAL));
assert(FT_LOAD_TARGET_MODE(FT_LOAD_TARGET_MONO) == @enumToInt(FT_RENDER_MODE_MONO));
assert(FT_LOAD_TARGET_MODE(FT_LOAD_TARGET_LCD) == @enumToInt(FT_RENDER_MODE_LCD));
assert(FT_LOAD_TARGET_MODE(FT_LOAD_TARGET_LCD_V) == @enumToInt(FT_RENDER_MODE_LCD_V));
}
pub const FT_Int16 = c_short;
pub const FT_UInt16 = c_ushort;
pub const FT_Int32 = c_int;
pub const FT_UInt32 = c_uint;
pub const FT_Fast = c_int;
pub const FT_UFast = c_uint;
pub const FT_Int64 = c_long;
pub const FT_UInt64 = c_ulong;
pub const FT_Memory = struct_FT_MemoryRec_;
pub const FT_Alloc_Func = ?extern fn(?*FT_Memory, c_long) ?*c_void;
pub const FT_Free_Func = ?extern fn(?*FT_Memory, ?*c_void) void;
pub const FT_Realloc_Func = ?extern fn(?*FT_Memory, c_long, c_long, ?*c_void) ?*c_void;
pub const struct_FT_MemoryRec_ = extern struct {
user: ?*c_void,
alloc: FT_Alloc_Func,
free: FT_Free_Func,
realloc: FT_Realloc_Func,
};
pub const union_FT_StreamDesc_ = extern union {
value: c_long,
pointer: ?*c_void,
};
pub const FT_StreamDesc = union_FT_StreamDesc_;
pub const FT_Stream = struct_FT_StreamRec_;
pub const FT_Stream_IoFunc = ?extern fn(?*FT_Stream, c_ulong, ?[*]u8, c_ulong) c_ulong;
pub const FT_Stream_CloseFunc = ?extern fn(?*FT_Stream) void;
pub const struct_FT_StreamRec_ = extern struct {
base: ?[*]u8,
size: c_ulong,
pos: c_ulong,
descriptor: FT_StreamDesc,
pathname: FT_StreamDesc,
read: FT_Stream_IoFunc,
close: FT_Stream_CloseFunc,
memory: ?*FT_Memory,
cursor: ?[*]u8,
limit: ?[*]u8,
};
pub const FT_StreamRec = struct_FT_StreamRec_;
pub const FT_Pos = c_long;
pub const struct_FT_Vector_ = extern struct {
x: FT_Pos,
y: FT_Pos,
};
pub const FT_Vector = struct_FT_Vector_;
pub const struct_FT_BBox_ = extern struct {
xMin: FT_Pos,
yMin: FT_Pos,
xMax: FT_Pos,
yMax: FT_Pos,
};
pub const FT_BBox = struct_FT_BBox_;
pub const FT_PIXEL_MODE_NONE = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_NONE;
pub const FT_PIXEL_MODE_MONO = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_MONO;
pub const FT_PIXEL_MODE_GRAY = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_GRAY;
pub const FT_PIXEL_MODE_GRAY2 = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_GRAY2;
pub const FT_PIXEL_MODE_GRAY4 = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_GRAY4;
pub const FT_PIXEL_MODE_LCD = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_LCD;
pub const FT_PIXEL_MODE_LCD_V = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_LCD_V;
pub const FT_PIXEL_MODE_BGRA = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_BGRA;
pub const FT_PIXEL_MODE_MAX = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_MAX;
pub const enum_FT_Pixel_Mode_ = extern enum {
FT_PIXEL_MODE_NONE = 0,
FT_PIXEL_MODE_MONO = 1,
FT_PIXEL_MODE_GRAY = 2,
FT_PIXEL_MODE_GRAY2 = 3,
FT_PIXEL_MODE_GRAY4 = 4,
FT_PIXEL_MODE_LCD = 5,
FT_PIXEL_MODE_LCD_V = 6,
FT_PIXEL_MODE_BGRA = 7,
FT_PIXEL_MODE_MAX = 8,
};
pub const FT_Pixel_Mode = enum_FT_Pixel_Mode_;
pub const struct_FT_Bitmap_ = extern struct {
rows: c_uint,
width: c_uint,
pitch: c_int,
buffer: ?[*]u8,
num_grays: c_ushort,
pixel_mode: u8,
palette_mode: u8,
palette: ?*c_void,
};
pub const FT_Bitmap = struct_FT_Bitmap_;
pub const struct_FT_Outline_ = extern struct {
n_contours: c_short,
n_points: c_short,
points: ?[*]FT_Vector,
tags: ?[*]u8,
contours: ?[*]c_short,
flags: c_int,
};
pub const FT_Outline = struct_FT_Outline_;
pub const FT_Outline_MoveToFunc = ?extern fn(?[*]const FT_Vector, ?*c_void) c_int;
pub const FT_Outline_LineToFunc = ?extern fn(?[*]const FT_Vector, ?*c_void) c_int;
pub const FT_Outline_ConicToFunc = ?extern fn(?[*]const FT_Vector, ?[*]const FT_Vector, ?*c_void) c_int;
pub const FT_Outline_CubicToFunc = ?extern fn(?[*]const FT_Vector, ?[*]const FT_Vector, ?[*]const FT_Vector, ?*c_void) c_int;
pub const struct_FT_Outline_Funcs_ = extern struct {
move_to: FT_Outline_MoveToFunc,
line_to: FT_Outline_LineToFunc,
conic_to: FT_Outline_ConicToFunc,
cubic_to: FT_Outline_CubicToFunc,
shift: c_int,
delta: FT_Pos,
};
pub const FT_Outline_Funcs = struct_FT_Outline_Funcs_;
pub const FT_GLYPH_FORMAT_NONE = enum_FT_Glyph_Format_.FT_GLYPH_FORMAT_NONE;
pub const FT_GLYPH_FORMAT_COMPOSITE = enum_FT_Glyph_Format_.FT_GLYPH_FORMAT_COMPOSITE;
pub const FT_GLYPH_FORMAT_BITMAP = enum_FT_Glyph_Format_.FT_GLYPH_FORMAT_BITMAP;
pub const FT_GLYPH_FORMAT_OUTLINE = enum_FT_Glyph_Format_.FT_GLYPH_FORMAT_OUTLINE;
pub const FT_GLYPH_FORMAT_PLOTTER = enum_FT_Glyph_Format_.FT_GLYPH_FORMAT_PLOTTER;
pub const enum_FT_Glyph_Format_ = extern enum {
FT_GLYPH_FORMAT_NONE = 0,
FT_GLYPH_FORMAT_COMPOSITE = 1668246896,
FT_GLYPH_FORMAT_BITMAP = 1651078259,
FT_GLYPH_FORMAT_OUTLINE = 1869968492,
FT_GLYPH_FORMAT_PLOTTER = 1886154612,
};
pub const FT_Glyph_Format = enum_FT_Glyph_Format_;
pub const struct_FT_RasterRec_ = @OpaqueType();
pub const FT_Raster = ?*struct_FT_RasterRec_;
pub const struct_FT_Span_ = extern struct {
x: c_short,
len: c_ushort,
coverage: u8,
};
pub const FT_Span = struct_FT_Span_;
pub const FT_SpanFunc = ?extern fn(c_int, c_int, ?[*]const FT_Span, ?*c_void) void;
pub const FT_Raster_BitTest_Func = ?extern fn(c_int, c_int, ?*c_void) c_int;
pub const FT_Raster_BitSet_Func = ?extern fn(c_int, c_int, ?*c_void) void;
pub const struct_FT_Raster_Params_ = extern struct {
target: ?[*]const FT_Bitmap,
source: ?*const c_void,
flags: c_int,
gray_spans: FT_SpanFunc,
black_spans: FT_SpanFunc,
bit_test: FT_Raster_BitTest_Func,
bit_set: FT_Raster_BitSet_Func,
user: ?*c_void,
clip_box: FT_BBox,
};
pub const FT_Raster_Params = struct_FT_Raster_Params_;
pub const FT_Raster_NewFunc = ?extern fn(?*c_void, ?[*]FT_Raster) c_int;
pub const FT_Raster_DoneFunc = ?extern fn(FT_Raster) void;
pub const FT_Raster_ResetFunc = ?extern fn(FT_Raster, ?[*]u8, c_ulong) void;
pub const FT_Raster_SetModeFunc = ?extern fn(FT_Raster, c_ulong, ?*c_void) c_int;
pub const FT_Raster_RenderFunc = ?extern fn(FT_Raster, ?[*]const FT_Raster_Params) c_int;
pub const struct_FT_Raster_Funcs_ = extern struct {
glyph_format: FT_Glyph_Format,
raster_new: FT_Raster_NewFunc,
raster_reset: FT_Raster_ResetFunc,
raster_set_mode: FT_Raster_SetModeFunc,
raster_render: FT_Raster_RenderFunc,
raster_done: FT_Raster_DoneFunc,
};
pub const FT_Raster_Funcs = struct_FT_Raster_Funcs_;
pub const FT_Bool = u8;
pub const FT_FWord = c_short;
pub const FT_UFWord = c_ushort;
pub const FT_Char = i8;
pub const FT_Byte = u8;
pub const FT_Bytes = ?[*]const FT_Byte;
pub const FT_Tag = FT_UInt32;
pub const FT_String = u8;
pub const FT_Short = c_short;
pub const FT_UShort = c_ushort;
pub const FT_Int = c_int;
pub const FT_UInt = c_uint;
pub const FT_Long = c_long;
pub const FT_ULong = c_ulong;
pub const FT_F2Dot14 = c_short;
pub const FT_F26Dot6 = c_long;
pub const FT_Fixed = c_long;
pub const FT_Error = c_int;
pub const FT_Pointer = ?*c_void;
pub const FT_Offset = usize;
pub const FT_PtrDist = ptrdiff_t;
pub const struct_FT_UnitVector_ = extern struct {
x: FT_F2Dot14,
y: FT_F2Dot14,
};
pub const FT_UnitVector = struct_FT_UnitVector_;
pub const struct_FT_Matrix_ = extern struct {
xx: FT_Fixed,
xy: FT_Fixed,
yx: FT_Fixed,
yy: FT_Fixed,
};
pub const FT_Matrix = struct_FT_Matrix_;
pub const struct_FT_Data_ = extern struct {
pointer: ?[*]const FT_Byte,
length: FT_Int,
};
pub const FT_Data = struct_FT_Data_;
pub const FT_Generic_Finalizer = ?extern fn(?*c_void) void;
pub const struct_FT_Generic_ = extern struct {
data: ?*c_void,
finalizer: FT_Generic_Finalizer,
};
pub const FT_Generic = struct_FT_Generic_;
pub const FT_ListNode = ?*struct_FT_ListNodeRec_;
pub const struct_FT_ListNodeRec_ = extern struct {
prev: ?*struct_FT_ListNodeRec_,
next: ?*struct_FT_ListNodeRec_,
data: ?*c_void,
};
pub const struct_FT_ListRec_ = extern struct {
head: FT_ListNode,
tail: FT_ListNode,
};
pub const FT_List = ?*struct_FT_ListRec_;
pub const FT_ListNodeRec = struct_FT_ListNodeRec_;
pub const FT_ListRec = struct_FT_ListRec_;
pub const FT_Mod_Err_Base = 0;
pub const FT_Mod_Err_Autofit = 0;
pub const FT_Mod_Err_BDF = 0;
pub const FT_Mod_Err_Bzip2 = 0;
pub const FT_Mod_Err_Cache = 0;
pub const FT_Mod_Err_CFF = 0;
pub const FT_Mod_Err_CID = 0;
pub const FT_Mod_Err_Gzip = 0;
pub const FT_Mod_Err_LZW = 0;
pub const FT_Mod_Err_OTvalid = 0;
pub const FT_Mod_Err_PCF = 0;
pub const FT_Mod_Err_PFR = 0;
pub const FT_Mod_Err_PSaux = 0;
pub const FT_Mod_Err_PShinter = 0;
pub const FT_Mod_Err_PSnames = 0;
pub const FT_Mod_Err_Raster = 0;
pub const FT_Mod_Err_SFNT = 0;
pub const FT_Mod_Err_Smooth = 0;
pub const FT_Mod_Err_TrueType = 0;
pub const FT_Mod_Err_Type1 = 0;
pub const FT_Mod_Err_Type42 = 0;
pub const FT_Mod_Err_Winfonts = 0;
pub const FT_Mod_Err_GXvalid = 0;
pub const FT_Mod_Err_Max = 1;
pub const FT_Err_Ok = 0;
pub const FT_Err_Cannot_Open_Resource = 1;
pub const FT_Err_Unknown_File_Format = 2;
pub const FT_Err_Invalid_File_Format = 3;
pub const FT_Err_Invalid_Version = 4;
pub const FT_Err_Lower_Module_Version = 5;
pub const FT_Err_Invalid_Argument = 6;
pub const FT_Err_Unimplemented_Feature = 7;
pub const FT_Err_Invalid_Table = 8;
pub const FT_Err_Invalid_Offset = 9;
pub const FT_Err_Array_Too_Large = 10;
pub const FT_Err_Missing_Module = 11;
pub const FT_Err_Missing_Property = 12;
pub const FT_Err_Invalid_Glyph_Index = 16;
pub const FT_Err_Invalid_Character_Code = 17;
pub const FT_Err_Invalid_Glyph_Format = 18;
pub const FT_Err_Cannot_Render_Glyph = 19;
pub const FT_Err_Invalid_Outline = 20;
pub const FT_Err_Invalid_Composite = 21;
pub const FT_Err_Too_Many_Hints = 22;
pub const FT_Err_Invalid_Pixel_Size = 23;
pub const FT_Err_Invalid_Handle = 32;
pub const FT_Err_Invalid_Library_Handle = 33;
pub const FT_Err_Invalid_Driver_Handle = 34;
pub const FT_Err_Invalid_Face_Handle = 35;
pub const FT_Err_Invalid_Size_Handle = 36;
pub const FT_Err_Invalid_Slot_Handle = 37;
pub const FT_Err_Invalid_CharMap_Handle = 38;
pub const FT_Err_Invalid_Cache_Handle = 39;
pub const FT_Err_Invalid_Stream_Handle = 40;
pub const FT_Err_Too_Many_Drivers = 48;
pub const FT_Err_Too_Many_Extensions = 49;
pub const FT_Err_Out_Of_Memory = 64;
pub const FT_Err_Unlisted_Object = 65;
pub const FT_Err_Cannot_Open_Stream = 81;
pub const FT_Err_Invalid_Stream_Seek = 82;
pub const FT_Err_Invalid_Stream_Skip = 83;
pub const FT_Err_Invalid_Stream_Read = 84;
pub const FT_Err_Invalid_Stream_Operation = 85;
pub const FT_Err_Invalid_Frame_Operation = 86;
pub const FT_Err_Nested_Frame_Access = 87;
pub const FT_Err_Invalid_Frame_Read = 88;
pub const FT_Err_Raster_Uninitialized = 96;
pub const FT_Err_Raster_Corrupted = 97;
pub const FT_Err_Raster_Overflow = 98;
pub const FT_Err_Raster_Negative_Height = 99;
pub const FT_Err_Too_Many_Caches = 112;
pub const FT_Err_Invalid_Opcode = 128;
pub const FT_Err_Too_Few_Arguments = 129;
pub const FT_Err_Stack_Overflow = 130;
pub const FT_Err_Code_Overflow = 131;
pub const FT_Err_Bad_Argument = 132;
pub const FT_Err_Divide_By_Zero = 133;
pub const FT_Err_Invalid_Reference = 134;
pub const FT_Err_Debug_OpCode = 135;
pub const FT_Err_ENDF_In_Exec_Stream = 136;
pub const FT_Err_Nested_DEFS = 137;
pub const FT_Err_Invalid_CodeRange = 138;
pub const FT_Err_Execution_Too_Long = 139;
pub const FT_Err_Too_Many_Function_Defs = 140;
pub const FT_Err_Too_Many_Instruction_Defs = 141;
pub const FT_Err_Table_Missing = 142;
pub const FT_Err_Horiz_Header_Missing = 143;
pub const FT_Err_Locations_Missing = 144;
pub const FT_Err_Name_Table_Missing = 145;
pub const FT_Err_CMap_Table_Missing = 146;
pub const FT_Err_Hmtx_Table_Missing = 147;
pub const FT_Err_Post_Table_Missing = 148;
pub const FT_Err_Invalid_Horiz_Metrics = 149;
pub const FT_Err_Invalid_CharMap_Format = 150;
pub const FT_Err_Invalid_PPem = 151;
pub const FT_Err_Invalid_Vert_Metrics = 152;
pub const FT_Err_Could_Not_Find_Context = 153;
pub const FT_Err_Invalid_Post_Table_Format = 154;
pub const FT_Err_Invalid_Post_Table = 155;
pub const FT_Err_DEF_In_Glyf_Bytecode = 156;
pub const FT_Err_Missing_Bitmap = 157;
pub const FT_Err_Syntax_Error = 160;
pub const FT_Err_Stack_Underflow = 161;
pub const FT_Err_Ignore = 162;
pub const FT_Err_No_Unicode_Glyph_Name = 163;
pub const FT_Err_Glyph_Too_Big = 164;
pub const FT_Err_Missing_Startfont_Field = 176;
pub const FT_Err_Missing_Font_Field = 177;
pub const FT_Err_Missing_Size_Field = 178;
pub const FT_Err_Missing_Fontboundingbox_Field = 179;
pub const FT_Err_Missing_Chars_Field = 180;
pub const FT_Err_Missing_Startchar_Field = 181;
pub const FT_Err_Missing_Encoding_Field = 182;
pub const FT_Err_Missing_Bbx_Field = 183;
pub const FT_Err_Bbx_Too_Big = 184;
pub const FT_Err_Corrupted_Font_Header = 185;
pub const FT_Err_Corrupted_Font_Glyphs = 186;
pub const FT_Err_Max = 187;
pub const struct_FT_Glyph_Metrics_ = extern struct {
width: FT_Pos,
height: FT_Pos,
horiBearingX: FT_Pos,
horiBearingY: FT_Pos,
horiAdvance: FT_Pos,
vertBearingX: FT_Pos,
vertBearingY: FT_Pos,
vertAdvance: FT_Pos,
};
pub const FT_Glyph_Metrics = struct_FT_Glyph_Metrics_;
pub const struct_FT_Bitmap_Size_ = extern struct {
height: FT_Short,
width: FT_Short,
size: FT_Pos,
x_ppem: FT_Pos,
y_ppem: FT_Pos,
};
pub const FT_Bitmap_Size = struct_FT_Bitmap_Size_;
pub const struct_FT_LibraryRec_ = @OpaqueType();
pub const FT_Library = ?*struct_FT_LibraryRec_;
pub const struct_FT_ModuleRec_ = @OpaqueType();
pub const FT_Module = ?*struct_FT_ModuleRec_;
pub const struct_FT_DriverRec_ = @OpaqueType();
pub const FT_Driver = ?*struct_FT_DriverRec_;
pub const struct_FT_RendererRec_ = @OpaqueType();
pub const FT_Renderer = ?*struct_FT_RendererRec_;
pub const FT_Face = struct_FT_FaceRec_;
pub const FT_Encoding = c_int;
//pub const FT_Encoding = extern enum {
// FT_ENCODING_NONE = 0,
// FT_ENCODING_MS_SYMBOL = 1937337698,
// FT_ENCODING_UNICODE = 1970170211,
// FT_ENCODING_SJIS = 1936353651,
// FT_ENCODING_PRC = 1734484000,
// FT_ENCODING_BIG5 = 1651074869,
// FT_ENCODING_WANSUNG = 2002873971,
// FT_ENCODING_JOHAB = 1785686113,
// FT_ENCODING_GB2312 = 1734484000,
// FT_ENCODING_MS_SJIS = 1936353651,
// FT_ENCODING_MS_GB2312 = 1734484000,
// FT_ENCODING_MS_BIG5 = 1651074869,
// FT_ENCODING_MS_WANSUNG = 2002873971,
// FT_ENCODING_MS_JOHAB = 1785686113,
// FT_ENCODING_ADOBE_STANDARD = 1094995778,
// FT_ENCODING_ADOBE_EXPERT = 1094992453,
// FT_ENCODING_ADOBE_CUSTOM = 1094992451,
// FT_ENCODING_ADOBE_LATIN_1 = 1818326065,
// FT_ENCODING_OLD_LATIN_2 = 1818326066,
// FT_ENCODING_APPLE_ROMAN = 1634889070,
//};
pub const FT_ENCODING_NONE: isize = 0;
pub const FT_ENCODING_MS_SYMBOL: isize = 1937337698;
pub const FT_ENCODING_UNICODE: isize = 1970170211;
pub const FT_ENCODING_SJIS: isize = 1936353651;
pub const FT_ENCODING_PRC: isize = 1734484000;
pub const FT_ENCODING_BIG5: isize = 1651074869;
pub const FT_ENCODING_WANSUNG: isize = 2002873971;
pub const FT_ENCODING_JOHAB: isize = 1785686113;
pub const FT_ENCODING_GB2312: isize = 1734484000;
pub const FT_ENCODING_MS_SJIS: isize = 1936353651;
pub const FT_ENCODING_MS_GB2312: isize = 1734484000;
pub const FT_ENCODING_MS_BIG5: isize = 1651074869;
pub const FT_ENCODING_MS_WANSUNG: isize = 2002873971;
pub const FT_ENCODING_MS_JOHAB: isize = 1785686113;
pub const FT_ENCODING_ADOBE_STANDARD: isize = 1094995778;
pub const FT_ENCODING_ADOBE_EXPERT: isize = 1094992453;
pub const FT_ENCODING_ADOBE_CUSTOM: isize = 1094992451;
pub const FT_ENCODING_ADOBE_LATIN_1: isize = 1818326065;
pub const FT_ENCODING_OLD_LATIN_2: isize = 1818326066;
pub const FT_ENCODING_APPLE_ROMAN: isize = 1634889070;
pub const struct_FT_CharMapRec_ = extern struct {
face: ?*FT_Face,
encoding: FT_Encoding,
platform_id: FT_UShort,
encoding_id: FT_UShort,
};
pub const FT_CharMap = struct_FT_CharMapRec_;
pub const struct_FT_SubGlyphRec_ = @OpaqueType();
pub const FT_SubGlyph = ?*struct_FT_SubGlyphRec_;
pub const struct_FT_Slot_InternalRec_ = @OpaqueType();
pub const FT_Slot_Internal = ?*struct_FT_Slot_InternalRec_;
pub const struct_FT_GlyphSlotRec_ = extern struct {
library: ?*FT_Library,
face: ?*FT_Face,
next: ?*FT_GlyphSlot,
reserved: FT_UInt,
generic: FT_Generic,
metrics: FT_Glyph_Metrics,
linearHoriAdvance: FT_Fixed,
linearVertAdvance: FT_Fixed,
advance: FT_Vector,
format: FT_Glyph_Format,
bitmap: FT_Bitmap,
bitmap_left: FT_Int,
bitmap_top: FT_Int,
outline: FT_Outline,
num_subglyphs: FT_UInt,
subglyphs: FT_SubGlyph,
control_data: ?*c_void,
control_len: c_long,
lsb_delta: FT_Pos,
rsb_delta: FT_Pos,
other: ?*c_void,
internal: FT_Slot_Internal,
};
pub const FT_GlyphSlot = struct_FT_GlyphSlotRec_;
pub const struct_FT_Size_Metrics_ = extern struct {
x_ppem: FT_UShort,
y_ppem: FT_UShort,
x_scale: FT_Fixed,
y_scale: FT_Fixed,
ascender: FT_Pos,
descender: FT_Pos,
height: FT_Pos,
max_advance: FT_Pos,
};
pub const FT_Size_Metrics = struct_FT_Size_Metrics_;
pub const struct_FT_Size_InternalRec_ = @OpaqueType();
pub const FT_Size_Internal = ?*struct_FT_Size_InternalRec_;
pub const struct_FT_SizeRec_ = extern struct {
face: ?*FT_Face,
generic: FT_Generic,
metrics: FT_Size_Metrics,
internal: FT_Size_Internal,
};
pub const FT_Size = ?*struct_FT_SizeRec_;
pub const struct_FT_Face_InternalRec_ = @OpaqueType();
pub const FT_Face_Internal = ?*struct_FT_Face_InternalRec_;
pub const struct_FT_FaceRec_ = extern struct {
num_faces: FT_Long,
face_index: FT_Long,
face_flags: FT_Long,
style_flags: FT_Long,
num_glyphs: FT_Long,
family_name: ?[*]FT_String,
style_name: ?[*]FT_String,
num_fixed_sizes: FT_Int,
available_sizes: ?[*]FT_Bitmap_Size,
num_charmaps: FT_Int,
charmaps: ?[*]?*FT_CharMap, // OK
//charmaps: ?*?*FT_CharMap, // OK
//charmaps: ?[]?*FT_CharMap, // error: extern structs cannot contain field of type ?[]?*structFT_CharMapRec_
generic: FT_Generic,
bbox: FT_BBox,
units_per_EM: FT_UShort,
ascender: FT_Short,
descender: FT_Short,
height: FT_Short,
max_advance_width: FT_Short,
max_advance_height: FT_Short,
underline_position: FT_Short,
underline_thickness: FT_Short,
glyph: ?*FT_GlyphSlot,
size: FT_Size,
charmap: ?*FT_CharMap,
driver: FT_Driver,
memory: *?FT_Memory,
stream: *?FT_Stream,
sizes_list: FT_ListRec,
autohint: FT_Generic,
extensions: ?*c_void,
internal: FT_Face_Internal,
};
pub const FT_CharMapRec = struct_FT_CharMapRec_;
pub const FT_FaceRec = struct_FT_FaceRec_;
pub const FT_SizeRec = struct_FT_SizeRec_;
pub const FT_GlyphSlotRec = struct_FT_GlyphSlotRec_;
//pub extern fn FT_Init_FreeType(alibrary: ?[*]FT_Library) FT_Error;
pub extern fn FT_Init_FreeType(alibrary: *?*FT_Library) FT_Error;
pub extern fn FT_Done_FreeType(library: ?*FT_Library) FT_Error;
pub const struct_FT_Parameter_ = extern struct {
tag: FT_ULong,
data: FT_Pointer,
};
pub const FT_Parameter = struct_FT_Parameter_;
pub const struct_FT_Open_Args_ = extern struct {
flags: FT_UInt,
memory_base: ?[*]const FT_Byte,
memory_size: FT_Long,
pathname: ?[*]FT_String,
stream: *?FT_Stream,
driver: FT_Module,
num_params: FT_Int,
params: ?[*]FT_Parameter,
};
pub const FT_Open_Args = struct_FT_Open_Args_;
pub extern fn FT_New_Face(library: ?*FT_Library, filepathname: ?[*]const u8, face_index: FT_Long, aface: ?*?*FT_Face) FT_Error;
pub extern fn FT_New_Memory_Face(library: ?*FT_Library, file_base: ?[*]const FT_Byte, file_size: FT_Long, face_index: FT_Long, aface: ?*?*FT_Face) FT_Error;
pub extern fn FT_Open_Face(library: ?*FT_Library, args: ?[*]const FT_Open_Args, face_index: FT_Long, aface: ?*?*FT_Face) FT_Error;
pub extern fn FT_Attach_File(face: ?*FT_Face, filepathname: ?[*]const u8) FT_Error;
pub extern fn FT_Attach_Stream(face: ?*FT_Face, parameters: ?[*]FT_Open_Args) FT_Error;
pub extern fn FT_Reference_Face(face: ?*FT_Face) FT_Error;
pub extern fn FT_Done_Face(face: ?*FT_Face) FT_Error;
pub extern fn FT_Select_Size(face: ?*FT_Face, strike_index: FT_Int) FT_Error;
pub const FT_SIZE_REQUEST_TYPE_NOMINAL = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_NOMINAL;
pub const FT_SIZE_REQUEST_TYPE_REAL_DIM = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_REAL_DIM;
pub const FT_SIZE_REQUEST_TYPE_BBOX = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_BBOX;
pub const FT_SIZE_REQUEST_TYPE_CELL = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_CELL;
pub const FT_SIZE_REQUEST_TYPE_SCALES = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_SCALES;
pub const FT_SIZE_REQUEST_TYPE_MAX = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_MAX;
pub const enum_FT_Size_Request_Type_ = extern enum {
FT_SIZE_REQUEST_TYPE_NOMINAL,
FT_SIZE_REQUEST_TYPE_REAL_DIM,
FT_SIZE_REQUEST_TYPE_BBOX,
FT_SIZE_REQUEST_TYPE_CELL,
FT_SIZE_REQUEST_TYPE_SCALES,
FT_SIZE_REQUEST_TYPE_MAX,
};
pub const FT_Size_Request_Type = enum_FT_Size_Request_Type_;
pub const struct_FT_Size_RequestRec_ = extern struct {
type: FT_Size_Request_Type,
width: FT_Long,
height: FT_Long,
horiResolution: FT_UInt,
vertResolution: FT_UInt,
};
pub const FT_Size_RequestRec = struct_FT_Size_RequestRec_;
pub const FT_Size_Request = ?*struct_FT_Size_RequestRec_;
pub extern fn FT_Request_Size(face: ?*FT_Face, req: FT_Size_Request) FT_Error;
pub extern fn FT_Set_Char_Size(face: ?*FT_Face, char_width: FT_F26Dot6, char_height: FT_F26Dot6, horz_resolution: FT_UInt, vert_resolution: FT_UInt) FT_Error;
pub extern fn FT_Set_Pixel_Sizes(face: ?*FT_Face, pixel_width: FT_UInt, pixel_height: FT_UInt) FT_Error;
pub extern fn FT_Load_Glyph(face: ?*FT_Face, glyph_index: FT_UInt, load_flags: FT_Int32) FT_Error;
pub extern fn FT_Load_Char(face: ?*FT_Face, char_code: FT_ULong, load_flags: FT_Int32) FT_Error;
pub extern fn FT_Set_Transform(face: ?*FT_Face, matrix: ?*FT_Matrix, delta: ?*FT_Vector) void;
pub const FT_RENDER_MODE_NORMAL = enum_FT_Render_Mode_.FT_RENDER_MODE_NORMAL;
pub const FT_RENDER_MODE_LIGHT = enum_FT_Render_Mode_.FT_RENDER_MODE_LIGHT;
pub const FT_RENDER_MODE_MONO = enum_FT_Render_Mode_.FT_RENDER_MODE_MONO;
pub const FT_RENDER_MODE_LCD = enum_FT_Render_Mode_.FT_RENDER_MODE_LCD;
pub const FT_RENDER_MODE_LCD_V = enum_FT_Render_Mode_.FT_RENDER_MODE_LCD_V;
pub const FT_RENDER_MODE_MAX = enum_FT_Render_Mode_.FT_RENDER_MODE_MAX;
pub const enum_FT_Render_Mode_ = extern enum {
FT_RENDER_MODE_NORMAL = 0,
FT_RENDER_MODE_LIGHT = 1,
FT_RENDER_MODE_MONO = 2,
FT_RENDER_MODE_LCD = 3,
FT_RENDER_MODE_LCD_V = 4,
FT_RENDER_MODE_MAX = 5,
};
pub const FT_Render_Mode = enum_FT_Render_Mode_;
pub extern fn FT_Render_Glyph(slot: ?*FT_GlyphSlot, render_mode: FT_Render_Mode) FT_Error;
pub const FT_KERNING_DEFAULT = enum_FT_Kerning_Mode_.FT_KERNING_DEFAULT;
pub const FT_KERNING_UNFITTED = enum_FT_Kerning_Mode_.FT_KERNING_UNFITTED;
pub const FT_KERNING_UNSCALED = enum_FT_Kerning_Mode_.FT_KERNING_UNSCALED;
pub const enum_FT_Kerning_Mode_ = extern enum {
FT_KERNING_DEFAULT = 0,
FT_KERNING_UNFITTED = 1,
FT_KERNING_UNSCALED = 2,
};
pub const FT_Kerning_Mode = enum_FT_Kerning_Mode_;
pub extern fn FT_Get_Kerning(face: ?*FT_Face, left_glyph: FT_UInt, right_glyph: FT_UInt, kern_mode: FT_UInt, akerning: ?[*]FT_Vector) FT_Error;
pub extern fn FT_Get_Track_Kerning(face: ?*FT_Face, point_size: FT_Fixed, degree: FT_Int, akerning: ?[*]FT_Fixed) FT_Error;
pub extern fn FT_Get_Glyph_Name(face: ?*FT_Face, glyph_index: FT_UInt, buffer: FT_Pointer, buffer_max: FT_UInt) FT_Error;
pub extern fn FT_Get_Postscript_Name(face: ?*FT_Face) ?[*]const u8;
pub extern fn FT_Select_Charmap(face: ?*FT_Face, encoding: FT_Encoding) FT_Error;
pub extern fn FT_Set_Charmap(face: ?*FT_Face, charmap: ?*FT_CharMap) FT_Error;
pub extern fn FT_Get_Charmap_Index(charmap: ?*FT_CharMap) FT_Int;
pub extern fn FT_Get_Char_Index(face: ?*FT_Face, charcode: FT_ULong) FT_UInt;
pub extern fn FT_Get_First_Char(face: ?*FT_Face, agindex: ?[*]FT_UInt) FT_ULong;
pub extern fn FT_Get_Next_Char(face: ?*FT_Face, char_code: FT_ULong, agindex: ?[*]FT_UInt) FT_ULong;
pub extern fn FT_Face_Properties(face: ?*FT_Face, num_properties: FT_UInt, properties: ?[*]FT_Parameter) FT_Error;
pub extern fn FT_Get_Name_Index(face: ?*FT_Face, glyph_name: ?[*]FT_String) FT_UInt;
pub extern fn FT_Get_SubGlyph_Info(glyph: ?*FT_GlyphSlot, sub_index: FT_UInt, p_index: ?[*]FT_Int, p_flags: ?[*]FT_UInt, p_arg1: ?[*]FT_Int, p_arg2: ?[*]FT_Int, p_transform: ?[*]FT_Matrix) FT_Error;
pub extern fn FT_Get_FSType_Flags(face: ?*FT_Face) FT_UShort;
pub extern fn FT_Face_GetCharVariantIndex(face: ?*FT_Face, charcode: FT_ULong, variantSelector: FT_ULong) FT_UInt;
pub extern fn FT_Face_GetCharVariantIsDefault(face: ?*FT_Face, charcode: FT_ULong, variantSelector: FT_ULong) FT_Int;
pub extern fn FT_Face_GetVariantSelectors(face: ?*FT_Face) ?[*]FT_UInt32;
pub extern fn FT_Face_GetVariantsOfChar(face: ?*FT_Face, charcode: FT_ULong) ?[*]FT_UInt32;
pub extern fn FT_Face_GetCharsOfVariant(face: ?*FT_Face, variantSelector: FT_ULong) ?[*]FT_UInt32;
pub extern fn FT_MulDiv(a: FT_Long, b: FT_Long, c: FT_Long) FT_Long;
pub extern fn FT_MulFix(a: FT_Long, b: FT_Long) FT_Long;
pub extern fn FT_DivFix(a: FT_Long, b: FT_Long) FT_Long;
pub extern fn FT_RoundFix(a: FT_Fixed) FT_Fixed;
pub extern fn FT_CeilFix(a: FT_Fixed) FT_Fixed;
pub extern fn FT_FloorFix(a: FT_Fixed) FT_Fixed;
pub extern fn FT_Vector_Transform(vec: ?[*]FT_Vector, matrix: ?[*]const FT_Matrix) void;
pub extern fn FT_Library_Version(library: ?*FT_Library, amajor: ?[*]FT_Int, aminor: ?[*]FT_Int, apatch: ?[*]FT_Int) void;
pub extern fn FT_Face_CheckTrueTypePatents(face: ?*FT_Face) FT_Bool;
pub extern fn FT_Face_SetUnpatentedHinting(face: ?*FT_Face, value: FT_Bool) FT_Bool; | freetype2.zig |
const std = @import("std");
/// A custom N-bit floating point type, representing `f * 2^e`.
/// e is biased, so it be directly shifted into the exponent bits.
/// Negative exponent indicates an invalid result.
pub fn BiasedFp(comptime T: type) type {
const MantissaT = mantissaType(T);
return struct {
const Self = @This();
/// The significant digits.
f: MantissaT,
/// The biased, binary exponent.
e: i32,
pub fn zero() Self {
return .{ .f = 0, .e = 0 };
}
pub fn zeroPow2(e: i32) Self {
return .{ .f = 0, .e = e };
}
pub fn inf(comptime FloatT: type) Self {
return .{ .f = 0, .e = (1 << std.math.floatExponentBits(FloatT)) - 1 };
}
pub fn eql(self: Self, other: Self) bool {
return self.f == other.f and self.e == other.e;
}
pub fn toFloat(self: Self, comptime FloatT: type, negative: bool) FloatT {
var word = self.f;
word |= @intCast(MantissaT, self.e) << std.math.floatMantissaBits(FloatT);
var f = floatFromUnsigned(FloatT, MantissaT, word);
if (negative) f = -f;
return f;
}
};
}
pub fn floatFromUnsigned(comptime T: type, comptime MantissaT: type, v: MantissaT) T {
return switch (T) {
f16 => @bitCast(f16, @truncate(u16, v)),
f32 => @bitCast(f32, @truncate(u32, v)),
f64 => @bitCast(f64, @truncate(u64, v)),
f128 => @bitCast(f128, v),
else => unreachable,
};
}
/// Represents a parsed floating point value as its components.
pub fn Number(comptime T: type) type {
return struct {
exponent: i64,
mantissa: mantissaType(T),
negative: bool,
/// More than max_mantissa digits were found during parse
many_digits: bool,
/// The number was a hex-float (e.g. 0x1.234p567)
hex: bool,
};
}
/// Determine if 8 bytes are all decimal digits.
/// This does not care about the order in which the bytes were loaded.
pub fn isEightDigits(v: u64) bool {
const a = v +% 0x4646_4646_4646_4646;
const b = v -% 0x3030_3030_3030_3030;
return ((a | b) & 0x8080_8080_8080_8080) == 0;
}
pub fn isDigit(c: u8, comptime base: u8) bool {
std.debug.assert(base == 10 or base == 16);
return if (base == 10)
'0' <= c and c <= '9'
else
'0' <= c and c <= '9' or 'a' <= c and c <= 'f' or 'A' <= c and c <= 'F';
}
/// Returns the underlying storage type used for the mantissa of floating-point type.
/// The output unsigned type must have at least as many bits as the input floating-point type.
pub fn mantissaType(comptime T: type) type {
return switch (T) {
f16, f32, f64 => u64,
f128 => u128,
else => unreachable,
};
} | lib/std/fmt/parse_float/common.zig |
const std = @import("std");
const ast = @import("./ast.zig");
const tok = @import("./token.zig");
const lex = @import("./lexer.zig");
const expr = @import("./expr.zig");
const tfmt = @import("./fmt.zig");
const ExprBlock = expr.ExprBlock;
const Cursor = expr.Cursor;
pub const Op = @import("./token/op.zig").Op;
pub const Block = @import("./token/block.zig").Block;
pub const Tty = @import("./token/type.zig").Tty;
pub const Kw = @import("./token/kw.zig").Kw;
const logs = std.log.scoped(.parser);
const Ast = ast.Ast;
const Token = tok.Token;
const Lexer = lex.Lexer;
pub const Parser = struct {
pos: Cursor,
arena: std.heap.ArenaAllocator,
tokens: std.ArrayList(Token),
allocator: std.mem.Allocator,
state: Parser.State,
const Self = @This();
pub fn init(alloc: std.mem.Allocator, input: []const u8) !Self {
var arena = std.heap.ArenaAllocator.init(alloc);
errdefer arena.deinit();
const tokens = try Lexer.init(input, alloc).lex();
return Self{
.pos = Cursor{ .line = 1, .col = 1 },
.allocator = arena.allocator(),
.tokens = tokens,
.state = State.init(alloc),
.arena = arena,
};
}
pub fn deinit(self: *Self) void {
self.arena.deinit();
self.allocator.free(u8);
}
pub fn next(self: *Self) ?Token {
return self.tokens.popOrNull();
}
pub fn parse(self: *Self) !Ast {
var output = Ast.init(self.allocator, self.arena);
var blocks = std.ArrayList(*ExprBlock).init(self.allocator);
// var curr_block: ?Block = null;
// var curr_expr_block: ?ExprBlock = null;
defer blocks.deinit();
for (self.tokens.items) |tk| {
logs.debug("{s}", .{try tfmt.toStr(tk, self.allocator, "")});
switch (tk.kind) {
.block => |bloc| {
if (@tagName(bloc)[0] == 'l') {
logs.warn("GOT BLOCK START {s}", .{@tagName(bloc)});
blocks.append(@tagName(bloc));
// curr_block = bloc;
// _ = try self.allocator.create(ExprBlock);
// curr_expr_block.? = &ExprBlock.init(self.pos.line, self.pos.col, bloc, self.allocator);
// self.state.curr_block = @enumToInt(bloc);
} else if (@tagName(bloc)[0] == 'r') {
logs.warn("GOT BLOCK START {s}", .{@tagName(bloc)});
blocks.append(@tagName(bloc));
// const bc = curr_block.?.closing();
// if (@enumToInt(bc) == @enumToInt(bloc)) {
// logs.warn("GOT BLOCK END {s}", .{@tagName(bloc)});
// try blocks.append(curr_expr_block.?);
// self.state.curr_block = null;
// curr_expr_block = null;
// curr_block = null;
} else {
logs.warn("GOT OTHER TOKEN {s}", .{@tagName(bloc)});
blocks.append(@tagName(bloc));
}
switch (bloc) {
.lpar => {},
.rpar => {},
.lbracket => {},
.rbracket => {},
.lbrace => {},
.rbrace => {},
.squote => {},
.dquote => {},
else => {},
}
// }
},
.unknown => return PerserError.UnknownToken,
.eof => break,
.op => |oper| switch (oper) {
.at => {},
else => {},
},
.kw => |kword| switch (kword) {
.let => {},
.do => {},
else => {},
},
.type => |typ| switch (typ) {
.none => {},
.ident => |_| {},
.byte => |_| {},
.str => |_| {},
.int => |_| {},
.float => |_| {},
.bool => |_| {},
.seq => {},
},
}
logs.info("{s}", .{tfmt.toStr(tk, self.allocator, "")});
// if (curr_expr_block) |ceb| {
// try ceb.tokens.append(tk);
// }
}
logs.warn("BLOCKS INFO: \n", .{});
for (blocks.items) |bloc| {
logs.warn("INFO: BLOCK {s} ({s}):", .{ bloc.pos, bloc.sblock.toStr() });
for (bloc.tokens.items) |tkn| {
logs.warn("TOKEN: {s} ", .{try tfmt.toStr(tkn, self.allocator, "")});
}
}
logs.warn("BLOCKS LEN: {d}", .{std.mem.len(blocks.items)});
return output;
}
pub fn blockToTree(self: *Self, block_start: Token, block_end: Token, between: []Token) !*Ast.Node {
const block_root = try self.allocator.create(Ast.Node);
defer self.allocator.destroy(block_root);
block_root.* = Ast.Node{ .lhs = null, .rhs = null, .data = block_start };
for (between) |btw| {
std.debug.print("{s}{s}{s}", .{ block_start.toStr(), btw.toStr(), block_end.toStr() });
}
return block_root;
}
pub fn toAst(self: *Self, tk: Token, lhs: ?*Ast.Node, rhs: ?*Ast.Node) !*Ast {
const res = try self.allocator.create(Ast);
defer self.allocator.destroy(res);
res.root = Ast.Node{ .lhs = lhs, .rhs = rhs, .data = tk };
return res;
}
pub fn toExprNode(self: *Self, tk: Token, lhs: ?*Ast.Node, rhs: ?*Ast.Node) !*Ast.Node {
const res = try self.allocator.create(Ast.Node);
defer self.allocator.destroy(res);
res.* = Ast.Node{ .lhs = lhs, .rhs = rhs, .data = tk };
return res;
}
pub fn toNode(self: *Self, tk: Token) !*Ast.Node {
const res = try self.allocator.create(Ast.Node);
defer self.allocator.destroy(res);
res.* = Ast.Node{ .lhs = null, .rhs = null, .data = tk };
return res;
}
pub const State = struct {
curr_t: ?Token,
curr_idx: Cursor,
curr_block: ?i32,
symbols: std.ArrayList(u32),
blocks: std.ArrayList(Block),
list: ?[]const u8,
pub fn init(all: std.mem.Allocator) Parser.State {
return Parser.State{
.curr_idx = Cursor{ .line = 1, .col = 1 },
.curr_t = null,
.curr_block = null,
.symbols = std.ArrayList(u32).init(all),
.blocks = std.ArrayList(Block).init(all),
.list = null,
};
}
pub fn beginBlock(self: Parser.State, blc: Block) void {
switch (blc) {
.lbrace => |braceid| if (braceid) |br_ident| {
self.blocks.put(br_ident, blc);
self.curr_block = br_ident;
} else {
const bid = @tagName(blc) ++ [_]u8{self.blocks.count()};
self.blocks.put(bid, blc);
self.curr_block = bid;
},
.rbrace => |braceid| if (braceid) |bident| {
self.curr_block = bident;
self.blocks.put(bident, blc);
} else {
const bid = @tagName(blc) ++ [_]u8{self.blocks.count()};
self.blocks.put(bid, blc);
self.curr_block = bid;
},
else => {},
}
}
};
};
pub const PerserError = error{
Eof,
NotFound,
UnknownToken,
}; | src/lang/parser.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day04.txt");
const Board = struct {
numbers: [25]u8,
marked: u25 = 0,
won: bool = false,
};
pub fn main() !void {
var segments = tokenize(u8, data, "\r\n ");
var draws = blk: {
var drawing_parts = tokenize(u8, segments.next().?, ",");
var draws = List(u8).init(gpa);
while(drawing_parts.next()) |part| {
draws.append(try parseInt(u8, part, 10)) catch unreachable;
}
break :blk draws.toOwnedSlice();
};
const boards = blk: {
var boards = List(Board).init(gpa);
while (true) {
var b: Board = .{ .numbers = undefined };
var i: usize = 0; while (i < 25) : (i += 1) {
const line = segments.next() orelse{
assert(i == 0);
break :blk boards.toOwnedSlice();
};
b.numbers[i] = try parseInt(u8, line, 10);
}
try boards.append(b);
}
};
var part1: u32 = 0;
var part2: u32 = 0;
var boards_remain = boards.len;
next_draw: for (draws) |drawn| {
for (boards) |*board| {
if (!board.won) {
next_number: for (board.numbers) |*it, index| {
if (it.* == drawn) {
const bit = @as(u25, 1) << @intCast(u5, index);
board.marked |= bit;
if (hasWon(board.*)) {
if (part1 == 0) part1 = score(board.*) * drawn;
board.won = true;
boards_remain -= 1;
if (boards_remain == 0) {
part2 = score(board.*) * drawn;
break :next_draw;
}
continue :next_number;
}
}
}
}
}
} else unreachable; // unfinished boards?
print("part1={}, part2={}\n", .{part1, part2});
}
fn hasWon(b: Board) bool {
const success_patterns = [_]u25 {
0b1000010000100001000010000,
0b0100001000010000100001000,
0b0010000100001000010000100,
0b0001000010000100001000010,
0b0000100001000010000100001,
0b1111100000000000000000000,
0b0000011111000000000000000,
0b0000000000111110000000000,
0b0000000000000001111100000,
0b0000000000000000000011111,
};
for (success_patterns) |pat| {
if (b.marked & pat == pat) {
return true;
}
}
return false;
}
fn score(b: Board) u32 {
var total: u32 = 0;
for (b.numbers) |it, i| {
const bit = @as(u25, 1) << @intCast(u5, i);
if (bit & b.marked == 0) {
total += it;
}
}
return total;
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const strEql = std.mem.eql;
const strToEnum = std.meta.stringToEnum;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc; | src/day04.zig |
const std = @import("std");
const Arena = std.heap.ArenaAllocator;
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
const yeti = @import("yeti");
const initCodebase = yeti.initCodebase;
const tokenize = yeti.tokenize;
const parse = yeti.parse;
const analyzeSemantics = yeti.analyzeSemantics;
const codegen = yeti.codegen;
const printWasm = yeti.printWasm;
const components = yeti.components;
const literalOf = yeti.query.literalOf;
const typeOf = yeti.query.typeOf;
const parentType = yeti.query.parentType;
const valueType = yeti.query.valueType;
const Entity = yeti.ecs.Entity;
const MockFileSystem = yeti.FileSystem;
test "tokenize function" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const module = try codebase.createEntity(.{});
const code = "start() u64 { 0 }";
var tokens = try tokenize(module, code);
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .symbol);
try expectEqualStrings(literalOf(token), "start");
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 0, .row = 0 },
.end = .{ .column = 5, .row = 0 },
});
}
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .left_paren);
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 5, .row = 0 },
.end = .{ .column = 6, .row = 0 },
});
}
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .right_paren);
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 6, .row = 0 },
.end = .{ .column = 7, .row = 0 },
});
}
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .symbol);
try expectEqualStrings(literalOf(token), "u64");
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 8, .row = 0 },
.end = .{ .column = 11, .row = 0 },
});
}
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .left_brace);
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 12, .row = 0 },
.end = .{ .column = 13, .row = 0 },
});
}
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .int);
try expectEqualStrings(literalOf(token), "0");
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 14, .row = 0 },
.end = .{ .column = 15, .row = 0 },
});
}
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .right_brace);
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 16, .row = 0 },
.end = .{ .column = 17, .row = 0 },
});
}
try expectEqual(tokens.next(), null);
}
test "tokenize multine function" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const module = try codebase.createEntity(.{});
const code =
\\f() u64 {
\\ x = 5
\\ y = 15
\\ x + y
\\}
;
var tokens = try tokenize(module, code);
try expectEqual(tokens.next().?.get(components.TokenKind), .symbol);
try expectEqual(tokens.next().?.get(components.TokenKind), .left_paren);
try expectEqual(tokens.next().?.get(components.TokenKind), .right_paren);
try expectEqual(tokens.next().?.get(components.TokenKind), .symbol);
try expectEqual(tokens.next().?.get(components.TokenKind), .left_brace);
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .new_line);
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 9, .row = 0 },
.end = .{ .column = 0, .row = 1 },
});
}
try expectEqual(tokens.next().?.get(components.TokenKind), .symbol);
try expectEqual(tokens.next().?.get(components.TokenKind), .equal);
try expectEqual(tokens.next().?.get(components.TokenKind), .int);
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .new_line);
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 7, .row = 1 },
.end = .{ .column = 0, .row = 2 },
});
}
try expectEqual(tokens.next().?.get(components.TokenKind), .symbol);
try expectEqual(tokens.next().?.get(components.TokenKind), .equal);
try expectEqual(tokens.next().?.get(components.TokenKind), .int);
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .new_line);
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 8, .row = 2 },
.end = .{ .column = 0, .row = 3 },
});
}
try expectEqual(tokens.next().?.get(components.TokenKind), .symbol);
try expectEqual(tokens.next().?.get(components.TokenKind), .plus);
try expectEqual(tokens.next().?.get(components.TokenKind), .symbol);
{
const token = tokens.next().?;
try expectEqual(token.get(components.TokenKind), .new_line);
try expectEqual(token.get(components.Span), .{
.begin = .{ .column = 7, .row = 3 },
.end = .{ .column = 0, .row = 4 },
});
}
try expectEqual(tokens.next().?.get(components.TokenKind), .right_brace);
try expectEqual(tokens.next(), null);
}
test "parse function" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const module = try codebase.createEntity(.{});
const code =
\\start() u64 {
\\ 0
\\}
;
var tokens = try tokenize(module, code);
try parse(module, &tokens);
const top_level = module.get(components.TopLevel);
const overloads = top_level.findString("start").get(components.Overloads).slice();
try expectEqual(overloads.len, 1);
const start = overloads[0];
const return_type = start.get(components.ReturnTypeAst).entity;
try expectEqual(return_type.get(components.AstKind), .symbol);
try expectEqualStrings(literalOf(return_type), "u64");
const body = overloads[0].get(components.Body).slice();
try expectEqual(body.len, 1);
const zero = body[0];
try expectEqual(zero.get(components.AstKind), .int);
try expectEqualStrings(literalOf(zero), "0");
}
test "parse two functions" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const module = try codebase.createEntity(.{});
const code =
\\sum_of_squares(x: u64, y: u64) u64 {
\\ x*2 + y*2
\\}
\\
\\start() u64 {
\\ sum_of_squares(10, 56 * 3)
\\}
;
var tokens = try tokenize(module, code);
try parse(module, &tokens);
{
const sum_of_squares = module.get(components.TopLevel).findString("sum_of_squares");
const overloads = sum_of_squares.get(components.Overloads).slice();
try expectEqual(overloads.len, 1);
try expectEqual(overloads[0].get(components.Parameters).slice().len, 2);
}
{
const start = module.get(components.TopLevel).findString("start");
const overloads = start.get(components.Overloads).slice();
try expectEqual(overloads.len, 1);
try expectEqual(overloads[0].get(components.Parameters).slice().len, 0);
}
}
test "parse overload" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const module = try codebase.createEntity(.{});
const code =
\\id(x: u64) u64 { x }
\\
\\id(x: f64) f64 { x }
;
var tokens = try tokenize(module, code);
try parse(module, &tokens);
const id = module.get(components.TopLevel).findString("id");
const overloads = id.get(components.Overloads).slice();
try expectEqual(overloads.len, 2);
{
const id_u64 = overloads[0];
const parameters = id_u64.get(components.Parameters).slice();
try expectEqual(parameters.len, 1);
const x = parameters[0];
try expectEqualStrings(literalOf(x), "x");
try expectEqualStrings(literalOf(x.get(components.TypeAst).entity), "u64");
try expectEqualStrings(literalOf(id_u64.get(components.ReturnTypeAst).entity), "u64");
}
{
const id_f64 = overloads[1];
const parameters = id_f64.get(components.Parameters).slice();
try expectEqual(parameters.len, 1);
const x = parameters[0];
try expectEqualStrings(literalOf(x), "x");
try expectEqualStrings(literalOf(x.get(components.TypeAst).entity), "f64");
try expectEqualStrings(literalOf(id_f64.get(components.ReturnTypeAst).entity), "f64");
}
}
test "analyze semantics call local function" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const builtins = codebase.get(components.Builtins);
const types = [_][]const u8{ "i64", "i32", "u64", "u32", "f64", "f32" };
const builtin_types = [_]Entity{ builtins.I64, builtins.I32, builtins.U64, builtins.U32, builtins.F64, builtins.F32 };
for (types) |type_of, i| {
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti", try std.fmt.allocPrint(arena.allocator(),
\\start() {s} {{
\\ baz()
\\}}
\\
\\baz() {s} {{
\\ 10
\\}}
, .{ type_of, type_of }));
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(start.get(components.Name).entity), "start");
try expectEqual(start.get(components.Parameters).len(), 0);
try expectEqual(start.get(components.ReturnType).entity, builtin_types[i]);
const baz = blk: {
const body = start.get(components.Body).slice();
try expectEqual(body.len, 1);
const call = body[0];
try expectEqual(call.get(components.AstKind), .call);
try expectEqual(call.get(components.Arguments).len(), 0);
try expectEqual(typeOf(call), builtin_types[i]);
break :blk call.get(components.Callable).entity;
};
try expectEqualStrings(literalOf(baz.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(baz.get(components.Name).entity), "baz");
try expectEqual(baz.get(components.Parameters).len(), 0);
try expectEqual(baz.get(components.ReturnType).entity, builtin_types[i]);
const body = baz.get(components.Body).slice();
try expectEqual(body.len, 1);
const int_literal = body[0];
try expectEqual(int_literal.get(components.AstKind), .int);
try expectEqual(typeOf(int_literal), builtin_types[i]);
try expectEqualStrings(literalOf(int_literal), "10");
}
}
test "analyze semantics function with argument" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const builtins = codebase.get(components.Builtins);
const types = [_][]const u8{ "i64", "i32", "u64", "u32", "f64", "f32" };
const builtin_types = [_]Entity{ builtins.I64, builtins.I32, builtins.U64, builtins.U32, builtins.F64, builtins.F32 };
for (types) |type_of, i| {
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti", try std.fmt.allocPrint(arena.allocator(),
\\start() {s} {{
\\ x: {s} = 10
\\ id(x)
\\}}
\\
\\id(x: {s}) {s} {{
\\ x
\\}}
, .{ type_of, type_of, type_of, type_of }));
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(start.get(components.Name).entity), "start");
try expectEqual(start.get(components.Parameters).len(), 0);
try expectEqual(start.get(components.ReturnType).entity, builtin_types[i]);
const id = blk: {
const body = start.get(components.Body).slice();
try expectEqual(body.len, 2);
const define = body[0];
try expectEqual(define.get(components.AstKind), .define);
try expectEqual(typeOf(define), builtins.Void);
try expectEqualStrings(literalOf(define.get(components.Value).entity), "10");
const x = define.get(components.Local).entity;
try expectEqual(x.get(components.AstKind), .local);
try expectEqualStrings(literalOf(x.get(components.Name).entity), "x");
try expectEqual(typeOf(x), builtin_types[i]);
const call = body[1];
try expectEqual(call.get(components.AstKind), .call);
try expectEqual(typeOf(call), builtin_types[i]);
const arguments = call.get(components.Arguments).slice();
try expectEqual(arguments.len, 1);
try expectEqual(arguments[0], x);
break :blk call.get(components.Callable).entity;
};
try expectEqualStrings(literalOf(id.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(id.get(components.Name).entity), "id");
const parameters = id.get(components.Parameters).slice();
try expectEqual(parameters.len, 1);
const x = parameters[0];
try expectEqual(typeOf(x), builtin_types[i]);
try expectEqualStrings(literalOf(x.get(components.Name).entity), "x");
const body = id.get(components.Body).slice();
try expectEqual(body.len, 1);
try expectEqual(body[0], x);
}
}
test "analyze semantics function call twice" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const builtins = codebase.get(components.Builtins);
const types = [_][]const u8{ "i64", "i32", "u64", "u32", "f64", "f32" };
const builtin_types = [_]Entity{ builtins.I64, builtins.I32, builtins.U64, builtins.U32, builtins.F64, builtins.F32 };
for (types) |type_of, i| {
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti", try std.fmt.allocPrint(arena.allocator(),
\\start() {s} {{
\\ x = id(10)
\\ id(25)
\\}}
\\
\\id(x: {s}) {s} {{
\\ x
\\}}
, .{ type_of, type_of, type_of }));
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(start.get(components.Name).entity), "start");
try expectEqual(start.get(components.Parameters).len(), 0);
try expectEqual(start.get(components.ReturnType).entity, builtin_types[i]);
const start_body = start.get(components.Body).slice();
try expectEqual(start_body.len, 2);
const id = blk: {
const define = start_body[0];
try expectEqual(define.get(components.AstKind), .define);
try expectEqual(typeOf(define), builtins.Void);
const x = define.get(components.Local).entity;
try expectEqual(x.get(components.AstKind), .local);
try expectEqualStrings(literalOf(x.get(components.Name).entity), "x");
try expectEqual(typeOf(x), builtin_types[i]);
const call = define.get(components.Value).entity;
try expectEqual(typeOf(call), builtin_types[i]);
try expectEqual(call.get(components.AstKind), .call);
const arguments = call.get(components.Arguments).slice();
try expectEqual(arguments.len, 1);
const argument = arguments[0];
try expectEqual(argument.get(components.AstKind), .int);
try expectEqual(typeOf(argument), builtin_types[i]);
try expectEqualStrings(literalOf(argument), "10");
break :blk call.get(components.Callable).entity;
};
const call = start_body[1];
try expectEqual(call.get(components.AstKind), .call);
try expectEqual(typeOf(call), builtin_types[i]);
const arguments = call.get(components.Arguments).slice();
try expectEqual(arguments.len, 1);
const argument = arguments[0];
try expectEqual(argument.get(components.AstKind), .int);
try expectEqual(typeOf(argument), builtin_types[i]);
try expectEqualStrings(literalOf(argument), "25");
try expectEqual(call.get(components.Callable).entity, id);
try expectEqualStrings(literalOf(id.get(components.Module).entity), "foo");
try expectEqualStrings(literalOf(id.get(components.Name).entity), "id");
const parameters = id.get(components.Parameters).slice();
try expectEqual(parameters.len, 1);
const x = parameters[0];
try expectEqual(typeOf(x), builtin_types[i]);
try expectEqualStrings(literalOf(x.get(components.Name).entity), "x");
const body = id.get(components.Body).slice();
try expectEqual(body.len, 1);
try expectEqual(body[0], x);
}
}
test "codegen call local function" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const types = [_][]const u8{ "i64", "i32", "u64", "u32", "f64", "f32" };
const const_kinds = [_]components.WasmInstructionKind{ .i64_const, .i32_const, .i64_const, .i32_const, .f64_const, .f32_const };
for (types) |type_, i| {
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti", try std.fmt.allocPrint(arena.allocator(),
\\start() {s} {{
\\ baz()
\\}}
\\
\\baz() {s} {{
\\ 10
\\}}
, .{ type_, type_ }));
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
try codegen(module);
const top_level = module.get(components.TopLevel);
const start = top_level.findString("start").get(components.Overloads).slice()[0];
const start_instructions = start.get(components.WasmInstructions).slice();
try expectEqual(start_instructions.len, 1);
const call = start_instructions[0];
try expectEqual(call.get(components.WasmInstructionKind), .call);
const baz = call.get(components.Callable).entity;
const baz_instructions = baz.get(components.WasmInstructions).slice();
try expectEqual(baz_instructions.len, 1);
const constant = baz_instructions[0];
try expectEqual(constant.get(components.WasmInstructionKind), const_kinds[i]);
try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "10");
}
}
test "print wasm call local function" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const types = [_][]const u8{ "f64", "f32" };
const wasm_types = [_][]const u8{ "f64", "f32" };
for (types) |type_, i| {
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti", try std.fmt.allocPrint(arena.allocator(),
\\start() {s} {{
\\ baz()
\\}}
\\
\\baz() {s} {{
\\ 10
\\}}
, .{ type_, type_ }));
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
try codegen(module);
const wasm = try printWasm(module);
try expectEqualStrings(wasm, try std.fmt.allocPrint(arena.allocator(),
\\(module
\\
\\ (func $foo/start (result {s})
\\ (call $foo/baz))
\\
\\ (func $foo/baz (result {s})
\\ ({s}.const 10))
\\
\\ (export "_start" (func $foo/start)))
, .{ wasm_types[i], wasm_types[i], wasm_types[i] }));
}
}
test "print wasm call local function with argument" {
var arena = Arena.init(std.heap.page_allocator);
defer arena.deinit();
var codebase = try initCodebase(&arena);
const types = [_][]const u8{ "i64", "i32", "u64", "u32", "f64", "f32" };
const wasm_types = [_][]const u8{ "i64", "i32", "i64", "i32", "f64", "f32" };
const const_kinds = [_][]const u8{ "i64.const", "i32.const", "i64.const", "i32.const", "f64.const", "f32.const" };
for (types) |type_, i| {
var fs = try MockFileSystem.init(&arena);
_ = try fs.newFile("foo.yeti", try std.fmt.allocPrint(arena.allocator(),
\\start() {s} {{
\\ id(5)
\\}}
\\
\\id(x: {s}) {s} {{
\\ x
\\}}
, .{ type_, type_, type_ }));
const module = try analyzeSemantics(codebase, fs, "foo.yeti");
try codegen(module);
const wasm = try printWasm(module);
try expectEqualStrings(wasm, try std.fmt.allocPrint(arena.allocator(),
\\(module
\\
\\ (func $foo/start (result {s})
\\ ({s} 5)
\\ (call $foo/id..x.{s}))
\\
\\ (func $foo/id..x.{s} (param $x {s}) (result {s})
\\ (local.get $x))
\\
\\ (export "_start" (func $foo/start)))
, .{ wasm_types[i], const_kinds[i], type_, type_, wasm_types[i], wasm_types[i] }));
}
} | src/tests/test_function.zig |
const std = @import("std");
const root = @import("root");
pub const STEP_SIZE = if (@hasDecl(root, "step_size")) root.step_size else 64;
comptime {
if (!(STEP_SIZE == 64 or STEP_SIZE == 128)) @compileError("step-size must be either 64 or 128");
}
pub const DEFAULT_MAX_DEPTH = 1024;
pub const u8xstep_size = std.meta.Vector(STEP_SIZE, u8);
pub const STREAMING = false;
pub const SIMDJSON_PADDING = 32;
// pub const log_level: std.log.Level = .debug;
pub const log_level: std.log.Level = .err;
pub var debug = log_level == .debug;
pub fn println(comptime fmt: []const u8, args: anytype) void {
print(fmt ++ "\n", args);
}
pub fn print(comptime fmt: []const u8, args: anytype) void {
if (debug)
std.debug.print(fmt, args);
// std.log.debug(fmt, args);
}
pub fn print_vec(name: []const u8, vec: anytype) void {
println("{s}: {any}", .{ name, @as([@sizeOf(@TypeOf(vec))]u8, vec) });
}
pub inline fn ROUNDUP_N(a: anytype, n: @TypeOf(a)) @TypeOf(a) {
return (a + (n - 1)) & ~(n - 1);
}
pub inline fn ptr_diff(comptime T: type, p1: anytype, p2: anytype) !T {
const U = std.meta.Child(@TypeOf(p1));
const V = std.meta.Child(@TypeOf(p2));
if (@sizeOf(U) != @sizeOf(V)) @compileError("ptr_diff: mismatched child sizes");
const diff = @ptrToInt(p1) - @ptrToInt(p2);
return std.math.cast(T, diff / (@sizeOf(U)));
}
pub const FileError = std.fs.File.OpenError || std.fs.File.ReadError || std.fs.File.SeekError;
pub const Error = std.mem.Allocator.Error || std.os.WriteError || FileError || error{ EndOfStream, Overflow } || JsonError;
pub const JsonError = error{
/// This parser can't support a document that big
CAPACITY,
/// Error allocating memory, most likely out of memory
MEMALLOC,
/// Something went wrong while writing to the tape (stage 2), this is a generic error
TAPE_ERROR,
/// Your document exceeds the user-specified depth limitation
DEPTH_ERROR,
/// Problem while parsing a string
STRING_ERROR,
/// Problem while parsing an atom starting with the letter 't'
T_ATOM_ERROR,
/// Problem while parsing an atom starting with the letter 'f'
F_ATOM_ERROR,
/// Problem while parsing an atom starting with the letter 'n'
N_ATOM_ERROR,
/// Problem while parsing a number
NUMBER_ERROR,
/// the input is not valid UTF-8
UTF8_ERROR,
/// unknown error, or uninitialized document
UNINITIALIZED,
/// no structural element found
EMPTY,
/// found unescaped characters in a string.
UNESCAPED_CHARS,
/// missing quote at the end
UNCLOSED_STRING,
/// unsupported architecture
UNSUPPORTED_ARCHITECTURE,
/// JSON element has a different type than user expected
INCORRECT_TYPE,
/// JSON number does not fit in 64 bits
NUMBER_OUT_OF_RANGE,
/// JSON array index too large
INDEX_OUT_OF_BOUNDS,
/// JSON field not found in object
NO_SUCH_FIELD,
/// Error reading a file
IO_ERROR,
/// Invalid JSON pointer reference
INVALID_JSON_POINTER,
/// Invalid URI fragment
INVALID_URI_FRAGMENT,
/// indicative of a bug in simdjson
UNEXPECTED_ERROR,
/// parser is already in use.
PARSER_IN_USE,
/// tried to iterate an array or object out of order
OUT_OF_ORDER_ITERATION,
/// The JSON doesn't have enough padding for simdjson to safely parse it.
INSUFFICIENT_PADDING,
}; | src/common.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.