authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-08-28 12:41:24-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-08-28 12:41:24-07:00
log6aeab0f323ff14d7ad248e18c372573f7a5a8cd1
tree7080297f629f39baa0b742985c5804cf6a2047e8
parent47f7ed1c4cb8acf7fed99a057fb84202962e4b1b
parent05cf44933d753f7a5a53ab289ea60fd43761de57

Merge remote-tracking branch 'origin/master' into llvm13

Conflicts: lib/libcxx/include/__config d57c0cc3bfeff9af297279759ec2b631e6d95140 added support for DragonFlyBSD to libc++ by updating some ifdefs. This needed to be synced with llvm13.

599 files changed, 8759 insertions(+), 8140 deletions(-)

CMakeLists.txt+1-1
...@@ -426,7 +426,7 @@ set(ZIG_STAGE2_SOURCES...@@ -426,7 +426,7 @@ set(ZIG_STAGE2_SOURCES
426 "${CMAKE_SOURCE_DIR}/lib/std/os.zig"426 "${CMAKE_SOURCE_DIR}/lib/std/os.zig"
427 "${CMAKE_SOURCE_DIR}/lib/std/os/bits.zig"427 "${CMAKE_SOURCE_DIR}/lib/std/os/bits.zig"
428 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux.zig"428 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux.zig"
429 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux/errno-generic.zig"429 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux/errno/generic.zig"
430 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux/netlink.zig"430 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux/netlink.zig"
431 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux/prctl.zig"431 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux/prctl.zig"
432 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux/securebits.zig"432 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux/securebits.zig"
build.zig+40-28
...@@ -17,8 +17,10 @@ pub fn build(b: *Builder) !void {...@@ -17,8 +17,10 @@ pub fn build(b: *Builder) !void {
17 b.setPreferredReleaseMode(.ReleaseFast);17 b.setPreferredReleaseMode(.ReleaseFast);
18 const mode = b.standardReleaseOptions();18 const mode = b.standardReleaseOptions();
19 const target = b.standardTargetOptions(.{});19 const target = b.standardTargetOptions(.{});
20 const single_threaded = b.option(bool, "single-threaded", "Build artifacts that run in single threaded mode") orelse false;
2021
21 var docgen_exe = b.addExecutable("docgen", "doc/docgen.zig");22 var docgen_exe = b.addExecutable("docgen", "doc/docgen.zig");
23 docgen_exe.single_threaded = single_threaded;
2224
23 const rel_zig_exe = try fs.path.relative(b.allocator, b.build_root, b.zig_exe);25 const rel_zig_exe = try fs.path.relative(b.allocator, b.build_root, b.zig_exe);
24 const langref_out_path = fs.path.join(26 const langref_out_path = fs.path.join(
...@@ -41,6 +43,7 @@ pub fn build(b: *Builder) !void {...@@ -41,6 +43,7 @@ pub fn build(b: *Builder) !void {
41 var test_stage2 = b.addTest("src/test.zig");43 var test_stage2 = b.addTest("src/test.zig");
42 test_stage2.setBuildMode(mode);44 test_stage2.setBuildMode(mode);
43 test_stage2.addPackagePath("test_cases", "test/cases.zig");45 test_stage2.addPackagePath("test_cases", "test/cases.zig");
46 test_stage2.single_threaded = single_threaded;
4447
45 const fmt_build_zig = b.addFmt(&[_][]const u8{"build.zig"});48 const fmt_build_zig = b.addFmt(&[_][]const u8{"build.zig"});
4649
...@@ -104,10 +107,15 @@ pub fn build(b: *Builder) !void {...@@ -104,10 +107,15 @@ pub fn build(b: *Builder) !void {
104 exe.setTarget(target);107 exe.setTarget(target);
105 toolchain_step.dependOn(&exe.step);108 toolchain_step.dependOn(&exe.step);
106 b.default_step.dependOn(&exe.step);109 b.default_step.dependOn(&exe.step);
110 exe.single_threaded = single_threaded;
111
112 const exe_options = b.addOptions();
113 exe.addOptions("build_options", exe_options);
114
115 exe_options.addOption(u32, "mem_leak_frames", mem_leak_frames);
116 exe_options.addOption(bool, "skip_non_native", skip_non_native);
117 exe_options.addOption(bool, "have_llvm", enable_llvm);
107118
108 exe.addBuildOption(u32, "mem_leak_frames", mem_leak_frames);
109 exe.addBuildOption(bool, "skip_non_native", skip_non_native);
110 exe.addBuildOption(bool, "have_llvm", enable_llvm);
111 if (enable_llvm) {119 if (enable_llvm) {
112 const cmake_cfg = if (static_llvm) null else findAndParseConfigH(b, config_h_path_option);120 const cmake_cfg = if (static_llvm) null else findAndParseConfigH(b, config_h_path_option);
113121
...@@ -131,6 +139,7 @@ pub fn build(b: *Builder) !void {...@@ -131,6 +139,7 @@ pub fn build(b: *Builder) !void {
131 softfloat.addIncludeDir("deps/SoftFloat-3e/source/8086");139 softfloat.addIncludeDir("deps/SoftFloat-3e/source/8086");
132 softfloat.addIncludeDir("deps/SoftFloat-3e/source/include");140 softfloat.addIncludeDir("deps/SoftFloat-3e/source/include");
133 softfloat.addCSourceFiles(&softfloat_sources, &[_][]const u8{ "-std=c99", "-O3" });141 softfloat.addCSourceFiles(&softfloat_sources, &[_][]const u8{ "-std=c99", "-O3" });
142 softfloat.single_threaded = single_threaded;
134143
135 exe.linkLibrary(softfloat);144 exe.linkLibrary(softfloat);
136 test_stage2.linkLibrary(softfloat);145 test_stage2.linkLibrary(softfloat);
...@@ -213,15 +222,15 @@ pub fn build(b: *Builder) !void {...@@ -213,15 +222,15 @@ pub fn build(b: *Builder) !void {
213 },222 },
214 }223 }
215 };224 };
216 exe.addBuildOption([:0]const u8, "version", try b.allocator.dupeZ(u8, version));225 exe_options.addOption([:0]const u8, "version", try b.allocator.dupeZ(u8, version));
217226
218 const semver = try std.SemanticVersion.parse(version);227 const semver = try std.SemanticVersion.parse(version);
219 exe.addBuildOption(std.SemanticVersion, "semver", semver);228 exe_options.addOption(std.SemanticVersion, "semver", semver);
220229
221 exe.addBuildOption(bool, "enable_logging", enable_logging);230 exe_options.addOption(bool, "enable_logging", enable_logging);
222 exe.addBuildOption(bool, "enable_tracy", tracy != null);231 exe_options.addOption(bool, "enable_tracy", tracy != null);
223 exe.addBuildOption(bool, "is_stage1", is_stage1);232 exe_options.addOption(bool, "is_stage1", is_stage1);
224 exe.addBuildOption(bool, "omit_stage2", omit_stage2);233 exe_options.addOption(bool, "omit_stage2", omit_stage2);
225 if (tracy) |tracy_path| {234 if (tracy) |tracy_path| {
226 const client_cpp = fs.path.join(235 const client_cpp = fs.path.join(
227 b.allocator,236 b.allocator,
...@@ -243,20 +252,23 @@ pub fn build(b: *Builder) !void {...@@ -243,20 +252,23 @@ pub fn build(b: *Builder) !void {
243 const is_darling_enabled = b.option(bool, "enable-darling", "[Experimental] Use Darling to run cross compiled macOS tests") orelse false;252 const is_darling_enabled = b.option(bool, "enable-darling", "[Experimental] Use Darling to run cross compiled macOS tests") orelse false;
244 const glibc_multi_dir = b.option([]const u8, "enable-foreign-glibc", "Provide directory with glibc installations to run cross compiled tests that link glibc");253 const glibc_multi_dir = b.option([]const u8, "enable-foreign-glibc", "Provide directory with glibc installations to run cross compiled tests that link glibc");
245254
246 test_stage2.addBuildOption(bool, "enable_logging", enable_logging);255 const test_stage2_options = b.addOptions();
247 test_stage2.addBuildOption(bool, "skip_non_native", skip_non_native);256 test_stage2.addOptions("build_options", test_stage2_options);
248 test_stage2.addBuildOption(bool, "skip_compile_errors", skip_compile_errors);257
249 test_stage2.addBuildOption(bool, "is_stage1", is_stage1);258 test_stage2_options.addOption(bool, "enable_logging", enable_logging);
250 test_stage2.addBuildOption(bool, "omit_stage2", omit_stage2);259 test_stage2_options.addOption(bool, "skip_non_native", skip_non_native);
251 test_stage2.addBuildOption(bool, "have_llvm", enable_llvm);260 test_stage2_options.addOption(bool, "skip_compile_errors", skip_compile_errors);
252 test_stage2.addBuildOption(bool, "enable_qemu", is_qemu_enabled);261 test_stage2_options.addOption(bool, "is_stage1", is_stage1);
253 test_stage2.addBuildOption(bool, "enable_wine", is_wine_enabled);262 test_stage2_options.addOption(bool, "omit_stage2", omit_stage2);
254 test_stage2.addBuildOption(bool, "enable_wasmtime", is_wasmtime_enabled);263 test_stage2_options.addOption(bool, "have_llvm", enable_llvm);
255 test_stage2.addBuildOption(u32, "mem_leak_frames", mem_leak_frames * 2);264 test_stage2_options.addOption(bool, "enable_qemu", is_qemu_enabled);
256 test_stage2.addBuildOption(bool, "enable_darling", is_darling_enabled);265 test_stage2_options.addOption(bool, "enable_wine", is_wine_enabled);
257 test_stage2.addBuildOption(?[]const u8, "glibc_multi_install_dir", glibc_multi_dir);266 test_stage2_options.addOption(bool, "enable_wasmtime", is_wasmtime_enabled);
258 test_stage2.addBuildOption([:0]const u8, "version", try b.allocator.dupeZ(u8, version));267 test_stage2_options.addOption(u32, "mem_leak_frames", mem_leak_frames * 2);
259 test_stage2.addBuildOption(std.SemanticVersion, "semver", semver);268 test_stage2_options.addOption(bool, "enable_darling", is_darling_enabled);
269 test_stage2_options.addOption(?[]const u8, "glibc_multi_install_dir", glibc_multi_dir);
270 test_stage2_options.addOption([:0]const u8, "version", try b.allocator.dupeZ(u8, version));
271 test_stage2_options.addOption(std.SemanticVersion, "semver", semver);
260272
261 const test_stage2_step = b.step("test-stage2", "Run the stage2 compiler tests");273 const test_stage2_step = b.step("test-stage2", "Run the stage2 compiler tests");
262 test_stage2_step.dependOn(&test_stage2.step);274 test_stage2_step.dependOn(&test_stage2.step);
...@@ -296,7 +308,7 @@ pub fn build(b: *Builder) !void {...@@ -296,7 +308,7 @@ pub fn build(b: *Builder) !void {
296 "behavior",308 "behavior",
297 "Run the behavior tests",309 "Run the behavior tests",
298 modes,310 modes,
299 false,311 false, // skip_single_threaded
300 skip_non_native,312 skip_non_native,
301 skip_libc,313 skip_libc,
302 is_wine_enabled,314 is_wine_enabled,
...@@ -313,9 +325,9 @@ pub fn build(b: *Builder) !void {...@@ -313,9 +325,9 @@ pub fn build(b: *Builder) !void {
313 "compiler-rt",325 "compiler-rt",
314 "Run the compiler_rt tests",326 "Run the compiler_rt tests",
315 modes,327 modes,
316 true,328 true, // skip_single_threaded
317 skip_non_native,329 skip_non_native,
318 true,330 true, // skip_libc
319 is_wine_enabled,331 is_wine_enabled,
320 is_qemu_enabled,332 is_qemu_enabled,
321 is_wasmtime_enabled,333 is_wasmtime_enabled,
...@@ -330,9 +342,9 @@ pub fn build(b: *Builder) !void {...@@ -330,9 +342,9 @@ pub fn build(b: *Builder) !void {
330 "minilibc",342 "minilibc",
331 "Run the mini libc tests",343 "Run the mini libc tests",
332 modes,344 modes,
333 true,345 true, // skip_single_threaded
334 skip_non_native,346 skip_non_native,
335 true,347 true, // skip_libc
336 is_wine_enabled,348 is_wine_enabled,
337 is_qemu_enabled,349 is_qemu_enabled,
338 is_wasmtime_enabled,350 is_wasmtime_enabled,
doc/docgen.zig+14-15
...@@ -887,16 +887,6 @@ fn tokenizeAndPrintRaw(...@@ -887,16 +887,6 @@ fn tokenizeAndPrintRaw(
887 next_tok_is_fn = true;887 next_tok_is_fn = true;
888 },888 },
889889
890 .keyword_undefined,
891 .keyword_null,
892 .keyword_true,
893 .keyword_false,
894 => {
895 try out.writeAll("<span class=\"tok-null\">");
896 try writeEscaped(out, src[token.loc.start..token.loc.end]);
897 try out.writeAll("</span>");
898 },
899
900 .string_literal,890 .string_literal,
901 .multiline_string_literal_line,891 .multiline_string_literal_line,
902 .char_literal,892 .char_literal,
...@@ -921,9 +911,18 @@ fn tokenizeAndPrintRaw(...@@ -921,9 +911,18 @@ fn tokenizeAndPrintRaw(
921 },911 },
922912
923 .identifier => {913 .identifier => {
924 if (prev_tok_was_fn) {914 const tok_bytes = src[token.loc.start..token.loc.end];
915 if (mem.eql(u8, tok_bytes, "undefined") or
916 mem.eql(u8, tok_bytes, "null") or
917 mem.eql(u8, tok_bytes, "true") or
918 mem.eql(u8, tok_bytes, "false"))
919 {
920 try out.writeAll("<span class=\"tok-null\">");
921 try writeEscaped(out, tok_bytes);
922 try out.writeAll("</span>");
923 } else if (prev_tok_was_fn) {
925 try out.writeAll("<span class=\"tok-fn\">");924 try out.writeAll("<span class=\"tok-fn\">");
926 try writeEscaped(out, src[token.loc.start..token.loc.end]);925 try writeEscaped(out, tok_bytes);
927 try out.writeAll("</span>");926 try out.writeAll("</span>");
928 } else {927 } else {
929 const is_int = blk: {928 const is_int = blk: {
...@@ -938,12 +937,12 @@ fn tokenizeAndPrintRaw(...@@ -938,12 +937,12 @@ fn tokenizeAndPrintRaw(
938 }937 }
939 break :blk true;938 break :blk true;
940 };939 };
941 if (is_int or isType(src[token.loc.start..token.loc.end])) {940 if (is_int or isType(tok_bytes)) {
942 try out.writeAll("<span class=\"tok-type\">");941 try out.writeAll("<span class=\"tok-type\">");
943 try writeEscaped(out, src[token.loc.start..token.loc.end]);942 try writeEscaped(out, tok_bytes);
944 try out.writeAll("</span>");943 try out.writeAll("</span>");
945 } else {944 } else {
946 try writeEscaped(out, src[token.loc.start..token.loc.end]);945 try writeEscaped(out, tok_bytes);
947 }946 }
948 }947 }
949 },948 },
doc/langref.html.in+42-21
...@@ -38,15 +38,20 @@...@@ -38,15 +38,20 @@
38 .file {38 .file {
39 text-decoration: underline;39 text-decoration: underline;
40 }40 }
41 pre,code {
42 font-size: 12pt;
43 }
44 pre > code {41 pre > code {
45 display: block;42 display: block;
46 overflow: auto;43 overflow: auto;
47 padding: 0.5em;44 padding: 0.5em;
48 color: #333;45 color: #333;
49 background: #f8f8f8;46 background: #f8f8f8;
47 border: 1px dotted silver;
48 line-height: normal;
49 }
50 code {
51 background-color: #f8f8f8;
52 border: 1px dotted silver;
53 padding-left: 0.3em;
54 padding-right: 0.3em;
50 }55 }
51 .table-wrapper {56 .table-wrapper {
52 width: 100%;57 width: 100%;
...@@ -95,6 +100,7 @@...@@ -95,6 +100,7 @@
95 #contents {100 #contents {
96 max-width: 60em;101 max-width: 60em;
97 margin: auto;102 margin: auto;
103 line-height: 1.5;
98 }104 }
99105
100 #toc {106 #toc {
...@@ -153,6 +159,11 @@...@@ -153,6 +159,11 @@
153 pre > code {159 pre > code {
154 color: #ccc;160 color: #ccc;
155 background: #222;161 background: #222;
162 border-color: #444;
163 }
164 code {
165 background-color: #222;
166 border-color: #444;
156 }167 }
157 .tok-kw {168 .tok-kw {
158 color: #eee;169 color: #eee;
...@@ -3152,7 +3163,9 @@ test "switch using enum literals" {...@@ -3152,7 +3163,9 @@ test "switch using enum literals" {
3152 It must specify a tag type and cannot consume every enumeration value.3163 It must specify a tag type and cannot consume every enumeration value.
3153 </p>3164 </p>
3154 <p>3165 <p>
3155 {#link|@intToEnum#} on a non-exhaustive enum cannot fail.3166 {#link|@intToEnum#} on a non-exhaustive enum involves the safety semantics
3167 of {#link|@intCast#} to the integer tag type, but beyond that always results in
3168 a well-defined enum value.
3156 </p>3169 </p>
3157 <p>3170 <p>
3158 A switch on a non-exhaustive enum can include a '_' prong as an alternative to an {#syntax#}else{#endsyntax#} prong3171 A switch on a non-exhaustive enum can include a '_' prong as an alternative to an {#syntax#}else{#endsyntax#} prong
...@@ -6634,14 +6647,21 @@ test "global assembly" {...@@ -6634,14 +6647,21 @@ test "global assembly" {
6634 <p>6647 <p>
6635 When a function is called, a frame is pushed to the stack,6648 When a function is called, a frame is pushed to the stack,
6636 the function runs until it reaches a return statement, and then the frame is popped from the stack.6649 the function runs until it reaches a return statement, and then the frame is popped from the stack.
6637 At the callsite, the following code does not run until the function returns.6650 The code following the callsite does not run until the function returns.
6638 </p>6651 </p>
6639 <p>6652 <p>
6640 An async function is a function whose callsite is split into an {#syntax#}async{#endsyntax#} initiation,6653 An async function is a function whose execution is split into an {#syntax#}async{#endsyntax#} initiation,
6641 followed by an {#syntax#}await{#endsyntax#} completion. Its frame is6654 followed by an {#syntax#}await{#endsyntax#} completion. Its frame is
6642 provided explicitly by the caller, and it can be suspended and resumed any number of times.6655 provided explicitly by the caller, and it can be suspended and resumed any number of times.
6643 </p>6656 </p>
6644 <p>6657 <p>
6658 The code following the {#syntax#}async{#endsyntax#} callsite runs immediately after the async
6659 function first suspends. When the return value of the async function is needed,
6660 the calling code can {#syntax#}await{#endsyntax#} on the async function frame.
6661 This will suspend the calling code until the async function completes, at which point
6662 execution resumes just after the {#syntax#}await{#endsyntax#} callsite.
6663 </p>
6664 <p>
6645 Zig infers that a function is {#syntax#}async{#endsyntax#} when it observes that the function contains6665 Zig infers that a function is {#syntax#}async{#endsyntax#} when it observes that the function contains
6646 a <strong>suspension point</strong>. Async functions can be called the same as normal functions. A6666 a <strong>suspension point</strong>. Async functions can be called the same as normal functions. A
6647 function call of an async function is a suspend point.6667 function call of an async function is a suspend point.
...@@ -6744,7 +6764,14 @@ fn testResumeFromSuspend(my_result: *i32) void {...@@ -6744,7 +6764,14 @@ fn testResumeFromSuspend(my_result: *i32) void {
6744 {#header_open|Async and Await#}6764 {#header_open|Async and Await#}
6745 <p>6765 <p>
6746 In the same way that every {#syntax#}suspend{#endsyntax#} has a matching6766 In the same way that every {#syntax#}suspend{#endsyntax#} has a matching
6747 {#syntax#}resume{#endsyntax#}, every {#syntax#}async{#endsyntax#} has a matching {#syntax#}await{#endsyntax#}.6767 {#syntax#}resume{#endsyntax#}, every {#syntax#}async{#endsyntax#} has a matching {#syntax#}await{#endsyntax#}
6768 in standard code.
6769 </p>
6770 <p>
6771 However, it is possible to have an {#syntax#}async{#endsyntax#} call
6772 without a matching {#syntax#}await{#endsyntax#}. Upon completion of the async function,
6773 execution would continue at the most recent {#syntax#}async{#endsyntax#} callsite or {#syntax#}resume{#endsyntax#} callsite,
6774 and the return value of the async function would be lost.
6748 </p>6775 </p>
6749 {#code_begin|test#}6776 {#code_begin|test#}
6750const std = @import("std");6777const std = @import("std");
...@@ -6779,7 +6806,9 @@ fn func() void {...@@ -6779,7 +6806,9 @@ fn func() void {
6779 </p>6806 </p>
6780 <p>6807 <p>
6781 {#syntax#}await{#endsyntax#} is a suspend point, and takes as an operand anything that6808 {#syntax#}await{#endsyntax#} is a suspend point, and takes as an operand anything that
6782 coerces to {#syntax#}anyframe->T{#endsyntax#}.6809 coerces to {#syntax#}anyframe->T{#endsyntax#}. Calling {#syntax#}await{#endsyntax#} on
6810 the frame of an async function will cause execution to continue at the
6811 {#syntax#}await{#endsyntax#} callsite once the target function completes.
6783 </p>6812 </p>
6784 <p>6813 <p>
6785 There is a common misconception that {#syntax#}await{#endsyntax#} resumes the target function.6814 There is a common misconception that {#syntax#}await{#endsyntax#} resumes the target function.
...@@ -7945,7 +7974,7 @@ test "@hasDecl" {...@@ -7945,7 +7974,7 @@ test "@hasDecl" {
7945 {#header_close#}7974 {#header_close#}
79467975
7947 {#header_open|@intToEnum#}7976 {#header_open|@intToEnum#}
7948 <pre>{#syntax#}@intToEnum(comptime DestType: type, int_value: std.meta.Tag(DestType)) DestType{#endsyntax#}</pre>7977 <pre>{#syntax#}@intToEnum(comptime DestType: type, integer: anytype) DestType{#endsyntax#}</pre>
7949 <p>7978 <p>
7950 Converts an integer into an {#link|enum#} value.7979 Converts an integer into an {#link|enum#} value.
7951 </p>7980 </p>
...@@ -11535,11 +11564,7 @@ PrimaryTypeExpr...@@ -11535,11 +11564,7 @@ PrimaryTypeExpr
11535 / INTEGER11564 / INTEGER
11536 / KEYWORD_comptime TypeExpr11565 / KEYWORD_comptime TypeExpr
11537 / KEYWORD_error DOT IDENTIFIER11566 / KEYWORD_error DOT IDENTIFIER
11538 / KEYWORD_false
11539 / KEYWORD_null
11540 / KEYWORD_anyframe11567 / KEYWORD_anyframe
11541 / KEYWORD_true
11542 / KEYWORD_undefined
11543 / KEYWORD_unreachable11568 / KEYWORD_unreachable
11544 / STRINGLITERAL11569 / STRINGLITERAL
11545 / SwitchExpr11570 / SwitchExpr
...@@ -11908,7 +11933,6 @@ KEYWORD_errdefer &lt;- 'errdefer' end_of_word...@@ -11908,7 +11933,6 @@ KEYWORD_errdefer &lt;- 'errdefer' end_of_word
11908KEYWORD_error &lt;- 'error' end_of_word11933KEYWORD_error &lt;- 'error' end_of_word
11909KEYWORD_export &lt;- 'export' end_of_word11934KEYWORD_export &lt;- 'export' end_of_word
11910KEYWORD_extern &lt;- 'extern' end_of_word11935KEYWORD_extern &lt;- 'extern' end_of_word
11911KEYWORD_false &lt;- 'false' end_of_word
11912KEYWORD_fn &lt;- 'fn' end_of_word11936KEYWORD_fn &lt;- 'fn' end_of_word
11913KEYWORD_for &lt;- 'for' end_of_word11937KEYWORD_for &lt;- 'for' end_of_word
11914KEYWORD_if &lt;- 'if' end_of_word11938KEYWORD_if &lt;- 'if' end_of_word
...@@ -11916,7 +11940,6 @@ KEYWORD_inline &lt;- 'inline' end_of_word...@@ -11916,7 +11940,6 @@ KEYWORD_inline &lt;- 'inline' end_of_word
11916KEYWORD_noalias &lt;- 'noalias' end_of_word11940KEYWORD_noalias &lt;- 'noalias' end_of_word
11917KEYWORD_nosuspend &lt;- 'nosuspend' end_of_word11941KEYWORD_nosuspend &lt;- 'nosuspend' end_of_word
11918KEYWORD_noinline &lt;- 'noinline' end_of_word11942KEYWORD_noinline &lt;- 'noinline' end_of_word
11919KEYWORD_null &lt;- 'null' end_of_word
11920KEYWORD_opaque &lt;- 'opaque' end_of_word11943KEYWORD_opaque &lt;- 'opaque' end_of_word
11921KEYWORD_or &lt;- 'or' end_of_word11944KEYWORD_or &lt;- 'or' end_of_word
11922KEYWORD_orelse &lt;- 'orelse' end_of_word11945KEYWORD_orelse &lt;- 'orelse' end_of_word
...@@ -11930,9 +11953,7 @@ KEYWORD_suspend &lt;- 'suspend' end_of_word...@@ -11930,9 +11953,7 @@ KEYWORD_suspend &lt;- 'suspend' end_of_word
11930KEYWORD_switch &lt;- 'switch' end_of_word11953KEYWORD_switch &lt;- 'switch' end_of_word
11931KEYWORD_test &lt;- 'test' end_of_word11954KEYWORD_test &lt;- 'test' end_of_word
11932KEYWORD_threadlocal &lt;- 'threadlocal' end_of_word11955KEYWORD_threadlocal &lt;- 'threadlocal' end_of_word
11933KEYWORD_true &lt;- 'true' end_of_word
11934KEYWORD_try &lt;- 'try' end_of_word11956KEYWORD_try &lt;- 'try' end_of_word
11935KEYWORD_undefined &lt;- 'undefined' end_of_word
11936KEYWORD_union &lt;- 'union' end_of_word11957KEYWORD_union &lt;- 'union' end_of_word
11937KEYWORD_unreachable &lt;- 'unreachable' end_of_word11958KEYWORD_unreachable &lt;- 'unreachable' end_of_word
11938KEYWORD_usingnamespace &lt;- 'usingnamespace' end_of_word11959KEYWORD_usingnamespace &lt;- 'usingnamespace' end_of_word
...@@ -11945,13 +11966,13 @@ keyword &lt;- KEYWORD_align / KEYWORD_allowzero / KEYWORD_and / KEYWORD_anyframe...@@ -11945,13 +11966,13 @@ keyword &lt;- KEYWORD_align / KEYWORD_allowzero / KEYWORD_and / KEYWORD_anyframe
11945 / KEYWORD_break / KEYWORD_callconv / KEYWORD_catch / KEYWORD_comptime11966 / KEYWORD_break / KEYWORD_callconv / KEYWORD_catch / KEYWORD_comptime
11946 / KEYWORD_const / KEYWORD_continue / KEYWORD_defer / KEYWORD_else11967 / KEYWORD_const / KEYWORD_continue / KEYWORD_defer / KEYWORD_else
11947 / KEYWORD_enum / KEYWORD_errdefer / KEYWORD_error / KEYWORD_export11968 / KEYWORD_enum / KEYWORD_errdefer / KEYWORD_error / KEYWORD_export
11948 / KEYWORD_extern / KEYWORD_false / KEYWORD_fn / KEYWORD_for / KEYWORD_if11969 / KEYWORD_extern / KEYWORD_fn / KEYWORD_for / KEYWORD_if
11949 / KEYWORD_inline / KEYWORD_noalias / KEYWORD_nosuspend / KEYWORD_noinline11970 / KEYWORD_inline / KEYWORD_noalias / KEYWORD_nosuspend / KEYWORD_noinline
11950 / KEYWORD_null / KEYWORD_opaque / KEYWORD_or / KEYWORD_orelse / KEYWORD_packed11971 / KEYWORD_opaque / KEYWORD_or / KEYWORD_orelse / KEYWORD_packed
11951 / KEYWORD_pub / KEYWORD_resume / KEYWORD_return / KEYWORD_linksection11972 / KEYWORD_pub / KEYWORD_resume / KEYWORD_return / KEYWORD_linksection
11952 / KEYWORD_struct / KEYWORD_suspend / KEYWORD_switch11973 / KEYWORD_struct / KEYWORD_suspend / KEYWORD_switch
11953 / KEYWORD_test / KEYWORD_threadlocal / KEYWORD_true / KEYWORD_try11974 / KEYWORD_test / KEYWORD_threadlocal / KEYWORD_try
11954 / KEYWORD_undefined / KEYWORD_union / KEYWORD_unreachable11975 / KEYWORD_union / KEYWORD_unreachable
11955 / KEYWORD_usingnamespace / KEYWORD_var / KEYWORD_volatile / KEYWORD_while11976 / KEYWORD_usingnamespace / KEYWORD_var / KEYWORD_volatile / KEYWORD_while
11956</code></pre>11977</code></pre>
11957 {#header_close#}11978 {#header_close#}
lib/libc/mingw/lib-common/compstui.def created+12
...@@ -0,0 +1,12 @@
1;
2; Exports of file COMPSTUI.dll
3;
4; Autogenerated by gen_exportdef
5; Written by Kai Tietz, 2007
6;
7LIBRARY COMPSTUI.dll
8EXPORTS
9CommonPropertySheetUIA
10CommonPropertySheetUIW
11GetCPSUIUserData
12SetCPSUIUserData
lib/libcxx/include/__config+7-6
...@@ -125,7 +125,7 @@...@@ -125,7 +125,7 @@
125# endif125# endif
126// Feature macros for disabling pre ABI v1 features. All of these options126// Feature macros for disabling pre ABI v1 features. All of these options
127// are deprecated.127// are deprecated.
128# if defined(__FreeBSD__)128# if defined(__FreeBSD__) || defined(__DragonFly__)
129# define _LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR129# define _LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR
130# endif130# endif
131#endif131#endif
...@@ -380,7 +380,7 @@...@@ -380,7 +380,7 @@
380# if __ANDROID_API__ >= 29380# if __ANDROID_API__ >= 29
381# define _LIBCPP_HAS_TIMESPEC_GET381# define _LIBCPP_HAS_TIMESPEC_GET
382# endif382# endif
383# elif defined(__Fuchsia__) || defined(__wasi__) || defined(__NetBSD__)383# elif defined(__Fuchsia__) || defined(__wasi__) || defined(__NetBSD__) || defined(__DragonFly__)
384# define _LIBCPP_HAS_ALIGNED_ALLOC384# define _LIBCPP_HAS_ALIGNED_ALLOC
385# define _LIBCPP_HAS_QUICK_EXIT385# define _LIBCPP_HAS_QUICK_EXIT
386# define _LIBCPP_HAS_TIMESPEC_GET386# define _LIBCPP_HAS_TIMESPEC_GET
...@@ -938,11 +938,11 @@ typedef unsigned int char32_t;...@@ -938,11 +938,11 @@ typedef unsigned int char32_t;
938#endif938#endif
939939
940#if defined(__APPLE__) || defined(__FreeBSD__) || defined(_LIBCPP_MSVCRT_LIKE) || \940#if defined(__APPLE__) || defined(__FreeBSD__) || defined(_LIBCPP_MSVCRT_LIKE) || \
941 defined(__sun__) || defined(__NetBSD__) || defined(__CloudABI__)941 defined(__sun__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__CloudABI__)
942#define _LIBCPP_LOCALE__L_EXTENSIONS 1942#define _LIBCPP_LOCALE__L_EXTENSIONS 1
943#endif943#endif
944944
945#ifdef __FreeBSD__945#if defined(__FreeBSD__) || defined(__DragonFly__)
946#define _DECLARE_C99_LDBL_MATH 1946#define _DECLARE_C99_LDBL_MATH 1
947#endif947#endif
948948
...@@ -970,11 +970,11 @@ typedef unsigned int char32_t;...@@ -970,11 +970,11 @@ typedef unsigned int char32_t;
970# define _LIBCPP_HAS_NO_ALIGNED_ALLOCATION970# define _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
971#endif971#endif
972972
973#if defined(__APPLE__) || defined(__FreeBSD__)973#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__)
974#define _LIBCPP_HAS_DEFAULTRUNELOCALE974#define _LIBCPP_HAS_DEFAULTRUNELOCALE
975#endif975#endif
976976
977#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__sun__)977#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__) || defined(__sun__)
978#define _LIBCPP_WCTYPE_IS_MASK978#define _LIBCPP_WCTYPE_IS_MASK
979#endif979#endif
980980
...@@ -1138,6 +1138,7 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(...@@ -1138,6 +1138,7 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
1138 defined(__wasi__) || \1138 defined(__wasi__) || \
1139 defined(__NetBSD__) || \1139 defined(__NetBSD__) || \
1140 defined(__OpenBSD__) || \1140 defined(__OpenBSD__) || \
1141 defined(__DragonFly__) || \
1141 defined(__NuttX__) || \1142 defined(__NuttX__) || \
1142 defined(__linux__) || \1143 defined(__linux__) || \
1143 defined(__GNU__) || \1144 defined(__GNU__) || \
lib/libcxx/include/__locale+3-3
...@@ -35,7 +35,7 @@...@@ -35,7 +35,7 @@
35# include <__support/newlib/xlocale.h>35# include <__support/newlib/xlocale.h>
36#elif defined(__OpenBSD__)36#elif defined(__OpenBSD__)
37# include <__support/openbsd/xlocale.h>37# include <__support/openbsd/xlocale.h>
38#elif (defined(__APPLE__) || defined(__FreeBSD__) \38#elif (defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__) \
39 || defined(__EMSCRIPTEN__) || defined(__IBMCPP__))39 || defined(__EMSCRIPTEN__) || defined(__IBMCPP__))
40# include <xlocale.h>40# include <xlocale.h>
41#elif defined(__Fuchsia__)41#elif defined(__Fuchsia__)
...@@ -450,10 +450,10 @@ public:...@@ -450,10 +450,10 @@ public:
450 static const mask blank = _BLANK;450 static const mask blank = _BLANK;
451 static const mask __regex_word = 0x80;451 static const mask __regex_word = 0x80;
452# define _LIBCPP_CTYPE_MASK_IS_COMPOSITE_PRINT452# define _LIBCPP_CTYPE_MASK_IS_COMPOSITE_PRINT
453#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__EMSCRIPTEN__) || defined(__NetBSD__)453#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__EMSCRIPTEN__) || defined(__NetBSD__) || defined(__DragonFly__)
454# ifdef __APPLE__454# ifdef __APPLE__
455 typedef __uint32_t mask;455 typedef __uint32_t mask;
456# elif defined(__FreeBSD__)456# elif defined(__FreeBSD__) || defined(__DragonFly__)
457 typedef unsigned long mask;457 typedef unsigned long mask;
458# elif defined(__EMSCRIPTEN__) || defined(__NetBSD__)458# elif defined(__EMSCRIPTEN__) || defined(__NetBSD__)
459 typedef unsigned short mask;459 typedef unsigned short mask;
lib/libcxx/include/locale+1-1
...@@ -228,7 +228,7 @@ _LIBCPP_PUSH_MACROS...@@ -228,7 +228,7 @@ _LIBCPP_PUSH_MACROS
228228
229_LIBCPP_BEGIN_NAMESPACE_STD229_LIBCPP_BEGIN_NAMESPACE_STD
230230
231#if defined(__APPLE__) || defined(__FreeBSD__)231#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__)
232# define _LIBCPP_GET_C_LOCALE 0232# define _LIBCPP_GET_C_LOCALE 0
233#elif defined(__CloudABI__) || defined(__NetBSD__)233#elif defined(__CloudABI__) || defined(__NetBSD__)
234# define _LIBCPP_GET_C_LOCALE LC_C_LOCALE234# define _LIBCPP_GET_C_LOCALE LC_C_LOCALE
lib/libcxx/src/locale.cpp+1-1
...@@ -1133,7 +1133,7 @@ ctype<char>::classic_table() noexcept...@@ -1133,7 +1133,7 @@ ctype<char>::classic_table() noexcept
1133const ctype<char>::mask*1133const ctype<char>::mask*
1134ctype<char>::classic_table() noexcept1134ctype<char>::classic_table() noexcept
1135{1135{
1136#if defined(__APPLE__) || defined(__FreeBSD__)1136#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__)
1137 return _DefaultRuneLocale.__runetype;1137 return _DefaultRuneLocale.__runetype;
1138#elif defined(__NetBSD__)1138#elif defined(__NetBSD__)
1139 return _C_ctype_tab_ + 1;1139 return _C_ctype_tab_ + 1;
lib/std/Progress.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! This API non-allocating, non-fallible, and thread-safe.1//! This API non-allocating, non-fallible, and thread-safe.
8//! The tradeoff is that users of this API must provide the storage2//! The tradeoff is that users of this API must provide the storage
9//! for each `Progress.Node`.3//! for each `Progress.Node`.
lib/std/SemanticVersion.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2020 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! A software version formatted according to the Semantic Version 2 specification.1//! A software version formatted according to the Semantic Version 2 specification.
8//!2//!
9//! See: https://semver.org3//! See: https://semver.org
lib/std/Thread.zig+87-87
...@@ -1,17 +1,12 @@...@@ -1,17 +1,12 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! This struct represents a kernel thread, and acts as a namespace for concurrency1//! This struct represents a kernel thread, and acts as a namespace for concurrency
8//! primitives that operate on kernel threads. For concurrency primitives that support2//! primitives that operate on kernel threads. For concurrency primitives that support
9//! both evented I/O and async I/O, see the respective names in the top level std namespace.3//! both evented I/O and async I/O, see the respective names in the top level std namespace.
104
11const std = @import("std.zig");5const std = @import("std.zig");
6const builtin = @import("builtin");
12const os = std.os;7const os = std.os;
13const assert = std.debug.assert;8const assert = std.debug.assert;
14const target = std.Target.current;9const target = builtin.target;
15const Atomic = std.atomic.Atomic;10const Atomic = std.atomic.Atomic;
1611
17pub const AutoResetEvent = @import("Thread/AutoResetEvent.zig");12pub const AutoResetEvent = @import("Thread/AutoResetEvent.zig");
...@@ -24,7 +19,8 @@ pub const Condition = @import("Thread/Condition.zig");...@@ -24,7 +19,8 @@ pub const Condition = @import("Thread/Condition.zig");
2419
25pub const spinLoopHint = @compileError("deprecated: use std.atomic.spinLoopHint");20pub const spinLoopHint = @compileError("deprecated: use std.atomic.spinLoopHint");
2621
27pub const use_pthreads = target.os.tag != .windows and std.Target.current.os.tag != .wasi and std.builtin.link_libc;22pub const use_pthreads = target.os.tag != .windows and target.os.tag != .wasi and builtin.link_libc;
23const is_gnu = target.abi.isGnu();
2824
29const Thread = @This();25const Thread = @This();
30const Impl = if (target.os.tag == .windows)26const Impl = if (target.os.tag == .windows)
...@@ -38,7 +34,7 @@ else...@@ -38,7 +34,7 @@ else
3834
39impl: Impl,35impl: Impl,
4036
41pub const max_name_len = switch (std.Target.current.os.tag) {37pub const max_name_len = switch (target.os.tag) {
42 .linux => 15,38 .linux => 15,
43 .windows => 31,39 .windows => 31,
44 .macos, .ios, .watchos, .tvos => 63,40 .macos, .ios, .watchos, .tvos => 63,
...@@ -64,20 +60,21 @@ pub fn setName(self: Thread, name: []const u8) SetNameError!void {...@@ -64,20 +60,21 @@ pub fn setName(self: Thread, name: []const u8) SetNameError!void {
64 break :blk name_buf[0..name.len :0];60 break :blk name_buf[0..name.len :0];
65 };61 };
6662
67 switch (std.Target.current.os.tag) {63 switch (target.os.tag) {
68 .linux => if (use_pthreads) {64 .linux => if (use_pthreads) {
69 const err = std.c.pthread_setname_np(self.getHandle(), name_with_terminator.ptr);65 const err = std.c.pthread_setname_np(self.getHandle(), name_with_terminator.ptr);
70 return switch (err) {66 switch (err) {
71 0 => {},67 .SUCCESS => return,
72 os.ERANGE => unreachable,68 .RANGE => unreachable,
73 else => return os.unexpectedErrno(err),69 else => |e| return os.unexpectedErrno(e),
74 };70 }
75 } else if (use_pthreads and self.getHandle() == std.c.pthread_self()) {71 } else if (use_pthreads and self.getHandle() == std.c.pthread_self()) {
72 // TODO: this is dead code. what did the author of this code intend to happen here?
76 const err = try os.prctl(.SET_NAME, .{@ptrToInt(name_with_terminator.ptr)});73 const err = try os.prctl(.SET_NAME, .{@ptrToInt(name_with_terminator.ptr)});
77 return switch (err) {74 switch (@intToEnum(os.E, err)) {
78 0 => {},75 .SUCCESS => return,
79 else => return os.unexpectedErrno(err),76 else => |e| return os.unexpectedErrno(e),
80 };77 }
81 } else {78 } else {
82 var buf: [32]u8 = undefined;79 var buf: [32]u8 = undefined;
83 const path = try std.fmt.bufPrint(&buf, "/proc/self/task/{d}/comm", .{self.getHandle()});80 const path = try std.fmt.bufPrint(&buf, "/proc/self/task/{d}/comm", .{self.getHandle()});
...@@ -87,7 +84,7 @@ pub fn setName(self: Thread, name: []const u8) SetNameError!void {...@@ -87,7 +84,7 @@ pub fn setName(self: Thread, name: []const u8) SetNameError!void {
8784
88 try file.writer().writeAll(name);85 try file.writer().writeAll(name);
89 },86 },
90 .windows => if (std.Target.current.os.isAtLeast(.windows, .win10_rs1)) |res| {87 .windows => if (target.os.isAtLeast(.windows, .win10_rs1)) |res| {
91 // SetThreadDescription is only available since version 1607, which is 10.0.14393.79588 // SetThreadDescription is only available since version 1607, which is 10.0.14393.795
92 // See https://en.wikipedia.org/wiki/Microsoft_Windows_SDK89 // See https://en.wikipedia.org/wiki/Microsoft_Windows_SDK
93 if (!res) {90 if (!res) {
...@@ -110,24 +107,25 @@ pub fn setName(self: Thread, name: []const u8) SetNameError!void {...@@ -110,24 +107,25 @@ pub fn setName(self: Thread, name: []const u8) SetNameError!void {
110 if (self.getHandle() != std.c.pthread_self()) return error.Unsupported;107 if (self.getHandle() != std.c.pthread_self()) return error.Unsupported;
111108
112 const err = std.c.pthread_setname_np(name_with_terminator.ptr);109 const err = std.c.pthread_setname_np(name_with_terminator.ptr);
113 return switch (err) {110 switch (err) {
114 0 => {},111 .SUCCESS => return,
115 else => return os.unexpectedErrno(err),112 else => |e| return os.unexpectedErrno(e),
116 };113 }
117 },114 },
118 .netbsd => if (use_pthreads) {115 .netbsd => if (use_pthreads) {
119 const err = std.c.pthread_setname_np(self.getHandle(), name_with_terminator.ptr, null);116 const err = std.c.pthread_setname_np(self.getHandle(), name_with_terminator.ptr, null);
120 return switch (err) {117 switch (err) {
121 0 => {},118 .SUCCESS => return,
122 os.EINVAL => unreachable,119 .INVAL => unreachable,
123 os.ESRCH => unreachable,120 .SRCH => unreachable,
124 os.ENOMEM => unreachable,121 .NOMEM => unreachable,
125 else => return os.unexpectedErrno(err),122 else => |e| return os.unexpectedErrno(e),
126 };123 }
127 },124 },
128 .freebsd, .openbsd => if (use_pthreads) {125 .freebsd, .openbsd => if (use_pthreads) {
129 // Use pthread_set_name_np for FreeBSD because pthread_setname_np is FreeBSD 12.2+ only.126 // Use pthread_set_name_np for FreeBSD because pthread_setname_np is FreeBSD 12.2+ only.
130 // TODO maybe revisit this if depending on FreeBSD 12.2+ is acceptable because pthread_setname_np can return an error.127 // TODO maybe revisit this if depending on FreeBSD 12.2+ is acceptable because
128 // pthread_setname_np can return an error.
131129
132 std.c.pthread_set_name_np(self.getHandle(), name_with_terminator.ptr);130 std.c.pthread_set_name_np(self.getHandle(), name_with_terminator.ptr);
133 },131 },
...@@ -151,20 +149,20 @@ pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]co...@@ -151,20 +149,20 @@ pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]co
151 buffer_ptr[max_name_len] = 0;149 buffer_ptr[max_name_len] = 0;
152 var buffer = std.mem.span(buffer_ptr);150 var buffer = std.mem.span(buffer_ptr);
153151
154 switch (std.Target.current.os.tag) {152 switch (target.os.tag) {
155 .linux => if (use_pthreads and comptime std.Target.current.abi.isGnu()) {153 .linux => if (use_pthreads and is_gnu) {
156 const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);154 const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);
157 return switch (err) {155 switch (err) {
158 0 => std.mem.sliceTo(buffer, 0),156 .SUCCESS => return std.mem.sliceTo(buffer, 0),
159 os.ERANGE => unreachable,157 .RANGE => unreachable,
160 else => return os.unexpectedErrno(err),158 else => |e| return os.unexpectedErrno(e),
161 };159 }
162 } else if (use_pthreads and self.getHandle() == std.c.pthread_self()) {160 } else if (use_pthreads and self.getHandle() == std.c.pthread_self()) {
163 const err = try os.prctl(.GET_NAME, .{@ptrToInt(buffer.ptr)});161 const err = try os.prctl(.GET_NAME, .{@ptrToInt(buffer.ptr)});
164 return switch (err) {162 switch (@intToEnum(os.E, err)) {
165 0 => std.mem.sliceTo(buffer, 0),163 .SUCCESS => return std.mem.sliceTo(buffer, 0),
166 else => return os.unexpectedErrno(err),164 else => |e| return os.unexpectedErrno(e),
167 };165 }
168 } else if (!use_pthreads) {166 } else if (!use_pthreads) {
169 var buf: [32]u8 = undefined;167 var buf: [32]u8 = undefined;
170 const path = try std.fmt.bufPrint(&buf, "/proc/self/task/{d}/comm", .{self.getHandle()});168 const path = try std.fmt.bufPrint(&buf, "/proc/self/task/{d}/comm", .{self.getHandle()});
...@@ -179,7 +177,7 @@ pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]co...@@ -179,7 +177,7 @@ pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]co
179 // musl doesn't provide pthread_getname_np and there's no way to retrieve the thread id of an arbitrary thread.177 // musl doesn't provide pthread_getname_np and there's no way to retrieve the thread id of an arbitrary thread.
180 return error.Unsupported;178 return error.Unsupported;
181 },179 },
182 .windows => if (std.Target.current.os.isAtLeast(.windows, .win10_rs1)) |res| {180 .windows => if (target.os.isAtLeast(.windows, .win10_rs1)) |res| {
183 // GetThreadDescription is only available since version 1607, which is 10.0.14393.795181 // GetThreadDescription is only available since version 1607, which is 10.0.14393.795
184 // See https://en.wikipedia.org/wiki/Microsoft_Windows_SDK182 // See https://en.wikipedia.org/wiki/Microsoft_Windows_SDK
185 if (!res) {183 if (!res) {
...@@ -198,20 +196,20 @@ pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]co...@@ -198,20 +196,20 @@ pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]co
198 },196 },
199 .macos, .ios, .watchos, .tvos => if (use_pthreads) {197 .macos, .ios, .watchos, .tvos => if (use_pthreads) {
200 const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);198 const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);
201 return switch (err) {199 switch (err) {
202 0 => std.mem.sliceTo(buffer, 0),200 .SUCCESS => return std.mem.sliceTo(buffer, 0),
203 os.ESRCH => unreachable,201 .SRCH => unreachable,
204 else => return os.unexpectedErrno(err),202 else => |e| return os.unexpectedErrno(e),
205 };203 }
206 },204 },
207 .netbsd => if (use_pthreads) {205 .netbsd => if (use_pthreads) {
208 const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);206 const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);
209 return switch (err) {207 switch (err) {
210 0 => std.mem.sliceTo(buffer, 0),208 .SUCCESS => return std.mem.sliceTo(buffer, 0),
211 os.EINVAL => unreachable,209 .INVAL => unreachable,
212 os.ESRCH => unreachable,210 .SRCH => unreachable,
213 else => return os.unexpectedErrno(err),211 else => |e| return os.unexpectedErrno(e),
214 };212 }
215 },213 },
216 .freebsd, .openbsd => if (use_pthreads) {214 .freebsd, .openbsd => if (use_pthreads) {
217 // Use pthread_get_name_np for FreeBSD because pthread_getname_np is FreeBSD 12.2+ only.215 // Use pthread_get_name_np for FreeBSD because pthread_getname_np is FreeBSD 12.2+ only.
...@@ -288,7 +286,7 @@ pub const SpawnError = error{...@@ -288,7 +286,7 @@ pub const SpawnError = error{
288/// The caller must eventually either call `join()` to wait for the thread to finish and free its resources286/// The caller must eventually either call `join()` to wait for the thread to finish and free its resources
289/// or call `detach()` to excuse the caller from calling `join()` and have the thread clean up its resources on completion`.287/// or call `detach()` to excuse the caller from calling `join()` and have the thread clean up its resources on completion`.
290pub fn spawn(config: SpawnConfig, comptime function: anytype, args: anytype) SpawnError!Thread {288pub fn spawn(config: SpawnConfig, comptime function: anytype, args: anytype) SpawnError!Thread {
291 if (std.builtin.single_threaded) {289 if (builtin.single_threaded) {
292 @compileError("Cannot spawn thread when building in single-threaded mode");290 @compileError("Cannot spawn thread when building in single-threaded mode");
293 }291 }
294292
...@@ -611,13 +609,13 @@ const PosixThreadImpl = struct {...@@ -611,13 +609,13 @@ const PosixThreadImpl = struct {
611 errdefer allocator.destroy(args_ptr);609 errdefer allocator.destroy(args_ptr);
612610
613 var attr: c.pthread_attr_t = undefined;611 var attr: c.pthread_attr_t = undefined;
614 if (c.pthread_attr_init(&attr) != 0) return error.SystemResources;612 if (c.pthread_attr_init(&attr) != .SUCCESS) return error.SystemResources;
615 defer assert(c.pthread_attr_destroy(&attr) == 0);613 defer assert(c.pthread_attr_destroy(&attr) == .SUCCESS);
616614
617 // Use the same set of parameters used by the libc-less impl.615 // Use the same set of parameters used by the libc-less impl.
618 const stack_size = std.math.max(config.stack_size, 16 * 1024);616 const stack_size = std.math.max(config.stack_size, 16 * 1024);
619 assert(c.pthread_attr_setstacksize(&attr, stack_size) == 0);617 assert(c.pthread_attr_setstacksize(&attr, stack_size) == .SUCCESS);
620 assert(c.pthread_attr_setguardsize(&attr, std.mem.page_size) == 0);618 assert(c.pthread_attr_setguardsize(&attr, std.mem.page_size) == .SUCCESS);
621619
622 var handle: c.pthread_t = undefined;620 var handle: c.pthread_t = undefined;
623 switch (c.pthread_create(621 switch (c.pthread_create(
...@@ -626,10 +624,10 @@ const PosixThreadImpl = struct {...@@ -626,10 +624,10 @@ const PosixThreadImpl = struct {
626 Instance.entryFn,624 Instance.entryFn,
627 if (@sizeOf(Args) > 1) @ptrCast(*c_void, args_ptr) else undefined,625 if (@sizeOf(Args) > 1) @ptrCast(*c_void, args_ptr) else undefined,
628 )) {626 )) {
629 0 => return Impl{ .handle = handle },627 .SUCCESS => return Impl{ .handle = handle },
630 os.EAGAIN => return error.SystemResources,628 .AGAIN => return error.SystemResources,
631 os.EPERM => unreachable,629 .PERM => unreachable,
632 os.EINVAL => unreachable,630 .INVAL => unreachable,
633 else => |err| return os.unexpectedErrno(err),631 else => |err| return os.unexpectedErrno(err),
634 }632 }
635 }633 }
...@@ -640,19 +638,19 @@ const PosixThreadImpl = struct {...@@ -640,19 +638,19 @@ const PosixThreadImpl = struct {
640638
641 fn detach(self: Impl) void {639 fn detach(self: Impl) void {
642 switch (c.pthread_detach(self.handle)) {640 switch (c.pthread_detach(self.handle)) {
643 0 => {},641 .SUCCESS => {},
644 os.EINVAL => unreachable, // thread handle is not joinable642 .INVAL => unreachable, // thread handle is not joinable
645 os.ESRCH => unreachable, // thread handle is invalid643 .SRCH => unreachable, // thread handle is invalid
646 else => unreachable,644 else => unreachable,
647 }645 }
648 }646 }
649647
650 fn join(self: Impl) void {648 fn join(self: Impl) void {
651 switch (c.pthread_join(self.handle, null)) {649 switch (c.pthread_join(self.handle, null)) {
652 0 => {},650 .SUCCESS => {},
653 os.EINVAL => unreachable, // thread handle is not joinable (or another thread is already joining in)651 .INVAL => unreachable, // thread handle is not joinable (or another thread is already joining in)
654 os.ESRCH => unreachable, // thread handle is invalid652 .SRCH => unreachable, // thread handle is invalid
655 os.EDEADLK => unreachable, // two threads tried to join each other653 .DEADLK => unreachable, // two threads tried to join each other
656 else => unreachable,654 else => unreachable,
657 }655 }
658 }656 }
...@@ -806,8 +804,10 @@ const LinuxThreadImpl = struct {...@@ -806,8 +804,10 @@ const LinuxThreadImpl = struct {
806 \\ 1:804 \\ 1:
807 \\ cmp %%sp, 0805 \\ cmp %%sp, 0
808 \\ beq 2f806 \\ beq 2f
807 \\ nop
809 \\ restore808 \\ restore
810 \\ ba 1f809 \\ ba 1f
810 \\ nop
811 \\ 2:811 \\ 2:
812 \\ mov 73, %%g1812 \\ mov 73, %%g1
813 \\ mov %[ptr], %%o0813 \\ mov %[ptr], %%o0
...@@ -937,13 +937,13 @@ const LinuxThreadImpl = struct {...@@ -937,13 +937,13 @@ const LinuxThreadImpl = struct {
937 tls_ptr,937 tls_ptr,
938 &instance.thread.child_tid.value,938 &instance.thread.child_tid.value,
939 ))) {939 ))) {
940 0 => return Impl{ .thread = &instance.thread },940 .SUCCESS => return Impl{ .thread = &instance.thread },
941 os.EAGAIN => return error.ThreadQuotaExceeded,941 .AGAIN => return error.ThreadQuotaExceeded,
942 os.EINVAL => unreachable,942 .INVAL => unreachable,
943 os.ENOMEM => return error.SystemResources,943 .NOMEM => return error.SystemResources,
944 os.ENOSPC => unreachable,944 .NOSPC => unreachable,
945 os.EPERM => unreachable,945 .PERM => unreachable,
946 os.EUSERS => unreachable,946 .USERS => unreachable,
947 else => |err| return os.unexpectedErrno(err),947 else => |err| return os.unexpectedErrno(err),
948 }948 }
949 }949 }
...@@ -982,9 +982,9 @@ const LinuxThreadImpl = struct {...@@ -982,9 +982,9 @@ const LinuxThreadImpl = struct {
982 tid,982 tid,
983 null,983 null,
984 ))) {984 ))) {
985 0 => continue,985 .SUCCESS => continue,
986 os.EINTR => continue,986 .INTR => continue,
987 os.EAGAIN => continue,987 .AGAIN => continue,
988 else => unreachable,988 else => unreachable,
989 }989 }
990 }990 }
...@@ -1011,7 +1011,7 @@ fn testThreadName(thread: *Thread) !void {...@@ -1011,7 +1011,7 @@ fn testThreadName(thread: *Thread) !void {
1011}1011}
10121012
1013test "setName, getName" {1013test "setName, getName" {
1014 if (std.builtin.single_threaded) return error.SkipZigTest;1014 if (builtin.single_threaded) return error.SkipZigTest;
10151015
1016 const Context = struct {1016 const Context = struct {
1017 start_wait_event: ResetEvent = undefined,1017 start_wait_event: ResetEvent = undefined,
...@@ -1029,7 +1029,7 @@ test "setName, getName" {...@@ -1029,7 +1029,7 @@ test "setName, getName" {
1029 // Wait for the main thread to have set the thread field in the context.1029 // Wait for the main thread to have set the thread field in the context.
1030 ctx.start_wait_event.wait();1030 ctx.start_wait_event.wait();
10311031
1032 switch (std.Target.current.os.tag) {1032 switch (target.os.tag) {
1033 .windows => testThreadName(&ctx.thread) catch |err| switch (err) {1033 .windows => testThreadName(&ctx.thread) catch |err| switch (err) {
1034 error.Unsupported => return error.SkipZigTest,1034 error.Unsupported => return error.SkipZigTest,
1035 else => return err,1035 else => return err,
...@@ -1054,7 +1054,7 @@ test "setName, getName" {...@@ -1054,7 +1054,7 @@ test "setName, getName" {
1054 context.start_wait_event.set();1054 context.start_wait_event.set();
1055 context.test_done_event.wait();1055 context.test_done_event.wait();
10561056
1057 switch (std.Target.current.os.tag) {1057 switch (target.os.tag) {
1058 .macos, .ios, .watchos, .tvos => {1058 .macos, .ios, .watchos, .tvos => {
1059 const res = thread.setName("foobar");1059 const res = thread.setName("foobar");
1060 try std.testing.expectError(error.Unsupported, res);1060 try std.testing.expectError(error.Unsupported, res);
...@@ -1063,7 +1063,7 @@ test "setName, getName" {...@@ -1063,7 +1063,7 @@ test "setName, getName" {
1063 error.Unsupported => return error.SkipZigTest,1063 error.Unsupported => return error.SkipZigTest,
1064 else => return err,1064 else => return err,
1065 },1065 },
1066 else => |tag| if (tag == .linux and use_pthreads and comptime std.Target.current.abi.isMusl()) {1066 else => |tag| if (tag == .linux and use_pthreads and comptime target.abi.isMusl()) {
1067 try thread.setName("foobar");1067 try thread.setName("foobar");
10681068
1069 var name_buffer: [max_name_len:0]u8 = undefined;1069 var name_buffer: [max_name_len:0]u8 = undefined;
...@@ -1096,7 +1096,7 @@ fn testIncrementNotify(value: *usize, event: *ResetEvent) void {...@@ -1096,7 +1096,7 @@ fn testIncrementNotify(value: *usize, event: *ResetEvent) void {
1096}1096}
10971097
1098test "Thread.join" {1098test "Thread.join" {
1099 if (std.builtin.single_threaded) return error.SkipZigTest;1099 if (builtin.single_threaded) return error.SkipZigTest;
11001100
1101 var value: usize = 0;1101 var value: usize = 0;
1102 var event: ResetEvent = undefined;1102 var event: ResetEvent = undefined;
...@@ -1110,7 +1110,7 @@ test "Thread.join" {...@@ -1110,7 +1110,7 @@ test "Thread.join" {
1110}1110}
11111111
1112test "Thread.detach" {1112test "Thread.detach" {
1113 if (std.builtin.single_threaded) return error.SkipZigTest;1113 if (builtin.single_threaded) return error.SkipZigTest;
11141114
1115 var value: usize = 0;1115 var value: usize = 0;
1116 var event: ResetEvent = undefined;1116 var event: ResetEvent = undefined;
lib/std/Thread/AutoResetEvent.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! Similar to `StaticResetEvent` but on `set()` it also (atomically) does `reset()`.1//! Similar to `StaticResetEvent` but on `set()` it also (atomically) does `reset()`.
8//! Unlike StaticResetEvent, `wait()` can only be called by one thread (MPSC-like).2//! Unlike StaticResetEvent, `wait()` can only be called by one thread (MPSC-like).
9//!3//!
lib/std/Thread/Condition.zig+8-14
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! A condition provides a way for a kernel thread to block until it is signaled1//! A condition provides a way for a kernel thread to block until it is signaled
8//! to wake up. Spurious wakeups are possible.2//! to wake up. Spurious wakeups are possible.
9//! This API supports static initialization and does not require deinitialization.3//! This API supports static initialization and does not require deinitialization.
...@@ -81,17 +75,17 @@ pub const PthreadCondition = struct {...@@ -81,17 +75,17 @@ pub const PthreadCondition = struct {
8175
82 pub fn wait(cond: *PthreadCondition, mutex: *Mutex) void {76 pub fn wait(cond: *PthreadCondition, mutex: *Mutex) void {
83 const rc = std.c.pthread_cond_wait(&cond.cond, &mutex.impl.pthread_mutex);77 const rc = std.c.pthread_cond_wait(&cond.cond, &mutex.impl.pthread_mutex);
84 assert(rc == 0);78 assert(rc == .SUCCESS);
85 }79 }
8680
87 pub fn signal(cond: *PthreadCondition) void {81 pub fn signal(cond: *PthreadCondition) void {
88 const rc = std.c.pthread_cond_signal(&cond.cond);82 const rc = std.c.pthread_cond_signal(&cond.cond);
89 assert(rc == 0);83 assert(rc == .SUCCESS);
90 }84 }
9185
92 pub fn broadcast(cond: *PthreadCondition) void {86 pub fn broadcast(cond: *PthreadCondition) void {
93 const rc = std.c.pthread_cond_broadcast(&cond.cond);87 const rc = std.c.pthread_cond_broadcast(&cond.cond);
94 assert(rc == 0);88 assert(rc == .SUCCESS);
95 }89 }
96};90};
9791
...@@ -115,9 +109,9 @@ pub const AtomicCondition = struct {...@@ -115,9 +109,9 @@ pub const AtomicCondition = struct {
115 0,109 0,
116 null,110 null,
117 ))) {111 ))) {
118 0 => {},112 .SUCCESS => {},
119 std.os.EINTR => {},113 .INTR => {},
120 std.os.EAGAIN => {},114 .AGAIN => {},
121 else => unreachable,115 else => unreachable,
122 }116 }
123 },117 },
...@@ -136,8 +130,8 @@ pub const AtomicCondition = struct {...@@ -136,8 +130,8 @@ pub const AtomicCondition = struct {
136 linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,130 linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,
137 1,131 1,
138 ))) {132 ))) {
139 0 => {},133 .SUCCESS => {},
140 std.os.EFAULT => {},134 .FAULT => {},
141 else => unreachable,135 else => unreachable,
142 }136 }
143 },137 },
lib/std/Thread/Futex.zig+39-45
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! Futex is a mechanism used to block (`wait`) and unblock (`wake`) threads using a 32bit memory address as hints.1//! Futex is a mechanism used to block (`wait`) and unblock (`wake`) threads using a 32bit memory address as hints.
8//! Blocking a thread is acknowledged only if the 32bit memory address is equal to a given value.2//! Blocking a thread is acknowledged only if the 32bit memory address is equal to a given value.
9//! This check helps avoid block/unblock deadlocks which occur if a `wake()` happens before a `wait()`.3//! This check helps avoid block/unblock deadlocks which occur if a `wake()` happens before a `wait()`.
...@@ -152,12 +146,12 @@ const LinuxFutex = struct {...@@ -152,12 +146,12 @@ const LinuxFutex = struct {
152 @bitCast(i32, expect),146 @bitCast(i32, expect),
153 ts_ptr,147 ts_ptr,
154 ))) {148 ))) {
155 0 => {}, // notified by `wake()`149 .SUCCESS => {}, // notified by `wake()`
156 std.os.EINTR => {}, // spurious wakeup150 .INTR => {}, // spurious wakeup
157 std.os.EAGAIN => {}, // ptr.* != expect151 .AGAIN => {}, // ptr.* != expect
158 std.os.ETIMEDOUT => return error.TimedOut,152 .TIMEDOUT => return error.TimedOut,
159 std.os.EINVAL => {}, // possibly timeout overflow153 .INVAL => {}, // possibly timeout overflow
160 std.os.EFAULT => unreachable,154 .FAULT => unreachable,
161 else => unreachable,155 else => unreachable,
162 }156 }
163 }157 }
...@@ -168,9 +162,9 @@ const LinuxFutex = struct {...@@ -168,9 +162,9 @@ const LinuxFutex = struct {
168 linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,162 linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,
169 std.math.cast(i32, num_waiters) catch std.math.maxInt(i32),163 std.math.cast(i32, num_waiters) catch std.math.maxInt(i32),
170 ))) {164 ))) {
171 0 => {}, // successful wake up165 .SUCCESS => {}, // successful wake up
172 std.os.EINVAL => {}, // invalid futex_wait() on ptr done elsewhere166 .INVAL => {}, // invalid futex_wait() on ptr done elsewhere
173 std.os.EFAULT => {}, // pointer became invalid while doing the wake167 .FAULT => {}, // pointer became invalid while doing the wake
174 else => unreachable,168 else => unreachable,
175 }169 }
176 }170 }
...@@ -215,13 +209,13 @@ const DarwinFutex = struct {...@@ -215,13 +209,13 @@ const DarwinFutex = struct {
215 };209 };
216210
217 if (status >= 0) return;211 if (status >= 0) return;
218 switch (-status) {212 switch (@intToEnum(std.os.E, -status)) {
219 darwin.EINTR => {},213 .INTR => {},
220 // Address of the futex is paged out. This is unlikely, but possible in theory, and214 // Address of the futex is paged out. This is unlikely, but possible in theory, and
221 // pthread/libdispatch on darwin bother to handle it. In this case we'll return215 // pthread/libdispatch on darwin bother to handle it. In this case we'll return
222 // without waiting, but the caller should retry anyway.216 // without waiting, but the caller should retry anyway.
223 darwin.EFAULT => {},217 .FAULT => {},
224 darwin.ETIMEDOUT => if (!timeout_overflowed) return error.TimedOut,218 .TIMEDOUT => if (!timeout_overflowed) return error.TimedOut,
225 else => unreachable,219 else => unreachable,
226 }220 }
227 }221 }
...@@ -237,11 +231,11 @@ const DarwinFutex = struct {...@@ -237,11 +231,11 @@ const DarwinFutex = struct {
237 const status = darwin.__ulock_wake(flags, addr, 0);231 const status = darwin.__ulock_wake(flags, addr, 0);
238232
239 if (status >= 0) return;233 if (status >= 0) return;
240 switch (-status) {234 switch (@intToEnum(std.os.E, -status)) {
241 darwin.EINTR => continue, // spurious wake()235 .INTR => continue, // spurious wake()
242 darwin.EFAULT => continue, // address of the lock was paged out236 .FAULT => continue, // address of the lock was paged out
243 darwin.ENOENT => return, // nothing was woken up237 .NOENT => return, // nothing was woken up
244 darwin.EALREADY => unreachable, // only for ULF_WAKE_THREAD238 .ALREADY => unreachable, // only for ULF_WAKE_THREAD
245 else => unreachable,239 else => unreachable,
246 }240 }
247 }241 }
...@@ -255,8 +249,8 @@ const PosixFutex = struct {...@@ -255,8 +249,8 @@ const PosixFutex = struct {
255 var waiter: List.Node = undefined;249 var waiter: List.Node = undefined;
256250
257 {251 {
258 assert(std.c.pthread_mutex_lock(&bucket.mutex) == 0);252 assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
259 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == 0);253 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
260254
261 if (ptr.load(.SeqCst) != expect) {255 if (ptr.load(.SeqCst) != expect) {
262 return;256 return;
...@@ -272,8 +266,8 @@ const PosixFutex = struct {...@@ -272,8 +266,8 @@ const PosixFutex = struct {
272 waiter.data.wait(null) catch unreachable;266 waiter.data.wait(null) catch unreachable;
273 };267 };
274268
275 assert(std.c.pthread_mutex_lock(&bucket.mutex) == 0);269 assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
276 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == 0);270 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
277271
278 if (waiter.data.address == address) {272 if (waiter.data.address == address) {
279 timed_out = true;273 timed_out = true;
...@@ -297,8 +291,8 @@ const PosixFutex = struct {...@@ -297,8 +291,8 @@ const PosixFutex = struct {
297 waiter.data.notify();291 waiter.data.notify();
298 };292 };
299293
300 assert(std.c.pthread_mutex_lock(&bucket.mutex) == 0);294 assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
301 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == 0);295 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
302296
303 var waiters = bucket.list.first;297 var waiters = bucket.list.first;
304 while (waiters) |waiter| {298 while (waiters) |waiter| {
...@@ -340,16 +334,13 @@ const PosixFutex = struct {...@@ -340,16 +334,13 @@ const PosixFutex = struct {
340 };334 };
341335
342 fn deinit(self: *Self) void {336 fn deinit(self: *Self) void {
343 const rc = std.c.pthread_cond_destroy(&self.cond);337 _ = std.c.pthread_cond_destroy(&self.cond);
344 assert(rc == 0 or rc == std.os.EINVAL);338 _ = std.c.pthread_mutex_destroy(&self.mutex);
345
346 const rm = std.c.pthread_mutex_destroy(&self.mutex);
347 assert(rm == 0 or rm == std.os.EINVAL);
348 }339 }
349340
350 fn wait(self: *Self, timeout: ?u64) error{TimedOut}!void {341 fn wait(self: *Self, timeout: ?u64) error{TimedOut}!void {
351 assert(std.c.pthread_mutex_lock(&self.mutex) == 0);342 assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS);
352 defer assert(std.c.pthread_mutex_unlock(&self.mutex) == 0);343 defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS);
353344
354 switch (self.state) {345 switch (self.state) {
355 .empty => self.state = .waiting,346 .empty => self.state = .waiting,
...@@ -378,28 +369,31 @@ const PosixFutex = struct {...@@ -378,28 +369,31 @@ const PosixFutex = struct {
378 }369 }
379370
380 const ts_ref = ts_ptr orelse {371 const ts_ref = ts_ptr orelse {
381 assert(std.c.pthread_cond_wait(&self.cond, &self.mutex) == 0);372 assert(std.c.pthread_cond_wait(&self.cond, &self.mutex) == .SUCCESS);
382 continue;373 continue;
383 };374 };
384375
385 const rc = std.c.pthread_cond_timedwait(&self.cond, &self.mutex, ts_ref);376 const rc = std.c.pthread_cond_timedwait(&self.cond, &self.mutex, ts_ref);
386 assert(rc == 0 or rc == std.os.ETIMEDOUT);377 switch (rc) {
387 if (rc == std.os.ETIMEDOUT) {378 .SUCCESS => {},
388 self.state = .empty;379 .TIMEDOUT => {
389 return error.TimedOut;380 self.state = .empty;
381 return error.TimedOut;
382 },
383 else => unreachable,
390 }384 }
391 }385 }
392 }386 }
393387
394 fn notify(self: *Self) void {388 fn notify(self: *Self) void {
395 assert(std.c.pthread_mutex_lock(&self.mutex) == 0);389 assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS);
396 defer assert(std.c.pthread_mutex_unlock(&self.mutex) == 0);390 defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS);
397391
398 switch (self.state) {392 switch (self.state) {
399 .empty => self.state = .notified,393 .empty => self.state = .notified,
400 .waiting => {394 .waiting => {
401 self.state = .notified;395 self.state = .notified;
402 assert(std.c.pthread_cond_signal(&self.cond) == 0);396 assert(std.c.pthread_cond_signal(&self.cond) == .SUCCESS);
403 },397 },
404 .notified => unreachable,398 .notified => unreachable,
405 }399 }
lib/std/Thread/Mutex.zig+16-22
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! Lock may be held only once. If the same thread tries to acquire1//! Lock may be held only once. If the same thread tries to acquire
8//! the same mutex twice, it deadlocks. This type supports static2//! the same mutex twice, it deadlocks. This type supports static
9//! initialization and is at most `@sizeOf(usize)` in size. When an3//! initialization and is at most `@sizeOf(usize)` in size. When an
...@@ -143,9 +137,9 @@ pub const AtomicMutex = struct {...@@ -143,9 +137,9 @@ pub const AtomicMutex = struct {
143 @enumToInt(new_state),137 @enumToInt(new_state),
144 null,138 null,
145 ))) {139 ))) {
146 0 => {},140 .SUCCESS => {},
147 std.os.EINTR => {},141 .INTR => {},
148 std.os.EAGAIN => {},142 .AGAIN => {},
149 else => unreachable,143 else => unreachable,
150 }144 }
151 },145 },
...@@ -164,8 +158,8 @@ pub const AtomicMutex = struct {...@@ -164,8 +158,8 @@ pub const AtomicMutex = struct {
164 linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,158 linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,
165 1,159 1,
166 ))) {160 ))) {
167 0 => {},161 .SUCCESS => {},
168 std.os.EFAULT => {},162 .FAULT => unreachable, // invalid pointer passed to futex_wake
169 else => unreachable,163 else => unreachable,
170 }164 }
171 },165 },
...@@ -182,10 +176,10 @@ pub const PthreadMutex = struct {...@@ -182,10 +176,10 @@ pub const PthreadMutex = struct {
182176
183 pub fn release(held: Held) void {177 pub fn release(held: Held) void {
184 switch (std.c.pthread_mutex_unlock(&held.mutex.pthread_mutex)) {178 switch (std.c.pthread_mutex_unlock(&held.mutex.pthread_mutex)) {
185 0 => return,179 .SUCCESS => return,
186 std.c.EINVAL => unreachable,180 .INVAL => unreachable,
187 std.c.EAGAIN => unreachable,181 .AGAIN => unreachable,
188 std.c.EPERM => unreachable,182 .PERM => unreachable,
189 else => unreachable,183 else => unreachable,
190 }184 }
191 }185 }
...@@ -195,7 +189,7 @@ pub const PthreadMutex = struct {...@@ -195,7 +189,7 @@ pub const PthreadMutex = struct {
195 /// the mutex is unavailable. Otherwise returns Held. Call189 /// the mutex is unavailable. Otherwise returns Held. Call
196 /// release on Held.190 /// release on Held.
197 pub fn tryAcquire(m: *PthreadMutex) ?Held {191 pub fn tryAcquire(m: *PthreadMutex) ?Held {
198 if (std.c.pthread_mutex_trylock(&m.pthread_mutex) == 0) {192 if (std.c.pthread_mutex_trylock(&m.pthread_mutex) == .SUCCESS) {
199 return Held{ .mutex = m };193 return Held{ .mutex = m };
200 } else {194 } else {
201 return null;195 return null;
...@@ -206,12 +200,12 @@ pub const PthreadMutex = struct {...@@ -206,12 +200,12 @@ pub const PthreadMutex = struct {
206 /// held by the calling thread.200 /// held by the calling thread.
207 pub fn acquire(m: *PthreadMutex) Held {201 pub fn acquire(m: *PthreadMutex) Held {
208 switch (std.c.pthread_mutex_lock(&m.pthread_mutex)) {202 switch (std.c.pthread_mutex_lock(&m.pthread_mutex)) {
209 0 => return Held{ .mutex = m },203 .SUCCESS => return Held{ .mutex = m },
210 std.c.EINVAL => unreachable,204 .INVAL => unreachable,
211 std.c.EBUSY => unreachable,205 .BUSY => unreachable,
212 std.c.EAGAIN => unreachable,206 .AGAIN => unreachable,
213 std.c.EDEADLK => unreachable,207 .DEADLK => unreachable,
214 std.c.EPERM => unreachable,208 .PERM => unreachable,
215 else => unreachable,209 else => unreachable,
216 }210 }
217 }211 }
lib/std/Thread/ResetEvent.zig+12-18
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! A thread-safe resource which supports blocking until signaled.1//! A thread-safe resource which supports blocking until signaled.
8//! This API is for kernel threads, not evented I/O.2//! This API is for kernel threads, not evented I/O.
9//! This API requires being initialized at runtime, and initialization3//! This API requires being initialized at runtime, and initialization
...@@ -130,7 +124,7 @@ pub const PosixEvent = struct {...@@ -130,7 +124,7 @@ pub const PosixEvent = struct {
130124
131 pub fn init(ev: *PosixEvent) !void {125 pub fn init(ev: *PosixEvent) !void {
132 switch (c.getErrno(c.sem_init(&ev.sem, 0, 0))) {126 switch (c.getErrno(c.sem_init(&ev.sem, 0, 0))) {
133 0 => return,127 .SUCCESS => return,
134 else => return error.SystemResources,128 else => return error.SystemResources,
135 }129 }
136 }130 }
...@@ -147,9 +141,9 @@ pub const PosixEvent = struct {...@@ -147,9 +141,9 @@ pub const PosixEvent = struct {
147 pub fn wait(ev: *PosixEvent) void {141 pub fn wait(ev: *PosixEvent) void {
148 while (true) {142 while (true) {
149 switch (c.getErrno(c.sem_wait(&ev.sem))) {143 switch (c.getErrno(c.sem_wait(&ev.sem))) {
150 0 => return,144 .SUCCESS => return,
151 c.EINTR => continue,145 .INTR => continue,
152 c.EINVAL => unreachable,146 .INVAL => unreachable,
153 else => unreachable,147 else => unreachable,
154 }148 }
155 }149 }
...@@ -165,10 +159,10 @@ pub const PosixEvent = struct {...@@ -165,10 +159,10 @@ pub const PosixEvent = struct {
165 ts.tv_nsec = @intCast(@TypeOf(ts.tv_nsec), @mod(timeout_abs, time.ns_per_s));159 ts.tv_nsec = @intCast(@TypeOf(ts.tv_nsec), @mod(timeout_abs, time.ns_per_s));
166 while (true) {160 while (true) {
167 switch (c.getErrno(c.sem_timedwait(&ev.sem, &ts))) {161 switch (c.getErrno(c.sem_timedwait(&ev.sem, &ts))) {
168 0 => return .event_set,162 .SUCCESS => return .event_set,
169 c.EINTR => continue,163 .INTR => continue,
170 c.EINVAL => unreachable,164 .INVAL => unreachable,
171 c.ETIMEDOUT => return .timed_out,165 .TIMEDOUT => return .timed_out,
172 else => unreachable,166 else => unreachable,
173 }167 }
174 }168 }
...@@ -177,10 +171,10 @@ pub const PosixEvent = struct {...@@ -177,10 +171,10 @@ pub const PosixEvent = struct {
177 pub fn reset(ev: *PosixEvent) void {171 pub fn reset(ev: *PosixEvent) void {
178 while (true) {172 while (true) {
179 switch (c.getErrno(c.sem_trywait(&ev.sem))) {173 switch (c.getErrno(c.sem_trywait(&ev.sem))) {
180 0 => continue, // Need to make it go to zero.174 .SUCCESS => continue, // Need to make it go to zero.
181 c.EINTR => continue,175 .INTR => continue,
182 c.EINVAL => unreachable,176 .INVAL => unreachable,
183 c.EAGAIN => return, // The semaphore currently has the value zero.177 .AGAIN => return, // The semaphore currently has the value zero.
184 else => unreachable,178 else => unreachable,
185 }179 }
186 }180 }
lib/std/Thread/RwLock.zig+11-19
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! A lock that supports one writer or many readers.1//! A lock that supports one writer or many readers.
8//! This API is for kernel threads, not evented I/O.2//! This API is for kernel threads, not evented I/O.
9//! This API requires being initialized at runtime, and initialization3//! This API requires being initialized at runtime, and initialization
...@@ -13,7 +7,7 @@ impl: Impl,...@@ -13,7 +7,7 @@ impl: Impl,
137
14const RwLock = @This();8const RwLock = @This();
15const std = @import("../std.zig");9const std = @import("../std.zig");
16const builtin = std.builtin;10const builtin = @import("builtin");
17const assert = std.debug.assert;11const assert = std.debug.assert;
18const Mutex = std.Thread.Mutex;12const Mutex = std.Thread.Mutex;
19const Semaphore = std.Semaphore;13const Semaphore = std.Semaphore;
...@@ -165,43 +159,41 @@ pub const PthreadRwLock = struct {...@@ -165,43 +159,41 @@ pub const PthreadRwLock = struct {
165 }159 }
166160
167 pub fn deinit(rwl: *PthreadRwLock) void {161 pub fn deinit(rwl: *PthreadRwLock) void {
168 const safe_rc = switch (std.builtin.os.tag) {162 const safe_rc: std.os.E = switch (builtin.os.tag) {
169 .dragonfly, .netbsd => std.os.EAGAIN,163 .dragonfly, .netbsd => .AGAIN,
170 else => 0,164 else => .SUCCESS,
171 };165 };
172
173 const rc = std.c.pthread_rwlock_destroy(&rwl.rwlock);166 const rc = std.c.pthread_rwlock_destroy(&rwl.rwlock);
174 assert(rc == 0 or rc == safe_rc);167 assert(rc == .SUCCESS or rc == safe_rc);
175
176 rwl.* = undefined;168 rwl.* = undefined;
177 }169 }
178170
179 pub fn tryLock(rwl: *PthreadRwLock) bool {171 pub fn tryLock(rwl: *PthreadRwLock) bool {
180 return pthread_rwlock_trywrlock(&rwl.rwlock) == 0;172 return pthread_rwlock_trywrlock(&rwl.rwlock) == .SUCCESS;
181 }173 }
182174
183 pub fn lock(rwl: *PthreadRwLock) void {175 pub fn lock(rwl: *PthreadRwLock) void {
184 const rc = pthread_rwlock_wrlock(&rwl.rwlock);176 const rc = pthread_rwlock_wrlock(&rwl.rwlock);
185 assert(rc == 0);177 assert(rc == .SUCCESS);
186 }178 }
187179
188 pub fn unlock(rwl: *PthreadRwLock) void {180 pub fn unlock(rwl: *PthreadRwLock) void {
189 const rc = pthread_rwlock_unlock(&rwl.rwlock);181 const rc = pthread_rwlock_unlock(&rwl.rwlock);
190 assert(rc == 0);182 assert(rc == .SUCCESS);
191 }183 }
192184
193 pub fn tryLockShared(rwl: *PthreadRwLock) bool {185 pub fn tryLockShared(rwl: *PthreadRwLock) bool {
194 return pthread_rwlock_tryrdlock(&rwl.rwlock) == 0;186 return pthread_rwlock_tryrdlock(&rwl.rwlock) == .SUCCESS;
195 }187 }
196188
197 pub fn lockShared(rwl: *PthreadRwLock) void {189 pub fn lockShared(rwl: *PthreadRwLock) void {
198 const rc = pthread_rwlock_rdlock(&rwl.rwlock);190 const rc = pthread_rwlock_rdlock(&rwl.rwlock);
199 assert(rc == 0);191 assert(rc == .SUCCESS);
200 }192 }
201193
202 pub fn unlockShared(rwl: *PthreadRwLock) void {194 pub fn unlockShared(rwl: *PthreadRwLock) void {
203 const rc = pthread_rwlock_unlock(&rwl.rwlock);195 const rc = pthread_rwlock_unlock(&rwl.rwlock);
204 assert(rc == 0);196 assert(rc == .SUCCESS);
205 }197 }
206};198};
207199
lib/std/Thread/Semaphore.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! A semaphore is an unsigned integer that blocks the kernel thread if1//! A semaphore is an unsigned integer that blocks the kernel thread if
8//! the number would become negative.2//! the number would become negative.
9//! This API supports static initialization and does not require deinitialization.3//! This API supports static initialization and does not require deinitialization.
lib/std/Thread/StaticResetEvent.zig+5-11
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! A thread-safe resource which supports blocking until signaled.1//! A thread-safe resource which supports blocking until signaled.
8//! This API is for kernel threads, not evented I/O.2//! This API is for kernel threads, not evented I/O.
9//! This API is statically initializable. It cannot fail to be initialized3//! This API is statically initializable. It cannot fail to be initialized
...@@ -201,7 +195,7 @@ pub const AtomicEvent = struct {...@@ -201,7 +195,7 @@ pub const AtomicEvent = struct {
201 const waiting = std.math.maxInt(i32); // wake_count195 const waiting = std.math.maxInt(i32); // wake_count
202 const ptr = @ptrCast(*const i32, waiters);196 const ptr = @ptrCast(*const i32, waiters);
203 const rc = linux.futex_wake(ptr, linux.FUTEX_WAKE | linux.FUTEX_PRIVATE_FLAG, waiting);197 const rc = linux.futex_wake(ptr, linux.FUTEX_WAKE | linux.FUTEX_PRIVATE_FLAG, waiting);
204 assert(linux.getErrno(rc) == 0);198 assert(linux.getErrno(rc) == .SUCCESS);
205 }199 }
206200
207 fn wait(waiters: *u32, timeout: ?u64) !void {201 fn wait(waiters: *u32, timeout: ?u64) !void {
...@@ -221,10 +215,10 @@ pub const AtomicEvent = struct {...@@ -221,10 +215,10 @@ pub const AtomicEvent = struct {
221 const ptr = @ptrCast(*const i32, waiters);215 const ptr = @ptrCast(*const i32, waiters);
222 const rc = linux.futex_wait(ptr, linux.FUTEX_WAIT | linux.FUTEX_PRIVATE_FLAG, expected, ts_ptr);216 const rc = linux.futex_wait(ptr, linux.FUTEX_WAIT | linux.FUTEX_PRIVATE_FLAG, expected, ts_ptr);
223 switch (linux.getErrno(rc)) {217 switch (linux.getErrno(rc)) {
224 0 => continue,218 .SUCCESS => continue,
225 os.ETIMEDOUT => return error.TimedOut,219 .TIMEDOUT => return error.TimedOut,
226 os.EINTR => continue,220 .INTR => continue,
227 os.EAGAIN => return,221 .AGAIN => return,
228 else => unreachable,222 else => unreachable,
229 }223 }
230 }224 }
lib/std/array_hash_map.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const debug = std.debug;2const debug = std.debug;
8const assert = debug.assert;3const assert = debug.assert;
lib/std/array_list.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const debug = std.debug;2const debug = std.debug;
8const assert = debug.assert;3const assert = debug.assert;
lib/std/ascii.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Does NOT look at the locale the way C89's toupper(3), isspace() et cetera does.1// Does NOT look at the locale the way C89's toupper(3), isspace() et cetera does.
7// I could have taken only a u7 to make this clear, but it would be slower2// I could have taken only a u7 to make this clear, but it would be slower
8// It is my opinion that encodings other than UTF-8 should not be supported.3// It is my opinion that encodings other than UTF-8 should not be supported.
lib/std/atomic.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std.zig");1const std = @import("std.zig");
8const target = std.Target.current;2const target = std.Target.current;
93
lib/std/atomic/Atomic.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../std.zig");1const std = @import("../std.zig");
82
9const testing = std.testing;3const testing = std.testing;
lib/std/atomic/queue.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/atomic/stack.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const assert = std.debug.assert;1const assert = std.debug.assert;
7const builtin = std.builtin;2const builtin = std.builtin;
8const expect = std.testing.expect;3const expect = std.testing.expect;
lib/std/base64.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const testing = std.testing;3const testing = std.testing;
lib/std/bit_set.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! This file defines several variants of bit sets. A bit set1//! This file defines several variants of bit sets. A bit set
8//! is a densely stored set of integers with a known maximum,2//! is a densely stored set of integers with a known maximum,
9//! in which each integer gets a single bit. Bit sets have very3//! in which each integer gets a single bit. Bit sets have very
lib/std/bounded_array.zig created+315
...@@ -0,0 +1,315 @@
1const std = @import("std.zig");
2const assert = std.debug.assert;
3const mem = std.mem;
4const testing = std.testing;
5
6/// A structure with an array and a length, that can be used as a slice.
7///
8/// Useful to pass around small arrays whose exact size is only known at
9/// runtime, but whose maximum size is known at comptime, without requiring
10/// an `Allocator`.
11///
12/// ```zig
13/// var actual_size = 32;
14/// var a = try BoundedArray(u8, 64).init(actual_size);
15/// var slice = a.slice(); // a slice of the 64-byte array
16/// var a_clone = a; // creates a copy - the structure doesn't use any internal pointers
17/// ```
18pub fn BoundedArray(comptime T: type, comptime capacity: usize) type {
19 return struct {
20 const Self = @This();
21 buffer: [capacity]T,
22 len: usize = 0,
23
24 /// Set the actual length of the slice.
25 /// Returns error.Overflow if it exceeds the length of the backing array.
26 pub fn init(len: usize) !Self {
27 if (len > capacity) return error.Overflow;
28 return Self{ .buffer = undefined, .len = len };
29 }
30
31 /// View the internal array as a mutable slice whose size was previously set.
32 pub fn slice(self: *Self) []T {
33 return self.buffer[0..self.len];
34 }
35
36 /// View the internal array as a constant slice whose size was previously set.
37 pub fn constSlice(self: Self) []const T {
38 return self.buffer[0..self.len];
39 }
40
41 /// Adjust the slice's length to `len`.
42 /// Does not initialize added items if any.
43 pub fn resize(self: *Self, len: usize) !void {
44 if (len > capacity) return error.Overflow;
45 self.len = len;
46 }
47
48 /// Copy the content of an existing slice.
49 pub fn fromSlice(m: []const T) !Self {
50 var list = try init(m.len);
51 std.mem.copy(T, list.slice(), m);
52 return list;
53 }
54
55 /// Return the element at index `i` of the slice.
56 pub fn get(self: Self, i: usize) T {
57 return self.constSlice()[i];
58 }
59
60 /// Set the value of the element at index `i` of the slice.
61 pub fn set(self: *Self, i: usize, item: T) void {
62 self.slice()[i] = item;
63 }
64
65 /// Return the maximum length of a slice.
66 pub fn capacity(self: Self) usize {
67 return self.buffer.len;
68 }
69
70 /// Check that the slice can hold at least `additional_count` items.
71 pub fn ensureUnusedCapacity(self: Self, additional_count: usize) !void {
72 if (self.len + additional_count > capacity) {
73 return error.Overflow;
74 }
75 }
76
77 /// Increase length by 1, returning a pointer to the new item.
78 pub fn addOne(self: *Self) !*T {
79 try self.ensureUnusedCapacity(1);
80 return self.addOneAssumeCapacity();
81 }
82
83 /// Increase length by 1, returning pointer to the new item.
84 /// Asserts that there is space for the new item.
85 pub fn addOneAssumeCapacity(self: *Self) *T {
86 assert(self.len < capacity);
87 self.len += 1;
88 return &self.slice()[self.len - 1];
89 }
90
91 /// Resize the slice, adding `n` new elements, which have `undefined` values.
92 /// The return value is a slice pointing to the uninitialized elements.
93 pub fn addManyAsArray(self: *Self, comptime n: usize) !*[n]T {
94 const prev_len = self.len;
95 try self.resize(self.len + n);
96 return self.slice()[prev_len..][0..n];
97 }
98
99 /// Remove and return the last element from the slice.
100 /// Asserts the slice has at least one item.
101 pub fn pop(self: *Self) T {
102 const item = self.get(self.len - 1);
103 self.len -= 1;
104 return item;
105 }
106
107 /// Remove and return the last element from the slice, or
108 /// return `null` if the slice is empty.
109 pub fn popOrNull(self: *Self) ?T {
110 return if (self.len == 0) null else self.pop();
111 }
112
113 /// Return a slice of only the extra capacity after items.
114 /// This can be useful for writing directly into it.
115 /// Note that such an operation must be followed up with a
116 /// call to `resize()`
117 pub fn unusedCapacitySlice(self: *Self) []T {
118 return self.buffer[self.len..];
119 }
120
121 /// Insert `item` at index `i` by moving `slice[n .. slice.len]` to make room.
122 /// This operation is O(N).
123 pub fn insert(self: *Self, i: usize, item: T) !void {
124 if (i >= self.len) {
125 return error.IndexOutOfBounds;
126 }
127 _ = try self.addOne();
128 var s = self.slice();
129 mem.copyBackwards(T, s[i + 1 .. s.len], s[i .. s.len - 1]);
130 self.buffer[i] = item;
131 }
132
133 /// Insert slice `items` at index `i` by moving `slice[i .. slice.len]` to make room.
134 /// This operation is O(N).
135 pub fn insertSlice(self: *Self, i: usize, items: []const T) !void {
136 try self.ensureUnusedCapacity(items.len);
137 self.len += items.len;
138 mem.copyBackwards(T, self.slice()[i + items.len .. self.len], self.constSlice()[i .. self.len - items.len]);
139 mem.copy(T, self.slice()[i .. i + items.len], items);
140 }
141
142 /// Replace range of elements `slice[start..start+len]` with `new_items`.
143 /// Grows slice if `len < new_items.len`.
144 /// Shrinks slice if `len > new_items.len`.
145 pub fn replaceRange(self: *Self, start: usize, len: usize, new_items: []const T) !void {
146 const after_range = start + len;
147 var range = self.slice()[start..after_range];
148
149 if (range.len == new_items.len) {
150 mem.copy(T, range, new_items);
151 } else if (range.len < new_items.len) {
152 const first = new_items[0..range.len];
153 const rest = new_items[range.len..];
154 mem.copy(T, range, first);
155 try self.insertSlice(after_range, rest);
156 } else {
157 mem.copy(T, range, new_items);
158 const after_subrange = start + new_items.len;
159 for (self.constSlice()[after_range..]) |item, i| {
160 self.slice()[after_subrange..][i] = item;
161 }
162 self.len -= len - new_items.len;
163 }
164 }
165
166 /// Extend the slice by 1 element.
167 pub fn append(self: *Self, item: T) !void {
168 const new_item_ptr = try self.addOne();
169 new_item_ptr.* = item;
170 }
171
172 /// Remove the element at index `i`, shift elements after index
173 /// `i` forward, and return the removed element.
174 /// Asserts the slice has at least one item.
175 /// This operation is O(N).
176 pub fn orderedRemove(self: *Self, i: usize) T {
177 const newlen = self.len - 1;
178 if (newlen == i) return self.pop();
179 const old_item = self.get(i);
180 for (self.slice()[i..newlen]) |*b, j| b.* = self.get(i + 1 + j);
181 self.set(newlen, undefined);
182 self.len = newlen;
183 return old_item;
184 }
185
186 /// Remove the element at the specified index and return it.
187 /// The empty slot is filled from the end of the slice.
188 /// This operation is O(1).
189 pub fn swapRemove(self: *Self, i: usize) T {
190 if (self.len - 1 == i) return self.pop();
191 const old_item = self.get(i);
192 self.set(i, self.pop());
193 return old_item;
194 }
195
196 /// Append the slice of items to the slice.
197 pub fn appendSlice(self: *Self, items: []const T) !void {
198 try self.ensureUnusedCapacity(items.len);
199 self.appendSliceAssumeCapacity(items);
200 }
201
202 /// Append the slice of items to the slice, asserting the capacity is already
203 /// enough to store the new items.
204 pub fn appendSliceAssumeCapacity(self: *Self, items: []const T) void {
205 const oldlen = self.len;
206 self.len += items.len;
207 mem.copy(T, self.slice()[oldlen..], items);
208 }
209
210 /// Append a value to the slice `n` times.
211 /// Allocates more memory as necessary.
212 pub fn appendNTimes(self: *Self, value: T, n: usize) !void {
213 const old_len = self.len;
214 try self.resize(old_len + n);
215 mem.set(T, self.slice()[old_len..self.len], value);
216 }
217
218 /// Append a value to the slice `n` times.
219 /// Asserts the capacity is enough.
220 pub fn appendNTimesAssumeCapacity(self: *Self, value: T, n: usize) void {
221 const old_len = self.len;
222 self.len += n;
223 assert(self.len <= capacity);
224 mem.set(T, self.slice()[old_len..self.len], value);
225 }
226 };
227}
228
229test "BoundedArray" {
230 var a = try BoundedArray(u8, 64).init(32);
231
232 try testing.expectEqual(a.capacity(), 64);
233 try testing.expectEqual(a.slice().len, 32);
234 try testing.expectEqual(a.constSlice().len, 32);
235
236 try a.resize(48);
237 try testing.expectEqual(a.len, 48);
238
239 const x = [_]u8{1} ** 10;
240 a = try BoundedArray(u8, 64).fromSlice(&x);
241 try testing.expectEqualSlices(u8, &x, a.constSlice());
242
243 var a2 = a;
244 try testing.expectEqualSlices(u8, a.constSlice(), a.constSlice());
245 a2.set(0, 0);
246 try testing.expect(a.get(0) != a2.get(0));
247
248 try testing.expectError(error.Overflow, a.resize(100));
249 try testing.expectError(error.Overflow, BoundedArray(u8, x.len - 1).fromSlice(&x));
250
251 try a.resize(0);
252 try a.ensureUnusedCapacity(a.capacity());
253 (try a.addOne()).* = 0;
254 try a.ensureUnusedCapacity(a.capacity() - 1);
255 try testing.expectEqual(a.len, 1);
256
257 const uninitialized = try a.addManyAsArray(4);
258 try testing.expectEqual(uninitialized.len, 4);
259 try testing.expectEqual(a.len, 5);
260
261 try a.append(0xff);
262 try testing.expectEqual(a.len, 6);
263 try testing.expectEqual(a.pop(), 0xff);
264
265 try a.resize(1);
266 try testing.expectEqual(a.popOrNull(), 0);
267 try testing.expectEqual(a.popOrNull(), null);
268 var unused = a.unusedCapacitySlice();
269 mem.set(u8, unused[0..8], 2);
270 unused[8] = 3;
271 unused[9] = 4;
272 try testing.expectEqual(unused.len, a.capacity());
273 try a.resize(10);
274
275 try a.insert(5, 0xaa);
276 try testing.expectEqual(a.len, 11);
277 try testing.expectEqual(a.get(5), 0xaa);
278 try testing.expectEqual(a.get(9), 3);
279 try testing.expectEqual(a.get(10), 4);
280
281 try a.appendSlice(&x);
282 try testing.expectEqual(a.len, 11 + x.len);
283
284 try a.appendNTimes(0xbb, 5);
285 try testing.expectEqual(a.len, 11 + x.len + 5);
286 try testing.expectEqual(a.pop(), 0xbb);
287
288 a.appendNTimesAssumeCapacity(0xcc, 5);
289 try testing.expectEqual(a.len, 11 + x.len + 5 - 1 + 5);
290 try testing.expectEqual(a.pop(), 0xcc);
291
292 try testing.expectEqual(a.len, 29);
293 try a.replaceRange(1, 20, &x);
294 try testing.expectEqual(a.len, 29 + x.len - 20);
295
296 try a.insertSlice(0, &x);
297 try testing.expectEqual(a.len, 29 + x.len - 20 + x.len);
298
299 try a.replaceRange(1, 5, &x);
300 try testing.expectEqual(a.len, 29 + x.len - 20 + x.len + x.len - 5);
301
302 try a.append(10);
303 try testing.expectEqual(a.pop(), 10);
304
305 try a.append(20);
306 const removed = a.orderedRemove(5);
307 try testing.expectEqual(removed, 1);
308 try testing.expectEqual(a.len, 34);
309
310 a.set(0, 0xdd);
311 a.set(a.len - 1, 0xee);
312 const swapped = a.swapRemove(0);
313 try testing.expectEqual(swapped, 0xdd);
314 try testing.expectEqual(a.get(0), 0xee);
315}
lib/std/buf_map.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const StringHashMap = std.StringHashMap;2const StringHashMap = std.StringHashMap;
8const mem = std.mem;3const mem = std.mem;
lib/std/buf_set.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const StringHashMap = std.StringHashMap;2const StringHashMap = std.StringHashMap;
8const mem = @import("mem.zig");3const mem = @import("mem.zig");
lib/std/build.zig+49-230
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const io = std.io;3const io = std.io;
...@@ -28,6 +23,7 @@ pub const WriteFileStep = @import("build/WriteFileStep.zig");...@@ -28,6 +23,7 @@ pub const WriteFileStep = @import("build/WriteFileStep.zig");
28pub const RunStep = @import("build/RunStep.zig");23pub const RunStep = @import("build/RunStep.zig");
29pub const CheckFileStep = @import("build/CheckFileStep.zig");24pub const CheckFileStep = @import("build/CheckFileStep.zig");
30pub const InstallRawStep = @import("build/InstallRawStep.zig");25pub const InstallRawStep = @import("build/InstallRawStep.zig");
26pub const OptionsStep = @import("build/OptionsStep.zig");
3127
32pub const Builder = struct {28pub const Builder = struct {
33 install_tls: TopLevelStep,29 install_tls: TopLevelStep,
...@@ -252,6 +248,10 @@ pub const Builder = struct {...@@ -252,6 +248,10 @@ pub const Builder = struct {
252 return LibExeObjStep.createExecutable(builder, name, root_src);248 return LibExeObjStep.createExecutable(builder, name, root_src);
253 }249 }
254250
251 pub fn addOptions(self: *Builder) *OptionsStep {
252 return OptionsStep.create(self);
253 }
254
255 pub fn addObject(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep {255 pub fn addObject(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep {
256 return addObjectSource(self, name, convertOptionalPathToFileSource(root_src));256 return addObjectSource(self, name, convertOptionalPathToFileSource(root_src));
257 }257 }
...@@ -1380,16 +1380,6 @@ pub const FileSource = union(enum) {...@@ -1380,16 +1380,6 @@ pub const FileSource = union(enum) {
1380 }1380 }
1381};1381};
13821382
1383const BuildOptionArtifactArg = struct {
1384 name: []const u8,
1385 artifact: *LibExeObjStep,
1386};
1387
1388const BuildOptionFileSourceArg = struct {
1389 name: []const u8,
1390 source: FileSource,
1391};
1392
1393pub const LibExeObjStep = struct {1383pub const LibExeObjStep = struct {
1394 pub const base_id = .lib_exe_obj;1384 pub const base_id = .lib_exe_obj;
13951385
...@@ -1432,15 +1422,13 @@ pub const LibExeObjStep = struct {...@@ -1432,15 +1422,13 @@ pub const LibExeObjStep = struct {
1432 single_threaded: bool,1422 single_threaded: bool,
1433 test_evented_io: bool = false,1423 test_evented_io: bool = false,
1434 code_model: builtin.CodeModel = .default,1424 code_model: builtin.CodeModel = .default,
1425 wasi_exec_model: ?builtin.WasiExecModel = null,
14351426
1436 root_src: ?FileSource,1427 root_src: ?FileSource,
1437 out_h_filename: []const u8,1428 out_h_filename: []const u8,
1438 out_lib_filename: []const u8,1429 out_lib_filename: []const u8,
1439 out_pdb_filename: []const u8,1430 out_pdb_filename: []const u8,
1440 packages: ArrayList(Pkg),1431 packages: ArrayList(Pkg),
1441 build_options_contents: std.ArrayList(u8),
1442 build_options_artifact_args: std.ArrayList(BuildOptionArtifactArg),
1443 build_options_file_source_args: std.ArrayList(BuildOptionFileSourceArg),
14441432
1445 object_src: []const u8,1433 object_src: []const u8,
14461434
...@@ -1607,9 +1595,6 @@ pub const LibExeObjStep = struct {...@@ -1607,9 +1595,6 @@ pub const LibExeObjStep = struct {
1607 .rpaths = ArrayList([]const u8).init(builder.allocator),1595 .rpaths = ArrayList([]const u8).init(builder.allocator),
1608 .framework_dirs = ArrayList([]const u8).init(builder.allocator),1596 .framework_dirs = ArrayList([]const u8).init(builder.allocator),
1609 .object_src = undefined,1597 .object_src = undefined,
1610 .build_options_contents = std.ArrayList(u8).init(builder.allocator),
1611 .build_options_artifact_args = std.ArrayList(BuildOptionArtifactArg).init(builder.allocator),
1612 .build_options_file_source_args = std.ArrayList(BuildOptionFileSourceArg).init(builder.allocator),
1613 .c_std = Builder.CStd.C99,1598 .c_std = Builder.CStd.C99,
1614 .override_lib_dir = null,1599 .override_lib_dir = null,
1615 .main_pkg_path = null,1600 .main_pkg_path = null,
...@@ -1735,7 +1720,6 @@ pub const LibExeObjStep = struct {...@@ -1735,7 +1720,6 @@ pub const LibExeObjStep = struct {
1735 }1720 }
17361721
1737 pub fn linkFramework(self: *LibExeObjStep, framework_name: []const u8) void {1722 pub fn linkFramework(self: *LibExeObjStep, framework_name: []const u8) void {
1738 assert(self.target.isDarwin());
1739 // Note: No need to dupe because frameworks dupes internally.1723 // Note: No need to dupe because frameworks dupes internally.
1740 self.frameworks.insert(framework_name) catch unreachable;1724 self.frameworks.insert(framework_name) catch unreachable;
1741 }1725 }
...@@ -2043,119 +2027,6 @@ pub const LibExeObjStep = struct {...@@ -2043,119 +2027,6 @@ pub const LibExeObjStep = struct {
2043 self.linkLibraryOrObject(obj);2027 self.linkLibraryOrObject(obj);
2044 }2028 }
20452029
2046 pub fn addBuildOption(self: *LibExeObjStep, comptime T: type, name: []const u8, value: T) void {
2047 const out = self.build_options_contents.writer();
2048 switch (T) {
2049 []const []const u8 => {
2050 out.print("pub const {}: []const []const u8 = &[_][]const u8{{\n", .{std.zig.fmtId(name)}) catch unreachable;
2051 for (value) |slice| {
2052 out.print(" \"{}\",\n", .{std.zig.fmtEscapes(slice)}) catch unreachable;
2053 }
2054 out.writeAll("};\n") catch unreachable;
2055 return;
2056 },
2057 [:0]const u8 => {
2058 out.print("pub const {}: [:0]const u8 = \"{}\";\n", .{ std.zig.fmtId(name), std.zig.fmtEscapes(value) }) catch unreachable;
2059 return;
2060 },
2061 []const u8 => {
2062 out.print("pub const {}: []const u8 = \"{}\";\n", .{ std.zig.fmtId(name), std.zig.fmtEscapes(value) }) catch unreachable;
2063 return;
2064 },
2065 ?[:0]const u8 => {
2066 out.print("pub const {}: ?[:0]const u8 = ", .{std.zig.fmtId(name)}) catch unreachable;
2067 if (value) |payload| {
2068 out.print("\"{}\";\n", .{std.zig.fmtEscapes(payload)}) catch unreachable;
2069 } else {
2070 out.writeAll("null;\n") catch unreachable;
2071 }
2072 return;
2073 },
2074 ?[]const u8 => {
2075 out.print("pub const {}: ?[]const u8 = ", .{std.zig.fmtId(name)}) catch unreachable;
2076 if (value) |payload| {
2077 out.print("\"{}\";\n", .{std.zig.fmtEscapes(payload)}) catch unreachable;
2078 } else {
2079 out.writeAll("null;\n") catch unreachable;
2080 }
2081 return;
2082 },
2083 std.builtin.Version => {
2084 out.print(
2085 \\pub const {}: @import("std").builtin.Version = .{{
2086 \\ .major = {d},
2087 \\ .minor = {d},
2088 \\ .patch = {d},
2089 \\}};
2090 \\
2091 , .{
2092 std.zig.fmtId(name),
2093
2094 value.major,
2095 value.minor,
2096 value.patch,
2097 }) catch unreachable;
2098 },
2099 std.SemanticVersion => {
2100 out.print(
2101 \\pub const {}: @import("std").SemanticVersion = .{{
2102 \\ .major = {d},
2103 \\ .minor = {d},
2104 \\ .patch = {d},
2105 \\
2106 , .{
2107 std.zig.fmtId(name),
2108
2109 value.major,
2110 value.minor,
2111 value.patch,
2112 }) catch unreachable;
2113 if (value.pre) |some| {
2114 out.print(" .pre = \"{}\",\n", .{std.zig.fmtEscapes(some)}) catch unreachable;
2115 }
2116 if (value.build) |some| {
2117 out.print(" .build = \"{}\",\n", .{std.zig.fmtEscapes(some)}) catch unreachable;
2118 }
2119 out.writeAll("};\n") catch unreachable;
2120 return;
2121 },
2122 else => {},
2123 }
2124 switch (@typeInfo(T)) {
2125 .Enum => |enum_info| {
2126 out.print("pub const {} = enum {{\n", .{std.zig.fmtId(@typeName(T))}) catch unreachable;
2127 inline for (enum_info.fields) |field| {
2128 out.print(" {},\n", .{std.zig.fmtId(field.name)}) catch unreachable;
2129 }
2130 out.writeAll("};\n") catch unreachable;
2131 },
2132 else => {},
2133 }
2134 out.print("pub const {}: {s} = {};\n", .{ std.zig.fmtId(name), @typeName(T), value }) catch unreachable;
2135 }
2136
2137 /// The value is the path in the cache dir.
2138 /// Adds a dependency automatically.
2139 pub fn addBuildOptionArtifact(self: *LibExeObjStep, name: []const u8, artifact: *LibExeObjStep) void {
2140 self.build_options_artifact_args.append(.{ .name = self.builder.dupe(name), .artifact = artifact }) catch unreachable;
2141 self.step.dependOn(&artifact.step);
2142 }
2143
2144 /// The value is the path in the cache dir.
2145 /// Adds a dependency automatically.
2146 /// basename refers to the basename of the WriteFileStep
2147 pub fn addBuildOptionFileSource(
2148 self: *LibExeObjStep,
2149 name: []const u8,
2150 source: FileSource,
2151 ) void {
2152 self.build_options_file_source_args.append(.{
2153 .name = name,
2154 .source = source.dupe(self.builder),
2155 }) catch unreachable;
2156 source.addStepDependencies(&self.step);
2157 }
2158
2159 pub fn addSystemIncludeDir(self: *LibExeObjStep, path: []const u8) void {2030 pub fn addSystemIncludeDir(self: *LibExeObjStep, path: []const u8) void {
2160 self.include_dirs.append(IncludeDir{ .raw_path_system = self.builder.dupe(path) }) catch unreachable;2031 self.include_dirs.append(IncludeDir{ .raw_path_system = self.builder.dupe(path) }) catch unreachable;
2161 }2032 }
...@@ -2181,6 +2052,10 @@ pub const LibExeObjStep = struct {...@@ -2181,6 +2052,10 @@ pub const LibExeObjStep = struct {
2181 self.addRecursiveBuildDeps(package);2052 self.addRecursiveBuildDeps(package);
2182 }2053 }
21832054
2055 pub fn addOptions(self: *LibExeObjStep, package_name: []const u8, options: *OptionsStep) void {
2056 self.addPackage(options.getPackage(package_name));
2057 }
2058
2184 fn addRecursiveBuildDeps(self: *LibExeObjStep, package: Pkg) void {2059 fn addRecursiveBuildDeps(self: *LibExeObjStep, package: Pkg) void {
2185 package.path.addStepDependencies(&self.step);2060 package.path.addStepDependencies(&self.step);
2186 if (package.dependencies) |deps| {2061 if (package.dependencies) |deps| {
...@@ -2247,28 +2122,6 @@ pub const LibExeObjStep = struct {...@@ -2247,28 +2122,6 @@ pub const LibExeObjStep = struct {
2247 self.step.dependOn(&other.step);2122 self.step.dependOn(&other.step);
2248 self.link_objects.append(.{ .other_step = other }) catch unreachable;2123 self.link_objects.append(.{ .other_step = other }) catch unreachable;
2249 self.include_dirs.append(.{ .other_step = other }) catch unreachable;2124 self.include_dirs.append(.{ .other_step = other }) catch unreachable;
2250
2251 // BUG: The following code introduces a order-of-call dependency:
2252 // var lib = addSharedLibrary(...);
2253 // var exe = addExecutable(...);
2254 // exe.linkLibrary(lib);
2255 // lib.linkSystemLibrary("foobar"); // this will be ignored for exe!
2256
2257 // Inherit dependency on system libraries
2258 for (other.link_objects.items) |link_object| {
2259 switch (link_object) {
2260 .system_lib => |name| self.linkSystemLibrary(name),
2261 else => continue,
2262 }
2263 }
2264
2265 // Inherit dependencies on darwin frameworks
2266 if (self.target.isDarwin() and !other.isDynamicLibrary()) {
2267 var it = other.frameworks.iterator();
2268 while (it.next()) |framework| {
2269 self.frameworks.insert(framework.*) catch unreachable;
2270 }
2271 }
2272 }2125 }
22732126
2274 fn makePackageCmd(self: *LibExeObjStep, pkg: Pkg, zig_args: *ArrayList([]const u8)) error{OutOfMemory}!void {2127 fn makePackageCmd(self: *LibExeObjStep, pkg: Pkg, zig_args: *ArrayList([]const u8)) error{OutOfMemory}!void {
...@@ -2322,6 +2175,31 @@ pub const LibExeObjStep = struct {...@@ -2322,6 +2175,31 @@ pub const LibExeObjStep = struct {
2322 if (self.root_src) |root_src| try zig_args.append(root_src.getPath(builder));2175 if (self.root_src) |root_src| try zig_args.append(root_src.getPath(builder));
23232176
2324 var prev_has_extra_flags = false;2177 var prev_has_extra_flags = false;
2178
2179 // Resolve transitive dependencies
2180 for (self.link_objects.items) |link_object| {
2181 switch (link_object) {
2182 .other_step => |other| {
2183 // Inherit dependency on system libraries
2184 for (other.link_objects.items) |other_link_object| {
2185 switch (other_link_object) {
2186 .system_lib => |name| self.linkSystemLibrary(name),
2187 else => continue,
2188 }
2189 }
2190
2191 // Inherit dependencies on darwin frameworks
2192 if (!other.isDynamicLibrary()) {
2193 var it = other.frameworks.iterator();
2194 while (it.next()) |framework| {
2195 self.frameworks.insert(framework.*) catch unreachable;
2196 }
2197 }
2198 },
2199 else => continue,
2200 }
2201 }
2202
2325 for (self.link_objects.items) |link_object| {2203 for (self.link_objects.items) |link_object| {
2326 switch (link_object) {2204 switch (link_object) {
2327 .static_path => |static_path| try zig_args.append(static_path.getPath(builder)),2205 .static_path => |static_path| try zig_args.append(static_path.getPath(builder)),
...@@ -2395,41 +2273,6 @@ pub const LibExeObjStep = struct {...@@ -2395,41 +2273,6 @@ pub const LibExeObjStep = struct {
2395 }2273 }
2396 }2274 }
23972275
2398 if (self.build_options_contents.items.len > 0 or
2399 self.build_options_artifact_args.items.len > 0 or
2400 self.build_options_file_source_args.items.len > 0)
2401 {
2402 // Render build artifact and write file options at the last minute, now that the path is known.
2403 //
2404 // Note that pathFromRoot uses resolve path, so this will have
2405 // correct behavior even if getOutputPath is already absolute.
2406 for (self.build_options_artifact_args.items) |item| {
2407 self.addBuildOption(
2408 []const u8,
2409 item.name,
2410 self.builder.pathFromRoot(item.artifact.getOutputSource().getPath(self.builder)),
2411 );
2412 }
2413 for (self.build_options_file_source_args.items) |item| {
2414 self.addBuildOption(
2415 []const u8,
2416 item.name,
2417 item.source.getPath(self.builder),
2418 );
2419 }
2420
2421 const build_options_file = try fs.path.join(
2422 builder.allocator,
2423 &[_][]const u8{ builder.cache_root, builder.fmt("{s}_build_options.zig", .{self.name}) },
2424 );
2425 const path_from_root = builder.pathFromRoot(build_options_file);
2426 try fs.cwd().writeFile(path_from_root, self.build_options_contents.items);
2427 try zig_args.append("--pkg-begin");
2428 try zig_args.append("build_options");
2429 try zig_args.append(path_from_root);
2430 try zig_args.append("--pkg-end");
2431 }
2432
2433 if (self.image_base) |image_base| {2276 if (self.image_base) |image_base| {
2434 try zig_args.append("--image-base");2277 try zig_args.append("--image-base");
2435 try zig_args.append(builder.fmt("0x{x}", .{image_base}));2278 try zig_args.append(builder.fmt("0x{x}", .{image_base}));
...@@ -2547,6 +2390,9 @@ pub const LibExeObjStep = struct {...@@ -2547,6 +2390,9 @@ pub const LibExeObjStep = struct {
2547 try zig_args.append("-mcmodel");2390 try zig_args.append("-mcmodel");
2548 try zig_args.append(@tagName(self.code_model));2391 try zig_args.append(@tagName(self.code_model));
2549 }2392 }
2393 if (self.wasi_exec_model) |model| {
2394 try zig_args.append(builder.fmt("-mexec-model={s}", .{@tagName(model)}));
2395 }
25502396
2551 if (!self.target.isNative()) {2397 if (!self.target.isNative()) {
2552 try zig_args.append("-target");2398 try zig_args.append("-target");
...@@ -2719,6 +2565,14 @@ pub const LibExeObjStep = struct {...@@ -2719,6 +2565,14 @@ pub const LibExeObjStep = struct {
2719 zig_args.append("-framework") catch unreachable;2565 zig_args.append("-framework") catch unreachable;
2720 zig_args.append(framework.*) catch unreachable;2566 zig_args.append(framework.*) catch unreachable;
2721 }2567 }
2568 } else {
2569 if (self.framework_dirs.items.len > 0) {
2570 warn("Framework directories have been added for a non-darwin target, this will have no affect on the build\n", .{});
2571 }
2572
2573 if (self.frameworks.count() > 0) {
2574 warn("Frameworks have been added for a non-darwin target, this will have no affect on the build\n", .{});
2575 }
2722 }2576 }
27232577
2724 if (builder.sysroot) |sysroot| {2578 if (builder.sysroot) |sysroot| {
...@@ -3026,7 +2880,8 @@ pub const InstallDirStep = struct {...@@ -3026,7 +2880,8 @@ pub const InstallDirStep = struct {
3026 const self = @fieldParentPtr(InstallDirStep, "step", step);2880 const self = @fieldParentPtr(InstallDirStep, "step", step);
3027 const dest_prefix = self.builder.getInstallPath(self.options.install_dir, self.options.install_subdir);2881 const dest_prefix = self.builder.getInstallPath(self.options.install_dir, self.options.install_subdir);
3028 const full_src_dir = self.builder.pathFromRoot(self.options.source_dir);2882 const full_src_dir = self.builder.pathFromRoot(self.options.source_dir);
3029 const src_dir = try std.fs.cwd().openDir(full_src_dir, .{ .iterate = true });2883 var src_dir = try std.fs.cwd().openDir(full_src_dir, .{ .iterate = true });
2884 defer src_dir.close();
3030 var it = try src_dir.walk(self.builder.allocator);2885 var it = try src_dir.walk(self.builder.allocator);
3031 next_entry: while (try it.next()) |entry| {2886 next_entry: while (try it.next()) |entry| {
3032 for (self.options.exclude_extensions) |ext| {2887 for (self.options.exclude_extensions) |ext| {
...@@ -3131,6 +2986,7 @@ pub const Step = struct {...@@ -3131,6 +2986,7 @@ pub const Step = struct {
3131 run,2986 run,
3132 check_file,2987 check_file,
3133 install_raw,2988 install_raw,
2989 options,
3134 custom,2990 custom,
3135 };2991 };
31362992
...@@ -3302,43 +3158,6 @@ test "Builder.dupePkg()" {...@@ -3302,43 +3158,6 @@ test "Builder.dupePkg()" {
3302 try std.testing.expect(dupe_deps[0].path.path.ptr != pkg_dep.path.path.ptr);3158 try std.testing.expect(dupe_deps[0].path.path.ptr != pkg_dep.path.path.ptr);
3303}3159}
33043160
3305test "LibExeObjStep.addBuildOption" {
3306 if (builtin.os.tag == .wasi) return error.SkipZigTest;
3307
3308 var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
3309 defer arena.deinit();
3310 var builder = try Builder.create(
3311 &arena.allocator,
3312 "test",
3313 "test",
3314 "test",
3315 "test",
3316 );
3317 defer builder.destroy();
3318
3319 var exe = builder.addExecutable("not_an_executable", "/not/an/executable.zig");
3320 exe.addBuildOption(usize, "option1", 1);
3321 exe.addBuildOption(?usize, "option2", null);
3322 exe.addBuildOption([]const u8, "string", "zigisthebest");
3323 exe.addBuildOption(?[]const u8, "optional_string", null);
3324 exe.addBuildOption(std.SemanticVersion, "semantic_version", try std.SemanticVersion.parse("0.1.2-foo+bar"));
3325
3326 try std.testing.expectEqualStrings(
3327 \\pub const option1: usize = 1;
3328 \\pub const option2: ?usize = null;
3329 \\pub const string: []const u8 = "zigisthebest";
3330 \\pub const optional_string: ?[]const u8 = null;
3331 \\pub const semantic_version: @import("std").SemanticVersion = .{
3332 \\ .major = 0,
3333 \\ .minor = 1,
3334 \\ .patch = 2,
3335 \\ .pre = "foo",
3336 \\ .build = "bar",
3337 \\};
3338 \\
3339 , exe.build_options_contents.items);
3340}
3341
3342test "LibExeObjStep.addPackage" {3161test "LibExeObjStep.addPackage" {
3343 if (builtin.os.tag == .wasi) return error.SkipZigTest;3162 if (builtin.os.tag == .wasi) return error.SkipZigTest;
33443163
lib/std/build/CheckFileStep.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const build = std.build;2const build = std.build;
8const Step = build.Step;3const Step = build.Step;
lib/std/build/FmtStep.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const build = @import("../build.zig");2const build = @import("../build.zig");
8const Step = build.Step;3const Step = build.Step;
lib/std/build/InstallRawStep.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
72
8const Allocator = std.mem.Allocator;3const Allocator = std.mem.Allocator;
lib/std/build/OptionsStep.zig created+257
...@@ -0,0 +1,257 @@
1const std = @import("../std.zig");
2const build = std.build;
3const fs = std.fs;
4const Step = build.Step;
5const Builder = build.Builder;
6const GeneratedFile = build.GeneratedFile;
7const LibExeObjStep = build.LibExeObjStep;
8const FileSource = build.FileSource;
9
10const OptionsStep = @This();
11
12step: Step,
13generated_file: GeneratedFile,
14builder: *Builder,
15
16contents: std.ArrayList(u8),
17artifact_args: std.ArrayList(OptionArtifactArg),
18file_source_args: std.ArrayList(OptionFileSourceArg),
19
20pub fn create(builder: *Builder) *OptionsStep {
21 const self = builder.allocator.create(OptionsStep) catch unreachable;
22 self.* = .{
23 .builder = builder,
24 .step = Step.init(.options, "options", builder.allocator, make),
25 .generated_file = undefined,
26 .contents = std.ArrayList(u8).init(builder.allocator),
27 .artifact_args = std.ArrayList(OptionArtifactArg).init(builder.allocator),
28 .file_source_args = std.ArrayList(OptionFileSourceArg).init(builder.allocator),
29 };
30 self.generated_file = .{ .step = &self.step };
31
32 return self;
33}
34
35pub fn addOption(self: *OptionsStep, comptime T: type, name: []const u8, value: T) void {
36 const out = self.contents.writer();
37 switch (T) {
38 []const []const u8 => {
39 out.print("pub const {}: []const []const u8 = &[_][]const u8{{\n", .{std.zig.fmtId(name)}) catch unreachable;
40 for (value) |slice| {
41 out.print(" \"{}\",\n", .{std.zig.fmtEscapes(slice)}) catch unreachable;
42 }
43 out.writeAll("};\n") catch unreachable;
44 return;
45 },
46 [:0]const u8 => {
47 out.print("pub const {}: [:0]const u8 = \"{}\";\n", .{ std.zig.fmtId(name), std.zig.fmtEscapes(value) }) catch unreachable;
48 return;
49 },
50 []const u8 => {
51 out.print("pub const {}: []const u8 = \"{}\";\n", .{ std.zig.fmtId(name), std.zig.fmtEscapes(value) }) catch unreachable;
52 return;
53 },
54 ?[:0]const u8 => {
55 out.print("pub const {}: ?[:0]const u8 = ", .{std.zig.fmtId(name)}) catch unreachable;
56 if (value) |payload| {
57 out.print("\"{}\";\n", .{std.zig.fmtEscapes(payload)}) catch unreachable;
58 } else {
59 out.writeAll("null;\n") catch unreachable;
60 }
61 return;
62 },
63 ?[]const u8 => {
64 out.print("pub const {}: ?[]const u8 = ", .{std.zig.fmtId(name)}) catch unreachable;
65 if (value) |payload| {
66 out.print("\"{}\";\n", .{std.zig.fmtEscapes(payload)}) catch unreachable;
67 } else {
68 out.writeAll("null;\n") catch unreachable;
69 }
70 return;
71 },
72 std.builtin.Version => {
73 out.print(
74 \\pub const {}: @import("std").builtin.Version = .{{
75 \\ .major = {d},
76 \\ .minor = {d},
77 \\ .patch = {d},
78 \\}};
79 \\
80 , .{
81 std.zig.fmtId(name),
82
83 value.major,
84 value.minor,
85 value.patch,
86 }) catch unreachable;
87 },
88 std.SemanticVersion => {
89 out.print(
90 \\pub const {}: @import("std").SemanticVersion = .{{
91 \\ .major = {d},
92 \\ .minor = {d},
93 \\ .patch = {d},
94 \\
95 , .{
96 std.zig.fmtId(name),
97
98 value.major,
99 value.minor,
100 value.patch,
101 }) catch unreachable;
102 if (value.pre) |some| {
103 out.print(" .pre = \"{}\",\n", .{std.zig.fmtEscapes(some)}) catch unreachable;
104 }
105 if (value.build) |some| {
106 out.print(" .build = \"{}\",\n", .{std.zig.fmtEscapes(some)}) catch unreachable;
107 }
108 out.writeAll("};\n") catch unreachable;
109 return;
110 },
111 else => {},
112 }
113 switch (@typeInfo(T)) {
114 .Enum => |enum_info| {
115 out.print("pub const {} = enum {{\n", .{std.zig.fmtId(@typeName(T))}) catch unreachable;
116 inline for (enum_info.fields) |field| {
117 out.print(" {},\n", .{std.zig.fmtId(field.name)}) catch unreachable;
118 }
119 out.writeAll("};\n") catch unreachable;
120 },
121 else => {},
122 }
123 out.print("pub const {}: {s} = {};\n", .{ std.zig.fmtId(name), @typeName(T), value }) catch unreachable;
124}
125
126/// The value is the path in the cache dir.
127/// Adds a dependency automatically.
128pub fn addOptionFileSource(
129 self: *OptionsStep,
130 name: []const u8,
131 source: FileSource,
132) void {
133 self.file_source_args.append(.{
134 .name = name,
135 .source = source.dupe(self.builder),
136 }) catch unreachable;
137 source.addStepDependencies(&self.step);
138}
139
140/// The value is the path in the cache dir.
141/// Adds a dependency automatically.
142pub fn addOptionArtifact(self: *OptionsStep, name: []const u8, artifact: *LibExeObjStep) void {
143 self.artifact_args.append(.{ .name = self.builder.dupe(name), .artifact = artifact }) catch unreachable;
144 self.step.dependOn(&artifact.step);
145}
146
147pub fn getPackage(self: OptionsStep, package_name: []const u8) build.Pkg {
148 return .{ .name = package_name, .path = self.getSource() };
149}
150
151pub fn getSource(self: OptionsStep) FileSource {
152 return .{ .generated = &self.generated_file };
153}
154
155fn make(step: *Step) !void {
156 const self = @fieldParentPtr(OptionsStep, "step", step);
157
158 for (self.artifact_args.items) |item| {
159 self.addOption(
160 []const u8,
161 item.name,
162 self.builder.pathFromRoot(item.artifact.getOutputSource().getPath(self.builder)),
163 );
164 }
165
166 for (self.file_source_args.items) |item| {
167 self.addOption(
168 []const u8,
169 item.name,
170 item.source.getPath(self.builder),
171 );
172 }
173
174 const options_directory = self.builder.pathFromRoot(
175 try fs.path.join(
176 self.builder.allocator,
177 &[_][]const u8{ self.builder.cache_root, "options" },
178 ),
179 );
180
181 try fs.cwd().makePath(options_directory);
182
183 const options_file = try fs.path.join(
184 self.builder.allocator,
185 &[_][]const u8{ options_directory, &self.hashContentsToFileName() },
186 );
187
188 try fs.cwd().writeFile(options_file, self.contents.items);
189
190 self.generated_file.path = options_file;
191}
192
193fn hashContentsToFileName(self: *OptionsStep) [64]u8 {
194 // This implementation is copied from `WriteFileStep.make`
195
196 var hash = std.crypto.hash.blake2.Blake2b384.init(.{});
197
198 // Random bytes to make OptionsStep unique. Refresh this with
199 // new random bytes when OptionsStep implementation is modified
200 // in a non-backwards-compatible way.
201 hash.update("yL0Ya4KkmcCjBlP8");
202 hash.update(self.contents.items);
203
204 var digest: [48]u8 = undefined;
205 hash.final(&digest);
206 var hash_basename: [64]u8 = undefined;
207 _ = fs.base64_encoder.encode(&hash_basename, &digest);
208 return hash_basename;
209}
210
211const OptionArtifactArg = struct {
212 name: []const u8,
213 artifact: *LibExeObjStep,
214};
215
216const OptionFileSourceArg = struct {
217 name: []const u8,
218 source: FileSource,
219};
220
221test "OptionsStep" {
222 if (std.builtin.os.tag == .wasi) return error.SkipZigTest;
223
224 var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
225 defer arena.deinit();
226 var builder = try Builder.create(
227 &arena.allocator,
228 "test",
229 "test",
230 "test",
231 "test",
232 );
233 defer builder.destroy();
234
235 const options = builder.addOptions();
236
237 options.addOption(usize, "option1", 1);
238 options.addOption(?usize, "option2", null);
239 options.addOption([]const u8, "string", "zigisthebest");
240 options.addOption(?[]const u8, "optional_string", null);
241 options.addOption(std.SemanticVersion, "semantic_version", try std.SemanticVersion.parse("0.1.2-foo+bar"));
242
243 try std.testing.expectEqualStrings(
244 \\pub const option1: usize = 1;
245 \\pub const option2: ?usize = null;
246 \\pub const string: []const u8 = "zigisthebest";
247 \\pub const optional_string: ?[]const u8 = null;
248 \\pub const semantic_version: @import("std").SemanticVersion = .{
249 \\ .major = 0,
250 \\ .minor = 1,
251 \\ .patch = 2,
252 \\ .pre = "foo",
253 \\ .build = "bar",
254 \\};
255 \\
256 , options.contents.items);
257}
lib/std/build/RunStep.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const build = std.build;3const build = std.build;
lib/std/build/TranslateCStep.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const build = std.build;2const build = std.build;
8const Step = build.Step;3const Step = build.Step;
lib/std/build/WriteFileStep.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const build = @import("../build.zig");2const build = @import("../build.zig");
8const Step = build.Step;3const Step = build.Step;
lib/std/builtin.zig+8-12
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
72
8// These are all deprecated.3// These are all deprecated.
...@@ -237,7 +232,7 @@ pub const TypeInfo = union(enum) {...@@ -237,7 +232,7 @@ pub const TypeInfo = union(enum) {
237 /// This field is an optional type.232 /// This field is an optional type.
238 /// The type of the sentinel is the element type of the pointer, which is233 /// The type of the sentinel is the element type of the pointer, which is
239 /// the value of the `child` field in this struct. However there is no way234 /// the value of the `child` field in this struct. However there is no way
240 /// to refer to that type here, so we use `var`.235 /// to refer to that type here, so we use `anytype`.
241 sentinel: anytype,236 sentinel: anytype,
242237
243 /// This data structure is used by the Zig language code generation and238 /// This data structure is used by the Zig language code generation and
...@@ -259,7 +254,7 @@ pub const TypeInfo = union(enum) {...@@ -259,7 +254,7 @@ pub const TypeInfo = union(enum) {
259 /// This field is an optional type.254 /// This field is an optional type.
260 /// The type of the sentinel is the element type of the array, which is255 /// The type of the sentinel is the element type of the array, which is
261 /// the value of the `child` field in this struct. However there is no way256 /// the value of the `child` field in this struct. However there is no way
262 /// to refer to that type here, so we use `var`.257 /// to refer to that type here, so we use `anytype`.
263 sentinel: anytype,258 sentinel: anytype,
264 };259 };
265260
...@@ -671,7 +666,12 @@ pub const PanicFn = fn ([]const u8, ?*StackTrace) noreturn;...@@ -671,7 +666,12 @@ pub const PanicFn = fn ([]const u8, ?*StackTrace) noreturn;
671666
672/// This function is used by the Zig language code generation and667/// This function is used by the Zig language code generation and
673/// therefore must be kept in sync with the compiler implementation.668/// therefore must be kept in sync with the compiler implementation.
674pub const panic: PanicFn = if (@hasDecl(root, "panic")) root.panic else default_panic;669pub const panic: PanicFn = if (@hasDecl(root, "panic"))
670 root.panic
671else if (@hasDecl(root, "os") and @hasDecl(root.os, "panic"))
672 root.os.panic
673else
674 default_panic;
675675
676/// This function is used by the Zig language code generation and676/// This function is used by the Zig language code generation and
677/// therefore must be kept in sync with the compiler implementation.677/// therefore must be kept in sync with the compiler implementation.
...@@ -684,10 +684,6 @@ pub fn default_panic(msg: []const u8, error_return_trace: ?*StackTrace) noreturn...@@ -684,10 +684,6 @@ pub fn default_panic(msg: []const u8, error_return_trace: ?*StackTrace) noreturn
684 @breakpoint();684 @breakpoint();
685 }685 }
686 }686 }
687 if (@hasDecl(root, "os") and @hasDecl(root.os, "panic")) {
688 root.os.panic(msg, error_return_trace);
689 unreachable;
690 }
691 switch (os.tag) {687 switch (os.tag) {
692 .freestanding => {688 .freestanding => {
693 while (true) {689 while (true) {
lib/std/c.zig+29-34
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = std.builtin;2const builtin = std.builtin;
8const page_size = std.mem.page_size;3const page_size = std.mem.page_size;
...@@ -35,11 +30,11 @@ pub usingnamespace switch (std.Target.current.os.tag) {...@@ -35,11 +30,11 @@ pub usingnamespace switch (std.Target.current.os.tag) {
35 else => struct {},30 else => struct {},
36};31};
3732
38pub fn getErrno(rc: anytype) c_int {33pub fn getErrno(rc: anytype) E {
39 if (rc == -1) {34 if (rc == -1) {
40 return _errno().*;35 return @intToEnum(E, _errno().*);
41 } else {36 } else {
42 return 0;37 return .SUCCESS;
43 }38 }
44}39}
4540
...@@ -270,22 +265,22 @@ pub extern "c" fn utimes(path: [*:0]const u8, times: *[2]timeval) c_int;...@@ -270,22 +265,22 @@ pub extern "c" fn utimes(path: [*:0]const u8, times: *[2]timeval) c_int;
270pub extern "c" fn utimensat(dirfd: fd_t, pathname: [*:0]const u8, times: *[2]timespec, flags: u32) c_int;265pub extern "c" fn utimensat(dirfd: fd_t, pathname: [*:0]const u8, times: *[2]timespec, flags: u32) c_int;
271pub extern "c" fn futimens(fd: fd_t, times: *const [2]timespec) c_int;266pub extern "c" fn futimens(fd: fd_t, times: *const [2]timespec) c_int;
272267
273pub extern "c" fn pthread_create(noalias newthread: *pthread_t, noalias attr: ?*const pthread_attr_t, start_routine: fn (?*c_void) callconv(.C) ?*c_void, noalias arg: ?*c_void) c_int;268pub extern "c" fn pthread_create(noalias newthread: *pthread_t, noalias attr: ?*const pthread_attr_t, start_routine: fn (?*c_void) callconv(.C) ?*c_void, noalias arg: ?*c_void) E;
274pub extern "c" fn pthread_attr_init(attr: *pthread_attr_t) c_int;269pub extern "c" fn pthread_attr_init(attr: *pthread_attr_t) E;
275pub extern "c" fn pthread_attr_setstack(attr: *pthread_attr_t, stackaddr: *c_void, stacksize: usize) c_int;270pub extern "c" fn pthread_attr_setstack(attr: *pthread_attr_t, stackaddr: *c_void, stacksize: usize) E;
276pub extern "c" fn pthread_attr_setstacksize(attr: *pthread_attr_t, stacksize: usize) c_int;271pub extern "c" fn pthread_attr_setstacksize(attr: *pthread_attr_t, stacksize: usize) E;
277pub extern "c" fn pthread_attr_setguardsize(attr: *pthread_attr_t, guardsize: usize) c_int;272pub extern "c" fn pthread_attr_setguardsize(attr: *pthread_attr_t, guardsize: usize) E;
278pub extern "c" fn pthread_attr_destroy(attr: *pthread_attr_t) c_int;273pub extern "c" fn pthread_attr_destroy(attr: *pthread_attr_t) E;
279pub extern "c" fn pthread_self() pthread_t;274pub extern "c" fn pthread_self() pthread_t;
280pub extern "c" fn pthread_join(thread: pthread_t, arg_return: ?*?*c_void) c_int;275pub extern "c" fn pthread_join(thread: pthread_t, arg_return: ?*?*c_void) E;
281pub extern "c" fn pthread_detach(thread: pthread_t) c_int;276pub extern "c" fn pthread_detach(thread: pthread_t) E;
282pub extern "c" fn pthread_atfork(277pub extern "c" fn pthread_atfork(
283 prepare: ?fn () callconv(.C) void,278 prepare: ?fn () callconv(.C) void,
284 parent: ?fn () callconv(.C) void,279 parent: ?fn () callconv(.C) void,
285 child: ?fn () callconv(.C) void,280 child: ?fn () callconv(.C) void,
286) c_int;281) c_int;
287pub extern "c" fn pthread_key_create(key: *pthread_key_t, destructor: ?fn (value: *c_void) callconv(.C) void) c_int;282pub extern "c" fn pthread_key_create(key: *pthread_key_t, destructor: ?fn (value: *c_void) callconv(.C) void) E;
288pub extern "c" fn pthread_key_delete(key: pthread_key_t) c_int;283pub extern "c" fn pthread_key_delete(key: pthread_key_t) E;
289pub extern "c" fn pthread_getspecific(key: pthread_key_t) ?*c_void;284pub extern "c" fn pthread_getspecific(key: pthread_key_t) ?*c_void;
290pub extern "c" fn pthread_setspecific(key: pthread_key_t, value: ?*c_void) c_int;285pub extern "c" fn pthread_setspecific(key: pthread_key_t, value: ?*c_void) c_int;
291pub extern "c" fn sem_init(sem: *sem_t, pshared: c_int, value: c_uint) c_int;286pub extern "c" fn sem_init(sem: *sem_t, pshared: c_int, value: c_uint) c_int;
...@@ -339,24 +334,24 @@ pub extern "c" fn dn_expand(...@@ -339,24 +334,24 @@ pub extern "c" fn dn_expand(
339) c_int;334) c_int;
340335
341pub const PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{};336pub const PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{};
342pub extern "c" fn pthread_mutex_lock(mutex: *pthread_mutex_t) c_int;337pub extern "c" fn pthread_mutex_lock(mutex: *pthread_mutex_t) E;
343pub extern "c" fn pthread_mutex_unlock(mutex: *pthread_mutex_t) c_int;338pub extern "c" fn pthread_mutex_unlock(mutex: *pthread_mutex_t) E;
344pub extern "c" fn pthread_mutex_trylock(mutex: *pthread_mutex_t) c_int;339pub extern "c" fn pthread_mutex_trylock(mutex: *pthread_mutex_t) E;
345pub extern "c" fn pthread_mutex_destroy(mutex: *pthread_mutex_t) c_int;340pub extern "c" fn pthread_mutex_destroy(mutex: *pthread_mutex_t) E;
346341
347pub const PTHREAD_COND_INITIALIZER = pthread_cond_t{};342pub const PTHREAD_COND_INITIALIZER = pthread_cond_t{};
348pub extern "c" fn pthread_cond_wait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t) c_int;343pub extern "c" fn pthread_cond_wait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t) E;
349pub extern "c" fn pthread_cond_timedwait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t, noalias abstime: *const timespec) c_int;344pub extern "c" fn pthread_cond_timedwait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t, noalias abstime: *const timespec) E;
350pub extern "c" fn pthread_cond_signal(cond: *pthread_cond_t) c_int;345pub extern "c" fn pthread_cond_signal(cond: *pthread_cond_t) E;
351pub extern "c" fn pthread_cond_broadcast(cond: *pthread_cond_t) c_int;346pub extern "c" fn pthread_cond_broadcast(cond: *pthread_cond_t) E;
352pub extern "c" fn pthread_cond_destroy(cond: *pthread_cond_t) c_int;347pub extern "c" fn pthread_cond_destroy(cond: *pthread_cond_t) E;
353348
354pub extern "c" fn pthread_rwlock_destroy(rwl: *pthread_rwlock_t) callconv(.C) c_int;349pub extern "c" fn pthread_rwlock_destroy(rwl: *pthread_rwlock_t) callconv(.C) E;
355pub extern "c" fn pthread_rwlock_rdlock(rwl: *pthread_rwlock_t) callconv(.C) c_int;350pub extern "c" fn pthread_rwlock_rdlock(rwl: *pthread_rwlock_t) callconv(.C) E;
356pub extern "c" fn pthread_rwlock_wrlock(rwl: *pthread_rwlock_t) callconv(.C) c_int;351pub extern "c" fn pthread_rwlock_wrlock(rwl: *pthread_rwlock_t) callconv(.C) E;
357pub extern "c" fn pthread_rwlock_tryrdlock(rwl: *pthread_rwlock_t) callconv(.C) c_int;352pub extern "c" fn pthread_rwlock_tryrdlock(rwl: *pthread_rwlock_t) callconv(.C) E;
358pub extern "c" fn pthread_rwlock_trywrlock(rwl: *pthread_rwlock_t) callconv(.C) c_int;353pub extern "c" fn pthread_rwlock_trywrlock(rwl: *pthread_rwlock_t) callconv(.C) E;
359pub extern "c" fn pthread_rwlock_unlock(rwl: *pthread_rwlock_t) callconv(.C) c_int;354pub extern "c" fn pthread_rwlock_unlock(rwl: *pthread_rwlock_t) callconv(.C) E;
360355
361pub const pthread_t = *opaque {};356pub const pthread_t = *opaque {};
362pub const FILE = opaque {};357pub const FILE = opaque {};
lib/std/c/darwin.zig+2-7
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const builtin = @import("builtin");3const builtin = @import("builtin");
...@@ -193,8 +188,8 @@ pub const pthread_attr_t = extern struct {...@@ -193,8 +188,8 @@ pub const pthread_attr_t = extern struct {
193188
194const pthread_t = std.c.pthread_t;189const pthread_t = std.c.pthread_t;
195pub extern "c" fn pthread_threadid_np(thread: ?pthread_t, thread_id: *u64) c_int;190pub extern "c" fn pthread_threadid_np(thread: ?pthread_t, thread_id: *u64) c_int;
196pub extern "c" fn pthread_setname_np(name: [*:0]const u8) c_int;191pub extern "c" fn pthread_setname_np(name: [*:0]const u8) E;
197pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) c_int;192pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
198193
199pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void;194pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void;
200195
lib/std/c/dragonfly.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7usingnamespace std.c;2usingnamespace std.c;
8extern "c" threadlocal var errno: c_int;3extern "c" threadlocal var errno: c_int;
lib/std/c/emscripten.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const pthread_mutex_t = extern struct {1pub const pthread_mutex_t = extern struct {
7 size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(4) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,2 size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(4) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
8};3};
lib/std/c/freebsd.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7usingnamespace std.c;2usingnamespace std.c;
83
lib/std/c/fuchsia.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const pthread_mutex_t = extern struct {1pub const pthread_mutex_t = extern struct {
7 size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,2 size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
8};3};
lib/std/c/haiku.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//1//
8const std = @import("../std.zig");2const std = @import("../std.zig");
9const builtin = std.builtin;3const builtin = std.builtin;
lib/std/c/hermit.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const pthread_mutex_t = extern struct {1pub const pthread_mutex_t = extern struct {
7 inner: usize = ~@as(usize, 0),2 inner: usize = ~@as(usize, 0),
8};3};
lib/std/c/linux.zig+2-7
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const maxInt = std.math.maxInt;2const maxInt = std.math.maxInt;
8const abi = std.Target.current.abi;3const abi = std.Target.current.abi;
...@@ -186,8 +181,8 @@ const __SIZEOF_PTHREAD_MUTEX_T = if (os_tag == .fuchsia) 40 else switch (abi) {...@@ -186,8 +181,8 @@ const __SIZEOF_PTHREAD_MUTEX_T = if (os_tag == .fuchsia) 40 else switch (abi) {
186};181};
187const __SIZEOF_SEM_T = 4 * @sizeOf(usize);182const __SIZEOF_SEM_T = 4 * @sizeOf(usize);
188183
189pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8) c_int;184pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8) E;
190pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) c_int;185pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
191186
192pub const RTLD_LAZY = 1;187pub const RTLD_LAZY = 1;
193pub const RTLD_NOW = 2;188pub const RTLD_NOW = 2;
lib/std/c/minix.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7pub const pthread_mutex_t = extern struct {2pub const pthread_mutex_t = extern struct {
8 size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,3 size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
lib/std/c/netbsd.zig+2-7
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
83
...@@ -95,5 +90,5 @@ pub const pthread_attr_t = extern struct {...@@ -95,5 +90,5 @@ pub const pthread_attr_t = extern struct {
9590
96pub const sem_t = ?*opaque {};91pub const sem_t = ?*opaque {};
9792
98pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8, arg: ?*c_void) c_int;93pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8, arg: ?*c_void) E;
99pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) c_int;94pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
lib/std/c/openbsd.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
83
lib/std/c/solaris.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const pthread_mutex_t = extern struct {1pub const pthread_mutex_t = extern struct {
7 __pthread_mutex_flag1: u16 = 0,2 __pthread_mutex_flag1: u16 = 0,
8 __pthread_mutex_flag2: u8 = 0,3 __pthread_mutex_flag2: u8 = 0,
lib/std/c/tokenizer.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const mem = std.mem;2const mem = std.mem;
83
lib/std/c/wasi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("../os/bits.zig");1usingnamespace @import("../os/bits.zig");
72
8extern threadlocal var errno: c_int;3extern threadlocal var errno: c_int;
lib/std/c/windows.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub extern "c" fn _errno() *c_int;1pub extern "c" fn _errno() *c_int;
72
8pub extern "c" fn _msize(memblock: ?*c_void) usize;3pub extern "c" fn _msize(memblock: ?*c_void) usize;
lib/std/child_process.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const cstr = std.cstr;2const cstr = std.cstr;
8const unicode = std.unicode;3const unicode = std.unicode;
lib/std/coff.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = std.builtin;1const builtin = std.builtin;
7const std = @import("std.zig");2const std = @import("std.zig");
8const io = std.io;3const io = std.io;
lib/std/compress.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
72
8pub const deflate = @import("compress/deflate.zig");3pub const deflate = @import("compress/deflate.zig");
lib/std/compress/deflate.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6//1//
7// Decompressor for DEFLATE data streams (RFC1951)2// Decompressor for DEFLATE data streams (RFC1951)
8//3//
lib/std/compress/gzip.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6//1//
7// Decompressor for GZIP data streams (RFC1952)2// Decompressor for GZIP data streams (RFC1952)
83
lib/std/compress/zlib.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6//1//
7// Decompressor for ZLIB data streams (RFC1950)2// Decompressor for ZLIB data streams (RFC1950)
83
lib/std/comptime_string_map.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const mem = std.mem;2const mem = std.mem;
83
lib/std/crypto.zig+9-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7/// Authenticated Encryption with Associated Data1/// Authenticated Encryption with Associated Data
8pub const aead = struct {2pub const aead = struct {
9 pub const aegis = struct {3 pub const aegis = struct {
...@@ -110,7 +104,16 @@ pub const onetimeauth = struct {...@@ -110,7 +104,16 @@ pub const onetimeauth = struct {
110///104///
111/// Password hashing functions must be used whenever sensitive data has to be directly derived from a password.105/// Password hashing functions must be used whenever sensitive data has to be directly derived from a password.
112pub const pwhash = struct {106pub const pwhash = struct {
107 pub const Encoding = enum {
108 phc,
109 crypt,
110 };
111 pub const KdfError = errors.Error || std.mem.Allocator.Error;
112 pub const HasherError = KdfError || @import("crypto/phc_encoding.zig").Error;
113 pub const Error = HasherError || error{AllocatorRequired};
114
113 pub const bcrypt = @import("crypto/bcrypt.zig");115 pub const bcrypt = @import("crypto/bcrypt.zig");
116 pub const scrypt = @import("crypto/scrypt.zig");
114 pub const pbkdf2 = @import("crypto/pbkdf2.zig").pbkdf2;117 pub const pbkdf2 = @import("crypto/pbkdf2.zig").pbkdf2;
115};118};
116119
lib/std/crypto/25519/curve25519.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const crypto = std.crypto;2const crypto = std.crypto;
83
lib/std/crypto/25519/ed25519.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const crypto = std.crypto;2const crypto = std.crypto;
8const debug = std.debug;3const debug = std.debug;
lib/std/crypto/25519/edwards25519.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const crypto = std.crypto;2const crypto = std.crypto;
8const debug = std.debug;3const debug = std.debug;
lib/std/crypto/25519/field.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const crypto = std.crypto;2const crypto = std.crypto;
8const readIntLittle = std.mem.readIntLittle;3const readIntLittle = std.mem.readIntLittle;
lib/std/crypto/25519/ristretto255.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const fmt = std.fmt;2const fmt = std.fmt;
83
lib/std/crypto/25519/scalar.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const mem = std.mem;2const mem = std.mem;
83
lib/std/crypto/25519/x25519.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const crypto = std.crypto;2const crypto = std.crypto;
8const mem = std.mem;3const mem = std.mem;
lib/std/crypto/aegis.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
8const mem = std.mem;2const mem = std.mem;
9const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/crypto/aes.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../std.zig");1const std = @import("../std.zig");
8const testing = std.testing;2const testing = std.testing;
9const builtin = std.builtin;3const builtin = std.builtin;
lib/std/crypto/aes/aesni.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../../std.zig");1const std = @import("../../std.zig");
8const mem = std.mem;2const mem = std.mem;
9const debug = std.debug;3const debug = std.debug;
lib/std/crypto/aes/armcrypto.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../../std.zig");1const std = @import("../../std.zig");
8const mem = std.mem;2const mem = std.mem;
9const debug = std.debug;3const debug = std.debug;
lib/std/crypto/aes/soft.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Based on Go stdlib implementation1// Based on Go stdlib implementation
72
8const std = @import("../../std.zig");3const std = @import("../../std.zig");
lib/std/crypto/aes_gcm.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
8const assert = std.debug.assert;2const assert = std.debug.assert;
9const builtin = std.builtin;3const builtin = std.builtin;
lib/std/crypto/aes_ocb.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
8const crypto = std.crypto;2const crypto = std.crypto;
9const aes = crypto.core.aes;3const aes = crypto.core.aes;
lib/std/crypto/bcrypt.zig+298-109
...@@ -1,26 +1,27 @@...@@ -1,26 +1,27 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
8const crypto = std.crypto;2const crypto = std.crypto;
3const debug = std.debug;
9const fmt = std.fmt;4const fmt = std.fmt;
10const math = std.math;5const math = std.math;
11const mem = std.mem;6const mem = std.mem;
12const debug = std.debug;7const pwhash = crypto.pwhash;
13const testing = std.testing;8const testing = std.testing;
14const utils = crypto.utils;9const utils = crypto.utils;
15const EncodingError = crypto.errors.EncodingError;10
16const PasswordVerificationError = crypto.errors.PasswordVerificationError;11const phc_format = @import("phc_encoding.zig");
12
13const KdfError = pwhash.KdfError;
14const HasherError = pwhash.HasherError;
15const EncodingError = phc_format.Error;
16const Error = pwhash.Error;
1717
18const salt_length: usize = 16;18const salt_length: usize = 16;
19const salt_str_length: usize = 22;19const salt_str_length: usize = 22;
20const ct_str_length: usize = 31;20const ct_str_length: usize = 31;
21const ct_length: usize = 24;21const ct_length: usize = 24;
22const dk_length: usize = ct_length - 1;
2223
23/// Length (in bytes) of a password hash24/// Length (in bytes) of a password hash in crypt encoding
24pub const hash_length: usize = 60;25pub const hash_length: usize = 60;
2526
26const State = struct {27const State = struct {
...@@ -139,71 +140,15 @@ const State = struct {...@@ -139,71 +140,15 @@ const State = struct {
139 }140 }
140};141};
141142
142// bcrypt has its own variant of base64, with its own alphabet and no padding143pub const Params = struct {
143const Codec = struct {144 rounds_log: u6,
144 const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
145
146 fn encode(b64: []u8, bin: []const u8) void {
147 var i: usize = 0;
148 var j: usize = 0;
149 while (i < bin.len) {
150 var c1 = bin[i];
151 i += 1;
152 b64[j] = alphabet[c1 >> 2];
153 j += 1;
154 c1 = (c1 & 3) << 4;
155 if (i >= bin.len) {
156 b64[j] = alphabet[c1];
157 j += 1;
158 break;
159 }
160 var c2 = bin[i];
161 i += 1;
162 c1 |= (c2 >> 4) & 0x0f;
163 b64[j] = alphabet[c1];
164 j += 1;
165 c1 = (c2 & 0x0f) << 2;
166 if (i >= bin.len) {
167 b64[j] = alphabet[c1];
168 j += 1;
169 break;
170 }
171 c2 = bin[i];
172 i += 1;
173 c1 |= (c2 >> 6) & 3;
174 b64[j] = alphabet[c1];
175 b64[j + 1] = alphabet[c2 & 0x3f];
176 j += 2;
177 }
178 debug.assert(j == b64.len);
179 }
180
181 fn decode(bin: []u8, b64: []const u8) EncodingError!void {
182 var i: usize = 0;
183 var j: usize = 0;
184 while (j < bin.len) {
185 const c1 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i]) orelse return error.InvalidEncoding);
186 const c2 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i + 1]) orelse return error.InvalidEncoding);
187 bin[j] = (c1 << 2) | ((c2 & 0x30) >> 4);
188 j += 1;
189 if (j >= bin.len) {
190 break;
191 }
192 const c3 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i + 2]) orelse return error.InvalidEncoding);
193 bin[j] = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2);
194 j += 1;
195 if (j >= bin.len) {
196 break;
197 }
198 const c4 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i + 3]) orelse return error.InvalidEncoding);
199 bin[j] = ((c3 & 0x03) << 6) | c4;
200 j += 1;
201 i += 4;
202 }
203 }
204};145};
205146
206fn strHashInternal(password: []const u8, rounds_log: u6, salt: [salt_length]u8) ![hash_length]u8 {147pub fn bcrypt(
148 password: []const u8,
149 salt: [salt_length]u8,
150 params: Params,
151) [dk_length]u8 {
207 var state = State{};152 var state = State{};
208 var password_buf: [73]u8 = undefined;153 var password_buf: [73]u8 = undefined;
209 const trimmed_len = math.min(password.len, password_buf.len - 1);154 const trimmed_len = math.min(password.len, password_buf.len - 1);
...@@ -212,7 +157,7 @@ fn strHashInternal(password: []const u8, rounds_log: u6, salt: [salt_length]u8)...@@ -212,7 +157,7 @@ fn strHashInternal(password: []const u8, rounds_log: u6, salt: [salt_length]u8)
212 var passwordZ = password_buf[0 .. trimmed_len + 1];157 var passwordZ = password_buf[0 .. trimmed_len + 1];
213 state.expand(salt[0..], passwordZ);158 state.expand(salt[0..], passwordZ);
214159
215 const rounds: u64 = @as(u64, 1) << rounds_log;160 const rounds: u64 = @as(u64, 1) << params.rounds_log;
216 var k: u64 = 0;161 var k: u64 = 0;
217 while (k < rounds) : (k += 1) {162 while (k < rounds) : (k += 1) {
218 state.expand0(passwordZ);163 state.expand0(passwordZ);
...@@ -230,18 +175,203 @@ fn strHashInternal(password: []const u8, rounds_log: u6, salt: [salt_length]u8)...@@ -230,18 +175,203 @@ fn strHashInternal(password: []const u8, rounds_log: u6, salt: [salt_length]u8)
230 for (cdata) |c, i| {175 for (cdata) |c, i| {
231 mem.writeIntBig(u32, ct[i * 4 ..][0..4], c);176 mem.writeIntBig(u32, ct[i * 4 ..][0..4], c);
232 }177 }
178 return ct[0..dk_length].*;
179}
233180
234 var salt_str: [salt_str_length]u8 = undefined;181const crypt_format = struct {
235 Codec.encode(salt_str[0..], salt[0..]);182 /// String prefix for bcrypt
183 pub const prefix = "$2";
184
185 // bcrypt has its own variant of base64, with its own alphabet and no padding
186 const Codec = struct {
187 const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
188
189 fn encode(b64: []u8, bin: []const u8) void {
190 var i: usize = 0;
191 var j: usize = 0;
192 while (i < bin.len) {
193 var c1 = bin[i];
194 i += 1;
195 b64[j] = alphabet[c1 >> 2];
196 j += 1;
197 c1 = (c1 & 3) << 4;
198 if (i >= bin.len) {
199 b64[j] = alphabet[c1];
200 j += 1;
201 break;
202 }
203 var c2 = bin[i];
204 i += 1;
205 c1 |= (c2 >> 4) & 0x0f;
206 b64[j] = alphabet[c1];
207 j += 1;
208 c1 = (c2 & 0x0f) << 2;
209 if (i >= bin.len) {
210 b64[j] = alphabet[c1];
211 j += 1;
212 break;
213 }
214 c2 = bin[i];
215 i += 1;
216 c1 |= (c2 >> 6) & 3;
217 b64[j] = alphabet[c1];
218 b64[j + 1] = alphabet[c2 & 0x3f];
219 j += 2;
220 }
221 debug.assert(j == b64.len);
222 }
236223
237 var ct_str: [ct_str_length]u8 = undefined;224 fn decode(bin: []u8, b64: []const u8) EncodingError!void {
238 Codec.encode(ct_str[0..], ct[0 .. ct.len - 1]);225 var i: usize = 0;
226 var j: usize = 0;
227 while (j < bin.len) {
228 const c1 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i]) orelse
229 return EncodingError.InvalidEncoding);
230 const c2 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i + 1]) orelse
231 return EncodingError.InvalidEncoding);
232 bin[j] = (c1 << 2) | ((c2 & 0x30) >> 4);
233 j += 1;
234 if (j >= bin.len) {
235 break;
236 }
237 const c3 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i + 2]) orelse
238 return EncodingError.InvalidEncoding);
239 bin[j] = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2);
240 j += 1;
241 if (j >= bin.len) {
242 break;
243 }
244 const c4 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i + 3]) orelse
245 return EncodingError.InvalidEncoding);
246 bin[j] = ((c3 & 0x03) << 6) | c4;
247 j += 1;
248 i += 4;
249 }
250 }
251 };
252
253 fn strHashInternal(
254 password: []const u8,
255 salt: [salt_length]u8,
256 params: Params,
257 ) [hash_length]u8 {
258 var dk = bcrypt(password, salt, params);
259
260 var salt_str: [salt_str_length]u8 = undefined;
261 Codec.encode(salt_str[0..], salt[0..]);
262
263 var ct_str: [ct_str_length]u8 = undefined;
264 Codec.encode(ct_str[0..], dk[0..]);
265
266 var s_buf: [hash_length]u8 = undefined;
267 const s = fmt.bufPrint(
268 s_buf[0..],
269 "{s}b${d}{d}${s}{s}",
270 .{ prefix, params.rounds_log / 10, params.rounds_log % 10, salt_str, ct_str },
271 ) catch unreachable;
272 debug.assert(s.len == s_buf.len);
273 return s_buf;
274 }
275};
239276
240 var s_buf: [hash_length]u8 = undefined;277/// Hash and verify passwords using the PHC format.
241 const s = fmt.bufPrint(s_buf[0..], "$2b${d}{d}${s}{s}", .{ rounds_log / 10, rounds_log % 10, salt_str, ct_str }) catch unreachable;278const PhcFormatHasher = struct {
242 debug.assert(s.len == s_buf.len);279 const alg_id = "bcrypt";
243 return s_buf;280 const BinValue = phc_format.BinValue;
244}281
282 const HashResult = struct {
283 alg_id: []const u8,
284 r: u6,
285 salt: BinValue(salt_length),
286 hash: BinValue(dk_length),
287 };
288
289 /// Return a non-deterministic hash of the password encoded as a PHC-format string
290 pub fn create(
291 password: []const u8,
292 params: Params,
293 buf: []u8,
294 ) HasherError![]const u8 {
295 var salt: [salt_length]u8 = undefined;
296 crypto.random.bytes(&salt);
297
298 const hash = bcrypt(password, salt, params);
299
300 return phc_format.serialize(HashResult{
301 .alg_id = alg_id,
302 .r = params.rounds_log,
303 .salt = try BinValue(salt_length).fromSlice(&salt),
304 .hash = try BinValue(dk_length).fromSlice(&hash),
305 }, buf);
306 }
307
308 /// Verify a password against a PHC-format encoded string
309 pub fn verify(
310 str: []const u8,
311 password: []const u8,
312 ) HasherError!void {
313 const hash_result = try phc_format.deserialize(HashResult, str);
314
315 if (!mem.eql(u8, hash_result.alg_id, alg_id)) return HasherError.PasswordVerificationFailed;
316 if (hash_result.salt.len != salt_length or hash_result.hash.len != dk_length)
317 return HasherError.InvalidEncoding;
318
319 const hash = bcrypt(password, hash_result.salt.buf, .{ .rounds_log = hash_result.r });
320 const expected_hash = hash_result.hash.constSlice();
321
322 if (!mem.eql(u8, &hash, expected_hash)) return HasherError.PasswordVerificationFailed;
323 }
324};
325
326/// Hash and verify passwords using the modular crypt format.
327const CryptFormatHasher = struct {
328 /// Length of a string returned by the create() function
329 pub const pwhash_str_length: usize = hash_length;
330
331 /// Return a non-deterministic hash of the password encoded into the modular crypt format
332 pub fn create(
333 password: []const u8,
334 params: Params,
335 buf: []u8,
336 ) HasherError![]const u8 {
337 if (buf.len < pwhash_str_length) return HasherError.NoSpaceLeft;
338
339 var salt: [salt_length]u8 = undefined;
340 crypto.random.bytes(&salt);
341
342 const hash = crypt_format.strHashInternal(password, salt, params);
343 mem.copy(u8, buf, &hash);
344
345 return buf[0..pwhash_str_length];
346 }
347
348 /// Verify a password against a string in modular crypt format
349 pub fn verify(
350 str: []const u8,
351 password: []const u8,
352 ) HasherError!void {
353 if (str.len != pwhash_str_length or str[3] != '$' or str[6] != '$')
354 return HasherError.InvalidEncoding;
355
356 const rounds_log_str = str[4..][0..2];
357 const rounds_log = fmt.parseInt(u6, rounds_log_str[0..], 10) catch
358 return HasherError.InvalidEncoding;
359
360 const salt_str = str[7..][0..salt_str_length];
361 var salt: [salt_length]u8 = undefined;
362 try crypt_format.Codec.decode(salt[0..], salt_str[0..]);
363
364 const wanted_s = crypt_format.strHashInternal(password, salt, .{ .rounds_log = rounds_log });
365 if (!mem.eql(u8, wanted_s[0..], str[0..])) return HasherError.PasswordVerificationFailed;
366 }
367};
368
369/// Options for hashing a password.
370pub const HashOptions = struct {
371 allocator: ?*mem.Allocator = null,
372 params: Params,
373 encoding: pwhash.Encoding,
374};
245375
246/// Compute a hash of a password using 2^rounds_log rounds of the bcrypt key stretching function.376/// Compute a hash of a password using 2^rounds_log rounds of the bcrypt key stretching function.
247/// bcrypt is a computationally expensive and cache-hard function, explicitly designed to slow down exhaustive searches.377/// bcrypt is a computationally expensive and cache-hard function, explicitly designed to slow down exhaustive searches.
...@@ -251,24 +381,32 @@ fn strHashInternal(password: []const u8, rounds_log: u6, salt: [salt_length]u8)...@@ -251,24 +381,32 @@ fn strHashInternal(password: []const u8, rounds_log: u6, salt: [salt_length]u8)
251/// IMPORTANT: by design, bcrypt silently truncates passwords to 72 bytes.381/// IMPORTANT: by design, bcrypt silently truncates passwords to 72 bytes.
252/// If this is an issue for your application, hash the password first using a function such as SHA-512,382/// If this is an issue for your application, hash the password first using a function such as SHA-512,
253/// and then use the resulting hash as the password parameter for bcrypt.383/// and then use the resulting hash as the password parameter for bcrypt.
254pub fn strHash(password: []const u8, rounds_log: u6) ![hash_length]u8 {384pub fn strHash(
255 var salt: [salt_length]u8 = undefined;385 password: []const u8,
256 crypto.random.bytes(&salt);386 options: HashOptions,
257 return strHashInternal(password, rounds_log, salt);387 out: []u8,
388) Error![]const u8 {
389 switch (options.encoding) {
390 .phc => return PhcFormatHasher.create(password, options.params, out),
391 .crypt => return CryptFormatHasher.create(password, options.params, out),
392 }
258}393}
259394
395/// Options for hash verification.
396pub const VerifyOptions = struct {
397 allocator: ?*mem.Allocator = null,
398};
399
260/// Verify that a previously computed hash is valid for a given password.400/// Verify that a previously computed hash is valid for a given password.
261pub fn strVerify(h: [hash_length]u8, password: []const u8) (EncodingError || PasswordVerificationError)!void {401pub fn strVerify(
262 if (!mem.eql(u8, "$2", h[0..2])) return error.InvalidEncoding;402 str: []const u8,
263 if (h[3] != '$' or h[6] != '$') return error.InvalidEncoding;403 password: []const u8,
264 const rounds_log_str = h[4..][0..2];404 _: VerifyOptions,
265 const salt_str = h[7..][0..salt_str_length];405) Error!void {
266 var salt: [salt_length]u8 = undefined;406 if (mem.startsWith(u8, str, crypt_format.prefix)) {
267 try Codec.decode(salt[0..], salt_str[0..]);407 return CryptFormatHasher.verify(str, password);
268 const rounds_log = fmt.parseInt(u6, rounds_log_str[0..], 10) catch return error.InvalidEncoding;408 } else {
269 const wanted_s = try strHashInternal(password, rounds_log, salt);409 return PhcFormatHasher.verify(str, password);
270 if (!mem.eql(u8, wanted_s[0..], h[0..])) {
271 return error.PasswordVerificationFailed;
272 }410 }
273}411}
274412
...@@ -276,20 +414,71 @@ test "bcrypt codec" {...@@ -276,20 +414,71 @@ test "bcrypt codec" {
276 var salt: [salt_length]u8 = undefined;414 var salt: [salt_length]u8 = undefined;
277 crypto.random.bytes(&salt);415 crypto.random.bytes(&salt);
278 var salt_str: [salt_str_length]u8 = undefined;416 var salt_str: [salt_str_length]u8 = undefined;
279 Codec.encode(salt_str[0..], salt[0..]);417 crypt_format.Codec.encode(salt_str[0..], salt[0..]);
280 var salt2: [salt_length]u8 = undefined;418 var salt2: [salt_length]u8 = undefined;
281 try Codec.decode(salt2[0..], salt_str[0..]);419 try crypt_format.Codec.decode(salt2[0..], salt_str[0..]);
282 try testing.expectEqualSlices(u8, salt[0..], salt2[0..]);420 try testing.expectEqualSlices(u8, salt[0..], salt2[0..]);
283}421}
284422
285test "bcrypt" {423test "bcrypt crypt format" {
286 const s = try strHash("password", 5);424 const hash_options = HashOptions{
287 try strVerify(s, "password");425 .params = .{ .rounds_log = 5 },
288 try testing.expectError(error.PasswordVerificationFailed, strVerify(s, "invalid password"));426 .encoding = .crypt,
289427 };
290 const long_s = try strHash("password" ** 100, 5);428 const verify_options = VerifyOptions{};
291 try strVerify(long_s, "password" ** 100);429
292 try strVerify(long_s, "password" ** 101);430 var buf: [hash_length]u8 = undefined;
431 const s = try strHash("password", hash_options, &buf);
432
433 try testing.expect(mem.startsWith(u8, s, crypt_format.prefix));
434 try strVerify(s, "password", verify_options);
435 try testing.expectError(
436 error.PasswordVerificationFailed,
437 strVerify(s, "invalid password", verify_options),
438 );
439
440 var long_buf: [hash_length]u8 = undefined;
441 const long_s = try strHash("password" ** 100, hash_options, &long_buf);
442
443 try testing.expect(mem.startsWith(u8, long_s, crypt_format.prefix));
444 try strVerify(long_s, "password" ** 100, verify_options);
445 try strVerify(long_s, "password" ** 101, verify_options);
446
447 try strVerify(
448 "$2b$08$WUQKyBCaKpziCwUXHiMVvu40dYVjkTxtWJlftl0PpjY2BxWSvFIEe",
449 "The devil himself",
450 verify_options,
451 );
452}
293453
294 try strVerify("$2b$08$WUQKyBCaKpziCwUXHiMVvu40dYVjkTxtWJlftl0PpjY2BxWSvFIEe".*, "The devil himself");454test "bcrypt phc format" {
455 const hash_options = HashOptions{
456 .params = .{ .rounds_log = 5 },
457 .encoding = .phc,
458 };
459 const verify_options = VerifyOptions{};
460 const prefix = "$bcrypt$";
461
462 var buf: [hash_length * 2]u8 = undefined;
463 const s = try strHash("password", hash_options, &buf);
464
465 try testing.expect(mem.startsWith(u8, s, prefix));
466 try strVerify(s, "password", verify_options);
467 try testing.expectError(
468 error.PasswordVerificationFailed,
469 strVerify(s, "invalid password", verify_options),
470 );
471
472 var long_buf: [hash_length * 2]u8 = undefined;
473 const long_s = try strHash("password" ** 100, hash_options, &long_buf);
474
475 try testing.expect(mem.startsWith(u8, long_s, prefix));
476 try strVerify(long_s, "password" ** 100, verify_options);
477 try strVerify(long_s, "password" ** 101, verify_options);
478
479 try strVerify(
480 "$bcrypt$r=5$2NopntlgE2lX3cTwr4qz8A$r3T7iKYQNnY4hAhGjk9RmuyvgrYJZwc",
481 "The devil himself",
482 verify_options,
483 );
295}484}
lib/std/crypto/benchmark.zig+44-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// zig run benchmark.zig --release-fast --zig-lib-dir ..1// zig run benchmark.zig --release-fast --zig-lib-dir ..
72
8const std = @import("../std.zig");3const std = @import("../std.zig");
...@@ -300,6 +295,43 @@ pub fn benchmarkAes8(comptime Aes: anytype, comptime count: comptime_int) !u64 {...@@ -300,6 +295,43 @@ pub fn benchmarkAes8(comptime Aes: anytype, comptime count: comptime_int) !u64 {
300 return throughput;295 return throughput;
301}296}
302297
298const CryptoPwhash = struct {
299 hashFn: anytype,
300 params: anytype,
301 name: []const u8,
302};
303const bcrypt_params = bcrypt.Params{ .rounds_log = 5 };
304const pwhashes = [_]CryptoPwhash{
305 CryptoPwhash{ .hashFn = bcrypt.strHash, .params = bcrypt_params, .name = "bcrypt" },
306 CryptoPwhash{ .hashFn = scrypt.strHash, .params = scrypt.Params.interactive, .name = "scrypt" },
307};
308
309fn benchmarkPwhash(
310 comptime hashFn: anytype,
311 comptime params: anytype,
312 comptime count: comptime_int,
313) !u64 {
314 const password = "testpass" ** 2;
315 const opts = .{ .allocator = std.testing.allocator, .params = params, .encoding = .phc };
316 var buf: [256]u8 = undefined;
317
318 var timer = try Timer.start();
319 const start = timer.lap();
320 {
321 var i: usize = 0;
322 while (i < count) : (i += 1) {
323 _ = try hashFn(password, opts, &buf);
324 mem.doNotOptimizeAway(&buf);
325 }
326 }
327 const end = timer.read();
328
329 const elapsed_s = @intToFloat(f64, end - start) / time.ns_per_s;
330 const throughput = @floatToInt(u64, count / elapsed_s);
331
332 return throughput;
333}
334
303fn usage() void {335fn usage() void {
304 std.debug.warn(336 std.debug.warn(
305 \\throughput_test [options]337 \\throughput_test [options]
...@@ -418,4 +450,11 @@ pub fn main() !void {...@@ -418,4 +450,11 @@ pub fn main() !void {
418 try stdout.print("{s:>17}: {:10} ops/s\n", .{ E.name, throughput });450 try stdout.print("{s:>17}: {:10} ops/s\n", .{ E.name, throughput });
419 }451 }
420 }452 }
453
454 inline for (pwhashes) |H| {
455 if (filter == null or std.mem.indexOf(u8, H.name, filter.?) != null) {
456 const throughput = try benchmarkPwhash(H.hashFn, H.params, mode(64));
457 try stdout.print("{s:>17}: {:10} ops/s\n", .{ H.name, throughput });
458 }
459 }
421}460}
lib/std/crypto/blake2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const mem = std.mem;2const mem = std.mem;
8const math = std.math;3const math = std.math;
lib/std/crypto/blake3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Translated from BLAKE3 reference implementation.1// Translated from BLAKE3 reference implementation.
7// Source: https://github.com/BLAKE3-team/BLAKE32// Source: https://github.com/BLAKE3-team/BLAKE3
83
lib/std/crypto/chacha20.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Based on public domain Supercop by Daniel J. Bernstein1// Based on public domain Supercop by Daniel J. Bernstein
72
8const std = @import("../std.zig");3const std = @import("../std.zig");
lib/std/crypto/ghash.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6//1//
7// Adapted from BearSSL's ctmul64 implementation originally written by Thomas Pornin <pornin@bolet.org>2// Adapted from BearSSL's ctmul64 implementation originally written by Thomas Pornin <pornin@bolet.org>
83
lib/std/crypto/gimli.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Gimli is a 384-bit permutation designed to achieve high security with high1// Gimli is a 384-bit permutation designed to achieve high security with high
7// performance across a broad range of platforms, including 64-bit Intel/AMD2// performance across a broad range of platforms, including 64-bit Intel/AMD
8// server CPUs, 64-bit and 32-bit ARM smartphone CPUs, 32-bit ARM3// server CPUs, 64-bit and 32-bit ARM smartphone CPUs, 32-bit ARM
lib/std/crypto/hkdf.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../std.zig");1const std = @import("../std.zig");
8const assert = std.debug.assert;2const assert = std.debug.assert;
9const hmac = std.crypto.auth.hmac;3const hmac = std.crypto.auth.hmac;
lib/std/crypto/hmac.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const crypto = std.crypto;2const crypto = std.crypto;
8const debug = std.debug;3const debug = std.debug;
lib/std/crypto/md5.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const mem = std.mem;2const mem = std.mem;
8const math = std.math;3const math = std.math;
lib/std/crypto/modes.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Based on Go stdlib implementation1// Based on Go stdlib implementation
72
8const std = @import("../std.zig");3const std = @import("../std.zig");
lib/std/crypto/pbkdf2.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
8const mem = std.mem;2const mem = std.mem;
9const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
lib/std/crypto/pcurves/p256.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
8const builtin = std.builtin;2const builtin = std.builtin;
9const crypto = std.crypto;3const crypto = std.crypto;
lib/std/crypto/pcurves/p256/field.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
8const common = @import("../common.zig");2const common = @import("../common.zig");
93
lib/std/crypto/pcurves/p256/scalar.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
8const builtin = std.builtin;2const builtin = std.builtin;
9const common = @import("../common.zig");3const common = @import("../common.zig");
lib/std/crypto/pcurves/tests.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
8const fmt = std.fmt;2const fmt = std.fmt;
9const testing = std.testing;3const testing = std.testing;
lib/std/crypto/phc_encoding.zig created+371
...@@ -0,0 +1,371 @@
1// https://github.com/P-H-C/phc-string-format
2
3const std = @import("std");
4const fmt = std.fmt;
5const io = std.io;
6const mem = std.mem;
7const meta = std.meta;
8
9const fields_delimiter = "$";
10const version_param_name = "v";
11const params_delimiter = ",";
12const kv_delimiter = "=";
13
14pub const Error = std.crypto.errors.EncodingError || error{NoSpaceLeft};
15
16const B64Decoder = std.base64.standard_no_pad.Decoder;
17const B64Encoder = std.base64.standard_no_pad.Encoder;
18
19/// A wrapped binary value whose maximum size is `max_len`.
20///
21/// This type must be used whenever a binary value is encoded in a PHC-formatted string.
22/// This includes `salt`, `hash`, and any other binary parameters such as keys.
23///
24/// Once initialized, the actual value can be read with the `constSlice()` function.
25pub fn BinValue(comptime max_len: usize) type {
26 return struct {
27 const Self = @This();
28 const capacity = max_len;
29 const max_encoded_length = B64Encoder.calcSize(max_len);
30
31 buf: [max_len]u8 = undefined,
32 len: usize = 0,
33
34 /// Wrap an existing byte slice
35 pub fn fromSlice(slice: []const u8) Error!Self {
36 if (slice.len > capacity) return Error.NoSpaceLeft;
37 var bin_value: Self = undefined;
38 mem.copy(u8, &bin_value.buf, slice);
39 bin_value.len = slice.len;
40 return bin_value;
41 }
42
43 /// Return the slice containing the actual value.
44 pub fn constSlice(self: Self) []const u8 {
45 return self.buf[0..self.len];
46 }
47
48 fn fromB64(self: *Self, str: []const u8) !void {
49 const len = B64Decoder.calcSizeForSlice(str) catch return Error.InvalidEncoding;
50 if (len > self.buf.len) return Error.NoSpaceLeft;
51 B64Decoder.decode(&self.buf, str) catch return Error.InvalidEncoding;
52 self.len = len;
53 }
54
55 fn toB64(self: Self, buf: []u8) ![]const u8 {
56 const value = self.constSlice();
57 const len = B64Encoder.calcSize(value.len);
58 if (len > buf.len) return Error.NoSpaceLeft;
59 return B64Encoder.encode(buf, value);
60 }
61 };
62}
63
64/// Deserialize a PHC-formatted string into a structure `HashResult`.
65///
66/// Required field in the `HashResult` structure:
67/// - `alg_id`: algorithm identifier
68/// Optional, special fields:
69/// - `alg_version`: algorithm version (unsigned integer)
70/// - `salt`: salt
71/// - `hash`: output of the hash function
72///
73/// Other fields will also be deserialized from the function parameters section.
74pub fn deserialize(comptime HashResult: type, str: []const u8) Error!HashResult {
75 var out = mem.zeroes(HashResult);
76 var it = mem.split(u8, str, fields_delimiter);
77 var set_fields: usize = 0;
78
79 while (true) {
80 // Read the algorithm identifier
81 if ((it.next() orelse return Error.InvalidEncoding).len != 0) return Error.InvalidEncoding;
82 out.alg_id = it.next() orelse return Error.InvalidEncoding;
83 set_fields += 1;
84
85 // Read the optional version number
86 var field = it.next() orelse break;
87 if (kvSplit(field)) |opt_version| {
88 if (mem.eql(u8, opt_version.key, version_param_name)) {
89 if (@hasField(HashResult, "alg_version")) {
90 const value_type_info = switch (@typeInfo(@TypeOf(out.alg_version))) {
91 .Optional => |opt| comptime @typeInfo(opt.child),
92 else => |t| t,
93 };
94 out.alg_version = fmt.parseUnsigned(
95 @Type(value_type_info),
96 opt_version.value,
97 10,
98 ) catch return Error.InvalidEncoding;
99 set_fields += 1;
100 }
101 field = it.next() orelse break;
102 }
103 } else |_| {}
104
105 // Read optional parameters
106 var has_params = false;
107 var it_params = mem.split(u8, field, params_delimiter);
108 while (it_params.next()) |params| {
109 const param = kvSplit(params) catch break;
110 var found = false;
111 inline for (comptime meta.fields(HashResult)) |p| {
112 if (mem.eql(u8, p.name, param.key)) {
113 switch (@typeInfo(p.field_type)) {
114 .Int => @field(out, p.name) = fmt.parseUnsigned(
115 p.field_type,
116 param.value,
117 10,
118 ) catch return Error.InvalidEncoding,
119 .Pointer => |ptr| {
120 if (!ptr.is_const) @compileError("Value slice must be constant");
121 @field(out, p.name) = param.value;
122 },
123 .Struct => try @field(out, p.name).fromB64(param.value),
124 else => std.debug.panic(
125 "Value for [{s}] must be an integer, a constant slice or a BinValue",
126 .{p.name},
127 ),
128 }
129 set_fields += 1;
130 found = true;
131 break;
132 }
133 }
134 if (!found) return Error.InvalidEncoding; // An unexpected parameter was found in the string
135 has_params = true;
136 }
137
138 // No separator between an empty parameters set and the salt
139 if (has_params) field = it.next() orelse break;
140
141 // Read an optional salt
142 if (@hasField(HashResult, "salt")) {
143 try out.salt.fromB64(field);
144 set_fields += 1;
145 } else {
146 return Error.InvalidEncoding;
147 }
148
149 // Read an optional hash
150 field = it.next() orelse break;
151 if (@hasField(HashResult, "hash")) {
152 try out.hash.fromB64(field);
153 set_fields += 1;
154 } else {
155 return Error.InvalidEncoding;
156 }
157 break;
158 }
159
160 // Check that all the required fields have been set, excluding optional values and parameters
161 // with default values
162 var expected_fields: usize = 0;
163 inline for (comptime meta.fields(HashResult)) |p| {
164 if (@typeInfo(p.field_type) != .Optional and p.default_value == null) {
165 expected_fields += 1;
166 }
167 }
168 if (set_fields < expected_fields) return Error.InvalidEncoding;
169
170 return out;
171}
172
173/// Serialize parameters into a PHC string.
174///
175/// Required field for `params`:
176/// - `alg_id`: algorithm identifier
177/// Optional, special fields:
178/// - `alg_version`: algorithm version (unsigned integer)
179/// - `salt`: salt
180/// - `hash`: output of the hash function
181///
182/// `params` can also include any additional parameters.
183pub fn serialize(params: anytype, str: []u8) Error![]const u8 {
184 var buf = io.fixedBufferStream(str);
185 try serializeTo(params, buf.writer());
186 return buf.getWritten();
187}
188
189/// Compute the number of bytes required to serialize `params`
190pub fn calcSize(params: anytype) usize {
191 var buf = io.countingWriter(io.null_writer);
192 serializeTo(params, buf.writer()) catch unreachable;
193 return @intCast(usize, buf.bytes_written);
194}
195
196fn serializeTo(params: anytype, out: anytype) !void {
197 const HashResult = @TypeOf(params);
198 try out.writeAll(fields_delimiter);
199 try out.writeAll(params.alg_id);
200
201 if (@hasField(HashResult, "alg_version")) {
202 if (@typeInfo(@TypeOf(params.alg_version)) == .Optional) {
203 if (params.alg_version) |alg_version| {
204 try out.print(
205 "{s}{s}{s}{}",
206 .{ fields_delimiter, version_param_name, kv_delimiter, alg_version },
207 );
208 }
209 } else {
210 try out.print(
211 "{s}{s}{s}{}",
212 .{ fields_delimiter, version_param_name, kv_delimiter, params.alg_version },
213 );
214 }
215 }
216
217 var has_params = false;
218 inline for (comptime meta.fields(HashResult)) |p| {
219 if (!(mem.eql(u8, p.name, "alg_id") or
220 mem.eql(u8, p.name, "alg_version") or
221 mem.eql(u8, p.name, "hash") or
222 mem.eql(u8, p.name, "salt")))
223 {
224 const value = @field(params, p.name);
225 try out.writeAll(if (has_params) params_delimiter else fields_delimiter);
226 if (@typeInfo(p.field_type) == .Struct) {
227 var buf: [@TypeOf(value).max_encoded_length]u8 = undefined;
228 try out.print("{s}{s}{s}", .{ p.name, kv_delimiter, try value.toB64(&buf) });
229 } else {
230 try out.print(
231 if (@typeInfo(@TypeOf(value)) == .Pointer) "{s}{s}{s}" else "{s}{s}{}",
232 .{ p.name, kv_delimiter, value },
233 );
234 }
235 has_params = true;
236 }
237 }
238
239 var has_salt = false;
240 if (@hasField(HashResult, "salt")) {
241 var buf: [@TypeOf(params.salt).max_encoded_length]u8 = undefined;
242 try out.print("{s}{s}", .{ fields_delimiter, try params.salt.toB64(&buf) });
243 has_salt = true;
244 }
245
246 if (@hasField(HashResult, "hash")) {
247 var buf: [@TypeOf(params.hash).max_encoded_length]u8 = undefined;
248 if (!has_salt) try out.writeAll(fields_delimiter);
249 try out.print("{s}{s}", .{ fields_delimiter, try params.hash.toB64(&buf) });
250 }
251}
252
253// Split a `key=value` string into `key` and `value`
254fn kvSplit(str: []const u8) !struct { key: []const u8, value: []const u8 } {
255 var it = mem.split(u8, str, kv_delimiter);
256 const key = it.next() orelse return Error.InvalidEncoding;
257 const value = it.next() orelse return Error.InvalidEncoding;
258 const ret = .{ .key = key, .value = value };
259 return ret;
260}
261
262test "phc format - encoding/decoding" {
263 const Input = struct {
264 str: []const u8,
265 HashResult: type,
266 };
267 const inputs = [_]Input{
268 .{
269 .str = "$argon2id$v=19$key=a2V5,m=4096,t=0,p=1$X1NhbHQAAAAAAAAAAAAAAA$bWh++MKN1OiFHKgIWTLvIi1iHicmHH7+Fv3K88ifFfI",
270 .HashResult = struct {
271 alg_id: []const u8,
272 alg_version: u16,
273 key: BinValue(16),
274 m: usize,
275 t: u64,
276 p: u32,
277 salt: BinValue(16),
278 hash: BinValue(32),
279 },
280 },
281 .{
282 .str = "$scrypt$v=1$ln=15,r=8,p=1$c2FsdHNhbHQ$dGVzdHBhc3M",
283 .HashResult = struct {
284 alg_id: []const u8,
285 alg_version: ?u30,
286 ln: u6,
287 r: u30,
288 p: u30,
289 salt: BinValue(16),
290 hash: BinValue(16),
291 },
292 },
293 .{
294 .str = "$scrypt",
295 .HashResult = struct { alg_id: []const u8 },
296 },
297 .{ .str = "$scrypt$v=1", .HashResult = struct { alg_id: []const u8, alg_version: u16 } },
298 .{
299 .str = "$scrypt$ln=15,r=8,p=1",
300 .HashResult = struct { alg_id: []const u8, alg_version: ?u30, ln: u6, r: u30, p: u30 },
301 },
302 .{
303 .str = "$scrypt$c2FsdHNhbHQ",
304 .HashResult = struct { alg_id: []const u8, salt: BinValue(16) },
305 },
306 .{
307 .str = "$scrypt$v=1$ln=15,r=8,p=1$c2FsdHNhbHQ",
308 .HashResult = struct {
309 alg_id: []const u8,
310 alg_version: u16,
311 ln: u6,
312 r: u30,
313 p: u30,
314 salt: BinValue(16),
315 },
316 },
317 .{
318 .str = "$scrypt$v=1$ln=15,r=8,p=1",
319 .HashResult = struct { alg_id: []const u8, alg_version: ?u30, ln: u6, r: u30, p: u30 },
320 },
321 .{
322 .str = "$scrypt$v=1$c2FsdHNhbHQ$dGVzdHBhc3M",
323 .HashResult = struct {
324 alg_id: []const u8,
325 alg_version: u16,
326 salt: BinValue(16),
327 hash: BinValue(16),
328 },
329 },
330 .{
331 .str = "$scrypt$v=1$c2FsdHNhbHQ",
332 .HashResult = struct { alg_id: []const u8, alg_version: u16, salt: BinValue(16) },
333 },
334 .{
335 .str = "$scrypt$c2FsdHNhbHQ$dGVzdHBhc3M",
336 .HashResult = struct { alg_id: []const u8, salt: BinValue(16), hash: BinValue(16) },
337 },
338 };
339 inline for (inputs) |input| {
340 const v = try deserialize(input.HashResult, input.str);
341 var buf: [input.str.len]u8 = undefined;
342 const s1 = try serialize(v, &buf);
343 try std.testing.expectEqualSlices(u8, input.str, s1);
344 }
345}
346
347test "phc format - empty input string" {
348 const s = "";
349 const v = deserialize(struct { alg_id: []const u8 }, s);
350 try std.testing.expectError(Error.InvalidEncoding, v);
351}
352
353test "phc format - hash without salt" {
354 const s = "$scrypt";
355 const v = deserialize(struct { alg_id: []const u8, hash: BinValue(16) }, s);
356 try std.testing.expectError(Error.InvalidEncoding, v);
357}
358
359test "phc format - calcSize" {
360 const s = "$scrypt$v=1$ln=15,r=8,p=1$c2FsdHNhbHQ$dGVzdHBhc3M";
361 const v = try deserialize(struct {
362 alg_id: []const u8,
363 alg_version: u16,
364 ln: u6,
365 r: u30,
366 p: u30,
367 salt: BinValue(8),
368 hash: BinValue(8),
369 }, s);
370 try std.testing.expectEqual(calcSize(v), s.len);
371}
lib/std/crypto/poly1305.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const utils = std.crypto.utils;2const utils = std.crypto.utils;
8const mem = std.mem;3const mem = std.mem;
lib/std/crypto/salsa20.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
8const crypto = std.crypto;2const crypto = std.crypto;
9const debug = std.debug;3const debug = std.debug;
lib/std/crypto/scrypt.zig created+657
...@@ -0,0 +1,657 @@
1// https://tools.ietf.org/html/rfc7914
2// https://github.com/golang/crypto/blob/master/scrypt/scrypt.go
3
4const std = @import("std");
5const crypto = std.crypto;
6const fmt = std.fmt;
7const io = std.io;
8const math = std.math;
9const mem = std.mem;
10const meta = std.meta;
11const pwhash = crypto.pwhash;
12
13const phc_format = @import("phc_encoding.zig");
14
15const HmacSha256 = crypto.auth.hmac.sha2.HmacSha256;
16const KdfError = pwhash.KdfError;
17const HasherError = pwhash.HasherError;
18const EncodingError = phc_format.Error;
19const Error = pwhash.Error;
20
21const max_size = math.maxInt(usize);
22const max_int = max_size >> 1;
23const default_salt_len = 32;
24const default_hash_len = 32;
25const max_salt_len = 64;
26const max_hash_len = 64;
27
28fn blockCopy(dst: []align(16) u32, src: []align(16) const u32, n: usize) void {
29 mem.copy(u32, dst, src[0 .. n * 16]);
30}
31
32fn blockXor(dst: []align(16) u32, src: []align(16) const u32, n: usize) void {
33 for (src[0 .. n * 16]) |v, i| {
34 dst[i] ^= v;
35 }
36}
37
38const QuarterRound = struct { a: usize, b: usize, c: usize, d: u6 };
39
40fn Rp(a: usize, b: usize, c: usize, d: u6) QuarterRound {
41 return QuarterRound{ .a = a, .b = b, .c = c, .d = d };
42}
43
44fn salsa8core(b: *align(16) [16]u32) void {
45 const arx_steps = comptime [_]QuarterRound{
46 Rp(4, 0, 12, 7), Rp(8, 4, 0, 9), Rp(12, 8, 4, 13), Rp(0, 12, 8, 18),
47 Rp(9, 5, 1, 7), Rp(13, 9, 5, 9), Rp(1, 13, 9, 13), Rp(5, 1, 13, 18),
48 Rp(14, 10, 6, 7), Rp(2, 14, 10, 9), Rp(6, 2, 14, 13), Rp(10, 6, 2, 18),
49 Rp(3, 15, 11, 7), Rp(7, 3, 15, 9), Rp(11, 7, 3, 13), Rp(15, 11, 7, 18),
50 Rp(1, 0, 3, 7), Rp(2, 1, 0, 9), Rp(3, 2, 1, 13), Rp(0, 3, 2, 18),
51 Rp(6, 5, 4, 7), Rp(7, 6, 5, 9), Rp(4, 7, 6, 13), Rp(5, 4, 7, 18),
52 Rp(11, 10, 9, 7), Rp(8, 11, 10, 9), Rp(9, 8, 11, 13), Rp(10, 9, 8, 18),
53 Rp(12, 15, 14, 7), Rp(13, 12, 15, 9), Rp(14, 13, 12, 13), Rp(15, 14, 13, 18),
54 };
55 var x = b.*;
56 var j: usize = 0;
57 while (j < 8) : (j += 2) {
58 inline for (arx_steps) |r| {
59 x[r.a] ^= math.rotl(u32, x[r.b] +% x[r.c], r.d);
60 }
61 }
62 j = 0;
63 while (j < 16) : (j += 1) {
64 b[j] +%= x[j];
65 }
66}
67
68fn salsaXor(tmp: *align(16) [16]u32, in: []align(16) const u32, out: []align(16) u32) void {
69 blockXor(tmp, in, 1);
70 salsa8core(tmp);
71 blockCopy(out, tmp, 1);
72}
73
74fn blockMix(tmp: *align(16) [16]u32, in: []align(16) const u32, out: []align(16) u32, r: u30) void {
75 blockCopy(tmp, in[(2 * r - 1) * 16 ..], 1);
76 var i: usize = 0;
77 while (i < 2 * r) : (i += 2) {
78 salsaXor(tmp, in[i * 16 ..], out[i * 8 ..]);
79 salsaXor(tmp, in[i * 16 + 16 ..], out[i * 8 + r * 16 ..]);
80 }
81}
82
83fn integerify(b: []align(16) const u32, r: u30) u64 {
84 const j = (2 * r - 1) * 16;
85 return @as(u64, b[j]) | @as(u64, b[j + 1]) << 32;
86}
87
88fn smix(b: []align(16) u8, r: u30, n: usize, v: []align(16) u32, xy: []align(16) u32) void {
89 var x = xy[0 .. 32 * r];
90 var y = xy[32 * r ..];
91
92 for (x) |*v1, j| {
93 v1.* = mem.readIntSliceLittle(u32, b[4 * j ..]);
94 }
95
96 var tmp: [16]u32 align(16) = undefined;
97 var i: usize = 0;
98 while (i < n) : (i += 2) {
99 blockCopy(v[i * (32 * r) ..], x, 2 * r);
100 blockMix(&tmp, x, y, r);
101
102 blockCopy(v[(i + 1) * (32 * r) ..], y, 2 * r);
103 blockMix(&tmp, y, x, r);
104 }
105
106 i = 0;
107 while (i < n) : (i += 2) {
108 var j = @intCast(usize, integerify(x, r) & (n - 1));
109 blockXor(x, v[j * (32 * r) ..], 2 * r);
110 blockMix(&tmp, x, y, r);
111
112 j = @intCast(usize, integerify(y, r) & (n - 1));
113 blockXor(y, v[j * (32 * r) ..], 2 * r);
114 blockMix(&tmp, y, x, r);
115 }
116
117 for (x) |v1, j| {
118 mem.writeIntLittle(u32, b[4 * j ..][0..4], v1);
119 }
120}
121
122pub const Params = struct {
123 const Self = @This();
124
125 ln: u6,
126 r: u30,
127 p: u30,
128
129 /// Baseline parameters for interactive logins
130 pub const interactive = Self.fromLimits(524288, 16777216);
131
132 /// Baseline parameters for offline usage
133 pub const sensitive = Self.fromLimits(33554432, 1073741824);
134
135 /// Create parameters from ops and mem limits
136 pub fn fromLimits(ops_limit: u64, mem_limit: usize) Self {
137 const ops = math.max(32768, ops_limit);
138 const r: u30 = 8;
139 if (ops < mem_limit / 32) {
140 const max_n = ops / (r * 4);
141 return Self{ .r = r, .p = 1, .ln = @intCast(u6, math.log2(max_n)) };
142 } else {
143 const max_n = mem_limit / (@intCast(usize, r) * 128);
144 const ln = @intCast(u6, math.log2(max_n));
145 const max_rp = math.min(0x3fffffff, (ops / 4) / (@as(u64, 1) << ln));
146 return Self{ .r = r, .p = @intCast(u30, max_rp / @as(u64, r)), .ln = ln };
147 }
148 }
149};
150
151/// Apply scrypt to generate a key from a password.
152///
153/// scrypt is defined in RFC 7914.
154///
155/// allocator: *mem.Allocator.
156///
157/// derived_key: Slice of appropriate size for generated key. Generally 16 or 32 bytes in length.
158/// May be uninitialized. All bytes will be overwritten.
159/// Maximum size is `derived_key.len / 32 == 0xffff_ffff`.
160///
161/// password: Arbitrary sequence of bytes of any length.
162///
163/// salt: Arbitrary sequence of bytes of any length.
164///
165/// params: Params.
166pub fn kdf(
167 allocator: *mem.Allocator,
168 derived_key: []u8,
169 password: []const u8,
170 salt: []const u8,
171 params: Params,
172) KdfError!void {
173 if (derived_key.len == 0 or derived_key.len / 32 > 0xffff_ffff) return KdfError.OutputTooLong;
174 if (params.ln == 0 or params.r == 0 or params.p == 0) return KdfError.WeakParameters;
175
176 const n64 = @as(u64, 1) << params.ln;
177 if (n64 > max_size) return KdfError.WeakParameters;
178 const n = @intCast(usize, n64);
179 if (@as(u64, params.r) * @as(u64, params.p) >= 1 << 30 or
180 params.r > max_int / 128 / @as(u64, params.p) or
181 params.r > max_int / 256 or
182 n > max_int / 128 / @as(u64, params.r)) return KdfError.WeakParameters;
183
184 var xy = try allocator.alignedAlloc(u32, 16, 64 * params.r);
185 defer allocator.free(xy);
186 var v = try allocator.alignedAlloc(u32, 16, 32 * n * params.r);
187 defer allocator.free(v);
188 var dk = try allocator.alignedAlloc(u8, 16, params.p * 128 * params.r);
189 defer allocator.free(dk);
190
191 try pwhash.pbkdf2(dk, password, salt, 1, HmacSha256);
192 var i: u32 = 0;
193 while (i < params.p) : (i += 1) {
194 smix(dk[i * 128 * params.r ..], params.r, n, v, xy);
195 }
196 try pwhash.pbkdf2(derived_key, password, dk, 1, HmacSha256);
197}
198
199const crypt_format = struct {
200 /// String prefix for scrypt
201 pub const prefix = "$7$";
202
203 /// Standard type for a set of scrypt parameters, with the salt and hash.
204 pub fn HashResult(comptime crypt_max_hash_len: usize) type {
205 return struct {
206 ln: u6,
207 r: u30,
208 p: u30,
209 salt: []const u8,
210 hash: BinValue(crypt_max_hash_len),
211 };
212 }
213
214 const Codec = CustomB64Codec("./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".*);
215
216 /// A wrapped binary value whose maximum size is `max_len`.
217 ///
218 /// This type must be used whenever a binary value is encoded in a PHC-formatted string.
219 /// This includes `salt`, `hash`, and any other binary parameters such as keys.
220 ///
221 /// Once initialized, the actual value can be read with the `constSlice()` function.
222 pub fn BinValue(comptime max_len: usize) type {
223 return struct {
224 const Self = @This();
225 const capacity = max_len;
226 const max_encoded_length = Codec.encodedLen(max_len);
227
228 buf: [max_len]u8 = undefined,
229 len: usize = 0,
230
231 /// Wrap an existing byte slice
232 pub fn fromSlice(slice: []const u8) EncodingError!Self {
233 if (slice.len > capacity) return EncodingError.NoSpaceLeft;
234 var bin_value: Self = undefined;
235 mem.copy(u8, &bin_value.buf, slice);
236 bin_value.len = slice.len;
237 return bin_value;
238 }
239
240 /// Return the slice containing the actual value.
241 pub fn constSlice(self: Self) []const u8 {
242 return self.buf[0..self.len];
243 }
244
245 fn fromB64(self: *Self, str: []const u8) !void {
246 const len = Codec.decodedLen(str.len);
247 if (len > self.buf.len) return EncodingError.NoSpaceLeft;
248 try Codec.decode(self.buf[0..len], str);
249 self.len = len;
250 }
251
252 fn toB64(self: Self, buf: []u8) ![]const u8 {
253 const value = self.constSlice();
254 const len = Codec.encodedLen(value.len);
255 if (len > buf.len) return EncodingError.NoSpaceLeft;
256 var encoded = buf[0..len];
257 Codec.encode(encoded, value);
258 return encoded;
259 }
260 };
261 }
262
263 /// Expand binary data into a salt for the modular crypt format.
264 pub fn saltFromBin(comptime len: usize, salt: [len]u8) [Codec.encodedLen(len)]u8 {
265 var buf: [Codec.encodedLen(len)]u8 = undefined;
266 Codec.encode(&buf, &salt);
267 return buf;
268 }
269
270 /// Deserialize a string into a structure `T` (matching `HashResult`).
271 pub fn deserialize(comptime T: type, str: []const u8) EncodingError!T {
272 var out: T = undefined;
273
274 if (str.len < 16) return EncodingError.InvalidEncoding;
275 if (!mem.eql(u8, prefix, str[0..3])) return EncodingError.InvalidEncoding;
276 out.ln = try Codec.intDecode(u6, str[3..4]);
277 out.r = try Codec.intDecode(u30, str[4..9]);
278 out.p = try Codec.intDecode(u30, str[9..14]);
279
280 var it = mem.split(u8, str[14..], "$");
281
282 const salt = it.next() orelse return EncodingError.InvalidEncoding;
283 if (@hasField(T, "salt")) out.salt = salt;
284
285 const hash_str = it.next() orelse return EncodingError.InvalidEncoding;
286 if (@hasField(T, "hash")) try out.hash.fromB64(hash_str);
287
288 return out;
289 }
290
291 /// Serialize parameters into a string in modular crypt format.
292 pub fn serialize(params: anytype, str: []u8) EncodingError![]const u8 {
293 var buf = io.fixedBufferStream(str);
294 try serializeTo(params, buf.writer());
295 return buf.getWritten();
296 }
297
298 /// Compute the number of bytes required to serialize `params`
299 pub fn calcSize(params: anytype) usize {
300 var buf = io.countingWriter(io.null_writer);
301 serializeTo(params, buf.writer()) catch unreachable;
302 return @intCast(usize, buf.bytes_written);
303 }
304
305 fn serializeTo(params: anytype, out: anytype) !void {
306 var header: [14]u8 = undefined;
307 mem.copy(u8, header[0..3], prefix);
308 Codec.intEncode(header[3..4], params.ln);
309 Codec.intEncode(header[4..9], params.r);
310 Codec.intEncode(header[9..14], params.p);
311 try out.writeAll(&header);
312 try out.writeAll(params.salt);
313 try out.writeAll("$");
314 var buf: [@TypeOf(params.hash).max_encoded_length]u8 = undefined;
315 const hash_str = try params.hash.toB64(&buf);
316 try out.writeAll(hash_str);
317 }
318
319 /// Custom codec that maps 6 bits into 8 like regular Base64, but uses its own alphabet,
320 /// encodes bits in little-endian, and can also encode integers.
321 fn CustomB64Codec(comptime map: [64]u8) type {
322 return struct {
323 const map64 = map;
324
325 fn encodedLen(len: usize) usize {
326 return (len * 4 + 2) / 3;
327 }
328
329 fn decodedLen(len: usize) usize {
330 return len / 4 * 3 + (len % 4) * 3 / 4;
331 }
332
333 fn intEncode(dst: []u8, src: anytype) void {
334 var n = src;
335 for (dst) |*x| {
336 x.* = map64[@truncate(u6, n)];
337 n = math.shr(@TypeOf(src), n, 6);
338 }
339 }
340
341 fn intDecode(comptime T: type, src: *const [(meta.bitCount(T) + 5) / 6]u8) !T {
342 var v: T = 0;
343 for (src) |x, i| {
344 const vi = mem.indexOfScalar(u8, &map64, x) orelse return EncodingError.InvalidEncoding;
345 v |= @intCast(T, vi) << @intCast(math.Log2Int(T), i * 6);
346 }
347 return v;
348 }
349
350 fn decode(dst: []u8, src: []const u8) !void {
351 std.debug.assert(dst.len == decodedLen(src.len));
352 var i: usize = 0;
353 while (i < src.len / 4) : (i += 1) {
354 mem.writeIntSliceLittle(u24, dst[i * 3 ..], try intDecode(u24, src[i * 4 ..][0..4]));
355 }
356 const leftover = src[i * 4 ..];
357 var v: u24 = 0;
358 for (leftover) |_, j| {
359 v |= @as(u24, try intDecode(u6, leftover[j..][0..1])) << @intCast(u5, j * 6);
360 }
361 for (dst[i * 3 ..]) |*x, j| {
362 x.* = @truncate(u8, v >> @intCast(u5, j * 8));
363 }
364 }
365
366 fn encode(dst: []u8, src: []const u8) void {
367 std.debug.assert(dst.len == encodedLen(src.len));
368 var i: usize = 0;
369 while (i < src.len / 3) : (i += 1) {
370 intEncode(dst[i * 4 ..][0..4], mem.readIntSliceLittle(u24, src[i * 3 ..]));
371 }
372 const leftover = src[i * 3 ..];
373 var v: u24 = 0;
374 for (leftover) |x, j| {
375 v |= @as(u24, x) << @intCast(u5, j * 8);
376 }
377 intEncode(dst[i * 4 ..], v);
378 }
379 };
380 }
381};
382
383/// Hash and verify passwords using the PHC format.
384const PhcFormatHasher = struct {
385 const alg_id = "scrypt";
386 const BinValue = phc_format.BinValue;
387
388 const HashResult = struct {
389 alg_id: []const u8,
390 ln: u6,
391 r: u30,
392 p: u30,
393 salt: BinValue(max_salt_len),
394 hash: BinValue(max_hash_len),
395 };
396
397 /// Return a non-deterministic hash of the password encoded as a PHC-format string
398 pub fn create(
399 allocator: *mem.Allocator,
400 password: []const u8,
401 params: Params,
402 buf: []u8,
403 ) HasherError![]const u8 {
404 var salt: [default_salt_len]u8 = undefined;
405 crypto.random.bytes(&salt);
406
407 var hash: [default_hash_len]u8 = undefined;
408 try kdf(allocator, &hash, password, &salt, params);
409
410 return phc_format.serialize(HashResult{
411 .alg_id = alg_id,
412 .ln = params.ln,
413 .r = params.r,
414 .p = params.p,
415 .salt = try BinValue(max_salt_len).fromSlice(&salt),
416 .hash = try BinValue(max_hash_len).fromSlice(&hash),
417 }, buf);
418 }
419
420 /// Verify a password against a PHC-format encoded string
421 pub fn verify(
422 allocator: *mem.Allocator,
423 str: []const u8,
424 password: []const u8,
425 ) HasherError!void {
426 const hash_result = try phc_format.deserialize(HashResult, str);
427 if (!mem.eql(u8, hash_result.alg_id, alg_id)) return HasherError.PasswordVerificationFailed;
428 const params = Params{ .ln = hash_result.ln, .r = hash_result.r, .p = hash_result.p };
429 const expected_hash = hash_result.hash.constSlice();
430 var hash_buf: [max_hash_len]u8 = undefined;
431 if (expected_hash.len > hash_buf.len) return HasherError.InvalidEncoding;
432 var hash = hash_buf[0..expected_hash.len];
433 try kdf(allocator, hash, password, hash_result.salt.constSlice(), params);
434 if (!mem.eql(u8, hash, expected_hash)) return HasherError.PasswordVerificationFailed;
435 }
436};
437
438/// Hash and verify passwords using the modular crypt format.
439const CryptFormatHasher = struct {
440 const BinValue = crypt_format.BinValue;
441 const HashResult = crypt_format.HashResult(max_hash_len);
442
443 /// Length of a string returned by the create() function
444 pub const pwhash_str_length: usize = 101;
445
446 /// Return a non-deterministic hash of the password encoded into the modular crypt format
447 pub fn create(
448 allocator: *mem.Allocator,
449 password: []const u8,
450 params: Params,
451 buf: []u8,
452 ) HasherError![]const u8 {
453 var salt_bin: [default_salt_len]u8 = undefined;
454 crypto.random.bytes(&salt_bin);
455 const salt = crypt_format.saltFromBin(salt_bin.len, salt_bin);
456
457 var hash: [default_hash_len]u8 = undefined;
458 try kdf(allocator, &hash, password, &salt, params);
459
460 return crypt_format.serialize(HashResult{
461 .ln = params.ln,
462 .r = params.r,
463 .p = params.p,
464 .salt = &salt,
465 .hash = try BinValue(max_hash_len).fromSlice(&hash),
466 }, buf);
467 }
468
469 /// Verify a password against a string in modular crypt format
470 pub fn verify(
471 allocator: *mem.Allocator,
472 str: []const u8,
473 password: []const u8,
474 ) HasherError!void {
475 const hash_result = try crypt_format.deserialize(HashResult, str);
476 const params = Params{ .ln = hash_result.ln, .r = hash_result.r, .p = hash_result.p };
477 const expected_hash = hash_result.hash.constSlice();
478 var hash_buf: [max_hash_len]u8 = undefined;
479 if (expected_hash.len > hash_buf.len) return HasherError.InvalidEncoding;
480 var hash = hash_buf[0..expected_hash.len];
481 try kdf(allocator, hash, password, hash_result.salt, params);
482 if (!mem.eql(u8, hash, expected_hash)) return HasherError.PasswordVerificationFailed;
483 }
484};
485
486/// Options for hashing a password.
487pub const HashOptions = struct {
488 allocator: ?*mem.Allocator,
489 params: Params,
490 encoding: pwhash.Encoding,
491};
492
493/// Compute a hash of a password using the scrypt key derivation function.
494/// The function returns a string that includes all the parameters required for verification.
495pub fn strHash(
496 password: []const u8,
497 options: HashOptions,
498 out: []u8,
499) Error![]const u8 {
500 const allocator = options.allocator orelse return Error.AllocatorRequired;
501 switch (options.encoding) {
502 .phc => return PhcFormatHasher.create(allocator, password, options.params, out),
503 .crypt => return CryptFormatHasher.create(allocator, password, options.params, out),
504 }
505}
506
507/// Options for hash verification.
508pub const VerifyOptions = struct {
509 allocator: ?*mem.Allocator,
510};
511
512/// Verify that a previously computed hash is valid for a given password.
513pub fn strVerify(
514 str: []const u8,
515 password: []const u8,
516 options: VerifyOptions,
517) Error!void {
518 const allocator = options.allocator orelse return Error.AllocatorRequired;
519 if (mem.startsWith(u8, str, crypt_format.prefix)) {
520 return CryptFormatHasher.verify(allocator, str, password);
521 } else {
522 return PhcFormatHasher.verify(allocator, str, password);
523 }
524}
525
526test "scrypt kdf" {
527 const password = "testpass";
528 const salt = "saltsalt";
529
530 var dk: [32]u8 = undefined;
531 try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 15, .r = 8, .p = 1 });
532
533 const hex = "1e0f97c3f6609024022fbe698da29c2fe53ef1087a8e396dc6d5d2a041e886de";
534 var bytes: [hex.len / 2]u8 = undefined;
535 _ = try fmt.hexToBytes(&bytes, hex);
536
537 try std.testing.expectEqualSlices(u8, &bytes, &dk);
538}
539
540test "scrypt kdf rfc 1" {
541 const password = "";
542 const salt = "";
543
544 var dk: [64]u8 = undefined;
545 try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 4, .r = 1, .p = 1 });
546
547 const hex = "77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906";
548 var bytes: [hex.len / 2]u8 = undefined;
549 _ = try fmt.hexToBytes(&bytes, hex);
550
551 try std.testing.expectEqualSlices(u8, &bytes, &dk);
552}
553
554test "scrypt kdf rfc 2" {
555 const password = "password";
556 const salt = "NaCl";
557
558 var dk: [64]u8 = undefined;
559 try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 10, .r = 8, .p = 16 });
560
561 const hex = "fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640";
562 var bytes: [hex.len / 2]u8 = undefined;
563 _ = try fmt.hexToBytes(&bytes, hex);
564
565 try std.testing.expectEqualSlices(u8, &bytes, &dk);
566}
567
568test "scrypt kdf rfc 3" {
569 const password = "pleaseletmein";
570 const salt = "SodiumChloride";
571
572 var dk: [64]u8 = undefined;
573 try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 14, .r = 8, .p = 1 });
574
575 const hex = "7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887";
576 var bytes: [hex.len / 2]u8 = undefined;
577 _ = try fmt.hexToBytes(&bytes, hex);
578
579 try std.testing.expectEqualSlices(u8, &bytes, &dk);
580}
581
582test "scrypt kdf rfc 4" {
583 // skip slow test
584 if (true) {
585 return error.SkipZigTest;
586 }
587
588 const password = "pleaseletmein";
589 const salt = "SodiumChloride";
590
591 var dk: [64]u8 = undefined;
592 try kdf(std.testing.allocator, &dk, password, salt, .{ .ln = 20, .r = 8, .p = 1 });
593
594 const hex = "2101cb9b6a511aaeaddbbe09cf70f881ec568d574a2ffd4dabe5ee9820adaa478e56fd8f4ba5d09ffa1c6d927c40f4c337304049e8a952fbcbf45c6fa77a41a4";
595 var bytes: [hex.len / 2]u8 = undefined;
596 _ = try fmt.hexToBytes(&bytes, hex);
597
598 try std.testing.expectEqualSlices(u8, &bytes, &dk);
599}
600
601test "scrypt password hashing (crypt format)" {
602 const str = "$7$A6....1....TrXs5Zk6s8sWHpQgWDIXTR8kUU3s6Jc3s.DtdS8M2i4$a4ik5hGDN7foMuHOW.cp.CtX01UyCeO0.JAG.AHPpx5";
603 const password = "Y0!?iQa9M%5ekffW(`";
604 try CryptFormatHasher.verify(std.testing.allocator, str, password);
605
606 const params = Params.interactive;
607 var buf: [CryptFormatHasher.pwhash_str_length]u8 = undefined;
608 const str2 = try CryptFormatHasher.create(std.testing.allocator, password, params, &buf);
609 try CryptFormatHasher.verify(std.testing.allocator, str2, password);
610}
611
612test "scrypt strHash and strVerify" {
613 const alloc = std.testing.allocator;
614
615 const password = "testpass";
616 const verify_options = VerifyOptions{ .allocator = alloc };
617 var buf: [128]u8 = undefined;
618
619 const s = try strHash(
620 password,
621 HashOptions{ .allocator = alloc, .params = Params.interactive, .encoding = .crypt },
622 &buf,
623 );
624 try strVerify(s, password, verify_options);
625
626 const s1 = try strHash(
627 password,
628 HashOptions{ .allocator = alloc, .params = Params.interactive, .encoding = .phc },
629 &buf,
630 );
631 try strVerify(s1, password, verify_options);
632}
633
634test "scrypt unix-scrypt" {
635 const alloc = std.testing.allocator;
636
637 // https://gitlab.com/jas/scrypt-unix-crypt/blob/master/unix-scrypt.txt
638 {
639 const str = "$7$C6..../....SodiumChloride$kBGj9fHznVYFQMEn/qDCfrDevf9YDtcDdKvEqHJLV8D";
640 const password = "pleaseletmein";
641 try strVerify(str, password, .{ .allocator = alloc });
642 }
643 // one of the libsodium test vectors
644 {
645 const str = "$7$B6....1....75gBMAGwfFWZqBdyF3WdTQnWdUsuTiWjG1fF9c1jiSD$tc8RoB3.Em3/zNgMLWo2u00oGIoTyJv4fl3Fl8Tix72";
646 const password = "^T5H$JYt39n%K*j:W]!1s?vg!:jGi]Ax?..l7[p0v:1jHTpla9;]bUN;?bWyCbtqg nrDFal+Jxl3,2`#^tFSu%v_+7iYse8-cCkNf!tD=KrW)";
647 try strVerify(str, password, .{ .allocator = alloc });
648 }
649}
650
651test "scrypt crypt format" {
652 const str = "$7$C6..../....SodiumChloride$kBGj9fHznVYFQMEn/qDCfrDevf9YDtcDdKvEqHJLV8D";
653 const params = try crypt_format.deserialize(crypt_format.HashResult(32), str);
654 var buf: [str.len]u8 = undefined;
655 const s1 = try crypt_format.serialize(params, &buf);
656 try std.testing.expectEqualStrings(s1, str);
657}
lib/std/crypto/sha1.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const mem = std.mem;2const mem = std.mem;
8const math = std.math;3const math = std.math;
lib/std/crypto/sha2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const mem = std.mem;2const mem = std.mem;
8const math = std.math;3const math = std.math;
lib/std/crypto/sha3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const mem = std.mem;2const mem = std.mem;
8const math = std.math;3const math = std.math;
lib/std/crypto/siphash.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6//1//
7// SipHash is a moderately fast pseudorandom function, returning a 64-bit or 128-bit tag for an arbitrary long input.2// SipHash is a moderately fast pseudorandom function, returning a 64-bit or 128-bit tag for an arbitrary long input.
8//3//
lib/std/crypto/test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const fmt = std.fmt;3const fmt = std.fmt;
lib/std/crypto/tlcsprng.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! Thread-local cryptographically secure pseudo-random number generator.1//! Thread-local cryptographically secure pseudo-random number generator.
8//! This file has public declarations that are intended to be used internally2//! This file has public declarations that are intended to be used internally
9//! by the standard library; this namespace is not intended to be exposed3//! by the standard library; this namespace is not intended to be exposed
lib/std/cstr.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const debug = std.debug;3const debug = std.debug;
lib/std/debug.zig+2-7
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const math = std.math;3const math = std.math;
...@@ -36,7 +31,7 @@ pub const LineInfo = struct {...@@ -36,7 +31,7 @@ pub const LineInfo = struct {
36 file_name: []const u8,31 file_name: []const u8,
37 allocator: ?*mem.Allocator,32 allocator: ?*mem.Allocator,
3833
39 fn deinit(self: LineInfo) void {34 pub fn deinit(self: LineInfo) void {
40 const allocator = self.allocator orelse return;35 const allocator = self.allocator orelse return;
41 allocator.free(self.file_name);36 allocator.free(self.file_name);
42 }37 }
...@@ -47,7 +42,7 @@ pub const SymbolInfo = struct {...@@ -47,7 +42,7 @@ pub const SymbolInfo = struct {
47 compile_unit_name: []const u8 = "???",42 compile_unit_name: []const u8 = "???",
48 line_info: ?LineInfo = null,43 line_info: ?LineInfo = null,
4944
50 fn deinit(self: @This()) void {45 pub fn deinit(self: @This()) void {
51 if (self.line_info) |li| {46 if (self.line_info) |li| {
52 li.deinit();47 li.deinit();
53 }48 }
lib/std/dwarf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const debug = std.debug;3const debug = std.debug;
lib/std/dwarf_bits.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const TAG_padding = 0x00;1pub const TAG_padding = 0x00;
7pub const TAG_array_type = 0x01;2pub const TAG_array_type = 0x01;
8pub const TAG_class_type = 0x02;3pub const TAG_class_type = 0x02;
lib/std/dynamic_library.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = std.builtin;1const builtin = std.builtin;
72
8const std = @import("std.zig");3const std = @import("std.zig");
lib/std/elf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const io = std.io;2const io = std.io;
8const os = std.os;3const os = std.os;
lib/std/enums.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! This module contains utilities and data structures for working with enums.1//! This module contains utilities and data structures for working with enums.
82
9const std = @import("std.zig");3const std = @import("std.zig");
lib/std/event.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const Channel = @import("event/channel.zig").Channel;1pub const Channel = @import("event/channel.zig").Channel;
7pub const Future = @import("event/future.zig").Future;2pub const Future = @import("event/future.zig").Future;
8pub const Group = @import("event/group.zig").Group;3pub const Group = @import("event/group.zig").Group;
lib/std/event/batch.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const testing = std.testing;2const testing = std.testing;
83
lib/std/event/channel.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/event/future.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const testing = std.testing;3const testing = std.testing;
lib/std/event/group.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const Lock = std.event.Lock;3const Lock = std.event.Lock;
lib/std/event/lock.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/event/locked.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const Lock = std.event.Lock;2const Lock = std.event.Lock;
83
lib/std/event/loop.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const root = @import("root");3const root = @import("root");
lib/std/event/rwlock.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/event/rwlocked.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const RwLock = std.event.RwLock;2const RwLock = std.event.RwLock;
83
lib/std/event/wait_group.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const Loop = std.event.Loop;3const Loop = std.event.Loop;
lib/std/fifo.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// FIFO of fixed size items1// FIFO of fixed size items
7// Usually used for e.g. byte buffers2// Usually used for e.g. byte buffers
83
lib/std/fmt.zig+1-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const math = std.math;2const math = std.math;
8const assert = std.debug.assert;3const assert = std.debug.assert;
...@@ -1757,6 +1752,7 @@ test "parseUnsigned" {...@@ -1757,6 +1752,7 @@ test "parseUnsigned" {
1757}1752}
17581753
1759pub const parseFloat = @import("fmt/parse_float.zig").parseFloat;1754pub const parseFloat = @import("fmt/parse_float.zig").parseFloat;
1755pub const ParseFloatError = @import("fmt/parse_float.zig").ParseFloatError;
1760pub const parseHexFloat = @import("fmt/parse_hex_float.zig").parseHexFloat;1756pub const parseHexFloat = @import("fmt/parse_hex_float.zig").parseHexFloat;
17611757
1762test {1758test {
lib/std/fmt/errol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const enum3 = @import("errol/enum3.zig").enum3;2const enum3 = @import("errol/enum3.zig").enum3;
8const enum3_data = @import("errol/enum3.zig").enum3_data;3const enum3_data = @import("errol/enum3.zig").enum3_data;
lib/std/fmt/errol/enum3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const enum3 = [_]u64{1pub const enum3 = [_]u64{
7 0x4e2e2785c3a2a20b,2 0x4e2e2785c3a2a20b,
8 0x240a28877a09a4e1,3 0x240a28877a09a4e1,
lib/std/fmt/errol/lookup.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const HP = struct {1pub const HP = struct {
7 val: f64,2 val: f64,
8 off: f64,3 off: f64,
lib/std/fmt/parse_float.zig+3-6
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Adapted from https://github.com/grzegorz-kraszewski/stringtofloat.1// Adapted from https://github.com/grzegorz-kraszewski/stringtofloat.
72
8// MIT License3// MIT License
...@@ -349,7 +344,9 @@ fn caseInEql(a: []const u8, b: []const u8) bool {...@@ -349,7 +344,9 @@ fn caseInEql(a: []const u8, b: []const u8) bool {
349 return true;344 return true;
350}345}
351346
352pub fn parseFloat(comptime T: type, s: []const u8) !T {347pub const ParseFloatError = error{InvalidCharacter};
348
349pub fn parseFloat(comptime T: type, s: []const u8) ParseFloatError!T {
353 if (s.len == 0 or (s.len == 1 and (s[0] == '+' or s[0] == '-'))) {350 if (s.len == 0 or (s.len == 1 and (s[0] == '+' or s[0] == '-'))) {
354 return error.InvalidCharacter;351 return error.InvalidCharacter;
355 }352 }
lib/std/fmt/parse_hex_float.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.const std = @import("std");
6//
7// The rounding logic is inspired by LLVM's APFloat and Go's atofHex1// The rounding logic is inspired by LLVM's APFloat and Go's atofHex
8// implementation.2// implementation.
93
lib/std/fs.zig+39-35
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const root = @import("root");1const root = @import("root");
7const builtin = std.builtin;2const builtin = std.builtin;
8const std = @import("std.zig");3const std = @import("std.zig");
...@@ -339,10 +334,10 @@ pub const Dir = struct {...@@ -339,10 +334,10 @@ pub const Dir = struct {
339 if (rc == 0) return null;334 if (rc == 0) return null;
340 if (rc < 0) {335 if (rc < 0) {
341 switch (os.errno(rc)) {336 switch (os.errno(rc)) {
342 os.EBADF => unreachable, // Dir is invalid or was opened without iteration ability337 .BADF => unreachable, // Dir is invalid or was opened without iteration ability
343 os.EFAULT => unreachable,338 .FAULT => unreachable,
344 os.ENOTDIR => unreachable,339 .NOTDIR => unreachable,
345 os.EINVAL => unreachable,340 .INVAL => unreachable,
346 else => |err| return os.unexpectedErrno(err),341 else => |err| return os.unexpectedErrno(err),
347 }342 }
348 }343 }
...@@ -385,11 +380,11 @@ pub const Dir = struct {...@@ -385,11 +380,11 @@ pub const Dir = struct {
385 else380 else
386 os.system.getdents(self.dir.fd, &self.buf, self.buf.len);381 os.system.getdents(self.dir.fd, &self.buf, self.buf.len);
387 switch (os.errno(rc)) {382 switch (os.errno(rc)) {
388 0 => {},383 .SUCCESS => {},
389 os.EBADF => unreachable, // Dir is invalid or was opened without iteration ability384 .BADF => unreachable, // Dir is invalid or was opened without iteration ability
390 os.EFAULT => unreachable,385 .FAULT => unreachable,
391 os.ENOTDIR => unreachable,386 .NOTDIR => unreachable,
392 os.EINVAL => unreachable,387 .INVAL => unreachable,
393 else => |err| return os.unexpectedErrno(err),388 else => |err| return os.unexpectedErrno(err),
394 }389 }
395 if (rc == 0) return null;390 if (rc == 0) return null;
...@@ -457,10 +452,10 @@ pub const Dir = struct {...@@ -457,10 +452,10 @@ pub const Dir = struct {
457 if (rc == 0) return null;452 if (rc == 0) return null;
458 if (rc < 0) {453 if (rc < 0) {
459 switch (os.errno(rc)) {454 switch (os.errno(rc)) {
460 os.EBADF => unreachable, // Dir is invalid or was opened without iteration ability455 .BADF => unreachable, // Dir is invalid or was opened without iteration ability
461 os.EFAULT => unreachable,456 .FAULT => unreachable,
462 os.ENOTDIR => unreachable,457 .NOTDIR => unreachable,
463 os.EINVAL => unreachable,458 .INVAL => unreachable,
464 else => |err| return os.unexpectedErrno(err),459 else => |err| return os.unexpectedErrno(err),
465 }460 }
466 }461 }
...@@ -522,11 +517,11 @@ pub const Dir = struct {...@@ -522,11 +517,11 @@ pub const Dir = struct {
522 if (self.index >= self.end_index) {517 if (self.index >= self.end_index) {
523 const rc = os.linux.getdents64(self.dir.fd, &self.buf, self.buf.len);518 const rc = os.linux.getdents64(self.dir.fd, &self.buf, self.buf.len);
524 switch (os.linux.getErrno(rc)) {519 switch (os.linux.getErrno(rc)) {
525 0 => {},520 .SUCCESS => {},
526 os.EBADF => unreachable, // Dir is invalid or was opened without iteration ability521 .BADF => unreachable, // Dir is invalid or was opened without iteration ability
527 os.EFAULT => unreachable,522 .FAULT => unreachable,
528 os.ENOTDIR => unreachable,523 .NOTDIR => unreachable,
529 os.EINVAL => unreachable,524 .INVAL => unreachable,
530 else => |err| return os.unexpectedErrno(err),525 else => |err| return os.unexpectedErrno(err),
531 }526 }
532 if (rc == 0) return null;527 if (rc == 0) return null;
...@@ -655,12 +650,12 @@ pub const Dir = struct {...@@ -655,12 +650,12 @@ pub const Dir = struct {
655 if (self.index >= self.end_index) {650 if (self.index >= self.end_index) {
656 var bufused: usize = undefined;651 var bufused: usize = undefined;
657 switch (w.fd_readdir(self.dir.fd, &self.buf, self.buf.len, self.cookie, &bufused)) {652 switch (w.fd_readdir(self.dir.fd, &self.buf, self.buf.len, self.cookie, &bufused)) {
658 w.ESUCCESS => {},653 .SUCCESS => {},
659 w.EBADF => unreachable, // Dir is invalid or was opened without iteration ability654 .BADF => unreachable, // Dir is invalid or was opened without iteration ability
660 w.EFAULT => unreachable,655 .FAULT => unreachable,
661 w.ENOTDIR => unreachable,656 .NOTDIR => unreachable,
662 w.EINVAL => unreachable,657 .INVAL => unreachable,
663 w.ENOTCAPABLE => return error.AccessDenied,658 .NOTCAPABLE => return error.AccessDenied,
664 else => |err| return os.unexpectedErrno(err),659 else => |err| return os.unexpectedErrno(err),
665 }660 }
666 if (bufused == 0) return null;661 if (bufused == 0) return null;
...@@ -795,22 +790,31 @@ pub const Dir = struct {...@@ -795,22 +790,31 @@ pub const Dir = struct {
795 .kind = base.kind,790 .kind = base.kind,
796 };791 };
797 } else {792 } else {
798 self.stack.pop().iter.dir.close();793 var item = self.stack.pop();
794 if (self.stack.items.len != 0) {
795 item.iter.dir.close();
796 }
799 }797 }
800 }798 }
801 return null;799 return null;
802 }800 }
803801
804 pub fn deinit(self: *Walker) void {802 pub fn deinit(self: *Walker) void {
805 while (self.stack.popOrNull()) |*item| item.iter.dir.close();803 while (self.stack.popOrNull()) |*item| {
804 if (self.stack.items.len != 0) {
805 item.iter.dir.close();
806 }
807 }
806 self.stack.deinit();808 self.stack.deinit();
807 self.name_buffer.deinit();809 self.name_buffer.deinit();
808 }810 }
809 };811 };
810812
811 /// Recursively iterates over a directory.813 /// Recursively iterates over a directory.
814 /// `self` must have been opened with `OpenDirOptions{.iterate = true}`.
812 /// Must call `Walker.deinit` when done.815 /// Must call `Walker.deinit` when done.
813 /// The order of returned file system entries is undefined.816 /// The order of returned file system entries is undefined.
817 /// `self` will not be closed after walking it.
814 pub fn walk(self: Dir, allocator: *Allocator) !Walker {818 pub fn walk(self: Dir, allocator: *Allocator) !Walker {
815 var name_buffer = std.ArrayList(u8).init(allocator);819 var name_buffer = std.ArrayList(u8).init(allocator);
816 errdefer name_buffer.deinit();820 errdefer name_buffer.deinit();
...@@ -2548,12 +2552,12 @@ fn copy_file(fd_in: os.fd_t, fd_out: os.fd_t) CopyFileError!void {...@@ -2548,12 +2552,12 @@ fn copy_file(fd_in: os.fd_t, fd_out: os.fd_t) CopyFileError!void {
2548 if (comptime std.Target.current.isDarwin()) {2552 if (comptime std.Target.current.isDarwin()) {
2549 const rc = os.system.fcopyfile(fd_in, fd_out, null, os.system.COPYFILE_DATA);2553 const rc = os.system.fcopyfile(fd_in, fd_out, null, os.system.COPYFILE_DATA);
2550 switch (os.errno(rc)) {2554 switch (os.errno(rc)) {
2551 0 => return,2555 .SUCCESS => return,
2552 os.EINVAL => unreachable,2556 .INVAL => unreachable,
2553 os.ENOMEM => return error.SystemResources,2557 .NOMEM => return error.SystemResources,
2554 // The source file is not a directory, symbolic link, or regular file.2558 // The source file is not a directory, symbolic link, or regular file.
2555 // Try with the fallback path before giving up.2559 // Try with the fallback path before giving up.
2556 os.ENOTSUP => {},2560 .OPNOTSUPP => {},
2557 else => |err| return os.unexpectedErrno(err),2561 else => |err| return os.unexpectedErrno(err),
2558 }2562 }
2559 }2563 }
lib/std/fs/file.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const os = std.os;3const os = std.os;
lib/std/fs/get_app_data_dir.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const unicode = std.unicode;3const unicode = std.unicode;
lib/std/fs/path.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const std = @import("../std.zig");2const std = @import("../std.zig");
8const debug = std.debug;3const debug = std.debug;
lib/std/fs/test.zig+2-14
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const builtin = std.builtin;3const builtin = std.builtin;
...@@ -909,11 +904,7 @@ test "open file with exclusive nonblocking lock twice (absolute paths)" {...@@ -909,11 +904,7 @@ test "open file with exclusive nonblocking lock twice (absolute paths)" {
909test "walker" {904test "walker" {
910 if (builtin.os.tag == .wasi) return error.SkipZigTest;905 if (builtin.os.tag == .wasi) return error.SkipZigTest;
911906
912 var arena = ArenaAllocator.init(testing.allocator);907 var tmp = tmpDir(.{ .iterate = true });
913 defer arena.deinit();
914 var allocator = &arena.allocator;
915
916 var tmp = tmpDir(.{});
917 defer tmp.cleanup();908 defer tmp.cleanup();
918909
919 // iteration order of walker is undefined, so need lookup maps to check against910 // iteration order of walker is undefined, so need lookup maps to check against
...@@ -942,10 +933,7 @@ test "walker" {...@@ -942,10 +933,7 @@ test "walker" {
942 try tmp.dir.makePath(kv.key);933 try tmp.dir.makePath(kv.key);
943 }934 }
944935
945 const tmp_path = try fs.path.join(allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] });936 var walker = try tmp.dir.walk(testing.allocator);
946 const tmp_dir = try fs.cwd().openDir(tmp_path, .{ .iterate = true });
947
948 var walker = try tmp_dir.walk(testing.allocator);
949 defer walker.deinit();937 defer walker.deinit();
950938
951 var num_walked: usize = 0;939 var num_walked: usize = 0;
lib/std/fs/wasi.zig+4-9
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const os = std.os;2const os = std.os;
8const mem = std.mem;3const mem = std.mem;
...@@ -121,13 +116,13 @@ pub const PreopenList = struct {...@@ -121,13 +116,13 @@ pub const PreopenList = struct {
121 while (true) {116 while (true) {
122 var buf: prestat_t = undefined;117 var buf: prestat_t = undefined;
123 switch (fd_prestat_get(fd, &buf)) {118 switch (fd_prestat_get(fd, &buf)) {
124 ESUCCESS => {},119 .SUCCESS => {},
125 ENOTSUP => {120 .OPNOTSUPP => {
126 // not a preopen, so keep going121 // not a preopen, so keep going
127 fd = try math.add(fd_t, fd, 1);122 fd = try math.add(fd_t, fd, 1);
128 continue;123 continue;
129 },124 },
130 EBADF => {125 .BADF => {
131 // OK, no more fds available126 // OK, no more fds available
132 break;127 break;
133 },128 },
...@@ -137,7 +132,7 @@ pub const PreopenList = struct {...@@ -137,7 +132,7 @@ pub const PreopenList = struct {
137 const path_buf = try self.buffer.allocator.alloc(u8, preopen_len);132 const path_buf = try self.buffer.allocator.alloc(u8, preopen_len);
138 mem.set(u8, path_buf, 0);133 mem.set(u8, path_buf, 0);
139 switch (fd_prestat_dir_name(fd, path_buf.ptr, preopen_len)) {134 switch (fd_prestat_dir_name(fd, path_buf.ptr, preopen_len)) {
140 ESUCCESS => {},135 .SUCCESS => {},
141 else => |err| return os.unexpectedErrno(err),136 else => |err| return os.unexpectedErrno(err),
142 }137 }
143 const preopen = Preopen.new(fd, PreopenType{ .Dir = path_buf });138 const preopen = Preopen.new(fd, PreopenType{ .Dir = path_buf });
lib/std/fs/watch.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = std.builtin;2const builtin = std.builtin;
8const event = std.event;3const event = std.event;
lib/std/hash.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const adler = @import("hash/adler.zig");1const adler = @import("hash/adler.zig");
7pub const Adler32 = adler.Adler32;2pub const Adler32 = adler.Adler32;
83
lib/std/hash/adler.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Adler32 checksum.1// Adler32 checksum.
7//2//
8// https://tools.ietf.org/html/rfc1950#section-93// https://tools.ietf.org/html/rfc1950#section-9
lib/std/hash/auto_hash.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const mem = std.mem;3const mem = std.mem;
lib/std/hash/benchmark.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// zig run benchmark.zig --release-fast --zig-lib-dir ..1// zig run benchmark.zig --release-fast --zig-lib-dir ..
72
8const builtin = std.builtin;3const builtin = std.builtin;
lib/std/hash/cityhash.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = std.builtin;2const builtin = std.builtin;
83
lib/std/hash/crc.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// There are two implementations of CRC32 implemented with the following key characteristics:1// There are two implementations of CRC32 implemented with the following key characteristics:
7//2//
8// - Crc32WithPoly uses 8Kb of tables but is ~10x faster than the small method.3// - Crc32WithPoly uses 8Kb of tables but is ~10x faster than the small method.
lib/std/hash/fnv.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// FNV1a - Fowler-Noll-Vo hash function1// FNV1a - Fowler-Noll-Vo hash function
7//2//
8// FNV1a is a fast, non-cryptographic hash function with fairly good distribution properties.3// FNV1a is a fast, non-cryptographic hash function with fairly good distribution properties.
lib/std/hash/murmur.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = @import("builtin");2const builtin = @import("builtin");
8const testing = std.testing;3const testing = std.testing;
lib/std/hash/wyhash.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const mem = std.mem;2const mem = std.mem;
83
lib/std/hash_map.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const assert = debug.assert;2const assert = debug.assert;
8const autoHash = std.hash.autoHash;3const autoHash = std.hash.autoHash;
lib/std/heap.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const root = @import("root");2const root = @import("root");
8const debug = std.debug;3const debug = std.debug;
lib/std/heap/arena_allocator.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const mem = std.mem;3const mem = std.mem;
lib/std/heap/general_purpose_allocator.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6//! # General Purpose Allocator1//! # General Purpose Allocator
7//!2//!
8//! ## Design Priorities3//! ## Design Priorities
lib/std/heap/log_to_writer_allocator.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const Allocator = std.mem.Allocator;2const Allocator = std.mem.Allocator;
83
lib/std/heap/logging_allocator.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const Allocator = std.mem.Allocator;2const Allocator = std.mem.Allocator;
83
lib/std/io.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const root = @import("root");3const root = @import("root");
lib/std/io/bit_reader.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const io = std.io;3const io = std.io;
lib/std/io/bit_writer.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const io = std.io;3const io = std.io;
lib/std/io/buffered_atomic_file.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const mem = std.mem;2const mem = std.mem;
8const fs = std.fs;3const fs = std.fs;
lib/std/io/buffered_reader.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const io = std.io;2const io = std.io;
8const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/io/buffered_writer.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const io = std.io;2const io = std.io;
83
lib/std/io/c_writer.zig+13-18
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const io = std.io;3const io = std.io;
...@@ -17,19 +12,19 @@ pub fn cWriter(c_file: *std.c.FILE) CWriter {...@@ -17,19 +12,19 @@ pub fn cWriter(c_file: *std.c.FILE) CWriter {
17fn cWriterWrite(c_file: *std.c.FILE, bytes: []const u8) std.fs.File.WriteError!usize {12fn cWriterWrite(c_file: *std.c.FILE, bytes: []const u8) std.fs.File.WriteError!usize {
18 const amt_written = std.c.fwrite(bytes.ptr, 1, bytes.len, c_file);13 const amt_written = std.c.fwrite(bytes.ptr, 1, bytes.len, c_file);
19 if (amt_written >= 0) return amt_written;14 if (amt_written >= 0) return amt_written;
20 switch (std.c._errno().*) {15 switch (@intToEnum(os.E, std.c._errno().*)) {
21 0 => unreachable,16 .SUCCESS => unreachable,
22 os.EINVAL => unreachable,17 .INVAL => unreachable,
23 os.EFAULT => unreachable,18 .FAULT => unreachable,
24 os.EAGAIN => unreachable, // this is a blocking API19 .AGAIN => unreachable, // this is a blocking API
25 os.EBADF => unreachable, // always a race condition20 .BADF => unreachable, // always a race condition
26 os.EDESTADDRREQ => unreachable, // connect was never called21 .DESTADDRREQ => unreachable, // connect was never called
27 os.EDQUOT => return error.DiskQuota,22 .DQUOT => return error.DiskQuota,
28 os.EFBIG => return error.FileTooBig,23 .FBIG => return error.FileTooBig,
29 os.EIO => return error.InputOutput,24 .IO => return error.InputOutput,
30 os.ENOSPC => return error.NoSpaceLeft,25 .NOSPC => return error.NoSpaceLeft,
31 os.EPERM => return error.AccessDenied,26 .PERM => return error.AccessDenied,
32 os.EPIPE => return error.BrokenPipe,27 .PIPE => return error.BrokenPipe,
33 else => |err| return os.unexpectedErrno(err),28 else => |err| return os.unexpectedErrno(err),
34 }29 }
35}30}
lib/std/io/change_detection_stream.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../std.zig");1const std = @import("../std.zig");
8const io = std.io;2const io = std.io;
9const mem = std.mem;3const mem = std.mem;
lib/std/io/counting_reader.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const io = std.io;2const io = std.io;
8const testing = std.testing;3const testing = std.testing;
lib/std/io/counting_writer.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const io = std.io;2const io = std.io;
8const testing = std.testing;3const testing = std.testing;
lib/std/io/find_byte_writer.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../std.zig");1const std = @import("../std.zig");
8const io = std.io;2const io = std.io;
9const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/io/fixed_buffer_stream.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const io = std.io;2const io = std.io;
8const testing = std.testing;3const testing = std.testing;
lib/std/io/limited_reader.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2020 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const io = std.io;2const io = std.io;
8const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/io/multi_writer.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const io = std.io;2const io = std.io;
8const testing = std.testing;3const testing = std.testing;
lib/std/io/peek_stream.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const io = std.io;2const io = std.io;
8const mem = std.mem;3const mem = std.mem;
lib/std/io/reader.zig+17-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const math = std.math;3const math = std.math;
...@@ -143,6 +138,23 @@ pub fn Reader(...@@ -143,6 +138,23 @@ pub fn Reader(
143 return array_list.toOwnedSlice();138 return array_list.toOwnedSlice();
144 }139 }
145140
141 /// Reads from the stream until specified byte is found. If the buffer is not
142 /// large enough to hold the entire contents, `error.StreamTooLong` is returned.
143 /// Returns a slice of the stream data, with ptr equal to `buf.ptr`. The
144 /// delimiter byte is not included in the returned slice.
145 pub fn readUntilDelimiter(self: Self, buf: []u8, delimiter: u8) ![]u8 {
146 var index: usize = 0;
147 while (true) {
148 const byte = try self.readByte();
149
150 if (byte == delimiter) return buf[0..index];
151 if (index >= buf.len) return error.StreamTooLong;
152
153 buf[index] = byte;
154 index += 1;
155 }
156 }
157
146 /// Allocates enough memory to read until `delimiter` or end-of-stream.158 /// Allocates enough memory to read until `delimiter` or end-of-stream.
147 /// If the allocated memory would be greater than `max_size`, returns159 /// If the allocated memory would be greater than `max_size`, returns
148 /// `error.StreamTooLong`. If end-of-stream is found, returns the rest160 /// `error.StreamTooLong`. If end-of-stream is found, returns the rest
lib/std/io/seekable_stream.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
72
8pub fn SeekableStream(3pub fn SeekableStream(
lib/std/io/stream_source.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const io = std.io;2const io = std.io;
83
lib/std/io/test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = @import("builtin");2const builtin = @import("builtin");
8const io = std.io;3const io = std.io;
lib/std/io/writer.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const builtin = std.builtin;3const builtin = std.builtin;
lib/std/json.zig+128-9
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// JSON parser conforming to RFC8259.1// JSON parser conforming to RFC8259.
7//2//
8// https://tools.ietf.org/html/rfc82593// https://tools.ietf.org/html/rfc8259
...@@ -1468,7 +1463,9 @@ pub const ParseOptions = struct {...@@ -1468,7 +1463,9 @@ pub const ParseOptions = struct {
1468 allow_trailing_data: bool = false,1463 allow_trailing_data: bool = false,
1469};1464};
14701465
1471fn skipValue(tokens: *TokenStream) !void {1466const SkipValueError = error{UnexpectedJsonDepth} || TokenStream.Error;
1467
1468fn skipValue(tokens: *TokenStream) SkipValueError!void {
1472 const original_depth = tokens.stackUsed();1469 const original_depth = tokens.stackUsed();
14731470
1474 // Return an error if no value is found1471 // Return an error if no value is found
...@@ -1530,7 +1527,84 @@ test "skipValue" {...@@ -1530,7 +1527,84 @@ test "skipValue" {
1530 }1527 }
1531}1528}
15321529
1533fn parseInternal(comptime T: type, token: Token, tokens: *TokenStream, options: ParseOptions) !T {1530fn ParseInternalError(comptime T: type) type {
1531 // `inferred_types` is used to avoid infinite recursion for recursive type definitions.
1532 const inferred_types = [_]type{};
1533 return ParseInternalErrorImpl(T, &inferred_types);
1534}
1535
1536fn ParseInternalErrorImpl(comptime T: type, comptime inferred_types: []const type) type {
1537 for (inferred_types) |ty| {
1538 if (T == ty) return error{};
1539 }
1540
1541 switch (@typeInfo(T)) {
1542 .Bool => return error{UnexpectedToken},
1543 .Float, .ComptimeFloat => return error{UnexpectedToken} || std.fmt.ParseFloatError,
1544 .Int, .ComptimeInt => {
1545 return error{ UnexpectedToken, InvalidNumber, Overflow } ||
1546 std.fmt.ParseIntError || std.fmt.ParseFloatError;
1547 },
1548 .Optional => |optionalInfo| {
1549 return ParseInternalErrorImpl(optionalInfo.child, inferred_types ++ [_]type{T});
1550 },
1551 .Enum => return error{ UnexpectedToken, InvalidEnumTag } || std.fmt.ParseIntError ||
1552 std.meta.IntToEnumError || std.meta.IntToEnumError,
1553 .Union => |unionInfo| {
1554 if (unionInfo.tag_type) |_| {
1555 var errors = error{NoUnionMembersMatched};
1556 for (unionInfo.fields) |u_field| {
1557 errors = errors || ParseInternalErrorImpl(u_field.field_type, inferred_types ++ [_]type{T});
1558 }
1559 return errors;
1560 } else {
1561 @compileError("Unable to parse into untagged union '" ++ @typeName(T) ++ "'");
1562 }
1563 },
1564 .Struct => |structInfo| {
1565 var errors = error{
1566 DuplicateJSONField,
1567 UnexpectedEndOfJson,
1568 UnexpectedToken,
1569 UnexpectedValue,
1570 UnknownField,
1571 MissingField,
1572 } || SkipValueError || TokenStream.Error;
1573 for (structInfo.fields) |field| {
1574 errors = errors || ParseInternalErrorImpl(field.field_type, inferred_types ++ [_]type{T});
1575 }
1576 return errors;
1577 },
1578 .Array => |arrayInfo| {
1579 return error{ UnexpectedEndOfJson, UnexpectedToken } || TokenStream.Error ||
1580 UnescapeValidStringError ||
1581 ParseInternalErrorImpl(arrayInfo.child, inferred_types ++ [_]type{T});
1582 },
1583 .Pointer => |ptrInfo| {
1584 var errors = error{AllocatorRequired} || std.mem.Allocator.Error;
1585 switch (ptrInfo.size) {
1586 .One => {
1587 return errors || ParseInternalErrorImpl(ptrInfo.child, inferred_types ++ [_]type{T});
1588 },
1589 .Slice => {
1590 return errors || error{ UnexpectedEndOfJson, UnexpectedToken } ||
1591 ParseInternalErrorImpl(ptrInfo.child, inferred_types ++ [_]type{T}) ||
1592 UnescapeValidStringError || TokenStream.Error;
1593 },
1594 else => @compileError("Unable to parse into type '" ++ @typeName(T) ++ "'"),
1595 }
1596 },
1597 else => return error{},
1598 }
1599 unreachable;
1600}
1601
1602fn parseInternal(
1603 comptime T: type,
1604 token: Token,
1605 tokens: *TokenStream,
1606 options: ParseOptions,
1607) ParseInternalError(T)!T {
1534 switch (@typeInfo(T)) {1608 switch (@typeInfo(T)) {
1535 .Bool => {1609 .Bool => {
1536 return switch (token) {1610 return switch (token) {
...@@ -1794,7 +1868,11 @@ fn parseInternal(comptime T: type, token: Token, tokens: *TokenStream, options:...@@ -1794,7 +1868,11 @@ fn parseInternal(comptime T: type, token: Token, tokens: *TokenStream, options:
1794 unreachable;1868 unreachable;
1795}1869}
17961870
1797pub fn parse(comptime T: type, tokens: *TokenStream, options: ParseOptions) !T {1871pub fn ParseError(comptime T: type) type {
1872 return ParseInternalError(T) || error{UnexpectedEndOfJson} || TokenStream.Error;
1873}
1874
1875pub fn parse(comptime T: type, tokens: *TokenStream, options: ParseOptions) ParseError(T)!T {
1798 const token = (try tokens.next()) orelse return error.UnexpectedEndOfJson;1876 const token = (try tokens.next()) orelse return error.UnexpectedEndOfJson;
1799 const r = try parseInternal(T, token, tokens, options);1877 const r = try parseInternal(T, token, tokens, options);
1800 errdefer parseFree(T, r, options);1878 errdefer parseFree(T, r, options);
...@@ -2181,6 +2259,45 @@ test "parse into struct ignoring unknown fields" {...@@ -2181,6 +2259,45 @@ test "parse into struct ignoring unknown fields" {
2181 try testing.expectEqualSlices(u8, "zig", r.language);2259 try testing.expectEqualSlices(u8, "zig", r.language);
2182}2260}
21832261
2262const ParseIntoRecursiveUnionDefinitionValue = union(enum) {
2263 integer: i64,
2264 array: []const ParseIntoRecursiveUnionDefinitionValue,
2265};
2266
2267test "parse into recursive union definition" {
2268 const T = struct {
2269 values: ParseIntoRecursiveUnionDefinitionValue,
2270 };
2271 const ops = ParseOptions{ .allocator = testing.allocator };
2272
2273 const r = try parse(T, &std.json.TokenStream.init("{\"values\":[58]}"), ops);
2274 defer parseFree(T, r, ops);
2275
2276 try testing.expectEqual(@as(i64, 58), r.values.array[0].integer);
2277}
2278
2279const ParseIntoDoubleRecursiveUnionValueFirst = union(enum) {
2280 integer: i64,
2281 array: []const ParseIntoDoubleRecursiveUnionValueSecond,
2282};
2283
2284const ParseIntoDoubleRecursiveUnionValueSecond = union(enum) {
2285 boolean: bool,
2286 array: []const ParseIntoDoubleRecursiveUnionValueFirst,
2287};
2288
2289test "parse into double recursive union definition" {
2290 const T = struct {
2291 values: ParseIntoDoubleRecursiveUnionValueFirst,
2292 };
2293 const ops = ParseOptions{ .allocator = testing.allocator };
2294
2295 const r = try parse(T, &std.json.TokenStream.init("{\"values\":[[58]]}"), ops);
2296 defer parseFree(T, r, ops);
2297
2298 try testing.expectEqual(@as(i64, 58), r.values.array[0].array[0].integer);
2299}
2300
2184/// A non-stream JSON parser which constructs a tree of Value's.2301/// A non-stream JSON parser which constructs a tree of Value's.
2185pub const Parser = struct {2302pub const Parser = struct {
2186 allocator: *Allocator,2303 allocator: *Allocator,
...@@ -2418,10 +2535,12 @@ pub const Parser = struct {...@@ -2418,10 +2535,12 @@ pub const Parser = struct {
2418 }2535 }
2419};2536};
24202537
2538pub const UnescapeValidStringError = error{InvalidUnicodeHexSymbol};
2539
2421/// Unescape a JSON string2540/// Unescape a JSON string
2422/// Only to be used on strings already validated by the parser2541/// Only to be used on strings already validated by the parser
2423/// (note the unreachable statements and lack of bounds checking)2542/// (note the unreachable statements and lack of bounds checking)
2424pub fn unescapeValidString(output: []u8, input: []const u8) !void {2543pub fn unescapeValidString(output: []u8, input: []const u8) UnescapeValidStringError!void {
2425 var inIndex: usize = 0;2544 var inIndex: usize = 0;
2426 var outIndex: usize = 0;2545 var outIndex: usize = 0;
24272546
lib/std/json/test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// RFC 8529 conformance tests.1// RFC 8529 conformance tests.
7//2//
8// Tests are taken from https://github.com/nst/JSONTestSuite3// Tests are taken from https://github.com/nst/JSONTestSuite
lib/std/json/write_stream.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
lib/std/leb128.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const testing = std.testing;2const testing = std.testing;
83
lib/std/linked_list.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const debug = std.debug;2const debug = std.debug;
8const assert = debug.assert;3const assert = debug.assert;
lib/std/log.zig+40-25
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! std.log is a standardized interface for logging which allows for the logging1//! std.log is a standardized interface for logging which allows for the logging
8//! of programs and libraries using this interface to be formatted and filtered2//! of programs and libraries using this interface to be formatted and filtered
9//! by the implementer of the root.log function.3//! by the implementer of the root.log function.
...@@ -100,6 +94,23 @@ pub const Level = enum {...@@ -100,6 +94,23 @@ pub const Level = enum {
100 info,94 info,
101 /// Debug: messages only useful for debugging.95 /// Debug: messages only useful for debugging.
102 debug,96 debug,
97
98 /// Returns a string literal of the given level in full text form.
99 pub fn asText(comptime self: Level) switch (self) {
100 .emerg => @TypeOf("emergency"),
101 .crit => @TypeOf("critical"),
102 .err => @TypeOf("error"),
103 .warn => @TypeOf("warning"),
104 else => @TypeOf(@tagName(self)),
105 } {
106 return switch (self) {
107 .emerg => "emergency",
108 .crit => "critical",
109 .err => "error",
110 .warn => "warning",
111 else => @tagName(self),
112 };
113 }
103};114};
104115
105/// The default log level is based on build mode.116/// The default log level is based on build mode.
...@@ -145,30 +156,34 @@ fn log(...@@ -145,30 +156,34 @@ fn log(
145 if (@typeInfo(@TypeOf(root.log)) != .Fn)156 if (@typeInfo(@TypeOf(root.log)) != .Fn)
146 @compileError("Expected root.log to be a function");157 @compileError("Expected root.log to be a function");
147 root.log(message_level, scope, format, args);158 root.log(message_level, scope, format, args);
148 } else if (std.Target.current.os.tag == .freestanding) {
149 // On freestanding one must provide a log function; we do not have
150 // any I/O configured.
151 return;
152 } else {159 } else {
153 const level_txt = switch (message_level) {160 defaultLog(message_level, scope, format, args);
154 .emerg => "emergency",
155 .alert => "alert",
156 .crit => "critical",
157 .err => "error",
158 .warn => "warning",
159 .notice => "notice",
160 .info => "info",
161 .debug => "debug",
162 };
163 const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
164 const stderr = std.io.getStdErr().writer();
165 const held = std.debug.getStderrMutex().acquire();
166 defer held.release();
167 nosuspend stderr.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;
168 }161 }
169 }162 }
170}163}
171164
165/// The default implementation for root.log. root.log may forward log messages
166/// to this function.
167pub fn defaultLog(
168 comptime message_level: Level,
169 comptime scope: @Type(.EnumLiteral),
170 comptime format: []const u8,
171 args: anytype,
172) void {
173 if (std.Target.current.os.tag == .freestanding) {
174 // On freestanding one must provide a log function; we do not have
175 // any I/O configured.
176 return;
177 }
178
179 const level_txt = comptime message_level.asText();
180 const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
181 const stderr = std.io.getStdErr().writer();
182 const held = std.debug.getStderrMutex().acquire();
183 defer held.release();
184 nosuspend stderr.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;
185}
186
172/// Returns a scoped logging namespace that logs all messages using the scope187/// Returns a scoped logging namespace that logs all messages using the scope
173/// provided here.188/// provided here.
174pub fn scoped(comptime scope: @Type(.EnumLiteral)) type {189pub fn scoped(comptime scope: @Type(.EnumLiteral)) type {
lib/std/macho.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const mach_header = extern struct {1pub const mach_header = extern struct {
7 magic: u32,2 magic: u32,
8 cputype: cpu_type_t,3 cputype: cpu_type_t,
lib/std/math.zig+4-9
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const mem = std.mem;3const mem = std.mem;
...@@ -111,11 +106,11 @@ pub const inf = @import("math/inf.zig").inf;...@@ -111,11 +106,11 @@ pub const inf = @import("math/inf.zig").inf;
111/// the specified tolerance.106/// the specified tolerance.
112///107///
113/// The `tolerance` parameter is the absolute tolerance used when determining if108/// The `tolerance` parameter is the absolute tolerance used when determining if
114/// the two numbers are close enough, a good value for this parameter is a small109/// the two numbers are close enough; a good value for this parameter is a small
115/// multiple of `epsilon(T)`.110/// multiple of `epsilon(T)`.
116///111///
117/// Note that this function is recommended for for comparing small numbers112/// Note that this function is recommended for comparing small numbers
118/// around zero, using `approxEqRel` is suggested otherwise.113/// around zero; using `approxEqRel` is suggested otherwise.
119///114///
120/// NaN values are never considered equal to any value.115/// NaN values are never considered equal to any value.
121pub fn approxEqAbs(comptime T: type, x: T, y: T, tolerance: T) bool {116pub fn approxEqAbs(comptime T: type, x: T, y: T, tolerance: T) bool {
...@@ -138,7 +133,7 @@ pub fn approxEqAbs(comptime T: type, x: T, y: T, tolerance: T) bool {...@@ -138,7 +133,7 @@ pub fn approxEqAbs(comptime T: type, x: T, y: T, tolerance: T) bool {
138/// than zero.133/// than zero.
139///134///
140/// The `tolerance` parameter is the relative tolerance used when determining if135/// The `tolerance` parameter is the relative tolerance used when determining if
141/// the two numbers are close enough, a good value for this parameter is usually136/// the two numbers are close enough; a good value for this parameter is usually
142/// `sqrt(epsilon(T))`, meaning that the two numbers are considered equal if at137/// `sqrt(epsilon(T))`, meaning that the two numbers are considered equal if at
143/// least half of the digits are equal.138/// least half of the digits are equal.
144///139///
lib/std/math/acos.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/acosh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/asin.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/asinh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/atan.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/atan2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/atanh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/big.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
83
lib/std/math/big/int.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const math = std.math;2const math = std.math;
8const Limb = std.math.big.Limb;3const Limb = std.math.big.Limb;
lib/std/math/big/int_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const mem = std.mem;2const mem = std.mem;
8const testing = std.testing;3const testing = std.testing;
lib/std/math/big/rational.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const debug = std.debug;2const debug = std.debug;
8const math = std.math;3const math = std.math;
lib/std/math/cbrt.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/ceil.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/complex.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/abs.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/acos.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/acosh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/arg.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/asin.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/asinh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/atan.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/complex/atanh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/conj.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/cos.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/cosh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/complex/exp.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/complex/ldexp.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/complex/log.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/pow.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/proj.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/sin.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/sinh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/complex/sqrt.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/complex/tan.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const math = std.math;3const math = std.math;
lib/std/math/complex/tanh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/copysign.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/cos.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from go, which is licensed under a BSD-3 license.1// Ported from go, which is licensed under a BSD-3 license.
7// https://golang.org/LICENSE2// https://golang.org/LICENSE
8//3//
lib/std/math/cosh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/epsilon.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const math = @import("../math.zig");1const math = @import("../math.zig");
72
8/// Returns the machine epsilon for type T.3/// Returns the machine epsilon for type T.
lib/std/math/exp.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/exp2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/expm1.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/expo2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/fabs.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/floor.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/fma.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/frexp.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/hypot.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/ilogb.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/inf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const math = std.math;2const math = std.math;
83
lib/std/math/isfinite.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const math = std.math;2const math = std.math;
8const expect = std.testing.expect;3const expect = std.testing.expect;
lib/std/math/isinf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const math = std.math;2const math = std.math;
8const expect = std.testing.expect;3const expect = std.testing.expect;
lib/std/math/isnan.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const math = std.math;2const math = std.math;
8const expect = std.testing.expect;3const expect = std.testing.expect;
lib/std/math/isnormal.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const math = std.math;2const math = std.math;
8const expect = std.testing.expect;3const expect = std.testing.expect;
lib/std/math/ln.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/log.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/log10.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/log1p.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/log2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/modf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/nan.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const math = @import("../math.zig");1const math = @import("../math.zig");
72
8/// Returns the nan representation for type T.3/// Returns the nan representation for type T.
lib/std/math/pow.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from go, which is licensed under a BSD-3 license.1// Ported from go, which is licensed under a BSD-3 license.
7// https://golang.org/LICENSE2// https://golang.org/LICENSE
8//3//
lib/std/math/powi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Based on Rust, which is licensed under the MIT license.1// Based on Rust, which is licensed under the MIT license.
7// https://github.com/rust-lang/rust/blob/360432f1e8794de58cd94f34c9c17ad65871e5b5/LICENSE-MIT2// https://github.com/rust-lang/rust/blob/360432f1e8794de58cd94f34c9c17ad65871e5b5/LICENSE-MIT
8//3//
lib/std/math/round.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/scalbn.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/signbit.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const math = std.math;2const math = std.math;
8const expect = std.testing.expect;3const expect = std.testing.expect;
lib/std/math/sin.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from go, which is licensed under a BSD-3 license.1// Ported from go, which is licensed under a BSD-3 license.
7// https://golang.org/LICENSE2// https://golang.org/LICENSE
8//3//
lib/std/math/sinh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/sqrt.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const math = std.math;2const math = std.math;
8const expect = std.testing.expect;3const expect = std.testing.expect;
lib/std/math/tan.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from go, which is licensed under a BSD-3 license.1// Ported from go, which is licensed under a BSD-3 license.
7// https://golang.org/LICENSE2// https://golang.org/LICENSE
8//3//
lib/std/math/tanh.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/math/trunc.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from musl, which is licensed under the MIT license:1// Ported from musl, which is licensed under the MIT license:
7// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT2// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
8//3//
lib/std/mem.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const debug = std.debug;2const debug = std.debug;
8const assert = debug.assert;3const assert = debug.assert;
lib/std/mem/Allocator.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6//! The standard memory allocation interface.1//! The standard memory allocation interface.
72
8const std = @import("../std.zig");3const std = @import("../std.zig");
lib/std/meta.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const debug = std.debug;3const debug = std.debug;
lib/std/meta/trailer_flags.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const meta = std.meta;2const meta = std.meta;
8const testing = std.testing;3const testing = std.testing;
lib/std/meta/trait.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const mem = std.mem;3const mem = std.mem;
lib/std/multi_array_list.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const meta = std.meta;3const meta = std.meta;
lib/std/net.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const builtin = @import("builtin");2const builtin = @import("builtin");
8const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/net/test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const net = std.net;3const net = std.net;
lib/std/once.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const testing = std.testing;3const testing = std.testing;
lib/std/os.zig+1308-1313
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// This file contains thin wrappers around OS-specific APIs, with these1// This file contains thin wrappers around OS-specific APIs, with these
7// specific goals in mind:2// specific goals in mind:
8// * Convert "errno"-style error codes into Zig errors.3// * Convert "errno"-style error codes into Zig errors.
...@@ -116,13 +111,13 @@ pub fn close(fd: fd_t) void {...@@ -116,13 +111,13 @@ pub fn close(fd: fd_t) void {
116 if (comptime std.Target.current.isDarwin()) {111 if (comptime std.Target.current.isDarwin()) {
117 // This avoids the EINTR problem.112 // This avoids the EINTR problem.
118 switch (darwin.getErrno(darwin.@"close$NOCANCEL"(fd))) {113 switch (darwin.getErrno(darwin.@"close$NOCANCEL"(fd))) {
119 EBADF => unreachable, // Always a race condition.114 .BADF => unreachable, // Always a race condition.
120 else => return,115 else => return,
121 }116 }
122 }117 }
123 switch (errno(system.close(fd))) {118 switch (errno(system.close(fd))) {
124 EBADF => unreachable, // Always a race condition.119 .BADF => unreachable, // Always a race condition.
125 EINTR => return, // This is still a success. See https://github.com/ziglang/zig/issues/2425120 .INTR => return, // This is still a success. See https://github.com/ziglang/zig/issues/2425
126 else => return,121 else => return,
127 }122 }
128}123}
...@@ -159,11 +154,11 @@ pub fn getrandom(buffer: []u8) GetRandomError!void {...@@ -159,11 +154,11 @@ pub fn getrandom(buffer: []u8) GetRandomError!void {
159 };154 };
160155
161 switch (res.err) {156 switch (res.err) {
162 0 => buf = buf[res.num_read..],157 .SUCCESS => buf = buf[res.num_read..],
163 EINVAL => unreachable,158 .INVAL => unreachable,
164 EFAULT => unreachable,159 .FAULT => unreachable,
165 EINTR => continue,160 .INTR => continue,
166 ENOSYS => return getRandomBytesDevURandom(buf),161 .NOSYS => return getRandomBytesDevURandom(buf),
167 else => return unexpectedErrno(res.err),162 else => return unexpectedErrno(res.err),
168 }163 }
169 }164 }
...@@ -175,7 +170,7 @@ pub fn getrandom(buffer: []u8) GetRandomError!void {...@@ -175,7 +170,7 @@ pub fn getrandom(buffer: []u8) GetRandomError!void {
175 return;170 return;
176 },171 },
177 .wasi => switch (wasi.random_get(buffer.ptr, buffer.len)) {172 .wasi => switch (wasi.random_get(buffer.ptr, buffer.len)) {
178 0 => return,173 .SUCCESS => return,
179 else => |err| return unexpectedErrno(err),174 else => |err| return unexpectedErrno(err),
180 },175 },
181 else => return getRandomBytesDevURandom(buffer),176 else => return getRandomBytesDevURandom(buffer),
...@@ -238,7 +233,7 @@ pub const RaiseError = UnexpectedError;...@@ -238,7 +233,7 @@ pub const RaiseError = UnexpectedError;
238pub fn raise(sig: u8) RaiseError!void {233pub fn raise(sig: u8) RaiseError!void {
239 if (builtin.link_libc) {234 if (builtin.link_libc) {
240 switch (errno(system.raise(sig))) {235 switch (errno(system.raise(sig))) {
241 0 => return,236 .SUCCESS => return,
242 else => |err| return unexpectedErrno(err),237 else => |err| return unexpectedErrno(err),
243 }238 }
244 }239 }
...@@ -255,7 +250,7 @@ pub fn raise(sig: u8) RaiseError!void {...@@ -255,7 +250,7 @@ pub fn raise(sig: u8) RaiseError!void {
255 _ = linux.sigprocmask(SIG_SETMASK, &set, null);250 _ = linux.sigprocmask(SIG_SETMASK, &set, null);
256251
257 switch (errno(rc)) {252 switch (errno(rc)) {
258 0 => return,253 .SUCCESS => return,
259 else => |err| return unexpectedErrno(err),254 else => |err| return unexpectedErrno(err),
260 }255 }
261 }256 }
...@@ -267,10 +262,10 @@ pub const KillError = error{PermissionDenied} || UnexpectedError;...@@ -267,10 +262,10 @@ pub const KillError = error{PermissionDenied} || UnexpectedError;
267262
268pub fn kill(pid: pid_t, sig: u8) KillError!void {263pub fn kill(pid: pid_t, sig: u8) KillError!void {
269 switch (errno(system.kill(pid, sig))) {264 switch (errno(system.kill(pid, sig))) {
270 0 => return,265 .SUCCESS => return,
271 EINVAL => unreachable, // invalid signal266 .INVAL => unreachable, // invalid signal
272 EPERM => return error.PermissionDenied,267 .PERM => return error.PermissionDenied,
273 ESRCH => unreachable, // always a race condition268 .SRCH => unreachable, // always a race condition
274 else => |err| return unexpectedErrno(err),269 else => |err| return unexpectedErrno(err),
275 }270 }
276}271}
...@@ -342,19 +337,19 @@ pub fn read(fd: fd_t, buf: []u8) ReadError!usize {...@@ -342,19 +337,19 @@ pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
342337
343 var nread: usize = undefined;338 var nread: usize = undefined;
344 switch (wasi.fd_read(fd, &iovs, iovs.len, &nread)) {339 switch (wasi.fd_read(fd, &iovs, iovs.len, &nread)) {
345 wasi.ESUCCESS => return nread,340 .SUCCESS => return nread,
346 wasi.EINTR => unreachable,341 .INTR => unreachable,
347 wasi.EINVAL => unreachable,342 .INVAL => unreachable,
348 wasi.EFAULT => unreachable,343 .FAULT => unreachable,
349 wasi.EAGAIN => unreachable,344 .AGAIN => unreachable,
350 wasi.EBADF => return error.NotOpenForReading, // Can be a race condition.345 .BADF => return error.NotOpenForReading, // Can be a race condition.
351 wasi.EIO => return error.InputOutput,346 .IO => return error.InputOutput,
352 wasi.EISDIR => return error.IsDir,347 .ISDIR => return error.IsDir,
353 wasi.ENOBUFS => return error.SystemResources,348 .NOBUFS => return error.SystemResources,
354 wasi.ENOMEM => return error.SystemResources,349 .NOMEM => return error.SystemResources,
355 wasi.ECONNRESET => return error.ConnectionResetByPeer,350 .CONNRESET => return error.ConnectionResetByPeer,
356 wasi.ETIMEDOUT => return error.ConnectionTimedOut,351 .TIMEDOUT => return error.ConnectionTimedOut,
357 wasi.ENOTCAPABLE => return error.AccessDenied,352 .NOTCAPABLE => return error.AccessDenied,
358 else => |err| return unexpectedErrno(err),353 else => |err| return unexpectedErrno(err),
359 }354 }
360 }355 }
...@@ -370,18 +365,18 @@ pub fn read(fd: fd_t, buf: []u8) ReadError!usize {...@@ -370,18 +365,18 @@ pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
370 while (true) {365 while (true) {
371 const rc = system.read(fd, buf.ptr, adjusted_len);366 const rc = system.read(fd, buf.ptr, adjusted_len);
372 switch (errno(rc)) {367 switch (errno(rc)) {
373 0 => return @intCast(usize, rc),368 .SUCCESS => return @intCast(usize, rc),
374 EINTR => continue,369 .INTR => continue,
375 EINVAL => unreachable,370 .INVAL => unreachable,
376 EFAULT => unreachable,371 .FAULT => unreachable,
377 EAGAIN => return error.WouldBlock,372 .AGAIN => return error.WouldBlock,
378 EBADF => return error.NotOpenForReading, // Can be a race condition.373 .BADF => return error.NotOpenForReading, // Can be a race condition.
379 EIO => return error.InputOutput,374 .IO => return error.InputOutput,
380 EISDIR => return error.IsDir,375 .ISDIR => return error.IsDir,
381 ENOBUFS => return error.SystemResources,376 .NOBUFS => return error.SystemResources,
382 ENOMEM => return error.SystemResources,377 .NOMEM => return error.SystemResources,
383 ECONNRESET => return error.ConnectionResetByPeer,378 .CONNRESET => return error.ConnectionResetByPeer,
384 ETIMEDOUT => return error.ConnectionTimedOut,379 .TIMEDOUT => return error.ConnectionTimedOut,
385 else => |err| return unexpectedErrno(err),380 else => |err| return unexpectedErrno(err),
386 }381 }
387 }382 }
...@@ -407,17 +402,17 @@ pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {...@@ -407,17 +402,17 @@ pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {
407 if (builtin.os.tag == .wasi and !builtin.link_libc) {402 if (builtin.os.tag == .wasi and !builtin.link_libc) {
408 var nread: usize = undefined;403 var nread: usize = undefined;
409 switch (wasi.fd_read(fd, iov.ptr, iov.len, &nread)) {404 switch (wasi.fd_read(fd, iov.ptr, iov.len, &nread)) {
410 wasi.ESUCCESS => return nread,405 .SUCCESS => return nread,
411 wasi.EINTR => unreachable,406 .INTR => unreachable,
412 wasi.EINVAL => unreachable,407 .INVAL => unreachable,
413 wasi.EFAULT => unreachable,408 .FAULT => unreachable,
414 wasi.EAGAIN => unreachable, // currently not support in WASI409 .AGAIN => unreachable, // currently not support in WASI
415 wasi.EBADF => return error.NotOpenForReading, // can be a race condition410 .BADF => return error.NotOpenForReading, // can be a race condition
416 wasi.EIO => return error.InputOutput,411 .IO => return error.InputOutput,
417 wasi.EISDIR => return error.IsDir,412 .ISDIR => return error.IsDir,
418 wasi.ENOBUFS => return error.SystemResources,413 .NOBUFS => return error.SystemResources,
419 wasi.ENOMEM => return error.SystemResources,414 .NOMEM => return error.SystemResources,
420 wasi.ENOTCAPABLE => return error.AccessDenied,415 .NOTCAPABLE => return error.AccessDenied,
421 else => |err| return unexpectedErrno(err),416 else => |err| return unexpectedErrno(err),
422 }417 }
423 }418 }
...@@ -426,16 +421,16 @@ pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {...@@ -426,16 +421,16 @@ pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {
426 // TODO handle the case when iov_len is too large and get rid of this @intCast421 // TODO handle the case when iov_len is too large and get rid of this @intCast
427 const rc = system.readv(fd, iov.ptr, iov_count);422 const rc = system.readv(fd, iov.ptr, iov_count);
428 switch (errno(rc)) {423 switch (errno(rc)) {
429 0 => return @intCast(usize, rc),424 .SUCCESS => return @intCast(usize, rc),
430 EINTR => continue,425 .INTR => continue,
431 EINVAL => unreachable,426 .INVAL => unreachable,
432 EFAULT => unreachable,427 .FAULT => unreachable,
433 EAGAIN => return error.WouldBlock,428 .AGAIN => return error.WouldBlock,
434 EBADF => return error.NotOpenForReading, // can be a race condition429 .BADF => return error.NotOpenForReading, // can be a race condition
435 EIO => return error.InputOutput,430 .IO => return error.InputOutput,
436 EISDIR => return error.IsDir,431 .ISDIR => return error.IsDir,
437 ENOBUFS => return error.SystemResources,432 .NOBUFS => return error.SystemResources,
438 ENOMEM => return error.SystemResources,433 .NOMEM => return error.SystemResources,
439 else => |err| return unexpectedErrno(err),434 else => |err| return unexpectedErrno(err),
440 }435 }
441 }436 }
...@@ -469,21 +464,21 @@ pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {...@@ -469,21 +464,21 @@ pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {
469464
470 var nread: usize = undefined;465 var nread: usize = undefined;
471 switch (wasi.fd_pread(fd, &iovs, iovs.len, offset, &nread)) {466 switch (wasi.fd_pread(fd, &iovs, iovs.len, offset, &nread)) {
472 wasi.ESUCCESS => return nread,467 .SUCCESS => return nread,
473 wasi.EINTR => unreachable,468 .INTR => unreachable,
474 wasi.EINVAL => unreachable,469 .INVAL => unreachable,
475 wasi.EFAULT => unreachable,470 .FAULT => unreachable,
476 wasi.EAGAIN => unreachable,471 .AGAIN => unreachable,
477 wasi.EBADF => return error.NotOpenForReading, // Can be a race condition.472 .BADF => return error.NotOpenForReading, // Can be a race condition.
478 wasi.EIO => return error.InputOutput,473 .IO => return error.InputOutput,
479 wasi.EISDIR => return error.IsDir,474 .ISDIR => return error.IsDir,
480 wasi.ENOBUFS => return error.SystemResources,475 .NOBUFS => return error.SystemResources,
481 wasi.ENOMEM => return error.SystemResources,476 .NOMEM => return error.SystemResources,
482 wasi.ECONNRESET => return error.ConnectionResetByPeer,477 .CONNRESET => return error.ConnectionResetByPeer,
483 wasi.ENXIO => return error.Unseekable,478 .NXIO => return error.Unseekable,
484 wasi.ESPIPE => return error.Unseekable,479 .SPIPE => return error.Unseekable,
485 wasi.EOVERFLOW => return error.Unseekable,480 .OVERFLOW => return error.Unseekable,
486 wasi.ENOTCAPABLE => return error.AccessDenied,481 .NOTCAPABLE => return error.AccessDenied,
487 else => |err| return unexpectedErrno(err),482 else => |err| return unexpectedErrno(err),
488 }483 }
489 }484 }
...@@ -505,20 +500,20 @@ pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {...@@ -505,20 +500,20 @@ pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {
505 while (true) {500 while (true) {
506 const rc = pread_sym(fd, buf.ptr, adjusted_len, ioffset);501 const rc = pread_sym(fd, buf.ptr, adjusted_len, ioffset);
507 switch (errno(rc)) {502 switch (errno(rc)) {
508 0 => return @intCast(usize, rc),503 .SUCCESS => return @intCast(usize, rc),
509 EINTR => continue,504 .INTR => continue,
510 EINVAL => unreachable,505 .INVAL => unreachable,
511 EFAULT => unreachable,506 .FAULT => unreachable,
512 EAGAIN => return error.WouldBlock,507 .AGAIN => return error.WouldBlock,
513 EBADF => return error.NotOpenForReading, // Can be a race condition.508 .BADF => return error.NotOpenForReading, // Can be a race condition.
514 EIO => return error.InputOutput,509 .IO => return error.InputOutput,
515 EISDIR => return error.IsDir,510 .ISDIR => return error.IsDir,
516 ENOBUFS => return error.SystemResources,511 .NOBUFS => return error.SystemResources,
517 ENOMEM => return error.SystemResources,512 .NOMEM => return error.SystemResources,
518 ECONNRESET => return error.ConnectionResetByPeer,513 .CONNRESET => return error.ConnectionResetByPeer,
519 ENXIO => return error.Unseekable,514 .NXIO => return error.Unseekable,
520 ESPIPE => return error.Unseekable,515 .SPIPE => return error.Unseekable,
521 EOVERFLOW => return error.Unseekable,516 .OVERFLOW => return error.Unseekable,
522 else => |err| return unexpectedErrno(err),517 else => |err| return unexpectedErrno(err),
523 }518 }
524 }519 }
...@@ -558,15 +553,15 @@ pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {...@@ -558,15 +553,15 @@ pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {
558 }553 }
559 if (std.Target.current.os.tag == .wasi and !builtin.link_libc) {554 if (std.Target.current.os.tag == .wasi and !builtin.link_libc) {
560 switch (wasi.fd_filestat_set_size(fd, length)) {555 switch (wasi.fd_filestat_set_size(fd, length)) {
561 wasi.ESUCCESS => return,556 .SUCCESS => return,
562 wasi.EINTR => unreachable,557 .INTR => unreachable,
563 wasi.EFBIG => return error.FileTooBig,558 .FBIG => return error.FileTooBig,
564 wasi.EIO => return error.InputOutput,559 .IO => return error.InputOutput,
565 wasi.EPERM => return error.AccessDenied,560 .PERM => return error.AccessDenied,
566 wasi.ETXTBSY => return error.FileBusy,561 .TXTBSY => return error.FileBusy,
567 wasi.EBADF => unreachable, // Handle not open for writing562 .BADF => unreachable, // Handle not open for writing
568 wasi.EINVAL => unreachable, // Handle not open for writing563 .INVAL => unreachable, // Handle not open for writing
569 wasi.ENOTCAPABLE => return error.AccessDenied,564 .NOTCAPABLE => return error.AccessDenied,
570 else => |err| return unexpectedErrno(err),565 else => |err| return unexpectedErrno(err),
571 }566 }
572 }567 }
...@@ -579,14 +574,14 @@ pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {...@@ -579,14 +574,14 @@ pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {
579574
580 const ilen = @bitCast(i64, length); // the OS treats this as unsigned575 const ilen = @bitCast(i64, length); // the OS treats this as unsigned
581 switch (errno(ftruncate_sym(fd, ilen))) {576 switch (errno(ftruncate_sym(fd, ilen))) {
582 0 => return,577 .SUCCESS => return,
583 EINTR => continue,578 .INTR => continue,
584 EFBIG => return error.FileTooBig,579 .FBIG => return error.FileTooBig,
585 EIO => return error.InputOutput,580 .IO => return error.InputOutput,
586 EPERM => return error.AccessDenied,581 .PERM => return error.AccessDenied,
587 ETXTBSY => return error.FileBusy,582 .TXTBSY => return error.FileBusy,
588 EBADF => unreachable, // Handle not open for writing583 .BADF => unreachable, // Handle not open for writing
589 EINVAL => unreachable, // Handle not open for writing584 .INVAL => unreachable, // Handle not open for writing
590 else => |err| return unexpectedErrno(err),585 else => |err| return unexpectedErrno(err),
591 }586 }
592 }587 }
...@@ -620,20 +615,20 @@ pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) PReadError!usize {...@@ -620,20 +615,20 @@ pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) PReadError!usize {
620 if (builtin.os.tag == .wasi and !builtin.link_libc) {615 if (builtin.os.tag == .wasi and !builtin.link_libc) {
621 var nread: usize = undefined;616 var nread: usize = undefined;
622 switch (wasi.fd_pread(fd, iov.ptr, iov.len, offset, &nread)) {617 switch (wasi.fd_pread(fd, iov.ptr, iov.len, offset, &nread)) {
623 wasi.ESUCCESS => return nread,618 .SUCCESS => return nread,
624 wasi.EINTR => unreachable,619 .INTR => unreachable,
625 wasi.EINVAL => unreachable,620 .INVAL => unreachable,
626 wasi.EFAULT => unreachable,621 .FAULT => unreachable,
627 wasi.EAGAIN => unreachable,622 .AGAIN => unreachable,
628 wasi.EBADF => return error.NotOpenForReading, // can be a race condition623 .BADF => return error.NotOpenForReading, // can be a race condition
629 wasi.EIO => return error.InputOutput,624 .IO => return error.InputOutput,
630 wasi.EISDIR => return error.IsDir,625 .ISDIR => return error.IsDir,
631 wasi.ENOBUFS => return error.SystemResources,626 .NOBUFS => return error.SystemResources,
632 wasi.ENOMEM => return error.SystemResources,627 .NOMEM => return error.SystemResources,
633 wasi.ENXIO => return error.Unseekable,628 .NXIO => return error.Unseekable,
634 wasi.ESPIPE => return error.Unseekable,629 .SPIPE => return error.Unseekable,
635 wasi.EOVERFLOW => return error.Unseekable,630 .OVERFLOW => return error.Unseekable,
636 wasi.ENOTCAPABLE => return error.AccessDenied,631 .NOTCAPABLE => return error.AccessDenied,
637 else => |err| return unexpectedErrno(err),632 else => |err| return unexpectedErrno(err),
638 }633 }
639 }634 }
...@@ -649,19 +644,19 @@ pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) PReadError!usize {...@@ -649,19 +644,19 @@ pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) PReadError!usize {
649 while (true) {644 while (true) {
650 const rc = preadv_sym(fd, iov.ptr, iov_count, ioffset);645 const rc = preadv_sym(fd, iov.ptr, iov_count, ioffset);
651 switch (errno(rc)) {646 switch (errno(rc)) {
652 0 => return @bitCast(usize, rc),647 .SUCCESS => return @bitCast(usize, rc),
653 EINTR => continue,648 .INTR => continue,
654 EINVAL => unreachable,649 .INVAL => unreachable,
655 EFAULT => unreachable,650 .FAULT => unreachable,
656 EAGAIN => return error.WouldBlock,651 .AGAIN => return error.WouldBlock,
657 EBADF => return error.NotOpenForReading, // can be a race condition652 .BADF => return error.NotOpenForReading, // can be a race condition
658 EIO => return error.InputOutput,653 .IO => return error.InputOutput,
659 EISDIR => return error.IsDir,654 .ISDIR => return error.IsDir,
660 ENOBUFS => return error.SystemResources,655 .NOBUFS => return error.SystemResources,
661 ENOMEM => return error.SystemResources,656 .NOMEM => return error.SystemResources,
662 ENXIO => return error.Unseekable,657 .NXIO => return error.Unseekable,
663 ESPIPE => return error.Unseekable,658 .SPIPE => return error.Unseekable,
664 EOVERFLOW => return error.Unseekable,659 .OVERFLOW => return error.Unseekable,
665 else => |err| return unexpectedErrno(err),660 else => |err| return unexpectedErrno(err),
666 }661 }
667 }662 }
...@@ -723,20 +718,20 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {...@@ -723,20 +718,20 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {
723 }};718 }};
724 var nwritten: usize = undefined;719 var nwritten: usize = undefined;
725 switch (wasi.fd_write(fd, &ciovs, ciovs.len, &nwritten)) {720 switch (wasi.fd_write(fd, &ciovs, ciovs.len, &nwritten)) {
726 wasi.ESUCCESS => return nwritten,721 .SUCCESS => return nwritten,
727 wasi.EINTR => unreachable,722 .INTR => unreachable,
728 wasi.EINVAL => unreachable,723 .INVAL => unreachable,
729 wasi.EFAULT => unreachable,724 .FAULT => unreachable,
730 wasi.EAGAIN => unreachable,725 .AGAIN => unreachable,
731 wasi.EBADF => return error.NotOpenForWriting, // can be a race condition.726 .BADF => return error.NotOpenForWriting, // can be a race condition.
732 wasi.EDESTADDRREQ => unreachable, // `connect` was never called.727 .DESTADDRREQ => unreachable, // `connect` was never called.
733 wasi.EDQUOT => return error.DiskQuota,728 .DQUOT => return error.DiskQuota,
734 wasi.EFBIG => return error.FileTooBig,729 .FBIG => return error.FileTooBig,
735 wasi.EIO => return error.InputOutput,730 .IO => return error.InputOutput,
736 wasi.ENOSPC => return error.NoSpaceLeft,731 .NOSPC => return error.NoSpaceLeft,
737 wasi.EPERM => return error.AccessDenied,732 .PERM => return error.AccessDenied,
738 wasi.EPIPE => return error.BrokenPipe,733 .PIPE => return error.BrokenPipe,
739 wasi.ENOTCAPABLE => return error.AccessDenied,734 .NOTCAPABLE => return error.AccessDenied,
740 else => |err| return unexpectedErrno(err),735 else => |err| return unexpectedErrno(err),
741 }736 }
742 }737 }
...@@ -751,20 +746,20 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {...@@ -751,20 +746,20 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {
751 while (true) {746 while (true) {
752 const rc = system.write(fd, bytes.ptr, adjusted_len);747 const rc = system.write(fd, bytes.ptr, adjusted_len);
753 switch (errno(rc)) {748 switch (errno(rc)) {
754 0 => return @intCast(usize, rc),749 .SUCCESS => return @intCast(usize, rc),
755 EINTR => continue,750 .INTR => continue,
756 EINVAL => unreachable,751 .INVAL => unreachable,
757 EFAULT => unreachable,752 .FAULT => unreachable,
758 EAGAIN => return error.WouldBlock,753 .AGAIN => return error.WouldBlock,
759 EBADF => return error.NotOpenForWriting, // can be a race condition.754 .BADF => return error.NotOpenForWriting, // can be a race condition.
760 EDESTADDRREQ => unreachable, // `connect` was never called.755 .DESTADDRREQ => unreachable, // `connect` was never called.
761 EDQUOT => return error.DiskQuota,756 .DQUOT => return error.DiskQuota,
762 EFBIG => return error.FileTooBig,757 .FBIG => return error.FileTooBig,
763 EIO => return error.InputOutput,758 .IO => return error.InputOutput,
764 ENOSPC => return error.NoSpaceLeft,759 .NOSPC => return error.NoSpaceLeft,
765 EPERM => return error.AccessDenied,760 .PERM => return error.AccessDenied,
766 EPIPE => return error.BrokenPipe,761 .PIPE => return error.BrokenPipe,
767 ECONNRESET => return error.ConnectionResetByPeer,762 .CONNRESET => return error.ConnectionResetByPeer,
768 else => |err| return unexpectedErrno(err),763 else => |err| return unexpectedErrno(err),
769 }764 }
770 }765 }
...@@ -787,7 +782,7 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {...@@ -787,7 +782,7 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {
787/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are782/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
788/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.783/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
789///784///
790/// If `iov.len` is larger than will fit in a `u31`, a partial write will occur.785/// If `iov.len` is larger than `IOV_MAX`, a partial write will occur.
791pub fn writev(fd: fd_t, iov: []const iovec_const) WriteError!usize {786pub fn writev(fd: fd_t, iov: []const iovec_const) WriteError!usize {
792 if (std.Target.current.os.tag == .windows) {787 if (std.Target.current.os.tag == .windows) {
793 // TODO improve this to use WriteFileScatter788 // TODO improve this to use WriteFileScatter
...@@ -798,42 +793,42 @@ pub fn writev(fd: fd_t, iov: []const iovec_const) WriteError!usize {...@@ -798,42 +793,42 @@ pub fn writev(fd: fd_t, iov: []const iovec_const) WriteError!usize {
798 if (builtin.os.tag == .wasi and !builtin.link_libc) {793 if (builtin.os.tag == .wasi and !builtin.link_libc) {
799 var nwritten: usize = undefined;794 var nwritten: usize = undefined;
800 switch (wasi.fd_write(fd, iov.ptr, iov.len, &nwritten)) {795 switch (wasi.fd_write(fd, iov.ptr, iov.len, &nwritten)) {
801 wasi.ESUCCESS => return nwritten,796 .SUCCESS => return nwritten,
802 wasi.EINTR => unreachable,797 .INTR => unreachable,
803 wasi.EINVAL => unreachable,798 .INVAL => unreachable,
804 wasi.EFAULT => unreachable,799 .FAULT => unreachable,
805 wasi.EAGAIN => unreachable,800 .AGAIN => unreachable,
806 wasi.EBADF => return error.NotOpenForWriting, // can be a race condition.801 .BADF => return error.NotOpenForWriting, // can be a race condition.
807 wasi.EDESTADDRREQ => unreachable, // `connect` was never called.802 .DESTADDRREQ => unreachable, // `connect` was never called.
808 wasi.EDQUOT => return error.DiskQuota,803 .DQUOT => return error.DiskQuota,
809 wasi.EFBIG => return error.FileTooBig,804 .FBIG => return error.FileTooBig,
810 wasi.EIO => return error.InputOutput,805 .IO => return error.InputOutput,
811 wasi.ENOSPC => return error.NoSpaceLeft,806 .NOSPC => return error.NoSpaceLeft,
812 wasi.EPERM => return error.AccessDenied,807 .PERM => return error.AccessDenied,
813 wasi.EPIPE => return error.BrokenPipe,808 .PIPE => return error.BrokenPipe,
814 wasi.ENOTCAPABLE => return error.AccessDenied,809 .NOTCAPABLE => return error.AccessDenied,
815 else => |err| return unexpectedErrno(err),810 else => |err| return unexpectedErrno(err),
816 }811 }
817 }812 }
818813
819 const iov_count = math.cast(u31, iov.len) catch math.maxInt(u31);814 const iov_count = if (iov.len > IOV_MAX) IOV_MAX else @intCast(u31, iov.len);
820 while (true) {815 while (true) {
821 const rc = system.writev(fd, iov.ptr, iov_count);816 const rc = system.writev(fd, iov.ptr, iov_count);
822 switch (errno(rc)) {817 switch (errno(rc)) {
823 0 => return @intCast(usize, rc),818 .SUCCESS => return @intCast(usize, rc),
824 EINTR => continue,819 .INTR => continue,
825 EINVAL => unreachable,820 .INVAL => unreachable,
826 EFAULT => unreachable,821 .FAULT => unreachable,
827 EAGAIN => return error.WouldBlock,822 .AGAIN => return error.WouldBlock,
828 EBADF => return error.NotOpenForWriting, // Can be a race condition.823 .BADF => return error.NotOpenForWriting, // Can be a race condition.
829 EDESTADDRREQ => unreachable, // `connect` was never called.824 .DESTADDRREQ => unreachable, // `connect` was never called.
830 EDQUOT => return error.DiskQuota,825 .DQUOT => return error.DiskQuota,
831 EFBIG => return error.FileTooBig,826 .FBIG => return error.FileTooBig,
832 EIO => return error.InputOutput,827 .IO => return error.InputOutput,
833 ENOSPC => return error.NoSpaceLeft,828 .NOSPC => return error.NoSpaceLeft,
834 EPERM => return error.AccessDenied,829 .PERM => return error.AccessDenied,
835 EPIPE => return error.BrokenPipe,830 .PIPE => return error.BrokenPipe,
836 ECONNRESET => return error.ConnectionResetByPeer,831 .CONNRESET => return error.ConnectionResetByPeer,
837 else => |err| return unexpectedErrno(err),832 else => |err| return unexpectedErrno(err),
838 }833 }
839 }834 }
...@@ -875,23 +870,23 @@ pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {...@@ -875,23 +870,23 @@ pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {
875870
876 var nwritten: usize = undefined;871 var nwritten: usize = undefined;
877 switch (wasi.fd_pwrite(fd, &ciovs, ciovs.len, offset, &nwritten)) {872 switch (wasi.fd_pwrite(fd, &ciovs, ciovs.len, offset, &nwritten)) {
878 wasi.ESUCCESS => return nwritten,873 .SUCCESS => return nwritten,
879 wasi.EINTR => unreachable,874 .INTR => unreachable,
880 wasi.EINVAL => unreachable,875 .INVAL => unreachable,
881 wasi.EFAULT => unreachable,876 .FAULT => unreachable,
882 wasi.EAGAIN => unreachable,877 .AGAIN => unreachable,
883 wasi.EBADF => return error.NotOpenForWriting, // can be a race condition.878 .BADF => return error.NotOpenForWriting, // can be a race condition.
884 wasi.EDESTADDRREQ => unreachable, // `connect` was never called.879 .DESTADDRREQ => unreachable, // `connect` was never called.
885 wasi.EDQUOT => return error.DiskQuota,880 .DQUOT => return error.DiskQuota,
886 wasi.EFBIG => return error.FileTooBig,881 .FBIG => return error.FileTooBig,
887 wasi.EIO => return error.InputOutput,882 .IO => return error.InputOutput,
888 wasi.ENOSPC => return error.NoSpaceLeft,883 .NOSPC => return error.NoSpaceLeft,
889 wasi.EPERM => return error.AccessDenied,884 .PERM => return error.AccessDenied,
890 wasi.EPIPE => return error.BrokenPipe,885 .PIPE => return error.BrokenPipe,
891 wasi.ENXIO => return error.Unseekable,886 .NXIO => return error.Unseekable,
892 wasi.ESPIPE => return error.Unseekable,887 .SPIPE => return error.Unseekable,
893 wasi.EOVERFLOW => return error.Unseekable,888 .OVERFLOW => return error.Unseekable,
894 wasi.ENOTCAPABLE => return error.AccessDenied,889 .NOTCAPABLE => return error.AccessDenied,
895 else => |err| return unexpectedErrno(err),890 else => |err| return unexpectedErrno(err),
896 }891 }
897 }892 }
...@@ -913,22 +908,22 @@ pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {...@@ -913,22 +908,22 @@ pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {
913 while (true) {908 while (true) {
914 const rc = pwrite_sym(fd, bytes.ptr, adjusted_len, ioffset);909 const rc = pwrite_sym(fd, bytes.ptr, adjusted_len, ioffset);
915 switch (errno(rc)) {910 switch (errno(rc)) {
916 0 => return @intCast(usize, rc),911 .SUCCESS => return @intCast(usize, rc),
917 EINTR => continue,912 .INTR => continue,
918 EINVAL => unreachable,913 .INVAL => unreachable,
919 EFAULT => unreachable,914 .FAULT => unreachable,
920 EAGAIN => return error.WouldBlock,915 .AGAIN => return error.WouldBlock,
921 EBADF => return error.NotOpenForWriting, // Can be a race condition.916 .BADF => return error.NotOpenForWriting, // Can be a race condition.
922 EDESTADDRREQ => unreachable, // `connect` was never called.917 .DESTADDRREQ => unreachable, // `connect` was never called.
923 EDQUOT => return error.DiskQuota,918 .DQUOT => return error.DiskQuota,
924 EFBIG => return error.FileTooBig,919 .FBIG => return error.FileTooBig,
925 EIO => return error.InputOutput,920 .IO => return error.InputOutput,
926 ENOSPC => return error.NoSpaceLeft,921 .NOSPC => return error.NoSpaceLeft,
927 EPERM => return error.AccessDenied,922 .PERM => return error.AccessDenied,
928 EPIPE => return error.BrokenPipe,923 .PIPE => return error.BrokenPipe,
929 ENXIO => return error.Unseekable,924 .NXIO => return error.Unseekable,
930 ESPIPE => return error.Unseekable,925 .SPIPE => return error.Unseekable,
931 EOVERFLOW => return error.Unseekable,926 .OVERFLOW => return error.Unseekable,
932 else => |err| return unexpectedErrno(err),927 else => |err| return unexpectedErrno(err),
933 }928 }
934 }929 }
...@@ -954,7 +949,7 @@ pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {...@@ -954,7 +949,7 @@ pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {
954/// * Darwin949/// * Darwin
955/// * Windows950/// * Windows
956///951///
957/// If `iov.len` is larger than will fit in a `u31`, a partial write will occur.952/// If `iov.len` is larger than `IOV_MAX`, a partial write will occur.
958pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usize {953pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usize {
959 const have_pwrite_but_not_pwritev = switch (std.Target.current.os.tag) {954 const have_pwrite_but_not_pwritev = switch (std.Target.current.os.tag) {
960 .windows, .macos, .ios, .watchos, .tvos, .haiku => true,955 .windows, .macos, .ios, .watchos, .tvos, .haiku => true,
...@@ -971,23 +966,23 @@ pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usiz...@@ -971,23 +966,23 @@ pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usiz
971 if (builtin.os.tag == .wasi and !builtin.link_libc) {966 if (builtin.os.tag == .wasi and !builtin.link_libc) {
972 var nwritten: usize = undefined;967 var nwritten: usize = undefined;
973 switch (wasi.fd_pwrite(fd, iov.ptr, iov.len, offset, &nwritten)) {968 switch (wasi.fd_pwrite(fd, iov.ptr, iov.len, offset, &nwritten)) {
974 wasi.ESUCCESS => return nwritten,969 .SUCCESS => return nwritten,
975 wasi.EINTR => unreachable,970 .INTR => unreachable,
976 wasi.EINVAL => unreachable,971 .INVAL => unreachable,
977 wasi.EFAULT => unreachable,972 .FAULT => unreachable,
978 wasi.EAGAIN => unreachable,973 .AGAIN => unreachable,
979 wasi.EBADF => return error.NotOpenForWriting, // Can be a race condition.974 .BADF => return error.NotOpenForWriting, // Can be a race condition.
980 wasi.EDESTADDRREQ => unreachable, // `connect` was never called.975 .DESTADDRREQ => unreachable, // `connect` was never called.
981 wasi.EDQUOT => return error.DiskQuota,976 .DQUOT => return error.DiskQuota,
982 wasi.EFBIG => return error.FileTooBig,977 .FBIG => return error.FileTooBig,
983 wasi.EIO => return error.InputOutput,978 .IO => return error.InputOutput,
984 wasi.ENOSPC => return error.NoSpaceLeft,979 .NOSPC => return error.NoSpaceLeft,
985 wasi.EPERM => return error.AccessDenied,980 .PERM => return error.AccessDenied,
986 wasi.EPIPE => return error.BrokenPipe,981 .PIPE => return error.BrokenPipe,
987 wasi.ENXIO => return error.Unseekable,982 .NXIO => return error.Unseekable,
988 wasi.ESPIPE => return error.Unseekable,983 .SPIPE => return error.Unseekable,
989 wasi.EOVERFLOW => return error.Unseekable,984 .OVERFLOW => return error.Unseekable,
990 wasi.ENOTCAPABLE => return error.AccessDenied,985 .NOTCAPABLE => return error.AccessDenied,
991 else => |err| return unexpectedErrno(err),986 else => |err| return unexpectedErrno(err),
992 }987 }
993 }988 }
...@@ -997,27 +992,27 @@ pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usiz...@@ -997,27 +992,27 @@ pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usiz
997 else992 else
998 system.pwritev;993 system.pwritev;
999994
1000 const iov_count = math.cast(u31, iov.len) catch math.maxInt(u31);995 const iov_count = if (iov.len > IOV_MAX) IOV_MAX else @intCast(u31, iov.len);
1001 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned996 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned
1002 while (true) {997 while (true) {
1003 const rc = pwritev_sym(fd, iov.ptr, iov_count, ioffset);998 const rc = pwritev_sym(fd, iov.ptr, iov_count, ioffset);
1004 switch (errno(rc)) {999 switch (errno(rc)) {
1005 0 => return @intCast(usize, rc),1000 .SUCCESS => return @intCast(usize, rc),
1006 EINTR => continue,1001 .INTR => continue,
1007 EINVAL => unreachable,1002 .INVAL => unreachable,
1008 EFAULT => unreachable,1003 .FAULT => unreachable,
1009 EAGAIN => return error.WouldBlock,1004 .AGAIN => return error.WouldBlock,
1010 EBADF => return error.NotOpenForWriting, // Can be a race condition.1005 .BADF => return error.NotOpenForWriting, // Can be a race condition.
1011 EDESTADDRREQ => unreachable, // `connect` was never called.1006 .DESTADDRREQ => unreachable, // `connect` was never called.
1012 EDQUOT => return error.DiskQuota,1007 .DQUOT => return error.DiskQuota,
1013 EFBIG => return error.FileTooBig,1008 .FBIG => return error.FileTooBig,
1014 EIO => return error.InputOutput,1009 .IO => return error.InputOutput,
1015 ENOSPC => return error.NoSpaceLeft,1010 .NOSPC => return error.NoSpaceLeft,
1016 EPERM => return error.AccessDenied,1011 .PERM => return error.AccessDenied,
1017 EPIPE => return error.BrokenPipe,1012 .PIPE => return error.BrokenPipe,
1018 ENXIO => return error.Unseekable,1013 .NXIO => return error.Unseekable,
1019 ESPIPE => return error.Unseekable,1014 .SPIPE => return error.Unseekable,
1020 EOVERFLOW => return error.Unseekable,1015 .OVERFLOW => return error.Unseekable,
1021 else => |err| return unexpectedErrno(err),1016 else => |err| return unexpectedErrno(err),
1022 }1017 }
1023 }1018 }
...@@ -1098,27 +1093,27 @@ pub fn openZ(file_path: [*:0]const u8, flags: u32, perm: mode_t) OpenError!fd_t...@@ -1098,27 +1093,27 @@ pub fn openZ(file_path: [*:0]const u8, flags: u32, perm: mode_t) OpenError!fd_t
1098 while (true) {1093 while (true) {
1099 const rc = open_sym(file_path, flags, perm);1094 const rc = open_sym(file_path, flags, perm);
1100 switch (errno(rc)) {1095 switch (errno(rc)) {
1101 0 => return @intCast(fd_t, rc),1096 .SUCCESS => return @intCast(fd_t, rc),
1102 EINTR => continue,1097 .INTR => continue,
11031098
1104 EFAULT => unreachable,1099 .FAULT => unreachable,
1105 EINVAL => unreachable,1100 .INVAL => unreachable,
1106 EACCES => return error.AccessDenied,1101 .ACCES => return error.AccessDenied,
1107 EFBIG => return error.FileTooBig,1102 .FBIG => return error.FileTooBig,
1108 EOVERFLOW => return error.FileTooBig,1103 .OVERFLOW => return error.FileTooBig,
1109 EISDIR => return error.IsDir,1104 .ISDIR => return error.IsDir,
1110 ELOOP => return error.SymLinkLoop,1105 .LOOP => return error.SymLinkLoop,
1111 EMFILE => return error.ProcessFdQuotaExceeded,1106 .MFILE => return error.ProcessFdQuotaExceeded,
1112 ENAMETOOLONG => return error.NameTooLong,1107 .NAMETOOLONG => return error.NameTooLong,
1113 ENFILE => return error.SystemFdQuotaExceeded,1108 .NFILE => return error.SystemFdQuotaExceeded,
1114 ENODEV => return error.NoDevice,1109 .NODEV => return error.NoDevice,
1115 ENOENT => return error.FileNotFound,1110 .NOENT => return error.FileNotFound,
1116 ENOMEM => return error.SystemResources,1111 .NOMEM => return error.SystemResources,
1117 ENOSPC => return error.NoSpaceLeft,1112 .NOSPC => return error.NoSpaceLeft,
1118 ENOTDIR => return error.NotDir,1113 .NOTDIR => return error.NotDir,
1119 EPERM => return error.AccessDenied,1114 .PERM => return error.AccessDenied,
1120 EEXIST => return error.PathAlreadyExists,1115 .EXIST => return error.PathAlreadyExists,
1121 EBUSY => return error.DeviceBusy,1116 .BUSY => return error.DeviceBusy,
1122 else => |err| return unexpectedErrno(err),1117 else => |err| return unexpectedErrno(err),
1123 }1118 }
1124 }1119 }
...@@ -1193,28 +1188,28 @@ pub fn openatWasi(dir_fd: fd_t, file_path: []const u8, lookup_flags: lookupflags...@@ -1193,28 +1188,28 @@ pub fn openatWasi(dir_fd: fd_t, file_path: []const u8, lookup_flags: lookupflags
1193 while (true) {1188 while (true) {
1194 var fd: fd_t = undefined;1189 var fd: fd_t = undefined;
1195 switch (wasi.path_open(dir_fd, lookup_flags, file_path.ptr, file_path.len, oflags, base, inheriting, fdflags, &fd)) {1190 switch (wasi.path_open(dir_fd, lookup_flags, file_path.ptr, file_path.len, oflags, base, inheriting, fdflags, &fd)) {
1196 wasi.ESUCCESS => return fd,1191 .SUCCESS => return fd,
1197 wasi.EINTR => continue,1192 .INTR => continue,
11981193
1199 wasi.EFAULT => unreachable,1194 .FAULT => unreachable,
1200 wasi.EINVAL => unreachable,1195 .INVAL => unreachable,
1201 wasi.EACCES => return error.AccessDenied,1196 .ACCES => return error.AccessDenied,
1202 wasi.EFBIG => return error.FileTooBig,1197 .FBIG => return error.FileTooBig,
1203 wasi.EOVERFLOW => return error.FileTooBig,1198 .OVERFLOW => return error.FileTooBig,
1204 wasi.EISDIR => return error.IsDir,1199 .ISDIR => return error.IsDir,
1205 wasi.ELOOP => return error.SymLinkLoop,1200 .LOOP => return error.SymLinkLoop,
1206 wasi.EMFILE => return error.ProcessFdQuotaExceeded,1201 .MFILE => return error.ProcessFdQuotaExceeded,
1207 wasi.ENAMETOOLONG => return error.NameTooLong,1202 .NAMETOOLONG => return error.NameTooLong,
1208 wasi.ENFILE => return error.SystemFdQuotaExceeded,1203 .NFILE => return error.SystemFdQuotaExceeded,
1209 wasi.ENODEV => return error.NoDevice,1204 .NODEV => return error.NoDevice,
1210 wasi.ENOENT => return error.FileNotFound,1205 .NOENT => return error.FileNotFound,
1211 wasi.ENOMEM => return error.SystemResources,1206 .NOMEM => return error.SystemResources,
1212 wasi.ENOSPC => return error.NoSpaceLeft,1207 .NOSPC => return error.NoSpaceLeft,
1213 wasi.ENOTDIR => return error.NotDir,1208 .NOTDIR => return error.NotDir,
1214 wasi.EPERM => return error.AccessDenied,1209 .PERM => return error.AccessDenied,
1215 wasi.EEXIST => return error.PathAlreadyExists,1210 .EXIST => return error.PathAlreadyExists,
1216 wasi.EBUSY => return error.DeviceBusy,1211 .BUSY => return error.DeviceBusy,
1217 wasi.ENOTCAPABLE => return error.AccessDenied,1212 .NOTCAPABLE => return error.AccessDenied,
1218 else => |err| return unexpectedErrno(err),1213 else => |err| return unexpectedErrno(err),
1219 }1214 }
1220 }1215 }
...@@ -1239,30 +1234,30 @@ pub fn openatZ(dir_fd: fd_t, file_path: [*:0]const u8, flags: u32, mode: mode_t)...@@ -1239,30 +1234,30 @@ pub fn openatZ(dir_fd: fd_t, file_path: [*:0]const u8, flags: u32, mode: mode_t)
1239 while (true) {1234 while (true) {
1240 const rc = openat_sym(dir_fd, file_path, flags, mode);1235 const rc = openat_sym(dir_fd, file_path, flags, mode);
1241 switch (errno(rc)) {1236 switch (errno(rc)) {
1242 0 => return @intCast(fd_t, rc),1237 .SUCCESS => return @intCast(fd_t, rc),
1243 EINTR => continue,1238 .INTR => continue,
12441239
1245 EFAULT => unreachable,1240 .FAULT => unreachable,
1246 EINVAL => unreachable,1241 .INVAL => unreachable,
1247 EBADF => unreachable,1242 .BADF => unreachable,
1248 EACCES => return error.AccessDenied,1243 .ACCES => return error.AccessDenied,
1249 EFBIG => return error.FileTooBig,1244 .FBIG => return error.FileTooBig,
1250 EOVERFLOW => return error.FileTooBig,1245 .OVERFLOW => return error.FileTooBig,
1251 EISDIR => return error.IsDir,1246 .ISDIR => return error.IsDir,
1252 ELOOP => return error.SymLinkLoop,1247 .LOOP => return error.SymLinkLoop,
1253 EMFILE => return error.ProcessFdQuotaExceeded,1248 .MFILE => return error.ProcessFdQuotaExceeded,
1254 ENAMETOOLONG => return error.NameTooLong,1249 .NAMETOOLONG => return error.NameTooLong,
1255 ENFILE => return error.SystemFdQuotaExceeded,1250 .NFILE => return error.SystemFdQuotaExceeded,
1256 ENODEV => return error.NoDevice,1251 .NODEV => return error.NoDevice,
1257 ENOENT => return error.FileNotFound,1252 .NOENT => return error.FileNotFound,
1258 ENOMEM => return error.SystemResources,1253 .NOMEM => return error.SystemResources,
1259 ENOSPC => return error.NoSpaceLeft,1254 .NOSPC => return error.NoSpaceLeft,
1260 ENOTDIR => return error.NotDir,1255 .NOTDIR => return error.NotDir,
1261 EPERM => return error.AccessDenied,1256 .PERM => return error.AccessDenied,
1262 EEXIST => return error.PathAlreadyExists,1257 .EXIST => return error.PathAlreadyExists,
1263 EBUSY => return error.DeviceBusy,1258 .BUSY => return error.DeviceBusy,
1264 EOPNOTSUPP => return error.FileLocksNotSupported,1259 .OPNOTSUPP => return error.FileLocksNotSupported,
1265 EWOULDBLOCK => return error.WouldBlock,1260 .AGAIN => return error.WouldBlock,
1266 else => |err| return unexpectedErrno(err),1261 else => |err| return unexpectedErrno(err),
1267 }1262 }
1268 }1263 }
...@@ -1286,9 +1281,9 @@ pub fn openatW(dir_fd: fd_t, file_path_w: []const u16, flags: u32, mode: mode_t)...@@ -1286,9 +1281,9 @@ pub fn openatW(dir_fd: fd_t, file_path_w: []const u16, flags: u32, mode: mode_t)
1286pub fn dup(old_fd: fd_t) !fd_t {1281pub fn dup(old_fd: fd_t) !fd_t {
1287 const rc = system.dup(old_fd);1282 const rc = system.dup(old_fd);
1288 return switch (errno(rc)) {1283 return switch (errno(rc)) {
1289 0 => return @intCast(fd_t, rc),1284 .SUCCESS => return @intCast(fd_t, rc),
1290 EMFILE => error.ProcessFdQuotaExceeded,1285 .MFILE => error.ProcessFdQuotaExceeded,
1291 EBADF => unreachable, // invalid file descriptor1286 .BADF => unreachable, // invalid file descriptor
1292 else => |err| return unexpectedErrno(err),1287 else => |err| return unexpectedErrno(err),
1293 };1288 };
1294}1289}
...@@ -1296,11 +1291,11 @@ pub fn dup(old_fd: fd_t) !fd_t {...@@ -1296,11 +1291,11 @@ pub fn dup(old_fd: fd_t) !fd_t {
1296pub fn dup2(old_fd: fd_t, new_fd: fd_t) !void {1291pub fn dup2(old_fd: fd_t, new_fd: fd_t) !void {
1297 while (true) {1292 while (true) {
1298 switch (errno(system.dup2(old_fd, new_fd))) {1293 switch (errno(system.dup2(old_fd, new_fd))) {
1299 0 => return,1294 .SUCCESS => return,
1300 EBUSY, EINTR => continue,1295 .BUSY, .INTR => continue,
1301 EMFILE => return error.ProcessFdQuotaExceeded,1296 .MFILE => return error.ProcessFdQuotaExceeded,
1302 EINVAL => unreachable, // invalid parameters passed to dup21297 .INVAL => unreachable, // invalid parameters passed to dup2
1303 EBADF => unreachable, // invalid file descriptor1298 .BADF => unreachable, // invalid file descriptor
1304 else => |err| return unexpectedErrno(err),1299 else => |err| return unexpectedErrno(err),
1305 }1300 }
1306 }1301 }
...@@ -1331,23 +1326,23 @@ pub fn execveZ(...@@ -1331,23 +1326,23 @@ pub fn execveZ(
1331 envp: [*:null]const ?[*:0]const u8,1326 envp: [*:null]const ?[*:0]const u8,
1332) ExecveError {1327) ExecveError {
1333 switch (errno(system.execve(path, child_argv, envp))) {1328 switch (errno(system.execve(path, child_argv, envp))) {
1334 0 => unreachable,1329 .SUCCESS => unreachable,
1335 EFAULT => unreachable,1330 .FAULT => unreachable,
1336 E2BIG => return error.SystemResources,1331 .@"2BIG" => return error.SystemResources,
1337 EMFILE => return error.ProcessFdQuotaExceeded,1332 .MFILE => return error.ProcessFdQuotaExceeded,
1338 ENAMETOOLONG => return error.NameTooLong,1333 .NAMETOOLONG => return error.NameTooLong,
1339 ENFILE => return error.SystemFdQuotaExceeded,1334 .NFILE => return error.SystemFdQuotaExceeded,
1340 ENOMEM => return error.SystemResources,1335 .NOMEM => return error.SystemResources,
1341 EACCES => return error.AccessDenied,1336 .ACCES => return error.AccessDenied,
1342 EPERM => return error.AccessDenied,1337 .PERM => return error.AccessDenied,
1343 EINVAL => return error.InvalidExe,1338 .INVAL => return error.InvalidExe,
1344 ENOEXEC => return error.InvalidExe,1339 .NOEXEC => return error.InvalidExe,
1345 EIO => return error.FileSystem,1340 .IO => return error.FileSystem,
1346 ELOOP => return error.FileSystem,1341 .LOOP => return error.FileSystem,
1347 EISDIR => return error.IsDir,1342 .ISDIR => return error.IsDir,
1348 ENOENT => return error.FileNotFound,1343 .NOENT => return error.FileNotFound,
1349 ENOTDIR => return error.NotDir,1344 .NOTDIR => return error.NotDir,
1350 ETXTBSY => return error.FileBusy,1345 .TXTBSY => return error.FileBusy,
1351 else => |err| return unexpectedErrno(err),1346 else => |err| return unexpectedErrno(err),
1352 }1347 }
1353}1348}
...@@ -1543,16 +1538,17 @@ pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 {...@@ -1543,16 +1538,17 @@ pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 {
1543 }1538 }
15441539
1545 const err = if (builtin.link_libc) blk: {1540 const err = if (builtin.link_libc) blk: {
1546 break :blk if (std.c.getcwd(out_buffer.ptr, out_buffer.len)) |_| 0 else std.c._errno().*;1541 const c_err = if (std.c.getcwd(out_buffer.ptr, out_buffer.len)) |_| 0 else std.c._errno().*;
1542 break :blk @intToEnum(E, c_err);
1547 } else blk: {1543 } else blk: {
1548 break :blk errno(system.getcwd(out_buffer.ptr, out_buffer.len));1544 break :blk errno(system.getcwd(out_buffer.ptr, out_buffer.len));
1549 };1545 };
1550 switch (err) {1546 switch (err) {
1551 0 => return mem.spanZ(std.meta.assumeSentinel(out_buffer.ptr, 0)),1547 .SUCCESS => return mem.spanZ(std.meta.assumeSentinel(out_buffer.ptr, 0)),
1552 EFAULT => unreachable,1548 .FAULT => unreachable,
1553 EINVAL => unreachable,1549 .INVAL => unreachable,
1554 ENOENT => return error.CurrentWorkingDirectoryUnlinked,1550 .NOENT => return error.CurrentWorkingDirectoryUnlinked,
1555 ERANGE => return error.NameTooLong,1551 .RANGE => return error.NameTooLong,
1556 else => return unexpectedErrno(err),1552 else => return unexpectedErrno(err),
1557 }1553 }
1558}1554}
...@@ -1601,21 +1597,21 @@ pub fn symlinkZ(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLin...@@ -1601,21 +1597,21 @@ pub fn symlinkZ(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLin
1601 @compileError("symlink is not supported on Windows; use std.os.windows.CreateSymbolicLink instead");1597 @compileError("symlink is not supported on Windows; use std.os.windows.CreateSymbolicLink instead");
1602 }1598 }
1603 switch (errno(system.symlink(target_path, sym_link_path))) {1599 switch (errno(system.symlink(target_path, sym_link_path))) {
1604 0 => return,1600 .SUCCESS => return,
1605 EFAULT => unreachable,1601 .FAULT => unreachable,
1606 EINVAL => unreachable,1602 .INVAL => unreachable,
1607 EACCES => return error.AccessDenied,1603 .ACCES => return error.AccessDenied,
1608 EPERM => return error.AccessDenied,1604 .PERM => return error.AccessDenied,
1609 EDQUOT => return error.DiskQuota,1605 .DQUOT => return error.DiskQuota,
1610 EEXIST => return error.PathAlreadyExists,1606 .EXIST => return error.PathAlreadyExists,
1611 EIO => return error.FileSystem,1607 .IO => return error.FileSystem,
1612 ELOOP => return error.SymLinkLoop,1608 .LOOP => return error.SymLinkLoop,
1613 ENAMETOOLONG => return error.NameTooLong,1609 .NAMETOOLONG => return error.NameTooLong,
1614 ENOENT => return error.FileNotFound,1610 .NOENT => return error.FileNotFound,
1615 ENOTDIR => return error.NotDir,1611 .NOTDIR => return error.NotDir,
1616 ENOMEM => return error.SystemResources,1612 .NOMEM => return error.SystemResources,
1617 ENOSPC => return error.NoSpaceLeft,1613 .NOSPC => return error.NoSpaceLeft,
1618 EROFS => return error.ReadOnlyFileSystem,1614 .ROFS => return error.ReadOnlyFileSystem,
1619 else => |err| return unexpectedErrno(err),1615 else => |err| return unexpectedErrno(err),
1620 }1616 }
1621}1617}
...@@ -1644,22 +1640,22 @@ pub const symlinkatC = @compileError("deprecated: renamed to symlinkatZ");...@@ -1644,22 +1640,22 @@ pub const symlinkatC = @compileError("deprecated: renamed to symlinkatZ");
1644/// See also `symlinkat`.1640/// See also `symlinkat`.
1645pub fn symlinkatWasi(target_path: []const u8, newdirfd: fd_t, sym_link_path: []const u8) SymLinkError!void {1641pub fn symlinkatWasi(target_path: []const u8, newdirfd: fd_t, sym_link_path: []const u8) SymLinkError!void {
1646 switch (wasi.path_symlink(target_path.ptr, target_path.len, newdirfd, sym_link_path.ptr, sym_link_path.len)) {1642 switch (wasi.path_symlink(target_path.ptr, target_path.len, newdirfd, sym_link_path.ptr, sym_link_path.len)) {
1647 wasi.ESUCCESS => {},1643 .SUCCESS => {},
1648 wasi.EFAULT => unreachable,1644 .FAULT => unreachable,
1649 wasi.EINVAL => unreachable,1645 .INVAL => unreachable,
1650 wasi.EACCES => return error.AccessDenied,1646 .ACCES => return error.AccessDenied,
1651 wasi.EPERM => return error.AccessDenied,1647 .PERM => return error.AccessDenied,
1652 wasi.EDQUOT => return error.DiskQuota,1648 .DQUOT => return error.DiskQuota,
1653 wasi.EEXIST => return error.PathAlreadyExists,1649 .EXIST => return error.PathAlreadyExists,
1654 wasi.EIO => return error.FileSystem,1650 .IO => return error.FileSystem,
1655 wasi.ELOOP => return error.SymLinkLoop,1651 .LOOP => return error.SymLinkLoop,
1656 wasi.ENAMETOOLONG => return error.NameTooLong,1652 .NAMETOOLONG => return error.NameTooLong,
1657 wasi.ENOENT => return error.FileNotFound,1653 .NOENT => return error.FileNotFound,
1658 wasi.ENOTDIR => return error.NotDir,1654 .NOTDIR => return error.NotDir,
1659 wasi.ENOMEM => return error.SystemResources,1655 .NOMEM => return error.SystemResources,
1660 wasi.ENOSPC => return error.NoSpaceLeft,1656 .NOSPC => return error.NoSpaceLeft,
1661 wasi.EROFS => return error.ReadOnlyFileSystem,1657 .ROFS => return error.ReadOnlyFileSystem,
1662 wasi.ENOTCAPABLE => return error.AccessDenied,1658 .NOTCAPABLE => return error.AccessDenied,
1663 else => |err| return unexpectedErrno(err),1659 else => |err| return unexpectedErrno(err),
1664 }1660 }
1665}1661}
...@@ -1671,21 +1667,21 @@ pub fn symlinkatZ(target_path: [*:0]const u8, newdirfd: fd_t, sym_link_path: [*:...@@ -1671,21 +1667,21 @@ pub fn symlinkatZ(target_path: [*:0]const u8, newdirfd: fd_t, sym_link_path: [*:
1671 @compileError("symlinkat is not supported on Windows; use std.os.windows.CreateSymbolicLink instead");1667 @compileError("symlinkat is not supported on Windows; use std.os.windows.CreateSymbolicLink instead");
1672 }1668 }
1673 switch (errno(system.symlinkat(target_path, newdirfd, sym_link_path))) {1669 switch (errno(system.symlinkat(target_path, newdirfd, sym_link_path))) {
1674 0 => return,1670 .SUCCESS => return,
1675 EFAULT => unreachable,1671 .FAULT => unreachable,
1676 EINVAL => unreachable,1672 .INVAL => unreachable,
1677 EACCES => return error.AccessDenied,1673 .ACCES => return error.AccessDenied,
1678 EPERM => return error.AccessDenied,1674 .PERM => return error.AccessDenied,
1679 EDQUOT => return error.DiskQuota,1675 .DQUOT => return error.DiskQuota,
1680 EEXIST => return error.PathAlreadyExists,1676 .EXIST => return error.PathAlreadyExists,
1681 EIO => return error.FileSystem,1677 .IO => return error.FileSystem,
1682 ELOOP => return error.SymLinkLoop,1678 .LOOP => return error.SymLinkLoop,
1683 ENAMETOOLONG => return error.NameTooLong,1679 .NAMETOOLONG => return error.NameTooLong,
1684 ENOENT => return error.FileNotFound,1680 .NOENT => return error.FileNotFound,
1685 ENOTDIR => return error.NotDir,1681 .NOTDIR => return error.NotDir,
1686 ENOMEM => return error.SystemResources,1682 .NOMEM => return error.SystemResources,
1687 ENOSPC => return error.NoSpaceLeft,1683 .NOSPC => return error.NoSpaceLeft,
1688 EROFS => return error.ReadOnlyFileSystem,1684 .ROFS => return error.ReadOnlyFileSystem,
1689 else => |err| return unexpectedErrno(err),1685 else => |err| return unexpectedErrno(err),
1690 }1686 }
1691}1687}
...@@ -1707,22 +1703,22 @@ pub const LinkError = UnexpectedError || error{...@@ -1707,22 +1703,22 @@ pub const LinkError = UnexpectedError || error{
17071703
1708pub fn linkZ(oldpath: [*:0]const u8, newpath: [*:0]const u8, flags: i32) LinkError!void {1704pub fn linkZ(oldpath: [*:0]const u8, newpath: [*:0]const u8, flags: i32) LinkError!void {
1709 switch (errno(system.link(oldpath, newpath, flags))) {1705 switch (errno(system.link(oldpath, newpath, flags))) {
1710 0 => return,1706 .SUCCESS => return,
1711 EACCES => return error.AccessDenied,1707 .ACCES => return error.AccessDenied,
1712 EDQUOT => return error.DiskQuota,1708 .DQUOT => return error.DiskQuota,
1713 EEXIST => return error.PathAlreadyExists,1709 .EXIST => return error.PathAlreadyExists,
1714 EFAULT => unreachable,1710 .FAULT => unreachable,
1715 EIO => return error.FileSystem,1711 .IO => return error.FileSystem,
1716 ELOOP => return error.SymLinkLoop,1712 .LOOP => return error.SymLinkLoop,
1717 EMLINK => return error.LinkQuotaExceeded,1713 .MLINK => return error.LinkQuotaExceeded,
1718 ENAMETOOLONG => return error.NameTooLong,1714 .NAMETOOLONG => return error.NameTooLong,
1719 ENOENT => return error.FileNotFound,1715 .NOENT => return error.FileNotFound,
1720 ENOMEM => return error.SystemResources,1716 .NOMEM => return error.SystemResources,
1721 ENOSPC => return error.NoSpaceLeft,1717 .NOSPC => return error.NoSpaceLeft,
1722 EPERM => return error.AccessDenied,1718 .PERM => return error.AccessDenied,
1723 EROFS => return error.ReadOnlyFileSystem,1719 .ROFS => return error.ReadOnlyFileSystem,
1724 EXDEV => return error.NotSameFileSystem,1720 .XDEV => return error.NotSameFileSystem,
1725 EINVAL => unreachable,1721 .INVAL => unreachable,
1726 else => |err| return unexpectedErrno(err),1722 else => |err| return unexpectedErrno(err),
1727 }1723 }
1728}1724}
...@@ -1743,23 +1739,23 @@ pub fn linkatZ(...@@ -1743,23 +1739,23 @@ pub fn linkatZ(
1743 flags: i32,1739 flags: i32,
1744) LinkatError!void {1740) LinkatError!void {
1745 switch (errno(system.linkat(olddir, oldpath, newdir, newpath, flags))) {1741 switch (errno(system.linkat(olddir, oldpath, newdir, newpath, flags))) {
1746 0 => return,1742 .SUCCESS => return,
1747 EACCES => return error.AccessDenied,1743 .ACCES => return error.AccessDenied,
1748 EDQUOT => return error.DiskQuota,1744 .DQUOT => return error.DiskQuota,
1749 EEXIST => return error.PathAlreadyExists,1745 .EXIST => return error.PathAlreadyExists,
1750 EFAULT => unreachable,1746 .FAULT => unreachable,
1751 EIO => return error.FileSystem,1747 .IO => return error.FileSystem,
1752 ELOOP => return error.SymLinkLoop,1748 .LOOP => return error.SymLinkLoop,
1753 EMLINK => return error.LinkQuotaExceeded,1749 .MLINK => return error.LinkQuotaExceeded,
1754 ENAMETOOLONG => return error.NameTooLong,1750 .NAMETOOLONG => return error.NameTooLong,
1755 ENOENT => return error.FileNotFound,1751 .NOENT => return error.FileNotFound,
1756 ENOMEM => return error.SystemResources,1752 .NOMEM => return error.SystemResources,
1757 ENOSPC => return error.NoSpaceLeft,1753 .NOSPC => return error.NoSpaceLeft,
1758 ENOTDIR => return error.NotDir,1754 .NOTDIR => return error.NotDir,
1759 EPERM => return error.AccessDenied,1755 .PERM => return error.AccessDenied,
1760 EROFS => return error.ReadOnlyFileSystem,1756 .ROFS => return error.ReadOnlyFileSystem,
1761 EXDEV => return error.NotSameFileSystem,1757 .XDEV => return error.NotSameFileSystem,
1762 EINVAL => unreachable,1758 .INVAL => unreachable,
1763 else => |err| return unexpectedErrno(err),1759 else => |err| return unexpectedErrno(err),
1764 }1760 }
1765}1761}
...@@ -1822,20 +1818,20 @@ pub fn unlinkZ(file_path: [*:0]const u8) UnlinkError!void {...@@ -1822,20 +1818,20 @@ pub fn unlinkZ(file_path: [*:0]const u8) UnlinkError!void {
1822 return unlinkW(file_path_w.span());1818 return unlinkW(file_path_w.span());
1823 }1819 }
1824 switch (errno(system.unlink(file_path))) {1820 switch (errno(system.unlink(file_path))) {
1825 0 => return,1821 .SUCCESS => return,
1826 EACCES => return error.AccessDenied,1822 .ACCES => return error.AccessDenied,
1827 EPERM => return error.AccessDenied,1823 .PERM => return error.AccessDenied,
1828 EBUSY => return error.FileBusy,1824 .BUSY => return error.FileBusy,
1829 EFAULT => unreachable,1825 .FAULT => unreachable,
1830 EINVAL => unreachable,1826 .INVAL => unreachable,
1831 EIO => return error.FileSystem,1827 .IO => return error.FileSystem,
1832 EISDIR => return error.IsDir,1828 .ISDIR => return error.IsDir,
1833 ELOOP => return error.SymLinkLoop,1829 .LOOP => return error.SymLinkLoop,
1834 ENAMETOOLONG => return error.NameTooLong,1830 .NAMETOOLONG => return error.NameTooLong,
1835 ENOENT => return error.FileNotFound,1831 .NOENT => return error.FileNotFound,
1836 ENOTDIR => return error.NotDir,1832 .NOTDIR => return error.NotDir,
1837 ENOMEM => return error.SystemResources,1833 .NOMEM => return error.SystemResources,
1838 EROFS => return error.ReadOnlyFileSystem,1834 .ROFS => return error.ReadOnlyFileSystem,
1839 else => |err| return unexpectedErrno(err),1835 else => |err| return unexpectedErrno(err),
1840 }1836 }
1841}1837}
...@@ -1875,24 +1871,24 @@ pub fn unlinkatWasi(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatErro...@@ -1875,24 +1871,24 @@ pub fn unlinkatWasi(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatErro
1875 else1871 else
1876 wasi.path_unlink_file(dirfd, file_path.ptr, file_path.len);1872 wasi.path_unlink_file(dirfd, file_path.ptr, file_path.len);
1877 switch (res) {1873 switch (res) {
1878 wasi.ESUCCESS => return,1874 .SUCCESS => return,
1879 wasi.EACCES => return error.AccessDenied,1875 .ACCES => return error.AccessDenied,
1880 wasi.EPERM => return error.AccessDenied,1876 .PERM => return error.AccessDenied,
1881 wasi.EBUSY => return error.FileBusy,1877 .BUSY => return error.FileBusy,
1882 wasi.EFAULT => unreachable,1878 .FAULT => unreachable,
1883 wasi.EIO => return error.FileSystem,1879 .IO => return error.FileSystem,
1884 wasi.EISDIR => return error.IsDir,1880 .ISDIR => return error.IsDir,
1885 wasi.ELOOP => return error.SymLinkLoop,1881 .LOOP => return error.SymLinkLoop,
1886 wasi.ENAMETOOLONG => return error.NameTooLong,1882 .NAMETOOLONG => return error.NameTooLong,
1887 wasi.ENOENT => return error.FileNotFound,1883 .NOENT => return error.FileNotFound,
1888 wasi.ENOTDIR => return error.NotDir,1884 .NOTDIR => return error.NotDir,
1889 wasi.ENOMEM => return error.SystemResources,1885 .NOMEM => return error.SystemResources,
1890 wasi.EROFS => return error.ReadOnlyFileSystem,1886 .ROFS => return error.ReadOnlyFileSystem,
1891 wasi.ENOTEMPTY => return error.DirNotEmpty,1887 .NOTEMPTY => return error.DirNotEmpty,
1892 wasi.ENOTCAPABLE => return error.AccessDenied,1888 .NOTCAPABLE => return error.AccessDenied,
18931889
1894 wasi.EINVAL => unreachable, // invalid flags, or pathname has . as last component1890 .INVAL => unreachable, // invalid flags, or pathname has . as last component
1895 wasi.EBADF => unreachable, // always a race condition1891 .BADF => unreachable, // always a race condition
18961892
1897 else => |err| return unexpectedErrno(err),1893 else => |err| return unexpectedErrno(err),
1898 }1894 }
...@@ -1905,23 +1901,23 @@ pub fn unlinkatZ(dirfd: fd_t, file_path_c: [*:0]const u8, flags: u32) UnlinkatEr...@@ -1905,23 +1901,23 @@ pub fn unlinkatZ(dirfd: fd_t, file_path_c: [*:0]const u8, flags: u32) UnlinkatEr
1905 return unlinkatW(dirfd, file_path_w.span(), flags);1901 return unlinkatW(dirfd, file_path_w.span(), flags);
1906 }1902 }
1907 switch (errno(system.unlinkat(dirfd, file_path_c, flags))) {1903 switch (errno(system.unlinkat(dirfd, file_path_c, flags))) {
1908 0 => return,1904 .SUCCESS => return,
1909 EACCES => return error.AccessDenied,1905 .ACCES => return error.AccessDenied,
1910 EPERM => return error.AccessDenied,1906 .PERM => return error.AccessDenied,
1911 EBUSY => return error.FileBusy,1907 .BUSY => return error.FileBusy,
1912 EFAULT => unreachable,1908 .FAULT => unreachable,
1913 EIO => return error.FileSystem,1909 .IO => return error.FileSystem,
1914 EISDIR => return error.IsDir,1910 .ISDIR => return error.IsDir,
1915 ELOOP => return error.SymLinkLoop,1911 .LOOP => return error.SymLinkLoop,
1916 ENAMETOOLONG => return error.NameTooLong,1912 .NAMETOOLONG => return error.NameTooLong,
1917 ENOENT => return error.FileNotFound,1913 .NOENT => return error.FileNotFound,
1918 ENOTDIR => return error.NotDir,1914 .NOTDIR => return error.NotDir,
1919 ENOMEM => return error.SystemResources,1915 .NOMEM => return error.SystemResources,
1920 EROFS => return error.ReadOnlyFileSystem,1916 .ROFS => return error.ReadOnlyFileSystem,
1921 ENOTEMPTY => return error.DirNotEmpty,1917 .NOTEMPTY => return error.DirNotEmpty,
19221918
1923 EINVAL => unreachable, // invalid flags, or pathname has . as last component1919 .INVAL => unreachable, // invalid flags, or pathname has . as last component
1924 EBADF => unreachable, // always a race condition1920 .BADF => unreachable, // always a race condition
19251921
1926 else => |err| return unexpectedErrno(err),1922 else => |err| return unexpectedErrno(err),
1927 }1923 }
...@@ -1982,25 +1978,25 @@ pub fn renameZ(old_path: [*:0]const u8, new_path: [*:0]const u8) RenameError!voi...@@ -1982,25 +1978,25 @@ pub fn renameZ(old_path: [*:0]const u8, new_path: [*:0]const u8) RenameError!voi
1982 return renameW(old_path_w.span().ptr, new_path_w.span().ptr);1978 return renameW(old_path_w.span().ptr, new_path_w.span().ptr);
1983 }1979 }
1984 switch (errno(system.rename(old_path, new_path))) {1980 switch (errno(system.rename(old_path, new_path))) {
1985 0 => return,1981 .SUCCESS => return,
1986 EACCES => return error.AccessDenied,1982 .ACCES => return error.AccessDenied,
1987 EPERM => return error.AccessDenied,1983 .PERM => return error.AccessDenied,
1988 EBUSY => return error.FileBusy,1984 .BUSY => return error.FileBusy,
1989 EDQUOT => return error.DiskQuota,1985 .DQUOT => return error.DiskQuota,
1990 EFAULT => unreachable,1986 .FAULT => unreachable,
1991 EINVAL => unreachable,1987 .INVAL => unreachable,
1992 EISDIR => return error.IsDir,1988 .ISDIR => return error.IsDir,
1993 ELOOP => return error.SymLinkLoop,1989 .LOOP => return error.SymLinkLoop,
1994 EMLINK => return error.LinkQuotaExceeded,1990 .MLINK => return error.LinkQuotaExceeded,
1995 ENAMETOOLONG => return error.NameTooLong,1991 .NAMETOOLONG => return error.NameTooLong,
1996 ENOENT => return error.FileNotFound,1992 .NOENT => return error.FileNotFound,
1997 ENOTDIR => return error.NotDir,1993 .NOTDIR => return error.NotDir,
1998 ENOMEM => return error.SystemResources,1994 .NOMEM => return error.SystemResources,
1999 ENOSPC => return error.NoSpaceLeft,1995 .NOSPC => return error.NoSpaceLeft,
2000 EEXIST => return error.PathAlreadyExists,1996 .EXIST => return error.PathAlreadyExists,
2001 ENOTEMPTY => return error.PathAlreadyExists,1997 .NOTEMPTY => return error.PathAlreadyExists,
2002 EROFS => return error.ReadOnlyFileSystem,1998 .ROFS => return error.ReadOnlyFileSystem,
2003 EXDEV => return error.RenameAcrossMountPoints,1999 .XDEV => return error.RenameAcrossMountPoints,
2004 else => |err| return unexpectedErrno(err),2000 else => |err| return unexpectedErrno(err),
2005 }2001 }
2006}2002}
...@@ -2036,26 +2032,26 @@ pub fn renameat(...@@ -2036,26 +2032,26 @@ pub fn renameat(
2036/// See also `renameat`.2032/// See also `renameat`.
2037pub fn renameatWasi(old_dir_fd: fd_t, old_path: []const u8, new_dir_fd: fd_t, new_path: []const u8) RenameError!void {2033pub fn renameatWasi(old_dir_fd: fd_t, old_path: []const u8, new_dir_fd: fd_t, new_path: []const u8) RenameError!void {
2038 switch (wasi.path_rename(old_dir_fd, old_path.ptr, old_path.len, new_dir_fd, new_path.ptr, new_path.len)) {2034 switch (wasi.path_rename(old_dir_fd, old_path.ptr, old_path.len, new_dir_fd, new_path.ptr, new_path.len)) {
2039 wasi.ESUCCESS => return,2035 .SUCCESS => return,
2040 wasi.EACCES => return error.AccessDenied,2036 .ACCES => return error.AccessDenied,
2041 wasi.EPERM => return error.AccessDenied,2037 .PERM => return error.AccessDenied,
2042 wasi.EBUSY => return error.FileBusy,2038 .BUSY => return error.FileBusy,
2043 wasi.EDQUOT => return error.DiskQuota,2039 .DQUOT => return error.DiskQuota,
2044 wasi.EFAULT => unreachable,2040 .FAULT => unreachable,
2045 wasi.EINVAL => unreachable,2041 .INVAL => unreachable,
2046 wasi.EISDIR => return error.IsDir,2042 .ISDIR => return error.IsDir,
2047 wasi.ELOOP => return error.SymLinkLoop,2043 .LOOP => return error.SymLinkLoop,
2048 wasi.EMLINK => return error.LinkQuotaExceeded,2044 .MLINK => return error.LinkQuotaExceeded,
2049 wasi.ENAMETOOLONG => return error.NameTooLong,2045 .NAMETOOLONG => return error.NameTooLong,
2050 wasi.ENOENT => return error.FileNotFound,2046 .NOENT => return error.FileNotFound,
2051 wasi.ENOTDIR => return error.NotDir,2047 .NOTDIR => return error.NotDir,
2052 wasi.ENOMEM => return error.SystemResources,2048 .NOMEM => return error.SystemResources,
2053 wasi.ENOSPC => return error.NoSpaceLeft,2049 .NOSPC => return error.NoSpaceLeft,
2054 wasi.EEXIST => return error.PathAlreadyExists,2050 .EXIST => return error.PathAlreadyExists,
2055 wasi.ENOTEMPTY => return error.PathAlreadyExists,2051 .NOTEMPTY => return error.PathAlreadyExists,
2056 wasi.EROFS => return error.ReadOnlyFileSystem,2052 .ROFS => return error.ReadOnlyFileSystem,
2057 wasi.EXDEV => return error.RenameAcrossMountPoints,2053 .XDEV => return error.RenameAcrossMountPoints,
2058 wasi.ENOTCAPABLE => return error.AccessDenied,2054 .NOTCAPABLE => return error.AccessDenied,
2059 else => |err| return unexpectedErrno(err),2055 else => |err| return unexpectedErrno(err),
2060 }2056 }
2061}2057}
...@@ -2074,25 +2070,25 @@ pub fn renameatZ(...@@ -2074,25 +2070,25 @@ pub fn renameatZ(
2074 }2070 }
20752071
2076 switch (errno(system.renameat(old_dir_fd, old_path, new_dir_fd, new_path))) {2072 switch (errno(system.renameat(old_dir_fd, old_path, new_dir_fd, new_path))) {
2077 0 => return,2073 .SUCCESS => return,
2078 EACCES => return error.AccessDenied,2074 .ACCES => return error.AccessDenied,
2079 EPERM => return error.AccessDenied,2075 .PERM => return error.AccessDenied,
2080 EBUSY => return error.FileBusy,2076 .BUSY => return error.FileBusy,
2081 EDQUOT => return error.DiskQuota,2077 .DQUOT => return error.DiskQuota,
2082 EFAULT => unreachable,2078 .FAULT => unreachable,
2083 EINVAL => unreachable,2079 .INVAL => unreachable,
2084 EISDIR => return error.IsDir,2080 .ISDIR => return error.IsDir,
2085 ELOOP => return error.SymLinkLoop,2081 .LOOP => return error.SymLinkLoop,
2086 EMLINK => return error.LinkQuotaExceeded,2082 .MLINK => return error.LinkQuotaExceeded,
2087 ENAMETOOLONG => return error.NameTooLong,2083 .NAMETOOLONG => return error.NameTooLong,
2088 ENOENT => return error.FileNotFound,2084 .NOENT => return error.FileNotFound,
2089 ENOTDIR => return error.NotDir,2085 .NOTDIR => return error.NotDir,
2090 ENOMEM => return error.SystemResources,2086 .NOMEM => return error.SystemResources,
2091 ENOSPC => return error.NoSpaceLeft,2087 .NOSPC => return error.NoSpaceLeft,
2092 EEXIST => return error.PathAlreadyExists,2088 .EXIST => return error.PathAlreadyExists,
2093 ENOTEMPTY => return error.PathAlreadyExists,2089 .NOTEMPTY => return error.PathAlreadyExists,
2094 EROFS => return error.ReadOnlyFileSystem,2090 .ROFS => return error.ReadOnlyFileSystem,
2095 EXDEV => return error.RenameAcrossMountPoints,2091 .XDEV => return error.RenameAcrossMountPoints,
2096 else => |err| return unexpectedErrno(err),2092 else => |err| return unexpectedErrno(err),
2097 }2093 }
2098}2094}
...@@ -2172,22 +2168,22 @@ pub const mkdiratC = @compileError("deprecated: renamed to mkdiratZ");...@@ -2172,22 +2168,22 @@ pub const mkdiratC = @compileError("deprecated: renamed to mkdiratZ");
2172pub fn mkdiratWasi(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!void {2168pub fn mkdiratWasi(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!void {
2173 _ = mode;2169 _ = mode;
2174 switch (wasi.path_create_directory(dir_fd, sub_dir_path.ptr, sub_dir_path.len)) {2170 switch (wasi.path_create_directory(dir_fd, sub_dir_path.ptr, sub_dir_path.len)) {
2175 wasi.ESUCCESS => return,2171 .SUCCESS => return,
2176 wasi.EACCES => return error.AccessDenied,2172 .ACCES => return error.AccessDenied,
2177 wasi.EBADF => unreachable,2173 .BADF => unreachable,
2178 wasi.EPERM => return error.AccessDenied,2174 .PERM => return error.AccessDenied,
2179 wasi.EDQUOT => return error.DiskQuota,2175 .DQUOT => return error.DiskQuota,
2180 wasi.EEXIST => return error.PathAlreadyExists,2176 .EXIST => return error.PathAlreadyExists,
2181 wasi.EFAULT => unreachable,2177 .FAULT => unreachable,
2182 wasi.ELOOP => return error.SymLinkLoop,2178 .LOOP => return error.SymLinkLoop,
2183 wasi.EMLINK => return error.LinkQuotaExceeded,2179 .MLINK => return error.LinkQuotaExceeded,
2184 wasi.ENAMETOOLONG => return error.NameTooLong,2180 .NAMETOOLONG => return error.NameTooLong,
2185 wasi.ENOENT => return error.FileNotFound,2181 .NOENT => return error.FileNotFound,
2186 wasi.ENOMEM => return error.SystemResources,2182 .NOMEM => return error.SystemResources,
2187 wasi.ENOSPC => return error.NoSpaceLeft,2183 .NOSPC => return error.NoSpaceLeft,
2188 wasi.ENOTDIR => return error.NotDir,2184 .NOTDIR => return error.NotDir,
2189 wasi.EROFS => return error.ReadOnlyFileSystem,2185 .ROFS => return error.ReadOnlyFileSystem,
2190 wasi.ENOTCAPABLE => return error.AccessDenied,2186 .NOTCAPABLE => return error.AccessDenied,
2191 else => |err| return unexpectedErrno(err),2187 else => |err| return unexpectedErrno(err),
2192 }2188 }
2193}2189}
...@@ -2198,21 +2194,21 @@ pub fn mkdiratZ(dir_fd: fd_t, sub_dir_path: [*:0]const u8, mode: u32) MakeDirErr...@@ -2198,21 +2194,21 @@ pub fn mkdiratZ(dir_fd: fd_t, sub_dir_path: [*:0]const u8, mode: u32) MakeDirErr
2198 return mkdiratW(dir_fd, sub_dir_path_w.span().ptr, mode);2194 return mkdiratW(dir_fd, sub_dir_path_w.span().ptr, mode);
2199 }2195 }
2200 switch (errno(system.mkdirat(dir_fd, sub_dir_path, mode))) {2196 switch (errno(system.mkdirat(dir_fd, sub_dir_path, mode))) {
2201 0 => return,2197 .SUCCESS => return,
2202 EACCES => return error.AccessDenied,2198 .ACCES => return error.AccessDenied,
2203 EBADF => unreachable,2199 .BADF => unreachable,
2204 EPERM => return error.AccessDenied,2200 .PERM => return error.AccessDenied,
2205 EDQUOT => return error.DiskQuota,2201 .DQUOT => return error.DiskQuota,
2206 EEXIST => return error.PathAlreadyExists,2202 .EXIST => return error.PathAlreadyExists,
2207 EFAULT => unreachable,2203 .FAULT => unreachable,
2208 ELOOP => return error.SymLinkLoop,2204 .LOOP => return error.SymLinkLoop,
2209 EMLINK => return error.LinkQuotaExceeded,2205 .MLINK => return error.LinkQuotaExceeded,
2210 ENAMETOOLONG => return error.NameTooLong,2206 .NAMETOOLONG => return error.NameTooLong,
2211 ENOENT => return error.FileNotFound,2207 .NOENT => return error.FileNotFound,
2212 ENOMEM => return error.SystemResources,2208 .NOMEM => return error.SystemResources,
2213 ENOSPC => return error.NoSpaceLeft,2209 .NOSPC => return error.NoSpaceLeft,
2214 ENOTDIR => return error.NotDir,2210 .NOTDIR => return error.NotDir,
2215 EROFS => return error.ReadOnlyFileSystem,2211 .ROFS => return error.ReadOnlyFileSystem,
2216 else => |err| return unexpectedErrno(err),2212 else => |err| return unexpectedErrno(err),
2217 }2213 }
2218}2214}
...@@ -2274,20 +2270,20 @@ pub fn mkdirZ(dir_path: [*:0]const u8, mode: u32) MakeDirError!void {...@@ -2274,20 +2270,20 @@ pub fn mkdirZ(dir_path: [*:0]const u8, mode: u32) MakeDirError!void {
2274 return mkdirW(dir_path_w.span(), mode);2270 return mkdirW(dir_path_w.span(), mode);
2275 }2271 }
2276 switch (errno(system.mkdir(dir_path, mode))) {2272 switch (errno(system.mkdir(dir_path, mode))) {
2277 0 => return,2273 .SUCCESS => return,
2278 EACCES => return error.AccessDenied,2274 .ACCES => return error.AccessDenied,
2279 EPERM => return error.AccessDenied,2275 .PERM => return error.AccessDenied,
2280 EDQUOT => return error.DiskQuota,2276 .DQUOT => return error.DiskQuota,
2281 EEXIST => return error.PathAlreadyExists,2277 .EXIST => return error.PathAlreadyExists,
2282 EFAULT => unreachable,2278 .FAULT => unreachable,
2283 ELOOP => return error.SymLinkLoop,2279 .LOOP => return error.SymLinkLoop,
2284 EMLINK => return error.LinkQuotaExceeded,2280 .MLINK => return error.LinkQuotaExceeded,
2285 ENAMETOOLONG => return error.NameTooLong,2281 .NAMETOOLONG => return error.NameTooLong,
2286 ENOENT => return error.FileNotFound,2282 .NOENT => return error.FileNotFound,
2287 ENOMEM => return error.SystemResources,2283 .NOMEM => return error.SystemResources,
2288 ENOSPC => return error.NoSpaceLeft,2284 .NOSPC => return error.NoSpaceLeft,
2289 ENOTDIR => return error.NotDir,2285 .NOTDIR => return error.NotDir,
2290 EROFS => return error.ReadOnlyFileSystem,2286 .ROFS => return error.ReadOnlyFileSystem,
2291 else => |err| return unexpectedErrno(err),2287 else => |err| return unexpectedErrno(err),
2292 }2288 }
2293}2289}
...@@ -2346,20 +2342,20 @@ pub fn rmdirZ(dir_path: [*:0]const u8) DeleteDirError!void {...@@ -2346,20 +2342,20 @@ pub fn rmdirZ(dir_path: [*:0]const u8) DeleteDirError!void {
2346 return rmdirW(dir_path_w.span());2342 return rmdirW(dir_path_w.span());
2347 }2343 }
2348 switch (errno(system.rmdir(dir_path))) {2344 switch (errno(system.rmdir(dir_path))) {
2349 0 => return,2345 .SUCCESS => return,
2350 EACCES => return error.AccessDenied,2346 .ACCES => return error.AccessDenied,
2351 EPERM => return error.AccessDenied,2347 .PERM => return error.AccessDenied,
2352 EBUSY => return error.FileBusy,2348 .BUSY => return error.FileBusy,
2353 EFAULT => unreachable,2349 .FAULT => unreachable,
2354 EINVAL => unreachable,2350 .INVAL => unreachable,
2355 ELOOP => return error.SymLinkLoop,2351 .LOOP => return error.SymLinkLoop,
2356 ENAMETOOLONG => return error.NameTooLong,2352 .NAMETOOLONG => return error.NameTooLong,
2357 ENOENT => return error.FileNotFound,2353 .NOENT => return error.FileNotFound,
2358 ENOMEM => return error.SystemResources,2354 .NOMEM => return error.SystemResources,
2359 ENOTDIR => return error.NotDir,2355 .NOTDIR => return error.NotDir,
2360 EEXIST => return error.DirNotEmpty,2356 .EXIST => return error.DirNotEmpty,
2361 ENOTEMPTY => return error.DirNotEmpty,2357 .NOTEMPTY => return error.DirNotEmpty,
2362 EROFS => return error.ReadOnlyFileSystem,2358 .ROFS => return error.ReadOnlyFileSystem,
2363 else => |err| return unexpectedErrno(err),2359 else => |err| return unexpectedErrno(err),
2364 }2360 }
2365}2361}
...@@ -2413,15 +2409,15 @@ pub fn chdirZ(dir_path: [*:0]const u8) ChangeCurDirError!void {...@@ -2413,15 +2409,15 @@ pub fn chdirZ(dir_path: [*:0]const u8) ChangeCurDirError!void {
2413 return chdirW(utf16_dir_path[0..len]);2409 return chdirW(utf16_dir_path[0..len]);
2414 }2410 }
2415 switch (errno(system.chdir(dir_path))) {2411 switch (errno(system.chdir(dir_path))) {
2416 0 => return,2412 .SUCCESS => return,
2417 EACCES => return error.AccessDenied,2413 .ACCES => return error.AccessDenied,
2418 EFAULT => unreachable,2414 .FAULT => unreachable,
2419 EIO => return error.FileSystem,2415 .IO => return error.FileSystem,
2420 ELOOP => return error.SymLinkLoop,2416 .LOOP => return error.SymLinkLoop,
2421 ENAMETOOLONG => return error.NameTooLong,2417 .NAMETOOLONG => return error.NameTooLong,
2422 ENOENT => return error.FileNotFound,2418 .NOENT => return error.FileNotFound,
2423 ENOMEM => return error.SystemResources,2419 .NOMEM => return error.SystemResources,
2424 ENOTDIR => return error.NotDir,2420 .NOTDIR => return error.NotDir,
2425 else => |err| return unexpectedErrno(err),2421 else => |err| return unexpectedErrno(err),
2426 }2422 }
2427}2423}
...@@ -2443,12 +2439,12 @@ pub const FchdirError = error{...@@ -2443,12 +2439,12 @@ pub const FchdirError = error{
2443pub fn fchdir(dirfd: fd_t) FchdirError!void {2439pub fn fchdir(dirfd: fd_t) FchdirError!void {
2444 while (true) {2440 while (true) {
2445 switch (errno(system.fchdir(dirfd))) {2441 switch (errno(system.fchdir(dirfd))) {
2446 0 => return,2442 .SUCCESS => return,
2447 EACCES => return error.AccessDenied,2443 .ACCES => return error.AccessDenied,
2448 EBADF => unreachable,2444 .BADF => unreachable,
2449 ENOTDIR => return error.NotDir,2445 .NOTDIR => return error.NotDir,
2450 EINTR => continue,2446 .INTR => continue,
2451 EIO => return error.FileSystem,2447 .IO => return error.FileSystem,
2452 else => |err| return unexpectedErrno(err),2448 else => |err| return unexpectedErrno(err),
2453 }2449 }
2454 }2450 }
...@@ -2501,16 +2497,16 @@ pub fn readlinkZ(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8...@@ -2501,16 +2497,16 @@ pub fn readlinkZ(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8
2501 }2497 }
2502 const rc = system.readlink(file_path, out_buffer.ptr, out_buffer.len);2498 const rc = system.readlink(file_path, out_buffer.ptr, out_buffer.len);
2503 switch (errno(rc)) {2499 switch (errno(rc)) {
2504 0 => return out_buffer[0..@bitCast(usize, rc)],2500 .SUCCESS => return out_buffer[0..@bitCast(usize, rc)],
2505 EACCES => return error.AccessDenied,2501 .ACCES => return error.AccessDenied,
2506 EFAULT => unreachable,2502 .FAULT => unreachable,
2507 EINVAL => unreachable,2503 .INVAL => unreachable,
2508 EIO => return error.FileSystem,2504 .IO => return error.FileSystem,
2509 ELOOP => return error.SymLinkLoop,2505 .LOOP => return error.SymLinkLoop,
2510 ENAMETOOLONG => return error.NameTooLong,2506 .NAMETOOLONG => return error.NameTooLong,
2511 ENOENT => return error.FileNotFound,2507 .NOENT => return error.FileNotFound,
2512 ENOMEM => return error.SystemResources,2508 .NOMEM => return error.SystemResources,
2513 ENOTDIR => return error.NotDir,2509 .NOTDIR => return error.NotDir,
2514 else => |err| return unexpectedErrno(err),2510 else => |err| return unexpectedErrno(err),
2515 }2511 }
2516}2512}
...@@ -2537,17 +2533,17 @@ pub const readlinkatC = @compileError("deprecated: renamed to readlinkatZ");...@@ -2537,17 +2533,17 @@ pub const readlinkatC = @compileError("deprecated: renamed to readlinkatZ");
2537pub fn readlinkatWasi(dirfd: fd_t, file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {2533pub fn readlinkatWasi(dirfd: fd_t, file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {
2538 var bufused: usize = undefined;2534 var bufused: usize = undefined;
2539 switch (wasi.path_readlink(dirfd, file_path.ptr, file_path.len, out_buffer.ptr, out_buffer.len, &bufused)) {2535 switch (wasi.path_readlink(dirfd, file_path.ptr, file_path.len, out_buffer.ptr, out_buffer.len, &bufused)) {
2540 wasi.ESUCCESS => return out_buffer[0..bufused],2536 .SUCCESS => return out_buffer[0..bufused],
2541 wasi.EACCES => return error.AccessDenied,2537 .ACCES => return error.AccessDenied,
2542 wasi.EFAULT => unreachable,2538 .FAULT => unreachable,
2543 wasi.EINVAL => unreachable,2539 .INVAL => unreachable,
2544 wasi.EIO => return error.FileSystem,2540 .IO => return error.FileSystem,
2545 wasi.ELOOP => return error.SymLinkLoop,2541 .LOOP => return error.SymLinkLoop,
2546 wasi.ENAMETOOLONG => return error.NameTooLong,2542 .NAMETOOLONG => return error.NameTooLong,
2547 wasi.ENOENT => return error.FileNotFound,2543 .NOENT => return error.FileNotFound,
2548 wasi.ENOMEM => return error.SystemResources,2544 .NOMEM => return error.SystemResources,
2549 wasi.ENOTDIR => return error.NotDir,2545 .NOTDIR => return error.NotDir,
2550 wasi.ENOTCAPABLE => return error.AccessDenied,2546 .NOTCAPABLE => return error.AccessDenied,
2551 else => |err| return unexpectedErrno(err),2547 else => |err| return unexpectedErrno(err),
2552 }2548 }
2553}2549}
...@@ -2567,16 +2563,16 @@ pub fn readlinkatZ(dirfd: fd_t, file_path: [*:0]const u8, out_buffer: []u8) Read...@@ -2567,16 +2563,16 @@ pub fn readlinkatZ(dirfd: fd_t, file_path: [*:0]const u8, out_buffer: []u8) Read
2567 }2563 }
2568 const rc = system.readlinkat(dirfd, file_path, out_buffer.ptr, out_buffer.len);2564 const rc = system.readlinkat(dirfd, file_path, out_buffer.ptr, out_buffer.len);
2569 switch (errno(rc)) {2565 switch (errno(rc)) {
2570 0 => return out_buffer[0..@bitCast(usize, rc)],2566 .SUCCESS => return out_buffer[0..@bitCast(usize, rc)],
2571 EACCES => return error.AccessDenied,2567 .ACCES => return error.AccessDenied,
2572 EFAULT => unreachable,2568 .FAULT => unreachable,
2573 EINVAL => unreachable,2569 .INVAL => unreachable,
2574 EIO => return error.FileSystem,2570 .IO => return error.FileSystem,
2575 ELOOP => return error.SymLinkLoop,2571 .LOOP => return error.SymLinkLoop,
2576 ENAMETOOLONG => return error.NameTooLong,2572 .NAMETOOLONG => return error.NameTooLong,
2577 ENOENT => return error.FileNotFound,2573 .NOENT => return error.FileNotFound,
2578 ENOMEM => return error.SystemResources,2574 .NOMEM => return error.SystemResources,
2579 ENOTDIR => return error.NotDir,2575 .NOTDIR => return error.NotDir,
2580 else => |err| return unexpectedErrno(err),2576 else => |err| return unexpectedErrno(err),
2581 }2577 }
2582}2578}
...@@ -2590,58 +2586,58 @@ pub const SetIdError = error{ResourceLimitReached} || SetEidError;...@@ -2590,58 +2586,58 @@ pub const SetIdError = error{ResourceLimitReached} || SetEidError;
25902586
2591pub fn setuid(uid: uid_t) SetIdError!void {2587pub fn setuid(uid: uid_t) SetIdError!void {
2592 switch (errno(system.setuid(uid))) {2588 switch (errno(system.setuid(uid))) {
2593 0 => return,2589 .SUCCESS => return,
2594 EAGAIN => return error.ResourceLimitReached,2590 .AGAIN => return error.ResourceLimitReached,
2595 EINVAL => return error.InvalidUserId,2591 .INVAL => return error.InvalidUserId,
2596 EPERM => return error.PermissionDenied,2592 .PERM => return error.PermissionDenied,
2597 else => |err| return unexpectedErrno(err),2593 else => |err| return unexpectedErrno(err),
2598 }2594 }
2599}2595}
26002596
2601pub fn seteuid(uid: uid_t) SetEidError!void {2597pub fn seteuid(uid: uid_t) SetEidError!void {
2602 switch (errno(system.seteuid(uid))) {2598 switch (errno(system.seteuid(uid))) {
2603 0 => return,2599 .SUCCESS => return,
2604 EINVAL => return error.InvalidUserId,2600 .INVAL => return error.InvalidUserId,
2605 EPERM => return error.PermissionDenied,2601 .PERM => return error.PermissionDenied,
2606 else => |err| return unexpectedErrno(err),2602 else => |err| return unexpectedErrno(err),
2607 }2603 }
2608}2604}
26092605
2610pub fn setreuid(ruid: uid_t, euid: uid_t) SetIdError!void {2606pub fn setreuid(ruid: uid_t, euid: uid_t) SetIdError!void {
2611 switch (errno(system.setreuid(ruid, euid))) {2607 switch (errno(system.setreuid(ruid, euid))) {
2612 0 => return,2608 .SUCCESS => return,
2613 EAGAIN => return error.ResourceLimitReached,2609 .AGAIN => return error.ResourceLimitReached,
2614 EINVAL => return error.InvalidUserId,2610 .INVAL => return error.InvalidUserId,
2615 EPERM => return error.PermissionDenied,2611 .PERM => return error.PermissionDenied,
2616 else => |err| return unexpectedErrno(err),2612 else => |err| return unexpectedErrno(err),
2617 }2613 }
2618}2614}
26192615
2620pub fn setgid(gid: gid_t) SetIdError!void {2616pub fn setgid(gid: gid_t) SetIdError!void {
2621 switch (errno(system.setgid(gid))) {2617 switch (errno(system.setgid(gid))) {
2622 0 => return,2618 .SUCCESS => return,
2623 EAGAIN => return error.ResourceLimitReached,2619 .AGAIN => return error.ResourceLimitReached,
2624 EINVAL => return error.InvalidUserId,2620 .INVAL => return error.InvalidUserId,
2625 EPERM => return error.PermissionDenied,2621 .PERM => return error.PermissionDenied,
2626 else => |err| return unexpectedErrno(err),2622 else => |err| return unexpectedErrno(err),
2627 }2623 }
2628}2624}
26292625
2630pub fn setegid(uid: uid_t) SetEidError!void {2626pub fn setegid(uid: uid_t) SetEidError!void {
2631 switch (errno(system.setegid(uid))) {2627 switch (errno(system.setegid(uid))) {
2632 0 => return,2628 .SUCCESS => return,
2633 EINVAL => return error.InvalidUserId,2629 .INVAL => return error.InvalidUserId,
2634 EPERM => return error.PermissionDenied,2630 .PERM => return error.PermissionDenied,
2635 else => |err| return unexpectedErrno(err),2631 else => |err| return unexpectedErrno(err),
2636 }2632 }
2637}2633}
26382634
2639pub fn setregid(rgid: gid_t, egid: gid_t) SetIdError!void {2635pub fn setregid(rgid: gid_t, egid: gid_t) SetIdError!void {
2640 switch (errno(system.setregid(rgid, egid))) {2636 switch (errno(system.setregid(rgid, egid))) {
2641 0 => return,2637 .SUCCESS => return,
2642 EAGAIN => return error.ResourceLimitReached,2638 .AGAIN => return error.ResourceLimitReached,
2643 EINVAL => return error.InvalidUserId,2639 .INVAL => return error.InvalidUserId,
2644 EPERM => return error.PermissionDenied,2640 .PERM => return error.PermissionDenied,
2645 else => |err| return unexpectedErrno(err),2641 else => |err| return unexpectedErrno(err),
2646 }2642 }
2647}2643}
...@@ -2680,9 +2676,10 @@ pub fn isatty(handle: fd_t) bool {...@@ -2680,9 +2676,10 @@ pub fn isatty(handle: fd_t) bool {
2680 while (true) {2676 while (true) {
2681 var wsz: linux.winsize = undefined;2677 var wsz: linux.winsize = undefined;
2682 const fd = @bitCast(usize, @as(isize, handle));2678 const fd = @bitCast(usize, @as(isize, handle));
2683 switch (linux.syscall3(.ioctl, fd, linux.TIOCGWINSZ, @ptrToInt(&wsz))) {2679 const rc = linux.syscall3(.ioctl, fd, linux.TIOCGWINSZ, @ptrToInt(&wsz));
2684 0 => return true,2680 switch (linux.getErrno(rc)) {
2685 EINTR => continue,2681 .SUCCESS => return true,
2682 .INTR => continue,
2686 else => return false,2683 else => return false,
2687 }2684 }
2688 }2685 }
...@@ -2777,22 +2774,22 @@ pub fn socket(domain: u32, socket_type: u32, protocol: u32) SocketError!socket_t...@@ -2777,22 +2774,22 @@ pub fn socket(domain: u32, socket_type: u32, protocol: u32) SocketError!socket_t
2777 socket_type;2774 socket_type;
2778 const rc = system.socket(domain, filtered_sock_type, protocol);2775 const rc = system.socket(domain, filtered_sock_type, protocol);
2779 switch (errno(rc)) {2776 switch (errno(rc)) {
2780 0 => {2777 .SUCCESS => {
2781 const fd = @intCast(fd_t, rc);2778 const fd = @intCast(fd_t, rc);
2782 if (!have_sock_flags) {2779 if (!have_sock_flags) {
2783 try setSockFlags(fd, socket_type);2780 try setSockFlags(fd, socket_type);
2784 }2781 }
2785 return fd;2782 return fd;
2786 },2783 },
2787 EACCES => return error.PermissionDenied,2784 .ACCES => return error.PermissionDenied,
2788 EAFNOSUPPORT => return error.AddressFamilyNotSupported,2785 .AFNOSUPPORT => return error.AddressFamilyNotSupported,
2789 EINVAL => return error.ProtocolFamilyNotAvailable,2786 .INVAL => return error.ProtocolFamilyNotAvailable,
2790 EMFILE => return error.ProcessFdQuotaExceeded,2787 .MFILE => return error.ProcessFdQuotaExceeded,
2791 ENFILE => return error.SystemFdQuotaExceeded,2788 .NFILE => return error.SystemFdQuotaExceeded,
2792 ENOBUFS => return error.SystemResources,2789 .NOBUFS => return error.SystemResources,
2793 ENOMEM => return error.SystemResources,2790 .NOMEM => return error.SystemResources,
2794 EPROTONOSUPPORT => return error.ProtocolNotSupported,2791 .PROTONOSUPPORT => return error.ProtocolNotSupported,
2795 EPROTOTYPE => return error.SocketTypeNotSupported,2792 .PROTOTYPE => return error.SocketTypeNotSupported,
2796 else => |err| return unexpectedErrno(err),2793 else => |err| return unexpectedErrno(err),
2797 }2794 }
2798}2795}
...@@ -2840,12 +2837,12 @@ pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {...@@ -2840,12 +2837,12 @@ pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {
2840 .both => SHUT_RDWR,2837 .both => SHUT_RDWR,
2841 });2838 });
2842 switch (errno(rc)) {2839 switch (errno(rc)) {
2843 0 => return,2840 .SUCCESS => return,
2844 EBADF => unreachable,2841 .BADF => unreachable,
2845 EINVAL => unreachable,2842 .INVAL => unreachable,
2846 ENOTCONN => return error.SocketNotConnected,2843 .NOTCONN => return error.SocketNotConnected,
2847 ENOTSOCK => unreachable,2844 .NOTSOCK => unreachable,
2848 ENOBUFS => return error.SystemResources,2845 .NOBUFS => return error.SystemResources,
2849 else => |err| return unexpectedErrno(err),2846 else => |err| return unexpectedErrno(err),
2850 }2847 }
2851 }2848 }
...@@ -2924,20 +2921,20 @@ pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!voi...@@ -2924,20 +2921,20 @@ pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!voi
2924 } else {2921 } else {
2925 const rc = system.bind(sock, addr, len);2922 const rc = system.bind(sock, addr, len);
2926 switch (errno(rc)) {2923 switch (errno(rc)) {
2927 0 => return,2924 .SUCCESS => return,
2928 EACCES => return error.AccessDenied,2925 .ACCES => return error.AccessDenied,
2929 EADDRINUSE => return error.AddressInUse,2926 .ADDRINUSE => return error.AddressInUse,
2930 EBADF => unreachable, // always a race condition if this error is returned2927 .BADF => unreachable, // always a race condition if this error is returned
2931 EINVAL => unreachable, // invalid parameters2928 .INVAL => unreachable, // invalid parameters
2932 ENOTSOCK => unreachable, // invalid `sockfd`2929 .NOTSOCK => unreachable, // invalid `sockfd`
2933 EADDRNOTAVAIL => return error.AddressNotAvailable,2930 .ADDRNOTAVAIL => return error.AddressNotAvailable,
2934 EFAULT => unreachable, // invalid `addr` pointer2931 .FAULT => unreachable, // invalid `addr` pointer
2935 ELOOP => return error.SymLinkLoop,2932 .LOOP => return error.SymLinkLoop,
2936 ENAMETOOLONG => return error.NameTooLong,2933 .NAMETOOLONG => return error.NameTooLong,
2937 ENOENT => return error.FileNotFound,2934 .NOENT => return error.FileNotFound,
2938 ENOMEM => return error.SystemResources,2935 .NOMEM => return error.SystemResources,
2939 ENOTDIR => return error.NotDir,2936 .NOTDIR => return error.NotDir,
2940 EROFS => return error.ReadOnlyFileSystem,2937 .ROFS => return error.ReadOnlyFileSystem,
2941 else => |err| return unexpectedErrno(err),2938 else => |err| return unexpectedErrno(err),
2942 }2939 }
2943 }2940 }
...@@ -2993,11 +2990,11 @@ pub fn listen(sock: socket_t, backlog: u31) ListenError!void {...@@ -2993,11 +2990,11 @@ pub fn listen(sock: socket_t, backlog: u31) ListenError!void {
2993 } else {2990 } else {
2994 const rc = system.listen(sock, backlog);2991 const rc = system.listen(sock, backlog);
2995 switch (errno(rc)) {2992 switch (errno(rc)) {
2996 0 => return,2993 .SUCCESS => return,
2997 EADDRINUSE => return error.AddressInUse,2994 .ADDRINUSE => return error.AddressInUse,
2998 EBADF => unreachable,2995 .BADF => unreachable,
2999 ENOTSOCK => return error.FileDescriptorNotASocket,2996 .NOTSOCK => return error.FileDescriptorNotASocket,
3000 EOPNOTSUPP => return error.OperationNotSupported,2997 .OPNOTSUPP => return error.OperationNotSupported,
3001 else => |err| return unexpectedErrno(err),2998 else => |err| return unexpectedErrno(err),
3002 }2999 }
3003 }3000 }
...@@ -3099,23 +3096,23 @@ pub fn accept(...@@ -3099,23 +3096,23 @@ pub fn accept(
3099 }3096 }
3100 } else {3097 } else {
3101 switch (errno(rc)) {3098 switch (errno(rc)) {
3102 0 => {3099 .SUCCESS => {
3103 break @intCast(socket_t, rc);3100 break @intCast(socket_t, rc);
3104 },3101 },
3105 EINTR => continue,3102 .INTR => continue,
3106 EAGAIN => return error.WouldBlock,3103 .AGAIN => return error.WouldBlock,
3107 EBADF => unreachable, // always a race condition3104 .BADF => unreachable, // always a race condition
3108 ECONNABORTED => return error.ConnectionAborted,3105 .CONNABORTED => return error.ConnectionAborted,
3109 EFAULT => unreachable,3106 .FAULT => unreachable,
3110 EINVAL => return error.SocketNotListening,3107 .INVAL => return error.SocketNotListening,
3111 ENOTSOCK => unreachable,3108 .NOTSOCK => unreachable,
3112 EMFILE => return error.ProcessFdQuotaExceeded,3109 .MFILE => return error.ProcessFdQuotaExceeded,
3113 ENFILE => return error.SystemFdQuotaExceeded,3110 .NFILE => return error.SystemFdQuotaExceeded,
3114 ENOBUFS => return error.SystemResources,3111 .NOBUFS => return error.SystemResources,
3115 ENOMEM => return error.SystemResources,3112 .NOMEM => return error.SystemResources,
3116 EOPNOTSUPP => unreachable,3113 .OPNOTSUPP => unreachable,
3117 EPROTO => return error.ProtocolFailure,3114 .PROTO => return error.ProtocolFailure,
3118 EPERM => return error.BlockedByFirewall,3115 .PERM => return error.BlockedByFirewall,
3119 else => |err| return unexpectedErrno(err),3116 else => |err| return unexpectedErrno(err),
3120 }3117 }
3121 }3118 }
...@@ -3144,13 +3141,13 @@ pub const EpollCreateError = error{...@@ -3144,13 +3141,13 @@ pub const EpollCreateError = error{
3144pub fn epoll_create1(flags: u32) EpollCreateError!i32 {3141pub fn epoll_create1(flags: u32) EpollCreateError!i32 {
3145 const rc = system.epoll_create1(flags);3142 const rc = system.epoll_create1(flags);
3146 switch (errno(rc)) {3143 switch (errno(rc)) {
3147 0 => return @intCast(i32, rc),3144 .SUCCESS => return @intCast(i32, rc),
3148 else => |err| return unexpectedErrno(err),3145 else => |err| return unexpectedErrno(err),
31493146
3150 EINVAL => unreachable,3147 .INVAL => unreachable,
3151 EMFILE => return error.ProcessFdQuotaExceeded,3148 .MFILE => return error.ProcessFdQuotaExceeded,
3152 ENFILE => return error.SystemFdQuotaExceeded,3149 .NFILE => return error.SystemFdQuotaExceeded,
3153 ENOMEM => return error.SystemResources,3150 .NOMEM => return error.SystemResources,
3154 }3151 }
3155}3152}
31563153
...@@ -3183,17 +3180,17 @@ pub const EpollCtlError = error{...@@ -3183,17 +3180,17 @@ pub const EpollCtlError = error{
3183pub fn epoll_ctl(epfd: i32, op: u32, fd: i32, event: ?*epoll_event) EpollCtlError!void {3180pub fn epoll_ctl(epfd: i32, op: u32, fd: i32, event: ?*epoll_event) EpollCtlError!void {
3184 const rc = system.epoll_ctl(epfd, op, fd, event);3181 const rc = system.epoll_ctl(epfd, op, fd, event);
3185 switch (errno(rc)) {3182 switch (errno(rc)) {
3186 0 => return,3183 .SUCCESS => return,
3187 else => |err| return unexpectedErrno(err),3184 else => |err| return unexpectedErrno(err),
31883185
3189 EBADF => unreachable, // always a race condition if this happens3186 .BADF => unreachable, // always a race condition if this happens
3190 EEXIST => return error.FileDescriptorAlreadyPresentInSet,3187 .EXIST => return error.FileDescriptorAlreadyPresentInSet,
3191 EINVAL => unreachable,3188 .INVAL => unreachable,
3192 ELOOP => return error.OperationCausesCircularLoop,3189 .LOOP => return error.OperationCausesCircularLoop,
3193 ENOENT => return error.FileDescriptorNotRegistered,3190 .NOENT => return error.FileDescriptorNotRegistered,
3194 ENOMEM => return error.SystemResources,3191 .NOMEM => return error.SystemResources,
3195 ENOSPC => return error.UserResourceLimitReached,3192 .NOSPC => return error.UserResourceLimitReached,
3196 EPERM => return error.FileDescriptorIncompatibleWithEpoll,3193 .PERM => return error.FileDescriptorIncompatibleWithEpoll,
3197 }3194 }
3198}3195}
31993196
...@@ -3205,11 +3202,11 @@ pub fn epoll_wait(epfd: i32, events: []epoll_event, timeout: i32) usize {...@@ -3205,11 +3202,11 @@ pub fn epoll_wait(epfd: i32, events: []epoll_event, timeout: i32) usize {
3205 // TODO get rid of the @intCast3202 // TODO get rid of the @intCast
3206 const rc = system.epoll_wait(epfd, events.ptr, @intCast(u32, events.len), timeout);3203 const rc = system.epoll_wait(epfd, events.ptr, @intCast(u32, events.len), timeout);
3207 switch (errno(rc)) {3204 switch (errno(rc)) {
3208 0 => return @intCast(usize, rc),3205 .SUCCESS => return @intCast(usize, rc),
3209 EINTR => continue,3206 .INTR => continue,
3210 EBADF => unreachable,3207 .BADF => unreachable,
3211 EFAULT => unreachable,3208 .FAULT => unreachable,
3212 EINVAL => unreachable,3209 .INVAL => unreachable,
3213 else => unreachable,3210 else => unreachable,
3214 }3211 }
3215 }3212 }
...@@ -3224,14 +3221,14 @@ pub const EventFdError = error{...@@ -3224,14 +3221,14 @@ pub const EventFdError = error{
3224pub fn eventfd(initval: u32, flags: u32) EventFdError!i32 {3221pub fn eventfd(initval: u32, flags: u32) EventFdError!i32 {
3225 const rc = system.eventfd(initval, flags);3222 const rc = system.eventfd(initval, flags);
3226 switch (errno(rc)) {3223 switch (errno(rc)) {
3227 0 => return @intCast(i32, rc),3224 .SUCCESS => return @intCast(i32, rc),
3228 else => |err| return unexpectedErrno(err),3225 else => |err| return unexpectedErrno(err),
32293226
3230 EINVAL => unreachable, // invalid parameters3227 .INVAL => unreachable, // invalid parameters
3231 EMFILE => return error.ProcessFdQuotaExceeded,3228 .MFILE => return error.ProcessFdQuotaExceeded,
3232 ENFILE => return error.SystemFdQuotaExceeded,3229 .NFILE => return error.SystemFdQuotaExceeded,
3233 ENODEV => return error.SystemResources,3230 .NODEV => return error.SystemResources,
3234 ENOMEM => return error.SystemResources,3231 .NOMEM => return error.SystemResources,
3235 }3232 }
3236}3233}
32373234
...@@ -3265,14 +3262,14 @@ pub fn getsockname(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock...@@ -3265,14 +3262,14 @@ pub fn getsockname(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock
3265 } else {3262 } else {
3266 const rc = system.getsockname(sock, addr, addrlen);3263 const rc = system.getsockname(sock, addr, addrlen);
3267 switch (errno(rc)) {3264 switch (errno(rc)) {
3268 0 => return,3265 .SUCCESS => return,
3269 else => |err| return unexpectedErrno(err),3266 else => |err| return unexpectedErrno(err),
32703267
3271 EBADF => unreachable, // always a race condition3268 .BADF => unreachable, // always a race condition
3272 EFAULT => unreachable,3269 .FAULT => unreachable,
3273 EINVAL => unreachable, // invalid parameters3270 .INVAL => unreachable, // invalid parameters
3274 ENOTSOCK => return error.FileDescriptorNotASocket,3271 .NOTSOCK => return error.FileDescriptorNotASocket,
3275 ENOBUFS => return error.SystemResources,3272 .NOBUFS => return error.SystemResources,
3276 }3273 }
3277 }3274 }
3278}3275}
...@@ -3294,14 +3291,14 @@ pub fn getpeername(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock...@@ -3294,14 +3291,14 @@ pub fn getpeername(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock
3294 } else {3291 } else {
3295 const rc = system.getpeername(sock, addr, addrlen);3292 const rc = system.getpeername(sock, addr, addrlen);
3296 switch (errno(rc)) {3293 switch (errno(rc)) {
3297 0 => return,3294 .SUCCESS => return,
3298 else => |err| return unexpectedErrno(err),3295 else => |err| return unexpectedErrno(err),
32993296
3300 EBADF => unreachable, // always a race condition3297 .BADF => unreachable, // always a race condition
3301 EFAULT => unreachable,3298 .FAULT => unreachable,
3302 EINVAL => unreachable, // invalid parameters3299 .INVAL => unreachable, // invalid parameters
3303 ENOTSOCK => return error.FileDescriptorNotASocket,3300 .NOTSOCK => return error.FileDescriptorNotASocket,
3304 ENOBUFS => return error.SystemResources,3301 .NOBUFS => return error.SystemResources,
3305 }3302 }
3306 }3303 }
3307}3304}
...@@ -3384,61 +3381,61 @@ pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) Conne...@@ -3384,61 +3381,61 @@ pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) Conne
33843381
3385 while (true) {3382 while (true) {
3386 switch (errno(system.connect(sock, sock_addr, len))) {3383 switch (errno(system.connect(sock, sock_addr, len))) {
3387 0 => return,3384 .SUCCESS => return,
3388 EACCES => return error.PermissionDenied,3385 .ACCES => return error.PermissionDenied,
3389 EPERM => return error.PermissionDenied,3386 .PERM => return error.PermissionDenied,
3390 EADDRINUSE => return error.AddressInUse,3387 .ADDRINUSE => return error.AddressInUse,
3391 EADDRNOTAVAIL => return error.AddressNotAvailable,3388 .ADDRNOTAVAIL => return error.AddressNotAvailable,
3392 EAFNOSUPPORT => return error.AddressFamilyNotSupported,3389 .AFNOSUPPORT => return error.AddressFamilyNotSupported,
3393 EAGAIN, EINPROGRESS => return error.WouldBlock,3390 .AGAIN, .INPROGRESS => return error.WouldBlock,
3394 EALREADY => return error.ConnectionPending,3391 .ALREADY => return error.ConnectionPending,
3395 EBADF => unreachable, // sockfd is not a valid open file descriptor.3392 .BADF => unreachable, // sockfd is not a valid open file descriptor.
3396 ECONNREFUSED => return error.ConnectionRefused,3393 .CONNREFUSED => return error.ConnectionRefused,
3397 ECONNRESET => return error.ConnectionResetByPeer,3394 .CONNRESET => return error.ConnectionResetByPeer,
3398 EFAULT => unreachable, // The socket structure address is outside the user's address space.3395 .FAULT => unreachable, // The socket structure address is outside the user's address space.
3399 EINTR => continue,3396 .INTR => continue,
3400 EISCONN => unreachable, // The socket is already connected.3397 .ISCONN => unreachable, // The socket is already connected.
3401 ENETUNREACH => return error.NetworkUnreachable,3398 .NETUNREACH => return error.NetworkUnreachable,
3402 ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.3399 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
3403 EPROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.3400 .PROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
3404 ETIMEDOUT => return error.ConnectionTimedOut,3401 .TIMEDOUT => return error.ConnectionTimedOut,
3405 ENOENT => return error.FileNotFound, // Returned when socket is AF_UNIX and the given path does not exist.3402 .NOENT => return error.FileNotFound, // Returned when socket is AF_UNIX and the given path does not exist.
3406 else => |err| return unexpectedErrno(err),3403 else => |err| return unexpectedErrno(err),
3407 }3404 }
3408 }3405 }
3409}3406}
34103407
3411pub fn getsockoptError(sockfd: fd_t) ConnectError!void {3408pub fn getsockoptError(sockfd: fd_t) ConnectError!void {
3412 var err_code: u32 = undefined;3409 var err_code: i32 = undefined;
3413 var size: u32 = @sizeOf(u32);3410 var size: u32 = @sizeOf(u32);
3414 const rc = system.getsockopt(sockfd, SOL_SOCKET, SO_ERROR, @ptrCast([*]u8, &err_code), &size);3411 const rc = system.getsockopt(sockfd, SOL_SOCKET, SO_ERROR, @ptrCast([*]u8, &err_code), &size);
3415 assert(size == 4);3412 assert(size == 4);
3416 switch (errno(rc)) {3413 switch (errno(rc)) {
3417 0 => switch (err_code) {3414 .SUCCESS => switch (@intToEnum(E, err_code)) {
3418 0 => return,3415 .SUCCESS => return,
3419 EACCES => return error.PermissionDenied,3416 .ACCES => return error.PermissionDenied,
3420 EPERM => return error.PermissionDenied,3417 .PERM => return error.PermissionDenied,
3421 EADDRINUSE => return error.AddressInUse,3418 .ADDRINUSE => return error.AddressInUse,
3422 EADDRNOTAVAIL => return error.AddressNotAvailable,3419 .ADDRNOTAVAIL => return error.AddressNotAvailable,
3423 EAFNOSUPPORT => return error.AddressFamilyNotSupported,3420 .AFNOSUPPORT => return error.AddressFamilyNotSupported,
3424 EAGAIN => return error.SystemResources,3421 .AGAIN => return error.SystemResources,
3425 EALREADY => return error.ConnectionPending,3422 .ALREADY => return error.ConnectionPending,
3426 EBADF => unreachable, // sockfd is not a valid open file descriptor.3423 .BADF => unreachable, // sockfd is not a valid open file descriptor.
3427 ECONNREFUSED => return error.ConnectionRefused,3424 .CONNREFUSED => return error.ConnectionRefused,
3428 EFAULT => unreachable, // The socket structure address is outside the user's address space.3425 .FAULT => unreachable, // The socket structure address is outside the user's address space.
3429 EISCONN => unreachable, // The socket is already connected.3426 .ISCONN => unreachable, // The socket is already connected.
3430 ENETUNREACH => return error.NetworkUnreachable,3427 .NETUNREACH => return error.NetworkUnreachable,
3431 ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.3428 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
3432 EPROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.3429 .PROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
3433 ETIMEDOUT => return error.ConnectionTimedOut,3430 .TIMEDOUT => return error.ConnectionTimedOut,
3434 ECONNRESET => return error.ConnectionResetByPeer,3431 .CONNRESET => return error.ConnectionResetByPeer,
3435 else => |err| return unexpectedErrno(err),3432 else => |err| return unexpectedErrno(err),
3436 },3433 },
3437 EBADF => unreachable, // The argument sockfd is not a valid file descriptor.3434 .BADF => unreachable, // The argument sockfd is not a valid file descriptor.
3438 EFAULT => unreachable, // The address pointed to by optval or optlen is not in a valid part of the process address space.3435 .FAULT => unreachable, // The address pointed to by optval or optlen is not in a valid part of the process address space.
3439 EINVAL => unreachable,3436 .INVAL => unreachable,
3440 ENOPROTOOPT => unreachable, // The option is unknown at the level indicated.3437 .NOPROTOOPT => unreachable, // The option is unknown at the level indicated.
3441 ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.3438 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
3442 else => |err| return unexpectedErrno(err),3439 else => |err| return unexpectedErrno(err),
3443 }3440 }
3444}3441}
...@@ -3454,13 +3451,13 @@ pub fn waitpid(pid: pid_t, flags: u32) WaitPidResult {...@@ -3454,13 +3451,13 @@ pub fn waitpid(pid: pid_t, flags: u32) WaitPidResult {
3454 while (true) {3451 while (true) {
3455 const rc = system.waitpid(pid, &status, if (builtin.link_libc) @intCast(c_int, flags) else flags);3452 const rc = system.waitpid(pid, &status, if (builtin.link_libc) @intCast(c_int, flags) else flags);
3456 switch (errno(rc)) {3453 switch (errno(rc)) {
3457 0 => return .{3454 .SUCCESS => return .{
3458 .pid = @intCast(pid_t, rc),3455 .pid = @intCast(pid_t, rc),
3459 .status = @bitCast(u32, status),3456 .status = @bitCast(u32, status),
3460 },3457 },
3461 EINTR => continue,3458 .INTR => continue,
3462 ECHILD => unreachable, // The process specified does not exist. It would be a race condition to handle this error.3459 .CHILD => unreachable, // The process specified does not exist. It would be a race condition to handle this error.
3463 EINVAL => unreachable, // Invalid flags.3460 .INVAL => unreachable, // Invalid flags.
3464 else => unreachable,3461 else => unreachable,
3465 }3462 }
3466 }3463 }
...@@ -3484,12 +3481,12 @@ pub fn fstat(fd: fd_t) FStatError!Stat {...@@ -3484,12 +3481,12 @@ pub fn fstat(fd: fd_t) FStatError!Stat {
3484 if (builtin.os.tag == .wasi and !builtin.link_libc) {3481 if (builtin.os.tag == .wasi and !builtin.link_libc) {
3485 var stat: wasi.filestat_t = undefined;3482 var stat: wasi.filestat_t = undefined;
3486 switch (wasi.fd_filestat_get(fd, &stat)) {3483 switch (wasi.fd_filestat_get(fd, &stat)) {
3487 wasi.ESUCCESS => return Stat.fromFilestat(stat),3484 .SUCCESS => return Stat.fromFilestat(stat),
3488 wasi.EINVAL => unreachable,3485 .INVAL => unreachable,
3489 wasi.EBADF => unreachable, // Always a race condition.3486 .BADF => unreachable, // Always a race condition.
3490 wasi.ENOMEM => return error.SystemResources,3487 .NOMEM => return error.SystemResources,
3491 wasi.EACCES => return error.AccessDenied,3488 .ACCES => return error.AccessDenied,
3492 wasi.ENOTCAPABLE => return error.AccessDenied,3489 .NOTCAPABLE => return error.AccessDenied,
3493 else => |err| return unexpectedErrno(err),3490 else => |err| return unexpectedErrno(err),
3494 }3491 }
3495 }3492 }
...@@ -3504,11 +3501,11 @@ pub fn fstat(fd: fd_t) FStatError!Stat {...@@ -3504,11 +3501,11 @@ pub fn fstat(fd: fd_t) FStatError!Stat {
35043501
3505 var stat = mem.zeroes(Stat);3502 var stat = mem.zeroes(Stat);
3506 switch (errno(fstat_sym(fd, &stat))) {3503 switch (errno(fstat_sym(fd, &stat))) {
3507 0 => return stat,3504 .SUCCESS => return stat,
3508 EINVAL => unreachable,3505 .INVAL => unreachable,
3509 EBADF => unreachable, // Always a race condition.3506 .BADF => unreachable, // Always a race condition.
3510 ENOMEM => return error.SystemResources,3507 .NOMEM => return error.SystemResources,
3511 EACCES => return error.AccessDenied,3508 .ACCES => return error.AccessDenied,
3512 else => |err| return unexpectedErrno(err),3509 else => |err| return unexpectedErrno(err),
3513 }3510 }
3514}3511}
...@@ -3536,16 +3533,16 @@ pub const fstatatC = @compileError("deprecated: renamed to fstatatZ");...@@ -3536,16 +3533,16 @@ pub const fstatatC = @compileError("deprecated: renamed to fstatatZ");
3536pub fn fstatatWasi(dirfd: fd_t, pathname: []const u8, flags: u32) FStatAtError!Stat {3533pub fn fstatatWasi(dirfd: fd_t, pathname: []const u8, flags: u32) FStatAtError!Stat {
3537 var stat: wasi.filestat_t = undefined;3534 var stat: wasi.filestat_t = undefined;
3538 switch (wasi.path_filestat_get(dirfd, flags, pathname.ptr, pathname.len, &stat)) {3535 switch (wasi.path_filestat_get(dirfd, flags, pathname.ptr, pathname.len, &stat)) {
3539 wasi.ESUCCESS => return Stat.fromFilestat(stat),3536 .SUCCESS => return Stat.fromFilestat(stat),
3540 wasi.EINVAL => unreachable,3537 .INVAL => unreachable,
3541 wasi.EBADF => unreachable, // Always a race condition.3538 .BADF => unreachable, // Always a race condition.
3542 wasi.ENOMEM => return error.SystemResources,3539 .NOMEM => return error.SystemResources,
3543 wasi.EACCES => return error.AccessDenied,3540 .ACCES => return error.AccessDenied,
3544 wasi.EFAULT => unreachable,3541 .FAULT => unreachable,
3545 wasi.ENAMETOOLONG => return error.NameTooLong,3542 .NAMETOOLONG => return error.NameTooLong,
3546 wasi.ENOENT => return error.FileNotFound,3543 .NOENT => return error.FileNotFound,
3547 wasi.ENOTDIR => return error.FileNotFound,3544 .NOTDIR => return error.FileNotFound,
3548 wasi.ENOTCAPABLE => return error.AccessDenied,3545 .NOTCAPABLE => return error.AccessDenied,
3549 else => |err| return unexpectedErrno(err),3546 else => |err| return unexpectedErrno(err),
3550 }3547 }
3551}3548}
...@@ -3560,17 +3557,17 @@ pub fn fstatatZ(dirfd: fd_t, pathname: [*:0]const u8, flags: u32) FStatAtError!S...@@ -3560,17 +3557,17 @@ pub fn fstatatZ(dirfd: fd_t, pathname: [*:0]const u8, flags: u32) FStatAtError!S
35603557
3561 var stat = mem.zeroes(Stat);3558 var stat = mem.zeroes(Stat);
3562 switch (errno(fstatat_sym(dirfd, pathname, &stat, flags))) {3559 switch (errno(fstatat_sym(dirfd, pathname, &stat, flags))) {
3563 0 => return stat,3560 .SUCCESS => return stat,
3564 EINVAL => unreachable,3561 .INVAL => unreachable,
3565 EBADF => unreachable, // Always a race condition.3562 .BADF => unreachable, // Always a race condition.
3566 ENOMEM => return error.SystemResources,3563 .NOMEM => return error.SystemResources,
3567 EACCES => return error.AccessDenied,3564 .ACCES => return error.AccessDenied,
3568 EPERM => return error.AccessDenied,3565 .PERM => return error.AccessDenied,
3569 EFAULT => unreachable,3566 .FAULT => unreachable,
3570 ENAMETOOLONG => return error.NameTooLong,3567 .NAMETOOLONG => return error.NameTooLong,
3571 ELOOP => return error.SymLinkLoop,3568 .LOOP => return error.SymLinkLoop,
3572 ENOENT => return error.FileNotFound,3569 .NOENT => return error.FileNotFound,
3573 ENOTDIR => return error.FileNotFound,3570 .NOTDIR => return error.FileNotFound,
3574 else => |err| return unexpectedErrno(err),3571 else => |err| return unexpectedErrno(err),
3575 }3572 }
3576}3573}
...@@ -3586,9 +3583,9 @@ pub const KQueueError = error{...@@ -3586,9 +3583,9 @@ pub const KQueueError = error{
3586pub fn kqueue() KQueueError!i32 {3583pub fn kqueue() KQueueError!i32 {
3587 const rc = system.kqueue();3584 const rc = system.kqueue();
3588 switch (errno(rc)) {3585 switch (errno(rc)) {
3589 0 => return @intCast(i32, rc),3586 .SUCCESS => return @intCast(i32, rc),
3590 EMFILE => return error.ProcessFdQuotaExceeded,3587 .MFILE => return error.ProcessFdQuotaExceeded,
3591 ENFILE => return error.SystemFdQuotaExceeded,3588 .NFILE => return error.SystemFdQuotaExceeded,
3592 else => |err| return unexpectedErrno(err),3589 else => |err| return unexpectedErrno(err),
3593 }3590 }
3594}3591}
...@@ -3627,15 +3624,15 @@ pub fn kevent(...@@ -3627,15 +3624,15 @@ pub fn kevent(
3627 timeout,3624 timeout,
3628 );3625 );
3629 switch (errno(rc)) {3626 switch (errno(rc)) {
3630 0 => return @intCast(usize, rc),3627 .SUCCESS => return @intCast(usize, rc),
3631 EACCES => return error.AccessDenied,3628 .ACCES => return error.AccessDenied,
3632 EFAULT => unreachable,3629 .FAULT => unreachable,
3633 EBADF => unreachable, // Always a race condition.3630 .BADF => unreachable, // Always a race condition.
3634 EINTR => continue,3631 .INTR => continue,
3635 EINVAL => unreachable,3632 .INVAL => unreachable,
3636 ENOENT => return error.EventNotFound,3633 .NOENT => return error.EventNotFound,
3637 ENOMEM => return error.SystemResources,3634 .NOMEM => return error.SystemResources,
3638 ESRCH => return error.ProcessNotFound,3635 .SRCH => return error.ProcessNotFound,
3639 else => unreachable,3636 else => unreachable,
3640 }3637 }
3641 }3638 }
...@@ -3651,11 +3648,11 @@ pub const INotifyInitError = error{...@@ -3651,11 +3648,11 @@ pub const INotifyInitError = error{
3651pub fn inotify_init1(flags: u32) INotifyInitError!i32 {3648pub fn inotify_init1(flags: u32) INotifyInitError!i32 {
3652 const rc = system.inotify_init1(flags);3649 const rc = system.inotify_init1(flags);
3653 switch (errno(rc)) {3650 switch (errno(rc)) {
3654 0 => return @intCast(i32, rc),3651 .SUCCESS => return @intCast(i32, rc),
3655 EINVAL => unreachable,3652 .INVAL => unreachable,
3656 EMFILE => return error.ProcessFdQuotaExceeded,3653 .MFILE => return error.ProcessFdQuotaExceeded,
3657 ENFILE => return error.SystemFdQuotaExceeded,3654 .NFILE => return error.SystemFdQuotaExceeded,
3658 ENOMEM => return error.SystemResources,3655 .NOMEM => return error.SystemResources,
3659 else => |err| return unexpectedErrno(err),3656 else => |err| return unexpectedErrno(err),
3660 }3657 }
3661}3658}
...@@ -3681,16 +3678,16 @@ pub const inotify_add_watchC = @compileError("deprecated: renamed to inotify_add...@@ -3681,16 +3678,16 @@ pub const inotify_add_watchC = @compileError("deprecated: renamed to inotify_add
3681pub fn inotify_add_watchZ(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) INotifyAddWatchError!i32 {3678pub fn inotify_add_watchZ(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) INotifyAddWatchError!i32 {
3682 const rc = system.inotify_add_watch(inotify_fd, pathname, mask);3679 const rc = system.inotify_add_watch(inotify_fd, pathname, mask);
3683 switch (errno(rc)) {3680 switch (errno(rc)) {
3684 0 => return @intCast(i32, rc),3681 .SUCCESS => return @intCast(i32, rc),
3685 EACCES => return error.AccessDenied,3682 .ACCES => return error.AccessDenied,
3686 EBADF => unreachable,3683 .BADF => unreachable,
3687 EFAULT => unreachable,3684 .FAULT => unreachable,
3688 EINVAL => unreachable,3685 .INVAL => unreachable,
3689 ENAMETOOLONG => return error.NameTooLong,3686 .NAMETOOLONG => return error.NameTooLong,
3690 ENOENT => return error.FileNotFound,3687 .NOENT => return error.FileNotFound,
3691 ENOMEM => return error.SystemResources,3688 .NOMEM => return error.SystemResources,
3692 ENOSPC => return error.UserResourceLimitReached,3689 .NOSPC => return error.UserResourceLimitReached,
3693 ENOTDIR => return error.NotDir,3690 .NOTDIR => return error.NotDir,
3694 else => |err| return unexpectedErrno(err),3691 else => |err| return unexpectedErrno(err),
3695 }3692 }
3696}3693}
...@@ -3698,9 +3695,9 @@ pub fn inotify_add_watchZ(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) I...@@ -3698,9 +3695,9 @@ pub fn inotify_add_watchZ(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) I
3698/// remove an existing watch from an inotify instance3695/// remove an existing watch from an inotify instance
3699pub fn inotify_rm_watch(inotify_fd: i32, wd: i32) void {3696pub fn inotify_rm_watch(inotify_fd: i32, wd: i32) void {
3700 switch (errno(system.inotify_rm_watch(inotify_fd, wd))) {3697 switch (errno(system.inotify_rm_watch(inotify_fd, wd))) {
3701 0 => return,3698 .SUCCESS => return,
3702 EBADF => unreachable,3699 .BADF => unreachable,
3703 EINVAL => unreachable,3700 .INVAL => unreachable,
3704 else => unreachable,3701 else => unreachable,
3705 }3702 }
3706}3703}
...@@ -3723,10 +3720,10 @@ pub const MProtectError = error{...@@ -3723,10 +3720,10 @@ pub const MProtectError = error{
3723pub fn mprotect(memory: []align(mem.page_size) u8, protection: u32) MProtectError!void {3720pub fn mprotect(memory: []align(mem.page_size) u8, protection: u32) MProtectError!void {
3724 assert(mem.isAligned(memory.len, mem.page_size));3721 assert(mem.isAligned(memory.len, mem.page_size));
3725 switch (errno(system.mprotect(memory.ptr, memory.len, protection))) {3722 switch (errno(system.mprotect(memory.ptr, memory.len, protection))) {
3726 0 => return,3723 .SUCCESS => return,
3727 EINVAL => unreachable,3724 .INVAL => unreachable,
3728 EACCES => return error.AccessDenied,3725 .ACCES => return error.AccessDenied,
3729 ENOMEM => return error.OutOfMemory,3726 .NOMEM => return error.OutOfMemory,
3730 else => |err| return unexpectedErrno(err),3727 else => |err| return unexpectedErrno(err),
3731 }3728 }
3732}3729}
...@@ -3736,9 +3733,9 @@ pub const ForkError = error{SystemResources} || UnexpectedError;...@@ -3736,9 +3733,9 @@ pub const ForkError = error{SystemResources} || UnexpectedError;
3736pub fn fork() ForkError!pid_t {3733pub fn fork() ForkError!pid_t {
3737 const rc = system.fork();3734 const rc = system.fork();
3738 switch (errno(rc)) {3735 switch (errno(rc)) {
3739 0 => return @intCast(pid_t, rc),3736 .SUCCESS => return @intCast(pid_t, rc),
3740 EAGAIN => return error.SystemResources,3737 .AGAIN => return error.SystemResources,
3741 ENOMEM => return error.SystemResources,3738 .NOMEM => return error.SystemResources,
3742 else => |err| return unexpectedErrno(err),3739 else => |err| return unexpectedErrno(err),
3743 }3740 }
3744}3741}
...@@ -3782,22 +3779,23 @@ pub fn mmap(...@@ -3782,22 +3779,23 @@ pub fn mmap(
3782 const rc = mmap_sym(ptr, length, prot, flags, fd, ioffset);3779 const rc = mmap_sym(ptr, length, prot, flags, fd, ioffset);
3783 const err = if (builtin.link_libc) blk: {3780 const err = if (builtin.link_libc) blk: {
3784 if (rc != std.c.MAP_FAILED) return @ptrCast([*]align(mem.page_size) u8, @alignCast(mem.page_size, rc))[0..length];3781 if (rc != std.c.MAP_FAILED) return @ptrCast([*]align(mem.page_size) u8, @alignCast(mem.page_size, rc))[0..length];
3785 break :blk system._errno().*;3782 break :blk @intToEnum(E, system._errno().*);
3786 } else blk: {3783 } else blk: {
3787 const err = errno(rc);3784 const err = errno(rc);
3788 if (err == 0) return @intToPtr([*]align(mem.page_size) u8, rc)[0..length];3785 if (err == .SUCCESS) return @intToPtr([*]align(mem.page_size) u8, rc)[0..length];
3789 break :blk err;3786 break :blk err;
3790 };3787 };
3791 switch (err) {3788 switch (err) {
3792 ETXTBSY => return error.AccessDenied,3789 .SUCCESS => unreachable,
3793 EACCES => return error.AccessDenied,3790 .TXTBSY => return error.AccessDenied,
3794 EPERM => return error.PermissionDenied,3791 .ACCES => return error.AccessDenied,
3795 EAGAIN => return error.LockedMemoryLimitExceeded,3792 .PERM => return error.PermissionDenied,
3796 EBADF => unreachable, // Always a race condition.3793 .AGAIN => return error.LockedMemoryLimitExceeded,
3797 EOVERFLOW => unreachable, // The number of pages used for length + offset would overflow.3794 .BADF => unreachable, // Always a race condition.
3798 ENODEV => return error.MemoryMappingNotSupported,3795 .OVERFLOW => unreachable, // The number of pages used for length + offset would overflow.
3799 EINVAL => unreachable, // Invalid parameters to mmap()3796 .NODEV => return error.MemoryMappingNotSupported,
3800 ENOMEM => return error.OutOfMemory,3797 .INVAL => unreachable, // Invalid parameters to mmap()
3798 .NOMEM => return error.OutOfMemory,
3801 else => return unexpectedErrno(err),3799 else => return unexpectedErrno(err),
3802 }3800 }
3803}3801}
...@@ -3810,9 +3808,9 @@ pub fn mmap(...@@ -3810,9 +3808,9 @@ pub fn mmap(
3810/// * The Windows function, VirtualFree, has this restriction.3808/// * The Windows function, VirtualFree, has this restriction.
3811pub fn munmap(memory: []align(mem.page_size) const u8) void {3809pub fn munmap(memory: []align(mem.page_size) const u8) void {
3812 switch (errno(system.munmap(memory.ptr, memory.len))) {3810 switch (errno(system.munmap(memory.ptr, memory.len))) {
3813 0 => return,3811 .SUCCESS => return,
3814 EINVAL => unreachable, // Invalid parameters.3812 .INVAL => unreachable, // Invalid parameters.
3815 ENOMEM => unreachable, // Attempted to unmap a region in the middle of an existing mapping.3813 .NOMEM => unreachable, // Attempted to unmap a region in the middle of an existing mapping.
3816 else => unreachable,3814 else => unreachable,
3817 }3815 }
3818}3816}
...@@ -3854,18 +3852,18 @@ pub fn accessZ(path: [*:0]const u8, mode: u32) AccessError!void {...@@ -3854,18 +3852,18 @@ pub fn accessZ(path: [*:0]const u8, mode: u32) AccessError!void {
3854 return;3852 return;
3855 }3853 }
3856 switch (errno(system.access(path, mode))) {3854 switch (errno(system.access(path, mode))) {
3857 0 => return,3855 .SUCCESS => return,
3858 EACCES => return error.PermissionDenied,3856 .ACCES => return error.PermissionDenied,
3859 EROFS => return error.ReadOnlyFileSystem,3857 .ROFS => return error.ReadOnlyFileSystem,
3860 ELOOP => return error.SymLinkLoop,3858 .LOOP => return error.SymLinkLoop,
3861 ETXTBSY => return error.FileBusy,3859 .TXTBSY => return error.FileBusy,
3862 ENOTDIR => return error.FileNotFound,3860 .NOTDIR => return error.FileNotFound,
3863 ENOENT => return error.FileNotFound,3861 .NOENT => return error.FileNotFound,
3864 ENAMETOOLONG => return error.NameTooLong,3862 .NAMETOOLONG => return error.NameTooLong,
3865 EINVAL => unreachable,3863 .INVAL => unreachable,
3866 EFAULT => unreachable,3864 .FAULT => unreachable,
3867 EIO => return error.InputOutput,3865 .IO => return error.InputOutput,
3868 ENOMEM => return error.SystemResources,3866 .NOMEM => return error.SystemResources,
3869 else => |err| return unexpectedErrno(err),3867 else => |err| return unexpectedErrno(err),
3870 }3868 }
3871}3869}
...@@ -3905,18 +3903,18 @@ pub fn faccessatZ(dirfd: fd_t, path: [*:0]const u8, mode: u32, flags: u32) Acces...@@ -3905,18 +3903,18 @@ pub fn faccessatZ(dirfd: fd_t, path: [*:0]const u8, mode: u32, flags: u32) Acces
3905 return faccessatW(dirfd, path_w.span().ptr, mode, flags);3903 return faccessatW(dirfd, path_w.span().ptr, mode, flags);
3906 }3904 }
3907 switch (errno(system.faccessat(dirfd, path, mode, flags))) {3905 switch (errno(system.faccessat(dirfd, path, mode, flags))) {
3908 0 => return,3906 .SUCCESS => return,
3909 EACCES => return error.PermissionDenied,3907 .ACCES => return error.PermissionDenied,
3910 EROFS => return error.ReadOnlyFileSystem,3908 .ROFS => return error.ReadOnlyFileSystem,
3911 ELOOP => return error.SymLinkLoop,3909 .LOOP => return error.SymLinkLoop,
3912 ETXTBSY => return error.FileBusy,3910 .TXTBSY => return error.FileBusy,
3913 ENOTDIR => return error.FileNotFound,3911 .NOTDIR => return error.FileNotFound,
3914 ENOENT => return error.FileNotFound,3912 .NOENT => return error.FileNotFound,
3915 ENAMETOOLONG => return error.NameTooLong,3913 .NAMETOOLONG => return error.NameTooLong,
3916 EINVAL => unreachable,3914 .INVAL => unreachable,
3917 EFAULT => unreachable,3915 .FAULT => unreachable,
3918 EIO => return error.InputOutput,3916 .IO => return error.InputOutput,
3919 ENOMEM => return error.SystemResources,3917 .NOMEM => return error.SystemResources,
3920 else => |err| return unexpectedErrno(err),3918 else => |err| return unexpectedErrno(err),
3921 }3919 }
3922}3920}
...@@ -3972,11 +3970,11 @@ pub const PipeError = error{...@@ -3972,11 +3970,11 @@ pub const PipeError = error{
3972pub fn pipe() PipeError![2]fd_t {3970pub fn pipe() PipeError![2]fd_t {
3973 var fds: [2]fd_t = undefined;3971 var fds: [2]fd_t = undefined;
3974 switch (errno(system.pipe(&fds))) {3972 switch (errno(system.pipe(&fds))) {
3975 0 => return fds,3973 .SUCCESS => return fds,
3976 EINVAL => unreachable, // Invalid parameters to pipe()3974 .INVAL => unreachable, // Invalid parameters to pipe()
3977 EFAULT => unreachable, // Invalid fds pointer3975 .FAULT => unreachable, // Invalid fds pointer
3978 ENFILE => return error.SystemFdQuotaExceeded,3976 .NFILE => return error.SystemFdQuotaExceeded,
3979 EMFILE => return error.ProcessFdQuotaExceeded,3977 .MFILE => return error.ProcessFdQuotaExceeded,
3980 else => |err| return unexpectedErrno(err),3978 else => |err| return unexpectedErrno(err),
3981 }3979 }
3982}3980}
...@@ -3985,11 +3983,11 @@ pub fn pipe2(flags: u32) PipeError![2]fd_t {...@@ -3985,11 +3983,11 @@ pub fn pipe2(flags: u32) PipeError![2]fd_t {
3985 if (@hasDecl(system, "pipe2")) {3983 if (@hasDecl(system, "pipe2")) {
3986 var fds: [2]fd_t = undefined;3984 var fds: [2]fd_t = undefined;
3987 switch (errno(system.pipe2(&fds, flags))) {3985 switch (errno(system.pipe2(&fds, flags))) {
3988 0 => return fds,3986 .SUCCESS => return fds,
3989 EINVAL => unreachable, // Invalid flags3987 .INVAL => unreachable, // Invalid flags
3990 EFAULT => unreachable, // Invalid fds pointer3988 .FAULT => unreachable, // Invalid fds pointer
3991 ENFILE => return error.SystemFdQuotaExceeded,3989 .NFILE => return error.SystemFdQuotaExceeded,
3992 EMFILE => return error.ProcessFdQuotaExceeded,3990 .MFILE => return error.ProcessFdQuotaExceeded,
3993 else => |err| return unexpectedErrno(err),3991 else => |err| return unexpectedErrno(err),
3994 }3992 }
3995 }3993 }
...@@ -4008,9 +4006,9 @@ pub fn pipe2(flags: u32) PipeError![2]fd_t {...@@ -4008,9 +4006,9 @@ pub fn pipe2(flags: u32) PipeError![2]fd_t {
4008 if (flags & O_CLOEXEC != 0) {4006 if (flags & O_CLOEXEC != 0) {
4009 for (fds) |fd| {4007 for (fds) |fd| {
4010 switch (errno(system.fcntl(fd, F_SETFD, @as(u32, FD_CLOEXEC)))) {4008 switch (errno(system.fcntl(fd, F_SETFD, @as(u32, FD_CLOEXEC)))) {
4011 0 => {},4009 .SUCCESS => {},
4012 EINVAL => unreachable, // Invalid flags4010 .INVAL => unreachable, // Invalid flags
4013 EBADF => unreachable, // Always a race condition4011 .BADF => unreachable, // Always a race condition
4014 else => |err| return unexpectedErrno(err),4012 else => |err| return unexpectedErrno(err),
4015 }4013 }
4016 }4014 }
...@@ -4021,9 +4019,9 @@ pub fn pipe2(flags: u32) PipeError![2]fd_t {...@@ -4021,9 +4019,9 @@ pub fn pipe2(flags: u32) PipeError![2]fd_t {
4021 if (new_flags != 0) {4019 if (new_flags != 0) {
4022 for (fds) |fd| {4020 for (fds) |fd| {
4023 switch (errno(system.fcntl(fd, F_SETFL, new_flags))) {4021 switch (errno(system.fcntl(fd, F_SETFL, new_flags))) {
4024 0 => {},4022 .SUCCESS => {},
4025 EINVAL => unreachable, // Invalid flags4023 .INVAL => unreachable, // Invalid flags
4026 EBADF => unreachable, // Always a race condition4024 .BADF => unreachable, // Always a race condition
4027 else => |err| return unexpectedErrno(err),4025 else => |err| return unexpectedErrno(err),
4028 }4026 }
4029 }4027 }
...@@ -4055,11 +4053,11 @@ pub fn sysctl(...@@ -4055,11 +4053,11 @@ pub fn sysctl(
40554053
4056 const name_len = math.cast(c_uint, name.len) catch return error.NameTooLong;4054 const name_len = math.cast(c_uint, name.len) catch return error.NameTooLong;
4057 switch (errno(system.sysctl(name.ptr, name_len, oldp, oldlenp, newp, newlen))) {4055 switch (errno(system.sysctl(name.ptr, name_len, oldp, oldlenp, newp, newlen))) {
4058 0 => return,4056 .SUCCESS => return,
4059 EFAULT => unreachable,4057 .FAULT => unreachable,
4060 EPERM => return error.PermissionDenied,4058 .PERM => return error.PermissionDenied,
4061 ENOMEM => return error.SystemResources,4059 .NOMEM => return error.SystemResources,
4062 ENOENT => return error.UnknownName,4060 .NOENT => return error.UnknownName,
4063 else => |err| return unexpectedErrno(err),4061 else => |err| return unexpectedErrno(err),
4064 }4062 }
4065}4063}
...@@ -4081,19 +4079,19 @@ pub fn sysctlbynameZ(...@@ -4081,19 +4079,19 @@ pub fn sysctlbynameZ(
4081 }4079 }
40824080
4083 switch (errno(system.sysctlbyname(name, oldp, oldlenp, newp, newlen))) {4081 switch (errno(system.sysctlbyname(name, oldp, oldlenp, newp, newlen))) {
4084 0 => return,4082 .SUCCESS => return,
4085 EFAULT => unreachable,4083 .FAULT => unreachable,
4086 EPERM => return error.PermissionDenied,4084 .PERM => return error.PermissionDenied,
4087 ENOMEM => return error.SystemResources,4085 .NOMEM => return error.SystemResources,
4088 ENOENT => return error.UnknownName,4086 .NOENT => return error.UnknownName,
4089 else => |err| return unexpectedErrno(err),4087 else => |err| return unexpectedErrno(err),
4090 }4088 }
4091}4089}
40924090
4093pub fn gettimeofday(tv: ?*timeval, tz: ?*timezone) void {4091pub fn gettimeofday(tv: ?*timeval, tz: ?*timezone) void {
4094 switch (errno(system.gettimeofday(tv, tz))) {4092 switch (errno(system.gettimeofday(tv, tz))) {
4095 0 => return,4093 .SUCCESS => return,
4096 EINVAL => unreachable,4094 .INVAL => unreachable,
4097 else => unreachable,4095 else => unreachable,
4098 }4096 }
4099}4097}
...@@ -4111,12 +4109,12 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {...@@ -4111,12 +4109,12 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
4111 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {4109 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
4112 var result: u64 = undefined;4110 var result: u64 = undefined;
4113 switch (errno(system.llseek(fd, offset, &result, SEEK_SET))) {4111 switch (errno(system.llseek(fd, offset, &result, SEEK_SET))) {
4114 0 => return,4112 .SUCCESS => return,
4115 EBADF => unreachable, // always a race condition4113 .BADF => unreachable, // always a race condition
4116 EINVAL => return error.Unseekable,4114 .INVAL => return error.Unseekable,
4117 EOVERFLOW => return error.Unseekable,4115 .OVERFLOW => return error.Unseekable,
4118 ESPIPE => return error.Unseekable,4116 .SPIPE => return error.Unseekable,
4119 ENXIO => return error.Unseekable,4117 .NXIO => return error.Unseekable,
4120 else => |err| return unexpectedErrno(err),4118 else => |err| return unexpectedErrno(err),
4121 }4119 }
4122 }4120 }
...@@ -4126,13 +4124,13 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {...@@ -4126,13 +4124,13 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
4126 if (builtin.os.tag == .wasi and !builtin.link_libc) {4124 if (builtin.os.tag == .wasi and !builtin.link_libc) {
4127 var new_offset: wasi.filesize_t = undefined;4125 var new_offset: wasi.filesize_t = undefined;
4128 switch (wasi.fd_seek(fd, @bitCast(wasi.filedelta_t, offset), wasi.WHENCE_SET, &new_offset)) {4126 switch (wasi.fd_seek(fd, @bitCast(wasi.filedelta_t, offset), wasi.WHENCE_SET, &new_offset)) {
4129 wasi.ESUCCESS => return,4127 .SUCCESS => return,
4130 wasi.EBADF => unreachable, // always a race condition4128 .BADF => unreachable, // always a race condition
4131 wasi.EINVAL => return error.Unseekable,4129 .INVAL => return error.Unseekable,
4132 wasi.EOVERFLOW => return error.Unseekable,4130 .OVERFLOW => return error.Unseekable,
4133 wasi.ESPIPE => return error.Unseekable,4131 .SPIPE => return error.Unseekable,
4134 wasi.ENXIO => return error.Unseekable,4132 .NXIO => return error.Unseekable,
4135 wasi.ENOTCAPABLE => return error.AccessDenied,4133 .NOTCAPABLE => return error.AccessDenied,
4136 else => |err| return unexpectedErrno(err),4134 else => |err| return unexpectedErrno(err),
4137 }4135 }
4138 }4136 }
...@@ -4144,12 +4142,12 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {...@@ -4144,12 +4142,12 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
41444142
4145 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned4143 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned
4146 switch (errno(lseek_sym(fd, ioffset, SEEK_SET))) {4144 switch (errno(lseek_sym(fd, ioffset, SEEK_SET))) {
4147 0 => return,4145 .SUCCESS => return,
4148 EBADF => unreachable, // always a race condition4146 .BADF => unreachable, // always a race condition
4149 EINVAL => return error.Unseekable,4147 .INVAL => return error.Unseekable,
4150 EOVERFLOW => return error.Unseekable,4148 .OVERFLOW => return error.Unseekable,
4151 ESPIPE => return error.Unseekable,4149 .SPIPE => return error.Unseekable,
4152 ENXIO => return error.Unseekable,4150 .NXIO => return error.Unseekable,
4153 else => |err| return unexpectedErrno(err),4151 else => |err| return unexpectedErrno(err),
4154 }4152 }
4155}4153}
...@@ -4159,12 +4157,12 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {...@@ -4159,12 +4157,12 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
4159 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {4157 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
4160 var result: u64 = undefined;4158 var result: u64 = undefined;
4161 switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_CUR))) {4159 switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_CUR))) {
4162 0 => return,4160 .SUCCESS => return,
4163 EBADF => unreachable, // always a race condition4161 .BADF => unreachable, // always a race condition
4164 EINVAL => return error.Unseekable,4162 .INVAL => return error.Unseekable,
4165 EOVERFLOW => return error.Unseekable,4163 .OVERFLOW => return error.Unseekable,
4166 ESPIPE => return error.Unseekable,4164 .SPIPE => return error.Unseekable,
4167 ENXIO => return error.Unseekable,4165 .NXIO => return error.Unseekable,
4168 else => |err| return unexpectedErrno(err),4166 else => |err| return unexpectedErrno(err),
4169 }4167 }
4170 }4168 }
...@@ -4174,13 +4172,13 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {...@@ -4174,13 +4172,13 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
4174 if (builtin.os.tag == .wasi and !builtin.link_libc) {4172 if (builtin.os.tag == .wasi and !builtin.link_libc) {
4175 var new_offset: wasi.filesize_t = undefined;4173 var new_offset: wasi.filesize_t = undefined;
4176 switch (wasi.fd_seek(fd, offset, wasi.WHENCE_CUR, &new_offset)) {4174 switch (wasi.fd_seek(fd, offset, wasi.WHENCE_CUR, &new_offset)) {
4177 wasi.ESUCCESS => return,4175 .SUCCESS => return,
4178 wasi.EBADF => unreachable, // always a race condition4176 .BADF => unreachable, // always a race condition
4179 wasi.EINVAL => return error.Unseekable,4177 .INVAL => return error.Unseekable,
4180 wasi.EOVERFLOW => return error.Unseekable,4178 .OVERFLOW => return error.Unseekable,
4181 wasi.ESPIPE => return error.Unseekable,4179 .SPIPE => return error.Unseekable,
4182 wasi.ENXIO => return error.Unseekable,4180 .NXIO => return error.Unseekable,
4183 wasi.ENOTCAPABLE => return error.AccessDenied,4181 .NOTCAPABLE => return error.AccessDenied,
4184 else => |err| return unexpectedErrno(err),4182 else => |err| return unexpectedErrno(err),
4185 }4183 }
4186 }4184 }
...@@ -4191,12 +4189,12 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {...@@ -4191,12 +4189,12 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
41914189
4192 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned4190 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned
4193 switch (errno(lseek_sym(fd, ioffset, SEEK_CUR))) {4191 switch (errno(lseek_sym(fd, ioffset, SEEK_CUR))) {
4194 0 => return,4192 .SUCCESS => return,
4195 EBADF => unreachable, // always a race condition4193 .BADF => unreachable, // always a race condition
4196 EINVAL => return error.Unseekable,4194 .INVAL => return error.Unseekable,
4197 EOVERFLOW => return error.Unseekable,4195 .OVERFLOW => return error.Unseekable,
4198 ESPIPE => return error.Unseekable,4196 .SPIPE => return error.Unseekable,
4199 ENXIO => return error.Unseekable,4197 .NXIO => return error.Unseekable,
4200 else => |err| return unexpectedErrno(err),4198 else => |err| return unexpectedErrno(err),
4201 }4199 }
4202}4200}
...@@ -4206,12 +4204,12 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {...@@ -4206,12 +4204,12 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
4206 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {4204 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
4207 var result: u64 = undefined;4205 var result: u64 = undefined;
4208 switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_END))) {4206 switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_END))) {
4209 0 => return,4207 .SUCCESS => return,
4210 EBADF => unreachable, // always a race condition4208 .BADF => unreachable, // always a race condition
4211 EINVAL => return error.Unseekable,4209 .INVAL => return error.Unseekable,
4212 EOVERFLOW => return error.Unseekable,4210 .OVERFLOW => return error.Unseekable,
4213 ESPIPE => return error.Unseekable,4211 .SPIPE => return error.Unseekable,
4214 ENXIO => return error.Unseekable,4212 .NXIO => return error.Unseekable,
4215 else => |err| return unexpectedErrno(err),4213 else => |err| return unexpectedErrno(err),
4216 }4214 }
4217 }4215 }
...@@ -4221,13 +4219,13 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {...@@ -4221,13 +4219,13 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
4221 if (builtin.os.tag == .wasi and !builtin.link_libc) {4219 if (builtin.os.tag == .wasi and !builtin.link_libc) {
4222 var new_offset: wasi.filesize_t = undefined;4220 var new_offset: wasi.filesize_t = undefined;
4223 switch (wasi.fd_seek(fd, offset, wasi.WHENCE_END, &new_offset)) {4221 switch (wasi.fd_seek(fd, offset, wasi.WHENCE_END, &new_offset)) {
4224 wasi.ESUCCESS => return,4222 .SUCCESS => return,
4225 wasi.EBADF => unreachable, // always a race condition4223 .BADF => unreachable, // always a race condition
4226 wasi.EINVAL => return error.Unseekable,4224 .INVAL => return error.Unseekable,
4227 wasi.EOVERFLOW => return error.Unseekable,4225 .OVERFLOW => return error.Unseekable,
4228 wasi.ESPIPE => return error.Unseekable,4226 .SPIPE => return error.Unseekable,
4229 wasi.ENXIO => return error.Unseekable,4227 .NXIO => return error.Unseekable,
4230 wasi.ENOTCAPABLE => return error.AccessDenied,4228 .NOTCAPABLE => return error.AccessDenied,
4231 else => |err| return unexpectedErrno(err),4229 else => |err| return unexpectedErrno(err),
4232 }4230 }
4233 }4231 }
...@@ -4238,12 +4236,12 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {...@@ -4238,12 +4236,12 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
42384236
4239 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned4237 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned
4240 switch (errno(lseek_sym(fd, ioffset, SEEK_END))) {4238 switch (errno(lseek_sym(fd, ioffset, SEEK_END))) {
4241 0 => return,4239 .SUCCESS => return,
4242 EBADF => unreachable, // always a race condition4240 .BADF => unreachable, // always a race condition
4243 EINVAL => return error.Unseekable,4241 .INVAL => return error.Unseekable,
4244 EOVERFLOW => return error.Unseekable,4242 .OVERFLOW => return error.Unseekable,
4245 ESPIPE => return error.Unseekable,4243 .SPIPE => return error.Unseekable,
4246 ENXIO => return error.Unseekable,4244 .NXIO => return error.Unseekable,
4247 else => |err| return unexpectedErrno(err),4245 else => |err| return unexpectedErrno(err),
4248 }4246 }
4249}4247}
...@@ -4253,12 +4251,12 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {...@@ -4253,12 +4251,12 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {
4253 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {4251 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
4254 var result: u64 = undefined;4252 var result: u64 = undefined;
4255 switch (errno(system.llseek(fd, 0, &result, SEEK_CUR))) {4253 switch (errno(system.llseek(fd, 0, &result, SEEK_CUR))) {
4256 0 => return result,4254 .SUCCESS => return result,
4257 EBADF => unreachable, // always a race condition4255 .BADF => unreachable, // always a race condition
4258 EINVAL => return error.Unseekable,4256 .INVAL => return error.Unseekable,
4259 EOVERFLOW => return error.Unseekable,4257 .OVERFLOW => return error.Unseekable,
4260 ESPIPE => return error.Unseekable,4258 .SPIPE => return error.Unseekable,
4261 ENXIO => return error.Unseekable,4259 .NXIO => return error.Unseekable,
4262 else => |err| return unexpectedErrno(err),4260 else => |err| return unexpectedErrno(err),
4263 }4261 }
4264 }4262 }
...@@ -4268,13 +4266,13 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {...@@ -4268,13 +4266,13 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {
4268 if (builtin.os.tag == .wasi and !builtin.link_libc) {4266 if (builtin.os.tag == .wasi and !builtin.link_libc) {
4269 var new_offset: wasi.filesize_t = undefined;4267 var new_offset: wasi.filesize_t = undefined;
4270 switch (wasi.fd_seek(fd, 0, wasi.WHENCE_CUR, &new_offset)) {4268 switch (wasi.fd_seek(fd, 0, wasi.WHENCE_CUR, &new_offset)) {
4271 wasi.ESUCCESS => return new_offset,4269 .SUCCESS => return new_offset,
4272 wasi.EBADF => unreachable, // always a race condition4270 .BADF => unreachable, // always a race condition
4273 wasi.EINVAL => return error.Unseekable,4271 .INVAL => return error.Unseekable,
4274 wasi.EOVERFLOW => return error.Unseekable,4272 .OVERFLOW => return error.Unseekable,
4275 wasi.ESPIPE => return error.Unseekable,4273 .SPIPE => return error.Unseekable,
4276 wasi.ENXIO => return error.Unseekable,4274 .NXIO => return error.Unseekable,
4277 wasi.ENOTCAPABLE => return error.AccessDenied,4275 .NOTCAPABLE => return error.AccessDenied,
4278 else => |err| return unexpectedErrno(err),4276 else => |err| return unexpectedErrno(err),
4279 }4277 }
4280 }4278 }
...@@ -4285,12 +4283,12 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {...@@ -4285,12 +4283,12 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {
42854283
4286 const rc = lseek_sym(fd, 0, SEEK_CUR);4284 const rc = lseek_sym(fd, 0, SEEK_CUR);
4287 switch (errno(rc)) {4285 switch (errno(rc)) {
4288 0 => return @bitCast(u64, rc),4286 .SUCCESS => return @bitCast(u64, rc),
4289 EBADF => unreachable, // always a race condition4287 .BADF => unreachable, // always a race condition
4290 EINVAL => return error.Unseekable,4288 .INVAL => return error.Unseekable,
4291 EOVERFLOW => return error.Unseekable,4289 .OVERFLOW => return error.Unseekable,
4292 ESPIPE => return error.Unseekable,4290 .SPIPE => return error.Unseekable,
4293 ENXIO => return error.Unseekable,4291 .NXIO => return error.Unseekable,
4294 else => |err| return unexpectedErrno(err),4292 else => |err| return unexpectedErrno(err),
4295 }4293 }
4296}4294}
...@@ -4306,15 +4304,15 @@ pub fn fcntl(fd: fd_t, cmd: i32, arg: usize) FcntlError!usize {...@@ -4306,15 +4304,15 @@ pub fn fcntl(fd: fd_t, cmd: i32, arg: usize) FcntlError!usize {
4306 while (true) {4304 while (true) {
4307 const rc = system.fcntl(fd, cmd, arg);4305 const rc = system.fcntl(fd, cmd, arg);
4308 switch (errno(rc)) {4306 switch (errno(rc)) {
4309 0 => return @intCast(usize, rc),4307 .SUCCESS => return @intCast(usize, rc),
4310 EINTR => continue,4308 .INTR => continue,
4311 EACCES => return error.Locked,4309 .ACCES => return error.Locked,
4312 EBADF => unreachable,4310 .BADF => unreachable,
4313 EBUSY => return error.FileBusy,4311 .BUSY => return error.FileBusy,
4314 EINVAL => unreachable, // invalid parameters4312 .INVAL => unreachable, // invalid parameters
4315 EPERM => return error.PermissionDenied,4313 .PERM => return error.PermissionDenied,
4316 EMFILE => return error.ProcessFdQuotaExceeded,4314 .MFILE => return error.ProcessFdQuotaExceeded,
4317 ENOTDIR => unreachable, // invalid parameter4315 .NOTDIR => unreachable, // invalid parameter
4318 else => |err| return unexpectedErrno(err),4316 else => |err| return unexpectedErrno(err),
4319 }4317 }
4320 }4318 }
...@@ -4381,12 +4379,12 @@ pub fn flock(fd: fd_t, operation: i32) FlockError!void {...@@ -4381,12 +4379,12 @@ pub fn flock(fd: fd_t, operation: i32) FlockError!void {
4381 while (true) {4379 while (true) {
4382 const rc = system.flock(fd, operation);4380 const rc = system.flock(fd, operation);
4383 switch (errno(rc)) {4381 switch (errno(rc)) {
4384 0 => return,4382 .SUCCESS => return,
4385 EBADF => unreachable,4383 .BADF => unreachable,
4386 EINTR => continue,4384 .INTR => continue,
4387 EINVAL => unreachable, // invalid parameters4385 .INVAL => unreachable, // invalid parameters
4388 ENOLCK => return error.SystemResources,4386 .NOLCK => return error.SystemResources,
4389 EWOULDBLOCK => return error.WouldBlock, // TODO: integrate with async instead of just returning an error4387 .AGAIN => return error.WouldBlock, // TODO: integrate with async instead of just returning an error
4390 else => |err| return unexpectedErrno(err),4388 else => |err| return unexpectedErrno(err),
4391 }4389 }
4392 }4390 }
...@@ -4456,17 +4454,18 @@ pub fn realpathZ(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealP...@@ -4456,17 +4454,18 @@ pub fn realpathZ(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealP
44564454
4457 return getFdPath(fd, out_buffer);4455 return getFdPath(fd, out_buffer);
4458 }4456 }
4459 const result_path = std.c.realpath(pathname, out_buffer) orelse switch (std.c._errno().*) {4457 const result_path = std.c.realpath(pathname, out_buffer) orelse switch (@intToEnum(E, std.c._errno().*)) {
4460 EINVAL => unreachable,4458 .SUCCESS => unreachable,
4461 EBADF => unreachable,4459 .INVAL => unreachable,
4462 EFAULT => unreachable,4460 .BADF => unreachable,
4463 EACCES => return error.AccessDenied,4461 .FAULT => unreachable,
4464 ENOENT => return error.FileNotFound,4462 .ACCES => return error.AccessDenied,
4465 ENOTSUP => return error.NotSupported,4463 .NOENT => return error.FileNotFound,
4466 ENOTDIR => return error.NotDir,4464 .OPNOTSUPP => return error.NotSupported,
4467 ENAMETOOLONG => return error.NameTooLong,4465 .NOTDIR => return error.NotDir,
4468 ELOOP => return error.SymLinkLoop,4466 .NAMETOOLONG => return error.NameTooLong,
4469 EIO => return error.InputOutput,4467 .LOOP => return error.SymLinkLoop,
4468 .IO => return error.InputOutput,
4470 else => |err| return unexpectedErrno(err),4469 else => |err| return unexpectedErrno(err),
4471 };4470 };
4472 return mem.spanZ(result_path);4471 return mem.spanZ(result_path);
...@@ -4528,8 +4527,8 @@ pub fn getFdPath(fd: fd_t, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {...@@ -4528,8 +4527,8 @@ pub fn getFdPath(fd: fd_t, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
4528 // the path to the file descriptor.4527 // the path to the file descriptor.
4529 @memset(out_buffer, 0, MAX_PATH_BYTES);4528 @memset(out_buffer, 0, MAX_PATH_BYTES);
4530 switch (errno(system.fcntl(fd, F_GETPATH, out_buffer))) {4529 switch (errno(system.fcntl(fd, F_GETPATH, out_buffer))) {
4531 0 => {},4530 .SUCCESS => {},
4532 EBADF => return error.FileNotFound,4531 .BADF => return error.FileNotFound,
4533 // TODO man pages for fcntl on macOS don't really tell you what4532 // TODO man pages for fcntl on macOS don't really tell you what
4534 // errno values to expect when command is F_GETPATH...4533 // errno values to expect when command is F_GETPATH...
4535 else => |err| return unexpectedErrno(err),4534 else => |err| return unexpectedErrno(err),
...@@ -4562,13 +4561,13 @@ pub fn nanosleep(seconds: u64, nanoseconds: u64) void {...@@ -4562,13 +4561,13 @@ pub fn nanosleep(seconds: u64, nanoseconds: u64) void {
4562 var rem: timespec = undefined;4561 var rem: timespec = undefined;
4563 while (true) {4562 while (true) {
4564 switch (errno(system.nanosleep(&req, &rem))) {4563 switch (errno(system.nanosleep(&req, &rem))) {
4565 EFAULT => unreachable,4564 .FAULT => unreachable,
4566 EINVAL => {4565 .INVAL => {
4567 // Sometimes Darwin returns EINVAL for no reason.4566 // Sometimes Darwin returns EINVAL for no reason.
4568 // We treat it as a spurious wakeup.4567 // We treat it as a spurious wakeup.
4569 return;4568 return;
4570 },4569 },
4571 EINTR => {4570 .INTR => {
4572 req = rem;4571 req = rem;
4573 continue;4572 continue;
4574 },4573 },
...@@ -4668,13 +4667,13 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {...@@ -4668,13 +4667,13 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {
4668 if (std.Target.current.os.tag == .wasi and !builtin.link_libc) {4667 if (std.Target.current.os.tag == .wasi and !builtin.link_libc) {
4669 var ts: timestamp_t = undefined;4668 var ts: timestamp_t = undefined;
4670 switch (system.clock_time_get(@bitCast(u32, clk_id), 1, &ts)) {4669 switch (system.clock_time_get(@bitCast(u32, clk_id), 1, &ts)) {
4671 0 => {4670 .SUCCESS => {
4672 tp.* = .{4671 tp.* = .{
4673 .tv_sec = @intCast(i64, ts / std.time.ns_per_s),4672 .tv_sec = @intCast(i64, ts / std.time.ns_per_s),
4674 .tv_nsec = @intCast(isize, ts % std.time.ns_per_s),4673 .tv_nsec = @intCast(isize, ts % std.time.ns_per_s),
4675 };4674 };
4676 },4675 },
4677 EINVAL => return error.UnsupportedClock,4676 .INVAL => return error.UnsupportedClock,
4678 else => |err| return unexpectedErrno(err),4677 else => |err| return unexpectedErrno(err),
4679 }4678 }
4680 return;4679 return;
...@@ -4698,9 +4697,9 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {...@@ -4698,9 +4697,9 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {
4698 }4697 }
46994698
4700 switch (errno(system.clock_gettime(clk_id, tp))) {4699 switch (errno(system.clock_gettime(clk_id, tp))) {
4701 0 => return,4700 .SUCCESS => return,
4702 EFAULT => unreachable,4701 .FAULT => unreachable,
4703 EINVAL => return error.UnsupportedClock,4702 .INVAL => return error.UnsupportedClock,
4704 else => |err| return unexpectedErrno(err),4703 else => |err| return unexpectedErrno(err),
4705 }4704 }
4706}4705}
...@@ -4709,20 +4708,20 @@ pub fn clock_getres(clk_id: i32, res: *timespec) ClockGetTimeError!void {...@@ -4709,20 +4708,20 @@ pub fn clock_getres(clk_id: i32, res: *timespec) ClockGetTimeError!void {
4709 if (std.Target.current.os.tag == .wasi and !builtin.link_libc) {4708 if (std.Target.current.os.tag == .wasi and !builtin.link_libc) {
4710 var ts: timestamp_t = undefined;4709 var ts: timestamp_t = undefined;
4711 switch (system.clock_res_get(@bitCast(u32, clk_id), &ts)) {4710 switch (system.clock_res_get(@bitCast(u32, clk_id), &ts)) {
4712 0 => res.* = .{4711 .SUCCESS => res.* = .{
4713 .tv_sec = @intCast(i64, ts / std.time.ns_per_s),4712 .tv_sec = @intCast(i64, ts / std.time.ns_per_s),
4714 .tv_nsec = @intCast(isize, ts % std.time.ns_per_s),4713 .tv_nsec = @intCast(isize, ts % std.time.ns_per_s),
4715 },4714 },
4716 EINVAL => return error.UnsupportedClock,4715 .INVAL => return error.UnsupportedClock,
4717 else => |err| return unexpectedErrno(err),4716 else => |err| return unexpectedErrno(err),
4718 }4717 }
4719 return;4718 return;
4720 }4719 }
47214720
4722 switch (errno(system.clock_getres(clk_id, res))) {4721 switch (errno(system.clock_getres(clk_id, res))) {
4723 0 => return,4722 .SUCCESS => return,
4724 EFAULT => unreachable,4723 .FAULT => unreachable,
4725 EINVAL => return error.UnsupportedClock,4724 .INVAL => return error.UnsupportedClock,
4726 else => |err| return unexpectedErrno(err),4725 else => |err| return unexpectedErrno(err),
4727 }4726 }
4728}4727}
...@@ -4732,11 +4731,11 @@ pub const SchedGetAffinityError = error{PermissionDenied} || UnexpectedError;...@@ -4732,11 +4731,11 @@ pub const SchedGetAffinityError = error{PermissionDenied} || UnexpectedError;
4732pub fn sched_getaffinity(pid: pid_t) SchedGetAffinityError!cpu_set_t {4731pub fn sched_getaffinity(pid: pid_t) SchedGetAffinityError!cpu_set_t {
4733 var set: cpu_set_t = undefined;4732 var set: cpu_set_t = undefined;
4734 switch (errno(system.sched_getaffinity(pid, @sizeOf(cpu_set_t), &set))) {4733 switch (errno(system.sched_getaffinity(pid, @sizeOf(cpu_set_t), &set))) {
4735 0 => return set,4734 .SUCCESS => return set,
4736 EFAULT => unreachable,4735 .FAULT => unreachable,
4737 EINVAL => unreachable,4736 .INVAL => unreachable,
4738 ESRCH => unreachable,4737 .SRCH => unreachable,
4739 EPERM => return error.PermissionDenied,4738 .PERM => return error.PermissionDenied,
4740 else => |err| return unexpectedErrno(err),4739 else => |err| return unexpectedErrno(err),
4741 }4740 }
4742}4741}
...@@ -4768,13 +4767,9 @@ pub const UnexpectedError = error{...@@ -4768,13 +4767,9 @@ pub const UnexpectedError = error{
47684767
4769/// Call this when you made a syscall or something that sets errno4768/// Call this when you made a syscall or something that sets errno
4770/// and you get an unexpected error.4769/// and you get an unexpected error.
4771pub fn unexpectedErrno(err: anytype) UnexpectedError {4770pub fn unexpectedErrno(err: E) UnexpectedError {
4772 if (@typeInfo(@TypeOf(err)) != .Int) {
4773 @compileError("err is expected to be an integer");
4774 }
4775
4776 if (unexpected_error_tracing) {4771 if (unexpected_error_tracing) {
4777 std.debug.warn("unexpected errno: {d}\n", .{err});4772 std.debug.warn("unexpected errno: {d}\n", .{@enumToInt(err)});
4778 std.debug.dumpCurrentStackTrace(null);4773 std.debug.dumpCurrentStackTrace(null);
4779 }4774 }
4780 return error.Unexpected;4775 return error.Unexpected;
...@@ -4790,11 +4785,11 @@ pub const SigaltstackError = error{...@@ -4790,11 +4785,11 @@ pub const SigaltstackError = error{
47904785
4791pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {4786pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {
4792 switch (errno(system.sigaltstack(ss, old_ss))) {4787 switch (errno(system.sigaltstack(ss, old_ss))) {
4793 0 => return,4788 .SUCCESS => return,
4794 EFAULT => unreachable,4789 .FAULT => unreachable,
4795 EINVAL => unreachable,4790 .INVAL => unreachable,
4796 ENOMEM => return error.SizeTooSmall,4791 .NOMEM => return error.SizeTooSmall,
4797 EPERM => return error.PermissionDenied,4792 .PERM => return error.PermissionDenied,
4798 else => |err| return unexpectedErrno(err),4793 else => |err| return unexpectedErrno(err),
4799 }4794 }
4800}4795}
...@@ -4802,9 +4797,9 @@ pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {...@@ -4802,9 +4797,9 @@ pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {
4802/// Examine and change a signal action.4797/// Examine and change a signal action.
4803pub fn sigaction(sig: u6, act: ?*const Sigaction, oact: ?*Sigaction) void {4798pub fn sigaction(sig: u6, act: ?*const Sigaction, oact: ?*Sigaction) void {
4804 switch (errno(system.sigaction(sig, act, oact))) {4799 switch (errno(system.sigaction(sig, act, oact))) {
4805 0 => return,4800 .SUCCESS => return,
4806 EFAULT => unreachable,4801 .FAULT => unreachable,
4807 EINVAL => unreachable,4802 .INVAL => unreachable,
4808 else => unreachable,4803 else => unreachable,
4809 }4804 }
4810}4805}
...@@ -4841,25 +4836,25 @@ pub fn futimens(fd: fd_t, times: *const [2]timespec) FutimensError!void {...@@ -4841,25 +4836,25 @@ pub fn futimens(fd: fd_t, times: *const [2]timespec) FutimensError!void {
4841 const atim = times[0].toTimestamp();4836 const atim = times[0].toTimestamp();
4842 const mtim = times[1].toTimestamp();4837 const mtim = times[1].toTimestamp();
4843 switch (wasi.fd_filestat_set_times(fd, atim, mtim, wasi.FILESTAT_SET_ATIM | wasi.FILESTAT_SET_MTIM)) {4838 switch (wasi.fd_filestat_set_times(fd, atim, mtim, wasi.FILESTAT_SET_ATIM | wasi.FILESTAT_SET_MTIM)) {
4844 wasi.ESUCCESS => return,4839 .SUCCESS => return,
4845 wasi.EACCES => return error.AccessDenied,4840 .ACCES => return error.AccessDenied,
4846 wasi.EPERM => return error.PermissionDenied,4841 .PERM => return error.PermissionDenied,
4847 wasi.EBADF => unreachable, // always a race condition4842 .BADF => unreachable, // always a race condition
4848 wasi.EFAULT => unreachable,4843 .FAULT => unreachable,
4849 wasi.EINVAL => unreachable,4844 .INVAL => unreachable,
4850 wasi.EROFS => return error.ReadOnlyFileSystem,4845 .ROFS => return error.ReadOnlyFileSystem,
4851 else => |err| return unexpectedErrno(err),4846 else => |err| return unexpectedErrno(err),
4852 }4847 }
4853 }4848 }
48544849
4855 switch (errno(system.futimens(fd, times))) {4850 switch (errno(system.futimens(fd, times))) {
4856 0 => return,4851 .SUCCESS => return,
4857 EACCES => return error.AccessDenied,4852 .ACCES => return error.AccessDenied,
4858 EPERM => return error.PermissionDenied,4853 .PERM => return error.PermissionDenied,
4859 EBADF => unreachable, // always a race condition4854 .BADF => unreachable, // always a race condition
4860 EFAULT => unreachable,4855 .FAULT => unreachable,
4861 EINVAL => unreachable,4856 .INVAL => unreachable,
4862 EROFS => return error.ReadOnlyFileSystem,4857 .ROFS => return error.ReadOnlyFileSystem,
4863 else => |err| return unexpectedErrno(err),4858 else => |err| return unexpectedErrno(err),
4864 }4859 }
4865}4860}
...@@ -4869,10 +4864,10 @@ pub const GetHostNameError = error{PermissionDenied} || UnexpectedError;...@@ -4869,10 +4864,10 @@ pub const GetHostNameError = error{PermissionDenied} || UnexpectedError;
4869pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {4864pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {
4870 if (builtin.link_libc) {4865 if (builtin.link_libc) {
4871 switch (errno(system.gethostname(name_buffer, name_buffer.len))) {4866 switch (errno(system.gethostname(name_buffer, name_buffer.len))) {
4872 0 => return mem.spanZ(std.meta.assumeSentinel(name_buffer, 0)),4867 .SUCCESS => return mem.spanZ(std.meta.assumeSentinel(name_buffer, 0)),
4873 EFAULT => unreachable,4868 .FAULT => unreachable,
4874 ENAMETOOLONG => unreachable, // HOST_NAME_MAX prevents this4869 .NAMETOOLONG => unreachable, // HOST_NAME_MAX prevents this
4875 EPERM => return error.PermissionDenied,4870 .PERM => return error.PermissionDenied,
4876 else => |err| return unexpectedErrno(err),4871 else => |err| return unexpectedErrno(err),
4877 }4872 }
4878 }4873 }
...@@ -4889,8 +4884,8 @@ pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {...@@ -4889,8 +4884,8 @@ pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {
4889pub fn uname() utsname {4884pub fn uname() utsname {
4890 var uts: utsname = undefined;4885 var uts: utsname = undefined;
4891 switch (errno(system.uname(&uts))) {4886 switch (errno(system.uname(&uts))) {
4892 0 => return uts,4887 .SUCCESS => return uts,
4893 EFAULT => unreachable,4888 .FAULT => unreachable,
4894 else => unreachable,4889 else => unreachable,
4895 }4890 }
4896}4891}
...@@ -5049,33 +5044,33 @@ pub fn sendmsg(...@@ -5049,33 +5044,33 @@ pub fn sendmsg(
5049 }5044 }
5050 } else {5045 } else {
5051 switch (errno(rc)) {5046 switch (errno(rc)) {
5052 0 => return @intCast(usize, rc),5047 .SUCCESS => return @intCast(usize, rc),
50535048
5054 EACCES => return error.AccessDenied,5049 .ACCES => return error.AccessDenied,
5055 EAGAIN => return error.WouldBlock,5050 .AGAIN => return error.WouldBlock,
5056 EALREADY => return error.FastOpenAlreadyInProgress,5051 .ALREADY => return error.FastOpenAlreadyInProgress,
5057 EBADF => unreachable, // always a race condition5052 .BADF => unreachable, // always a race condition
5058 ECONNRESET => return error.ConnectionResetByPeer,5053 .CONNRESET => return error.ConnectionResetByPeer,
5059 EDESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set.5054 .DESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set.
5060 EFAULT => unreachable, // An invalid user space address was specified for an argument.5055 .FAULT => unreachable, // An invalid user space address was specified for an argument.
5061 EINTR => continue,5056 .INTR => continue,
5062 EINVAL => unreachable, // Invalid argument passed.5057 .INVAL => unreachable, // Invalid argument passed.
5063 EISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified5058 .ISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified
5064 EMSGSIZE => return error.MessageTooBig,5059 .MSGSIZE => return error.MessageTooBig,
5065 ENOBUFS => return error.SystemResources,5060 .NOBUFS => return error.SystemResources,
5066 ENOMEM => return error.SystemResources,5061 .NOMEM => return error.SystemResources,
5067 ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.5062 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
5068 EOPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type.5063 .OPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type.
5069 EPIPE => return error.BrokenPipe,5064 .PIPE => return error.BrokenPipe,
5070 EAFNOSUPPORT => return error.AddressFamilyNotSupported,5065 .AFNOSUPPORT => return error.AddressFamilyNotSupported,
5071 ELOOP => return error.SymLinkLoop,5066 .LOOP => return error.SymLinkLoop,
5072 ENAMETOOLONG => return error.NameTooLong,5067 .NAMETOOLONG => return error.NameTooLong,
5073 ENOENT => return error.FileNotFound,5068 .NOENT => return error.FileNotFound,
5074 ENOTDIR => return error.NotDir,5069 .NOTDIR => return error.NotDir,
5075 EHOSTUNREACH => return error.NetworkUnreachable,5070 .HOSTUNREACH => return error.NetworkUnreachable,
5076 ENETUNREACH => return error.NetworkUnreachable,5071 .NETUNREACH => return error.NetworkUnreachable,
5077 ENOTCONN => return error.SocketNotConnected,5072 .NOTCONN => return error.SocketNotConnected,
5078 ENETDOWN => return error.NetworkSubsystemFailed,5073 .NETDOWN => return error.NetworkSubsystemFailed,
5079 else => |err| return unexpectedErrno(err),5074 else => |err| return unexpectedErrno(err),
5080 }5075 }
5081 }5076 }
...@@ -5149,33 +5144,33 @@ pub fn sendto(...@@ -5149,33 +5144,33 @@ pub fn sendto(
5149 }5144 }
5150 } else {5145 } else {
5151 switch (errno(rc)) {5146 switch (errno(rc)) {
5152 0 => return @intCast(usize, rc),5147 .SUCCESS => return @intCast(usize, rc),
51535148
5154 EACCES => return error.AccessDenied,5149 .ACCES => return error.AccessDenied,
5155 EAGAIN => return error.WouldBlock,5150 .AGAIN => return error.WouldBlock,
5156 EALREADY => return error.FastOpenAlreadyInProgress,5151 .ALREADY => return error.FastOpenAlreadyInProgress,
5157 EBADF => unreachable, // always a race condition5152 .BADF => unreachable, // always a race condition
5158 ECONNRESET => return error.ConnectionResetByPeer,5153 .CONNRESET => return error.ConnectionResetByPeer,
5159 EDESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set.5154 .DESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set.
5160 EFAULT => unreachable, // An invalid user space address was specified for an argument.5155 .FAULT => unreachable, // An invalid user space address was specified for an argument.
5161 EINTR => continue,5156 .INTR => continue,
5162 EINVAL => unreachable, // Invalid argument passed.5157 .INVAL => unreachable, // Invalid argument passed.
5163 EISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified5158 .ISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified
5164 EMSGSIZE => return error.MessageTooBig,5159 .MSGSIZE => return error.MessageTooBig,
5165 ENOBUFS => return error.SystemResources,5160 .NOBUFS => return error.SystemResources,
5166 ENOMEM => return error.SystemResources,5161 .NOMEM => return error.SystemResources,
5167 ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.5162 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
5168 EOPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type.5163 .OPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type.
5169 EPIPE => return error.BrokenPipe,5164 .PIPE => return error.BrokenPipe,
5170 EAFNOSUPPORT => return error.AddressFamilyNotSupported,5165 .AFNOSUPPORT => return error.AddressFamilyNotSupported,
5171 ELOOP => return error.SymLinkLoop,5166 .LOOP => return error.SymLinkLoop,
5172 ENAMETOOLONG => return error.NameTooLong,5167 .NAMETOOLONG => return error.NameTooLong,
5173 ENOENT => return error.FileNotFound,5168 .NOENT => return error.FileNotFound,
5174 ENOTDIR => return error.NotDir,5169 .NOTDIR => return error.NotDir,
5175 EHOSTUNREACH => return error.NetworkUnreachable,5170 .HOSTUNREACH => return error.NetworkUnreachable,
5176 ENETUNREACH => return error.NetworkUnreachable,5171 .NETUNREACH => return error.NetworkUnreachable,
5177 ENOTCONN => return error.SocketNotConnected,5172 .NOTCONN => return error.SocketNotConnected,
5178 ENETDOWN => return error.NetworkSubsystemFailed,5173 .NETDOWN => return error.NetworkSubsystemFailed,
5179 else => |err| return unexpectedErrno(err),5174 else => |err| return unexpectedErrno(err),
5180 }5175 }
5181 }5176 }
...@@ -5312,7 +5307,7 @@ pub fn sendfile(...@@ -5312,7 +5307,7 @@ pub fn sendfile(
5312 var offset: off_t = @bitCast(off_t, in_offset);5307 var offset: off_t = @bitCast(off_t, in_offset);
5313 const rc = sendfile_sym(out_fd, in_fd, &offset, adjusted_count);5308 const rc = sendfile_sym(out_fd, in_fd, &offset, adjusted_count);
5314 switch (errno(rc)) {5309 switch (errno(rc)) {
5315 0 => {5310 .SUCCESS => {
5316 const amt = @bitCast(usize, rc);5311 const amt = @bitCast(usize, rc);
5317 total_written += amt;5312 total_written += amt;
5318 if (in_len == 0 and amt == 0) {5313 if (in_len == 0 and amt == 0) {
...@@ -5325,12 +5320,12 @@ pub fn sendfile(...@@ -5325,12 +5320,12 @@ pub fn sendfile(
5325 }5320 }
5326 },5321 },
53275322
5328 EBADF => unreachable, // Always a race condition.5323 .BADF => unreachable, // Always a race condition.
5329 EFAULT => unreachable, // Segmentation fault.5324 .FAULT => unreachable, // Segmentation fault.
5330 EOVERFLOW => unreachable, // We avoid passing too large of a `count`.5325 .OVERFLOW => unreachable, // We avoid passing too large of a `count`.
5331 ENOTCONN => unreachable, // `out_fd` is an unconnected socket.5326 .NOTCONN => unreachable, // `out_fd` is an unconnected socket.
53325327
5333 EINVAL, ENOSYS => {5328 .INVAL, .NOSYS => {
5334 // EINVAL could be any of the following situations:5329 // EINVAL could be any of the following situations:
5335 // * Descriptor is not valid or locked5330 // * Descriptor is not valid or locked
5336 // * an mmap(2)-like operation is not available for in_fd5331 // * an mmap(2)-like operation is not available for in_fd
...@@ -5340,17 +5335,17 @@ pub fn sendfile(...@@ -5340,17 +5335,17 @@ pub fn sendfile(
5340 // manually, the same as ENOSYS.5335 // manually, the same as ENOSYS.
5341 break :sf;5336 break :sf;
5342 },5337 },
5343 EAGAIN => if (std.event.Loop.instance) |loop| {5338 .AGAIN => if (std.event.Loop.instance) |loop| {
5344 loop.waitUntilFdWritable(out_fd);5339 loop.waitUntilFdWritable(out_fd);
5345 continue;5340 continue;
5346 } else {5341 } else {
5347 return error.WouldBlock;5342 return error.WouldBlock;
5348 },5343 },
5349 EIO => return error.InputOutput,5344 .IO => return error.InputOutput,
5350 EPIPE => return error.BrokenPipe,5345 .PIPE => return error.BrokenPipe,
5351 ENOMEM => return error.SystemResources,5346 .NOMEM => return error.SystemResources,
5352 ENXIO => return error.Unseekable,5347 .NXIO => return error.Unseekable,
5353 ESPIPE => return error.Unseekable,5348 .SPIPE => return error.Unseekable,
5354 else => |err| {5349 else => |err| {
5355 unexpectedErrno(err) catch {};5350 unexpectedErrno(err) catch {};
5356 break :sf;5351 break :sf;
...@@ -5392,13 +5387,13 @@ pub fn sendfile(...@@ -5392,13 +5387,13 @@ pub fn sendfile(
5392 const err = errno(system.sendfile(in_fd, out_fd, offset, adjusted_count, hdtr, &sbytes, flags));5387 const err = errno(system.sendfile(in_fd, out_fd, offset, adjusted_count, hdtr, &sbytes, flags));
5393 const amt = @bitCast(usize, sbytes);5388 const amt = @bitCast(usize, sbytes);
5394 switch (err) {5389 switch (err) {
5395 0 => return amt,5390 .SUCCESS => return amt,
53965391
5397 EBADF => unreachable, // Always a race condition.5392 .BADF => unreachable, // Always a race condition.
5398 EFAULT => unreachable, // Segmentation fault.5393 .FAULT => unreachable, // Segmentation fault.
5399 ENOTCONN => unreachable, // `out_fd` is an unconnected socket.5394 .NOTCONN => unreachable, // `out_fd` is an unconnected socket.
54005395
5401 EINVAL, EOPNOTSUPP, ENOTSOCK, ENOSYS => {5396 .INVAL, .OPNOTSUPP, .NOTSOCK, .NOSYS => {
5402 // EINVAL could be any of the following situations:5397 // EINVAL could be any of the following situations:
5403 // * The fd argument is not a regular file.5398 // * The fd argument is not a regular file.
5404 // * The s argument is not a SOCK_STREAM type socket.5399 // * The s argument is not a SOCK_STREAM type socket.
...@@ -5408,9 +5403,9 @@ pub fn sendfile(...@@ -5408,9 +5403,9 @@ pub fn sendfile(
5408 break :sf;5403 break :sf;
5409 },5404 },
54105405
5411 EINTR => if (amt != 0) return amt else continue,5406 .INTR => if (amt != 0) return amt else continue,
54125407
5413 EAGAIN => if (amt != 0) {5408 .AGAIN => if (amt != 0) {
5414 return amt;5409 return amt;
5415 } else if (std.event.Loop.instance) |loop| {5410 } else if (std.event.Loop.instance) |loop| {
5416 loop.waitUntilFdWritable(out_fd);5411 loop.waitUntilFdWritable(out_fd);
...@@ -5419,7 +5414,7 @@ pub fn sendfile(...@@ -5419,7 +5414,7 @@ pub fn sendfile(
5419 return error.WouldBlock;5414 return error.WouldBlock;
5420 },5415 },
54215416
5422 EBUSY => if (amt != 0) {5417 .BUSY => if (amt != 0) {
5423 return amt;5418 return amt;
5424 } else if (std.event.Loop.instance) |loop| {5419 } else if (std.event.Loop.instance) |loop| {
5425 loop.waitUntilFdReadable(in_fd);5420 loop.waitUntilFdReadable(in_fd);
...@@ -5428,9 +5423,9 @@ pub fn sendfile(...@@ -5428,9 +5423,9 @@ pub fn sendfile(
5428 return error.WouldBlock;5423 return error.WouldBlock;
5429 },5424 },
54305425
5431 EIO => return error.InputOutput,5426 .IO => return error.InputOutput,
5432 ENOBUFS => return error.SystemResources,5427 .NOBUFS => return error.SystemResources,
5433 EPIPE => return error.BrokenPipe,5428 .PIPE => return error.BrokenPipe,
54345429
5435 else => {5430 else => {
5436 unexpectedErrno(err) catch {};5431 unexpectedErrno(err) catch {};
...@@ -5471,18 +5466,18 @@ pub fn sendfile(...@@ -5471,18 +5466,18 @@ pub fn sendfile(
5471 const err = errno(system.sendfile(in_fd, out_fd, signed_offset, &sbytes, hdtr, flags));5466 const err = errno(system.sendfile(in_fd, out_fd, signed_offset, &sbytes, hdtr, flags));
5472 const amt = @bitCast(usize, sbytes);5467 const amt = @bitCast(usize, sbytes);
5473 switch (err) {5468 switch (err) {
5474 0 => return amt,5469 .SUCCESS => return amt,
54755470
5476 EBADF => unreachable, // Always a race condition.5471 .BADF => unreachable, // Always a race condition.
5477 EFAULT => unreachable, // Segmentation fault.5472 .FAULT => unreachable, // Segmentation fault.
5478 EINVAL => unreachable,5473 .INVAL => unreachable,
5479 ENOTCONN => unreachable, // `out_fd` is an unconnected socket.5474 .NOTCONN => unreachable, // `out_fd` is an unconnected socket.
54805475
5481 ENOTSUP, ENOTSOCK, ENOSYS => break :sf,5476 .OPNOTSUPP, .NOTSOCK, .NOSYS => break :sf,
54825477
5483 EINTR => if (amt != 0) return amt else continue,5478 .INTR => if (amt != 0) return amt else continue,
54845479
5485 EAGAIN => if (amt != 0) {5480 .AGAIN => if (amt != 0) {
5486 return amt;5481 return amt;
5487 } else if (std.event.Loop.instance) |loop| {5482 } else if (std.event.Loop.instance) |loop| {
5488 loop.waitUntilFdWritable(out_fd);5483 loop.waitUntilFdWritable(out_fd);
...@@ -5491,8 +5486,8 @@ pub fn sendfile(...@@ -5491,8 +5486,8 @@ pub fn sendfile(
5491 return error.WouldBlock;5486 return error.WouldBlock;
5492 },5487 },
54935488
5494 EIO => return error.InputOutput,5489 .IO => return error.InputOutput,
5495 EPIPE => return error.BrokenPipe,5490 .PIPE => return error.BrokenPipe,
54965491
5497 else => {5492 else => {
5498 unexpectedErrno(err) catch {};5493 unexpectedErrno(err) catch {};
...@@ -5595,22 +5590,22 @@ pub fn copy_file_range(fd_in: fd_t, off_in: u64, fd_out: fd_t, off_out: u64, len...@@ -5595,22 +5590,22 @@ pub fn copy_file_range(fd_in: fd_t, off_in: u64, fd_out: fd_t, off_out: u64, len
55955590
5596 const rc = system.copy_file_range(fd_in, &off_in_copy, fd_out, &off_out_copy, len, flags);5591 const rc = system.copy_file_range(fd_in, &off_in_copy, fd_out, &off_out_copy, len, flags);
5597 switch (system.getErrno(rc)) {5592 switch (system.getErrno(rc)) {
5598 0 => return @intCast(usize, rc),5593 .SUCCESS => return @intCast(usize, rc),
5599 EBADF => return error.FilesOpenedWithWrongFlags,5594 .BADF => return error.FilesOpenedWithWrongFlags,
5600 EFBIG => return error.FileTooBig,5595 .FBIG => return error.FileTooBig,
5601 EIO => return error.InputOutput,5596 .IO => return error.InputOutput,
5602 EISDIR => return error.IsDir,5597 .ISDIR => return error.IsDir,
5603 ENOMEM => return error.OutOfMemory,5598 .NOMEM => return error.OutOfMemory,
5604 ENOSPC => return error.NoSpaceLeft,5599 .NOSPC => return error.NoSpaceLeft,
5605 EOVERFLOW => return error.Unseekable,5600 .OVERFLOW => return error.Unseekable,
5606 EPERM => return error.PermissionDenied,5601 .PERM => return error.PermissionDenied,
5607 ETXTBSY => return error.FileBusy,5602 .TXTBSY => return error.FileBusy,
5608 // these may not be regular files, try fallback5603 // these may not be regular files, try fallback
5609 EINVAL => {},5604 .INVAL => {},
5610 // support for cross-filesystem copy added in Linux 5.3, use fallback5605 // support for cross-filesystem copy added in Linux 5.3, use fallback
5611 EXDEV => {},5606 .XDEV => {},
5612 // syscall added in Linux 4.5, use fallback5607 // syscall added in Linux 4.5, use fallback
5613 ENOSYS => {5608 .NOSYS => {
5614 has_copy_file_range_syscall.store(false, .Monotonic);5609 has_copy_file_range_syscall.store(false, .Monotonic);
5615 },5610 },
5616 else => |err| return unexpectedErrno(err),5611 else => |err| return unexpectedErrno(err),
...@@ -5652,11 +5647,11 @@ pub fn poll(fds: []pollfd, timeout: i32) PollError!usize {...@@ -5652,11 +5647,11 @@ pub fn poll(fds: []pollfd, timeout: i32) PollError!usize {
5652 }5647 }
5653 } else {5648 } else {
5654 switch (errno(rc)) {5649 switch (errno(rc)) {
5655 0 => return @intCast(usize, rc),5650 .SUCCESS => return @intCast(usize, rc),
5656 EFAULT => unreachable,5651 .FAULT => unreachable,
5657 EINTR => continue,5652 .INTR => continue,
5658 EINVAL => unreachable,5653 .INVAL => unreachable,
5659 ENOMEM => return error.SystemResources,5654 .NOMEM => return error.SystemResources,
5660 else => |err| return unexpectedErrno(err),5655 else => |err| return unexpectedErrno(err),
5661 }5656 }
5662 }5657 }
...@@ -5681,11 +5676,11 @@ pub fn ppoll(fds: []pollfd, timeout: ?*const timespec, mask: ?*const sigset_t) P...@@ -5681,11 +5676,11 @@ pub fn ppoll(fds: []pollfd, timeout: ?*const timespec, mask: ?*const sigset_t) P
5681 }5676 }
5682 const rc = system.ppoll(fds.ptr, fds.len, ts_ptr, mask);5677 const rc = system.ppoll(fds.ptr, fds.len, ts_ptr, mask);
5683 switch (errno(rc)) {5678 switch (errno(rc)) {
5684 0 => return @intCast(usize, rc),5679 .SUCCESS => return @intCast(usize, rc),
5685 EFAULT => unreachable,5680 .FAULT => unreachable,
5686 EINTR => return error.SignalInterrupt,5681 .INTR => return error.SignalInterrupt,
5687 EINVAL => unreachable,5682 .INVAL => unreachable,
5688 ENOMEM => return error.SystemResources,5683 .NOMEM => return error.SystemResources,
5689 else => |err| return unexpectedErrno(err),5684 else => |err| return unexpectedErrno(err),
5690 }5685 }
5691}5686}
...@@ -5750,17 +5745,17 @@ pub fn recvfrom(...@@ -5750,17 +5745,17 @@ pub fn recvfrom(
5750 }5745 }
5751 } else {5746 } else {
5752 switch (errno(rc)) {5747 switch (errno(rc)) {
5753 0 => return @intCast(usize, rc),5748 .SUCCESS => return @intCast(usize, rc),
5754 EBADF => unreachable, // always a race condition5749 .BADF => unreachable, // always a race condition
5755 EFAULT => unreachable,5750 .FAULT => unreachable,
5756 EINVAL => unreachable,5751 .INVAL => unreachable,
5757 ENOTCONN => unreachable,5752 .NOTCONN => unreachable,
5758 ENOTSOCK => unreachable,5753 .NOTSOCK => unreachable,
5759 EINTR => continue,5754 .INTR => continue,
5760 EAGAIN => return error.WouldBlock,5755 .AGAIN => return error.WouldBlock,
5761 ENOMEM => return error.SystemResources,5756 .NOMEM => return error.SystemResources,
5762 ECONNREFUSED => return error.ConnectionRefused,5757 .CONNREFUSED => return error.ConnectionRefused,
5763 ECONNRESET => return error.ConnectionResetByPeer,5758 .CONNRESET => return error.ConnectionResetByPeer,
5764 else => |err| return unexpectedErrno(err),5759 else => |err| return unexpectedErrno(err),
5765 }5760 }
5766 }5761 }
...@@ -5830,8 +5825,8 @@ pub fn sched_yield() SchedYieldError!void {...@@ -5830,8 +5825,8 @@ pub fn sched_yield() SchedYieldError!void {
5830 return;5825 return;
5831 }5826 }
5832 switch (errno(system.sched_yield())) {5827 switch (errno(system.sched_yield())) {
5833 0 => return,5828 .SUCCESS => return,
5834 ENOSYS => return error.SystemCannotYield,5829 .NOSYS => return error.SystemCannotYield,
5835 else => return error.SystemCannotYield,5830 else => return error.SystemCannotYield,
5836 }5831 }
5837}5832}
...@@ -5874,17 +5869,17 @@ pub fn setsockopt(fd: socket_t, level: u32, optname: u32, opt: []const u8) SetSo...@@ -5874,17 +5869,17 @@ pub fn setsockopt(fd: socket_t, level: u32, optname: u32, opt: []const u8) SetSo
5874 return;5869 return;
5875 } else {5870 } else {
5876 switch (errno(system.setsockopt(fd, level, optname, opt.ptr, @intCast(socklen_t, opt.len)))) {5871 switch (errno(system.setsockopt(fd, level, optname, opt.ptr, @intCast(socklen_t, opt.len)))) {
5877 0 => {},5872 .SUCCESS => {},
5878 EBADF => unreachable, // always a race condition5873 .BADF => unreachable, // always a race condition
5879 ENOTSOCK => unreachable, // always a race condition5874 .NOTSOCK => unreachable, // always a race condition
5880 EINVAL => unreachable,5875 .INVAL => unreachable,
5881 EFAULT => unreachable,5876 .FAULT => unreachable,
5882 EDOM => return error.TimeoutTooBig,5877 .DOM => return error.TimeoutTooBig,
5883 EISCONN => return error.AlreadyConnected,5878 .ISCONN => return error.AlreadyConnected,
5884 ENOPROTOOPT => return error.InvalidProtocolOption,5879 .NOPROTOOPT => return error.InvalidProtocolOption,
5885 ENOMEM => return error.SystemResources,5880 .NOMEM => return error.SystemResources,
5886 ENOBUFS => return error.SystemResources,5881 .NOBUFS => return error.SystemResources,
5887 EPERM => return error.PermissionDenied,5882 .PERM => return error.PermissionDenied,
5888 else => |err| return unexpectedErrno(err),5883 else => |err| return unexpectedErrno(err),
5889 }5884 }
5890 }5885 }
...@@ -5909,13 +5904,13 @@ pub fn memfd_createZ(name: [*:0]const u8, flags: u32) MemFdCreateError!fd_t {...@@ -5909,13 +5904,13 @@ pub fn memfd_createZ(name: [*:0]const u8, flags: u32) MemFdCreateError!fd_t {
5909 const getErrno = if (use_c) std.c.getErrno else linux.getErrno;5904 const getErrno = if (use_c) std.c.getErrno else linux.getErrno;
5910 const rc = sys.memfd_create(name, flags);5905 const rc = sys.memfd_create(name, flags);
5911 switch (getErrno(rc)) {5906 switch (getErrno(rc)) {
5912 0 => return @intCast(fd_t, rc),5907 .SUCCESS => return @intCast(fd_t, rc),
5913 EFAULT => unreachable, // name has invalid memory5908 .FAULT => unreachable, // name has invalid memory
5914 EINVAL => unreachable, // name/flags are faulty5909 .INVAL => unreachable, // name/flags are faulty
5915 ENFILE => return error.SystemFdQuotaExceeded,5910 .NFILE => return error.SystemFdQuotaExceeded,
5916 EMFILE => return error.ProcessFdQuotaExceeded,5911 .MFILE => return error.ProcessFdQuotaExceeded,
5917 ENOMEM => return error.OutOfMemory,5912 .NOMEM => return error.OutOfMemory,
5918 ENOSYS => return error.SystemOutdated,5913 .NOSYS => return error.SystemOutdated,
5919 else => |err| return unexpectedErrno(err),5914 else => |err| return unexpectedErrno(err),
5920 }5915 }
5921}5916}
...@@ -5940,9 +5935,9 @@ pub fn getrusage(who: i32) rusage {...@@ -5940,9 +5935,9 @@ pub fn getrusage(who: i32) rusage {
5940 var result: rusage = undefined;5935 var result: rusage = undefined;
5941 const rc = system.getrusage(who, &result);5936 const rc = system.getrusage(who, &result);
5942 switch (errno(rc)) {5937 switch (errno(rc)) {
5943 0 => return result,5938 .SUCCESS => return result,
5944 EINVAL => unreachable,5939 .INVAL => unreachable,
5945 EFAULT => unreachable,5940 .FAULT => unreachable,
5946 else => unreachable,5941 else => unreachable,
5947 }5942 }
5948}5943}
...@@ -5953,10 +5948,10 @@ pub fn tcgetattr(handle: fd_t) TermiosGetError!termios {...@@ -5953,10 +5948,10 @@ pub fn tcgetattr(handle: fd_t) TermiosGetError!termios {
5953 while (true) {5948 while (true) {
5954 var term: termios = undefined;5949 var term: termios = undefined;
5955 switch (errno(system.tcgetattr(handle, &term))) {5950 switch (errno(system.tcgetattr(handle, &term))) {
5956 0 => return term,5951 .SUCCESS => return term,
5957 EINTR => continue,5952 .INTR => continue,
5958 EBADF => unreachable,5953 .BADF => unreachable,
5959 ENOTTY => return error.NotATerminal,5954 .NOTTY => return error.NotATerminal,
5960 else => |err| return unexpectedErrno(err),5955 else => |err| return unexpectedErrno(err),
5961 }5956 }
5962 }5957 }
...@@ -5967,12 +5962,12 @@ pub const TermiosSetError = TermiosGetError || error{ProcessOrphaned};...@@ -5967,12 +5962,12 @@ pub const TermiosSetError = TermiosGetError || error{ProcessOrphaned};
5967pub fn tcsetattr(handle: fd_t, optional_action: TCSA, termios_p: termios) TermiosSetError!void {5962pub fn tcsetattr(handle: fd_t, optional_action: TCSA, termios_p: termios) TermiosSetError!void {
5968 while (true) {5963 while (true) {
5969 switch (errno(system.tcsetattr(handle, optional_action, &termios_p))) {5964 switch (errno(system.tcsetattr(handle, optional_action, &termios_p))) {
5970 0 => return,5965 .SUCCESS => return,
5971 EBADF => unreachable,5966 .BADF => unreachable,
5972 EINTR => continue,5967 .INTR => continue,
5973 EINVAL => unreachable,5968 .INVAL => unreachable,
5974 ENOTTY => return error.NotATerminal,5969 .NOTTY => return error.NotATerminal,
5975 EIO => return error.ProcessOrphaned,5970 .IO => return error.ProcessOrphaned,
5976 else => |err| return unexpectedErrno(err),5971 else => |err| return unexpectedErrno(err),
5977 }5972 }
5978 }5973 }
...@@ -5986,15 +5981,15 @@ pub const IoCtl_SIOCGIFINDEX_Error = error{...@@ -5986,15 +5981,15 @@ pub const IoCtl_SIOCGIFINDEX_Error = error{
5986pub fn ioctl_SIOCGIFINDEX(fd: fd_t, ifr: *ifreq) IoCtl_SIOCGIFINDEX_Error!void {5981pub fn ioctl_SIOCGIFINDEX(fd: fd_t, ifr: *ifreq) IoCtl_SIOCGIFINDEX_Error!void {
5987 while (true) {5982 while (true) {
5988 switch (errno(system.ioctl(fd, SIOCGIFINDEX, @ptrToInt(ifr)))) {5983 switch (errno(system.ioctl(fd, SIOCGIFINDEX, @ptrToInt(ifr)))) {
5989 0 => return,5984 .SUCCESS => return,
5990 EINVAL => unreachable, // Bad parameters.5985 .INVAL => unreachable, // Bad parameters.
5991 ENOTTY => unreachable,5986 .NOTTY => unreachable,
5992 ENXIO => unreachable,5987 .NXIO => unreachable,
5993 EBADF => unreachable, // Always a race condition.5988 .BADF => unreachable, // Always a race condition.
5994 EFAULT => unreachable, // Bad pointer parameter.5989 .FAULT => unreachable, // Bad pointer parameter.
5995 EINTR => continue,5990 .INTR => continue,
5996 EIO => return error.FileSystem,5991 .IO => return error.FileSystem,
5997 ENODEV => return error.InterfaceNotFound,5992 .NODEV => return error.InterfaceNotFound,
5998 else => |err| return unexpectedErrno(err),5993 else => |err| return unexpectedErrno(err),
5999 }5994 }
6000 }5995 }
...@@ -6003,13 +5998,13 @@ pub fn ioctl_SIOCGIFINDEX(fd: fd_t, ifr: *ifreq) IoCtl_SIOCGIFINDEX_Error!void {...@@ -6003,13 +5998,13 @@ pub fn ioctl_SIOCGIFINDEX(fd: fd_t, ifr: *ifreq) IoCtl_SIOCGIFINDEX_Error!void {
6003pub fn signalfd(fd: fd_t, mask: *const sigset_t, flags: u32) !fd_t {5998pub fn signalfd(fd: fd_t, mask: *const sigset_t, flags: u32) !fd_t {
6004 const rc = system.signalfd(fd, mask, flags);5999 const rc = system.signalfd(fd, mask, flags);
6005 switch (errno(rc)) {6000 switch (errno(rc)) {
6006 0 => return @intCast(fd_t, rc),6001 .SUCCESS => return @intCast(fd_t, rc),
6007 EBADF, EINVAL => unreachable,6002 .BADF, .INVAL => unreachable,
6008 ENFILE => return error.SystemFdQuotaExceeded,6003 .NFILE => return error.SystemFdQuotaExceeded,
6009 ENOMEM => return error.SystemResources,6004 .NOMEM => return error.SystemResources,
6010 EMFILE => return error.ProcessResources,6005 .MFILE => return error.ProcessResources,
6011 ENODEV => return error.InodeMountFail,6006 .NODEV => return error.InodeMountFail,
6012 ENOSYS => return error.SystemOutdated,6007 .NOSYS => return error.SystemOutdated,
6013 else => |err| return unexpectedErrno(err),6008 else => |err| return unexpectedErrno(err),
6014 }6009 }
6015}6010}
...@@ -6030,11 +6025,11 @@ pub fn sync() void {...@@ -6030,11 +6025,11 @@ pub fn sync() void {
6030pub fn syncfs(fd: fd_t) SyncError!void {6025pub fn syncfs(fd: fd_t) SyncError!void {
6031 const rc = system.syncfs(fd);6026 const rc = system.syncfs(fd);
6032 switch (errno(rc)) {6027 switch (errno(rc)) {
6033 0 => return,6028 .SUCCESS => return,
6034 EBADF, EINVAL, EROFS => unreachable,6029 .BADF, .INVAL, .ROFS => unreachable,
6035 EIO => return error.InputOutput,6030 .IO => return error.InputOutput,
6036 ENOSPC => return error.NoSpaceLeft,6031 .NOSPC => return error.NoSpaceLeft,
6037 EDQUOT => return error.DiskQuota,6032 .DQUOT => return error.DiskQuota,
6038 else => |err| return unexpectedErrno(err),6033 else => |err| return unexpectedErrno(err),
6039 }6034 }
6040}6035}
...@@ -6054,11 +6049,11 @@ pub fn fsync(fd: fd_t) SyncError!void {...@@ -6054,11 +6049,11 @@ pub fn fsync(fd: fd_t) SyncError!void {
6054 }6049 }
6055 const rc = system.fsync(fd);6050 const rc = system.fsync(fd);
6056 switch (errno(rc)) {6051 switch (errno(rc)) {
6057 0 => return,6052 .SUCCESS => return,
6058 EBADF, EINVAL, EROFS => unreachable,6053 .BADF, .INVAL, .ROFS => unreachable,
6059 EIO => return error.InputOutput,6054 .IO => return error.InputOutput,
6060 ENOSPC => return error.NoSpaceLeft,6055 .NOSPC => return error.NoSpaceLeft,
6061 EDQUOT => return error.DiskQuota,6056 .DQUOT => return error.DiskQuota,
6062 else => |err| return unexpectedErrno(err),6057 else => |err| return unexpectedErrno(err),
6063 }6058 }
6064}6059}
...@@ -6073,11 +6068,11 @@ pub fn fdatasync(fd: fd_t) SyncError!void {...@@ -6073,11 +6068,11 @@ pub fn fdatasync(fd: fd_t) SyncError!void {
6073 }6068 }
6074 const rc = system.fdatasync(fd);6069 const rc = system.fdatasync(fd);
6075 switch (errno(rc)) {6070 switch (errno(rc)) {
6076 0 => return,6071 .SUCCESS => return,
6077 EBADF, EINVAL, EROFS => unreachable,6072 .BADF, .INVAL, .ROFS => unreachable,
6078 EIO => return error.InputOutput,6073 .IO => return error.InputOutput,
6079 ENOSPC => return error.NoSpaceLeft,6074 .NOSPC => return error.NoSpaceLeft,
6080 EDQUOT => return error.DiskQuota,6075 .DQUOT => return error.DiskQuota,
6081 else => |err| return unexpectedErrno(err),6076 else => |err| return unexpectedErrno(err),
6082 }6077 }
6083}6078}
...@@ -6111,15 +6106,15 @@ pub fn prctl(option: PR, args: anytype) PrctlError!u31 {...@@ -6111,15 +6106,15 @@ pub fn prctl(option: PR, args: anytype) PrctlError!u31 {
61116106
6112 const rc = system.prctl(@enumToInt(option), buf[0], buf[1], buf[2], buf[3]);6107 const rc = system.prctl(@enumToInt(option), buf[0], buf[1], buf[2], buf[3]);
6113 switch (errno(rc)) {6108 switch (errno(rc)) {
6114 0 => return @intCast(u31, rc),6109 .SUCCESS => return @intCast(u31, rc),
6115 EACCES => return error.AccessDenied,6110 .ACCES => return error.AccessDenied,
6116 EBADF => return error.InvalidFileDescriptor,6111 .BADF => return error.InvalidFileDescriptor,
6117 EFAULT => return error.InvalidAddress,6112 .FAULT => return error.InvalidAddress,
6118 EINVAL => unreachable,6113 .INVAL => unreachable,
6119 ENODEV, ENXIO => return error.UnsupportedFeature,6114 .NODEV, .NXIO => return error.UnsupportedFeature,
6120 EOPNOTSUPP => return error.OperationNotSupported,6115 .OPNOTSUPP => return error.OperationNotSupported,
6121 EPERM, EBUSY => return error.PermissionDenied,6116 .PERM, .BUSY => return error.PermissionDenied,
6122 ERANGE => unreachable,6117 .RANGE => unreachable,
6123 else => |err| return unexpectedErrno(err),6118 else => |err| return unexpectedErrno(err),
6124 }6119 }
6125}6120}
...@@ -6134,9 +6129,9 @@ pub fn getrlimit(resource: rlimit_resource) GetrlimitError!rlimit {...@@ -6134,9 +6129,9 @@ pub fn getrlimit(resource: rlimit_resource) GetrlimitError!rlimit {
61346129
6135 var limits: rlimit = undefined;6130 var limits: rlimit = undefined;
6136 switch (errno(getrlimit_sym(resource, &limits))) {6131 switch (errno(getrlimit_sym(resource, &limits))) {
6137 0 => return limits,6132 .SUCCESS => return limits,
6138 EFAULT => unreachable, // bogus pointer6133 .FAULT => unreachable, // bogus pointer
6139 EINVAL => unreachable,6134 .INVAL => unreachable,
6140 else => |err| return unexpectedErrno(err),6135 else => |err| return unexpectedErrno(err),
6141 }6136 }
6142}6137}
...@@ -6150,10 +6145,10 @@ pub fn setrlimit(resource: rlimit_resource, limits: rlimit) SetrlimitError!void...@@ -6150,10 +6145,10 @@ pub fn setrlimit(resource: rlimit_resource, limits: rlimit) SetrlimitError!void
6150 system.setrlimit;6145 system.setrlimit;
61516146
6152 switch (errno(setrlimit_sym(resource, &limits))) {6147 switch (errno(setrlimit_sym(resource, &limits))) {
6153 0 => return,6148 .SUCCESS => return,
6154 EFAULT => unreachable, // bogus pointer6149 .FAULT => unreachable, // bogus pointer
6155 EINVAL => return error.LimitTooBig, // this could also mean "invalid resource", but that would be unreachable6150 .INVAL => return error.LimitTooBig, // this could also mean "invalid resource", but that would be unreachable
6156 EPERM => return error.PermissionDenied,6151 .PERM => return error.PermissionDenied,
6157 else => |err| return unexpectedErrno(err),6152 else => |err| return unexpectedErrno(err),
6158 }6153 }
6159}6154}
...@@ -6194,14 +6189,14 @@ pub const MadviseError = error{...@@ -6194,14 +6189,14 @@ pub const MadviseError = error{
6194/// This syscall is optional and is sometimes configured to be disabled.6189/// This syscall is optional and is sometimes configured to be disabled.
6195pub fn madvise(ptr: [*]align(mem.page_size) u8, length: usize, advice: u32) MadviseError!void {6190pub fn madvise(ptr: [*]align(mem.page_size) u8, length: usize, advice: u32) MadviseError!void {
6196 switch (errno(system.madvise(ptr, length, advice))) {6191 switch (errno(system.madvise(ptr, length, advice))) {
6197 0 => return,6192 .SUCCESS => return,
6198 EACCES => return error.AccessDenied,6193 .ACCES => return error.AccessDenied,
6199 EAGAIN => return error.SystemResources,6194 .AGAIN => return error.SystemResources,
6200 EBADF => unreachable, // The map exists, but the area maps something that isn't a file.6195 .BADF => unreachable, // The map exists, but the area maps something that isn't a file.
6201 EINVAL => return error.InvalidSyscall,6196 .INVAL => return error.InvalidSyscall,
6202 EIO => return error.WouldExceedMaximumResidentSetSize,6197 .IO => return error.WouldExceedMaximumResidentSetSize,
6203 ENOMEM => return error.OutOfMemory,6198 .NOMEM => return error.OutOfMemory,
6204 ENOSYS => return error.MadviseUnavailable,6199 .NOSYS => return error.MadviseUnavailable,
6205 else => |err| return unexpectedErrno(err),6200 else => |err| return unexpectedErrno(err),
6206 }6201 }
6207}6202}
lib/std/os/bits.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6//! Platform-dependent types and values that are used along with OS-specific APIs.1//! Platform-dependent types and values that are used along with OS-specific APIs.
7//! These are imported into `std.c`, `std.os`, and `std.os.linux`.2//! These are imported into `std.c`, `std.os`, and `std.os.linux`.
8//! Root source files can define `os.bits` and these will additionally be added3//! Root source files can define `os.bits` and these will additionally be added
lib/std/os/bits/darwin.zig+230-229
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
...@@ -235,6 +230,7 @@ pub const host_t = mach_port_t;...@@ -235,6 +230,7 @@ pub const host_t = mach_port_t;
235pub const CALENDAR_CLOCK = 1;230pub const CALENDAR_CLOCK = 1;
236231
237pub const PATH_MAX = 1024;232pub const PATH_MAX = 1024;
233pub const IOV_MAX = 16;
238234
239pub const STDIN_FILENO = 0;235pub const STDIN_FILENO = 0;
240pub const STDOUT_FILENO = 1;236pub const STDOUT_FILENO = 1;
...@@ -865,337 +861,342 @@ pub fn WIFSIGNALED(x: u32) bool {...@@ -865,337 +861,342 @@ pub fn WIFSIGNALED(x: u32) bool {
865 return wstatus(x) != wstopped and wstatus(x) != 0;861 return wstatus(x) != wstopped and wstatus(x) != 0;
866}862}
867863
868/// Operation not permitted864pub const E = enum(u16) {
869pub const EPERM = 1;865 /// No error occurred.
866 SUCCESS = 0,
870867
871/// No such file or directory868 /// Operation not permitted
872pub const ENOENT = 2;869 PERM = 1,
873870
874/// No such process871 /// No such file or directory
875pub const ESRCH = 3;872 NOENT = 2,
876873
877/// Interrupted system call874 /// No such process
878pub const EINTR = 4;875 SRCH = 3,
879876
880/// Input/output error877 /// Interrupted system call
881pub const EIO = 5;878 INTR = 4,
882879
883/// Device not configured880 /// Input/output error
884pub const ENXIO = 6;881 IO = 5,
885882
886/// Argument list too long883 /// Device not configured
887pub const E2BIG = 7;884 NXIO = 6,
888885
889/// Exec format error886 /// Argument list too long
890pub const ENOEXEC = 8;887 @"2BIG" = 7,
891888
892/// Bad file descriptor889 /// Exec format error
893pub const EBADF = 9;890 NOEXEC = 8,
894891
895/// No child processes892 /// Bad file descriptor
896pub const ECHILD = 10;893 BADF = 9,
897894
898/// Resource deadlock avoided895 /// No child processes
899pub const EDEADLK = 11;896 CHILD = 10,
900897
901/// Cannot allocate memory898 /// Resource deadlock avoided
902pub const ENOMEM = 12;899 DEADLK = 11,
903900
904/// Permission denied901 /// Cannot allocate memory
905pub const EACCES = 13;902 NOMEM = 12,
906903
907/// Bad address904 /// Permission denied
908pub const EFAULT = 14;905 ACCES = 13,
909906
910/// Block device required907 /// Bad address
911pub const ENOTBLK = 15;908 FAULT = 14,
912909
913/// Device / Resource busy910 /// Block device required
914pub const EBUSY = 16;911 NOTBLK = 15,
915912
916/// File exists913 /// Device / Resource busy
917pub const EEXIST = 17;914 BUSY = 16,
918915
919/// Cross-device link916 /// File exists
920pub const EXDEV = 18;917 EXIST = 17,
921918
922/// Operation not supported by device919 /// Cross-device link
923pub const ENODEV = 19;920 XDEV = 18,
924921
925/// Not a directory922 /// Operation not supported by device
926pub const ENOTDIR = 20;923 NODEV = 19,
927924
928/// Is a directory925 /// Not a directory
929pub const EISDIR = 21;926 NOTDIR = 20,
930927
931/// Invalid argument928 /// Is a directory
932pub const EINVAL = 22;929 ISDIR = 21,
933930
934/// Too many open files in system931 /// Invalid argument
935pub const ENFILE = 23;932 INVAL = 22,
936933
937/// Too many open files934 /// Too many open files in system
938pub const EMFILE = 24;935 NFILE = 23,
939936
940/// Inappropriate ioctl for device937 /// Too many open files
941pub const ENOTTY = 25;938 MFILE = 24,
942939
943/// Text file busy940 /// Inappropriate ioctl for device
944pub const ETXTBSY = 26;941 NOTTY = 25,
945942
946/// File too large943 /// Text file busy
947pub const EFBIG = 27;944 TXTBSY = 26,
948945
949/// No space left on device946 /// File too large
950pub const ENOSPC = 28;947 FBIG = 27,
951948
952/// Illegal seek949 /// No space left on device
953pub const ESPIPE = 29;950 NOSPC = 28,
954951
955/// Read-only file system952 /// Illegal seek
956pub const EROFS = 30;953 SPIPE = 29,
957954
958/// Too many links955 /// Read-only file system
959pub const EMLINK = 31;956 ROFS = 30,
960/// Broken pipe
961957
962// math software958 /// Too many links
963pub const EPIPE = 32;959 MLINK = 31,
964960
965/// Numerical argument out of domain961 /// Broken pipe
966pub const EDOM = 33;962 PIPE = 32,
967/// Result too large
968963
969// non-blocking and interrupt i/o964 // math software
970pub const ERANGE = 34;
971965
972/// Resource temporarily unavailable966 /// Numerical argument out of domain
973pub const EAGAIN = 35;967 DOM = 33,
974968
975/// Operation would block969 /// Result too large
976pub const EWOULDBLOCK = EAGAIN;970 RANGE = 34,
977971
978/// Operation now in progress972 // non-blocking and interrupt i/o
979pub const EINPROGRESS = 36;
980/// Operation already in progress
981973
982// ipc/network software -- argument errors974 /// Resource temporarily unavailable
983pub const EALREADY = 37;975 /// This is the same code used for `WOULDBLOCK`.
976 AGAIN = 35,
984977
985/// Socket operation on non-socket978 /// Operation now in progress
986pub const ENOTSOCK = 38;979 INPROGRESS = 36,
987980
988/// Destination address required981 /// Operation already in progress
989pub const EDESTADDRREQ = 39;982 ALREADY = 37,
990983
991/// Message too long984 // ipc/network software -- argument errors
992pub const EMSGSIZE = 40;
993985
994/// Protocol wrong type for socket986 /// Socket operation on non-socket
995pub const EPROTOTYPE = 41;987 NOTSOCK = 38,
996988
997/// Protocol not available989 /// Destination address required
998pub const ENOPROTOOPT = 42;990 DESTADDRREQ = 39,
999991
1000/// Protocol not supported992 /// Message too long
1001pub const EPROTONOSUPPORT = 43;993 MSGSIZE = 40,
1002994
1003/// Socket type not supported995 /// Protocol wrong type for socket
1004pub const ESOCKTNOSUPPORT = 44;996 PROTOTYPE = 41,
1005997
1006/// Operation not supported998 /// Protocol not available
1007pub const ENOTSUP = 45;999 NOPROTOOPT = 42,
10081000
1009/// Operation not supported. Alias of `ENOTSUP`.1001 /// Protocol not supported
1010pub const EOPNOTSUPP = ENOTSUP;1002 PROTONOSUPPORT = 43,
10111003
1012/// Protocol family not supported1004 /// Socket type not supported
1013pub const EPFNOSUPPORT = 46;1005 SOCKTNOSUPPORT = 44,
10141006
1015/// Address family not supported by protocol family1007 /// Operation not supported
1016pub const EAFNOSUPPORT = 47;1008 /// The same code is used for `NOTSUP`.
1009 OPNOTSUPP = 45,
10171010
1018/// Address already in use1011 /// Protocol family not supported
1019pub const EADDRINUSE = 48;1012 PFNOSUPPORT = 46,
1020/// Can't assign requested address
10211013
1022// ipc/network software -- operational errors1014 /// Address family not supported by protocol family
1023pub const EADDRNOTAVAIL = 49;1015 AFNOSUPPORT = 47,
10241016
1025/// Network is down1017 /// Address already in use
1026pub const ENETDOWN = 50;1018 ADDRINUSE = 48,
1019 /// Can't assign requested address
10271020
1028/// Network is unreachable1021 // ipc/network software -- operational errors
1029pub const ENETUNREACH = 51;1022 ADDRNOTAVAIL = 49,
10301023
1031/// Network dropped connection on reset1024 /// Network is down
1032pub const ENETRESET = 52;1025 NETDOWN = 50,
10331026
1034/// Software caused connection abort1027 /// Network is unreachable
1035pub const ECONNABORTED = 53;1028 NETUNREACH = 51,
10361029
1037/// Connection reset by peer1030 /// Network dropped connection on reset
1038pub const ECONNRESET = 54;1031 NETRESET = 52,
10391032
1040/// No buffer space available1033 /// Software caused connection abort
1041pub const ENOBUFS = 55;1034 CONNABORTED = 53,
10421035
1043/// Socket is already connected1036 /// Connection reset by peer
1044pub const EISCONN = 56;1037 CONNRESET = 54,
10451038
1046/// Socket is not connected1039 /// No buffer space available
1047pub const ENOTCONN = 57;1040 NOBUFS = 55,
10481041
1049/// Can't send after socket shutdown1042 /// Socket is already connected
1050pub const ESHUTDOWN = 58;1043 ISCONN = 56,
10511044
1052/// Too many references: can't splice1045 /// Socket is not connected
1053pub const ETOOMANYREFS = 59;1046 NOTCONN = 57,
10541047
1055/// Operation timed out1048 /// Can't send after socket shutdown
1056pub const ETIMEDOUT = 60;1049 SHUTDOWN = 58,
10571050
1058/// Connection refused1051 /// Too many references: can't splice
1059pub const ECONNREFUSED = 61;1052 TOOMANYREFS = 59,
10601053
1061/// Too many levels of symbolic links1054 /// Operation timed out
1062pub const ELOOP = 62;1055 TIMEDOUT = 60,
10631056
1064/// File name too long1057 /// Connection refused
1065pub const ENAMETOOLONG = 63;1058 CONNREFUSED = 61,
10661059
1067/// Host is down1060 /// Too many levels of symbolic links
1068pub const EHOSTDOWN = 64;1061 LOOP = 62,
10691062
1070/// No route to host1063 /// File name too long
1071pub const EHOSTUNREACH = 65;1064 NAMETOOLONG = 63,
1072/// Directory not empty
10731065
1074// quotas & mush1066 /// Host is down
1075pub const ENOTEMPTY = 66;1067 HOSTDOWN = 64,
10761068
1077/// Too many processes1069 /// No route to host
1078pub const EPROCLIM = 67;1070 HOSTUNREACH = 65,
1071 /// Directory not empty
10791072
1080/// Too many users1073 // quotas & mush
1081pub const EUSERS = 68;1074 NOTEMPTY = 66,
1082/// Disc quota exceeded
10831075
1084// Network File System1076 /// Too many processes
1085pub const EDQUOT = 69;1077 PROCLIM = 67,
10861078
1087/// Stale NFS file handle1079 /// Too many users
1088pub const ESTALE = 70;1080 USERS = 68,
1081 /// Disc quota exceeded
10891082
1090/// Too many levels of remote in path1083 // Network File System
1091pub const EREMOTE = 71;1084 DQUOT = 69,
10921085
1093/// RPC struct is bad1086 /// Stale NFS file handle
1094pub const EBADRPC = 72;1087 STALE = 70,
10951088
1096/// RPC version wrong1089 /// Too many levels of remote in path
1097pub const ERPCMISMATCH = 73;1090 REMOTE = 71,
10981091
1099/// RPC prog. not avail1092 /// RPC struct is bad
1100pub const EPROGUNAVAIL = 74;1093 BADRPC = 72,
11011094
1102/// Program version wrong1095 /// RPC version wrong
1103pub const EPROGMISMATCH = 75;1096 RPCMISMATCH = 73,
11041097
1105/// Bad procedure for program1098 /// RPC prog. not avail
1106pub const EPROCUNAVAIL = 76;1099 PROGUNAVAIL = 74,
11071100
1108/// No locks available1101 /// Program version wrong
1109pub const ENOLCK = 77;1102 PROGMISMATCH = 75,
11101103
1111/// Function not implemented1104 /// Bad procedure for program
1112pub const ENOSYS = 78;1105 PROCUNAVAIL = 76,
11131106
1114/// Inappropriate file type or format1107 /// No locks available
1115pub const EFTYPE = 79;1108 NOLCK = 77,
11161109
1117/// Authentication error1110 /// Function not implemented
1118pub const EAUTH = 80;1111 NOSYS = 78,
1119/// Need authenticator
11201112
1121// Intelligent device errors1113 /// Inappropriate file type or format
1122pub const ENEEDAUTH = 81;1114 FTYPE = 79,
11231115
1124/// Device power is off1116 /// Authentication error
1125pub const EPWROFF = 82;1117 AUTH = 80,
11261118
1127/// Device error, e.g. paper out1119 /// Need authenticator
1128pub const EDEVERR = 83;1120 NEEDAUTH = 81,
1129/// Value too large to be stored in data type
11301121
1131// Program loading errors1122 // Intelligent device errors
1132pub const EOVERFLOW = 84;
11331123
1134/// Bad executable1124 /// Device power is off
1135pub const EBADEXEC = 85;1125 PWROFF = 82,
11361126
1137/// Bad CPU type in executable1127 /// Device error, e.g. paper out
1138pub const EBADARCH = 86;1128 DEVERR = 83,
11391129
1140/// Shared library version mismatch1130 /// Value too large to be stored in data type
1141pub const ESHLIBVERS = 87;1131 OVERFLOW = 84,
11421132
1143/// Malformed Macho file1133 // Program loading errors
1144pub const EBADMACHO = 88;
11451134
1146/// Operation canceled1135 /// Bad executable
1147pub const ECANCELED = 89;1136 BADEXEC = 85,
11481137
1149/// Identifier removed1138 /// Bad CPU type in executable
1150pub const EIDRM = 90;1139 BADARCH = 86,
11511140
1152/// No message of desired type1141 /// Shared library version mismatch
1153pub const ENOMSG = 91;1142 SHLIBVERS = 87,
11541143
1155/// Illegal byte sequence1144 /// Malformed Macho file
1156pub const EILSEQ = 92;1145 BADMACHO = 88,
11571146
1158/// Attribute not found1147 /// Operation canceled
1159pub const ENOATTR = 93;1148 CANCELED = 89,
11601149
1161/// Bad message1150 /// Identifier removed
1162pub const EBADMSG = 94;1151 IDRM = 90,
11631152
1164/// Reserved1153 /// No message of desired type
1165pub const EMULTIHOP = 95;1154 NOMSG = 91,
11661155
1167/// No message available on STREAM1156 /// Illegal byte sequence
1168pub const ENODATA = 96;1157 ILSEQ = 92,
11691158
1170/// Reserved1159 /// Attribute not found
1171pub const ENOLINK = 97;1160 NOATTR = 93,
11721161
1173/// No STREAM resources1162 /// Bad message
1174pub const ENOSR = 98;1163 BADMSG = 94,
11751164
1176/// Not a STREAM1165 /// Reserved
1177pub const ENOSTR = 99;1166 MULTIHOP = 95,
11781167
1179/// Protocol error1168 /// No message available on STREAM
1180pub const EPROTO = 100;1169 NODATA = 96,
11811170
1182/// STREAM ioctl timeout1171 /// Reserved
1183pub const ETIME = 101;1172 NOLINK = 97,
11841173
1185/// No such policy registered1174 /// No STREAM resources
1186pub const ENOPOLICY = 103;1175 NOSR = 98,
11871176
1188/// State not recoverable1177 /// Not a STREAM
1189pub const ENOTRECOVERABLE = 104;1178 NOSTR = 99,
11901179
1191/// Previous owner died1180 /// Protocol error
1192pub const EOWNERDEAD = 105;1181 PROTO = 100,
11931182
1194/// Interface output queue is full1183 /// STREAM ioctl timeout
1195pub const EQFULL = 106;1184 TIME = 101,
11961185
1197/// Must be equal largest errno1186 /// No such policy registered
1198pub const ELAST = 106;1187 NOPOLICY = 103,
1188
1189 /// State not recoverable
1190 NOTRECOVERABLE = 104,
1191
1192 /// Previous owner died
1193 OWNERDEAD = 105,
1194
1195 /// Interface output queue is full
1196 QFULL = 106,
1197
1198 _,
1199};
11991200
1200pub const SIGSTKSZ = 131072;1201pub const SIGSTKSZ = 131072;
1201pub const MINSIGSTKSZ = 32768;1202pub const MINSIGSTKSZ = 32768;
lib/std/os/bits/dragonfly.zig+103-102
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const maxInt = std.math.maxInt;2const maxInt = std.math.maxInt;
83
...@@ -25,103 +20,108 @@ pub const gid_t = u32;...@@ -25,103 +20,108 @@ pub const gid_t = u32;
25pub const time_t = isize;20pub const time_t = isize;
26pub const suseconds_t = c_long;21pub const suseconds_t = c_long;
2722
28pub const ENOTSUP = EOPNOTSUPP;23pub const E = enum(u16) {
29pub const EWOULDBLOCK = EAGAIN;24 /// No error occurred.
30pub const EPERM = 1;25 SUCCESS = 0,
31pub const ENOENT = 2;26
32pub const ESRCH = 3;27 PERM = 1,
33pub const EINTR = 4;28 NOENT = 2,
34pub const EIO = 5;29 SRCH = 3,
35pub const ENXIO = 6;30 INTR = 4,
36pub const E2BIG = 7;31 IO = 5,
37pub const ENOEXEC = 8;32 NXIO = 6,
38pub const EBADF = 9;33 @"2BIG" = 7,
39pub const ECHILD = 10;34 NOEXEC = 8,
40pub const EDEADLK = 11;35 BADF = 9,
41pub const ENOMEM = 12;36 CHILD = 10,
42pub const EACCES = 13;37 DEADLK = 11,
43pub const EFAULT = 14;38 NOMEM = 12,
44pub const ENOTBLK = 15;39 ACCES = 13,
45pub const EBUSY = 16;40 FAULT = 14,
46pub const EEXIST = 17;41 NOTBLK = 15,
47pub const EXDEV = 18;42 BUSY = 16,
48pub const ENODEV = 19;43 EXIST = 17,
49pub const ENOTDIR = 20;44 XDEV = 18,
50pub const EISDIR = 21;45 NODEV = 19,
51pub const EINVAL = 22;46 NOTDIR = 20,
52pub const ENFILE = 23;47 ISDIR = 21,
53pub const EMFILE = 24;48 INVAL = 22,
54pub const ENOTTY = 25;49 NFILE = 23,
55pub const ETXTBSY = 26;50 MFILE = 24,
56pub const EFBIG = 27;51 NOTTY = 25,
57pub const ENOSPC = 28;52 TXTBSY = 26,
58pub const ESPIPE = 29;53 FBIG = 27,
59pub const EROFS = 30;54 NOSPC = 28,
60pub const EMLINK = 31;55 SPIPE = 29,
61pub const EPIPE = 32;56 ROFS = 30,
62pub const EDOM = 33;57 MLINK = 31,
63pub const ERANGE = 34;58 PIPE = 32,
64pub const EAGAIN = 35;59 DOM = 33,
65pub const EINPROGRESS = 36;60 RANGE = 34,
66pub const EALREADY = 37;61 /// This code is also used for `WOULDBLOCK`.
67pub const ENOTSOCK = 38;62 AGAIN = 35,
68pub const EDESTADDRREQ = 39;63 INPROGRESS = 36,
69pub const EMSGSIZE = 40;64 ALREADY = 37,
70pub const EPROTOTYPE = 41;65 NOTSOCK = 38,
71pub const ENOPROTOOPT = 42;66 DESTADDRREQ = 39,
72pub const EPROTONOSUPPORT = 43;67 MSGSIZE = 40,
73pub const ESOCKTNOSUPPORT = 44;68 PROTOTYPE = 41,
74pub const EOPNOTSUPP = 45;69 NOPROTOOPT = 42,
75pub const EPFNOSUPPORT = 46;70 PROTONOSUPPORT = 43,
76pub const EAFNOSUPPORT = 47;71 SOCKTNOSUPPORT = 44,
77pub const EADDRINUSE = 48;72 /// This code is also used for `NOTSUP`.
78pub const EADDRNOTAVAIL = 49;73 OPNOTSUPP = 45,
79pub const ENETDOWN = 50;74 PFNOSUPPORT = 46,
80pub const ENETUNREACH = 51;75 AFNOSUPPORT = 47,
81pub const ENETRESET = 52;76 ADDRINUSE = 48,
82pub const ECONNABORTED = 53;77 ADDRNOTAVAIL = 49,
83pub const ECONNRESET = 54;78 NETDOWN = 50,
84pub const ENOBUFS = 55;79 NETUNREACH = 51,
85pub const EISCONN = 56;80 NETRESET = 52,
86pub const ENOTCONN = 57;81 CONNABORTED = 53,
87pub const ESHUTDOWN = 58;82 CONNRESET = 54,
88pub const ETOOMANYREFS = 59;83 NOBUFS = 55,
89pub const ETIMEDOUT = 60;84 ISCONN = 56,
90pub const ECONNREFUSED = 61;85 NOTCONN = 57,
91pub const ELOOP = 62;86 SHUTDOWN = 58,
92pub const ENAMETOOLONG = 63;87 TOOMANYREFS = 59,
93pub const EHOSTDOWN = 64;88 TIMEDOUT = 60,
94pub const EHOSTUNREACH = 65;89 CONNREFUSED = 61,
95pub const ENOTEMPTY = 66;90 LOOP = 62,
96pub const EPROCLIM = 67;91 NAMETOOLONG = 63,
97pub const EUSERS = 68;92 HOSTDOWN = 64,
98pub const EDQUOT = 69;93 HOSTUNREACH = 65,
99pub const ESTALE = 70;94 NOTEMPTY = 66,
100pub const EREMOTE = 71;95 PROCLIM = 67,
101pub const EBADRPC = 72;96 USERS = 68,
102pub const ERPCMISMATCH = 73;97 DQUOT = 69,
103pub const EPROGUNAVAIL = 74;98 STALE = 70,
104pub const EPROGMISMATCH = 75;99 REMOTE = 71,
105pub const EPROCUNAVAIL = 76;100 BADRPC = 72,
106pub const ENOLCK = 77;101 RPCMISMATCH = 73,
107pub const ENOSYS = 78;102 PROGUNAVAIL = 74,
108pub const EFTYPE = 79;103 PROGMISMATCH = 75,
109pub const EAUTH = 80;104 PROCUNAVAIL = 76,
110pub const ENEEDAUTH = 81;105 NOLCK = 77,
111pub const EIDRM = 82;106 NOSYS = 78,
112pub const ENOMSG = 83;107 FTYPE = 79,
113pub const EOVERFLOW = 84;108 AUTH = 80,
114pub const ECANCELED = 85;109 NEEDAUTH = 81,
115pub const EILSEQ = 86;110 IDRM = 82,
116pub const ENOATTR = 87;111 NOMSG = 83,
117pub const EDOOFUS = 88;112 OVERFLOW = 84,
118pub const EBADMSG = 89;113 CANCELED = 85,
119pub const EMULTIHOP = 90;114 ILSEQ = 86,
120pub const ENOLINK = 91;115 NOATTR = 87,
121pub const EPROTO = 92;116 DOOFUS = 88,
122pub const ENOMEDIUM = 93;117 BADMSG = 89,
123pub const ELAST = 99;118 MULTIHOP = 90,
124pub const EASYNC = 99;119 NOLINK = 91,
120 PROTO = 92,
121 NOMEDIUM = 93,
122 ASYNC = 99,
123 _,
124};
125125
126pub const STDIN_FILENO = 0;126pub const STDIN_FILENO = 0;
127pub const STDOUT_FILENO = 1;127pub const STDOUT_FILENO = 1;
...@@ -168,6 +168,7 @@ pub const SA_NOCLDWAIT = 0x0020;...@@ -168,6 +168,7 @@ pub const SA_NOCLDWAIT = 0x0020;
168pub const SA_SIGINFO = 0x0040;168pub const SA_SIGINFO = 0x0040;
169169
170pub const PATH_MAX = 1024;170pub const PATH_MAX = 1024;
171pub const IOV_MAX = KERN_IOV_MAX;
171172
172pub const ino_t = c_ulong;173pub const ino_t = c_ulong;
173174
lib/std/os/bits/freebsd.zig+130-126
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const builtin = @import("builtin");2const builtin = @import("builtin");
8const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
...@@ -238,8 +233,10 @@ pub const CTL_DEBUG = 5;...@@ -238,8 +233,10 @@ pub const CTL_DEBUG = 5;
238233
239pub const KERN_PROC = 14; // struct: process entries234pub const KERN_PROC = 14; // struct: process entries
240pub const KERN_PROC_PATHNAME = 12; // path to executable235pub const KERN_PROC_PATHNAME = 12; // path to executable
236pub const KERN_IOV_MAX = 35;
241237
242pub const PATH_MAX = 1024;238pub const PATH_MAX = 1024;
239pub const IOV_MAX = KERN_IOV_MAX;
243240
244pub const STDIN_FILENO = 0;241pub const STDIN_FILENO = 0;
245pub const STDOUT_FILENO = 1;242pub const STDOUT_FILENO = 1;
...@@ -885,127 +882,134 @@ pub usingnamespace switch (builtin.target.cpu.arch) {...@@ -885,127 +882,134 @@ pub usingnamespace switch (builtin.target.cpu.arch) {
885 else => struct {},882 else => struct {},
886};883};
887884
888pub const EPERM = 1; // Operation not permitted885pub const E = enum(u16) {
889pub const ENOENT = 2; // No such file or directory886 /// No error occurred.
890pub const ESRCH = 3; // No such process887 SUCCESS = 0,
891pub const EINTR = 4; // Interrupted system call888
892pub const EIO = 5; // Input/output error889 PERM = 1, // Operation not permitted
893pub const ENXIO = 6; // Device not configured890 NOENT = 2, // No such file or directory
894pub const E2BIG = 7; // Argument list too long891 SRCH = 3, // No such process
895pub const ENOEXEC = 8; // Exec format error892 INTR = 4, // Interrupted system call
896pub const EBADF = 9; // Bad file descriptor893 IO = 5, // Input/output error
897pub const ECHILD = 10; // No child processes894 NXIO = 6, // Device not configured
898pub const EDEADLK = 11; // Resource deadlock avoided895 @"2BIG" = 7, // Argument list too long
899// 11 was EAGAIN896 NOEXEC = 8, // Exec format error
900pub const ENOMEM = 12; // Cannot allocate memory897 BADF = 9, // Bad file descriptor
901pub const EACCES = 13; // Permission denied898 CHILD = 10, // No child processes
902pub const EFAULT = 14; // Bad address899 DEADLK = 11, // Resource deadlock avoided
903pub const ENOTBLK = 15; // Block device required900 // 11 was AGAIN
904pub const EBUSY = 16; // Device busy901 NOMEM = 12, // Cannot allocate memory
905pub const EEXIST = 17; // File exists902 ACCES = 13, // Permission denied
906pub const EXDEV = 18; // Cross-device link903 FAULT = 14, // Bad address
907pub const ENODEV = 19; // Operation not supported by device904 NOTBLK = 15, // Block device required
908pub const ENOTDIR = 20; // Not a directory905 BUSY = 16, // Device busy
909pub const EISDIR = 21; // Is a directory906 EXIST = 17, // File exists
910pub const EINVAL = 22; // Invalid argument907 XDEV = 18, // Cross-device link
911pub const ENFILE = 23; // Too many open files in system908 NODEV = 19, // Operation not supported by device
912pub const EMFILE = 24; // Too many open files909 NOTDIR = 20, // Not a directory
913pub const ENOTTY = 25; // Inappropriate ioctl for device910 ISDIR = 21, // Is a directory
914pub const ETXTBSY = 26; // Text file busy911 INVAL = 22, // Invalid argument
915pub const EFBIG = 27; // File too large912 NFILE = 23, // Too many open files in system
916pub const ENOSPC = 28; // No space left on device913 MFILE = 24, // Too many open files
917pub const ESPIPE = 29; // Illegal seek914 NOTTY = 25, // Inappropriate ioctl for device
918pub const EROFS = 30; // Read-only filesystem915 TXTBSY = 26, // Text file busy
919pub const EMLINK = 31; // Too many links916 FBIG = 27, // File too large
920pub const EPIPE = 32; // Broken pipe917 NOSPC = 28, // No space left on device
921918 SPIPE = 29, // Illegal seek
922// math software919 ROFS = 30, // Read-only filesystem
923pub const EDOM = 33; // Numerical argument out of domain920 MLINK = 31, // Too many links
924pub const ERANGE = 34; // Result too large921 PIPE = 32, // Broken pipe
925922
926// non-blocking and interrupt i/o923 // math software
927pub const EAGAIN = 35; // Resource temporarily unavailable924 DOM = 33, // Numerical argument out of domain
928pub const EWOULDBLOCK = EAGAIN; // Operation would block925 RANGE = 34, // Result too large
929pub const EINPROGRESS = 36; // Operation now in progress926
930pub const EALREADY = 37; // Operation already in progress927 // non-blocking and interrupt i/o
931928
932// ipc/network software -- argument errors929 /// Resource temporarily unavailable
933pub const ENOTSOCK = 38; // Socket operation on non-socket930 /// This code is also used for `WOULDBLOCK`: operation would block.
934pub const EDESTADDRREQ = 39; // Destination address required931 AGAIN = 35,
935pub const EMSGSIZE = 40; // Message too long932 INPROGRESS = 36, // Operation now in progress
936pub const EPROTOTYPE = 41; // Protocol wrong type for socket933 ALREADY = 37, // Operation already in progress
937pub const ENOPROTOOPT = 42; // Protocol not available934
938pub const EPROTONOSUPPORT = 43; // Protocol not supported935 // ipc/network software -- argument errors
939pub const ESOCKTNOSUPPORT = 44; // Socket type not supported936 NOTSOCK = 38, // Socket operation on non-socket
940pub const EOPNOTSUPP = 45; // Operation not supported937 DESTADDRREQ = 39, // Destination address required
941pub const ENOTSUP = EOPNOTSUPP; // Operation not supported938 MSGSIZE = 40, // Message too long
942pub const EPFNOSUPPORT = 46; // Protocol family not supported939 PROTOTYPE = 41, // Protocol wrong type for socket
943pub const EAFNOSUPPORT = 47; // Address family not supported by protocol family940 NOPROTOOPT = 42, // Protocol not available
944pub const EADDRINUSE = 48; // Address already in use941 PROTONOSUPPORT = 43, // Protocol not supported
945pub const EADDRNOTAVAIL = 49; // Can't assign requested address942 SOCKTNOSUPPORT = 44, // Socket type not supported
946943 /// Operation not supported
947// ipc/network software -- operational errors944 /// This code is also used for `NOTSUP`.
948pub const ENETDOWN = 50; // Network is down945 OPNOTSUPP = 45,
949pub const ENETUNREACH = 51; // Network is unreachable946 PFNOSUPPORT = 46, // Protocol family not supported
950pub const ENETRESET = 52; // Network dropped connection on reset947 AFNOSUPPORT = 47, // Address family not supported by protocol family
951pub const ECONNABORTED = 53; // Software caused connection abort948 ADDRINUSE = 48, // Address already in use
952pub const ECONNRESET = 54; // Connection reset by peer949 ADDRNOTAVAIL = 49, // Can't assign requested address
953pub const ENOBUFS = 55; // No buffer space available950
954pub const EISCONN = 56; // Socket is already connected951 // ipc/network software -- operational errors
955pub const ENOTCONN = 57; // Socket is not connected952 NETDOWN = 50, // Network is down
956pub const ESHUTDOWN = 58; // Can't send after socket shutdown953 NETUNREACH = 51, // Network is unreachable
957pub const ETOOMANYREFS = 59; // Too many references: can't splice954 NETRESET = 52, // Network dropped connection on reset
958pub const ETIMEDOUT = 60; // Operation timed out955 CONNABORTED = 53, // Software caused connection abort
959pub const ECONNREFUSED = 61; // Connection refused956 CONNRESET = 54, // Connection reset by peer
960957 NOBUFS = 55, // No buffer space available
961pub const ELOOP = 62; // Too many levels of symbolic links958 ISCONN = 56, // Socket is already connected
962pub const ENAMETOOLONG = 63; // File name too long959 NOTCONN = 57, // Socket is not connected
963960 SHUTDOWN = 58, // Can't send after socket shutdown
964// should be rearranged961 TOOMANYREFS = 59, // Too many references: can't splice
965pub const EHOSTDOWN = 64; // Host is down962 TIMEDOUT = 60, // Operation timed out
966pub const EHOSTUNREACH = 65; // No route to host963 CONNREFUSED = 61, // Connection refused
967pub const ENOTEMPTY = 66; // Directory not empty964
968965 LOOP = 62, // Too many levels of symbolic links
969// quotas & mush966 NAMETOOLONG = 63, // File name too long
970pub const EPROCLIM = 67; // Too many processes967
971pub const EUSERS = 68; // Too many users968 // should be rearranged
972pub const EDQUOT = 69; // Disc quota exceeded969 HOSTDOWN = 64, // Host is down
973970 HOSTUNREACH = 65, // No route to host
974// Network File System971 NOTEMPTY = 66, // Directory not empty
975pub const ESTALE = 70; // Stale NFS file handle972
976pub const EREMOTE = 71; // Too many levels of remote in path973 // quotas & mush
977pub const EBADRPC = 72; // RPC struct is bad974 PROCLIM = 67, // Too many processes
978pub const ERPCMISMATCH = 73; // RPC version wrong975 USERS = 68, // Too many users
979pub const EPROGUNAVAIL = 74; // RPC prog. not avail976 DQUOT = 69, // Disc quota exceeded
980pub const EPROGMISMATCH = 75; // Program version wrong977
981pub const EPROCUNAVAIL = 76; // Bad procedure for program978 // Network File System
982979 STALE = 70, // Stale NFS file handle
983pub const ENOLCK = 77; // No locks available980 REMOTE = 71, // Too many levels of remote in path
984pub const ENOSYS = 78; // Function not implemented981 BADRPC = 72, // RPC struct is bad
985982 RPCMISMATCH = 73, // RPC version wrong
986pub const EFTYPE = 79; // Inappropriate file type or format983 PROGUNAVAIL = 74, // RPC prog. not avail
987pub const EAUTH = 80; // Authentication error984 PROGMISMATCH = 75, // Program version wrong
988pub const ENEEDAUTH = 81; // Need authenticator985 PROCUNAVAIL = 76, // Bad procedure for program
989pub const EIDRM = 82; // Identifier removed986
990pub const ENOMSG = 83; // No message of desired type987 NOLCK = 77, // No locks available
991pub const EOVERFLOW = 84; // Value too large to be stored in data type988 NOSYS = 78, // Function not implemented
992pub const ECANCELED = 85; // Operation canceled989
993pub const EILSEQ = 86; // Illegal byte sequence990 FTYPE = 79, // Inappropriate file type or format
994pub const ENOATTR = 87; // Attribute not found991 AUTH = 80, // Authentication error
995992 NEEDAUTH = 81, // Need authenticator
996pub const EDOOFUS = 88; // Programming error993 IDRM = 82, // Identifier removed
997994 NOMSG = 83, // No message of desired type
998pub const EBADMSG = 89; // Bad message995 OVERFLOW = 84, // Value too large to be stored in data type
999pub const EMULTIHOP = 90; // Multihop attempted996 CANCELED = 85, // Operation canceled
1000pub const ENOLINK = 91; // Link has been severed997 ILSEQ = 86, // Illegal byte sequence
1001pub const EPROTO = 92; // Protocol error998 NOATTR = 87, // Attribute not found
1002999
1003pub const ENOTCAPABLE = 93; // Capabilities insufficient1000 DOOFUS = 88, // Programming error
1004pub const ECAPMODE = 94; // Not permitted in capability mode1001
1005pub const ENOTRECOVERABLE = 95; // State not recoverable1002 BADMSG = 89, // Bad message
1006pub const EOWNERDEAD = 96; // Previous owner died1003 MULTIHOP = 90, // Multihop attempted
10071004 NOLINK = 91, // Link has been severed
1008pub const ELAST = 96; // Must be equal largest errno1005 PROTO = 92, // Protocol error
1006
1007 NOTCAPABLE = 93, // Capabilities insufficient
1008 CAPMODE = 94, // Not permitted in capability mode
1009 NOTRECOVERABLE = 95, // State not recoverable
1010 OWNERDEAD = 96, // Previous owner died
1011 _,
1012};
10091013
1010pub const MINSIGSTKSZ = switch (builtin.target.cpu.arch) {1014pub const MINSIGSTKSZ = switch (builtin.target.cpu.arch) {
1011 .i386, .x86_64 => 2048,1015 .i386, .x86_64 => 2048,
lib/std/os/bits/haiku.zig+124-124
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2020 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const maxInt = std.math.maxInt;2const maxInt = std.math.maxInt;
83
...@@ -734,125 +729,130 @@ pub const sigset_t = extern struct {...@@ -734,125 +729,130 @@ pub const sigset_t = extern struct {
734 __bits: [_SIG_WORDS]u32,729 __bits: [_SIG_WORDS]u32,
735};730};
736731
737pub const EPERM = -0x7ffffff1; // Operation not permitted732pub const E = enum(i32) {
738pub const ENOENT = -0x7fff9ffd; // No such file or directory733 /// No error occurred.
739pub const ESRCH = -0x7fff8ff3; // No such process734 SUCCESS = 0,
740pub const EINTR = -0x7ffffff6; // Interrupted system call735 PERM = -0x7ffffff1, // Operation not permitted
741pub const EIO = -0x7fffffff; // Input/output error736 NOENT = -0x7fff9ffd, // No such file or directory
742pub const ENXIO = -0x7fff8ff5; // Device not configured737 SRCH = -0x7fff8ff3, // No such process
743pub const E2BIG = -0x7fff8fff; // Argument list too long738 INTR = -0x7ffffff6, // Interrupted system call
744pub const ENOEXEC = -0x7fffecfe; // Exec format error739 IO = -0x7fffffff, // Input/output error
745pub const ECHILD = -0x7fff8ffe; // No child processes740 NXIO = -0x7fff8ff5, // Device not configured
746pub const EDEADLK = -0x7fff8ffd; // Resource deadlock avoided741 @"2BIG" = -0x7fff8fff, // Argument list too long
747pub const ENOMEM = -0x80000000; // Cannot allocate memory742 NOEXEC = -0x7fffecfe, // Exec format error
748pub const EACCES = -0x7ffffffe; // Permission denied743 CHILD = -0x7fff8ffe, // No child processes
749pub const EFAULT = -0x7fffecff; // Bad address744 DEADLK = -0x7fff8ffd, // Resource deadlock avoided
750pub const EBUSY = -0x7ffffff2; // Device busy745 NOMEM = -0x80000000, // Cannot allocate memory
751pub const EEXIST = -0x7fff9ffe; // File exists746 ACCES = -0x7ffffffe, // Permission denied
752pub const EXDEV = -0x7fff9ff5; // Cross-device link747 FAULT = -0x7fffecff, // Bad address
753pub const ENODEV = -0x7fff8ff9; // Operation not supported by device748 BUSY = -0x7ffffff2, // Device busy
754pub const ENOTDIR = -0x7fff9ffb; // Not a directory749 EXIST = -0x7fff9ffe, // File exists
755pub const EISDIR = -0x7fff9ff7; // Is a directory750 XDEV = -0x7fff9ff5, // Cross-device link
756pub const EINVAL = -0x7ffffffb; // Invalid argument751 NODEV = -0x7fff8ff9, // Operation not supported by device
757pub const ENFILE = -0x7fff8ffa; // Too many open files in system752 NOTDIR = -0x7fff9ffb, // Not a directory
758pub const EMFILE = -0x7fff9ff6; // Too many open files753 ISDIR = -0x7fff9ff7, // Is a directory
759pub const ENOTTY = -0x7fff8ff6; // Inappropriate ioctl for device754 INVAL = -0x7ffffffb, // Invalid argument
760pub const ETXTBSY = -0x7fff8fc5; // Text file busy755 NFILE = -0x7fff8ffa, // Too many open files in system
761pub const EFBIG = -0x7fff8ffc; // File too large756 MFILE = -0x7fff9ff6, // Too many open files
762pub const ENOSPC = -0x7fff9ff9; // No space left on device757 NOTTY = -0x7fff8ff6, // Inappropriate ioctl for device
763pub const ESPIPE = -0x7fff8ff4; // Illegal seek758 TXTBSY = -0x7fff8fc5, // Text file busy
764pub const EROFS = -0x7fff9ff8; // Read-only filesystem759 FBIG = -0x7fff8ffc, // File too large
765pub const EMLINK = -0x7fff8ffb; // Too many links760 NOSPC = -0x7fff9ff9, // No space left on device
766pub const EPIPE = -0x7fff9ff3; // Broken pipe761 SPIPE = -0x7fff8ff4, // Illegal seek
767pub const EBADF = -0x7fffa000; // Bad file descriptor762 ROFS = -0x7fff9ff8, // Read-only filesystem
768763 MLINK = -0x7fff8ffb, // Too many links
769// math software764 PIPE = -0x7fff9ff3, // Broken pipe
770pub const EDOM = 33; // Numerical argument out of domain765 BADF = -0x7fffa000, // Bad file descriptor
771pub const ERANGE = 34; // Result too large766
772767 // math software
773// non-blocking and interrupt i/o768 DOM = 33, // Numerical argument out of domain
774pub const EAGAIN = -0x7ffffff5;769 RANGE = 34, // Result too large
775pub const EWOULDBLOCK = -0x7ffffff5;770
776pub const EINPROGRESS = -0x7fff8fdc;771 // non-blocking and interrupt i/o
777pub const EALREADY = -0x7fff8fdb;772
778773 /// Also used for `WOULDBLOCK`.
779// ipc/network software -- argument errors774 AGAIN = -0x7ffffff5,
780pub const ENOTSOCK = 38; // Socket operation on non-socket775 INPROGRESS = -0x7fff8fdc,
781pub const EDESTADDRREQ = 39; // Destination address required776 ALREADY = -0x7fff8fdb,
782pub const EMSGSIZE = 40; // Message too long777
783pub const EPROTOTYPE = 41; // Protocol wrong type for socket778 // ipc/network software -- argument errors
784pub const ENOPROTOOPT = 42; // Protocol not available779 NOTSOCK = 38, // Socket operation on non-socket
785pub const EPROTONOSUPPORT = 43; // Protocol not supported780 DESTADDRREQ = 39, // Destination address required
786pub const ESOCKTNOSUPPORT = 44; // Socket type not supported781 MSGSIZE = 40, // Message too long
787pub const EOPNOTSUPP = 45; // Operation not supported782 PROTOTYPE = 41, // Protocol wrong type for socket
788pub const ENOTSUP = EOPNOTSUPP; // Operation not supported783 NOPROTOOPT = 42, // Protocol not available
789pub const EPFNOSUPPORT = 46; // Protocol family not supported784 PROTONOSUPPORT = 43, // Protocol not supported
790pub const EAFNOSUPPORT = 47; // Address family not supported by protocol family785 SOCKTNOSUPPORT = 44, // Socket type not supported
791pub const EADDRINUSE = 48; // Address already in use786 /// Also used for `NOTSUP`.
792pub const EADDRNOTAVAIL = 49; // Can't assign requested address787 OPNOTSUPP = 45, // Operation not supported
793788 PFNOSUPPORT = 46, // Protocol family not supported
794// ipc/network software -- operational errors789 AFNOSUPPORT = 47, // Address family not supported by protocol family
795pub const ENETDOWN = 50; // Network is down790 ADDRINUSE = 48, // Address already in use
796pub const ENETUNREACH = 51; // Network is unreachable791 ADDRNOTAVAIL = 49, // Can't assign requested address
797pub const ENETRESET = 52; // Network dropped connection on reset792
798pub const ECONNABORTED = 53; // Software caused connection abort793 // ipc/network software -- operational errors
799pub const ECONNRESET = 54; // Connection reset by peer794 NETDOWN = 50, // Network is down
800pub const ENOBUFS = 55; // No buffer space available795 NETUNREACH = 51, // Network is unreachable
801pub const EISCONN = 56; // Socket is already connected796 NETRESET = 52, // Network dropped connection on reset
802pub const ENOTCONN = 57; // Socket is not connected797 CONNABORTED = 53, // Software caused connection abort
803pub const ESHUTDOWN = 58; // Can't send after socket shutdown798 CONNRESET = 54, // Connection reset by peer
804pub const ETOOMANYREFS = 59; // Too many references: can't splice799 NOBUFS = 55, // No buffer space available
805pub const ETIMEDOUT = 60; // Operation timed out800 ISCONN = 56, // Socket is already connected
806pub const ECONNREFUSED = 61; // Connection refused801 NOTCONN = 57, // Socket is not connected
807802 SHUTDOWN = 58, // Can't send after socket shutdown
808pub const ELOOP = 62; // Too many levels of symbolic links803 TOOMANYREFS = 59, // Too many references: can't splice
809pub const ENAMETOOLONG = 63; // File name too long804 TIMEDOUT = 60, // Operation timed out
810805 CONNREFUSED = 61, // Connection refused
811// should be rearranged806
812pub const EHOSTDOWN = 64; // Host is down807 LOOP = 62, // Too many levels of symbolic links
813pub const EHOSTUNREACH = 65; // No route to host808 NAMETOOLONG = 63, // File name too long
814pub const ENOTEMPTY = 66; // Directory not empty809
815810 // should be rearranged
816// quotas & mush811 HOSTDOWN = 64, // Host is down
817pub const EPROCLIM = 67; // Too many processes812 HOSTUNREACH = 65, // No route to host
818pub const EUSERS = 68; // Too many users813 NOTEMPTY = 66, // Directory not empty
819pub const EDQUOT = 69; // Disc quota exceeded814
820815 // quotas & mush
821// Network File System816 PROCLIM = 67, // Too many processes
822pub const ESTALE = 70; // Stale NFS file handle817 USERS = 68, // Too many users
823pub const EREMOTE = 71; // Too many levels of remote in path818 DQUOT = 69, // Disc quota exceeded
824pub const EBADRPC = 72; // RPC struct is bad819
825pub const ERPCMISMATCH = 73; // RPC version wrong820 // Network File System
826pub const EPROGUNAVAIL = 74; // RPC prog. not avail821 STALE = 70, // Stale NFS file handle
827pub const EPROGMISMATCH = 75; // Program version wrong822 REMOTE = 71, // Too many levels of remote in path
828pub const EPROCUNAVAIL = 76; // Bad procedure for program823 BADRPC = 72, // RPC struct is bad
829824 RPCMISMATCH = 73, // RPC version wrong
830pub const ENOLCK = 77; // No locks available825 PROGUNAVAIL = 74, // RPC prog. not avail
831pub const ENOSYS = 78; // Function not implemented826 PROGMISMATCH = 75, // Program version wrong
832827 PROCUNAVAIL = 76, // Bad procedure for program
833pub const EFTYPE = 79; // Inappropriate file type or format828
834pub const EAUTH = 80; // Authentication error829 NOLCK = 77, // No locks available
835pub const ENEEDAUTH = 81; // Need authenticator830 NOSYS = 78, // Function not implemented
836pub const EIDRM = 82; // Identifier removed831
837pub const ENOMSG = 83; // No message of desired type832 FTYPE = 79, // Inappropriate file type or format
838pub const EOVERFLOW = 84; // Value too large to be stored in data type833 AUTH = 80, // Authentication error
839pub const ECANCELED = 85; // Operation canceled834 NEEDAUTH = 81, // Need authenticator
840pub const EILSEQ = 86; // Illegal byte sequence835 IDRM = 82, // Identifier removed
841pub const ENOATTR = 87; // Attribute not found836 NOMSG = 83, // No message of desired type
842837 OVERFLOW = 84, // Value too large to be stored in data type
843pub const EDOOFUS = 88; // Programming error838 CANCELED = 85, // Operation canceled
844839 ILSEQ = 86, // Illegal byte sequence
845pub const EBADMSG = 89; // Bad message840 NOATTR = 87, // Attribute not found
846pub const EMULTIHOP = 90; // Multihop attempted841
847pub const ENOLINK = 91; // Link has been severed842 DOOFUS = 88, // Programming error
848pub const EPROTO = 92; // Protocol error843
849844 BADMSG = 89, // Bad message
850pub const ENOTCAPABLE = 93; // Capabilities insufficient845 MULTIHOP = 90, // Multihop attempted
851pub const ECAPMODE = 94; // Not permitted in capability mode846 NOLINK = 91, // Link has been severed
852pub const ENOTRECOVERABLE = 95; // State not recoverable847 PROTO = 92, // Protocol error
853pub const EOWNERDEAD = 96; // Previous owner died848
854849 NOTCAPABLE = 93, // Capabilities insufficient
855pub const ELAST = 96; // Must be equal largest errno850 CAPMODE = 94, // Not permitted in capability mode
851 NOTRECOVERABLE = 95, // State not recoverable
852 OWNERDEAD = 96, // Previous owner died
853
854 _,
855};
856856
857pub const MINSIGSTKSZ = switch (builtin.cpu.arch) {857pub const MINSIGSTKSZ = switch (builtin.cpu.arch) {
858 .i386, .x86_64 => 2048,858 .i386, .x86_64 => 2048,
lib/std/os/bits/linux.zig+17-9
...@@ -1,17 +1,12 @@...@@ -1,17 +1,12 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const maxInt = std.math.maxInt;2const maxInt = std.math.maxInt;
8const arch = @import("builtin").target.cpu.arch;3const arch = @import("builtin").target.cpu.arch;
9pub usingnamespace @import("posix.zig");4pub usingnamespace @import("posix.zig");
105
11pub usingnamespace switch (arch) {6pub const E = switch (arch) {
12 .mips, .mipsel => @import("linux/errno-mips.zig"),7 .mips, .mipsel => @import("linux/errno/mips.zig").E,
13 .sparc, .sparcel, .sparcv9 => @import("linux/errno-sparc.zig"),8 .sparc, .sparcel, .sparcv9 => @import("linux/errno/sparc.zig").E,
14 else => @import("linux/errno-generic.zig"),9 else => @import("linux/errno/generic.zig").E,
15};10};
1611
17pub usingnamespace switch (arch) {12pub usingnamespace switch (arch) {
...@@ -887,6 +882,7 @@ pub const CLONE_VM = 0x00000100;...@@ -887,6 +882,7 @@ pub const CLONE_VM = 0x00000100;
887pub const CLONE_FS = 0x00000200;882pub const CLONE_FS = 0x00000200;
888pub const CLONE_FILES = 0x00000400;883pub const CLONE_FILES = 0x00000400;
889pub const CLONE_SIGHAND = 0x00000800;884pub const CLONE_SIGHAND = 0x00000800;
885pub const CLONE_PIDFD = 0x00001000;
890pub const CLONE_PTRACE = 0x00002000;886pub const CLONE_PTRACE = 0x00002000;
891pub const CLONE_VFORK = 0x00004000;887pub const CLONE_VFORK = 0x00004000;
892pub const CLONE_PARENT = 0x00008000;888pub const CLONE_PARENT = 0x00008000;
...@@ -911,6 +907,8 @@ pub const CLONE_IO = 0x80000000;...@@ -911,6 +907,8 @@ pub const CLONE_IO = 0x80000000;
911907
912/// Clear any signal handler and reset to SIG_DFL.908/// Clear any signal handler and reset to SIG_DFL.
913pub const CLONE_CLEAR_SIGHAND = 0x100000000;909pub const CLONE_CLEAR_SIGHAND = 0x100000000;
910/// Clone into a specific cgroup given the right permissions.
911pub const CLONE_INTO_CGROUP = 0x200000000;
914912
915// cloning flags intersect with CSIGNAL so can be used with unshare and clone3 syscalls only.913// cloning flags intersect with CSIGNAL so can be used with unshare and clone3 syscalls only.
916914
...@@ -1131,6 +1129,9 @@ pub const SIG_IGN = @intToPtr(?Sigaction.sigaction_fn, 1);...@@ -1131,6 +1129,9 @@ pub const SIG_IGN = @intToPtr(?Sigaction.sigaction_fn, 1);
11311129
1132pub const empty_sigset = [_]u32{0} ** @typeInfo(sigset_t).Array.len;1130pub const empty_sigset = [_]u32{0} ** @typeInfo(sigset_t).Array.len;
11331131
1132pub const SFD_CLOEXEC = O_CLOEXEC;
1133pub const SFD_NONBLOCK = O_NONBLOCK;
1134
1134pub const signalfd_siginfo = extern struct {1135pub const signalfd_siginfo = extern struct {
1135 signo: u32,1136 signo: u32,
1136 errno: i32,1137 errno: i32,
...@@ -1659,6 +1660,13 @@ pub const io_uring_cqe = extern struct {...@@ -1659,6 +1660,13 @@ pub const io_uring_cqe = extern struct {
1659 /// result code for this event1660 /// result code for this event
1660 res: i32,1661 res: i32,
1661 flags: u32,1662 flags: u32,
1663
1664 pub fn err(self: io_uring_cqe) E {
1665 if (self.res > -4096 and self.res < 0) {
1666 return @intToEnum(E, -self.res);
1667 }
1668 return .SUCCESS;
1669 }
1662};1670};
16631671
1664// io_uring_cqe.flags1672// io_uring_cqe.flags
lib/std/os/bits/linux/arm-eabi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// arm-eabi-specific declarations that are intended to be imported into the POSIX namespace.1// arm-eabi-specific declarations that are intended to be imported into the POSIX namespace.
7const std = @import("../../../std.zig");2const std = @import("../../../std.zig");
8const linux = std.os.linux;3const linux = std.os.linux;
lib/std/os/bits/linux/arm64.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// arm64-specific declarations that are intended to be imported into the POSIX namespace.1// arm64-specific declarations that are intended to be imported into the POSIX namespace.
7// This does include Linux-only APIs.2// This does include Linux-only APIs.
83
lib/std/os/bits/linux/errno-generic.zig deleted-462
...@@ -1,462 +0,0 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6/// Operation not permitted
7pub const EPERM = 1;
8
9/// No such file or directory
10pub const ENOENT = 2;
11
12/// No such process
13pub const ESRCH = 3;
14
15/// Interrupted system call
16pub const EINTR = 4;
17
18/// I/O error
19pub const EIO = 5;
20
21/// No such device or address
22pub const ENXIO = 6;
23
24/// Arg list too long
25pub const E2BIG = 7;
26
27/// Exec format error
28pub const ENOEXEC = 8;
29
30/// Bad file number
31pub const EBADF = 9;
32
33/// No child processes
34pub const ECHILD = 10;
35
36/// Try again
37pub const EAGAIN = 11;
38
39/// Out of memory
40pub const ENOMEM = 12;
41
42/// Permission denied
43pub const EACCES = 13;
44
45/// Bad address
46pub const EFAULT = 14;
47
48/// Block device required
49pub const ENOTBLK = 15;
50
51/// Device or resource busy
52pub const EBUSY = 16;
53
54/// File exists
55pub const EEXIST = 17;
56
57/// Cross-device link
58pub const EXDEV = 18;
59
60/// No such device
61pub const ENODEV = 19;
62
63/// Not a directory
64pub const ENOTDIR = 20;
65
66/// Is a directory
67pub const EISDIR = 21;
68
69/// Invalid argument
70pub const EINVAL = 22;
71
72/// File table overflow
73pub const ENFILE = 23;
74
75/// Too many open files
76pub const EMFILE = 24;
77
78/// Not a typewriter
79pub const ENOTTY = 25;
80
81/// Text file busy
82pub const ETXTBSY = 26;
83
84/// File too large
85pub const EFBIG = 27;
86
87/// No space left on device
88pub const ENOSPC = 28;
89
90/// Illegal seek
91pub const ESPIPE = 29;
92
93/// Read-only file system
94pub const EROFS = 30;
95
96/// Too many links
97pub const EMLINK = 31;
98
99/// Broken pipe
100pub const EPIPE = 32;
101
102/// Math argument out of domain of func
103pub const EDOM = 33;
104
105/// Math result not representable
106pub const ERANGE = 34;
107
108/// Resource deadlock would occur
109pub const EDEADLK = 35;
110
111/// File name too long
112pub const ENAMETOOLONG = 36;
113
114/// No record locks available
115pub const ENOLCK = 37;
116
117/// Function not implemented
118pub const ENOSYS = 38;
119
120/// Directory not empty
121pub const ENOTEMPTY = 39;
122
123/// Too many symbolic links encountered
124pub const ELOOP = 40;
125
126/// Operation would block
127pub const EWOULDBLOCK = EAGAIN;
128
129/// No message of desired type
130pub const ENOMSG = 42;
131
132/// Identifier removed
133pub const EIDRM = 43;
134
135/// Channel number out of range
136pub const ECHRNG = 44;
137
138/// Level 2 not synchronized
139pub const EL2NSYNC = 45;
140
141/// Level 3 halted
142pub const EL3HLT = 46;
143
144/// Level 3 reset
145pub const EL3RST = 47;
146
147/// Link number out of range
148pub const ELNRNG = 48;
149
150/// Protocol driver not attached
151pub const EUNATCH = 49;
152
153/// No CSI structure available
154pub const ENOCSI = 50;
155
156/// Level 2 halted
157pub const EL2HLT = 51;
158
159/// Invalid exchange
160pub const EBADE = 52;
161
162/// Invalid request descriptor
163pub const EBADR = 53;
164
165/// Exchange full
166pub const EXFULL = 54;
167
168/// No anode
169pub const ENOANO = 55;
170
171/// Invalid request code
172pub const EBADRQC = 56;
173
174/// Invalid slot
175pub const EBADSLT = 57;
176
177/// Bad font file format
178pub const EBFONT = 59;
179
180/// Device not a stream
181pub const ENOSTR = 60;
182
183/// No data available
184pub const ENODATA = 61;
185
186/// Timer expired
187pub const ETIME = 62;
188
189/// Out of streams resources
190pub const ENOSR = 63;
191
192/// Machine is not on the network
193pub const ENONET = 64;
194
195/// Package not installed
196pub const ENOPKG = 65;
197
198/// Object is remote
199pub const EREMOTE = 66;
200
201/// Link has been severed
202pub const ENOLINK = 67;
203
204/// Advertise error
205pub const EADV = 68;
206
207/// Srmount error
208pub const ESRMNT = 69;
209
210/// Communication error on send
211pub const ECOMM = 70;
212
213/// Protocol error
214pub const EPROTO = 71;
215
216/// Multihop attempted
217pub const EMULTIHOP = 72;
218
219/// RFS specific error
220pub const EDOTDOT = 73;
221
222/// Not a data message
223pub const EBADMSG = 74;
224
225/// Value too large for defined data type
226pub const EOVERFLOW = 75;
227
228/// Name not unique on network
229pub const ENOTUNIQ = 76;
230
231/// File descriptor in bad state
232pub const EBADFD = 77;
233
234/// Remote address changed
235pub const EREMCHG = 78;
236
237/// Can not access a needed shared library
238pub const ELIBACC = 79;
239
240/// Accessing a corrupted shared library
241pub const ELIBBAD = 80;
242
243/// .lib section in a.out corrupted
244pub const ELIBSCN = 81;
245
246/// Attempting to link in too many shared libraries
247pub const ELIBMAX = 82;
248
249/// Cannot exec a shared library directly
250pub const ELIBEXEC = 83;
251
252/// Illegal byte sequence
253pub const EILSEQ = 84;
254
255/// Interrupted system call should be restarted
256pub const ERESTART = 85;
257
258/// Streams pipe error
259pub const ESTRPIPE = 86;
260
261/// Too many users
262pub const EUSERS = 87;
263
264/// Socket operation on non-socket
265pub const ENOTSOCK = 88;
266
267/// Destination address required
268pub const EDESTADDRREQ = 89;
269
270/// Message too long
271pub const EMSGSIZE = 90;
272
273/// Protocol wrong type for socket
274pub const EPROTOTYPE = 91;
275
276/// Protocol not available
277pub const ENOPROTOOPT = 92;
278
279/// Protocol not supported
280pub const EPROTONOSUPPORT = 93;
281
282/// Socket type not supported
283pub const ESOCKTNOSUPPORT = 94;
284
285/// Operation not supported on transport endpoint
286pub const EOPNOTSUPP = 95;
287pub const ENOTSUP = EOPNOTSUPP;
288
289/// Protocol family not supported
290pub const EPFNOSUPPORT = 96;
291
292/// Address family not supported by protocol
293pub const EAFNOSUPPORT = 97;
294
295/// Address already in use
296pub const EADDRINUSE = 98;
297
298/// Cannot assign requested address
299pub const EADDRNOTAVAIL = 99;
300
301/// Network is down
302pub const ENETDOWN = 100;
303
304/// Network is unreachable
305pub const ENETUNREACH = 101;
306
307/// Network dropped connection because of reset
308pub const ENETRESET = 102;
309
310/// Software caused connection abort
311pub const ECONNABORTED = 103;
312
313/// Connection reset by peer
314pub const ECONNRESET = 104;
315
316/// No buffer space available
317pub const ENOBUFS = 105;
318
319/// Transport endpoint is already connected
320pub const EISCONN = 106;
321
322/// Transport endpoint is not connected
323pub const ENOTCONN = 107;
324
325/// Cannot send after transport endpoint shutdown
326pub const ESHUTDOWN = 108;
327
328/// Too many references: cannot splice
329pub const ETOOMANYREFS = 109;
330
331/// Connection timed out
332pub const ETIMEDOUT = 110;
333
334/// Connection refused
335pub const ECONNREFUSED = 111;
336
337/// Host is down
338pub const EHOSTDOWN = 112;
339
340/// No route to host
341pub const EHOSTUNREACH = 113;
342
343/// Operation already in progress
344pub const EALREADY = 114;
345
346/// Operation now in progress
347pub const EINPROGRESS = 115;
348
349/// Stale NFS file handle
350pub const ESTALE = 116;
351
352/// Structure needs cleaning
353pub const EUCLEAN = 117;
354
355/// Not a XENIX named type file
356pub const ENOTNAM = 118;
357
358/// No XENIX semaphores available
359pub const ENAVAIL = 119;
360
361/// Is a named type file
362pub const EISNAM = 120;
363
364/// Remote I/O error
365pub const EREMOTEIO = 121;
366
367/// Quota exceeded
368pub const EDQUOT = 122;
369
370/// No medium found
371pub const ENOMEDIUM = 123;
372
373/// Wrong medium type
374pub const EMEDIUMTYPE = 124;
375
376/// Operation canceled
377pub const ECANCELED = 125;
378
379/// Required key not available
380pub const ENOKEY = 126;
381
382/// Key has expired
383pub const EKEYEXPIRED = 127;
384
385/// Key has been revoked
386pub const EKEYREVOKED = 128;
387
388/// Key was rejected by service
389pub const EKEYREJECTED = 129;
390
391// for robust mutexes
392
393/// Owner died
394pub const EOWNERDEAD = 130;
395
396/// State not recoverable
397pub const ENOTRECOVERABLE = 131;
398
399/// Operation not possible due to RF-kill
400pub const ERFKILL = 132;
401
402/// Memory page has hardware error
403pub const EHWPOISON = 133;
404
405// nameserver query return codes
406
407/// DNS server returned answer with no data
408pub const ENSROK = 0;
409
410/// DNS server returned answer with no data
411pub const ENSRNODATA = 160;
412
413/// DNS server claims query was misformatted
414pub const ENSRFORMERR = 161;
415
416/// DNS server returned general failure
417pub const ENSRSERVFAIL = 162;
418
419/// Domain name not found
420pub const ENSRNOTFOUND = 163;
421
422/// DNS server does not implement requested operation
423pub const ENSRNOTIMP = 164;
424
425/// DNS server refused query
426pub const ENSRREFUSED = 165;
427
428/// Misformatted DNS query
429pub const ENSRBADQUERY = 166;
430
431/// Misformatted domain name
432pub const ENSRBADNAME = 167;
433
434/// Unsupported address family
435pub const ENSRBADFAMILY = 168;
436
437/// Misformatted DNS reply
438pub const ENSRBADRESP = 169;
439
440/// Could not contact DNS servers
441pub const ENSRCONNREFUSED = 170;
442
443/// Timeout while contacting DNS servers
444pub const ENSRTIMEOUT = 171;
445
446/// End of file
447pub const ENSROF = 172;
448
449/// Error reading file
450pub const ENSRFILE = 173;
451
452/// Out of memory
453pub const ENSRNOMEM = 174;
454
455/// Application terminated lookup
456pub const ENSRDESTRUCTION = 175;
457
458/// Domain name is too long
459pub const ENSRQUERYDOMAINTOOLONG = 176;
460
461/// Domain name is too long
462pub const ENSRCNAMELOOP = 177;
lib/std/os/bits/linux/errno-mips.zig deleted-143
...@@ -1,143 +0,0 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7// These are MIPS ABI compatible.
8
9pub const EPERM = 1;
10pub const ENOENT = 2;
11pub const ESRCH = 3;
12pub const EINTR = 4;
13pub const EIO = 5;
14pub const ENXIO = 6;
15pub const E2BIG = 7;
16pub const ENOEXEC = 8;
17pub const EBADF = 9;
18pub const ECHILD = 10;
19pub const EAGAIN = 11;
20pub const ENOMEM = 12;
21pub const EACCES = 13;
22pub const EFAULT = 14;
23pub const ENOTBLK = 15;
24pub const EBUSY = 16;
25pub const EEXIST = 17;
26pub const EXDEV = 18;
27pub const ENODEV = 19;
28pub const ENOTDIR = 20;
29pub const EISDIR = 21;
30pub const EINVAL = 22;
31pub const ENFILE = 23;
32pub const EMFILE = 24;
33pub const ENOTTY = 25;
34pub const ETXTBSY = 26;
35pub const EFBIG = 27;
36pub const ENOSPC = 28;
37pub const ESPIPE = 29;
38pub const EROFS = 30;
39pub const EMLINK = 31;
40pub const EPIPE = 32;
41pub const EDOM = 33;
42pub const ERANGE = 34;
43
44pub const ENOMSG = 35;
45pub const EIDRM = 36;
46pub const ECHRNG = 37;
47pub const EL2NSYNC = 38;
48pub const EL3HLT = 39;
49pub const EL3RST = 40;
50pub const ELNRNG = 41;
51pub const EUNATCH = 42;
52pub const ENOCSI = 43;
53pub const EL2HLT = 44;
54pub const EDEADLK = 45;
55pub const ENOLCK = 46;
56pub const EBADE = 50;
57pub const EBADR = 51;
58pub const EXFULL = 52;
59pub const ENOANO = 53;
60pub const EBADRQC = 54;
61pub const EBADSLT = 55;
62pub const EDEADLOCK = 56;
63pub const EBFONT = 59;
64pub const ENOSTR = 60;
65pub const ENODATA = 61;
66pub const ETIME = 62;
67pub const ENOSR = 63;
68pub const ENONET = 64;
69pub const ENOPKG = 65;
70pub const EREMOTE = 66;
71pub const ENOLINK = 67;
72pub const EADV = 68;
73pub const ESRMNT = 69;
74pub const ECOMM = 70;
75pub const EPROTO = 71;
76pub const EDOTDOT = 73;
77pub const EMULTIHOP = 74;
78pub const EBADMSG = 77;
79pub const ENAMETOOLONG = 78;
80pub const EOVERFLOW = 79;
81pub const ENOTUNIQ = 80;
82pub const EBADFD = 81;
83pub const EREMCHG = 82;
84pub const ELIBACC = 83;
85pub const ELIBBAD = 84;
86pub const ELIBSCN = 85;
87pub const ELIBMAX = 86;
88pub const ELIBEXEC = 87;
89pub const EILSEQ = 88;
90pub const ENOSYS = 89;
91pub const ELOOP = 90;
92pub const ERESTART = 91;
93pub const ESTRPIPE = 92;
94pub const ENOTEMPTY = 93;
95pub const EUSERS = 94;
96pub const ENOTSOCK = 95;
97pub const EDESTADDRREQ = 96;
98pub const EMSGSIZE = 97;
99pub const EPROTOTYPE = 98;
100pub const ENOPROTOOPT = 99;
101pub const EPROTONOSUPPORT = 120;
102pub const ESOCKTNOSUPPORT = 121;
103pub const EOPNOTSUPP = 122;
104pub const ENOTSUP = EOPNOTSUPP;
105pub const EPFNOSUPPORT = 123;
106pub const EAFNOSUPPORT = 124;
107pub const EADDRINUSE = 125;
108pub const EADDRNOTAVAIL = 126;
109pub const ENETDOWN = 127;
110pub const ENETUNREACH = 128;
111pub const ENETRESET = 129;
112pub const ECONNABORTED = 130;
113pub const ECONNRESET = 131;
114pub const ENOBUFS = 132;
115pub const EISCONN = 133;
116pub const ENOTCONN = 134;
117pub const EUCLEAN = 135;
118pub const ENOTNAM = 137;
119pub const ENAVAIL = 138;
120pub const EISNAM = 139;
121pub const EREMOTEIO = 140;
122pub const ESHUTDOWN = 143;
123pub const ETOOMANYREFS = 144;
124pub const ETIMEDOUT = 145;
125pub const ECONNREFUSED = 146;
126pub const EHOSTDOWN = 147;
127pub const EHOSTUNREACH = 148;
128pub const EWOULDBLOCK = EAGAIN;
129pub const EALREADY = 149;
130pub const EINPROGRESS = 150;
131pub const ESTALE = 151;
132pub const ECANCELED = 158;
133pub const ENOMEDIUM = 159;
134pub const EMEDIUMTYPE = 160;
135pub const ENOKEY = 161;
136pub const EKEYEXPIRED = 162;
137pub const EKEYREVOKED = 163;
138pub const EKEYREJECTED = 164;
139pub const EOWNERDEAD = 165;
140pub const ENOTRECOVERABLE = 166;
141pub const ERFKILL = 167;
142pub const EHWPOISON = 168;
143pub const EDQUOT = 1133;
lib/std/os/bits/linux/errno-sparc.zig deleted-145
...@@ -1,145 +0,0 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7// These match the SunOS error numbering scheme.
8
9pub const EPERM = 1;
10pub const ENOENT = 2;
11pub const ESRCH = 3;
12pub const EINTR = 4;
13pub const EIO = 5;
14pub const ENXIO = 6;
15pub const E2BIG = 7;
16pub const ENOEXEC = 8;
17pub const EBADF = 9;
18pub const ECHILD = 10;
19pub const EAGAIN = 11;
20pub const ENOMEM = 12;
21pub const EACCES = 13;
22pub const EFAULT = 14;
23pub const ENOTBLK = 15;
24pub const EBUSY = 16;
25pub const EEXIST = 17;
26pub const EXDEV = 18;
27pub const ENODEV = 19;
28pub const ENOTDIR = 20;
29pub const EISDIR = 21;
30pub const EINVAL = 22;
31pub const ENFILE = 23;
32pub const EMFILE = 24;
33pub const ENOTTY = 25;
34pub const ETXTBSY = 26;
35pub const EFBIG = 27;
36pub const ENOSPC = 28;
37pub const ESPIPE = 29;
38pub const EROFS = 30;
39pub const EMLINK = 31;
40pub const EPIPE = 32;
41pub const EDOM = 33;
42pub const ERANGE = 34;
43
44pub const EWOULDBLOCK = EAGAIN;
45pub const EINPROGRESS = 36;
46pub const EALREADY = 37;
47pub const ENOTSOCK = 38;
48pub const EDESTADDRREQ = 39;
49pub const EMSGSIZE = 40;
50pub const EPROTOTYPE = 41;
51pub const ENOPROTOOPT = 42;
52pub const EPROTONOSUPPORT = 43;
53pub const ESOCKTNOSUPPORT = 44;
54pub const EOPNOTSUPP = 45;
55pub const ENOTSUP = EOPNOTSUPP;
56pub const EPFNOSUPPORT = 46;
57pub const EAFNOSUPPORT = 47;
58pub const EADDRINUSE = 48;
59pub const EADDRNOTAVAIL = 49;
60pub const ENETDOWN = 50;
61pub const ENETUNREACH = 51;
62pub const ENETRESET = 52;
63pub const ECONNABORTED = 53;
64pub const ECONNRESET = 54;
65pub const ENOBUFS = 55;
66pub const EISCONN = 56;
67pub const ENOTCONN = 57;
68pub const ESHUTDOWN = 58;
69pub const ETOOMANYREFS = 59;
70pub const ETIMEDOUT = 60;
71pub const ECONNREFUSED = 61;
72pub const ELOOP = 62;
73pub const ENAMETOOLONG = 63;
74pub const EHOSTDOWN = 64;
75pub const EHOSTUNREACH = 65;
76pub const ENOTEMPTY = 66;
77pub const EPROCLIM = 67;
78pub const EUSERS = 68;
79pub const EDQUOT = 69;
80pub const ESTALE = 70;
81pub const EREMOTE = 71;
82pub const ENOSTR = 72;
83pub const ETIME = 73;
84pub const ENOSR = 74;
85pub const ENOMSG = 75;
86pub const EBADMSG = 76;
87pub const EIDRM = 77;
88pub const EDEADLK = 78;
89pub const ENOLCK = 79;
90pub const ENONET = 80;
91pub const ERREMOTE = 81;
92pub const ENOLINK = 82;
93pub const EADV = 83;
94pub const ESRMNT = 84;
95pub const ECOMM = 85;
96pub const EPROTO = 86;
97pub const EMULTIHOP = 87;
98pub const EDOTDOT = 88;
99pub const EREMCHG = 89;
100pub const ENOSYS = 90;
101pub const ESTRPIPE = 91;
102pub const EOVERFLOW = 92;
103pub const EBADFD = 93;
104pub const ECHRNG = 94;
105pub const EL2NSYNC = 95;
106pub const EL3HLT = 96;
107pub const EL3RST = 97;
108pub const ELNRNG = 98;
109pub const EUNATCH = 99;
110pub const ENOCSI = 100;
111pub const EL2HLT = 101;
112pub const EBADE = 102;
113pub const EBADR = 103;
114pub const EXFULL = 104;
115pub const ENOANO = 105;
116pub const EBADRQC = 106;
117pub const EBADSLT = 107;
118pub const EDEADLOCK = 108;
119pub const EBFONT = 109;
120pub const ELIBEXEC = 110;
121pub const ENODATA = 111;
122pub const ELIBBAD = 112;
123pub const ENOPKG = 113;
124pub const ELIBACC = 114;
125pub const ENOTUNIQ = 115;
126pub const ERESTART = 116;
127pub const EUCLEAN = 117;
128pub const ENOTNAM = 118;
129pub const ENAVAIL = 119;
130pub const EISNAM = 120;
131pub const EREMOTEIO = 121;
132pub const EILSEQ = 122;
133pub const ELIBMAX = 123;
134pub const ELIBSCN = 124;
135pub const ENOMEDIUM = 125;
136pub const EMEDIUMTYPE = 126;
137pub const ECANCELED = 127;
138pub const ENOKEY = 128;
139pub const EKEYEXPIRED = 129;
140pub const EKEYREVOKED = 130;
141pub const EKEYREJECTED = 131;
142pub const EOWNERDEAD = 132;
143pub const ENOTRECOVERABLE = 133;
144pub const ERFKILL = 134;
145pub const EHWPOISON = 135;
lib/std/os/bits/linux/errno/generic.zig created+460
...@@ -0,0 +1,460 @@
1pub const E = enum(u16) {
2 /// No error occurred.
3 /// Same code used for `NSROK`.
4 SUCCESS = 0,
5
6 /// Operation not permitted
7 PERM = 1,
8
9 /// No such file or directory
10 NOENT = 2,
11
12 /// No such process
13 SRCH = 3,
14
15 /// Interrupted system call
16 INTR = 4,
17
18 /// I/O error
19 IO = 5,
20
21 /// No such device or address
22 NXIO = 6,
23
24 /// Arg list too long
25 @"2BIG" = 7,
26
27 /// Exec format error
28 NOEXEC = 8,
29
30 /// Bad file number
31 BADF = 9,
32
33 /// No child processes
34 CHILD = 10,
35
36 /// Try again
37 /// Also means: WOULDBLOCK: operation would block
38 AGAIN = 11,
39
40 /// Out of memory
41 NOMEM = 12,
42
43 /// Permission denied
44 ACCES = 13,
45
46 /// Bad address
47 FAULT = 14,
48
49 /// Block device required
50 NOTBLK = 15,
51
52 /// Device or resource busy
53 BUSY = 16,
54
55 /// File exists
56 EXIST = 17,
57
58 /// Cross-device link
59 XDEV = 18,
60
61 /// No such device
62 NODEV = 19,
63
64 /// Not a directory
65 NOTDIR = 20,
66
67 /// Is a directory
68 ISDIR = 21,
69
70 /// Invalid argument
71 INVAL = 22,
72
73 /// File table overflow
74 NFILE = 23,
75
76 /// Too many open files
77 MFILE = 24,
78
79 /// Not a typewriter
80 NOTTY = 25,
81
82 /// Text file busy
83 TXTBSY = 26,
84
85 /// File too large
86 FBIG = 27,
87
88 /// No space left on device
89 NOSPC = 28,
90
91 /// Illegal seek
92 SPIPE = 29,
93
94 /// Read-only file system
95 ROFS = 30,
96
97 /// Too many links
98 MLINK = 31,
99
100 /// Broken pipe
101 PIPE = 32,
102
103 /// Math argument out of domain of func
104 DOM = 33,
105
106 /// Math result not representable
107 RANGE = 34,
108
109 /// Resource deadlock would occur
110 DEADLK = 35,
111
112 /// File name too long
113 NAMETOOLONG = 36,
114
115 /// No record locks available
116 NOLCK = 37,
117
118 /// Function not implemented
119 NOSYS = 38,
120
121 /// Directory not empty
122 NOTEMPTY = 39,
123
124 /// Too many symbolic links encountered
125 LOOP = 40,
126
127 /// No message of desired type
128 NOMSG = 42,
129
130 /// Identifier removed
131 IDRM = 43,
132
133 /// Channel number out of range
134 CHRNG = 44,
135
136 /// Level 2 not synchronized
137 L2NSYNC = 45,
138
139 /// Level 3 halted
140 L3HLT = 46,
141
142 /// Level 3 reset
143 L3RST = 47,
144
145 /// Link number out of range
146 LNRNG = 48,
147
148 /// Protocol driver not attached
149 UNATCH = 49,
150
151 /// No CSI structure available
152 NOCSI = 50,
153
154 /// Level 2 halted
155 L2HLT = 51,
156
157 /// Invalid exchange
158 BADE = 52,
159
160 /// Invalid request descriptor
161 BADR = 53,
162
163 /// Exchange full
164 XFULL = 54,
165
166 /// No anode
167 NOANO = 55,
168
169 /// Invalid request code
170 BADRQC = 56,
171
172 /// Invalid slot
173 BADSLT = 57,
174
175 /// Bad font file format
176 BFONT = 59,
177
178 /// Device not a stream
179 NOSTR = 60,
180
181 /// No data available
182 NODATA = 61,
183
184 /// Timer expired
185 TIME = 62,
186
187 /// Out of streams resources
188 NOSR = 63,
189
190 /// Machine is not on the network
191 NONET = 64,
192
193 /// Package not installed
194 NOPKG = 65,
195
196 /// Object is remote
197 REMOTE = 66,
198
199 /// Link has been severed
200 NOLINK = 67,
201
202 /// Advertise error
203 ADV = 68,
204
205 /// Srmount error
206 SRMNT = 69,
207
208 /// Communication error on send
209 COMM = 70,
210
211 /// Protocol error
212 PROTO = 71,
213
214 /// Multihop attempted
215 MULTIHOP = 72,
216
217 /// RFS specific error
218 DOTDOT = 73,
219
220 /// Not a data message
221 BADMSG = 74,
222
223 /// Value too large for defined data type
224 OVERFLOW = 75,
225
226 /// Name not unique on network
227 NOTUNIQ = 76,
228
229 /// File descriptor in bad state
230 BADFD = 77,
231
232 /// Remote address changed
233 REMCHG = 78,
234
235 /// Can not access a needed shared library
236 LIBACC = 79,
237
238 /// Accessing a corrupted shared library
239 LIBBAD = 80,
240
241 /// .lib section in a.out corrupted
242 LIBSCN = 81,
243
244 /// Attempting to link in too many shared libraries
245 LIBMAX = 82,
246
247 /// Cannot exec a shared library directly
248 LIBEXEC = 83,
249
250 /// Illegal byte sequence
251 ILSEQ = 84,
252
253 /// Interrupted system call should be restarted
254 RESTART = 85,
255
256 /// Streams pipe error
257 STRPIPE = 86,
258
259 /// Too many users
260 USERS = 87,
261
262 /// Socket operation on non-socket
263 NOTSOCK = 88,
264
265 /// Destination address required
266 DESTADDRREQ = 89,
267
268 /// Message too long
269 MSGSIZE = 90,
270
271 /// Protocol wrong type for socket
272 PROTOTYPE = 91,
273
274 /// Protocol not available
275 NOPROTOOPT = 92,
276
277 /// Protocol not supported
278 PROTONOSUPPORT = 93,
279
280 /// Socket type not supported
281 SOCKTNOSUPPORT = 94,
282
283 /// Operation not supported on transport endpoint
284 /// This code also means `NOTSUP`.
285 OPNOTSUPP = 95,
286
287 /// Protocol family not supported
288 PFNOSUPPORT = 96,
289
290 /// Address family not supported by protocol
291 AFNOSUPPORT = 97,
292
293 /// Address already in use
294 ADDRINUSE = 98,
295
296 /// Cannot assign requested address
297 ADDRNOTAVAIL = 99,
298
299 /// Network is down
300 NETDOWN = 100,
301
302 /// Network is unreachable
303 NETUNREACH = 101,
304
305 /// Network dropped connection because of reset
306 NETRESET = 102,
307
308 /// Software caused connection abort
309 CONNABORTED = 103,
310
311 /// Connection reset by peer
312 CONNRESET = 104,
313
314 /// No buffer space available
315 NOBUFS = 105,
316
317 /// Transport endpoint is already connected
318 ISCONN = 106,
319
320 /// Transport endpoint is not connected
321 NOTCONN = 107,
322
323 /// Cannot send after transport endpoint shutdown
324 SHUTDOWN = 108,
325
326 /// Too many references: cannot splice
327 TOOMANYREFS = 109,
328
329 /// Connection timed out
330 TIMEDOUT = 110,
331
332 /// Connection refused
333 CONNREFUSED = 111,
334
335 /// Host is down
336 HOSTDOWN = 112,
337
338 /// No route to host
339 HOSTUNREACH = 113,
340
341 /// Operation already in progress
342 ALREADY = 114,
343
344 /// Operation now in progress
345 INPROGRESS = 115,
346
347 /// Stale NFS file handle
348 STALE = 116,
349
350 /// Structure needs cleaning
351 UCLEAN = 117,
352
353 /// Not a XENIX named type file
354 NOTNAM = 118,
355
356 /// No XENIX semaphores available
357 NAVAIL = 119,
358
359 /// Is a named type file
360 ISNAM = 120,
361
362 /// Remote I/O error
363 REMOTEIO = 121,
364
365 /// Quota exceeded
366 DQUOT = 122,
367
368 /// No medium found
369 NOMEDIUM = 123,
370
371 /// Wrong medium type
372 MEDIUMTYPE = 124,
373
374 /// Operation canceled
375 CANCELED = 125,
376
377 /// Required key not available
378 NOKEY = 126,
379
380 /// Key has expired
381 KEYEXPIRED = 127,
382
383 /// Key has been revoked
384 KEYREVOKED = 128,
385
386 /// Key was rejected by service
387 KEYREJECTED = 129,
388
389 // for robust mutexes
390
391 /// Owner died
392 OWNERDEAD = 130,
393
394 /// State not recoverable
395 NOTRECOVERABLE = 131,
396
397 /// Operation not possible due to RF-kill
398 RFKILL = 132,
399
400 /// Memory page has hardware error
401 HWPOISON = 133,
402
403 // nameserver query return codes
404
405 /// DNS server returned answer with no data
406 NSRNODATA = 160,
407
408 /// DNS server claims query was misformatted
409 NSRFORMERR = 161,
410
411 /// DNS server returned general failure
412 NSRSERVFAIL = 162,
413
414 /// Domain name not found
415 NSRNOTFOUND = 163,
416
417 /// DNS server does not implement requested operation
418 NSRNOTIMP = 164,
419
420 /// DNS server refused query
421 NSRREFUSED = 165,
422
423 /// Misformatted DNS query
424 NSRBADQUERY = 166,
425
426 /// Misformatted domain name
427 NSRBADNAME = 167,
428
429 /// Unsupported address family
430 NSRBADFAMILY = 168,
431
432 /// Misformatted DNS reply
433 NSRBADRESP = 169,
434
435 /// Could not contact DNS servers
436 NSRCONNREFUSED = 170,
437
438 /// Timeout while contacting DNS servers
439 NSRTIMEOUT = 171,
440
441 /// End of file
442 NSROF = 172,
443
444 /// Error reading file
445 NSRFILE = 173,
446
447 /// Out of memory
448 NSRNOMEM = 174,
449
450 /// Application terminated lookup
451 NSRDESTRUCTION = 175,
452
453 /// Domain name is too long
454 NSRQUERYDOMAINTOOLONG = 176,
455
456 /// Domain name is too long
457 NSRCNAMELOOP = 177,
458
459 _,
460};
lib/std/os/bits/linux/errno/mips.zig created+141
...@@ -0,0 +1,141 @@
1//! These are MIPS ABI compatible.
2pub const E = enum(i32) {
3 /// No error occurred.
4 SUCCESS = 0,
5
6 PERM = 1,
7 NOENT = 2,
8 SRCH = 3,
9 INTR = 4,
10 IO = 5,
11 NXIO = 6,
12 @"2BIG" = 7,
13 NOEXEC = 8,
14 BADF = 9,
15 CHILD = 10,
16 /// Also used for WOULDBLOCK.
17 AGAIN = 11,
18 NOMEM = 12,
19 ACCES = 13,
20 FAULT = 14,
21 NOTBLK = 15,
22 BUSY = 16,
23 EXIST = 17,
24 XDEV = 18,
25 NODEV = 19,
26 NOTDIR = 20,
27 ISDIR = 21,
28 INVAL = 22,
29 NFILE = 23,
30 MFILE = 24,
31 NOTTY = 25,
32 TXTBSY = 26,
33 FBIG = 27,
34 NOSPC = 28,
35 SPIPE = 29,
36 ROFS = 30,
37 MLINK = 31,
38 PIPE = 32,
39 DOM = 33,
40 RANGE = 34,
41
42 NOMSG = 35,
43 IDRM = 36,
44 CHRNG = 37,
45 L2NSYNC = 38,
46 L3HLT = 39,
47 L3RST = 40,
48 LNRNG = 41,
49 UNATCH = 42,
50 NOCSI = 43,
51 L2HLT = 44,
52 DEADLK = 45,
53 NOLCK = 46,
54 BADE = 50,
55 BADR = 51,
56 XFULL = 52,
57 NOANO = 53,
58 BADRQC = 54,
59 BADSLT = 55,
60 DEADLOCK = 56,
61 BFONT = 59,
62 NOSTR = 60,
63 NODATA = 61,
64 TIME = 62,
65 NOSR = 63,
66 NONET = 64,
67 NOPKG = 65,
68 REMOTE = 66,
69 NOLINK = 67,
70 ADV = 68,
71 SRMNT = 69,
72 COMM = 70,
73 PROTO = 71,
74 DOTDOT = 73,
75 MULTIHOP = 74,
76 BADMSG = 77,
77 NAMETOOLONG = 78,
78 OVERFLOW = 79,
79 NOTUNIQ = 80,
80 BADFD = 81,
81 REMCHG = 82,
82 LIBACC = 83,
83 LIBBAD = 84,
84 LIBSCN = 85,
85 LIBMAX = 86,
86 LIBEXEC = 87,
87 ILSEQ = 88,
88 NOSYS = 89,
89 LOOP = 90,
90 RESTART = 91,
91 STRPIPE = 92,
92 NOTEMPTY = 93,
93 USERS = 94,
94 NOTSOCK = 95,
95 DESTADDRREQ = 96,
96 MSGSIZE = 97,
97 PROTOTYPE = 98,
98 NOPROTOOPT = 99,
99 PROTONOSUPPORT = 120,
100 SOCKTNOSUPPORT = 121,
101 OPNOTSUPP = 122,
102 PFNOSUPPORT = 123,
103 AFNOSUPPORT = 124,
104 ADDRINUSE = 125,
105 ADDRNOTAVAIL = 126,
106 NETDOWN = 127,
107 NETUNREACH = 128,
108 NETRESET = 129,
109 CONNABORTED = 130,
110 CONNRESET = 131,
111 NOBUFS = 132,
112 ISCONN = 133,
113 NOTCONN = 134,
114 UCLEAN = 135,
115 NOTNAM = 137,
116 NAVAIL = 138,
117 ISNAM = 139,
118 REMOTEIO = 140,
119 SHUTDOWN = 143,
120 TOOMANYREFS = 144,
121 TIMEDOUT = 145,
122 CONNREFUSED = 146,
123 HOSTDOWN = 147,
124 HOSTUNREACH = 148,
125 ALREADY = 149,
126 INPROGRESS = 150,
127 STALE = 151,
128 CANCELED = 158,
129 NOMEDIUM = 159,
130 MEDIUMTYPE = 160,
131 NOKEY = 161,
132 KEYEXPIRED = 162,
133 KEYREVOKED = 163,
134 KEYREJECTED = 164,
135 OWNERDEAD = 165,
136 NOTRECOVERABLE = 166,
137 RFKILL = 167,
138 HWPOISON = 168,
139 DQUOT = 1133,
140 _,
141};
lib/std/os/bits/linux/errno/sparc.zig created+144
...@@ -0,0 +1,144 @@
1//! These match the SunOS error numbering scheme.
2pub const E = enum(i32) {
3 /// No error occurred.
4 SUCCESS = 0,
5
6 PERM = 1,
7 NOENT = 2,
8 SRCH = 3,
9 INTR = 4,
10 IO = 5,
11 NXIO = 6,
12 @"2BIG" = 7,
13 NOEXEC = 8,
14 BADF = 9,
15 CHILD = 10,
16 /// Also used for WOULDBLOCK
17 AGAIN = 11,
18 NOMEM = 12,
19 ACCES = 13,
20 FAULT = 14,
21 NOTBLK = 15,
22 BUSY = 16,
23 EXIST = 17,
24 XDEV = 18,
25 NODEV = 19,
26 NOTDIR = 20,
27 ISDIR = 21,
28 INVAL = 22,
29 NFILE = 23,
30 MFILE = 24,
31 NOTTY = 25,
32 TXTBSY = 26,
33 FBIG = 27,
34 NOSPC = 28,
35 SPIPE = 29,
36 ROFS = 30,
37 MLINK = 31,
38 PIPE = 32,
39 DOM = 33,
40 RANGE = 34,
41
42 INPROGRESS = 36,
43 ALREADY = 37,
44 NOTSOCK = 38,
45 DESTADDRREQ = 39,
46 MSGSIZE = 40,
47 PROTOTYPE = 41,
48 NOPROTOOPT = 42,
49 PROTONOSUPPORT = 43,
50 SOCKTNOSUPPORT = 44,
51 /// Also used for NOTSUP
52 OPNOTSUPP = 45,
53 PFNOSUPPORT = 46,
54 AFNOSUPPORT = 47,
55 ADDRINUSE = 48,
56 ADDRNOTAVAIL = 49,
57 NETDOWN = 50,
58 NETUNREACH = 51,
59 NETRESET = 52,
60 CONNABORTED = 53,
61 CONNRESET = 54,
62 NOBUFS = 55,
63 ISCONN = 56,
64 NOTCONN = 57,
65 SHUTDOWN = 58,
66 TOOMANYREFS = 59,
67 TIMEDOUT = 60,
68 CONNREFUSED = 61,
69 LOOP = 62,
70 NAMETOOLONG = 63,
71 HOSTDOWN = 64,
72 HOSTUNREACH = 65,
73 NOTEMPTY = 66,
74 PROCLIM = 67,
75 USERS = 68,
76 DQUOT = 69,
77 STALE = 70,
78 REMOTE = 71,
79 NOSTR = 72,
80 TIME = 73,
81 NOSR = 74,
82 NOMSG = 75,
83 BADMSG = 76,
84 IDRM = 77,
85 DEADLK = 78,
86 NOLCK = 79,
87 NONET = 80,
88 RREMOTE = 81,
89 NOLINK = 82,
90 ADV = 83,
91 SRMNT = 84,
92 COMM = 85,
93 PROTO = 86,
94 MULTIHOP = 87,
95 DOTDOT = 88,
96 REMCHG = 89,
97 NOSYS = 90,
98 STRPIPE = 91,
99 OVERFLOW = 92,
100 BADFD = 93,
101 CHRNG = 94,
102 L2NSYNC = 95,
103 L3HLT = 96,
104 L3RST = 97,
105 LNRNG = 98,
106 UNATCH = 99,
107 NOCSI = 100,
108 L2HLT = 101,
109 BADE = 102,
110 BADR = 103,
111 XFULL = 104,
112 NOANO = 105,
113 BADRQC = 106,
114 BADSLT = 107,
115 DEADLOCK = 108,
116 BFONT = 109,
117 LIBEXEC = 110,
118 NODATA = 111,
119 LIBBAD = 112,
120 NOPKG = 113,
121 LIBACC = 114,
122 NOTUNIQ = 115,
123 RESTART = 116,
124 UCLEAN = 117,
125 NOTNAM = 118,
126 NAVAIL = 119,
127 ISNAM = 120,
128 REMOTEIO = 121,
129 ILSEQ = 122,
130 LIBMAX = 123,
131 LIBSCN = 124,
132 NOMEDIUM = 125,
133 MEDIUMTYPE = 126,
134 CANCELED = 127,
135 NOKEY = 128,
136 KEYEXPIRED = 129,
137 KEYREVOKED = 130,
138 KEYREJECTED = 131,
139 OWNERDEAD = 132,
140 NOTRECOVERABLE = 133,
141 RFKILL = 134,
142 HWPOISON = 135,
143 _,
144};
lib/std/os/bits/linux/i386.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// i386-specific declarations that are intended to be imported into the POSIX namespace.1// i386-specific declarations that are intended to be imported into the POSIX namespace.
7// This does include Linux-only APIs.2// This does include Linux-only APIs.
83
lib/std/os/bits/linux/mips.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../../std.zig");1const std = @import("../../../std.zig");
7const linux = std.os.linux;2const linux = std.os.linux;
8const socklen_t = linux.socklen_t;3const socklen_t = linux.socklen_t;
lib/std/os/bits/linux/netlink.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("../linux.zig");1usingnamespace @import("../linux.zig");
72
8/// Routing/device hook3/// Routing/device hook
lib/std/os/bits/linux/powerpc.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../../../std.zig");1const std = @import("../../../std.zig");
8const linux = std.os.linux;2const linux = std.os.linux;
9const socklen_t = linux.socklen_t;3const socklen_t = linux.socklen_t;
lib/std/os/bits/linux/powerpc64.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../../../std.zig");1const std = @import("../../../std.zig");
8const linux = std.os.linux;2const linux = std.os.linux;
9const socklen_t = linux.socklen_t;3const socklen_t = linux.socklen_t;
lib/std/os/bits/linux/prctl.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7pub const PR = enum(i32) {1pub const PR = enum(i32) {
8 SET_PDEATHSIG = 1,2 SET_PDEATHSIG = 1,
9 GET_PDEATHSIG = 2,3 GET_PDEATHSIG = 2,
lib/std/os/bits/linux/riscv64.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// riscv64-specific declarations that are intended to be imported into the POSIX namespace.1// riscv64-specific declarations that are intended to be imported into the POSIX namespace.
7const std = @import("../../../std.zig");2const std = @import("../../../std.zig");
8const uid_t = std.os.linux.uid_t;3const uid_t = std.os.linux.uid_t;
lib/std/os/bits/linux/securebits.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7fn issecure_mask(comptime x: comptime_int) comptime_int {1fn issecure_mask(comptime x: comptime_int) comptime_int {
8 return 1 << x;2 return 1 << x;
9}3}
lib/std/os/bits/linux/x86_64.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// x86-64-specific declarations that are intended to be imported into the POSIX namespace.1// x86-64-specific declarations that are intended to be imported into the POSIX namespace.
7const std = @import("../../../std.zig");2const std = @import("../../../std.zig");
8const pid_t = linux.pid_t;3const pid_t = linux.pid_t;
lib/std/os/bits/linux/xdp.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("../linux.zig");1usingnamespace @import("../linux.zig");
72
8pub const XDP_SHARED_UMEM = (1 << 0);3pub const XDP_SHARED_UMEM = (1 << 0);
lib/std/os/bits/netbsd.zig+140-139
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
...@@ -405,8 +400,10 @@ pub const CTL_DEBUG = 5;...@@ -405,8 +400,10 @@ pub const CTL_DEBUG = 5;
405400
406pub const KERN_PROC_ARGS = 48; // struct: process argv/env401pub const KERN_PROC_ARGS = 48; // struct: process argv/env
407pub const KERN_PROC_PATHNAME = 5; // path to executable402pub const KERN_PROC_PATHNAME = 5; // path to executable
403pub const KERN_IOV_MAX = 38;
408404
409pub const PATH_MAX = 1024;405pub const PATH_MAX = 1024;
406pub const IOV_MAX = KERN_IOV_MAX;
410407
411pub const STDIN_FILENO = 0;408pub const STDIN_FILENO = 0;
412pub const STDOUT_FILENO = 1;409pub const STDOUT_FILENO = 1;
...@@ -931,140 +928,144 @@ pub const ucontext_t = extern struct {...@@ -931,140 +928,144 @@ pub const ucontext_t = extern struct {
931 ]u32,928 ]u32,
932};929};
933930
934pub const EPERM = 1; // Operation not permitted931pub const E = enum(u16) {
935pub const ENOENT = 2; // No such file or directory932 /// No error occurred.
936pub const ESRCH = 3; // No such process933 SUCCESS = 0,
937pub const EINTR = 4; // Interrupted system call934 PERM = 1, // Operation not permitted
938pub const EIO = 5; // Input/output error935 NOENT = 2, // No such file or directory
939pub const ENXIO = 6; // Device not configured936 SRCH = 3, // No such process
940pub const E2BIG = 7; // Argument list too long937 INTR = 4, // Interrupted system call
941pub const ENOEXEC = 8; // Exec format error938 IO = 5, // Input/output error
942pub const EBADF = 9; // Bad file descriptor939 NXIO = 6, // Device not configured
943pub const ECHILD = 10; // No child processes940 @"2BIG" = 7, // Argument list too long
944pub const EDEADLK = 11; // Resource deadlock avoided941 NOEXEC = 8, // Exec format error
945// 11 was EAGAIN942 BADF = 9, // Bad file descriptor
946pub const ENOMEM = 12; // Cannot allocate memory943 CHILD = 10, // No child processes
947pub const EACCES = 13; // Permission denied944 DEADLK = 11, // Resource deadlock avoided
948pub const EFAULT = 14; // Bad address945 // 11 was AGAIN
949pub const ENOTBLK = 15; // Block device required946 NOMEM = 12, // Cannot allocate memory
950pub const EBUSY = 16; // Device busy947 ACCES = 13, // Permission denied
951pub const EEXIST = 17; // File exists948 FAULT = 14, // Bad address
952pub const EXDEV = 18; // Cross-device link949 NOTBLK = 15, // Block device required
953pub const ENODEV = 19; // Operation not supported by device950 BUSY = 16, // Device busy
954pub const ENOTDIR = 20; // Not a directory951 EXIST = 17, // File exists
955pub const EISDIR = 21; // Is a directory952 XDEV = 18, // Cross-device link
956pub const EINVAL = 22; // Invalid argument953 NODEV = 19, // Operation not supported by device
957pub const ENFILE = 23; // Too many open files in system954 NOTDIR = 20, // Not a directory
958pub const EMFILE = 24; // Too many open files955 ISDIR = 21, // Is a directory
959pub const ENOTTY = 25; // Inappropriate ioctl for device956 INVAL = 22, // Invalid argument
960pub const ETXTBSY = 26; // Text file busy957 NFILE = 23, // Too many open files in system
961pub const EFBIG = 27; // File too large958 MFILE = 24, // Too many open files
962pub const ENOSPC = 28; // No space left on device959 NOTTY = 25, // Inappropriate ioctl for device
963pub const ESPIPE = 29; // Illegal seek960 TXTBSY = 26, // Text file busy
964pub const EROFS = 30; // Read-only file system961 FBIG = 27, // File too large
965pub const EMLINK = 31; // Too many links962 NOSPC = 28, // No space left on device
966pub const EPIPE = 32; // Broken pipe963 SPIPE = 29, // Illegal seek
967964 ROFS = 30, // Read-only file system
968// math software965 MLINK = 31, // Too many links
969pub const EDOM = 33; // Numerical argument out of domain966 PIPE = 32, // Broken pipe
970pub const ERANGE = 34; // Result too large or too small967
971968 // math software
972// non-blocking and interrupt i/o969 DOM = 33, // Numerical argument out of domain
973pub const EAGAIN = 35; // Resource temporarily unavailable970 RANGE = 34, // Result too large or too small
974pub const EWOULDBLOCK = EAGAIN; // Operation would block971
975pub const EINPROGRESS = 36; // Operation now in progress972 // non-blocking and interrupt i/o
976pub const EALREADY = 37; // Operation already in progress973 // also: WOULDBLOCK: operation would block
977974 AGAIN = 35, // Resource temporarily unavailable
978// ipc/network software -- argument errors975 INPROGRESS = 36, // Operation now in progress
979pub const ENOTSOCK = 38; // Socket operation on non-socket976 ALREADY = 37, // Operation already in progress
980pub const EDESTADDRREQ = 39; // Destination address required977
981pub const EMSGSIZE = 40; // Message too long978 // ipc/network software -- argument errors
982pub const EPROTOTYPE = 41; // Protocol wrong type for socket979 NOTSOCK = 38, // Socket operation on non-socket
983pub const ENOPROTOOPT = 42; // Protocol option not available980 DESTADDRREQ = 39, // Destination address required
984pub const EPROTONOSUPPORT = 43; // Protocol not supported981 MSGSIZE = 40, // Message too long
985pub const ESOCKTNOSUPPORT = 44; // Socket type not supported982 PROTOTYPE = 41, // Protocol wrong type for socket
986pub const EOPNOTSUPP = 45; // Operation not supported983 NOPROTOOPT = 42, // Protocol option not available
987pub const EPFNOSUPPORT = 46; // Protocol family not supported984 PROTONOSUPPORT = 43, // Protocol not supported
988pub const EAFNOSUPPORT = 47; // Address family not supported by protocol family985 SOCKTNOSUPPORT = 44, // Socket type not supported
989pub const EADDRINUSE = 48; // Address already in use986 OPNOTSUPP = 45, // Operation not supported
990pub const EADDRNOTAVAIL = 49; // Can't assign requested address987 PFNOSUPPORT = 46, // Protocol family not supported
991988 AFNOSUPPORT = 47, // Address family not supported by protocol family
992// ipc/network software -- operational errors989 ADDRINUSE = 48, // Address already in use
993pub const ENETDOWN = 50; // Network is down990 ADDRNOTAVAIL = 49, // Can't assign requested address
994pub const ENETUNREACH = 51; // Network is unreachable991
995pub const ENETRESET = 52; // Network dropped connection on reset992 // ipc/network software -- operational errors
996pub const ECONNABORTED = 53; // Software caused connection abort993 NETDOWN = 50, // Network is down
997pub const ECONNRESET = 54; // Connection reset by peer994 NETUNREACH = 51, // Network is unreachable
998pub const ENOBUFS = 55; // No buffer space available995 NETRESET = 52, // Network dropped connection on reset
999pub const EISCONN = 56; // Socket is already connected996 CONNABORTED = 53, // Software caused connection abort
1000pub const ENOTCONN = 57; // Socket is not connected997 CONNRESET = 54, // Connection reset by peer
1001pub const ESHUTDOWN = 58; // Can't send after socket shutdown998 NOBUFS = 55, // No buffer space available
1002pub const ETOOMANYREFS = 59; // Too many references: can't splice999 ISCONN = 56, // Socket is already connected
1003pub const ETIMEDOUT = 60; // Operation timed out1000 NOTCONN = 57, // Socket is not connected
1004pub const ECONNREFUSED = 61; // Connection refused1001 SHUTDOWN = 58, // Can't send after socket shutdown
10051002 TOOMANYREFS = 59, // Too many references: can't splice
1006pub const ELOOP = 62; // Too many levels of symbolic links1003 TIMEDOUT = 60, // Operation timed out
1007pub const ENAMETOOLONG = 63; // File name too long1004 CONNREFUSED = 61, // Connection refused
10081005
1009// should be rearranged1006 LOOP = 62, // Too many levels of symbolic links
1010pub const EHOSTDOWN = 64; // Host is down1007 NAMETOOLONG = 63, // File name too long
1011pub const EHOSTUNREACH = 65; // No route to host1008
1012pub const ENOTEMPTY = 66; // Directory not empty1009 // should be rearranged
10131010 HOSTDOWN = 64, // Host is down
1014// quotas & mush1011 HOSTUNREACH = 65, // No route to host
1015pub const EPROCLIM = 67; // Too many processes1012 NOTEMPTY = 66, // Directory not empty
1016pub const EUSERS = 68; // Too many users1013
1017pub const EDQUOT = 69; // Disc quota exceeded1014 // quotas & mush
10181015 PROCLIM = 67, // Too many processes
1019// Network File System1016 USERS = 68, // Too many users
1020pub const ESTALE = 70; // Stale NFS file handle1017 DQUOT = 69, // Disc quota exceeded
1021pub const EREMOTE = 71; // Too many levels of remote in path1018
1022pub const EBADRPC = 72; // RPC struct is bad1019 // Network File System
1023pub const ERPCMISMATCH = 73; // RPC version wrong1020 STALE = 70, // Stale NFS file handle
1024pub const EPROGUNAVAIL = 74; // RPC prog. not avail1021 REMOTE = 71, // Too many levels of remote in path
1025pub const EPROGMISMATCH = 75; // Program version wrong1022 BADRPC = 72, // RPC struct is bad
1026pub const EPROCUNAVAIL = 76; // Bad procedure for program1023 RPCMISMATCH = 73, // RPC version wrong
10271024 PROGUNAVAIL = 74, // RPC prog. not avail
1028pub const ENOLCK = 77; // No locks available1025 PROGMISMATCH = 75, // Program version wrong
1029pub const ENOSYS = 78; // Function not implemented1026 PROCUNAVAIL = 76, // Bad procedure for program
10301027
1031pub const EFTYPE = 79; // Inappropriate file type or format1028 NOLCK = 77, // No locks available
1032pub const EAUTH = 80; // Authentication error1029 NOSYS = 78, // Function not implemented
1033pub const ENEEDAUTH = 81; // Need authenticator1030
10341031 FTYPE = 79, // Inappropriate file type or format
1035// SystemV IPC1032 AUTH = 80, // Authentication error
1036pub const EIDRM = 82; // Identifier removed1033 NEEDAUTH = 81, // Need authenticator
1037pub const ENOMSG = 83; // No message of desired type1034
1038pub const EOVERFLOW = 84; // Value too large to be stored in data type1035 // SystemV IPC
10391036 IDRM = 82, // Identifier removed
1040// Wide/multibyte-character handling, ISO/IEC 9899/AMD1:19951037 NOMSG = 83, // No message of desired type
1041pub const EILSEQ = 85; // Illegal byte sequence1038 OVERFLOW = 84, // Value too large to be stored in data type
10421039
1043// From IEEE Std 1003.1-20011040 // Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995
1044// Base, Realtime, Threads or Thread Priority Scheduling option errors1041 ILSEQ = 85, // Illegal byte sequence
1045pub const ENOTSUP = 86; // Not supported1042
10461043 // From IEEE Std 1003.1-2001
1047// Realtime option errors1044 // Base, Realtime, Threads or Thread Priority Scheduling option errors
1048pub const ECANCELED = 87; // Operation canceled1045 NOTSUP = 86, // Not supported
10491046
1050// Realtime, XSI STREAMS option errors1047 // Realtime option errors
1051pub const EBADMSG = 88; // Bad or Corrupt message1048 CANCELED = 87, // Operation canceled
10521049
1053// XSI STREAMS option errors1050 // Realtime, XSI STREAMS option errors
1054pub const ENODATA = 89; // No message available1051 BADMSG = 88, // Bad or Corrupt message
1055pub const ENOSR = 90; // No STREAM resources1052
1056pub const ENOSTR = 91; // Not a STREAM1053 // XSI STREAMS option errors
1057pub const ETIME = 92; // STREAM ioctl timeout1054 NODATA = 89, // No message available
10581055 NOSR = 90, // No STREAM resources
1059// File system extended attribute errors1056 NOSTR = 91, // Not a STREAM
1060pub const ENOATTR = 93; // Attribute not found1057 TIME = 92, // STREAM ioctl timeout
10611058
1062// Realtime, XSI STREAMS option errors1059 // File system extended attribute errors
1063pub const EMULTIHOP = 94; // Multihop attempted1060 NOATTR = 93, // Attribute not found
1064pub const ENOLINK = 95; // Link has been severed1061
1065pub const EPROTO = 96; // Protocol error1062 // Realtime, XSI STREAMS option errors
10661063 MULTIHOP = 94, // Multihop attempted
1067pub const ELAST = 96; // Must equal largest errno1064 NOLINK = 95, // Link has been severed
1065 PROTO = 96, // Protocol error
1066
1067 _,
1068};
10681069
1069pub const MINSIGSTKSZ = 8192;1070pub const MINSIGSTKSZ = 8192;
1070pub const SIGSTKSZ = MINSIGSTKSZ + 32768;1071pub const SIGSTKSZ = MINSIGSTKSZ + 32768;
lib/std/os/bits/openbsd.zig+124-124
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
...@@ -295,6 +290,7 @@ pub const AI_NUMERICSERV = 16;...@@ -295,6 +290,7 @@ pub const AI_NUMERICSERV = 16;
295pub const AI_ADDRCONFIG = 64;290pub const AI_ADDRCONFIG = 64;
296291
297pub const PATH_MAX = 1024;292pub const PATH_MAX = 1024;
293pub const IOV_MAX = 1024;
298294
299pub const STDIN_FILENO = 0;295pub const STDIN_FILENO = 0;
300pub const STDOUT_FILENO = 1;296pub const STDOUT_FILENO = 1;
...@@ -824,125 +820,129 @@ pub usingnamespace switch (builtin.target.cpu.arch) {...@@ -824,125 +820,129 @@ pub usingnamespace switch (builtin.target.cpu.arch) {
824pub const sigset_t = c_uint;820pub const sigset_t = c_uint;
825pub const empty_sigset: sigset_t = 0;821pub const empty_sigset: sigset_t = 0;
826822
827pub const EPERM = 1; // Operation not permitted823pub const E = enum(u16) {
828pub const ENOENT = 2; // No such file or directory824 /// No error occurred.
829pub const ESRCH = 3; // No such process825 SUCCESS = 0,
830pub const EINTR = 4; // Interrupted system call826 PERM = 1, // Operation not permitted
831pub const EIO = 5; // Input/output error827 NOENT = 2, // No such file or directory
832pub const ENXIO = 6; // Device not configured828 SRCH = 3, // No such process
833pub const E2BIG = 7; // Argument list too long829 INTR = 4, // Interrupted system call
834pub const ENOEXEC = 8; // Exec format error830 IO = 5, // Input/output error
835pub const EBADF = 9; // Bad file descriptor831 NXIO = 6, // Device not configured
836pub const ECHILD = 10; // No child processes832 @"2BIG" = 7, // Argument list too long
837pub const EDEADLK = 11; // Resource deadlock avoided833 NOEXEC = 8, // Exec format error
838// 11 was EAGAIN834 BADF = 9, // Bad file descriptor
839pub const ENOMEM = 12; // Cannot allocate memory835 CHILD = 10, // No child processes
840pub const EACCES = 13; // Permission denied836 DEADLK = 11, // Resource deadlock avoided
841pub const EFAULT = 14; // Bad address837 // 11 was AGAIN
842pub const ENOTBLK = 15; // Block device required838 NOMEM = 12, // Cannot allocate memory
843pub const EBUSY = 16; // Device busy839 ACCES = 13, // Permission denied
844pub const EEXIST = 17; // File exists840 FAULT = 14, // Bad address
845pub const EXDEV = 18; // Cross-device link841 NOTBLK = 15, // Block device required
846pub const ENODEV = 19; // Operation not supported by device842 BUSY = 16, // Device busy
847pub const ENOTDIR = 20; // Not a directory843 EXIST = 17, // File exists
848pub const EISDIR = 21; // Is a directory844 XDEV = 18, // Cross-device link
849pub const EINVAL = 22; // Invalid argument845 NODEV = 19, // Operation not supported by device
850pub const ENFILE = 23; // Too many open files in system846 NOTDIR = 20, // Not a directory
851pub const EMFILE = 24; // Too many open files847 ISDIR = 21, // Is a directory
852pub const ENOTTY = 25; // Inappropriate ioctl for device848 INVAL = 22, // Invalid argument
853pub const ETXTBSY = 26; // Text file busy849 NFILE = 23, // Too many open files in system
854pub const EFBIG = 27; // File too large850 MFILE = 24, // Too many open files
855pub const ENOSPC = 28; // No space left on device851 NOTTY = 25, // Inappropriate ioctl for device
856pub const ESPIPE = 29; // Illegal seek852 TXTBSY = 26, // Text file busy
857pub const EROFS = 30; // Read-only file system853 FBIG = 27, // File too large
858pub const EMLINK = 31; // Too many links854 NOSPC = 28, // No space left on device
859pub const EPIPE = 32; // Broken pipe855 SPIPE = 29, // Illegal seek
860856 ROFS = 30, // Read-only file system
861// math software857 MLINK = 31, // Too many links
862pub const EDOM = 33; // Numerical argument out of domain858 PIPE = 32, // Broken pipe
863pub const ERANGE = 34; // Result too large or too small859
864860 // math software
865// non-blocking and interrupt i/o861 DOM = 33, // Numerical argument out of domain
866pub const EAGAIN = 35; // Resource temporarily unavailable862 RANGE = 34, // Result too large or too small
867pub const EWOULDBLOCK = EAGAIN; // Operation would block863
868pub const EINPROGRESS = 36; // Operation now in progress864 // non-blocking and interrupt i/o
869pub const EALREADY = 37; // Operation already in progress865 // also: WOULDBLOCK: operation would block
870866 AGAIN = 35, // Resource temporarily unavailable
871// ipc/network software -- argument errors867 INPROGRESS = 36, // Operation now in progress
872pub const ENOTSOCK = 38; // Socket operation on non-socket868 ALREADY = 37, // Operation already in progress
873pub const EDESTADDRREQ = 39; // Destination address required869
874pub const EMSGSIZE = 40; // Message too long870 // ipc/network software -- argument errors
875pub const EPROTOTYPE = 41; // Protocol wrong type for socket871 NOTSOCK = 38, // Socket operation on non-socket
876pub const ENOPROTOOPT = 42; // Protocol option not available872 DESTADDRREQ = 39, // Destination address required
877pub const EPROTONOSUPPORT = 43; // Protocol not supported873 MSGSIZE = 40, // Message too long
878pub const ESOCKTNOSUPPORT = 44; // Socket type not supported874 PROTOTYPE = 41, // Protocol wrong type for socket
879pub const EOPNOTSUPP = 45; // Operation not supported875 NOPROTOOPT = 42, // Protocol option not available
880pub const EPFNOSUPPORT = 46; // Protocol family not supported876 PROTONOSUPPORT = 43, // Protocol not supported
881pub const EAFNOSUPPORT = 47; // Address family not supported by protocol family877 SOCKTNOSUPPORT = 44, // Socket type not supported
882pub const EADDRINUSE = 48; // Address already in use878 OPNOTSUPP = 45, // Operation not supported
883pub const EADDRNOTAVAIL = 49; // Can't assign requested address879 PFNOSUPPORT = 46, // Protocol family not supported
884880 AFNOSUPPORT = 47, // Address family not supported by protocol family
885// ipc/network software -- operational errors881 ADDRINUSE = 48, // Address already in use
886pub const ENETDOWN = 50; // Network is down882 ADDRNOTAVAIL = 49, // Can't assign requested address
887pub const ENETUNREACH = 51; // Network is unreachable883
888pub const ENETRESET = 52; // Network dropped connection on reset884 // ipc/network software -- operational errors
889pub const ECONNABORTED = 53; // Software caused connection abort885 NETDOWN = 50, // Network is down
890pub const ECONNRESET = 54; // Connection reset by peer886 NETUNREACH = 51, // Network is unreachable
891pub const ENOBUFS = 55; // No buffer space available887 NETRESET = 52, // Network dropped connection on reset
892pub const EISCONN = 56; // Socket is already connected888 CONNABORTED = 53, // Software caused connection abort
893pub const ENOTCONN = 57; // Socket is not connected889 CONNRESET = 54, // Connection reset by peer
894pub const ESHUTDOWN = 58; // Can't send after socket shutdown890 NOBUFS = 55, // No buffer space available
895pub const ETOOMANYREFS = 59; // Too many references: can't splice891 ISCONN = 56, // Socket is already connected
896pub const ETIMEDOUT = 60; // Operation timed out892 NOTCONN = 57, // Socket is not connected
897pub const ECONNREFUSED = 61; // Connection refused893 SHUTDOWN = 58, // Can't send after socket shutdown
898894 TOOMANYREFS = 59, // Too many references: can't splice
899pub const ELOOP = 62; // Too many levels of symbolic links895 TIMEDOUT = 60, // Operation timed out
900pub const ENAMETOOLONG = 63; // File name too long896 CONNREFUSED = 61, // Connection refused
901897
902// should be rearranged898 LOOP = 62, // Too many levels of symbolic links
903pub const EHOSTDOWN = 64; // Host is down899 NAMETOOLONG = 63, // File name too long
904pub const EHOSTUNREACH = 65; // No route to host900
905pub const ENOTEMPTY = 66; // Directory not empty901 // should be rearranged
906902 HOSTDOWN = 64, // Host is down
907// quotas & mush903 HOSTUNREACH = 65, // No route to host
908pub const EPROCLIM = 67; // Too many processes904 NOTEMPTY = 66, // Directory not empty
909pub const EUSERS = 68; // Too many users905
910pub const EDQUOT = 69; // Disc quota exceeded906 // quotas & mush
911907 PROCLIM = 67, // Too many processes
912// Network File System908 USERS = 68, // Too many users
913pub const ESTALE = 70; // Stale NFS file handle909 DQUOT = 69, // Disc quota exceeded
914pub const EREMOTE = 71; // Too many levels of remote in path910
915pub const EBADRPC = 72; // RPC struct is bad911 // Network File System
916pub const ERPCMISMATCH = 73; // RPC version wrong912 STALE = 70, // Stale NFS file handle
917pub const EPROGUNAVAIL = 74; // RPC prog. not avail913 REMOTE = 71, // Too many levels of remote in path
918pub const EPROGMISMATCH = 75; // Program version wrong914 BADRPC = 72, // RPC struct is bad
919pub const EPROCUNAVAIL = 76; // Bad procedure for program915 RPCMISMATCH = 73, // RPC version wrong
920916 PROGUNAVAIL = 74, // RPC prog. not avail
921pub const ENOLCK = 77; // No locks available917 PROGMISMATCH = 75, // Program version wrong
922pub const ENOSYS = 78; // Function not implemented918 PROCUNAVAIL = 76, // Bad procedure for program
923919
924pub const EFTYPE = 79; // Inappropriate file type or format920 NOLCK = 77, // No locks available
925pub const EAUTH = 80; // Authentication error921 NOSYS = 78, // Function not implemented
926pub const ENEEDAUTH = 81; // Need authenticator922
927pub const EIPSEC = 82; // IPsec processing failure923 FTYPE = 79, // Inappropriate file type or format
928pub const ENOATTR = 83; // Attribute not found924 AUTH = 80, // Authentication error
929925 NEEDAUTH = 81, // Need authenticator
930// Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995926 IPSEC = 82, // IPsec processing failure
931pub const EILSEQ = 84; // Illegal byte sequence927 NOATTR = 83, // Attribute not found
932928
933pub const ENOMEDIUM = 85; // No medium found929 // Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995
934pub const EMEDIUMTYPE = 86; // Wrong medium type930 ILSEQ = 84, // Illegal byte sequence
935pub const EOVERFLOW = 87; // Value too large to be stored in data type931
936pub const ECANCELED = 88; // Operation canceled932 NOMEDIUM = 85, // No medium found
937pub const EIDRM = 89; // Identifier removed933 MEDIUMTYPE = 86, // Wrong medium type
938pub const ENOMSG = 90; // No message of desired type934 OVERFLOW = 87, // Value too large to be stored in data type
939pub const ENOTSUP = 91; // Not supported935 CANCELED = 88, // Operation canceled
940pub const EBADMSG = 92; // Bad or Corrupt message936 IDRM = 89, // Identifier removed
941pub const ENOTRECOVERABLE = 93; // State not recoverable937 NOMSG = 90, // No message of desired type
942pub const EOWNERDEAD = 94; // Previous owner died938 NOTSUP = 91, // Not supported
943pub const EPROTO = 95; // Protocol error939 BADMSG = 92, // Bad or Corrupt message
944940 NOTRECOVERABLE = 93, // State not recoverable
945pub const ELAST = 95; // Must equal largest errno941 OWNERDEAD = 94, // Previous owner died
942 PROTO = 95, // Protocol error
943
944 _,
945};
946946
947const _MAX_PAGE_SHIFT = switch (builtin.target.cpu.arch) {947const _MAX_PAGE_SHIFT = switch (builtin.target.cpu.arch) {
948 .i386 => 12,948 .i386 => 12,
lib/std/os/bits/posix.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7pub const iovec = extern struct {1pub const iovec = extern struct {
8 iov_base: [*]u8,2 iov_base: [*]u8,
9 iov_len: usize,3 iov_len: usize,
lib/std/os/bits/wasi.zig+85-85
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Convenience types and consts used by std.os module1// Convenience types and consts used by std.os module
7const builtin = @import("builtin");2const builtin = @import("builtin");
8const posix = @import("posix.zig");3const posix = @import("posix.zig");
...@@ -76,6 +71,8 @@ pub const kernel_stat = struct {...@@ -76,6 +71,8 @@ pub const kernel_stat = struct {
76 }71 }
77};72};
7873
74pub const IOV_MAX = 1024;
75
79pub const AT_REMOVEDIR: u32 = 0x4;76pub const AT_REMOVEDIR: u32 = 0x4;
80pub const AT_FDCWD: fd_t = -2;77pub const AT_FDCWD: fd_t = -2;
8178
...@@ -109,86 +106,89 @@ pub const dirent_t = extern struct {...@@ -109,86 +106,89 @@ pub const dirent_t = extern struct {
109 d_type: filetype_t,106 d_type: filetype_t,
110};107};
111108
112pub const errno_t = u16;109pub const errno_t = enum(u16) {
113pub const ESUCCESS: errno_t = 0;110 SUCCESS = 0,
114pub const E2BIG: errno_t = 1;111 @"2BIG" = 1,
115pub const EACCES: errno_t = 2;112 ACCES = 2,
116pub const EADDRINUSE: errno_t = 3;113 ADDRINUSE = 3,
117pub const EADDRNOTAVAIL: errno_t = 4;114 ADDRNOTAVAIL = 4,
118pub const EAFNOSUPPORT: errno_t = 5;115 AFNOSUPPORT = 5,
119pub const EAGAIN: errno_t = 6;116 /// This is also the error code used for `WOULDBLOCK`.
120pub const EWOULDBLOCK = EAGAIN;117 AGAIN = 6,
121pub const EALREADY: errno_t = 7;118 ALREADY = 7,
122pub const EBADF: errno_t = 8;119 BADF = 8,
123pub const EBADMSG: errno_t = 9;120 BADMSG = 9,
124pub const EBUSY: errno_t = 10;121 BUSY = 10,
125pub const ECANCELED: errno_t = 11;122 CANCELED = 11,
126pub const ECHILD: errno_t = 12;123 CHILD = 12,
127pub const ECONNABORTED: errno_t = 13;124 CONNABORTED = 13,
128pub const ECONNREFUSED: errno_t = 14;125 CONNREFUSED = 14,
129pub const ECONNRESET: errno_t = 15;126 CONNRESET = 15,
130pub const EDEADLK: errno_t = 16;127 DEADLK = 16,
131pub const EDESTADDRREQ: errno_t = 17;128 DESTADDRREQ = 17,
132pub const EDOM: errno_t = 18;129 DOM = 18,
133pub const EDQUOT: errno_t = 19;130 DQUOT = 19,
134pub const EEXIST: errno_t = 20;131 EXIST = 20,
135pub const EFAULT: errno_t = 21;132 FAULT = 21,
136pub const EFBIG: errno_t = 22;133 FBIG = 22,
137pub const EHOSTUNREACH: errno_t = 23;134 HOSTUNREACH = 23,
138pub const EIDRM: errno_t = 24;135 IDRM = 24,
139pub const EILSEQ: errno_t = 25;136 ILSEQ = 25,
140pub const EINPROGRESS: errno_t = 26;137 INPROGRESS = 26,
141pub const EINTR: errno_t = 27;138 INTR = 27,
142pub const EINVAL: errno_t = 28;139 INVAL = 28,
143pub const EIO: errno_t = 29;140 IO = 29,
144pub const EISCONN: errno_t = 30;141 ISCONN = 30,
145pub const EISDIR: errno_t = 31;142 ISDIR = 31,
146pub const ELOOP: errno_t = 32;143 LOOP = 32,
147pub const EMFILE: errno_t = 33;144 MFILE = 33,
148pub const EMLINK: errno_t = 34;145 MLINK = 34,
149pub const EMSGSIZE: errno_t = 35;146 MSGSIZE = 35,
150pub const EMULTIHOP: errno_t = 36;147 MULTIHOP = 36,
151pub const ENAMETOOLONG: errno_t = 37;148 NAMETOOLONG = 37,
152pub const ENETDOWN: errno_t = 38;149 NETDOWN = 38,
153pub const ENETRESET: errno_t = 39;150 NETRESET = 39,
154pub const ENETUNREACH: errno_t = 40;151 NETUNREACH = 40,
155pub const ENFILE: errno_t = 41;152 NFILE = 41,
156pub const ENOBUFS: errno_t = 42;153 NOBUFS = 42,
157pub const ENODEV: errno_t = 43;154 NODEV = 43,
158pub const ENOENT: errno_t = 44;155 NOENT = 44,
159pub const ENOEXEC: errno_t = 45;156 NOEXEC = 45,
160pub const ENOLCK: errno_t = 46;157 NOLCK = 46,
161pub const ENOLINK: errno_t = 47;158 NOLINK = 47,
162pub const ENOMEM: errno_t = 48;159 NOMEM = 48,
163pub const ENOMSG: errno_t = 49;160 NOMSG = 49,
164pub const ENOPROTOOPT: errno_t = 50;161 NOPROTOOPT = 50,
165pub const ENOSPC: errno_t = 51;162 NOSPC = 51,
166pub const ENOSYS: errno_t = 52;163 NOSYS = 52,
167pub const ENOTCONN: errno_t = 53;164 NOTCONN = 53,
168pub const ENOTDIR: errno_t = 54;165 NOTDIR = 54,
169pub const ENOTEMPTY: errno_t = 55;166 NOTEMPTY = 55,
170pub const ENOTRECOVERABLE: errno_t = 56;167 NOTRECOVERABLE = 56,
171pub const ENOTSOCK: errno_t = 57;168 NOTSOCK = 57,
172pub const ENOTSUP: errno_t = 58;169 /// This is also the code used for `NOTSUP`.
173pub const EOPNOTSUPP = ENOTSUP;170 OPNOTSUPP = 58,
174pub const ENOTTY: errno_t = 59;171 NOTTY = 59,
175pub const ENXIO: errno_t = 60;172 NXIO = 60,
176pub const EOVERFLOW: errno_t = 61;173 OVERFLOW = 61,
177pub const EOWNERDEAD: errno_t = 62;174 OWNERDEAD = 62,
178pub const EPERM: errno_t = 63;175 PERM = 63,
179pub const EPIPE: errno_t = 64;176 PIPE = 64,
180pub const EPROTO: errno_t = 65;177 PROTO = 65,
181pub const EPROTONOSUPPORT: errno_t = 66;178 PROTONOSUPPORT = 66,
182pub const EPROTOTYPE: errno_t = 67;179 PROTOTYPE = 67,
183pub const ERANGE: errno_t = 68;180 RANGE = 68,
184pub const EROFS: errno_t = 69;181 ROFS = 69,
185pub const ESPIPE: errno_t = 70;182 SPIPE = 70,
186pub const ESRCH: errno_t = 71;183 SRCH = 71,
187pub const ESTALE: errno_t = 72;184 STALE = 72,
188pub const ETIMEDOUT: errno_t = 73;185 TIMEDOUT = 73,
189pub const ETXTBSY: errno_t = 74;186 TXTBSY = 74,
190pub const EXDEV: errno_t = 75;187 XDEV = 75,
191pub const ENOTCAPABLE: errno_t = 76;188 NOTCAPABLE = 76,
189 _,
190};
191pub const E = errno_t;
192192
193pub const event_t = extern struct {193pub const event_t = extern struct {
194 userdata: userdata_t,194 userdata: userdata_t,
lib/std/os/bits/windows.zig+90-91
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// The reference for these types and values is Microsoft Windows's ucrt (Universal C RunTime).1// The reference for these types and values is Microsoft Windows's ucrt (Universal C RunTime).
72
8usingnamespace @import("../windows/bits.zig");3usingnamespace @import("../windows/bits.zig");
...@@ -87,93 +82,97 @@ pub const SEEK_SET = 0;...@@ -87,93 +82,97 @@ pub const SEEK_SET = 0;
87pub const SEEK_CUR = 1;82pub const SEEK_CUR = 1;
88pub const SEEK_END = 2;83pub const SEEK_END = 2;
8984
90pub const EPERM = 1;85pub const E = enum(u16) {
91pub const ENOENT = 2;86 /// No error occurred.
92pub const ESRCH = 3;87 SUCCESS = 0,
93pub const EINTR = 4;88 PERM = 1,
94pub const EIO = 5;89 NOENT = 2,
95pub const ENXIO = 6;90 SRCH = 3,
96pub const E2BIG = 7;91 INTR = 4,
97pub const ENOEXEC = 8;92 IO = 5,
98pub const EBADF = 9;93 NXIO = 6,
99pub const ECHILD = 10;94 @"2BIG" = 7,
100pub const EAGAIN = 11;95 NOEXEC = 8,
101pub const ENOMEM = 12;96 BADF = 9,
102pub const EACCES = 13;97 CHILD = 10,
103pub const EFAULT = 14;98 AGAIN = 11,
104pub const EBUSY = 16;99 NOMEM = 12,
105pub const EEXIST = 17;100 ACCES = 13,
106pub const EXDEV = 18;101 FAULT = 14,
107pub const ENODEV = 19;102 BUSY = 16,
108pub const ENOTDIR = 20;103 EXIST = 17,
109pub const EISDIR = 21;104 XDEV = 18,
110pub const ENFILE = 23;105 NODEV = 19,
111pub const EMFILE = 24;106 NOTDIR = 20,
112pub const ENOTTY = 25;107 ISDIR = 21,
113pub const EFBIG = 27;108 NFILE = 23,
114pub const ENOSPC = 28;109 MFILE = 24,
115pub const ESPIPE = 29;110 NOTTY = 25,
116pub const EROFS = 30;111 FBIG = 27,
117pub const EMLINK = 31;112 NOSPC = 28,
118pub const EPIPE = 32;113 SPIPE = 29,
119pub const EDOM = 33;114 ROFS = 30,
120pub const EDEADLK = 36;115 MLINK = 31,
121pub const ENAMETOOLONG = 38;116 PIPE = 32,
122pub const ENOLCK = 39;117 DOM = 33,
123pub const ENOSYS = 40;118 /// Also means `DEADLOCK`.
124pub const ENOTEMPTY = 41;119 DEADLK = 36,
125120 NAMETOOLONG = 38,
126pub const EINVAL = 22;121 NOLCK = 39,
127pub const ERANGE = 34;122 NOSYS = 40,
128pub const EILSEQ = 42;123 NOTEMPTY = 41,
129pub const STRUNCATE = 80;124
125 INVAL = 22,
126 RANGE = 34,
127 ILSEQ = 42,
128
129 // POSIX Supplement
130 ADDRINUSE = 100,
131 ADDRNOTAVAIL = 101,
132 AFNOSUPPORT = 102,
133 ALREADY = 103,
134 BADMSG = 104,
135 CANCELED = 105,
136 CONNABORTED = 106,
137 CONNREFUSED = 107,
138 CONNRESET = 108,
139 DESTADDRREQ = 109,
140 HOSTUNREACH = 110,
141 IDRM = 111,
142 INPROGRESS = 112,
143 ISCONN = 113,
144 LOOP = 114,
145 MSGSIZE = 115,
146 NETDOWN = 116,
147 NETRESET = 117,
148 NETUNREACH = 118,
149 NOBUFS = 119,
150 NODATA = 120,
151 NOLINK = 121,
152 NOMSG = 122,
153 NOPROTOOPT = 123,
154 NOSR = 124,
155 NOSTR = 125,
156 NOTCONN = 126,
157 NOTRECOVERABLE = 127,
158 NOTSOCK = 128,
159 NOTSUP = 129,
160 OPNOTSUPP = 130,
161 OTHER = 131,
162 OVERFLOW = 132,
163 OWNERDEAD = 133,
164 PROTO = 134,
165 PROTONOSUPPORT = 135,
166 PROTOTYPE = 136,
167 TIME = 137,
168 TIMEDOUT = 138,
169 TXTBSY = 139,
170 WOULDBLOCK = 140,
171 DQUOT = 10069,
172 _,
173};
130174
131// Support EDEADLOCK for compatibility with older Microsoft C versions175pub const STRUNCATE = 80;
132pub const EDEADLOCK = EDEADLK;
133
134// POSIX Supplement
135pub const EADDRINUSE = 100;
136pub const EADDRNOTAVAIL = 101;
137pub const EAFNOSUPPORT = 102;
138pub const EALREADY = 103;
139pub const EBADMSG = 104;
140pub const ECANCELED = 105;
141pub const ECONNABORTED = 106;
142pub const ECONNREFUSED = 107;
143pub const ECONNRESET = 108;
144pub const EDESTADDRREQ = 109;
145pub const EHOSTUNREACH = 110;
146pub const EIDRM = 111;
147pub const EINPROGRESS = 112;
148pub const EISCONN = 113;
149pub const ELOOP = 114;
150pub const EMSGSIZE = 115;
151pub const ENETDOWN = 116;
152pub const ENETRESET = 117;
153pub const ENETUNREACH = 118;
154pub const ENOBUFS = 119;
155pub const ENODATA = 120;
156pub const ENOLINK = 121;
157pub const ENOMSG = 122;
158pub const ENOPROTOOPT = 123;
159pub const ENOSR = 124;
160pub const ENOSTR = 125;
161pub const ENOTCONN = 126;
162pub const ENOTRECOVERABLE = 127;
163pub const ENOTSOCK = 128;
164pub const ENOTSUP = 129;
165pub const EOPNOTSUPP = 130;
166pub const EOTHER = 131;
167pub const EOVERFLOW = 132;
168pub const EOWNERDEAD = 133;
169pub const EPROTO = 134;
170pub const EPROTONOSUPPORT = 135;
171pub const EPROTOTYPE = 136;
172pub const ETIME = 137;
173pub const ETIMEDOUT = 138;
174pub const ETXTBSY = 139;
175pub const EWOULDBLOCK = 140;
176pub const EDQUOT = 10069;
177176
178pub const F_OK = 0;177pub const F_OK = 0;
179178
lib/std/os/darwin.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7pub usingnamespace std.c;2pub usingnamespace std.c;
8pub usingnamespace @import("bits.zig");3pub usingnamespace @import("bits.zig");
lib/std/os/dragonfly.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7pub usingnamespace std.c;2pub usingnamespace std.c;
8pub usingnamespace @import("bits.zig");3pub usingnamespace @import("bits.zig");
lib/std/os/freebsd.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7pub usingnamespace std.c;2pub usingnamespace std.c;
8pub usingnamespace @import("bits.zig");3pub usingnamespace @import("bits.zig");
lib/std/os/haiku.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2020 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7pub usingnamespace std.c;2pub usingnamespace std.c;
8pub usingnamespace @import("bits.zig");3pub usingnamespace @import("bits.zig");
lib/std/os/linux.zig+8-12
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// This file provides the system interface functions for Linux matching those1// This file provides the system interface functions for Linux matching those
7// that are provided by libc, whether or not libc is linked. The following2// that are provided by libc, whether or not libc is linked. The following
8// abstractions are made:3// abstractions are made:
...@@ -91,9 +86,10 @@ fn splitValue64(val: i64) [2]u32 {...@@ -91,9 +86,10 @@ fn splitValue64(val: i64) [2]u32 {
91}86}
9287
93/// Get the errno from a syscall return value, or 0 for no error.88/// Get the errno from a syscall return value, or 0 for no error.
94pub fn getErrno(r: usize) u12 {89pub fn getErrno(r: usize) E {
95 const signed_r = @bitCast(isize, r);90 const signed_r = @bitCast(isize, r);
96 return if (signed_r > -4096 and signed_r < 0) @intCast(u12, -signed_r) else 0;91 const int = if (signed_r > -4096 and signed_r < 0) -signed_r else 0;
92 return @intToEnum(E, int);
97}93}
9894
99pub fn dup(old: i32) usize {95pub fn dup(old: i32) usize {
...@@ -281,7 +277,7 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of...@@ -281,7 +277,7 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of
281 if (@hasField(SYS, "mmap2")) {277 if (@hasField(SYS, "mmap2")) {
282 // Make sure the offset is also specified in multiples of page size278 // Make sure the offset is also specified in multiples of page size
283 if ((offset & (MMAP2_UNIT - 1)) != 0)279 if ((offset & (MMAP2_UNIT - 1)) != 0)
284 return @bitCast(usize, @as(isize, -EINVAL));280 return @bitCast(usize, -@as(isize, @enumToInt(E.INVAL)));
285281
286 return syscall6(282 return syscall6(
287 .mmap2,283 .mmap2,
...@@ -746,7 +742,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) usize {...@@ -746,7 +742,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) usize {
746 const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);742 const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);
747 const rc = f(clk_id, tp);743 const rc = f(clk_id, tp);
748 switch (rc) {744 switch (rc) {
749 0, @bitCast(usize, @as(isize, -EINVAL)) => return rc,745 0, @bitCast(usize, -@as(isize, @enumToInt(E.INVAL))) => return rc,
750 else => {},746 else => {},
751 }747 }
752 }748 }
...@@ -764,7 +760,7 @@ fn init_vdso_clock_gettime(clk: i32, ts: *timespec) callconv(.C) usize {...@@ -764,7 +760,7 @@ fn init_vdso_clock_gettime(clk: i32, ts: *timespec) callconv(.C) usize {
764 const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);760 const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);
765 return f(clk, ts);761 return f(clk, ts);
766 }762 }
767 return @bitCast(usize, @as(isize, -ENOSYS));763 return @bitCast(usize, -@as(isize, @enumToInt(E.NOSYS)));
768}764}
769765
770pub fn clock_getres(clk_id: i32, tp: *timespec) usize {766pub fn clock_getres(clk_id: i32, tp: *timespec) usize {
...@@ -961,7 +957,7 @@ pub fn sigaction(sig: u6, noalias act: ?*const Sigaction, noalias oact: ?*Sigact...@@ -961,7 +957,7 @@ pub fn sigaction(sig: u6, noalias act: ?*const Sigaction, noalias oact: ?*Sigact
961 .sparc, .sparcv9 => syscall5(.rt_sigaction, sig, ksa_arg, oldksa_arg, @ptrToInt(ksa.restorer), mask_size),957 .sparc, .sparcv9 => syscall5(.rt_sigaction, sig, ksa_arg, oldksa_arg, @ptrToInt(ksa.restorer), mask_size),
962 else => syscall4(.rt_sigaction, sig, ksa_arg, oldksa_arg, mask_size),958 else => syscall4(.rt_sigaction, sig, ksa_arg, oldksa_arg, mask_size),
963 };959 };
964 if (getErrno(result) != 0) return result;960 if (getErrno(result) != .SUCCESS) return result;
965961
966 if (oact) |old| {962 if (oact) |old| {
967 old.handler.handler = oldksa.handler;963 old.handler.handler = oldksa.handler;
...@@ -1202,7 +1198,7 @@ pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *S...@@ -1202,7 +1198,7 @@ pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *S
1202 @ptrToInt(statx_buf),1198 @ptrToInt(statx_buf),
1203 );1199 );
1204 }1200 }
1205 return @bitCast(usize, @as(isize, -ENOSYS));1201 return @bitCast(usize, -@as(isize, @enumToInt(E.NOSYS)));
1206}1202}
12071203
1208pub fn listxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize {1204pub fn listxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize {
lib/std/os/linux/arm-eabi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("../bits/linux.zig");1usingnamespace @import("../bits/linux.zig");
72
8pub fn syscall0(number: SYS) usize {3pub fn syscall0(number: SYS) usize {
lib/std/os/linux/arm64.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("../bits/linux.zig");1usingnamespace @import("../bits/linux.zig");
72
8pub fn syscall0(number: SYS) usize {3pub fn syscall0(number: SYS) usize {
lib/std/os/linux/bpf.zig+31-36
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace std.os.linux;1usingnamespace std.os.linux;
7const std = @import("../../std.zig");2const std = @import("../../std.zig");
8const errno = getErrno;3const errno = getErrno;
...@@ -1508,13 +1503,13 @@ pub fn map_create(map_type: MapType, key_size: u32, value_size: u32, max_entries...@@ -1508,13 +1503,13 @@ pub fn map_create(map_type: MapType, key_size: u32, value_size: u32, max_entries
1508 attr.map_create.max_entries = max_entries;1503 attr.map_create.max_entries = max_entries;
15091504
1510 const rc = bpf(.map_create, &attr, @sizeOf(MapCreateAttr));1505 const rc = bpf(.map_create, &attr, @sizeOf(MapCreateAttr));
1511 return switch (errno(rc)) {1506 switch (errno(rc)) {
1512 0 => @intCast(fd_t, rc),1507 .SUCCESS => return @intCast(fd_t, rc),
1513 EINVAL => error.MapTypeOrAttrInvalid,1508 .INVAL => return error.MapTypeOrAttrInvalid,
1514 ENOMEM => error.SystemResources,1509 .NOMEM => return error.SystemResources,
1515 EPERM => error.AccessDenied,1510 .PERM => return error.AccessDenied,
1516 else => |err| unexpectedErrno(err),1511 else => |err| return unexpectedErrno(err),
1517 };1512 }
1518}1513}
15191514
1520test "map_create" {1515test "map_create" {
...@@ -1533,12 +1528,12 @@ pub fn map_lookup_elem(fd: fd_t, key: []const u8, value: []u8) !void {...@@ -1533,12 +1528,12 @@ pub fn map_lookup_elem(fd: fd_t, key: []const u8, value: []u8) !void {
15331528
1534 const rc = bpf(.map_lookup_elem, &attr, @sizeOf(MapElemAttr));1529 const rc = bpf(.map_lookup_elem, &attr, @sizeOf(MapElemAttr));
1535 switch (errno(rc)) {1530 switch (errno(rc)) {
1536 0 => return,1531 .SUCCESS => return,
1537 EBADF => return error.BadFd,1532 .BADF => return error.BadFd,
1538 EFAULT => unreachable,1533 .FAULT => unreachable,
1539 EINVAL => return error.FieldInAttrNeedsZeroing,1534 .INVAL => return error.FieldInAttrNeedsZeroing,
1540 ENOENT => return error.NotFound,1535 .NOENT => return error.NotFound,
1541 EPERM => return error.AccessDenied,1536 .PERM => return error.AccessDenied,
1542 else => |err| return unexpectedErrno(err),1537 else => |err| return unexpectedErrno(err),
1543 }1538 }
1544}1539}
...@@ -1555,13 +1550,13 @@ pub fn map_update_elem(fd: fd_t, key: []const u8, value: []const u8, flags: u64)...@@ -1555,13 +1550,13 @@ pub fn map_update_elem(fd: fd_t, key: []const u8, value: []const u8, flags: u64)
15551550
1556 const rc = bpf(.map_update_elem, &attr, @sizeOf(MapElemAttr));1551 const rc = bpf(.map_update_elem, &attr, @sizeOf(MapElemAttr));
1557 switch (errno(rc)) {1552 switch (errno(rc)) {
1558 0 => return,1553 .SUCCESS => return,
1559 E2BIG => return error.ReachedMaxEntries,1554 .@"2BIG" => return error.ReachedMaxEntries,
1560 EBADF => return error.BadFd,1555 .BADF => return error.BadFd,
1561 EFAULT => unreachable,1556 .FAULT => unreachable,
1562 EINVAL => return error.FieldInAttrNeedsZeroing,1557 .INVAL => return error.FieldInAttrNeedsZeroing,
1563 ENOMEM => return error.SystemResources,1558 .NOMEM => return error.SystemResources,
1564 EPERM => return error.AccessDenied,1559 .PERM => return error.AccessDenied,
1565 else => |err| return unexpectedErrno(err),1560 else => |err| return unexpectedErrno(err),
1566 }1561 }
1567}1562}
...@@ -1576,12 +1571,12 @@ pub fn map_delete_elem(fd: fd_t, key: []const u8) !void {...@@ -1576,12 +1571,12 @@ pub fn map_delete_elem(fd: fd_t, key: []const u8) !void {
15761571
1577 const rc = bpf(.map_delete_elem, &attr, @sizeOf(MapElemAttr));1572 const rc = bpf(.map_delete_elem, &attr, @sizeOf(MapElemAttr));
1578 switch (errno(rc)) {1573 switch (errno(rc)) {
1579 0 => return,1574 .SUCCESS => return,
1580 EBADF => return error.BadFd,1575 .BADF => return error.BadFd,
1581 EFAULT => unreachable,1576 .FAULT => unreachable,
1582 EINVAL => return error.FieldInAttrNeedsZeroing,1577 .INVAL => return error.FieldInAttrNeedsZeroing,
1583 ENOENT => return error.NotFound,1578 .NOENT => return error.NotFound,
1584 EPERM => return error.AccessDenied,1579 .PERM => return error.AccessDenied,
1585 else => |err| return unexpectedErrno(err),1580 else => |err| return unexpectedErrno(err),
1586 }1581 }
1587}1582}
...@@ -1639,11 +1634,11 @@ pub fn prog_load(...@@ -1639,11 +1634,11 @@ pub fn prog_load(
16391634
1640 const rc = bpf(.prog_load, &attr, @sizeOf(ProgLoadAttr));1635 const rc = bpf(.prog_load, &attr, @sizeOf(ProgLoadAttr));
1641 return switch (errno(rc)) {1636 return switch (errno(rc)) {
1642 0 => @intCast(fd_t, rc),1637 .SUCCESS => @intCast(fd_t, rc),
1643 EACCES => error.UnsafeProgram,1638 .ACCES => error.UnsafeProgram,
1644 EFAULT => unreachable,1639 .FAULT => unreachable,
1645 EINVAL => error.InvalidProgram,1640 .INVAL => error.InvalidProgram,
1646 EPERM => error.AccessDenied,1641 .PERM => error.AccessDenied,
1647 else => |err| unexpectedErrno(err),1642 else => |err| unexpectedErrno(err),
1648 };1643 };
1649}1644}
lib/std/os/linux/bpf/btf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const magic = 0xeb9f;1const magic = 0xeb9f;
7const version = 1;2const version = 1;
83
lib/std/os/linux/bpf/btf_ext.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const Header = packed struct {1pub const Header = packed struct {
7 magic: u16,2 magic: u16,
8 version: u8,3 version: u8,
lib/std/os/linux/bpf/helpers.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const kern = @import("kern.zig");1const kern = @import("kern.zig");
72
8// in BPF, all the helper calls3// in BPF, all the helper calls
lib/std/os/linux/bpf/kern.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../../std.zig");1const std = @import("../../../std.zig");
72
8const in_bpf_program = switch (std.builtin.cpu.arch) {3const in_bpf_program = switch (std.builtin.cpu.arch) {
lib/std/os/linux/i386.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("../bits/linux.zig");1usingnamespace @import("../bits/linux.zig");
72
8pub fn syscall0(number: SYS) usize {3pub fn syscall0(number: SYS) usize {
lib/std/os/linux/io_uring.zig+44-49
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const builtin = std.builtin;3const builtin = std.builtin;
...@@ -54,19 +49,19 @@ pub const IO_Uring = struct {...@@ -54,19 +49,19 @@ pub const IO_Uring = struct {
5449
55 const res = linux.io_uring_setup(entries, p);50 const res = linux.io_uring_setup(entries, p);
56 switch (linux.getErrno(res)) {51 switch (linux.getErrno(res)) {
57 0 => {},52 .SUCCESS => {},
58 linux.EFAULT => return error.ParamsOutsideAccessibleAddressSpace,53 .FAULT => return error.ParamsOutsideAccessibleAddressSpace,
59 // The resv array contains non-zero data, p.flags contains an unsupported flag,54 // The resv array contains non-zero data, p.flags contains an unsupported flag,
60 // entries out of bounds, IORING_SETUP_SQ_AFF was specified without IORING_SETUP_SQPOLL,55 // entries out of bounds, IORING_SETUP_SQ_AFF was specified without IORING_SETUP_SQPOLL,
61 // or IORING_SETUP_CQSIZE was specified but io_uring_params.cq_entries was invalid:56 // or IORING_SETUP_CQSIZE was specified but io_uring_params.cq_entries was invalid:
62 linux.EINVAL => return error.ArgumentsInvalid,57 .INVAL => return error.ArgumentsInvalid,
63 linux.EMFILE => return error.ProcessFdQuotaExceeded,58 .MFILE => return error.ProcessFdQuotaExceeded,
64 linux.ENFILE => return error.SystemFdQuotaExceeded,59 .NFILE => return error.SystemFdQuotaExceeded,
65 linux.ENOMEM => return error.SystemResources,60 .NOMEM => return error.SystemResources,
66 // IORING_SETUP_SQPOLL was specified but effective user ID lacks sufficient privileges,61 // IORING_SETUP_SQPOLL was specified but effective user ID lacks sufficient privileges,
67 // or a container seccomp policy prohibits io_uring syscalls:62 // or a container seccomp policy prohibits io_uring syscalls:
68 linux.EPERM => return error.PermissionDenied,63 .PERM => return error.PermissionDenied,
69 linux.ENOSYS => return error.SystemOutdated,64 .NOSYS => return error.SystemOutdated,
70 else => |errno| return os.unexpectedErrno(errno),65 else => |errno| return os.unexpectedErrno(errno),
71 }66 }
72 const fd = @intCast(os.fd_t, res);67 const fd = @intCast(os.fd_t, res);
...@@ -180,31 +175,31 @@ pub const IO_Uring = struct {...@@ -180,31 +175,31 @@ pub const IO_Uring = struct {
180 assert(self.fd >= 0);175 assert(self.fd >= 0);
181 const res = linux.io_uring_enter(self.fd, to_submit, min_complete, flags, null);176 const res = linux.io_uring_enter(self.fd, to_submit, min_complete, flags, null);
182 switch (linux.getErrno(res)) {177 switch (linux.getErrno(res)) {
183 0 => {},178 .SUCCESS => {},
184 // The kernel was unable to allocate memory or ran out of resources for the request.179 // The kernel was unable to allocate memory or ran out of resources for the request.
185 // The application should wait for some completions and try again:180 // The application should wait for some completions and try again:
186 linux.EAGAIN => return error.SystemResources,181 .AGAIN => return error.SystemResources,
187 // The SQE `fd` is invalid, or IOSQE_FIXED_FILE was set but no files were registered:182 // The SQE `fd` is invalid, or IOSQE_FIXED_FILE was set but no files were registered:
188 linux.EBADF => return error.FileDescriptorInvalid,183 .BADF => return error.FileDescriptorInvalid,
189 // The file descriptor is valid, but the ring is not in the right state.184 // The file descriptor is valid, but the ring is not in the right state.
190 // See io_uring_register(2) for how to enable the ring.185 // See io_uring_register(2) for how to enable the ring.
191 linux.EBADFD => return error.FileDescriptorInBadState,186 .BADFD => return error.FileDescriptorInBadState,
192 // The application attempted to overcommit the number of requests it can have pending.187 // The application attempted to overcommit the number of requests it can have pending.
193 // The application should wait for some completions and try again:188 // The application should wait for some completions and try again:
194 linux.EBUSY => return error.CompletionQueueOvercommitted,189 .BUSY => return error.CompletionQueueOvercommitted,
195 // The SQE is invalid, or valid but the ring was setup with IORING_SETUP_IOPOLL:190 // The SQE is invalid, or valid but the ring was setup with IORING_SETUP_IOPOLL:
196 linux.EINVAL => return error.SubmissionQueueEntryInvalid,191 .INVAL => return error.SubmissionQueueEntryInvalid,
197 // The buffer is outside the process' accessible address space, or IORING_OP_READ_FIXED192 // The buffer is outside the process' accessible address space, or IORING_OP_READ_FIXED
198 // or IORING_OP_WRITE_FIXED was specified but no buffers were registered, or the range193 // or IORING_OP_WRITE_FIXED was specified but no buffers were registered, or the range
199 // described by `addr` and `len` is not within the buffer registered at `buf_index`:194 // described by `addr` and `len` is not within the buffer registered at `buf_index`:
200 linux.EFAULT => return error.BufferInvalid,195 .FAULT => return error.BufferInvalid,
201 linux.ENXIO => return error.RingShuttingDown,196 .NXIO => return error.RingShuttingDown,
202 // The kernel believes our `self.fd` does not refer to an io_uring instance,197 // The kernel believes our `self.fd` does not refer to an io_uring instance,
203 // or the opcode is valid but not supported by this kernel (more likely):198 // or the opcode is valid but not supported by this kernel (more likely):
204 linux.EOPNOTSUPP => return error.OpcodeNotSupported,199 .OPNOTSUPP => return error.OpcodeNotSupported,
205 // The operation was interrupted by a delivery of a signal before it could complete.200 // The operation was interrupted by a delivery of a signal before it could complete.
206 // This can happen while waiting for events with IORING_ENTER_GETEVENTS:201 // This can happen while waiting for events with IORING_ENTER_GETEVENTS:
207 linux.EINTR => return error.SignalInterrupt,202 .INTR => return error.SignalInterrupt,
208 else => |errno| return os.unexpectedErrno(errno),203 else => |errno| return os.unexpectedErrno(errno),
209 }204 }
210 return @intCast(u32, res);205 return @intCast(u32, res);
...@@ -681,22 +676,22 @@ pub const IO_Uring = struct {...@@ -681,22 +676,22 @@ pub const IO_Uring = struct {
681676
682 fn handle_registration_result(res: usize) !void {677 fn handle_registration_result(res: usize) !void {
683 switch (linux.getErrno(res)) {678 switch (linux.getErrno(res)) {
684 0 => {},679 .SUCCESS => {},
685 // One or more fds in the array are invalid, or the kernel does not support sparse sets:680 // One or more fds in the array are invalid, or the kernel does not support sparse sets:
686 linux.EBADF => return error.FileDescriptorInvalid,681 .BADF => return error.FileDescriptorInvalid,
687 linux.EBUSY => return error.FilesAlreadyRegistered,682 .BUSY => return error.FilesAlreadyRegistered,
688 linux.EINVAL => return error.FilesEmpty,683 .INVAL => return error.FilesEmpty,
689 // Adding `nr_args` file references would exceed the maximum allowed number of files the684 // Adding `nr_args` file references would exceed the maximum allowed number of files the
690 // user is allowed to have according to the per-user RLIMIT_NOFILE resource limit and685 // user is allowed to have according to the per-user RLIMIT_NOFILE resource limit and
691 // the CAP_SYS_RESOURCE capability is not set, or `nr_args` exceeds the maximum allowed686 // the CAP_SYS_RESOURCE capability is not set, or `nr_args` exceeds the maximum allowed
692 // for a fixed file set (older kernels have a limit of 1024 files vs 64K files):687 // for a fixed file set (older kernels have a limit of 1024 files vs 64K files):
693 linux.EMFILE => return error.UserFdQuotaExceeded,688 .MFILE => return error.UserFdQuotaExceeded,
694 // Insufficient kernel resources, or the caller had a non-zero RLIMIT_MEMLOCK soft689 // Insufficient kernel resources, or the caller had a non-zero RLIMIT_MEMLOCK soft
695 // resource limit but tried to lock more memory than the limit permitted (not enforced690 // resource limit but tried to lock more memory than the limit permitted (not enforced
696 // when the process is privileged with CAP_IPC_LOCK):691 // when the process is privileged with CAP_IPC_LOCK):
697 linux.ENOMEM => return error.SystemResources,692 .NOMEM => return error.SystemResources,
698 // Attempt to register files on a ring already registering files or being torn down:693 // Attempt to register files on a ring already registering files or being torn down:
699 linux.ENXIO => return error.RingShuttingDownOrAlreadyRegisteringFiles,694 .NXIO => return error.RingShuttingDownOrAlreadyRegisteringFiles,
700 else => |errno| return os.unexpectedErrno(errno),695 else => |errno| return os.unexpectedErrno(errno),
701 }696 }
702 }697 }
...@@ -706,8 +701,8 @@ pub const IO_Uring = struct {...@@ -706,8 +701,8 @@ pub const IO_Uring = struct {
706 assert(self.fd >= 0);701 assert(self.fd >= 0);
707 const res = linux.io_uring_register(self.fd, .UNREGISTER_FILES, null, 0);702 const res = linux.io_uring_register(self.fd, .UNREGISTER_FILES, null, 0);
708 switch (linux.getErrno(res)) {703 switch (linux.getErrno(res)) {
709 0 => {},704 .SUCCESS => {},
710 linux.ENXIO => return error.FilesNotRegistered,705 .NXIO => return error.FilesNotRegistered,
711 else => |errno| return os.unexpectedErrno(errno),706 else => |errno| return os.unexpectedErrno(errno),
712 }707 }
713 }708 }
...@@ -1272,8 +1267,8 @@ test "write/read" {...@@ -1272,8 +1267,8 @@ test "write/read" {
1272 const cqe_read = try ring.copy_cqe();1267 const cqe_read = try ring.copy_cqe();
1273 // Prior to Linux Kernel 5.6 this is the only way to test for read/write support:1268 // Prior to Linux Kernel 5.6 this is the only way to test for read/write support:
1274 // https://lwn.net/Articles/809820/1269 // https://lwn.net/Articles/809820/
1275 if (cqe_write.res == -linux.EINVAL) return error.SkipZigTest;1270 if (cqe_write.err() == .INVAL) return error.SkipZigTest;
1276 if (cqe_read.res == -linux.EINVAL) return error.SkipZigTest;1271 if (cqe_read.err() == .INVAL) return error.SkipZigTest;
1277 try testing.expectEqual(linux.io_uring_cqe{1272 try testing.expectEqual(linux.io_uring_cqe{
1278 .user_data = 0x11111111,1273 .user_data = 0x11111111,
1279 .res = buffer_write.len,1274 .res = buffer_write.len,
...@@ -1322,11 +1317,11 @@ test "openat" {...@@ -1322,11 +1317,11 @@ test "openat" {
13221317
1323 const cqe_openat = try ring.copy_cqe();1318 const cqe_openat = try ring.copy_cqe();
1324 try testing.expectEqual(@as(u64, 0x33333333), cqe_openat.user_data);1319 try testing.expectEqual(@as(u64, 0x33333333), cqe_openat.user_data);
1325 if (cqe_openat.res == -linux.EINVAL) return error.SkipZigTest;1320 if (cqe_openat.err() == .INVAL) return error.SkipZigTest;
1326 // AT_FDCWD is not fully supported before kernel 5.6:1321 // AT_FDCWD is not fully supported before kernel 5.6:
1327 // See https://lore.kernel.org/io-uring/20200207155039.12819-1-axboe@kernel.dk/T/1322 // See https://lore.kernel.org/io-uring/20200207155039.12819-1-axboe@kernel.dk/T/
1328 // We use IORING_FEAT_RW_CUR_POS to know if we are pre-5.6 since that feature was added in 5.6.1323 // We use IORING_FEAT_RW_CUR_POS to know if we are pre-5.6 since that feature was added in 5.6.
1329 if (cqe_openat.res == -linux.EBADF and (ring.features & linux.IORING_FEAT_RW_CUR_POS) == 0) {1324 if (cqe_openat.err() == .BADF and (ring.features & linux.IORING_FEAT_RW_CUR_POS) == 0) {
1330 return error.SkipZigTest;1325 return error.SkipZigTest;
1331 }1326 }
1332 if (cqe_openat.res <= 0) std.debug.print("\ncqe_openat.res={}\n", .{cqe_openat.res});1327 if (cqe_openat.res <= 0) std.debug.print("\ncqe_openat.res={}\n", .{cqe_openat.res});
...@@ -1357,7 +1352,7 @@ test "close" {...@@ -1357,7 +1352,7 @@ test "close" {
1357 try testing.expectEqual(@as(u32, 1), try ring.submit());1352 try testing.expectEqual(@as(u32, 1), try ring.submit());
13581353
1359 const cqe_close = try ring.copy_cqe();1354 const cqe_close = try ring.copy_cqe();
1360 if (cqe_close.res == -linux.EINVAL) return error.SkipZigTest;1355 if (cqe_close.err() == .INVAL) return error.SkipZigTest;
1361 try testing.expectEqual(linux.io_uring_cqe{1356 try testing.expectEqual(linux.io_uring_cqe{
1362 .user_data = 0x44444444,1357 .user_data = 0x44444444,
1363 .res = 0,1358 .res = 0,
...@@ -1397,9 +1392,9 @@ test "accept/connect/send/recv" {...@@ -1397,9 +1392,9 @@ test "accept/connect/send/recv" {
1397 try testing.expectEqual(@as(u32, 1), try ring.submit());1392 try testing.expectEqual(@as(u32, 1), try ring.submit());
13981393
1399 var cqe_accept = try ring.copy_cqe();1394 var cqe_accept = try ring.copy_cqe();
1400 if (cqe_accept.res == -linux.EINVAL) return error.SkipZigTest;1395 if (cqe_accept.err() == .INVAL) return error.SkipZigTest;
1401 var cqe_connect = try ring.copy_cqe();1396 var cqe_connect = try ring.copy_cqe();
1402 if (cqe_connect.res == -linux.EINVAL) return error.SkipZigTest;1397 if (cqe_connect.err() == .INVAL) return error.SkipZigTest;
14031398
1404 // The accept/connect CQEs may arrive in any order, the connect CQE will sometimes come first:1399 // The accept/connect CQEs may arrive in any order, the connect CQE will sometimes come first:
1405 if (cqe_accept.user_data == 0xcccccccc and cqe_connect.user_data == 0xaaaaaaaa) {1400 if (cqe_accept.user_data == 0xcccccccc and cqe_connect.user_data == 0xaaaaaaaa) {
...@@ -1425,7 +1420,7 @@ test "accept/connect/send/recv" {...@@ -1425,7 +1420,7 @@ test "accept/connect/send/recv" {
1425 try testing.expectEqual(@as(u32, 2), try ring.submit());1420 try testing.expectEqual(@as(u32, 2), try ring.submit());
14261421
1427 const cqe_send = try ring.copy_cqe();1422 const cqe_send = try ring.copy_cqe();
1428 if (cqe_send.res == -linux.EINVAL) return error.SkipZigTest;1423 if (cqe_send.err() == .INVAL) return error.SkipZigTest;
1429 try testing.expectEqual(linux.io_uring_cqe{1424 try testing.expectEqual(linux.io_uring_cqe{
1430 .user_data = 0xeeeeeeee,1425 .user_data = 0xeeeeeeee,
1431 .res = buffer_send.len,1426 .res = buffer_send.len,
...@@ -1433,7 +1428,7 @@ test "accept/connect/send/recv" {...@@ -1433,7 +1428,7 @@ test "accept/connect/send/recv" {
1433 }, cqe_send);1428 }, cqe_send);
14341429
1435 const cqe_recv = try ring.copy_cqe();1430 const cqe_recv = try ring.copy_cqe();
1436 if (cqe_recv.res == -linux.EINVAL) return error.SkipZigTest;1431 if (cqe_recv.err() == .INVAL) return error.SkipZigTest;
1437 try testing.expectEqual(linux.io_uring_cqe{1432 try testing.expectEqual(linux.io_uring_cqe{
1438 .user_data = 0xffffffff,1433 .user_data = 0xffffffff,
1439 .res = buffer_recv.len,1434 .res = buffer_recv.len,
...@@ -1466,7 +1461,7 @@ test "timeout (after a relative time)" {...@@ -1466,7 +1461,7 @@ test "timeout (after a relative time)" {
14661461
1467 try testing.expectEqual(linux.io_uring_cqe{1462 try testing.expectEqual(linux.io_uring_cqe{
1468 .user_data = 0x55555555,1463 .user_data = 0x55555555,
1469 .res = -linux.ETIME,1464 .res = -@as(i32, @enumToInt(linux.E.TIME)),
1470 .flags = 0,1465 .flags = 0,
1471 }, cqe);1466 }, cqe);
14721467
...@@ -1535,14 +1530,14 @@ test "timeout_remove" {...@@ -1535,14 +1530,14 @@ test "timeout_remove" {
1535 // We use IORING_FEAT_RW_CUR_POS as a safety check here to make sure we are at least pre-5.6.1530 // We use IORING_FEAT_RW_CUR_POS as a safety check here to make sure we are at least pre-5.6.
1536 // We don't want to skip this test for newer kernels.1531 // We don't want to skip this test for newer kernels.
1537 if (cqe_timeout.user_data == 0x99999999 and1532 if (cqe_timeout.user_data == 0x99999999 and
1538 cqe_timeout.res == -linux.EBADF and1533 cqe_timeout.err() == .BADF and
1539 (ring.features & linux.IORING_FEAT_RW_CUR_POS) == 0)1534 (ring.features & linux.IORING_FEAT_RW_CUR_POS) == 0)
1540 {1535 {
1541 return error.SkipZigTest;1536 return error.SkipZigTest;
1542 }1537 }
1543 try testing.expectEqual(linux.io_uring_cqe{1538 try testing.expectEqual(linux.io_uring_cqe{
1544 .user_data = 0x88888888,1539 .user_data = 0x88888888,
1545 .res = -linux.ECANCELED,1540 .res = -@as(i32, @enumToInt(linux.E.CANCELED)),
1546 .flags = 0,1541 .flags = 0,
1547 }, cqe_timeout);1542 }, cqe_timeout);
15481543
...@@ -1578,15 +1573,15 @@ test "fallocate" {...@@ -1578,15 +1573,15 @@ test "fallocate" {
1578 try testing.expectEqual(@as(u32, 1), try ring.submit());1573 try testing.expectEqual(@as(u32, 1), try ring.submit());
15791574
1580 const cqe = try ring.copy_cqe();1575 const cqe = try ring.copy_cqe();
1581 switch (-cqe.res) {1576 switch (cqe.err()) {
1582 0 => {},1577 .SUCCESS => {},
1583 // This kernel's io_uring does not yet implement fallocate():1578 // This kernel's io_uring does not yet implement fallocate():
1584 linux.EINVAL => return error.SkipZigTest,1579 .INVAL => return error.SkipZigTest,
1585 // This kernel does not implement fallocate():1580 // This kernel does not implement fallocate():
1586 linux.ENOSYS => return error.SkipZigTest,1581 .NOSYS => return error.SkipZigTest,
1587 // The filesystem containing the file referred to by fd does not support this operation;1582 // The filesystem containing the file referred to by fd does not support this operation;
1588 // or the mode is not supported by the filesystem containing the file referred to by fd:1583 // or the mode is not supported by the filesystem containing the file referred to by fd:
1589 linux.EOPNOTSUPP => return error.SkipZigTest,1584 .OPNOTSUPP => return error.SkipZigTest,
1590 else => |errno| std.debug.panic("unhandled errno: {}", .{errno}),1585 else => |errno| std.debug.panic("unhandled errno: {}", .{errno}),
1591 }1586 }
1592 try testing.expectEqual(linux.io_uring_cqe{1587 try testing.expectEqual(linux.io_uring_cqe{
lib/std/os/linux/mips.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("../bits/linux.zig");1usingnamespace @import("../bits/linux.zig");
72
8pub fn syscall0(number: SYS) usize {3pub fn syscall0(number: SYS) usize {
lib/std/os/linux/powerpc.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7usingnamespace @import("../bits/linux.zig");1usingnamespace @import("../bits/linux.zig");
82
9pub fn syscall0(number: SYS) usize {3pub fn syscall0(number: SYS) usize {
lib/std/os/linux/powerpc64.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7usingnamespace @import("../bits/linux.zig");1usingnamespace @import("../bits/linux.zig");
82
9pub fn syscall0(number: SYS) usize {3pub fn syscall0(number: SYS) usize {
lib/std/os/linux/riscv64.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("../bits/linux.zig");1usingnamespace @import("../bits/linux.zig");
72
8pub fn syscall0(number: SYS) usize {3pub fn syscall0(number: SYS) usize {
lib/std/os/linux/sparc64.zig+3-1
...@@ -169,7 +169,9 @@ pub extern fn clone(func: fn (arg: usize) callconv(.C) u8, stack: usize, flags:...@@ -169,7 +169,9 @@ pub extern fn clone(func: fn (arg: usize) callconv(.C) u8, stack: usize, flags:
169169
170pub const restore = restore_rt;170pub const restore = restore_rt;
171171
172pub fn restore_rt() callconv(.Naked) void {172// Need to use C ABI here instead of naked
173// to prevent an infinite loop when calling rt_sigreturn.
174pub fn restore_rt() callconv(.C) void {
173 return asm volatile ("t 0x6d"175 return asm volatile ("t 0x6d"
174 :176 :
175 : [number] "{g1}" (@enumToInt(SYS.rt_sigreturn))177 : [number] "{g1}" (@enumToInt(SYS.rt_sigreturn))
lib/std/os/linux/test.zig+15-20
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const linux = std.os.linux;3const linux = std.os.linux;
...@@ -22,9 +17,9 @@ test "fallocate" {...@@ -22,9 +17,9 @@ test "fallocate" {
2217
23 const len: i64 = 65536;18 const len: i64 = 65536;
24 switch (linux.getErrno(linux.fallocate(file.handle, 0, 0, len))) {19 switch (linux.getErrno(linux.fallocate(file.handle, 0, 0, len))) {
25 0 => {},20 .SUCCESS => {},
26 linux.ENOSYS => return error.SkipZigTest,21 .NOSYS => return error.SkipZigTest,
27 linux.EOPNOTSUPP => return error.SkipZigTest,22 .OPNOTSUPP => return error.SkipZigTest,
28 else => |errno| std.debug.panic("unhandled errno: {}", .{errno}),23 else => |errno| std.debug.panic("unhandled errno: {}", .{errno}),
29 }24 }
3025
...@@ -37,11 +32,11 @@ test "getpid" {...@@ -37,11 +32,11 @@ test "getpid" {
3732
38test "timer" {33test "timer" {
39 const epoll_fd = linux.epoll_create();34 const epoll_fd = linux.epoll_create();
40 var err: usize = linux.getErrno(epoll_fd);35 var err: linux.E = linux.getErrno(epoll_fd);
41 try expect(err == 0);36 try expect(err == .SUCCESS);
4237
43 const timer_fd = linux.timerfd_create(linux.CLOCK_MONOTONIC, 0);38 const timer_fd = linux.timerfd_create(linux.CLOCK_MONOTONIC, 0);
44 try expect(linux.getErrno(timer_fd) == 0);39 try expect(linux.getErrno(timer_fd) == .SUCCESS);
4540
46 const time_interval = linux.timespec{41 const time_interval = linux.timespec{
47 .tv_sec = 0,42 .tv_sec = 0,
...@@ -53,22 +48,22 @@ test "timer" {...@@ -53,22 +48,22 @@ test "timer" {
53 .it_value = time_interval,48 .it_value = time_interval,
54 };49 };
5550
56 err = linux.timerfd_settime(@intCast(i32, timer_fd), 0, &new_time, null);51 err = linux.getErrno(linux.timerfd_settime(@intCast(i32, timer_fd), 0, &new_time, null));
57 try expect(err == 0);52 try expect(err == .SUCCESS);
5853
59 var event = linux.epoll_event{54 var event = linux.epoll_event{
60 .events = linux.EPOLLIN | linux.EPOLLOUT | linux.EPOLLET,55 .events = linux.EPOLLIN | linux.EPOLLOUT | linux.EPOLLET,
61 .data = linux.epoll_data{ .ptr = 0 },56 .data = linux.epoll_data{ .ptr = 0 },
62 };57 };
6358
64 err = linux.epoll_ctl(@intCast(i32, epoll_fd), linux.EPOLL_CTL_ADD, @intCast(i32, timer_fd), &event);59 err = linux.getErrno(linux.epoll_ctl(@intCast(i32, epoll_fd), linux.EPOLL_CTL_ADD, @intCast(i32, timer_fd), &event));
65 try expect(err == 0);60 try expect(err == .SUCCESS);
6661
67 const events_one: linux.epoll_event = undefined;62 const events_one: linux.epoll_event = undefined;
68 var events = [_]linux.epoll_event{events_one} ** 8;63 var events = [_]linux.epoll_event{events_one} ** 8;
6964
70 // TODO implicit cast from *[N]T to [*]T65 err = linux.getErrno(linux.epoll_wait(@intCast(i32, epoll_fd), &events, 8, -1));
71 err = linux.epoll_wait(@intCast(i32, epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1);66 try expect(err == .SUCCESS);
72}67}
7368
74test "statx" {69test "statx" {
...@@ -81,15 +76,15 @@ test "statx" {...@@ -81,15 +76,15 @@ test "statx" {
8176
82 var statx_buf: linux.Statx = undefined;77 var statx_buf: linux.Statx = undefined;
83 switch (linux.getErrno(linux.statx(file.handle, "", linux.AT_EMPTY_PATH, linux.STATX_BASIC_STATS, &statx_buf))) {78 switch (linux.getErrno(linux.statx(file.handle, "", linux.AT_EMPTY_PATH, linux.STATX_BASIC_STATS, &statx_buf))) {
84 0 => {},79 .SUCCESS => {},
85 // The statx syscall was only introduced in linux 4.1180 // The statx syscall was only introduced in linux 4.11
86 linux.ENOSYS => return error.SkipZigTest,81 .NOSYS => return error.SkipZigTest,
87 else => unreachable,82 else => unreachable,
88 }83 }
8984
90 var stat_buf: linux.kernel_stat = undefined;85 var stat_buf: linux.kernel_stat = undefined;
91 switch (linux.getErrno(linux.fstatat(file.handle, "", &stat_buf, linux.AT_EMPTY_PATH))) {86 switch (linux.getErrno(linux.fstatat(file.handle, "", &stat_buf, linux.AT_EMPTY_PATH))) {
92 0 => {},87 .SUCCESS => {},
93 else => unreachable,88 else => unreachable,
94 }89 }
9590
lib/std/os/linux/thumb.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("../bits/linux.zig");1usingnamespace @import("../bits/linux.zig");
72
8// The syscall interface is identical to the ARM one but we're facing an extra3// The syscall interface is identical to the ARM one but we're facing an extra
lib/std/os/linux/tls.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const os = std.os;2const os = std.os;
8const mem = std.mem;3const mem = std.mem;
lib/std/os/linux/vdso.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const elf = std.elf;2const elf = std.elf;
8const linux = std.os.linux;3const linux = std.os.linux;
lib/std/os/linux/x86_64.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("../bits/linux.zig");1usingnamespace @import("../bits/linux.zig");
72
8pub fn syscall0(number: SYS) usize {3pub fn syscall0(number: SYS) usize {
lib/std/os/netbsd.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7pub usingnamespace std.c;2pub usingnamespace std.c;
8pub usingnamespace @import("bits.zig");3pub usingnamespace @import("bits.zig");
lib/std/os/openbsd.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7pub usingnamespace std.c;2pub usingnamespace std.c;
8pub usingnamespace @import("bits.zig");3pub usingnamespace @import("bits.zig");
lib/std/os/test.zig+14-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const os = std.os;2const os = std.os;
8const testing = std.testing;3const testing = std.testing;
...@@ -786,3 +781,17 @@ test "dup & dup2" {...@@ -786,3 +781,17 @@ test "dup & dup2" {
786 var buf: [7]u8 = undefined;781 var buf: [7]u8 = undefined;
787 try testing.expectEqualStrings("dupdup2", buf[0..try file.readAll(&buf)]);782 try testing.expectEqualStrings("dupdup2", buf[0..try file.readAll(&buf)]);
788}783}
784
785test "writev longer than IOV_MAX" {
786 if (native_os == .windows or native_os == .wasi) return error.SkipZigTest;
787
788 var tmp = tmpDir(.{});
789 defer tmp.cleanup();
790
791 var file = try tmp.dir.createFile("pwritev", .{});
792 defer file.close();
793
794 const iovecs = [_]os.iovec_const{.{ .iov_base = "a", .iov_len = 1 }} ** (os.IOV_MAX + 1);
795 const amt = try file.writev(&iovecs);
796 try testing.expectEqual(@as(usize, os.IOV_MAX), amt);
797}
lib/std/os/uefi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
72
8/// A protocol is an interface identified by a GUID.3/// A protocol is an interface identified by a GUID.
lib/std/os/uefi/protocols.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const LoadedImageProtocol = @import("protocols/loaded_image_protocol.zig").LoadedImageProtocol;1pub const LoadedImageProtocol = @import("protocols/loaded_image_protocol.zig").LoadedImageProtocol;
7pub const loaded_image_device_path_protocol_guid = @import("protocols/loaded_image_protocol.zig").loaded_image_device_path_protocol_guid;2pub const loaded_image_device_path_protocol_guid = @import("protocols/loaded_image_protocol.zig").loaded_image_device_path_protocol_guid;
83
lib/std/os/uefi/protocols/absolute_pointer_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Event = uefi.Event;2const Event = uefi.Event;
8const Guid = uefi.Guid;3const Guid = uefi.Guid;
lib/std/os/uefi/protocols/device_path_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
83
lib/std/os/uefi/protocols/edid_active_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
83
lib/std/os/uefi/protocols/edid_discovered_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
83
lib/std/os/uefi/protocols/edid_override_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Handle = uefi.Handle;3const Handle = uefi.Handle;
lib/std/os/uefi/protocols/file_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Time = uefi.Time;3const Time = uefi.Time;
lib/std/os/uefi/protocols/graphics_output_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Status = uefi.Status;3const Status = uefi.Status;
lib/std/os/uefi/protocols/hii.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
83
lib/std/os/uefi/protocols/hii_database_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Status = uefi.Status;3const Status = uefi.Status;
lib/std/os/uefi/protocols/hii_popup_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Status = uefi.Status;3const Status = uefi.Status;
lib/std/os/uefi/protocols/ip6_config_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Event = uefi.Event;3const Event = uefi.Event;
lib/std/os/uefi/protocols/ip6_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Event = uefi.Event;3const Event = uefi.Event;
lib/std/os/uefi/protocols/ip6_service_binding_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Handle = uefi.Handle;2const Handle = uefi.Handle;
8const Guid = uefi.Guid;3const Guid = uefi.Guid;
lib/std/os/uefi/protocols/loaded_image_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Handle = uefi.Handle;3const Handle = uefi.Handle;
lib/std/os/uefi/protocols/managed_network_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Event = uefi.Event;3const Event = uefi.Event;
lib/std/os/uefi/protocols/managed_network_service_binding_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Handle = uefi.Handle;2const Handle = uefi.Handle;
8const Guid = uefi.Guid;3const Guid = uefi.Guid;
lib/std/os/uefi/protocols/rng_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Status = uefi.Status;3const Status = uefi.Status;
lib/std/os/uefi/protocols/shell_parameters_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const FileHandle = uefi.FileHandle;3const FileHandle = uefi.FileHandle;
lib/std/os/uefi/protocols/simple_file_system_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const FileProtocol = uefi.protocols.FileProtocol;3const FileProtocol = uefi.protocols.FileProtocol;
lib/std/os/uefi/protocols/simple_network_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Event = uefi.Event;2const Event = uefi.Event;
8const Guid = uefi.Guid;3const Guid = uefi.Guid;
lib/std/os/uefi/protocols/simple_pointer_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Event = uefi.Event;2const Event = uefi.Event;
8const Guid = uefi.Guid;3const Guid = uefi.Guid;
lib/std/os/uefi/protocols/simple_text_input_ex_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Event = uefi.Event;2const Event = uefi.Event;
8const Guid = uefi.Guid;3const Guid = uefi.Guid;
lib/std/os/uefi/protocols/simple_text_input_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Event = uefi.Event;2const Event = uefi.Event;
8const Guid = uefi.Guid;3const Guid = uefi.Guid;
lib/std/os/uefi/protocols/simple_text_output_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Status = uefi.Status;3const Status = uefi.Status;
lib/std/os/uefi/protocols/udp6_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const Event = uefi.Event;3const Event = uefi.Event;
lib/std/os/uefi/protocols/udp6_service_binding_protocol.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Handle = uefi.Handle;2const Handle = uefi.Handle;
8const Guid = uefi.Guid;3const Guid = uefi.Guid;
lib/std/os/uefi/status.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const high_bit = 1 << @typeInfo(usize).Int.bits - 1;1const high_bit = 1 << @typeInfo(usize).Int.bits - 1;
72
8pub const Status = enum(usize) {3pub const Status = enum(usize) {
lib/std/os/uefi/tables.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const AllocateType = @import("tables/boot_services.zig").AllocateType;1pub const AllocateType = @import("tables/boot_services.zig").AllocateType;
7pub const BootServices = @import("tables/boot_services.zig").BootServices;2pub const BootServices = @import("tables/boot_services.zig").BootServices;
8pub const ConfigurationTable = @import("tables/configuration_table.zig").ConfigurationTable;3pub const ConfigurationTable = @import("tables/configuration_table.zig").ConfigurationTable;
lib/std/os/uefi/tables/boot_services.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Event = uefi.Event;2const Event = uefi.Event;
8const Guid = uefi.Guid;3const Guid = uefi.Guid;
lib/std/os/uefi/tables/configuration_table.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
83
lib/std/os/uefi/tables/runtime_services.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const Guid = uefi.Guid;2const Guid = uefi.Guid;
8const TableHeader = uefi.tables.TableHeader;3const TableHeader = uefi.tables.TableHeader;
lib/std/os/uefi/tables/system_table.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
7const BootServices = uefi.tables.BootServices;2const BootServices = uefi.tables.BootServices;
8const ConfigurationTable = uefi.tables.ConfigurationTable;3const ConfigurationTable = uefi.tables.ConfigurationTable;
lib/std/os/uefi/tables/table_header.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const TableHeader = extern struct {1pub const TableHeader = extern struct {
7 signature: u64,2 signature: u64,
8 revision: u32,3 revision: u32,
lib/std/os/wasi.zig+1-6
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// wasi_snapshot_preview1 spec available (in witx format) here:1// wasi_snapshot_preview1 spec available (in witx format) here:
7// * typenames -- https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/witx/typenames.witx2// * typenames -- https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/witx/typenames.witx
8// * module -- https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/witx/wasi_snapshot_preview1.witx3// * module -- https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/witx/wasi_snapshot_preview1.witx
...@@ -83,6 +78,6 @@ pub extern "wasi_snapshot_preview1" fn sock_send(sock: fd_t, si_data: *const cio...@@ -83,6 +78,6 @@ pub extern "wasi_snapshot_preview1" fn sock_send(sock: fd_t, si_data: *const cio
83pub extern "wasi_snapshot_preview1" fn sock_shutdown(sock: fd_t, how: sdflags_t) errno_t;78pub extern "wasi_snapshot_preview1" fn sock_shutdown(sock: fd_t, how: sdflags_t) errno_t;
8479
85/// Get the errno from a syscall return value, or 0 for no error.80/// Get the errno from a syscall return value, or 0 for no error.
86pub fn getErrno(r: errno_t) usize {81pub fn getErrno(r: errno_t) errno_t {
87 return r;82 return r;
88}83}
lib/std/os/windows.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// This file contains thin wrappers around Windows-specific APIs, with these1// This file contains thin wrappers around Windows-specific APIs, with these
7// specific goals in mind:2// specific goals in mind:
8// * Convert "errno"-style error codes into Zig errors.3// * Convert "errno"-style error codes into Zig errors.
lib/std/os/windows/advapi32.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("bits.zig");1usingnamespace @import("bits.zig");
72
8pub extern "advapi32" fn RegOpenKeyExW(3pub extern "advapi32" fn RegOpenKeyExW(
lib/std/os/windows/bits.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Platform-dependent types and values that are used along with OS-specific APIs.1// Platform-dependent types and values that are used along with OS-specific APIs.
72
8const std = @import("../../std.zig");3const std = @import("../../std.zig");
lib/std/os/windows/gdi32.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("bits.zig");1usingnamespace @import("bits.zig");
72
8pub const PIXELFORMATDESCRIPTOR = extern struct {3pub const PIXELFORMATDESCRIPTOR = extern struct {
lib/std/os/windows/kernel32.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("bits.zig");1usingnamespace @import("bits.zig");
72
8pub extern "kernel32" fn AddVectoredExceptionHandler(First: c_ulong, Handler: ?VECTORED_EXCEPTION_HANDLER) callconv(WINAPI) ?*c_void;3pub extern "kernel32" fn AddVectoredExceptionHandler(First: c_ulong, Handler: ?VECTORED_EXCEPTION_HANDLER) callconv(WINAPI) ?*c_void;
lib/std/os/windows/lang.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const NEUTRAL = 0x00;1pub const NEUTRAL = 0x00;
7pub const INVARIANT = 0x7f;2pub const INVARIANT = 0x7f;
8pub const AFRIKAANS = 0x36;3pub const AFRIKAANS = 0x36;
lib/std/os/windows/ntdll.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("bits.zig");1usingnamespace @import("bits.zig");
72
8pub extern "NtDll" fn RtlGetVersion(3pub extern "NtDll" fn RtlGetVersion(
lib/std/os/windows/ntstatus.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7/// NTSTATUS codes from https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/596a1078-e883-4972-9bbc-49e60bebca55?1/// NTSTATUS codes from https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/596a1078-e883-4972-9bbc-49e60bebca55?
8pub const NTSTATUS = enum(u32) {2pub const NTSTATUS = enum(u32) {
9 /// The caller specified WaitAny for WaitType and one of the dispatcher3 /// The caller specified WaitAny for WaitType and one of the dispatcher
lib/std/os/windows/ole32.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("bits.zig");1usingnamespace @import("bits.zig");
72
8pub extern "ole32" fn CoTaskMemFree(pv: LPVOID) callconv(WINAPI) void;3pub extern "ole32" fn CoTaskMemFree(pv: LPVOID) callconv(WINAPI) void;
lib/std/os/windows/psapi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("bits.zig");1usingnamespace @import("bits.zig");
72
8pub extern "psapi" fn EmptyWorkingSet(hProcess: HANDLE) callconv(WINAPI) BOOL;3pub extern "psapi" fn EmptyWorkingSet(hProcess: HANDLE) callconv(WINAPI) BOOL;
lib/std/os/windows/shell32.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("bits.zig");1usingnamespace @import("bits.zig");
72
8pub extern "shell32" fn SHGetKnownFolderPath(rfid: *const KNOWNFOLDERID, dwFlags: DWORD, hToken: ?HANDLE, ppszPath: *[*:0]WCHAR) callconv(WINAPI) HRESULT;3pub extern "shell32" fn SHGetKnownFolderPath(rfid: *const KNOWNFOLDERID, dwFlags: DWORD, hToken: ?HANDLE, ppszPath: *[*:0]WCHAR) callconv(WINAPI) HRESULT;
lib/std/os/windows/sublang.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const NEUTRAL = 0x00;1pub const NEUTRAL = 0x00;
7pub const DEFAULT = 0x01;2pub const DEFAULT = 0x01;
8pub const SYS_DEFAULT = 0x02;3pub const SYS_DEFAULT = 0x02;
lib/std/os/windows/test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2020 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7const builtin = @import("builtin");2const builtin = @import("builtin");
8const windows = std.os.windows;3const windows = std.os.windows;
lib/std/os/windows/user32.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("bits.zig");1usingnamespace @import("bits.zig");
7const std = @import("std");2const std = @import("std");
8const builtin = std.builtin;3const builtin = std.builtin;
lib/std/os/windows/win32error.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Codes are from https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/18d8fbe8-a967-4f1c-ae50-99ca8e491d2d1// Codes are from https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/18d8fbe8-a967-4f1c-ae50-99ca8e491d2d
7pub const Win32Error = enum(u16) {2pub const Win32Error = enum(u16) {
8 /// The operation completed successfully.3 /// The operation completed successfully.
lib/std/os/windows/winmm.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6usingnamespace @import("bits.zig");1usingnamespace @import("bits.zig");
72
8pub const MMRESULT = UINT;3pub const MMRESULT = UINT;
lib/std/os/windows/ws2_32.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../../std.zig");1const std = @import("../../std.zig");
7usingnamespace @import("bits.zig");2usingnamespace @import("bits.zig");
83
lib/std/packed_int_array.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = @import("builtin");2const builtin = @import("builtin");
8const debug = std.debug;3const debug = std.debug;
lib/std/pdb.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = std.builtin;1const builtin = std.builtin;
7const std = @import("std.zig");2const std = @import("std.zig");
8const io = std.io;3const io = std.io;
lib/std/priority_dequeue.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const Allocator = std.mem.Allocator;2const Allocator = std.mem.Allocator;
8const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/priority_queue.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const Allocator = std.mem.Allocator;2const Allocator = std.mem.Allocator;
8const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/process.zig+4-9
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const os = std.os;3const os = std.os;
...@@ -93,7 +88,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {...@@ -93,7 +88,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
93 var environ_buf_size: usize = undefined;88 var environ_buf_size: usize = undefined;
9489
95 const environ_sizes_get_ret = os.wasi.environ_sizes_get(&environ_count, &environ_buf_size);90 const environ_sizes_get_ret = os.wasi.environ_sizes_get(&environ_count, &environ_buf_size);
96 if (environ_sizes_get_ret != os.wasi.ESUCCESS) {91 if (environ_sizes_get_ret != .SUCCESS) {
97 return os.unexpectedErrno(environ_sizes_get_ret);92 return os.unexpectedErrno(environ_sizes_get_ret);
98 }93 }
9994
...@@ -103,7 +98,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {...@@ -103,7 +98,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
103 defer allocator.free(environ_buf);98 defer allocator.free(environ_buf);
10499
105 const environ_get_ret = os.wasi.environ_get(environ.ptr, environ_buf.ptr);100 const environ_get_ret = os.wasi.environ_get(environ.ptr, environ_buf.ptr);
106 if (environ_get_ret != os.wasi.ESUCCESS) {101 if (environ_get_ret != .SUCCESS) {
107 return os.unexpectedErrno(environ_get_ret);102 return os.unexpectedErrno(environ_get_ret);
108 }103 }
109104
...@@ -255,7 +250,7 @@ pub const ArgIteratorWasi = struct {...@@ -255,7 +250,7 @@ pub const ArgIteratorWasi = struct {
255 var buf_size: usize = undefined;250 var buf_size: usize = undefined;
256251
257 switch (w.args_sizes_get(&count, &buf_size)) {252 switch (w.args_sizes_get(&count, &buf_size)) {
258 w.ESUCCESS => {},253 .SUCCESS => {},
259 else => |err| return os.unexpectedErrno(err),254 else => |err| return os.unexpectedErrno(err),
260 }255 }
261256
...@@ -265,7 +260,7 @@ pub const ArgIteratorWasi = struct {...@@ -265,7 +260,7 @@ pub const ArgIteratorWasi = struct {
265 var argv_buf = try allocator.alloc(u8, buf_size);260 var argv_buf = try allocator.alloc(u8, buf_size);
266261
267 switch (w.args_get(argv.ptr, argv_buf.ptr)) {262 switch (w.args_get(argv.ptr, argv_buf.ptr)) {
268 w.ESUCCESS => {},263 .SUCCESS => {},
269 else => |err| return os.unexpectedErrno(err),264 else => |err| return os.unexpectedErrno(err),
270 }265 }
271266
lib/std/rand.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! The engines provided here should be initialized from an external source.1//! The engines provided here should be initialized from an external source.
8//! For a thread-local cryptographically secure pseudo random number generator,2//! For a thread-local cryptographically secure pseudo random number generator,
9//! use `std.crypto.random`.3//! use `std.crypto.random`.
lib/std/rand/Gimli.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! CSPRNG1//! CSPRNG
82
9const std = @import("std");3const std = @import("std");
lib/std/rand/Isaac64.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! ISAAC64 - http://www.burtleburtle.net/bob/rand/isaacafa.html1//! ISAAC64 - http://www.burtleburtle.net/bob/rand/isaacafa.html
8//!2//!
9//! Follows the general idea of the implementation from here with a few shortcuts.3//! Follows the general idea of the implementation from here with a few shortcuts.
lib/std/rand/Pcg.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! PCG32 - http://www.pcg-random.org/1//! PCG32 - http://www.pcg-random.org/
8//!2//!
9//! PRNG3//! PRNG
lib/std/rand/Sfc64.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! Sfc64 pseudo-random number generator from Practically Random.1//! Sfc64 pseudo-random number generator from Practically Random.
8//! Fastest engine of pracrand and smallest footprint.2//! Fastest engine of pracrand and smallest footprint.
9//! See http://pracrand.sourceforge.net/3//! See http://pracrand.sourceforge.net/
lib/std/rand/Xoroshiro128.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! Xoroshiro128+ - http://xoroshiro.di.unimi.it/1//! Xoroshiro128+ - http://xoroshiro.di.unimi.it/
8//!2//!
9//! PRNG3//! PRNG
lib/std/rand/Xoshiro256.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7//! Xoshiro256++ - http://xoroshiro.di.unimi.it/1//! Xoshiro256++ - http://xoroshiro.di.unimi.it/
8//!2//!
9//! PRNG3//! PRNG
lib/std/rand/ziggurat.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Implements ZIGNOR [1].1// Implements ZIGNOR [1].
7//2//
8// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to Generate Normal Random Samples*]3// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to Generate Normal Random Samples*]
lib/std/sort.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const testing = std.testing;3const testing = std.testing;
lib/std/special/build_runner.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const root = @import("@build");1const root = @import("@build");
7const std = @import("std");2const std = @import("std");
8const builtin = @import("builtin");3const builtin = @import("builtin");
lib/std/special/c.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// This is Zig's multi-target implementation of libc.1// This is Zig's multi-target implementation of libc.
7// When builtin.link_libc is true, we need to export all the functions and2// When builtin.link_libc is true, we need to export all the functions and
8// provide an entire C API.3// provide an entire C API.
lib/std/special/compiler_rt.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = std.builtin;2const builtin = std.builtin;
8const is_test = builtin.is_test;3const is_test = builtin.is_test;
lib/std/special/compiler_rt/addXf3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/blob/02d85149a05cb1f6dc49f0ba7a2ceca53718ae17/compiler-rt/lib/builtins/fp_add_impl.inc3// https://github.com/llvm/llvm-project/blob/02d85149a05cb1f6dc49f0ba7a2ceca53718ae17/compiler-rt/lib/builtins/fp_add_impl.inc
lib/std/special/compiler_rt/addXf3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/blob/02d85149a05cb1f6dc49f0ba7a2ceca53718ae17/compiler-rt/test/builtins/Unit/addtf3_test.c3// https://github.com/llvm/llvm-project/blob/02d85149a05cb1f6dc49f0ba7a2ceca53718ae17/compiler-rt/test/builtins/Unit/addtf3_test.c
lib/std/special/compiler_rt/arm.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// ARM specific builtins1// ARM specific builtins
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/ashldi3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __ashldi3 = @import("shift.zig").__ashldi3;1const __ashldi3 = @import("shift.zig").__ashldi3;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/ashlti3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __ashlti3 = @import("shift.zig").__ashlti3;1const __ashlti3 = @import("shift.zig").__ashlti3;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/ashrdi3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __ashrdi3 = @import("shift.zig").__ashrdi3;1const __ashrdi3 = @import("shift.zig").__ashrdi3;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/ashrti3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __ashrti3 = @import("shift.zig").__ashrti3;1const __ashrti3 = @import("shift.zig").__ashrti3;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/atomics.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = std.builtin;2const builtin = std.builtin;
8const arch = std.Target.current.cpu.arch;3const arch = std.Target.current.cpu.arch;
lib/std/special/compiler_rt/aulldiv.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
72
8pub fn _alldiv(a: i64, b: i64) callconv(.Stdcall) i64 {3pub fn _alldiv(a: i64, b: i64) callconv(.Stdcall) i64 {
lib/std/special/compiler_rt/aullrem.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
72
8pub fn _allrem(a: i64, b: i64) callconv(.Stdcall) i64 {3pub fn _allrem(a: i64, b: i64) callconv(.Stdcall) i64 {
lib/std/special/compiler_rt/clear_cache.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const arch = std.builtin.cpu.arch;2const arch = std.builtin.cpu.arch;
8const os = std.builtin.os.tag;3const os = std.builtin.os.tag;
lib/std/special/compiler_rt/clzsi2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = std.builtin;2const builtin = std.builtin;
83
lib/std/special/compiler_rt/clzsi2_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const clzsi2 = @import("clzsi2.zig");1const clzsi2 = @import("clzsi2.zig");
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/compareXf2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/lib/builtins/comparesf2.c3// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/lib/builtins/comparesf2.c
lib/std/special/compiler_rt/comparedf2_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/test/builtins/Unit/comparedf2_test.c3// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/test/builtins/Unit/comparedf2_test.c
lib/std/special/compiler_rt/comparesf2_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/test/builtins/Unit/comparesf2_test.c3// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/test/builtins/Unit/comparesf2_test.c
lib/std/special/compiler_rt/divdf3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/lib/builtins/divdf3.c3// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/lib/builtins/divdf3.c
lib/std/special/compiler_rt/divdf3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/test/builtins/Unit/divdf3_test.c3// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/test/builtins/Unit/divdf3_test.c
lib/std/special/compiler_rt/divsf3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/lib/builtins/divsf3.c3// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/lib/builtins/divsf3.c
lib/std/special/compiler_rt/divsf3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/test/builtins/Unit/divsf3_test.c3// https://github.com/llvm/llvm-project/commit/d674d96bc56c0f377879d01c9d8dfdaaa7859cdb/compiler-rt/test/builtins/Unit/divsf3_test.c
lib/std/special/compiler_rt/divtf3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/divtf3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const math = std.math;2const math = std.math;
8const testing = std.testing;3const testing = std.testing;
lib/std/special/compiler_rt/divti3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const udivmod = @import("udivmod.zig").udivmod;1const udivmod = @import("udivmod.zig").udivmod;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/divti3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __divti3 = @import("divti3.zig").__divti3;1const __divti3 = @import("divti3.zig").__divti3;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/emutls.zig+3-9
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2018 LLVM Compiler Infrastructure
3// Copyright (c) 2020 Sebastien Marie <semarie@online.fr>
4// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
5// The MIT license requires this copyright notice to be included in all copies
6// and substantial portions of the software.
7// __emutls_get_address specific builtin1// __emutls_get_address specific builtin
8//2//
9// derived work from LLVM Compiler Infrastructure - release 8.0 (MIT)3// derived work from LLVM Compiler Infrastructure - release 8.0 (MIT)
...@@ -201,7 +195,7 @@ const current_thread_storage = struct {...@@ -201,7 +195,7 @@ const current_thread_storage = struct {
201195
202 /// Initialize pthread_key_t.196 /// Initialize pthread_key_t.
203 fn init() void {197 fn init() void {
204 if (std.c.pthread_key_create(&current_thread_storage.key, current_thread_storage.deinit) != 0) {198 if (std.c.pthread_key_create(&current_thread_storage.key, current_thread_storage.deinit) != .SUCCESS) {
205 abort();199 abort();
206 }200 }
207 }201 }
...@@ -248,14 +242,14 @@ const emutls_control = extern struct {...@@ -248,14 +242,14 @@ const emutls_control = extern struct {
248242
249 /// Simple wrapper for global lock.243 /// Simple wrapper for global lock.
250 fn lock() void {244 fn lock() void {
251 if (std.c.pthread_mutex_lock(&emutls_control.mutex) != 0) {245 if (std.c.pthread_mutex_lock(&emutls_control.mutex) != .SUCCESS) {
252 abort();246 abort();
253 }247 }
254 }248 }
255249
256 /// Simple wrapper for global unlock.250 /// Simple wrapper for global unlock.
257 fn unlock() void {251 fn unlock() void {
258 if (std.c.pthread_mutex_unlock(&emutls_control.mutex) != 0) {252 if (std.c.pthread_mutex_unlock(&emutls_control.mutex) != .SUCCESS) {
259 abort();253 abort();
260 }254 }
261 }255 }
lib/std/special/compiler_rt/extendXfYf2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = @import("builtin");2const builtin = @import("builtin");
8const is_test = builtin.is_test;3const is_test = builtin.is_test;
lib/std/special/compiler_rt/extendXfYf2_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const __extendhfsf2 = @import("extendXfYf2.zig").__extendhfsf2;2const __extendhfsf2 = @import("extendXfYf2.zig").__extendhfsf2;
8const __extendhftf2 = @import("extendXfYf2.zig").__extendhftf2;3const __extendhftf2 = @import("extendXfYf2.zig").__extendhftf2;
lib/std/special/compiler_rt/fixdfdi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixint = @import("fixint.zig").fixint;1const fixint = @import("fixint.zig").fixint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixdfdi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixdfdi = @import("fixdfdi.zig").__fixdfdi;1const __fixdfdi = @import("fixdfdi.zig").__fixdfdi;
7const std = @import("std");2const std = @import("std");
8const math = std.math;3const math = std.math;
lib/std/special/compiler_rt/fixdfsi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixint = @import("fixint.zig").fixint;1const fixint = @import("fixint.zig").fixint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixdfsi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixdfsi = @import("fixdfsi.zig").__fixdfsi;1const __fixdfsi = @import("fixdfsi.zig").__fixdfsi;
7const std = @import("std");2const std = @import("std");
8const math = std.math;3const math = std.math;
lib/std/special/compiler_rt/fixdfti.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixint = @import("fixint.zig").fixint;1const fixint = @import("fixint.zig").fixint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixdfti_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixdfti = @import("fixdfti.zig").__fixdfti;1const __fixdfti = @import("fixdfti.zig").__fixdfti;
7const std = @import("std");2const std = @import("std");
8const math = std.math;3const math = std.math;
lib/std/special/compiler_rt/fixint.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const is_test = @import("builtin").is_test;1const is_test = @import("builtin").is_test;
7const std = @import("std");2const std = @import("std");
8const math = std.math;3const math = std.math;
lib/std/special/compiler_rt/fixint_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const is_test = @import("builtin").is_test;1const is_test = @import("builtin").is_test;
7const std = @import("std");2const std = @import("std");
8const math = std.math;3const math = std.math;
lib/std/special/compiler_rt/fixsfdi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixint = @import("fixint.zig").fixint;1const fixint = @import("fixint.zig").fixint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixsfdi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixsfdi = @import("fixsfdi.zig").__fixsfdi;1const __fixsfdi = @import("fixsfdi.zig").__fixsfdi;
7const std = @import("std");2const std = @import("std");
8const math = std.math;3const math = std.math;
lib/std/special/compiler_rt/fixsfsi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixint = @import("fixint.zig").fixint;1const fixint = @import("fixint.zig").fixint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixsfsi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixsfsi = @import("fixsfsi.zig").__fixsfsi;1const __fixsfsi = @import("fixsfsi.zig").__fixsfsi;
7const std = @import("std");2const std = @import("std");
8const math = std.math;3const math = std.math;
lib/std/special/compiler_rt/fixsfti.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixint = @import("fixint.zig").fixint;1const fixint = @import("fixint.zig").fixint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixsfti_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixsfti = @import("fixsfti.zig").__fixsfti;1const __fixsfti = @import("fixsfti.zig").__fixsfti;
7const std = @import("std");2const std = @import("std");
8const math = std.math;3const math = std.math;
lib/std/special/compiler_rt/fixtfdi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixint = @import("fixint.zig").fixint;1const fixint = @import("fixint.zig").fixint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixtfdi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixtfdi = @import("fixtfdi.zig").__fixtfdi;1const __fixtfdi = @import("fixtfdi.zig").__fixtfdi;
7const std = @import("std");2const std = @import("std");
8const math = std.math;3const math = std.math;
lib/std/special/compiler_rt/fixtfsi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixint = @import("fixint.zig").fixint;1const fixint = @import("fixint.zig").fixint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixtfsi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixtfsi = @import("fixtfsi.zig").__fixtfsi;1const __fixtfsi = @import("fixtfsi.zig").__fixtfsi;
7const std = @import("std");2const std = @import("std");
8const math = std.math;3const math = std.math;
lib/std/special/compiler_rt/fixtfti.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixint = @import("fixint.zig").fixint;1const fixint = @import("fixint.zig").fixint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixtfti_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixtfti = @import("fixtfti.zig").__fixtfti;1const __fixtfti = @import("fixtfti.zig").__fixtfti;
7const std = @import("std");2const std = @import("std");
8const math = std.math;3const math = std.math;
lib/std/special/compiler_rt/fixuint.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const is_test = @import("builtin").is_test;1const is_test = @import("builtin").is_test;
7const Log2Int = @import("std").math.Log2Int;2const Log2Int = @import("std").math.Log2Int;
83
lib/std/special/compiler_rt/fixunsdfdi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixuint = @import("fixuint.zig").fixuint;1const fixuint = @import("fixuint.zig").fixuint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunsdfdi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixunsdfdi = @import("fixunsdfdi.zig").__fixunsdfdi;1const __fixunsdfdi = @import("fixunsdfdi.zig").__fixunsdfdi;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunsdfsi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixuint = @import("fixuint.zig").fixuint;1const fixuint = @import("fixuint.zig").fixuint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunsdfsi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixunsdfsi = @import("fixunsdfsi.zig").__fixunsdfsi;1const __fixunsdfsi = @import("fixunsdfsi.zig").__fixunsdfsi;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunsdfti.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixuint = @import("fixuint.zig").fixuint;1const fixuint = @import("fixuint.zig").fixuint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunsdfti_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixunsdfti = @import("fixunsdfti.zig").__fixunsdfti;1const __fixunsdfti = @import("fixunsdfti.zig").__fixunsdfti;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunssfdi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixuint = @import("fixuint.zig").fixuint;1const fixuint = @import("fixuint.zig").fixuint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunssfdi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixunssfdi = @import("fixunssfdi.zig").__fixunssfdi;1const __fixunssfdi = @import("fixunssfdi.zig").__fixunssfdi;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunssfsi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixuint = @import("fixuint.zig").fixuint;1const fixuint = @import("fixuint.zig").fixuint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunssfsi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixunssfsi = @import("fixunssfsi.zig").__fixunssfsi;1const __fixunssfsi = @import("fixunssfsi.zig").__fixunssfsi;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunssfti.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixuint = @import("fixuint.zig").fixuint;1const fixuint = @import("fixuint.zig").fixuint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunssfti_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixunssfti = @import("fixunssfti.zig").__fixunssfti;1const __fixunssfti = @import("fixunssfti.zig").__fixunssfti;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunstfdi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixuint = @import("fixuint.zig").fixuint;1const fixuint = @import("fixuint.zig").fixuint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunstfdi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixunstfdi = @import("fixunstfdi.zig").__fixunstfdi;1const __fixunstfdi = @import("fixunstfdi.zig").__fixunstfdi;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunstfsi.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixuint = @import("fixuint.zig").fixuint;1const fixuint = @import("fixuint.zig").fixuint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunstfsi_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixunstfsi = @import("fixunstfsi.zig").__fixunstfsi;1const __fixunstfsi = @import("fixunstfsi.zig").__fixunstfsi;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunstfti.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const fixuint = @import("fixuint.zig").fixuint;1const fixuint = @import("fixuint.zig").fixuint;
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunstfti_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __fixunstfti = @import("fixunstfti.zig").__fixunstfti;1const __fixunstfti = @import("fixunstfti.zig").__fixunstfti;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatXisf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const std = @import("std");2const std = @import("std");
8const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/floatdidf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const std = @import("std");2const std = @import("std");
83
lib/std/special/compiler_rt/floatdidf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floatdidf = @import("floatdidf.zig").__floatdidf;1const __floatdidf = @import("floatdidf.zig").__floatdidf;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatdisf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floatdisf = @import("floatXisf.zig").__floatdisf;1const __floatdisf = @import("floatXisf.zig").__floatdisf;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatditf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const is_test = builtin.is_test;2const is_test = builtin.is_test;
8const std = @import("std");3const std = @import("std");
lib/std/special/compiler_rt/floatditf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floatditf = @import("floatditf.zig").__floatditf;1const __floatditf = @import("floatditf.zig").__floatditf;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatsiXf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const std = @import("std");2const std = @import("std");
8const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/floattidf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const is_test = builtin.is_test;2const is_test = builtin.is_test;
8const std = @import("std");3const std = @import("std");
lib/std/special/compiler_rt/floattidf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floattidf = @import("floattidf.zig").__floattidf;1const __floattidf = @import("floattidf.zig").__floattidf;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floattisf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floattisf = @import("floatXisf.zig").__floattisf;1const __floattisf = @import("floatXisf.zig").__floattisf;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floattitf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const is_test = builtin.is_test;2const is_test = builtin.is_test;
8const std = @import("std");3const std = @import("std");
lib/std/special/compiler_rt/floattitf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floattitf = @import("floattitf.zig").__floattitf;1const __floattitf = @import("floattitf.zig").__floattitf;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatundidf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const std = @import("std");2const std = @import("std");
83
lib/std/special/compiler_rt/floatundidf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floatundidf = @import("floatundidf.zig").__floatundidf;1const __floatundidf = @import("floatundidf.zig").__floatundidf;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatundisf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const std = @import("std");2const std = @import("std");
8const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/floatunditf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const is_test = builtin.is_test;2const is_test = builtin.is_test;
8const std = @import("std");3const std = @import("std");
lib/std/special/compiler_rt/floatunditf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floatunditf = @import("floatunditf.zig").__floatunditf;1const __floatunditf = @import("floatunditf.zig").__floatunditf;
72
8fn test__floatunditf(a: u64, expected_hi: u64, expected_lo: u64) !void {3fn test__floatunditf(a: u64, expected_hi: u64, expected_lo: u64) !void {
lib/std/special/compiler_rt/floatunsidf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const std = @import("std");2const std = @import("std");
8const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/floatunsisf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const std = @import("std");2const std = @import("std");
8const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/floatunsitf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const is_test = builtin.is_test;2const is_test = builtin.is_test;
8const std = @import("std");3const std = @import("std");
lib/std/special/compiler_rt/floatunsitf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floatunsitf = @import("floatunsitf.zig").__floatunsitf;1const __floatunsitf = @import("floatunsitf.zig").__floatunsitf;
72
8fn test__floatunsitf(a: u32, expected_hi: u64, expected_lo: u64) !void {3fn test__floatunsitf(a: u32, expected_hi: u64, expected_lo: u64) !void {
lib/std/special/compiler_rt/floatuntidf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const is_test = builtin.is_test;2const is_test = builtin.is_test;
8const std = @import("std");3const std = @import("std");
lib/std/special/compiler_rt/floatuntidf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floatuntidf = @import("floatuntidf.zig").__floatuntidf;1const __floatuntidf = @import("floatuntidf.zig").__floatuntidf;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatuntisf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const is_test = builtin.is_test;2const is_test = builtin.is_test;
8const std = @import("std");3const std = @import("std");
lib/std/special/compiler_rt/floatuntisf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floatuntisf = @import("floatuntisf.zig").__floatuntisf;1const __floatuntisf = @import("floatuntisf.zig").__floatuntisf;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatuntitf.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const is_test = builtin.is_test;2const is_test = builtin.is_test;
8const std = @import("std");3const std = @import("std");
lib/std/special/compiler_rt/floatuntitf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __floatuntitf = @import("floatuntitf.zig").__floatuntitf;1const __floatuntitf = @import("floatuntitf.zig").__floatuntitf;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/int.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Builtin functions that operate on integer types1// Builtin functions that operate on integer types
7const builtin = @import("builtin");2const builtin = @import("builtin");
8const testing = @import("std").testing;3const testing = @import("std").testing;
lib/std/special/compiler_rt/lshrdi3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __lshrdi3 = @import("shift.zig").__lshrdi3;1const __lshrdi3 = @import("shift.zig").__lshrdi3;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/lshrti3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __lshrti3 = @import("shift.zig").__lshrti3;1const __lshrti3 = @import("shift.zig").__lshrti3;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/modti3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/blob/2ffb1b0413efa9a24eb3c49e710e36f92e2cb50b/compiler-rt/lib/builtins/modti3.c3// https://github.com/llvm/llvm-project/blob/2ffb1b0413efa9a24eb3c49e710e36f92e2cb50b/compiler-rt/lib/builtins/modti3.c
lib/std/special/compiler_rt/modti3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __modti3 = @import("modti3.zig").__modti3;1const __modti3 = @import("modti3.zig").__modti3;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/mulXf3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/blob/2ffb1b0413efa9a24eb3c49e710e36f92e2cb50b/compiler-rt/lib/builtins/fp_mul_impl.inc3// https://github.com/llvm/llvm-project/blob/2ffb1b0413efa9a24eb3c49e710e36f92e2cb50b/compiler-rt/lib/builtins/fp_mul_impl.inc
lib/std/special/compiler_rt/mulXf3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Ported from:1// Ported from:
7//2//
8// https://github.com/llvm/llvm-project/blob/2ffb1b0413efa9a24eb3c49e710e36f92e2cb50b/compiler-rt/test/builtins/Unit/multf3_test.c3// https://github.com/llvm/llvm-project/blob/2ffb1b0413efa9a24eb3c49e710e36f92e2cb50b/compiler-rt/test/builtins/Unit/multf3_test.c
lib/std/special/compiler_rt/muldi3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const is_test = std.builtin.is_test;2const is_test = std.builtin.is_test;
8const native_endian = std.Target.current.cpu.arch.endian();3const native_endian = std.Target.current.cpu.arch.endian();
lib/std/special/compiler_rt/muldi3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __muldi3 = @import("muldi3.zig").__muldi3;1const __muldi3 = @import("muldi3.zig").__muldi3;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/mulodi4.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const compiler_rt = @import("../compiler_rt.zig");2const compiler_rt = @import("../compiler_rt.zig");
8const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/mulodi4_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __mulodi4 = @import("mulodi4.zig").__mulodi4;1const __mulodi4 = @import("mulodi4.zig").__mulodi4;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/muloti4.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const compiler_rt = @import("../compiler_rt.zig");2const compiler_rt = @import("../compiler_rt.zig");
83
lib/std/special/compiler_rt/muloti4_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __muloti4 = @import("muloti4.zig").__muloti4;1const __muloti4 = @import("muloti4.zig").__muloti4;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/multi3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const compiler_rt = @import("../compiler_rt.zig");1const compiler_rt = @import("../compiler_rt.zig");
7const std = @import("std");2const std = @import("std");
8const is_test = std.builtin.is_test;3const is_test = std.builtin.is_test;
lib/std/special/compiler_rt/multi3_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __multi3 = @import("multi3.zig").__multi3;1const __multi3 = @import("multi3.zig").__multi3;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/negXf2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
72
8pub fn __negsf2(a: f32) callconv(.C) f32 {3pub fn __negsf2(a: f32) callconv(.C) f32 {
lib/std/special/compiler_rt/popcountdi2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const compiler_rt = @import("../compiler_rt.zig");2const compiler_rt = @import("../compiler_rt.zig");
83
lib/std/special/compiler_rt/popcountdi2_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __popcountdi2 = @import("popcountdi2.zig").__popcountdi2;1const __popcountdi2 = @import("popcountdi2.zig").__popcountdi2;
7const testing = @import("std").testing;2const testing = @import("std").testing;
83
lib/std/special/compiler_rt/shift.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const Log2Int = std.math.Log2Int;2const Log2Int = std.math.Log2Int;
8const native_endian = std.Target.current.cpu.arch.endian();3const native_endian = std.Target.current.cpu.arch.endian();
lib/std/special/compiler_rt/sparc.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2020 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6//1//
7// SPARC uses a different naming scheme for its support routines so we map it here to the x86 name.2// SPARC uses a different naming scheme for its support routines so we map it here to the x86 name.
83
lib/std/special/compiler_rt/stack_probe.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const native_arch = @import("std").Target.current.cpu.arch;1const native_arch = @import("std").Target.current.cpu.arch;
72
8// Zig's own stack-probe routine (available only on x86 and x86_64)3// Zig's own stack-probe routine (available only on x86 and x86_64)
lib/std/special/compiler_rt/truncXfYf2.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
72
8pub fn __truncsfhf2(a: f32) callconv(.C) u16 {3pub fn __truncsfhf2(a: f32) callconv(.C) u16 {
lib/std/special/compiler_rt/truncXfYf2_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const __truncsfhf2 = @import("truncXfYf2.zig").__truncsfhf2;1const __truncsfhf2 = @import("truncXfYf2.zig").__truncsfhf2;
72
8fn test__truncsfhf2(a: u32, expected: u16) !void {3fn test__truncsfhf2(a: u32, expected: u16) !void {
lib/std/special/compiler_rt/udivmod.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const is_test = builtin.is_test;2const is_test = builtin.is_test;
8const native_endian = @import("std").Target.current.cpu.arch.endian();3const native_endian = @import("std").Target.current.cpu.arch.endian();
lib/std/special/compiler_rt/udivmoddi4_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Disable formatting to avoid unnecessary source repository bloat.1// Disable formatting to avoid unnecessary source repository bloat.
7// zig fmt: off2// zig fmt: off
8const __udivmoddi4 = @import("int.zig").__udivmoddi4;3const __udivmoddi4 = @import("int.zig").__udivmoddi4;
lib/std/special/compiler_rt/udivmodti4.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const udivmod = @import("udivmod.zig").udivmod;1const udivmod = @import("udivmod.zig").udivmod;
7const builtin = @import("builtin");2const builtin = @import("builtin");
8const compiler_rt = @import("../compiler_rt.zig");3const compiler_rt = @import("../compiler_rt.zig");
lib/std/special/compiler_rt/udivmodti4_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// Disable formatting to avoid unnecessary source repository bloat.1// Disable formatting to avoid unnecessary source repository bloat.
7// zig fmt: off2// zig fmt: off
8const __udivmodti4 = @import("udivmodti4.zig").__udivmodti4;3const __udivmodti4 = @import("udivmodti4.zig").__udivmodti4;
lib/std/special/compiler_rt/udivti3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const udivmodti4 = @import("udivmodti4.zig");1const udivmodti4 = @import("udivmodti4.zig");
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/special/compiler_rt/umodti3.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const udivmodti4 = @import("udivmodti4.zig");1const udivmodti4 = @import("udivmodti4.zig");
7const builtin = @import("builtin");2const builtin = @import("builtin");
8const compiler_rt = @import("../compiler_rt.zig");3const compiler_rt = @import("../compiler_rt.zig");
lib/std/special/ssp.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6//1//
7// Small Zig reimplementation of gcc's libssp.2// Small Zig reimplementation of gcc's libssp.
8//3//
lib/std/special/test_runner.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const io = std.io;2const io = std.io;
8const builtin = @import("builtin");3const builtin = @import("builtin");
lib/std/start.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6// This file is included in the compilation unit when exporting an executable.1// This file is included in the compilation unit when exporting an executable.
72
8const root = @import("root");3const root = @import("root");
lib/std/start_windows_tls.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = @import("builtin");2const builtin = @import("builtin");
83
lib/std/std.zig+1-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6pub const ArrayHashMap = array_hash_map.ArrayHashMap;1pub const ArrayHashMap = array_hash_map.ArrayHashMap;
7pub const ArrayHashMapUnmanaged = array_hash_map.ArrayHashMapUnmanaged;2pub const ArrayHashMapUnmanaged = array_hash_map.ArrayHashMapUnmanaged;
8pub const ArrayList = @import("array_list.zig").ArrayList;3pub const ArrayList = @import("array_list.zig").ArrayList;
...@@ -13,6 +8,7 @@ pub const AutoArrayHashMap = array_hash_map.AutoArrayHashMap;...@@ -13,6 +8,7 @@ pub const AutoArrayHashMap = array_hash_map.AutoArrayHashMap;
13pub const AutoArrayHashMapUnmanaged = array_hash_map.AutoArrayHashMapUnmanaged;8pub const AutoArrayHashMapUnmanaged = array_hash_map.AutoArrayHashMapUnmanaged;
14pub const AutoHashMap = hash_map.AutoHashMap;9pub const AutoHashMap = hash_map.AutoHashMap;
15pub const AutoHashMapUnmanaged = hash_map.AutoHashMapUnmanaged;10pub const AutoHashMapUnmanaged = hash_map.AutoHashMapUnmanaged;
11pub const BoundedArray = @import("bounded_array.zig").BoundedArray;
16pub const BufMap = @import("buf_map.zig").BufMap;12pub const BufMap = @import("buf_map.zig").BufMap;
17pub const BufSet = @import("buf_set.zig").BufSet;13pub const BufSet = @import("buf_set.zig").BufSet;
18pub const ChildProcess = @import("child_process.zig").ChildProcess;14pub const ChildProcess = @import("child_process.zig").ChildProcess;
lib/std/target.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const mem = std.mem;2const mem = std.mem;
8const builtin = std.builtin;3const builtin = std.builtin;
lib/std/testing.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
72
8const math = std.math;3const math = std.math;
lib/std/testing/failing_allocator.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const mem = std.mem;2const mem = std.mem;
83
lib/std/time.zig+1-6
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const assert = std.debug.assert;3const assert = std.debug.assert;
...@@ -92,7 +87,7 @@ pub fn nanoTimestamp() i128 {...@@ -92,7 +87,7 @@ pub fn nanoTimestamp() i128 {
92 if (builtin.os.tag == .wasi and !builtin.link_libc) {87 if (builtin.os.tag == .wasi and !builtin.link_libc) {
93 var ns: os.wasi.timestamp_t = undefined;88 var ns: os.wasi.timestamp_t = undefined;
94 const err = os.wasi.clock_time_get(os.wasi.CLOCK_REALTIME, 1, &ns);89 const err = os.wasi.clock_time_get(os.wasi.CLOCK_REALTIME, 1, &ns);
95 assert(err == os.wasi.ESUCCESS);90 assert(err == .SUCCESS);
96 return ns;91 return ns;
97 }92 }
98 var ts: os.timespec = undefined;93 var ts: os.timespec = undefined;
lib/std/time/epoch.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6//! Epoch reference times in terms of their difference from1//! Epoch reference times in terms of their difference from
7//! UTC 1970-01-01 in seconds.2//! UTC 1970-01-01 in seconds.
83
lib/std/unicode.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("./std.zig");1const std = @import("./std.zig");
7const builtin = std.builtin;2const builtin = std.builtin;
8const assert = std.debug.assert;3const assert = std.debug.assert;
lib/std/unicode/throughput_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const builtin = std.builtin;2const builtin = std.builtin;
8const time = std.time;3const time = std.time;
lib/std/valgrind.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const builtin = @import("builtin");1const builtin = @import("builtin");
7const std = @import("std.zig");2const std = @import("std.zig");
8const math = std.math;3const math = std.math;
lib/std/valgrind/callgrind.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const valgrind = std.valgrind;2const valgrind = std.valgrind;
83
lib/std/valgrind/memcheck.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const testing = std.testing;2const testing = std.testing;
8const valgrind = std.valgrind;3const valgrind = std.valgrind;
lib/std/wasm.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const testing = @import("std.zig").testing;1const testing = @import("std.zig").testing;
72
8// TODO: Add support for multi-byte ops (e.g. table operations)3// TODO: Add support for multi-byte ops (e.g. table operations)
lib/std/x.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std.zig");1const std = @import("std.zig");
82
9pub const os = struct {3pub const os = struct {
lib/std/x/net/ip.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../../std.zig");1const std = @import("../../std.zig");
82
9const fmt = std.fmt;3const fmt = std.fmt;
lib/std/x/net/tcp.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../../std.zig");1const std = @import("../../std.zig");
82
9const io = std.io;3const io = std.io;
lib/std/x/os/net.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../../std.zig");1const std = @import("../../std.zig");
82
9const os = std.os;3const os = std.os;
lib/std/x/os/socket.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../../std.zig");1const std = @import("../../std.zig");
8const net = @import("net.zig");2const net = @import("net.zig");
93
lib/std/x/os/socket_posix.zig+49-55
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../../std.zig");1const std = @import("../../std.zig");
82
9const os = std.os;3const os = std.os;
...@@ -82,32 +76,32 @@ pub fn Mixin(comptime Socket: type) type {...@@ -82,32 +76,32 @@ pub fn Mixin(comptime Socket: type) type {
82 while (true) {76 while (true) {
83 const rc = os.system.sendmsg(self.fd, &msg, @intCast(c_int, flags));77 const rc = os.system.sendmsg(self.fd, &msg, @intCast(c_int, flags));
84 return switch (os.errno(rc)) {78 return switch (os.errno(rc)) {
85 0 => return @intCast(usize, rc),79 .SUCCESS => return @intCast(usize, rc),
86 os.EACCES => error.AccessDenied,80 .ACCES => error.AccessDenied,
87 os.EAGAIN => error.WouldBlock,81 .AGAIN => error.WouldBlock,
88 os.EALREADY => error.FastOpenAlreadyInProgress,82 .ALREADY => error.FastOpenAlreadyInProgress,
89 os.EBADF => unreachable, // always a race condition83 .BADF => unreachable, // always a race condition
90 os.ECONNRESET => error.ConnectionResetByPeer,84 .CONNRESET => error.ConnectionResetByPeer,
91 os.EDESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set.85 .DESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set.
92 os.EFAULT => unreachable, // An invalid user space address was specified for an argument.86 .FAULT => unreachable, // An invalid user space address was specified for an argument.
93 os.EINTR => continue,87 .INTR => continue,
94 os.EINVAL => unreachable, // Invalid argument passed.88 .INVAL => unreachable, // Invalid argument passed.
95 os.EISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified89 .ISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified
96 os.EMSGSIZE => error.MessageTooBig,90 .MSGSIZE => error.MessageTooBig,
97 os.ENOBUFS => error.SystemResources,91 .NOBUFS => error.SystemResources,
98 os.ENOMEM => error.SystemResources,92 .NOMEM => error.SystemResources,
99 os.ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.93 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
100 os.EOPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type.94 .OPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type.
101 os.EPIPE => error.BrokenPipe,95 .PIPE => error.BrokenPipe,
102 os.EAFNOSUPPORT => error.AddressFamilyNotSupported,96 .AFNOSUPPORT => error.AddressFamilyNotSupported,
103 os.ELOOP => error.SymLinkLoop,97 .LOOP => error.SymLinkLoop,
104 os.ENAMETOOLONG => error.NameTooLong,98 .NAMETOOLONG => error.NameTooLong,
105 os.ENOENT => error.FileNotFound,99 .NOENT => error.FileNotFound,
106 os.ENOTDIR => error.NotDir,100 .NOTDIR => error.NotDir,
107 os.EHOSTUNREACH => error.NetworkUnreachable,101 .HOSTUNREACH => error.NetworkUnreachable,
108 os.ENETUNREACH => error.NetworkUnreachable,102 .NETUNREACH => error.NetworkUnreachable,
109 os.ENOTCONN => error.SocketNotConnected,103 .NOTCONN => error.SocketNotConnected,
110 os.ENETDOWN => error.NetworkSubsystemFailed,104 .NETDOWN => error.NetworkSubsystemFailed,
111 else => |err| os.unexpectedErrno(err),105 else => |err| os.unexpectedErrno(err),
112 };106 };
113 }107 }
...@@ -120,17 +114,17 @@ pub fn Mixin(comptime Socket: type) type {...@@ -120,17 +114,17 @@ pub fn Mixin(comptime Socket: type) type {
120 while (true) {114 while (true) {
121 const rc = os.system.recvmsg(self.fd, msg, @intCast(c_int, flags));115 const rc = os.system.recvmsg(self.fd, msg, @intCast(c_int, flags));
122 return switch (os.errno(rc)) {116 return switch (os.errno(rc)) {
123 0 => @intCast(usize, rc),117 .SUCCESS => @intCast(usize, rc),
124 os.EBADF => unreachable, // always a race condition118 .BADF => unreachable, // always a race condition
125 os.EFAULT => unreachable,119 .FAULT => unreachable,
126 os.EINVAL => unreachable,120 .INVAL => unreachable,
127 os.ENOTCONN => unreachable,121 .NOTCONN => unreachable,
128 os.ENOTSOCK => unreachable,122 .NOTSOCK => unreachable,
129 os.EINTR => continue,123 .INTR => continue,
130 os.EAGAIN => error.WouldBlock,124 .AGAIN => error.WouldBlock,
131 os.ENOMEM => error.SystemResources,125 .NOMEM => error.SystemResources,
132 os.ECONNREFUSED => error.ConnectionRefused,126 .CONNREFUSED => error.ConnectionRefused,
133 os.ECONNRESET => error.ConnectionResetByPeer,127 .CONNRESET => error.ConnectionResetByPeer,
134 else => |err| os.unexpectedErrno(err),128 else => |err| os.unexpectedErrno(err),
135 };129 };
136 }130 }
...@@ -164,12 +158,12 @@ pub fn Mixin(comptime Socket: type) type {...@@ -164,12 +158,12 @@ pub fn Mixin(comptime Socket: type) type {
164158
165 const rc = os.system.getsockopt(self.fd, os.SOL_SOCKET, os.SO_RCVBUF, mem.asBytes(&value), &value_len);159 const rc = os.system.getsockopt(self.fd, os.SOL_SOCKET, os.SO_RCVBUF, mem.asBytes(&value), &value_len);
166 return switch (os.errno(rc)) {160 return switch (os.errno(rc)) {
167 0 => value,161 .SUCCESS => value,
168 os.EBADF => error.BadFileDescriptor,162 .BADF => error.BadFileDescriptor,
169 os.EFAULT => error.InvalidAddressSpace,163 .FAULT => error.InvalidAddressSpace,
170 os.EINVAL => error.InvalidSocketOption,164 .INVAL => error.InvalidSocketOption,
171 os.ENOPROTOOPT => error.UnknownSocketOption,165 .NOPROTOOPT => error.UnknownSocketOption,
172 os.ENOTSOCK => error.NotASocket,166 .NOTSOCK => error.NotASocket,
173 else => |err| os.unexpectedErrno(err),167 else => |err| os.unexpectedErrno(err),
174 };168 };
175 }169 }
...@@ -181,12 +175,12 @@ pub fn Mixin(comptime Socket: type) type {...@@ -181,12 +175,12 @@ pub fn Mixin(comptime Socket: type) type {
181175
182 const rc = os.system.getsockopt(self.fd, os.SOL_SOCKET, os.SO_SNDBUF, mem.asBytes(&value), &value_len);176 const rc = os.system.getsockopt(self.fd, os.SOL_SOCKET, os.SO_SNDBUF, mem.asBytes(&value), &value_len);
183 return switch (os.errno(rc)) {177 return switch (os.errno(rc)) {
184 0 => value,178 .SUCCESS => value,
185 os.EBADF => error.BadFileDescriptor,179 .BADF => error.BadFileDescriptor,
186 os.EFAULT => error.InvalidAddressSpace,180 .FAULT => error.InvalidAddressSpace,
187 os.EINVAL => error.InvalidSocketOption,181 .INVAL => error.InvalidSocketOption,
188 os.ENOPROTOOPT => error.UnknownSocketOption,182 .NOPROTOOPT => error.UnknownSocketOption,
189 os.ENOTSOCK => error.NotASocket,183 .NOTSOCK => error.NotASocket,
190 else => |err| os.unexpectedErrno(err),184 else => |err| os.unexpectedErrno(err),
191 };185 };
192 }186 }
lib/std/x/os/socket_windows.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("../../std.zig");1const std = @import("../../std.zig");
8const net = @import("net.zig");2const net = @import("net.zig");
93
lib/std/zig.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std.zig");1const std = @import("std.zig");
7const tokenizer = @import("zig/tokenizer.zig");2const tokenizer = @import("zig/tokenizer.zig");
8const fmt = @import("zig/fmt.zig");3const fmt = @import("zig/fmt.zig");
lib/std/zig/ast.zig-21
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const testing = std.testing;3const testing = std.testing;
...@@ -351,10 +346,6 @@ pub const Tree = struct {...@@ -351,10 +346,6 @@ pub const Tree = struct {
351 .char_literal,346 .char_literal,
352 .integer_literal,347 .integer_literal,
353 .float_literal,348 .float_literal,
354 .false_literal,
355 .true_literal,
356 .null_literal,
357 .undefined_literal,
358 .unreachable_literal,349 .unreachable_literal,
359 .string_literal,350 .string_literal,
360 .multiline_string_literal,351 .multiline_string_literal,
...@@ -716,10 +707,6 @@ pub const Tree = struct {...@@ -716,10 +707,6 @@ pub const Tree = struct {
716 .char_literal,707 .char_literal,
717 .integer_literal,708 .integer_literal,
718 .float_literal,709 .float_literal,
719 .false_literal,
720 .true_literal,
721 .null_literal,
722 .undefined_literal,
723 .unreachable_literal,710 .unreachable_literal,
724 .identifier,711 .identifier,
725 .deref,712 .deref,
...@@ -2762,14 +2749,6 @@ pub const Node = struct {...@@ -2762,14 +2749,6 @@ pub const Node = struct {
2762 /// Both lhs and rhs unused.2749 /// Both lhs and rhs unused.
2763 float_literal,2750 float_literal,
2764 /// Both lhs and rhs unused.2751 /// Both lhs and rhs unused.
2765 false_literal,
2766 /// Both lhs and rhs unused.
2767 true_literal,
2768 /// Both lhs and rhs unused.
2769 null_literal,
2770 /// Both lhs and rhs unused.
2771 undefined_literal,
2772 /// Both lhs and rhs unused.
2773 unreachable_literal,2752 unreachable_literal,
2774 /// Both lhs and rhs unused.2753 /// Both lhs and rhs unused.
2775 /// Most identifiers will not have explicit AST nodes, however for expressions2754 /// Most identifiers will not have explicit AST nodes, however for expressions
lib/std/zig/c_builtins.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
82
9pub inline fn __builtin_bswap16(val: u16) u16 {3pub inline fn __builtin_bswap16(val: u16) u16 {
lib/std/zig/c_translation.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");1const std = @import("std");
8const testing = std.testing;2const testing = std.testing;
9const math = std.math;3const math = std.math;
lib/std/zig/cross_target.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const Target = std.Target;3const Target = std.Target;
lib/std/zig/parse.zig-41
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const Allocator = std.mem.Allocator;3const Allocator = std.mem.Allocator;
...@@ -2231,11 +2226,7 @@ const Parser = struct {...@@ -2231,11 +2226,7 @@ const Parser = struct {
2231 /// / INTEGER2226 /// / INTEGER
2232 /// / KEYWORD_comptime TypeExpr2227 /// / KEYWORD_comptime TypeExpr
2233 /// / KEYWORD_error DOT IDENTIFIER2228 /// / KEYWORD_error DOT IDENTIFIER
2234 /// / KEYWORD_false
2235 /// / KEYWORD_null
2236 /// / KEYWORD_anyframe2229 /// / KEYWORD_anyframe
2237 /// / KEYWORD_true
2238 /// / KEYWORD_undefined
2239 /// / KEYWORD_unreachable2230 /// / KEYWORD_unreachable
2240 /// / STRINGLITERAL2231 /// / STRINGLITERAL
2241 /// / SwitchExpr2232 /// / SwitchExpr
...@@ -2278,38 +2269,6 @@ const Parser = struct {...@@ -2278,38 +2269,6 @@ const Parser = struct {
2278 .rhs = undefined,2269 .rhs = undefined,
2279 },2270 },
2280 }),2271 }),
2281 .keyword_false => return p.addNode(.{
2282 .tag = .false_literal,
2283 .main_token = p.nextToken(),
2284 .data = .{
2285 .lhs = undefined,
2286 .rhs = undefined,
2287 },
2288 }),
2289 .keyword_true => return p.addNode(.{
2290 .tag = .true_literal,
2291 .main_token = p.nextToken(),
2292 .data = .{
2293 .lhs = undefined,
2294 .rhs = undefined,
2295 },
2296 }),
2297 .keyword_null => return p.addNode(.{
2298 .tag = .null_literal,
2299 .main_token = p.nextToken(),
2300 .data = .{
2301 .lhs = undefined,
2302 .rhs = undefined,
2303 },
2304 }),
2305 .keyword_undefined => return p.addNode(.{
2306 .tag = .undefined_literal,
2307 .main_token = p.nextToken(),
2308 .data = .{
2309 .lhs = undefined,
2310 .rhs = undefined,
2311 },
2312 }),
2313 .keyword_unreachable => return p.addNode(.{2272 .keyword_unreachable => return p.addNode(.{
2314 .tag = .unreachable_literal,2273 .tag = .unreachable_literal,
2315 .main_token = p.nextToken(),2274 .main_token = p.nextToken(),
lib/std/zig/parser_test.zig-6
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7test "zig fmt: preserves clobbers in inline asm with stray comma" {1test "zig fmt: preserves clobbers in inline asm with stray comma" {
8 try testTransform(2 try testTransform(
9 \\fn foo() void {3 \\fn foo() void {
lib/std/zig/perf_test.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const mem = std.mem;2const mem = std.mem;
8const warn = std.debug.warn;3const warn = std.debug.warn;
lib/std/zig/render.zig-9
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const mem = std.mem;3const mem = std.mem;
...@@ -192,11 +187,7 @@ fn renderExpression(gpa: *Allocator, ais: *Ais, tree: ast.Tree, node: ast.Node.I...@@ -192,11 +187,7 @@ fn renderExpression(gpa: *Allocator, ais: *Ais, tree: ast.Tree, node: ast.Node.I
192 .integer_literal,187 .integer_literal,
193 .float_literal,188 .float_literal,
194 .char_literal,189 .char_literal,
195 .true_literal,
196 .false_literal,
197 .null_literal,
198 .unreachable_literal,190 .unreachable_literal,
199 .undefined_literal,
200 .anyframe_literal,191 .anyframe_literal,
201 .string_literal,192 .string_literal,
202 => return renderToken(ais, tree, main_tokens[node], space),193 => return renderToken(ais, tree, main_tokens[node], space),
lib/std/zig/string_literal.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const assert = std.debug.assert;2const assert = std.debug.assert;
83
lib/std/zig/system.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const elf = std.elf;2const elf = std.elf;
8const mem = std.mem;3const mem = std.mem;
lib/std/zig/system/darwin.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const mem = std.mem;2const mem = std.mem;
8const Allocator = mem.Allocator;3const Allocator = mem.Allocator;
lib/std/zig/system/darwin/macos.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const assert = std.debug.assert;2const assert = std.debug.assert;
8const mem = std.mem;3const mem = std.mem;
lib/std/zig/system/windows.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2020 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
72
8pub const WindowsVersion = std.Target.Os.WindowsVersion;3pub const WindowsVersion = std.Target.Os.WindowsVersion;
lib/std/zig/system/x86.zig-5
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("std");1const std = @import("std");
7const Target = std.Target;2const Target = std.Target;
8const CrossTarget = std.zig.CrossTarget;3const CrossTarget = std.zig.CrossTarget;
lib/std/zig/tokenizer.zig-17
...@@ -1,8 +1,3 @@...@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6const std = @import("../std.zig");1const std = @import("../std.zig");
7const mem = std.mem;2const mem = std.mem;
83
...@@ -37,7 +32,6 @@ pub const Token = struct {...@@ -37,7 +32,6 @@ pub const Token = struct {
37 .{ "error", .keyword_error },32 .{ "error", .keyword_error },
38 .{ "export", .keyword_export },33 .{ "export", .keyword_export },
39 .{ "extern", .keyword_extern },34 .{ "extern", .keyword_extern },
40 .{ "false", .keyword_false },
41 .{ "fn", .keyword_fn },35 .{ "fn", .keyword_fn },
42 .{ "for", .keyword_for },36 .{ "for", .keyword_for },
43 .{ "if", .keyword_if },37 .{ "if", .keyword_if },
...@@ -45,7 +39,6 @@ pub const Token = struct {...@@ -45,7 +39,6 @@ pub const Token = struct {
45 .{ "noalias", .keyword_noalias },39 .{ "noalias", .keyword_noalias },
46 .{ "noinline", .keyword_noinline },40 .{ "noinline", .keyword_noinline },
47 .{ "nosuspend", .keyword_nosuspend },41 .{ "nosuspend", .keyword_nosuspend },
48 .{ "null", .keyword_null },
49 .{ "opaque", .keyword_opaque },42 .{ "opaque", .keyword_opaque },
50 .{ "or", .keyword_or },43 .{ "or", .keyword_or },
51 .{ "orelse", .keyword_orelse },44 .{ "orelse", .keyword_orelse },
...@@ -59,9 +52,7 @@ pub const Token = struct {...@@ -59,9 +52,7 @@ pub const Token = struct {
59 .{ "switch", .keyword_switch },52 .{ "switch", .keyword_switch },
60 .{ "test", .keyword_test },53 .{ "test", .keyword_test },
61 .{ "threadlocal", .keyword_threadlocal },54 .{ "threadlocal", .keyword_threadlocal },
62 .{ "true", .keyword_true },
63 .{ "try", .keyword_try },55 .{ "try", .keyword_try },
64 .{ "undefined", .keyword_undefined },
65 .{ "union", .keyword_union },56 .{ "union", .keyword_union },
66 .{ "unreachable", .keyword_unreachable },57 .{ "unreachable", .keyword_unreachable },
67 .{ "usingnamespace", .keyword_usingnamespace },58 .{ "usingnamespace", .keyword_usingnamespace },
...@@ -162,7 +153,6 @@ pub const Token = struct {...@@ -162,7 +153,6 @@ pub const Token = struct {
162 keyword_error,153 keyword_error,
163 keyword_export,154 keyword_export,
164 keyword_extern,155 keyword_extern,
165 keyword_false,
166 keyword_fn,156 keyword_fn,
167 keyword_for,157 keyword_for,
168 keyword_if,158 keyword_if,
...@@ -170,7 +160,6 @@ pub const Token = struct {...@@ -170,7 +160,6 @@ pub const Token = struct {
170 keyword_noalias,160 keyword_noalias,
171 keyword_noinline,161 keyword_noinline,
172 keyword_nosuspend,162 keyword_nosuspend,
173 keyword_null,
174 keyword_opaque,163 keyword_opaque,
175 keyword_or,164 keyword_or,
176 keyword_orelse,165 keyword_orelse,
...@@ -184,9 +173,7 @@ pub const Token = struct {...@@ -184,9 +173,7 @@ pub const Token = struct {
184 keyword_switch,173 keyword_switch,
185 keyword_test,174 keyword_test,
186 keyword_threadlocal,175 keyword_threadlocal,
187 keyword_true,
188 keyword_try,176 keyword_try,
189 keyword_undefined,
190 keyword_union,177 keyword_union,
191 keyword_unreachable,178 keyword_unreachable,
192 keyword_usingnamespace,179 keyword_usingnamespace,
...@@ -285,7 +272,6 @@ pub const Token = struct {...@@ -285,7 +272,6 @@ pub const Token = struct {
285 .keyword_error => "error",272 .keyword_error => "error",
286 .keyword_export => "export",273 .keyword_export => "export",
287 .keyword_extern => "extern",274 .keyword_extern => "extern",
288 .keyword_false => "false",
289 .keyword_fn => "fn",275 .keyword_fn => "fn",
290 .keyword_for => "for",276 .keyword_for => "for",
291 .keyword_if => "if",277 .keyword_if => "if",
...@@ -293,7 +279,6 @@ pub const Token = struct {...@@ -293,7 +279,6 @@ pub const Token = struct {
293 .keyword_noalias => "noalias",279 .keyword_noalias => "noalias",
294 .keyword_noinline => "noinline",280 .keyword_noinline => "noinline",
295 .keyword_nosuspend => "nosuspend",281 .keyword_nosuspend => "nosuspend",
296 .keyword_null => "null",
297 .keyword_opaque => "opaque",282 .keyword_opaque => "opaque",
298 .keyword_or => "or",283 .keyword_or => "or",
299 .keyword_orelse => "orelse",284 .keyword_orelse => "orelse",
...@@ -307,9 +292,7 @@ pub const Token = struct {...@@ -307,9 +292,7 @@ pub const Token = struct {
307 .keyword_switch => "switch",292 .keyword_switch => "switch",
308 .keyword_test => "test",293 .keyword_test => "test",
309 .keyword_threadlocal => "threadlocal",294 .keyword_threadlocal => "threadlocal",
310 .keyword_true => "true",
311 .keyword_try => "try",295 .keyword_try => "try",
312 .keyword_undefined => "undefined",
313 .keyword_union => "union",296 .keyword_union => "union",
314 .keyword_unreachable => "unreachable",297 .keyword_unreachable => "unreachable",
315 .keyword_usingnamespace => "usingnamespace",298 .keyword_usingnamespace => "usingnamespace",
src/Air.zig+31-2
...@@ -94,6 +94,12 @@ pub const Inst = struct {...@@ -94,6 +94,12 @@ pub const Inst = struct {
94 /// Result type is the same as both operands.94 /// Result type is the same as both operands.
95 /// Uses the `bin_op` field.95 /// Uses the `bin_op` field.
96 bit_or,96 bit_or,
97 /// Shift right. `>>`
98 /// Uses the `bin_op` field.
99 shr,
100 /// Shift left. `<<`
101 /// Uses the `bin_op` field.
102 shl,
97 /// Bitwise XOR. `^`103 /// Bitwise XOR. `^`
98 /// Uses the `bin_op` field.104 /// Uses the `bin_op` field.
99 xor,105 xor,
...@@ -258,6 +264,13 @@ pub const Inst = struct {...@@ -258,6 +264,13 @@ pub const Inst = struct {
258 /// Given a pointer to a struct and a field index, returns a pointer to the field.264 /// Given a pointer to a struct and a field index, returns a pointer to the field.
259 /// Uses the `ty_pl` field, payload is `StructField`.265 /// Uses the `ty_pl` field, payload is `StructField`.
260 struct_field_ptr,266 struct_field_ptr,
267 /// Given a pointer to a struct, returns a pointer to the field.
268 /// The field index is the number at the end of the name.
269 /// Uses `ty_op` field.
270 struct_field_ptr_index_0,
271 struct_field_ptr_index_1,
272 struct_field_ptr_index_2,
273 struct_field_ptr_index_3,
261 /// Given a byval struct and a field index, returns the field byval.274 /// Given a byval struct and a field index, returns the field byval.
262 /// Uses the `ty_pl` field, payload is `StructField`.275 /// Uses the `ty_pl` field, payload is `StructField`.
263 struct_field_val,276 struct_field_val,
...@@ -280,6 +293,10 @@ pub const Inst = struct {...@@ -280,6 +293,10 @@ pub const Inst = struct {
280 /// Result type is the element type of the pointer operand.293 /// Result type is the element type of the pointer operand.
281 /// Uses the `bin_op` field.294 /// Uses the `bin_op` field.
282 ptr_elem_val,295 ptr_elem_val,
296 /// Given a pointer value, and element index, return the element pointer at that index.
297 /// Result type is pointer to the element type of the pointer operand.
298 /// Uses the `ty_pl` field with payload `Bin`.
299 ptr_elem_ptr,
283 /// Given a pointer to a pointer, and element index, return the element value of the inner300 /// Given a pointer to a pointer, and element index, return the element value of the inner
284 /// pointer at that index.301 /// pointer at that index.
285 /// Result type is the element type of the inner pointer operand.302 /// Result type is the element type of the inner pointer operand.
...@@ -404,6 +421,11 @@ pub const StructField = struct {...@@ -404,6 +421,11 @@ pub const StructField = struct {
404 field_index: u32,421 field_index: u32,
405};422};
406423
424pub const Bin = struct {
425 lhs: Inst.Ref,
426 rhs: Inst.Ref,
427};
428
407/// Trailing:429/// Trailing:
408/// 0. `Inst.Ref` for every outputs_len430/// 0. `Inst.Ref` for every outputs_len
409/// 1. `Inst.Ref` for every inputs_len431/// 1. `Inst.Ref` for every inputs_len
...@@ -445,6 +467,8 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {...@@ -445,6 +467,8 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {
445 .xor,467 .xor,
446 .ptr_add,468 .ptr_add,
447 .ptr_sub,469 .ptr_sub,
470 .shr,
471 .shl,
448 => return air.typeOf(datas[inst].bin_op.lhs),472 => return air.typeOf(datas[inst].bin_op.lhs),
449473
450 .cmp_lt,474 .cmp_lt,
...@@ -474,6 +498,7 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {...@@ -474,6 +498,7 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {
474 .constant,498 .constant,
475 .struct_field_ptr,499 .struct_field_ptr,
476 .struct_field_val,500 .struct_field_val,
501 .ptr_elem_ptr,
477 => return air.getRefType(datas[inst].ty_pl.ty),502 => return air.getRefType(datas[inst].ty_pl.ty),
478503
479 .not,504 .not,
...@@ -492,6 +517,10 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {...@@ -492,6 +517,10 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {
492 .wrap_errunion_payload,517 .wrap_errunion_payload,
493 .wrap_errunion_err,518 .wrap_errunion_err,
494 .slice_ptr,519 .slice_ptr,
520 .struct_field_ptr_index_0,
521 .struct_field_ptr_index_1,
522 .struct_field_ptr_index_2,
523 .struct_field_ptr_index_3,
495 => return air.getRefType(datas[inst].ty_op.ty),524 => return air.getRefType(datas[inst].ty_op.ty),
496525
497 .loop,526 .loop,
...@@ -519,8 +548,8 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {...@@ -519,8 +548,8 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {
519 },548 },
520549
521 .slice_elem_val, .ptr_elem_val => {550 .slice_elem_val, .ptr_elem_val => {
522 const slice_ty = air.typeOf(datas[inst].bin_op.lhs);551 const ptr_ty = air.typeOf(datas[inst].bin_op.lhs);
523 return slice_ty.elemType();552 return ptr_ty.elemType();
524 },553 },
525 .ptr_slice_elem_val, .ptr_ptr_elem_val => {554 .ptr_slice_elem_val, .ptr_ptr_elem_val => {
526 const outer_ptr_ty = air.typeOf(datas[inst].bin_op.lhs);555 const outer_ptr_ty = air.typeOf(datas[inst].bin_op.lhs);
src/AstGen.zig+158-106
...@@ -370,10 +370,6 @@ fn lvalExpr(gz: *GenZir, scope: *Scope, node: ast.Node.Index) InnerError!Zir.Ins...@@ -370,10 +370,6 @@ fn lvalExpr(gz: *GenZir, scope: *Scope, node: ast.Node.Index) InnerError!Zir.Ins
370 .bool_not,370 .bool_not,
371 .address_of,371 .address_of,
372 .float_literal,372 .float_literal,
373 .undefined_literal,
374 .true_literal,
375 .false_literal,
376 .null_literal,
377 .optional_type,373 .optional_type,
378 .block,374 .block,
379 .block_semicolon,375 .block_semicolon,
...@@ -698,7 +694,13 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr...@@ -698,7 +694,13 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr
698 .lhs = lhs,694 .lhs = lhs,
699 .start = start,695 .start = start,
700 });696 });
701 return rvalue(gz, rl, result, node);697 switch (rl) {
698 .ref, .none_or_ref => return result,
699 else => {
700 const dereffed = try gz.addUnNode(.load, result, node);
701 return rvalue(gz, rl, dereffed, node);
702 },
703 }
702 },704 },
703 .slice => {705 .slice => {
704 const lhs = try expr(gz, scope, .ref, node_datas[node].lhs);706 const lhs = try expr(gz, scope, .ref, node_datas[node].lhs);
...@@ -710,7 +712,13 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr...@@ -710,7 +712,13 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr
710 .start = start,712 .start = start,
711 .end = end,713 .end = end,
712 });714 });
713 return rvalue(gz, rl, result, node);715 switch (rl) {
716 .ref, .none_or_ref => return result,
717 else => {
718 const dereffed = try gz.addUnNode(.load, result, node);
719 return rvalue(gz, rl, dereffed, node);
720 },
721 }
714 },722 },
715 .slice_sentinel => {723 .slice_sentinel => {
716 const lhs = try expr(gz, scope, .ref, node_datas[node].lhs);724 const lhs = try expr(gz, scope, .ref, node_datas[node].lhs);
...@@ -724,7 +732,13 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr...@@ -724,7 +732,13 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr
724 .end = end,732 .end = end,
725 .sentinel = sentinel,733 .sentinel = sentinel,
726 });734 });
727 return rvalue(gz, rl, result, node);735 switch (rl) {
736 .ref, .none_or_ref => return result,
737 else => {
738 const dereffed = try gz.addUnNode(.load, result, node);
739 return rvalue(gz, rl, dereffed, node);
740 },
741 }
728 },742 },
729743
730 .deref => {744 .deref => {
...@@ -741,10 +755,6 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr...@@ -741,10 +755,6 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr
741 const result = try expr(gz, scope, .ref, node_datas[node].lhs);755 const result = try expr(gz, scope, .ref, node_datas[node].lhs);
742 return rvalue(gz, rl, result, node);756 return rvalue(gz, rl, result, node);
743 },757 },
744 .undefined_literal => return rvalue(gz, rl, .undef, node),
745 .true_literal => return rvalue(gz, rl, .bool_true, node),
746 .false_literal => return rvalue(gz, rl, .bool_false, node),
747 .null_literal => return rvalue(gz, rl, .null_value, node),
748 .optional_type => {758 .optional_type => {
749 const operand = try typeExpr(gz, scope, node_datas[node].lhs);759 const operand = try typeExpr(gz, scope, node_datas[node].lhs);
750 const result = try gz.addUnNode(.optional_type, operand, node);760 const result = try gz.addUnNode(.optional_type, operand, node);
...@@ -2367,7 +2377,7 @@ fn varDecl(...@@ -2367,7 +2377,7 @@ fn varDecl(
2367 }2377 }
2368 const ident_name = try astgen.identAsString(name_token);2378 const ident_name = try astgen.identAsString(name_token);
23692379
2370 try astgen.detectLocalShadowing(scope, ident_name, name_token);2380 try astgen.detectLocalShadowing(scope, ident_name, name_token, ident_name_raw);
23712381
2372 if (var_decl.ast.init_node == 0) {2382 if (var_decl.ast.init_node == 0) {
2373 return astgen.failNode(node, "variables must be initialized", .{});2383 return astgen.failNode(node, "variables must be initialized", .{});
...@@ -2873,7 +2883,7 @@ fn fnDecl(...@@ -2873,7 +2883,7 @@ fn fnDecl(
2873 };2883 };
2874 const fn_name_str_index = try astgen.identAsString(fn_name_token);2884 const fn_name_str_index = try astgen.identAsString(fn_name_token);
28752885
2876 try astgen.declareNewName(scope, fn_name_str_index, decl_node);2886 try astgen.declareNewName(scope, fn_name_str_index, decl_node, fn_name_token);
28772887
2878 // We insert this at the beginning so that its instruction index marks the2888 // We insert this at the beginning so that its instruction index marks the
2879 // start of the top level declaration.2889 // start of the top level declaration.
...@@ -2934,12 +2944,13 @@ fn fnDecl(...@@ -2934,12 +2944,13 @@ fn fnDecl(
2934 } else false;2944 } else false;
29352945
2936 const param_name: u32 = if (param.name_token) |name_token| blk: {2946 const param_name: u32 = if (param.name_token) |name_token| blk: {
2937 if (mem.eql(u8, "_", tree.tokenSlice(name_token)))2947 const name_bytes = tree.tokenSlice(name_token);
2948 if (mem.eql(u8, "_", name_bytes))
2938 break :blk 0;2949 break :blk 0;
29392950
2940 const param_name = try astgen.identAsString(name_token);2951 const param_name = try astgen.identAsString(name_token);
2941 if (!is_extern) {2952 if (!is_extern) {
2942 try astgen.detectLocalShadowing(params_scope, param_name, name_token);2953 try astgen.detectLocalShadowing(params_scope, param_name, name_token, name_bytes);
2943 }2954 }
2944 break :blk param_name;2955 break :blk param_name;
2945 } else if (!is_extern) {2956 } else if (!is_extern) {
...@@ -3142,7 +3153,7 @@ fn globalVarDecl(...@@ -3142,7 +3153,7 @@ fn globalVarDecl(
3142 const name_token = var_decl.ast.mut_token + 1;3153 const name_token = var_decl.ast.mut_token + 1;
3143 const name_str_index = try astgen.identAsString(name_token);3154 const name_str_index = try astgen.identAsString(name_token);
31443155
3145 try astgen.declareNewName(scope, name_str_index, node);3156 try astgen.declareNewName(scope, name_str_index, node, name_token);
31463157
3147 var block_scope: GenZir = .{3158 var block_scope: GenZir = .{
3148 .parent = scope,3159 .parent = scope,
...@@ -5017,7 +5028,7 @@ fn ifExpr(...@@ -5017,7 +5028,7 @@ fn ifExpr(
5017 const token_name_str = tree.tokenSlice(token_name_index);5028 const token_name_str = tree.tokenSlice(token_name_index);
5018 if (mem.eql(u8, "_", token_name_str))5029 if (mem.eql(u8, "_", token_name_str))
5019 break :s &then_scope.base;5030 break :s &then_scope.base;
5020 try astgen.detectLocalShadowing(&then_scope.base, ident_name, token_name_index);5031 try astgen.detectLocalShadowing(&then_scope.base, ident_name, token_name_index, token_name_str);
5021 payload_val_scope = .{5032 payload_val_scope = .{
5022 .parent = &then_scope.base,5033 .parent = &then_scope.base,
5023 .gen_zir = &then_scope,5034 .gen_zir = &then_scope,
...@@ -5036,11 +5047,12 @@ fn ifExpr(...@@ -5036,11 +5047,12 @@ fn ifExpr(
5036 .optional_payload_unsafe_ptr5047 .optional_payload_unsafe_ptr
5037 else5048 else
5038 .optional_payload_unsafe;5049 .optional_payload_unsafe;
5039 if (mem.eql(u8, "_", tree.tokenSlice(ident_token)))5050 const ident_bytes = tree.tokenSlice(ident_token);
5051 if (mem.eql(u8, "_", ident_bytes))
5040 break :s &then_scope.base;5052 break :s &then_scope.base;
5041 const payload_inst = try then_scope.addUnNode(tag, cond.inst, node);5053 const payload_inst = try then_scope.addUnNode(tag, cond.inst, node);
5042 const ident_name = try astgen.identAsString(ident_token);5054 const ident_name = try astgen.identAsString(ident_token);
5043 try astgen.detectLocalShadowing(&then_scope.base, ident_name, ident_token);5055 try astgen.detectLocalShadowing(&then_scope.base, ident_name, ident_token, ident_bytes);
5044 payload_val_scope = .{5056 payload_val_scope = .{
5045 .parent = &then_scope.base,5057 .parent = &then_scope.base,
5046 .gen_zir = &then_scope,5058 .gen_zir = &then_scope,
...@@ -5082,7 +5094,7 @@ fn ifExpr(...@@ -5082,7 +5094,7 @@ fn ifExpr(
5082 const error_token_str = tree.tokenSlice(error_token);5094 const error_token_str = tree.tokenSlice(error_token);
5083 if (mem.eql(u8, "_", error_token_str))5095 if (mem.eql(u8, "_", error_token_str))
5084 break :s &else_scope.base;5096 break :s &else_scope.base;
5085 try astgen.detectLocalShadowing(&else_scope.base, ident_name, error_token);5097 try astgen.detectLocalShadowing(&else_scope.base, ident_name, error_token, error_token_str);
5086 payload_val_scope = .{5098 payload_val_scope = .{
5087 .parent = &else_scope.base,5099 .parent = &else_scope.base,
5088 .gen_zir = &else_scope,5100 .gen_zir = &else_scope,
...@@ -5273,11 +5285,12 @@ fn whileExpr(...@@ -5273,11 +5285,12 @@ fn whileExpr(
5273 .err_union_payload_unsafe;5285 .err_union_payload_unsafe;
5274 const payload_inst = try then_scope.addUnNode(tag, cond.inst, node);5286 const payload_inst = try then_scope.addUnNode(tag, cond.inst, node);
5275 const ident_token = if (payload_is_ref) payload_token + 1 else payload_token;5287 const ident_token = if (payload_is_ref) payload_token + 1 else payload_token;
5276 if (mem.eql(u8, "_", tree.tokenSlice(ident_token)))5288 const ident_bytes = tree.tokenSlice(ident_token);
5289 if (mem.eql(u8, "_", ident_bytes))
5277 break :s &then_scope.base;5290 break :s &then_scope.base;
5278 const payload_name_loc = payload_token + @boolToInt(payload_is_ref);5291 const payload_name_loc = payload_token + @boolToInt(payload_is_ref);
5279 const ident_name = try astgen.identAsString(payload_name_loc);5292 const ident_name = try astgen.identAsString(payload_name_loc);
5280 try astgen.detectLocalShadowing(&then_scope.base, ident_name, payload_name_loc);5293 try astgen.detectLocalShadowing(&then_scope.base, ident_name, payload_name_loc, ident_bytes);
5281 payload_val_scope = .{5294 payload_val_scope = .{
5282 .parent = &then_scope.base,5295 .parent = &then_scope.base,
5283 .gen_zir = &then_scope,5296 .gen_zir = &then_scope,
...@@ -5298,9 +5311,10 @@ fn whileExpr(...@@ -5298,9 +5311,10 @@ fn whileExpr(
5298 .optional_payload_unsafe;5311 .optional_payload_unsafe;
5299 const payload_inst = try then_scope.addUnNode(tag, cond.inst, node);5312 const payload_inst = try then_scope.addUnNode(tag, cond.inst, node);
5300 const ident_name = try astgen.identAsString(ident_token);5313 const ident_name = try astgen.identAsString(ident_token);
5301 if (mem.eql(u8, "_", tree.tokenSlice(ident_token)))5314 const ident_bytes = tree.tokenSlice(ident_token);
5315 if (mem.eql(u8, "_", ident_bytes))
5302 break :s &then_scope.base;5316 break :s &then_scope.base;
5303 try astgen.detectLocalShadowing(&then_scope.base, ident_name, ident_token);5317 try astgen.detectLocalShadowing(&then_scope.base, ident_name, ident_token, ident_bytes);
5304 payload_val_scope = .{5318 payload_val_scope = .{
5305 .parent = &then_scope.base,5319 .parent = &then_scope.base,
5306 .gen_zir = &then_scope,5320 .gen_zir = &then_scope,
...@@ -5356,9 +5370,10 @@ fn whileExpr(...@@ -5356,9 +5370,10 @@ fn whileExpr(
5356 .err_union_code;5370 .err_union_code;
5357 const payload_inst = try else_scope.addUnNode(tag, cond.inst, node);5371 const payload_inst = try else_scope.addUnNode(tag, cond.inst, node);
5358 const ident_name = try astgen.identAsString(error_token);5372 const ident_name = try astgen.identAsString(error_token);
5359 if (mem.eql(u8, tree.tokenSlice(error_token), "_"))5373 const ident_bytes = tree.tokenSlice(error_token);
5374 if (mem.eql(u8, ident_bytes, "_"))
5360 break :s &else_scope.base;5375 break :s &else_scope.base;
5361 try astgen.detectLocalShadowing(&else_scope.base, ident_name, error_token);5376 try astgen.detectLocalShadowing(&else_scope.base, ident_name, error_token, ident_bytes);
5362 payload_val_scope = .{5377 payload_val_scope = .{
5363 .parent = &else_scope.base,5378 .parent = &else_scope.base,
5364 .gen_zir = &else_scope,5379 .gen_zir = &else_scope,
...@@ -5418,12 +5433,19 @@ fn forExpr(...@@ -5418,12 +5433,19 @@ fn forExpr(
5418 if (for_full.label_token) |label_token| {5433 if (for_full.label_token) |label_token| {
5419 try astgen.checkLabelRedefinition(scope, label_token);5434 try astgen.checkLabelRedefinition(scope, label_token);
5420 }5435 }
5436
5421 // Set up variables and constants.5437 // Set up variables and constants.
5422 const is_inline = parent_gz.force_comptime or for_full.inline_token != null;5438 const is_inline = parent_gz.force_comptime or for_full.inline_token != null;
5423 const tree = astgen.tree;5439 const tree = astgen.tree;
5424 const token_tags = tree.tokens.items(.tag);5440 const token_tags = tree.tokens.items(.tag);
54255441
5426 const array_ptr = try expr(parent_gz, scope, .none_or_ref, for_full.ast.cond_expr);5442 const payload_is_ref = if (for_full.payload_token) |payload_token|
5443 token_tags[payload_token] == .asterisk
5444 else
5445 false;
5446
5447 const cond_rl: ResultLoc = if (payload_is_ref) .ref else .none;
5448 const array_ptr = try expr(parent_gz, scope, cond_rl, for_full.ast.cond_expr);
5427 const len = try parent_gz.addUnNode(.indexable_ptr_len, array_ptr, for_full.ast.cond_expr);5449 const len = try parent_gz.addUnNode(.indexable_ptr_len, array_ptr, for_full.ast.cond_expr);
54285450
5429 const index_ptr = blk: {5451 const index_ptr = blk: {
...@@ -5498,7 +5520,7 @@ fn forExpr(...@@ -5498,7 +5520,7 @@ fn forExpr(
5498 const name_str_index = try astgen.identAsString(ident);5520 const name_str_index = try astgen.identAsString(ident);
5499 const tag: Zir.Inst.Tag = if (is_ptr) .elem_ptr else .elem_val;5521 const tag: Zir.Inst.Tag = if (is_ptr) .elem_ptr else .elem_val;
5500 const payload_inst = try then_scope.addBin(tag, array_ptr, index);5522 const payload_inst = try then_scope.addBin(tag, array_ptr, index);
5501 try astgen.detectLocalShadowing(&then_scope.base, name_str_index, ident);5523 try astgen.detectLocalShadowing(&then_scope.base, name_str_index, ident, value_name);
5502 payload_val_scope = .{5524 payload_val_scope = .{
5503 .parent = &then_scope.base,5525 .parent = &then_scope.base,
5504 .gen_zir = &then_scope,5526 .gen_zir = &then_scope,
...@@ -5518,11 +5540,12 @@ fn forExpr(...@@ -5518,11 +5540,12 @@ fn forExpr(
5518 ident + 25540 ident + 2
5519 else5541 else
5520 break :blk payload_sub_scope;5542 break :blk payload_sub_scope;
5521 if (mem.eql(u8, tree.tokenSlice(index_token), "_")) {5543 const token_bytes = tree.tokenSlice(index_token);
5544 if (mem.eql(u8, token_bytes, "_")) {
5522 return astgen.failTok(index_token, "discard of index capture; omit it instead", .{});5545 return astgen.failTok(index_token, "discard of index capture; omit it instead", .{});
5523 }5546 }
5524 const index_name = try astgen.identAsString(index_token);5547 const index_name = try astgen.identAsString(index_token);
5525 try astgen.detectLocalShadowing(payload_sub_scope, index_name, index_token);5548 try astgen.detectLocalShadowing(payload_sub_scope, index_name, index_token, token_bytes);
5526 index_scope = .{5549 index_scope = .{
5527 .parent = payload_sub_scope,5550 .parent = payload_sub_scope,
5528 .gen_zir = &then_scope,5551 .gen_zir = &then_scope,
...@@ -6294,34 +6317,36 @@ fn identifier(...@@ -6294,34 +6317,36 @@ fn identifier(
6294 }6317 }
6295 const ident_name = try astgen.identifierTokenString(ident_token);6318 const ident_name = try astgen.identifierTokenString(ident_token);
62966319
6297 if (simple_types.get(ident_name)) |zir_const_ref| {6320 if (ident_name_raw[0] != '@') {
6298 return rvalue(gz, rl, zir_const_ref, ident);6321 if (simple_types.get(ident_name)) |zir_const_ref| {
6299 }6322 return rvalue(gz, rl, zir_const_ref, ident);
6323 }
63006324
6301 if (ident_name.len >= 2) integer: {6325 if (ident_name.len >= 2) integer: {
6302 const first_c = ident_name[0];6326 const first_c = ident_name[0];
6303 if (first_c == 'i' or first_c == 'u') {6327 if (first_c == 'i' or first_c == 'u') {
6304 const signedness: std.builtin.Signedness = switch (first_c == 'i') {6328 const signedness: std.builtin.Signedness = switch (first_c == 'i') {
6305 true => .signed,6329 true => .signed,
6306 false => .unsigned,6330 false => .unsigned,
6307 };6331 };
6308 const bit_count = std.fmt.parseInt(u16, ident_name[1..], 10) catch |err| switch (err) {6332 const bit_count = std.fmt.parseInt(u16, ident_name[1..], 10) catch |err| switch (err) {
6309 error.Overflow => return astgen.failNode(6333 error.Overflow => return astgen.failNode(
6310 ident,6334 ident,
6311 "primitive integer type '{s}' exceeds maximum bit width of 65535",6335 "primitive integer type '{s}' exceeds maximum bit width of 65535",
6312 .{ident_name},6336 .{ident_name},
6313 ),6337 ),
6314 error.InvalidCharacter => break :integer,6338 error.InvalidCharacter => break :integer,
6315 };6339 };
6316 const result = try gz.add(.{6340 const result = try gz.add(.{
6317 .tag = .int_type,6341 .tag = .int_type,
6318 .data = .{ .int_type = .{6342 .data = .{ .int_type = .{
6319 .src_node = gz.nodeIndexToRelative(ident),6343 .src_node = gz.nodeIndexToRelative(ident),
6320 .signedness = signedness,6344 .signedness = signedness,
6321 .bit_count = bit_count,6345 .bit_count = bit_count,
6322 } },6346 } },
6323 });6347 });
6324 return rvalue(gz, rl, result, ident);6348 return rvalue(gz, rl, result, ident);
6349 }
6325 }6350 }
6326 }6351 }
63276352
...@@ -7102,38 +7127,38 @@ fn builtinCall(...@@ -7102,38 +7127,38 @@ fn builtinCall(
7102 .bit_size_of => return simpleUnOpType(gz, scope, rl, node, params[0], .bit_size_of),7127 .bit_size_of => return simpleUnOpType(gz, scope, rl, node, params[0], .bit_size_of),
7103 .align_of => return simpleUnOpType(gz, scope, rl, node, params[0], .align_of),7128 .align_of => return simpleUnOpType(gz, scope, rl, node, params[0], .align_of),
71047129
7105 .ptr_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .ptr_to_int),7130 .ptr_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .ptr_to_int),
7106 .error_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .error_to_int),7131 .error_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .error_to_int),
7107 .int_to_error => return simpleUnOp(gz, scope, rl, node, .{ .ty = .u16_type }, params[0], .int_to_error),7132 .int_to_error => return simpleUnOp(gz, scope, rl, node, .{ .ty = .u16_type }, params[0], .int_to_error),
7108 .compile_error => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .compile_error),7133 .compile_error => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .compile_error),
7109 .set_eval_branch_quota => return simpleUnOp(gz, scope, rl, node, .{ .ty = .u32_type }, params[0], .set_eval_branch_quota),7134 .set_eval_branch_quota => return simpleUnOp(gz, scope, rl, node, .{ .ty = .u32_type }, params[0], .set_eval_branch_quota),
7110 .enum_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .enum_to_int),7135 .enum_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .enum_to_int),
7111 .bool_to_int => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .bool_to_int),7136 .bool_to_int => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .bool_to_int),
7112 .embed_file => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .embed_file),7137 .embed_file => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .embed_file),
7113 .error_name => return simpleUnOp(gz, scope, rl, node, .{ .ty = .anyerror_type }, params[0], .error_name),7138 .error_name => return simpleUnOp(gz, scope, rl, node, .{ .ty = .anyerror_type }, params[0], .error_name),
7114 .panic => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .panic),7139 .panic => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .panic),
7115 .set_align_stack => return simpleUnOp(gz, scope, rl, node, align_rl, params[0], .set_align_stack),7140 .set_align_stack => return simpleUnOp(gz, scope, rl, node, align_rl, params[0], .set_align_stack),
7116 .set_cold => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .set_cold),7141 .set_cold => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .set_cold),
7117 .set_float_mode => return simpleUnOp(gz, scope, rl, node, .{ .ty = .float_mode_type }, params[0], .set_float_mode),7142 .set_float_mode => return simpleUnOp(gz, scope, rl, node, .{ .coerced_ty = .float_mode_type }, params[0], .set_float_mode),
7118 .set_runtime_safety => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .set_runtime_safety),7143 .set_runtime_safety => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .set_runtime_safety),
7119 .sqrt => return simpleUnOp(gz, scope, rl, node, .none, params[0], .sqrt),7144 .sqrt => return simpleUnOp(gz, scope, rl, node, .none, params[0], .sqrt),
7120 .sin => return simpleUnOp(gz, scope, rl, node, .none, params[0], .sin),7145 .sin => return simpleUnOp(gz, scope, rl, node, .none, params[0], .sin),
7121 .cos => return simpleUnOp(gz, scope, rl, node, .none, params[0], .cos),7146 .cos => return simpleUnOp(gz, scope, rl, node, .none, params[0], .cos),
7122 .exp => return simpleUnOp(gz, scope, rl, node, .none, params[0], .exp),7147 .exp => return simpleUnOp(gz, scope, rl, node, .none, params[0], .exp),
7123 .exp2 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .exp2),7148 .exp2 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .exp2),
7124 .log => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log),7149 .log => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log),
7125 .log2 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log2),7150 .log2 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log2),
7126 .log10 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log10),7151 .log10 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log10),
7127 .fabs => return simpleUnOp(gz, scope, rl, node, .none, params[0], .fabs),7152 .fabs => return simpleUnOp(gz, scope, rl, node, .none, params[0], .fabs),
7128 .floor => return simpleUnOp(gz, scope, rl, node, .none, params[0], .floor),7153 .floor => return simpleUnOp(gz, scope, rl, node, .none, params[0], .floor),
7129 .ceil => return simpleUnOp(gz, scope, rl, node, .none, params[0], .ceil),7154 .ceil => return simpleUnOp(gz, scope, rl, node, .none, params[0], .ceil),
7130 .trunc => return simpleUnOp(gz, scope, rl, node, .none, params[0], .trunc),7155 .trunc => return simpleUnOp(gz, scope, rl, node, .none, params[0], .trunc),
7131 .round => return simpleUnOp(gz, scope, rl, node, .none, params[0], .round),7156 .round => return simpleUnOp(gz, scope, rl, node, .none, params[0], .round),
7132 .tag_name => return simpleUnOp(gz, scope, rl, node, .none, params[0], .tag_name),7157 .tag_name => return simpleUnOp(gz, scope, rl, node, .none, params[0], .tag_name),
7133 .Type => return simpleUnOp(gz, scope, rl, node, .none, params[0], .reify),7158 .Type => return simpleUnOp(gz, scope, rl, node, .{ .coerced_ty = .type_info_type }, params[0], .reify),
7134 .type_name => return simpleUnOp(gz, scope, rl, node, .none, params[0], .type_name),7159 .type_name => return simpleUnOp(gz, scope, rl, node, .none, params[0], .type_name),
7135 .Frame => return simpleUnOp(gz, scope, rl, node, .none, params[0], .frame_type),7160 .Frame => return simpleUnOp(gz, scope, rl, node, .none, params[0], .frame_type),
7136 .frame_size => return simpleUnOp(gz, scope, rl, node, .none, params[0], .frame_size),7161 .frame_size => return simpleUnOp(gz, scope, rl, node, .none, params[0], .frame_size),
71377162
7138 .float_to_int => return typeCast(gz, scope, rl, node, params[0], params[1], .float_to_int),7163 .float_to_int => return typeCast(gz, scope, rl, node, params[0], params[1], .float_to_int),
7139 .int_to_float => return typeCast(gz, scope, rl, node, params[0], params[1], .int_to_float),7164 .int_to_float => return typeCast(gz, scope, rl, node, params[0], params[1], .int_to_float),
...@@ -7819,10 +7844,6 @@ fn nodeMayNeedMemoryLocation(tree: *const ast.Tree, start_node: ast.Node.Index)...@@ -7819,10 +7844,6 @@ fn nodeMayNeedMemoryLocation(tree: *const ast.Tree, start_node: ast.Node.Index)
7819 .string_literal,7844 .string_literal,
7820 .multiline_string_literal,7845 .multiline_string_literal,
7821 .char_literal,7846 .char_literal,
7822 .true_literal,
7823 .false_literal,
7824 .null_literal,
7825 .undefined_literal,
7826 .unreachable_literal,7847 .unreachable_literal,
7827 .identifier,7848 .identifier,
7828 .error_set_decl,7849 .error_set_decl,
...@@ -8059,10 +8080,6 @@ fn nodeMayEvalToError(tree: *const ast.Tree, start_node: ast.Node.Index) enum {...@@ -8059,10 +8080,6 @@ fn nodeMayEvalToError(tree: *const ast.Tree, start_node: ast.Node.Index) enum {
8059 .string_literal,8080 .string_literal,
8060 .multiline_string_literal,8081 .multiline_string_literal,
8061 .char_literal,8082 .char_literal,
8062 .true_literal,
8063 .false_literal,
8064 .null_literal,
8065 .undefined_literal,
8066 .unreachable_literal,8083 .unreachable_literal,
8067 .error_set_decl,8084 .error_set_decl,
8068 .container_decl,8085 .container_decl,
...@@ -8232,10 +8249,6 @@ fn nodeImpliesRuntimeBits(tree: *const ast.Tree, start_node: ast.Node.Index) boo...@@ -8232,10 +8249,6 @@ fn nodeImpliesRuntimeBits(tree: *const ast.Tree, start_node: ast.Node.Index) boo
8232 .string_literal,8249 .string_literal,
8233 .multiline_string_literal,8250 .multiline_string_literal,
8234 .char_literal,8251 .char_literal,
8235 .true_literal,
8236 .false_literal,
8237 .null_literal,
8238 .undefined_literal,
8239 .unreachable_literal,8252 .unreachable_literal,
8240 .identifier,8253 .identifier,
8241 .error_set_decl,8254 .error_set_decl,
...@@ -10006,8 +10019,21 @@ fn declareNewName(...@@ -10006,8 +10019,21 @@ fn declareNewName(
10006 start_scope: *Scope,10019 start_scope: *Scope,
10007 name_index: u32,10020 name_index: u32,
10008 node: ast.Node.Index,10021 node: ast.Node.Index,
10022 name_token: ast.TokenIndex,
10009) !void {10023) !void {
10010 const gpa = astgen.gpa;10024 const gpa = astgen.gpa;
10025
10026 const token_bytes = astgen.tree.tokenSlice(name_token);
10027 if (token_bytes[0] != '@' and isPrimitive(token_bytes)) {
10028 return astgen.failTokNotes(name_token, "name shadows primitive '{s}'", .{
10029 token_bytes,
10030 }, &[_]u32{
10031 try astgen.errNoteTok(name_token, "consider using @\"{s}\" to disambiguate", .{
10032 token_bytes,
10033 }),
10034 });
10035 }
10036
10011 var scope = start_scope;10037 var scope = start_scope;
10012 while (true) {10038 while (true) {
10013 switch (scope.tag) {10039 switch (scope.tag) {
...@@ -10019,7 +10045,7 @@ fn declareNewName(...@@ -10019,7 +10045,7 @@ fn declareNewName(
10019 const ns = scope.cast(Scope.Namespace).?;10045 const ns = scope.cast(Scope.Namespace).?;
10020 const gop = try ns.decls.getOrPut(gpa, name_index);10046 const gop = try ns.decls.getOrPut(gpa, name_index);
10021 if (gop.found_existing) {10047 if (gop.found_existing) {
10022 const name = try gpa.dupe(u8, mem.spanZ(astgen.nullTerminatedString(name_index)));10048 const name = try gpa.dupe(u8, mem.span(astgen.nullTerminatedString(name_index)));
10023 defer gpa.free(name);10049 defer gpa.free(name);
10024 return astgen.failNodeNotes(node, "redeclaration of '{s}'", .{10050 return astgen.failNodeNotes(node, "redeclaration of '{s}'", .{
10025 name,10051 name,
...@@ -10035,21 +10061,45 @@ fn declareNewName(...@@ -10035,21 +10061,45 @@ fn declareNewName(
10035 }10061 }
10036}10062}
1003710063
10038/// Local variables shadowing detection, including function parameters.10064fn isPrimitive(name: []const u8) bool {
10065 if (simple_types.get(name) != null) return true;
10066 if (name.len < 2) return false;
10067 const first_c = name[0];
10068 if (first_c != 'i' and first_c != 'u') return false;
10069 if (std.fmt.parseInt(u16, name[1..], 10)) |_| {
10070 return true;
10071 } else |err| switch (err) {
10072 error.Overflow => return true,
10073 error.InvalidCharacter => return false,
10074 }
10075}
10076
10077/// Local variables shadowing detection, including function parameters and primitives.
10039fn detectLocalShadowing(10078fn detectLocalShadowing(
10040 astgen: *AstGen,10079 astgen: *AstGen,
10041 scope: *Scope,10080 scope: *Scope,
10042 ident_name: u32,10081 ident_name: u32,
10043 name_token: ast.TokenIndex,10082 name_token: ast.TokenIndex,
10083 token_bytes: []const u8,
10044) !void {10084) !void {
10045 const gpa = astgen.gpa;10085 const gpa = astgen.gpa;
10086 if (token_bytes[0] != '@' and isPrimitive(token_bytes)) {
10087 return astgen.failTokNotes(name_token, "name shadows primitive '{s}'", .{
10088 token_bytes,
10089 }, &[_]u32{
10090 try astgen.errNoteTok(name_token, "consider using @\"{s}\" to disambiguate", .{
10091 token_bytes,
10092 }),
10093 });
10094 }
1004610095
10047 var s = scope;10096 var s = scope;
10048 while (true) switch (s.tag) {10097 while (true) switch (s.tag) {
10049 .local_val => {10098 .local_val => {
10050 const local_val = s.cast(Scope.LocalVal).?;10099 const local_val = s.cast(Scope.LocalVal).?;
10051 if (local_val.name == ident_name) {10100 if (local_val.name == ident_name) {
10052 const name = try gpa.dupe(u8, mem.spanZ(astgen.nullTerminatedString(ident_name)));10101 const name_slice = mem.span(astgen.nullTerminatedString(ident_name));
10102 const name = try gpa.dupe(u8, name_slice);
10053 defer gpa.free(name);10103 defer gpa.free(name);
10054 return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{10104 return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{
10055 @tagName(local_val.id_cat), name,10105 @tagName(local_val.id_cat), name,
...@@ -10066,7 +10116,8 @@ fn detectLocalShadowing(...@@ -10066,7 +10116,8 @@ fn detectLocalShadowing(
10066 .local_ptr => {10116 .local_ptr => {
10067 const local_ptr = s.cast(Scope.LocalPtr).?;10117 const local_ptr = s.cast(Scope.LocalPtr).?;
10068 if (local_ptr.name == ident_name) {10118 if (local_ptr.name == ident_name) {
10069 const name = try gpa.dupe(u8, mem.spanZ(astgen.nullTerminatedString(ident_name)));10119 const name_slice = mem.span(astgen.nullTerminatedString(ident_name));
10120 const name = try gpa.dupe(u8, name_slice);
10070 defer gpa.free(name);10121 defer gpa.free(name);
10071 return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{10122 return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{
10072 @tagName(local_ptr.id_cat), name,10123 @tagName(local_ptr.id_cat), name,
...@@ -10086,7 +10137,8 @@ fn detectLocalShadowing(...@@ -10086,7 +10137,8 @@ fn detectLocalShadowing(
10086 s = ns.parent;10137 s = ns.parent;
10087 continue;10138 continue;
10088 };10139 };
10089 const name = try gpa.dupe(u8, mem.spanZ(astgen.nullTerminatedString(ident_name)));10140 const name_slice = mem.span(astgen.nullTerminatedString(ident_name));
10141 const name = try gpa.dupe(u8, name_slice);
10090 defer gpa.free(name);10142 defer gpa.free(name);
10091 return astgen.failTokNotes(name_token, "local shadows declaration of '{s}'", .{10143 return astgen.failTokNotes(name_token, "local shadows declaration of '{s}'", .{
10092 name,10144 name,
src/Compilation.zig+1
...@@ -2557,6 +2557,7 @@ pub fn cImport(comp: *Compilation, c_src: []const u8) !CImportResult {...@@ -2557,6 +2557,7 @@ pub fn cImport(comp: *Compilation, c_src: []const u8) !CImportResult {
2557 var argv = std.ArrayList([]const u8).init(comp.gpa);2557 var argv = std.ArrayList([]const u8).init(comp.gpa);
2558 defer argv.deinit();2558 defer argv.deinit();
25592559
2560 try argv.append(""); // argv[0] is program name, actual args start at [1]
2560 try comp.addTranslateCCArgs(arena, &argv, .c, out_dep_path);2561 try comp.addTranslateCCArgs(arena, &argv, .c, out_dep_path);
25612562
2562 try argv.append(out_h_path);2563 try argv.append(out_h_path);
src/Liveness.zig+10
...@@ -249,6 +249,8 @@ fn analyzeInst(...@@ -249,6 +249,8 @@ fn analyzeInst(
249 .ptr_slice_elem_val,249 .ptr_slice_elem_val,
250 .ptr_elem_val,250 .ptr_elem_val,
251 .ptr_ptr_elem_val,251 .ptr_ptr_elem_val,
252 .shl,
253 .shr,
252 => {254 => {
253 const o = inst_datas[inst].bin_op;255 const o = inst_datas[inst].bin_op;
254 return trackOperands(a, new_set, inst, main_tomb, .{ o.lhs, o.rhs, .none });256 return trackOperands(a, new_set, inst, main_tomb, .{ o.lhs, o.rhs, .none });
...@@ -280,6 +282,10 @@ fn analyzeInst(...@@ -280,6 +282,10 @@ fn analyzeInst(
280 .wrap_errunion_err,282 .wrap_errunion_err,
281 .slice_ptr,283 .slice_ptr,
282 .slice_len,284 .slice_len,
285 .struct_field_ptr_index_0,
286 .struct_field_ptr_index_1,
287 .struct_field_ptr_index_2,
288 .struct_field_ptr_index_3,
283 => {289 => {
284 const o = inst_datas[inst].ty_op;290 const o = inst_datas[inst].ty_op;
285 return trackOperands(a, new_set, inst, main_tomb, .{ o.operand, .none, .none });291 return trackOperands(a, new_set, inst, main_tomb, .{ o.operand, .none, .none });
...@@ -328,6 +334,10 @@ fn analyzeInst(...@@ -328,6 +334,10 @@ fn analyzeInst(
328 const extra = a.air.extraData(Air.StructField, inst_datas[inst].ty_pl.payload).data;334 const extra = a.air.extraData(Air.StructField, inst_datas[inst].ty_pl.payload).data;
329 return trackOperands(a, new_set, inst, main_tomb, .{ extra.struct_operand, .none, .none });335 return trackOperands(a, new_set, inst, main_tomb, .{ extra.struct_operand, .none, .none });
330 },336 },
337 .ptr_elem_ptr => {
338 const extra = a.air.extraData(Air.Bin, inst_datas[inst].ty_pl.payload).data;
339 return trackOperands(a, new_set, inst, main_tomb, .{ extra.lhs, extra.rhs, .none });
340 },
331 .br => {341 .br => {
332 const br = inst_datas[inst].br;342 const br = inst_datas[inst].br;
333 return trackOperands(a, new_set, inst, main_tomb, .{ br.operand, .none, .none });343 return trackOperands(a, new_set, inst, main_tomb, .{ br.operand, .none, .none });
src/Module.zig+88-310
...@@ -66,6 +66,10 @@ import_table: std.StringArrayHashMapUnmanaged(*Scope.File) = .{},...@@ -66,6 +66,10 @@ import_table: std.StringArrayHashMapUnmanaged(*Scope.File) = .{},
66/// to the same function.66/// to the same function.
67monomorphed_funcs: MonomorphedFuncsSet = .{},67monomorphed_funcs: MonomorphedFuncsSet = .{},
6868
69/// The set of all comptime function calls that have been cached so that future calls
70/// with the same parameters will get the same return value.
71memoized_calls: MemoizedCallSet = .{},
72
69/// We optimize memory usage for a compilation with no compile errors by storing the73/// We optimize memory usage for a compilation with no compile errors by storing the
70/// error messages and mapping outside of `Decl`.74/// error messages and mapping outside of `Decl`.
71/// The ErrorMsg memory is owned by the decl, using Module's general purpose allocator.75/// The ErrorMsg memory is owned by the decl, using Module's general purpose allocator.
...@@ -157,6 +161,60 @@ const MonomorphedFuncsContext = struct {...@@ -157,6 +161,60 @@ const MonomorphedFuncsContext = struct {
157 }161 }
158};162};
159163
164pub const MemoizedCallSet = std.HashMapUnmanaged(
165 MemoizedCall.Key,
166 MemoizedCall.Result,
167 MemoizedCall,
168 std.hash_map.default_max_load_percentage,
169);
170
171pub const MemoizedCall = struct {
172 pub const Key = struct {
173 func: *Fn,
174 args: []TypedValue,
175 };
176
177 pub const Result = struct {
178 val: Value,
179 arena: std.heap.ArenaAllocator.State,
180 };
181
182 pub fn eql(ctx: @This(), a: Key, b: Key) bool {
183 _ = ctx;
184
185 if (a.func != b.func) return false;
186
187 assert(a.args.len == b.args.len);
188 for (a.args) |a_arg, arg_i| {
189 const b_arg = b.args[arg_i];
190 if (!a_arg.eql(b_arg)) {
191 return false;
192 }
193 }
194
195 return true;
196 }
197
198 /// Must match `Sema.GenericCallAdapter.hash`.
199 pub fn hash(ctx: @This(), key: Key) u64 {
200 _ = ctx;
201
202 var hasher = std.hash.Wyhash.init(0);
203
204 // The generic function Decl is guaranteed to be the first dependency
205 // of each of its instantiations.
206 std.hash.autoHash(&hasher, @ptrToInt(key.func));
207
208 // This logic must be kept in sync with the logic in `analyzeCall` that
209 // computes the hash.
210 for (key.args) |arg| {
211 arg.hash(&hasher);
212 }
213
214 return hasher.final();
215 }
216};
217
160/// A `Module` has zero or one of these depending on whether `-femit-h` is enabled.218/// A `Module` has zero or one of these depending on whether `-femit-h` is enabled.
161pub const GlobalEmitH = struct {219pub const GlobalEmitH = struct {
162 /// Where to put the output.220 /// Where to put the output.
...@@ -554,8 +612,8 @@ pub const Decl = struct {...@@ -554,8 +612,8 @@ pub const Decl = struct {
554 assert(struct_obj.owner_decl == decl);612 assert(struct_obj.owner_decl == decl);
555 return &struct_obj.namespace;613 return &struct_obj.namespace;
556 },614 },
557 .enum_full => {615 .enum_full, .enum_nonexhaustive => {
558 const enum_obj = ty.castTag(.enum_full).?.data;616 const enum_obj = ty.cast(Type.Payload.EnumFull).?.data;
559 assert(enum_obj.owner_decl == decl);617 assert(enum_obj.owner_decl == decl);
560 return &enum_obj.namespace;618 return &enum_obj.namespace;
561 },619 },
...@@ -660,6 +718,7 @@ pub const Struct = struct {...@@ -660,6 +718,7 @@ pub const Struct = struct {
660 /// is necessary to determine whether it has bits at runtime.718 /// is necessary to determine whether it has bits at runtime.
661 known_has_bits: bool,719 known_has_bits: bool,
662720
721 /// The `Type` and `Value` memory is owned by the arena of the Struct's owner_decl.
663 pub const Field = struct {722 pub const Field = struct {
664 /// Uses `noreturn` to indicate `anytype`.723 /// Uses `noreturn` to indicate `anytype`.
665 /// undefined until `status` is `have_field_types` or `have_layout`.724 /// undefined until `status` is `have_field_types` or `have_layout`.
...@@ -2254,15 +2313,26 @@ pub fn deinit(mod: *Module) void {...@@ -2254,15 +2313,26 @@ pub fn deinit(mod: *Module) void {
2254 }2313 }
2255 mod.export_owners.deinit(gpa);2314 mod.export_owners.deinit(gpa);
22562315
2257 var it = mod.global_error_set.keyIterator();2316 {
2258 while (it.next()) |key| {2317 var it = mod.global_error_set.keyIterator();
2259 gpa.free(key.*);2318 while (it.next()) |key| {
2319 gpa.free(key.*);
2320 }
2321 mod.global_error_set.deinit(gpa);
2260 }2322 }
2261 mod.global_error_set.deinit(gpa);
22622323
2263 mod.error_name_list.deinit(gpa);2324 mod.error_name_list.deinit(gpa);
2264 mod.test_functions.deinit(gpa);2325 mod.test_functions.deinit(gpa);
2265 mod.monomorphed_funcs.deinit(gpa);2326 mod.monomorphed_funcs.deinit(gpa);
2327
2328 {
2329 var it = mod.memoized_calls.iterator();
2330 while (it.next()) |entry| {
2331 gpa.free(entry.key_ptr.args);
2332 entry.value_ptr.arena.promote(gpa).deinit();
2333 }
2334 mod.memoized_calls.deinit(gpa);
2335 }
2266}2336}
22672337
2268fn freeExportList(gpa: *Allocator, export_list: []*Export) void {2338fn freeExportList(gpa: *Allocator, export_list: []*Export) void {
...@@ -3091,6 +3161,9 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {...@@ -3091,6 +3161,9 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
3091 if (linksection_ref == .none) break :blk Value.initTag(.null_value);3161 if (linksection_ref == .none) break :blk Value.initTag(.null_value);
3092 break :blk (try sema.resolveInstConst(&block_scope, src, linksection_ref)).val;3162 break :blk (try sema.resolveInstConst(&block_scope, src, linksection_ref)).val;
3093 };3163 };
3164 // Note this resolves the type of the Decl, not the value; if this Decl
3165 // is a struct, for example, this resolves `type` (which needs no resolution),
3166 // not the struct itself.
3094 try sema.resolveTypeLayout(&block_scope, src, decl_tv.ty);3167 try sema.resolveTypeLayout(&block_scope, src, decl_tv.ty);
30953168
3096 // We need the memory for the Type to go into the arena for the Decl3169 // We need the memory for the Type to go into the arena for the Decl
...@@ -3193,6 +3266,15 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {...@@ -3193,6 +3266,15 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
3193 if (type_changed and mod.emit_h != null) {3266 if (type_changed and mod.emit_h != null) {
3194 try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl });3267 try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl });
3195 }3268 }
3269 } else if (decl_tv.ty.zigTypeTag() == .Type) {
3270 // In case this Decl is a struct or union, we need to resolve the fields
3271 // while we still have the `Sema` in scope, so that the field type expressions
3272 // can use the resolved AIR instructions that they possibly reference.
3273 // We do this after the decl is populated and set to `complete` so that a `Decl`
3274 // may reference itself.
3275 var buffer: Value.ToTypeBuffer = undefined;
3276 const ty = decl.val.toType(&buffer);
3277 try sema.resolveDeclFields(&block_scope, src, ty);
3196 }3278 }
31973279
3198 if (decl.is_exported) {3280 if (decl.is_exported) {
...@@ -4024,7 +4106,6 @@ pub fn createAnonymousDeclFromDeclNamed(...@@ -4024,7 +4106,6 @@ pub fn createAnonymousDeclFromDeclNamed(
4024 new_decl.ty = typed_value.ty;4106 new_decl.ty = typed_value.ty;
4025 new_decl.val = typed_value.val;4107 new_decl.val = typed_value.val;
4026 new_decl.has_tv = true;4108 new_decl.has_tv = true;
4027 new_decl.owns_tv = true;
4028 new_decl.analysis = .complete;4109 new_decl.analysis = .complete;
4029 new_decl.generation = mod.generation;4110 new_decl.generation = mod.generation;
40304111
...@@ -4450,309 +4531,6 @@ pub const PeerTypeCandidateSrc = union(enum) {...@@ -4450,309 +4531,6 @@ pub const PeerTypeCandidateSrc = union(enum) {
4450 }4531 }
4451};4532};
44524533
4453pub fn analyzeStructFields(mod: *Module, struct_obj: *Struct) CompileError!void {
4454 const tracy = trace(@src());
4455 defer tracy.end();
4456
4457 const gpa = mod.gpa;
4458 const zir = struct_obj.owner_decl.namespace.file_scope.zir;
4459 const extended = zir.instructions.items(.data)[struct_obj.zir_index].extended;
4460 assert(extended.opcode == .struct_decl);
4461 const small = @bitCast(Zir.Inst.StructDecl.Small, extended.small);
4462 var extra_index: usize = extended.operand;
4463
4464 const src: LazySrcLoc = .{ .node_offset = struct_obj.node_offset };
4465 extra_index += @boolToInt(small.has_src_node);
4466
4467 const body_len = if (small.has_body_len) blk: {
4468 const body_len = zir.extra[extra_index];
4469 extra_index += 1;
4470 break :blk body_len;
4471 } else 0;
4472
4473 const fields_len = if (small.has_fields_len) blk: {
4474 const fields_len = zir.extra[extra_index];
4475 extra_index += 1;
4476 break :blk fields_len;
4477 } else 0;
4478
4479 const decls_len = if (small.has_decls_len) decls_len: {
4480 const decls_len = zir.extra[extra_index];
4481 extra_index += 1;
4482 break :decls_len decls_len;
4483 } else 0;
4484
4485 // Skip over decls.
4486 var decls_it = zir.declIteratorInner(extra_index, decls_len);
4487 while (decls_it.next()) |_| {}
4488 extra_index = decls_it.extra_index;
4489
4490 const body = zir.extra[extra_index..][0..body_len];
4491 if (fields_len == 0) {
4492 assert(body.len == 0);
4493 return;
4494 }
4495 extra_index += body.len;
4496
4497 var decl_arena = struct_obj.owner_decl.value_arena.?.promote(gpa);
4498 defer struct_obj.owner_decl.value_arena.?.* = decl_arena.state;
4499
4500 try struct_obj.fields.ensureCapacity(&decl_arena.allocator, fields_len);
4501
4502 // We create a block for the field type instructions because they
4503 // may need to reference Decls from inside the struct namespace.
4504 // Within the field type, default value, and alignment expressions, the "owner decl"
4505 // should be the struct itself. Thus we need a new Sema.
4506 var sema: Sema = .{
4507 .mod = mod,
4508 .gpa = gpa,
4509 .arena = &decl_arena.allocator,
4510 .code = zir,
4511 .owner_decl = struct_obj.owner_decl,
4512 .namespace = &struct_obj.namespace,
4513 .owner_func = null,
4514 .func = null,
4515 .fn_ret_ty = Type.initTag(.void),
4516 };
4517 defer sema.deinit();
4518
4519 var block: Scope.Block = .{
4520 .parent = null,
4521 .sema = &sema,
4522 .src_decl = struct_obj.owner_decl,
4523 .instructions = .{},
4524 .inlining = null,
4525 .is_comptime = true,
4526 };
4527 defer assert(block.instructions.items.len == 0); // should all be comptime instructions
4528
4529 if (body.len != 0) {
4530 _ = try sema.analyzeBody(&block, body);
4531 }
4532
4533 const bits_per_field = 4;
4534 const fields_per_u32 = 32 / bits_per_field;
4535 const bit_bags_count = std.math.divCeil(usize, fields_len, fields_per_u32) catch unreachable;
4536 var bit_bag_index: usize = extra_index;
4537 extra_index += bit_bags_count;
4538 var cur_bit_bag: u32 = undefined;
4539 var field_i: u32 = 0;
4540 while (field_i < fields_len) : (field_i += 1) {
4541 if (field_i % fields_per_u32 == 0) {
4542 cur_bit_bag = zir.extra[bit_bag_index];
4543 bit_bag_index += 1;
4544 }
4545 const has_align = @truncate(u1, cur_bit_bag) != 0;
4546 cur_bit_bag >>= 1;
4547 const has_default = @truncate(u1, cur_bit_bag) != 0;
4548 cur_bit_bag >>= 1;
4549 const is_comptime = @truncate(u1, cur_bit_bag) != 0;
4550 cur_bit_bag >>= 1;
4551 const unused = @truncate(u1, cur_bit_bag) != 0;
4552 cur_bit_bag >>= 1;
4553
4554 _ = unused;
4555
4556 const field_name_zir = zir.nullTerminatedString(zir.extra[extra_index]);
4557 extra_index += 1;
4558 const field_type_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
4559 extra_index += 1;
4560
4561 // This string needs to outlive the ZIR code.
4562 const field_name = try decl_arena.allocator.dupe(u8, field_name_zir);
4563 if (field_type_ref == .none) {
4564 return mod.fail(&block.base, src, "TODO: implement anytype struct field", .{});
4565 }
4566 const field_ty: Type = if (field_type_ref == .none)
4567 Type.initTag(.noreturn)
4568 else
4569 // TODO: if we need to report an error here, use a source location
4570 // that points to this type expression rather than the struct.
4571 // But only resolve the source location if we need to emit a compile error.
4572 try sema.resolveType(&block, src, field_type_ref);
4573
4574 const gop = struct_obj.fields.getOrPutAssumeCapacity(field_name);
4575 assert(!gop.found_existing);
4576 gop.value_ptr.* = .{
4577 .ty = field_ty,
4578 .abi_align = Value.initTag(.abi_align_default),
4579 .default_val = Value.initTag(.unreachable_value),
4580 .is_comptime = is_comptime,
4581 .offset = undefined,
4582 };
4583
4584 if (has_align) {
4585 const align_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
4586 extra_index += 1;
4587 // TODO: if we need to report an error here, use a source location
4588 // that points to this alignment expression rather than the struct.
4589 // But only resolve the source location if we need to emit a compile error.
4590 gop.value_ptr.abi_align = (try sema.resolveInstConst(&block, src, align_ref)).val;
4591 }
4592 if (has_default) {
4593 const default_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
4594 extra_index += 1;
4595 // TODO: if we need to report an error here, use a source location
4596 // that points to this default value expression rather than the struct.
4597 // But only resolve the source location if we need to emit a compile error.
4598 gop.value_ptr.default_val = (try sema.resolveInstConst(&block, src, default_ref)).val;
4599 }
4600 }
4601}
4602
4603pub fn analyzeUnionFields(mod: *Module, union_obj: *Union) CompileError!void {
4604 const tracy = trace(@src());
4605 defer tracy.end();
4606
4607 const gpa = mod.gpa;
4608 const zir = union_obj.owner_decl.namespace.file_scope.zir;
4609 const extended = zir.instructions.items(.data)[union_obj.zir_index].extended;
4610 assert(extended.opcode == .union_decl);
4611 const small = @bitCast(Zir.Inst.UnionDecl.Small, extended.small);
4612 var extra_index: usize = extended.operand;
4613
4614 const src: LazySrcLoc = .{ .node_offset = union_obj.node_offset };
4615 extra_index += @boolToInt(small.has_src_node);
4616
4617 if (small.has_tag_type) {
4618 extra_index += 1;
4619 }
4620
4621 const body_len = if (small.has_body_len) blk: {
4622 const body_len = zir.extra[extra_index];
4623 extra_index += 1;
4624 break :blk body_len;
4625 } else 0;
4626
4627 const fields_len = if (small.has_fields_len) blk: {
4628 const fields_len = zir.extra[extra_index];
4629 extra_index += 1;
4630 break :blk fields_len;
4631 } else 0;
4632
4633 const decls_len = if (small.has_decls_len) decls_len: {
4634 const decls_len = zir.extra[extra_index];
4635 extra_index += 1;
4636 break :decls_len decls_len;
4637 } else 0;
4638
4639 // Skip over decls.
4640 var decls_it = zir.declIteratorInner(extra_index, decls_len);
4641 while (decls_it.next()) |_| {}
4642 extra_index = decls_it.extra_index;
4643
4644 const body = zir.extra[extra_index..][0..body_len];
4645 if (fields_len == 0) {
4646 assert(body.len == 0);
4647 return;
4648 }
4649 extra_index += body.len;
4650
4651 var decl_arena = union_obj.owner_decl.value_arena.?.promote(gpa);
4652 defer union_obj.owner_decl.value_arena.?.* = decl_arena.state;
4653
4654 try union_obj.fields.ensureCapacity(&decl_arena.allocator, fields_len);
4655
4656 // We create a block for the field type instructions because they
4657 // may need to reference Decls from inside the struct namespace.
4658 // Within the field type, default value, and alignment expressions, the "owner decl"
4659 // should be the struct itself. Thus we need a new Sema.
4660 var sema: Sema = .{
4661 .mod = mod,
4662 .gpa = gpa,
4663 .arena = &decl_arena.allocator,
4664 .code = zir,
4665 .owner_decl = union_obj.owner_decl,
4666 .namespace = &union_obj.namespace,
4667 .owner_func = null,
4668 .func = null,
4669 .fn_ret_ty = Type.initTag(.void),
4670 };
4671 defer sema.deinit();
4672
4673 var block: Scope.Block = .{
4674 .parent = null,
4675 .sema = &sema,
4676 .src_decl = union_obj.owner_decl,
4677 .instructions = .{},
4678 .inlining = null,
4679 .is_comptime = true,
4680 };
4681 defer assert(block.instructions.items.len == 0); // should all be comptime instructions
4682
4683 if (body.len != 0) {
4684 _ = try sema.analyzeBody(&block, body);
4685 }
4686
4687 const bits_per_field = 4;
4688 const fields_per_u32 = 32 / bits_per_field;
4689 const bit_bags_count = std.math.divCeil(usize, fields_len, fields_per_u32) catch unreachable;
4690 var bit_bag_index: usize = extra_index;
4691 extra_index += bit_bags_count;
4692 var cur_bit_bag: u32 = undefined;
4693 var field_i: u32 = 0;
4694 while (field_i < fields_len) : (field_i += 1) {
4695 if (field_i % fields_per_u32 == 0) {
4696 cur_bit_bag = zir.extra[bit_bag_index];
4697 bit_bag_index += 1;
4698 }
4699 const has_type = @truncate(u1, cur_bit_bag) != 0;
4700 cur_bit_bag >>= 1;
4701 const has_align = @truncate(u1, cur_bit_bag) != 0;
4702 cur_bit_bag >>= 1;
4703 const has_tag = @truncate(u1, cur_bit_bag) != 0;
4704 cur_bit_bag >>= 1;
4705 const unused = @truncate(u1, cur_bit_bag) != 0;
4706 cur_bit_bag >>= 1;
4707 _ = unused;
4708
4709 const field_name_zir = zir.nullTerminatedString(zir.extra[extra_index]);
4710 extra_index += 1;
4711
4712 const field_type_ref: Zir.Inst.Ref = if (has_type) blk: {
4713 const field_type_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
4714 extra_index += 1;
4715 break :blk field_type_ref;
4716 } else .none;
4717
4718 const align_ref: Zir.Inst.Ref = if (has_align) blk: {
4719 const align_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
4720 extra_index += 1;
4721 break :blk align_ref;
4722 } else .none;
4723
4724 if (has_tag) {
4725 extra_index += 1;
4726 }
4727
4728 // This string needs to outlive the ZIR code.
4729 const field_name = try decl_arena.allocator.dupe(u8, field_name_zir);
4730 const field_ty: Type = if (field_type_ref == .none)
4731 Type.initTag(.void)
4732 else
4733 // TODO: if we need to report an error here, use a source location
4734 // that points to this type expression rather than the union.
4735 // But only resolve the source location if we need to emit a compile error.
4736 try sema.resolveType(&block, src, field_type_ref);
4737
4738 const gop = union_obj.fields.getOrPutAssumeCapacity(field_name);
4739 assert(!gop.found_existing);
4740 gop.value_ptr.* = .{
4741 .ty = field_ty,
4742 .abi_align = Value.initTag(.abi_align_default),
4743 };
4744
4745 if (align_ref != .none) {
4746 // TODO: if we need to report an error here, use a source location
4747 // that points to this alignment expression rather than the struct.
4748 // But only resolve the source location if we need to emit a compile error.
4749 gop.value_ptr.abi_align = (try sema.resolveInstConst(&block, src, align_ref)).val;
4750 }
4751 }
4752
4753 // TODO resolve the union tag_type_ref
4754}
4755
4756/// Called from `performAllTheWork`, after all AstGen workers have finished,4534/// Called from `performAllTheWork`, after all AstGen workers have finished,
4757/// and before the main semantic analysis loop begins.4535/// and before the main semantic analysis loop begins.
4758pub fn processOutdatedAndDeletedDecls(mod: *Module) !void {4536pub fn processOutdatedAndDeletedDecls(mod: *Module) !void {
src/Sema.zig+768-180
...@@ -649,6 +649,24 @@ fn resolveValue(...@@ -649,6 +649,24 @@ fn resolveValue(
649 return sema.failWithNeededComptime(block, src);649 return sema.failWithNeededComptime(block, src);
650}650}
651651
652/// Value Tag `variable` will cause a compile error.
653/// Value Tag `undef` may be returned.
654fn resolveConstMaybeUndefVal(
655 sema: *Sema,
656 block: *Scope.Block,
657 src: LazySrcLoc,
658 inst: Air.Inst.Ref,
659) CompileError!Value {
660 if (try sema.resolveMaybeUndefValAllowVariables(block, src, inst)) |val| {
661 switch (val.tag()) {
662 .variable => return sema.failWithNeededComptime(block, src),
663 .generic_poison => return error.GenericPoison,
664 else => return val,
665 }
666 }
667 return sema.failWithNeededComptime(block, src);
668}
669
652/// Will not return Value Tags: `variable`, `undef`. Instead they will emit compile errors.670/// Will not return Value Tags: `variable`, `undef`. Instead they will emit compile errors.
653/// See `resolveValue` for an alternative.671/// See `resolveValue` for an alternative.
654fn resolveConstValue(672fn resolveConstValue(
...@@ -866,6 +884,7 @@ fn zirStructDecl(...@@ -866,6 +884,7 @@ fn zirStructDecl(
866 .ty = Type.initTag(.type),884 .ty = Type.initTag(.type),
867 .val = struct_val,885 .val = struct_val,
868 }, type_name);886 }, type_name);
887 new_decl.owns_tv = true;
869 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);888 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
870 struct_obj.* = .{889 struct_obj.* = .{
871 .owner_decl = new_decl,890 .owner_decl = new_decl,
...@@ -986,6 +1005,7 @@ fn zirEnumDecl(...@@ -986,6 +1005,7 @@ fn zirEnumDecl(
986 .ty = Type.initTag(.type),1005 .ty = Type.initTag(.type),
987 .val = enum_val,1006 .val = enum_val,
988 }, type_name);1007 }, type_name);
1008 new_decl.owns_tv = true;
989 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);1009 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
9901010
991 enum_obj.* = .{1011 enum_obj.* = .{
...@@ -1032,25 +1052,27 @@ fn zirEnumDecl(...@@ -1032,25 +1052,27 @@ fn zirEnumDecl(
1032 // We create a block for the field type instructions because they1052 // We create a block for the field type instructions because they
1033 // may need to reference Decls from inside the enum namespace.1053 // may need to reference Decls from inside the enum namespace.
1034 // Within the field type, default value, and alignment expressions, the "owner decl"1054 // Within the field type, default value, and alignment expressions, the "owner decl"
1035 // should be the enum itself. Thus we need a new Sema.1055 // should be the enum itself.
1036 var enum_sema: Sema = .{1056
1037 .mod = mod,1057 const prev_owner_decl = sema.owner_decl;
1038 .gpa = gpa,1058 sema.owner_decl = new_decl;
1039 .arena = &new_decl_arena.allocator,1059 defer sema.owner_decl = prev_owner_decl;
1040 .code = sema.code,1060
1041 .inst_map = sema.inst_map,1061 const prev_namespace = sema.namespace;
1042 .owner_decl = new_decl,1062 sema.namespace = &enum_obj.namespace;
1043 .namespace = &enum_obj.namespace,1063 defer sema.namespace = prev_namespace;
1044 .owner_func = null,1064
1045 .func = null,1065 const prev_owner_func = sema.owner_func;
1046 .fn_ret_ty = Type.initTag(.void),1066 sema.owner_func = null;
1047 .branch_quota = sema.branch_quota,1067 defer sema.owner_func = prev_owner_func;
1048 .branch_count = sema.branch_count,1068
1049 };1069 const prev_func = sema.func;
1070 sema.func = null;
1071 defer sema.func = prev_func;
10501072
1051 var enum_block: Scope.Block = .{1073 var enum_block: Scope.Block = .{
1052 .parent = null,1074 .parent = null,
1053 .sema = &enum_sema,1075 .sema = sema,
1054 .src_decl = new_decl,1076 .src_decl = new_decl,
1055 .instructions = .{},1077 .instructions = .{},
1056 .inlining = null,1078 .inlining = null,
...@@ -1059,11 +1081,8 @@ fn zirEnumDecl(...@@ -1059,11 +1081,8 @@ fn zirEnumDecl(
1059 defer assert(enum_block.instructions.items.len == 0); // should all be comptime instructions1081 defer assert(enum_block.instructions.items.len == 0); // should all be comptime instructions
10601082
1061 if (body.len != 0) {1083 if (body.len != 0) {
1062 _ = try enum_sema.analyzeBody(&enum_block, body);1084 _ = try sema.analyzeBody(&enum_block, body);
1063 }1085 }
1064
1065 sema.branch_count = enum_sema.branch_count;
1066 sema.branch_quota = enum_sema.branch_quota;
1067 }1086 }
1068 var bit_bag_index: usize = body_end;1087 var bit_bag_index: usize = body_end;
1069 var cur_bit_bag: u32 = undefined;1088 var cur_bit_bag: u32 = undefined;
...@@ -1153,6 +1172,7 @@ fn zirUnionDecl(...@@ -1153,6 +1172,7 @@ fn zirUnionDecl(
1153 .ty = Type.initTag(.type),1172 .ty = Type.initTag(.type),
1154 .val = union_val,1173 .val = union_val,
1155 }, type_name);1174 }, type_name);
1175 new_decl.owns_tv = true;
1156 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);1176 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
1157 union_obj.* = .{1177 union_obj.* = .{
1158 .owner_decl = new_decl,1178 .owner_decl = new_decl,
...@@ -1224,6 +1244,7 @@ fn zirErrorSetDecl(...@@ -1224,6 +1244,7 @@ fn zirErrorSetDecl(
1224 .ty = Type.initTag(.type),1244 .ty = Type.initTag(.type),
1225 .val = error_set_val,1245 .val = error_set_val,
1226 }, type_name);1246 }, type_name);
1247 new_decl.owns_tv = true;
1227 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);1248 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
1228 const names = try new_decl_arena.allocator.alloc([]const u8, fields.len);1249 const names = try new_decl_arena.allocator.alloc([]const u8, fields.len);
1229 for (fields) |str_index, i| {1250 for (fields) |str_index, i| {
...@@ -1466,8 +1487,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Inde...@@ -1466,8 +1487,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Inde
1466 const ptr = sema.resolveInst(inst_data.operand);1487 const ptr = sema.resolveInst(inst_data.operand);
1467 const ptr_inst = Air.refToIndex(ptr).?;1488 const ptr_inst = Air.refToIndex(ptr).?;
1468 assert(sema.air_instructions.items(.tag)[ptr_inst] == .constant);1489 assert(sema.air_instructions.items(.tag)[ptr_inst] == .constant);
1469 const air_datas = sema.air_instructions.items(.data);1490 const value_index = sema.air_instructions.items(.data)[ptr_inst].ty_pl.payload;
1470 const value_index = air_datas[ptr_inst].ty_pl.payload;
1471 const ptr_val = sema.air_values.items[value_index];1491 const ptr_val = sema.air_values.items[value_index];
1472 const var_is_mut = switch (sema.typeOf(ptr).tag()) {1492 const var_is_mut = switch (sema.typeOf(ptr).tag()) {
1473 .inferred_alloc_const => false,1493 .inferred_alloc_const => false,
...@@ -1481,7 +1501,8 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Inde...@@ -1481,7 +1501,8 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Inde
14811501
1482 const final_elem_ty = try decl.ty.copy(sema.arena);1502 const final_elem_ty = try decl.ty.copy(sema.arena);
1483 const final_ptr_ty = try Module.simplePtrType(sema.arena, final_elem_ty, true, .One);1503 const final_ptr_ty = try Module.simplePtrType(sema.arena, final_elem_ty, true, .One);
1484 air_datas[ptr_inst].ty_pl.ty = try sema.addType(final_ptr_ty);1504 const final_ptr_ty_inst = try sema.addType(final_ptr_ty);
1505 sema.air_instructions.items(.data)[ptr_inst].ty_pl.ty = final_ptr_ty_inst;
14851506
1486 if (var_is_mut) {1507 if (var_is_mut) {
1487 sema.air_values.items[value_index] = try Value.Tag.decl_ref_mut.create(sema.arena, .{1508 sema.air_values.items[value_index] = try Value.Tag.decl_ref_mut.create(sema.arena, .{
...@@ -2562,6 +2583,19 @@ fn analyzeCall(...@@ -2562,6 +2583,19 @@ fn analyzeCall(
2562 defer merges.results.deinit(gpa);2583 defer merges.results.deinit(gpa);
2563 defer merges.br_list.deinit(gpa);2584 defer merges.br_list.deinit(gpa);
25642585
2586 // If it's a comptime function call, we need to memoize it as long as no external
2587 // comptime memory is mutated.
2588 var memoized_call_key: Module.MemoizedCall.Key = undefined;
2589 var delete_memoized_call_key = false;
2590 defer if (delete_memoized_call_key) gpa.free(memoized_call_key.args);
2591 if (is_comptime_call) {
2592 memoized_call_key = .{
2593 .func = module_fn,
2594 .args = try gpa.alloc(TypedValue, func_ty_info.param_types.len),
2595 };
2596 delete_memoized_call_key = true;
2597 }
2598
2565 try sema.emitBackwardBranch(&child_block, call_src);2599 try sema.emitBackwardBranch(&child_block, call_src);
25662600
2567 // This will have return instructions analyzed as break instructions to2601 // This will have return instructions analyzed as break instructions to
...@@ -2586,12 +2620,32 @@ fn analyzeCall(...@@ -2586,12 +2620,32 @@ fn analyzeCall(
2586 const arg_src = call_src; // TODO: better source location2620 const arg_src = call_src; // TODO: better source location
2587 const casted_arg = try sema.coerce(&child_block, param_ty, uncasted_args[arg_i], arg_src);2621 const casted_arg = try sema.coerce(&child_block, param_ty, uncasted_args[arg_i], arg_src);
2588 try sema.inst_map.putNoClobber(gpa, inst, casted_arg);2622 try sema.inst_map.putNoClobber(gpa, inst, casted_arg);
2623
2624 if (is_comptime_call) {
2625 const arg_val = try sema.resolveConstMaybeUndefVal(&child_block, arg_src, casted_arg);
2626 memoized_call_key.args[arg_i] = .{
2627 .ty = param_ty,
2628 .val = arg_val,
2629 };
2630 }
2631
2589 arg_i += 1;2632 arg_i += 1;
2590 continue;2633 continue;
2591 },2634 },
2592 .param_anytype, .param_anytype_comptime => {2635 .param_anytype, .param_anytype_comptime => {
2593 // No coercion needed.2636 // No coercion needed.
2594 try sema.inst_map.putNoClobber(gpa, inst, uncasted_args[arg_i]);2637 const uncasted_arg = uncasted_args[arg_i];
2638 try sema.inst_map.putNoClobber(gpa, inst, uncasted_arg);
2639
2640 if (is_comptime_call) {
2641 const arg_src = call_src; // TODO: better source location
2642 const arg_val = try sema.resolveConstMaybeUndefVal(&child_block, arg_src, uncasted_arg);
2643 memoized_call_key.args[arg_i] = .{
2644 .ty = sema.typeOf(uncasted_arg),
2645 .val = arg_val,
2646 };
2647 }
2648
2595 arg_i += 1;2649 arg_i += 1;
2596 continue;2650 continue;
2597 },2651 },
...@@ -2623,8 +2677,61 @@ fn analyzeCall(...@@ -2623,8 +2677,61 @@ fn analyzeCall(
2623 sema.fn_ret_ty = fn_ret_ty;2677 sema.fn_ret_ty = fn_ret_ty;
2624 defer sema.fn_ret_ty = parent_fn_ret_ty;2678 defer sema.fn_ret_ty = parent_fn_ret_ty;
26252679
2626 _ = try sema.analyzeBody(&child_block, fn_info.body);2680 // This `res2` is here instead of directly breaking from `res` due to a stage1
2627 break :res try sema.analyzeBlockBody(block, call_src, &child_block, merges);2681 // bug generating invalid LLVM IR.
2682 const res2: Air.Inst.Ref = res2: {
2683 if (is_comptime_call) {
2684 if (mod.memoized_calls.get(memoized_call_key)) |result| {
2685 const ty_inst = try sema.addType(fn_ret_ty);
2686 try sema.air_values.append(gpa, result.val);
2687 sema.air_instructions.set(block_inst, .{
2688 .tag = .constant,
2689 .data = .{ .ty_pl = .{
2690 .ty = ty_inst,
2691 .payload = @intCast(u32, sema.air_values.items.len - 1),
2692 } },
2693 });
2694 break :res2 Air.indexToRef(block_inst);
2695 }
2696 }
2697
2698 _ = try sema.analyzeBody(&child_block, fn_info.body);
2699 const result = try sema.analyzeBlockBody(block, call_src, &child_block, merges);
2700
2701 if (is_comptime_call) {
2702 const result_val = try sema.resolveConstMaybeUndefVal(block, call_src, result);
2703
2704 // TODO: check whether any external comptime memory was mutated by the
2705 // comptime function call. If so, then do not memoize the call here.
2706 {
2707 var arena_allocator = std.heap.ArenaAllocator.init(gpa);
2708 errdefer arena_allocator.deinit();
2709 const arena = &arena_allocator.allocator;
2710
2711 for (memoized_call_key.args) |*arg| {
2712 arg.* = try arg.*.copy(arena);
2713 }
2714
2715 try mod.memoized_calls.put(gpa, memoized_call_key, .{
2716 .val = result_val,
2717 .arena = arena_allocator.state,
2718 });
2719 delete_memoized_call_key = false;
2720 }
2721
2722 // Much like in `Module.semaDecl`, if the result is a struct or union type,
2723 // we need to resolve the field type expressions right here, right now, while
2724 // the child `Sema` is still available, with the AIR instruction map intact,
2725 // because the field type expressions may reference into it.
2726 if (sema.typeOf(result).zigTypeTag() == .Type) {
2727 const ty = try sema.analyzeAsType(&child_block, call_src, result);
2728 try sema.resolveDeclFields(&child_block, call_src, ty);
2729 }
2730 }
2731
2732 break :res2 result;
2733 };
2734 break :res res2;
2628 } else if (func_ty_info.is_generic) res: {2735 } else if (func_ty_info.is_generic) res: {
2629 const func_val = try sema.resolveConstValue(block, func_src, func);2736 const func_val = try sema.resolveConstValue(block, func_src, func);
2630 const module_fn = func_val.castTag(.function).?.data;2737 const module_fn = func_val.castTag(.function).?.data;
...@@ -3291,31 +3398,9 @@ fn zirEnumToInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileE...@@ -3291,31 +3398,9 @@ fn zirEnumToInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileE
3291 }3398 }
32923399
3293 if (try sema.resolveMaybeUndefVal(block, operand_src, enum_tag)) |enum_tag_val| {3400 if (try sema.resolveMaybeUndefVal(block, operand_src, enum_tag)) |enum_tag_val| {
3294 if (enum_tag_val.castTag(.enum_field_index)) |enum_field_payload| {3401 var buffer: Value.Payload.U64 = undefined;
3295 const field_index = enum_field_payload.data;3402 const val = enum_tag_val.enumToInt(enum_tag_ty, &buffer);
3296 switch (enum_tag_ty.tag()) {3403 return sema.addConstant(int_tag_ty, try val.copy(sema.arena));
3297 .enum_full => {
3298 const enum_full = enum_tag_ty.castTag(.enum_full).?.data;
3299 if (enum_full.values.count() != 0) {
3300 const val = enum_full.values.keys()[field_index];
3301 return sema.addConstant(int_tag_ty, val);
3302 } else {
3303 // Field index and integer values are the same.
3304 const val = try Value.Tag.int_u64.create(arena, field_index);
3305 return sema.addConstant(int_tag_ty, val);
3306 }
3307 },
3308 .enum_simple => {
3309 // Field index and integer values are the same.
3310 const val = try Value.Tag.int_u64.create(arena, field_index);
3311 return sema.addConstant(int_tag_ty, val);
3312 },
3313 else => unreachable,
3314 }
3315 } else {
3316 // Assume it is already an integer and return it directly.
3317 return sema.addConstant(int_tag_ty, enum_tag_val);
3318 }
3319 }3404 }
33203405
3321 try sema.requireRuntimeBlock(block, src);3406 try sema.requireRuntimeBlock(block, src);
...@@ -3400,7 +3485,10 @@ fn zirOptionalPayloadPtr(...@@ -3400,7 +3485,10 @@ fn zirOptionalPayloadPtr(
3400 return sema.mod.fail(&block.base, src, "unable to unwrap null", .{});3485 return sema.mod.fail(&block.base, src, "unable to unwrap null", .{});
3401 }3486 }
3402 // The same Value represents the pointer to the optional and the payload.3487 // The same Value represents the pointer to the optional and the payload.
3403 return sema.addConstant(child_pointer, pointer_val);3488 return sema.addConstant(
3489 child_pointer,
3490 try Value.Tag.opt_payload_ptr.create(sema.arena, pointer_val),
3491 );
3404 }3492 }
3405 }3493 }
34063494
...@@ -3437,7 +3525,8 @@ fn zirOptionalPayload(...@@ -3437,7 +3525,8 @@ fn zirOptionalPayload(
3437 if (val.isNull()) {3525 if (val.isNull()) {
3438 return sema.mod.fail(&block.base, src, "unable to unwrap null", .{});3526 return sema.mod.fail(&block.base, src, "unable to unwrap null", .{});
3439 }3527 }
3440 return sema.addConstant(child_type, val);3528 const sub_val = val.castTag(.opt_payload).?.data;
3529 return sema.addConstant(child_type, sub_val);
3441 }3530 }
34423531
3443 try sema.requireRuntimeBlock(block, src);3532 try sema.requireRuntimeBlock(block, src);
...@@ -5294,17 +5383,56 @@ fn zirShl(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!A...@@ -5294,17 +5383,56 @@ fn zirShl(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!A
5294 const tracy = trace(@src());5383 const tracy = trace(@src());
5295 defer tracy.end();5384 defer tracy.end();
52965385
5297 _ = block;5386 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
5298 _ = inst;5387 const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
5299 return sema.mod.fail(&block.base, sema.src, "TODO implement zirShl", .{});5388 const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
5389 const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
5390 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
5391 const lhs = sema.resolveInst(extra.lhs);
5392 const rhs = sema.resolveInst(extra.rhs);
5393
5394 if (try sema.resolveMaybeUndefVal(block, lhs_src, lhs)) |lhs_val| {
5395 if (try sema.resolveMaybeUndefVal(block, rhs_src, rhs)) |rhs_val| {
5396 if (lhs_val.isUndef() or rhs_val.isUndef()) {
5397 return sema.addConstUndef(sema.typeOf(lhs));
5398 }
5399 return sema.mod.fail(&block.base, src, "TODO implement comptime shl", .{});
5400 }
5401 }
5402
5403 try sema.requireRuntimeBlock(block, src);
5404 return block.addBinOp(.shl, lhs, rhs);
5300}5405}
53015406
5302fn zirShr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {5407fn zirShr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
5303 const tracy = trace(@src());5408 const tracy = trace(@src());
5304 defer tracy.end();5409 defer tracy.end();
53055410
5306 _ = inst;5411 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
5307 return sema.mod.fail(&block.base, sema.src, "TODO implement zirShr", .{});5412 const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
5413 const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
5414 const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
5415 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
5416 const lhs = sema.resolveInst(extra.lhs);
5417 const rhs = sema.resolveInst(extra.rhs);
5418
5419 if (try sema.resolveMaybeUndefVal(block, lhs_src, lhs)) |lhs_val| {
5420 if (try sema.resolveMaybeUndefVal(block, rhs_src, rhs)) |rhs_val| {
5421 const lhs_ty = sema.typeOf(lhs);
5422 if (lhs_val.isUndef() or rhs_val.isUndef()) {
5423 return sema.addConstUndef(lhs_ty);
5424 }
5425 // If rhs is 0, return lhs without doing any calculations.
5426 if (rhs_val.compareWithZero(.eq)) {
5427 return sema.addConstant(lhs_ty, lhs_val);
5428 }
5429 const val = try lhs_val.shr(rhs_val, sema.arena);
5430 return sema.addConstant(lhs_ty, val);
5431 }
5432 }
5433
5434 try sema.requireRuntimeBlock(block, src);
5435 return block.addBinOp(.shr, lhs, rhs);
5308}5436}
53095437
5310fn zirBitwise(5438fn zirBitwise(
...@@ -5975,6 +6103,28 @@ fn zirTypeInfo(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileEr...@@ -5975,6 +6103,28 @@ fn zirTypeInfo(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileEr
5975 }),6103 }),
5976 );6104 );
5977 },6105 },
6106 .Int => {
6107 const info = ty.intInfo(target);
6108 const field_values = try sema.arena.alloc(Value, 2);
6109 // signedness: Signedness,
6110 field_values[0] = try Value.Tag.enum_field_index.create(
6111 sema.arena,
6112 @enumToInt(info.signedness),
6113 );
6114 // bits: comptime_int,
6115 field_values[1] = try Value.Tag.int_u64.create(sema.arena, info.bits);
6116
6117 return sema.addConstant(
6118 type_info_ty,
6119 try Value.Tag.@"union".create(sema.arena, .{
6120 .tag = try Value.Tag.enum_field_index.create(
6121 sema.arena,
6122 @enumToInt(@typeInfo(std.builtin.TypeInfo).Union.tag_type.?.Int),
6123 ),
6124 .val = try Value.Tag.@"struct".create(sema.arena, field_values.ptr),
6125 }),
6126 );
6127 },
5978 else => |t| return sema.mod.fail(&block.base, src, "TODO: implement zirTypeInfo for {s}", .{6128 else => |t| return sema.mod.fail(&block.base, src, "TODO: implement zirTypeInfo for {s}", .{
5979 @tagName(t),6129 @tagName(t),
5980 }),6130 }),
...@@ -6001,13 +6151,37 @@ fn zirTypeofElem(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) Compile...@@ -6001,13 +6151,37 @@ fn zirTypeofElem(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) Compile
6001fn zirTypeofLog2IntType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {6151fn zirTypeofLog2IntType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
6002 const inst_data = sema.code.instructions.items(.data)[inst].un_node;6152 const inst_data = sema.code.instructions.items(.data)[inst].un_node;
6003 const src = inst_data.src();6153 const src = inst_data.src();
6004 return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirTypeofLog2IntType", .{});6154 const operand = sema.resolveInst(inst_data.operand);
6155 const operand_ty = sema.typeOf(operand);
6156 return sema.log2IntType(block, operand_ty, src);
6005}6157}
60066158
6007fn zirLog2IntType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {6159fn zirLog2IntType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
6008 const inst_data = sema.code.instructions.items(.data)[inst].un_node;6160 const inst_data = sema.code.instructions.items(.data)[inst].un_node;
6009 const src = inst_data.src();6161 const src = inst_data.src();
6010 return sema.mod.fail(&block.base, src, "TODO: implement Sema.zirLog2IntType", .{});6162 const operand = try sema.resolveType(block, src, inst_data.operand);
6163 return sema.log2IntType(block, operand, src);
6164}
6165
6166fn log2IntType(sema: *Sema, block: *Scope.Block, operand: Type, src: LazySrcLoc) CompileError!Air.Inst.Ref {
6167 switch (operand.zigTypeTag()) {
6168 .ComptimeInt => return Air.Inst.Ref.comptime_int_type,
6169 .Int => {
6170 var count: u16 = 0;
6171 var s = operand.bitSize(sema.mod.getTarget()) - 1;
6172 while (s != 0) : (s >>= 1) {
6173 count += 1;
6174 }
6175 const res = try Module.makeIntType(sema.arena, .unsigned, count);
6176 return sema.addType(res);
6177 },
6178 else => return sema.mod.fail(
6179 &block.base,
6180 src,
6181 "bit shifting operation expected integer type, found '{}'",
6182 .{operand},
6183 ),
6184 }
6011}6185}
60126186
6013fn zirTypeofPeer(6187fn zirTypeofPeer(
...@@ -6464,99 +6638,134 @@ fn zirStructInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref:...@@ -6464,99 +6638,134 @@ fn zirStructInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref:
6464 const first_field_type_data = zir_datas[first_item.field_type].pl_node;6638 const first_field_type_data = zir_datas[first_item.field_type].pl_node;
6465 const first_field_type_extra = sema.code.extraData(Zir.Inst.FieldType, first_field_type_data.payload_index).data;6639 const first_field_type_extra = sema.code.extraData(Zir.Inst.FieldType, first_field_type_data.payload_index).data;
6466 const unresolved_struct_type = try sema.resolveType(block, src, first_field_type_extra.container_type);6640 const unresolved_struct_type = try sema.resolveType(block, src, first_field_type_extra.container_type);
6467 const struct_ty = try sema.resolveTypeFields(block, src, unresolved_struct_type);6641 const resolved_ty = try sema.resolveTypeFields(block, src, unresolved_struct_type);
6468 const struct_obj = struct_ty.castTag(.@"struct").?.data;6642
64696643 if (resolved_ty.castTag(.@"struct")) |struct_payload| {
6470 // Maps field index to field_type index of where it was already initialized.6644 const struct_obj = struct_payload.data;
6471 // For making sure all fields are accounted for and no fields are duplicated.6645
6472 const found_fields = try gpa.alloc(Zir.Inst.Index, struct_obj.fields.count());6646 // Maps field index to field_type index of where it was already initialized.
6473 defer gpa.free(found_fields);6647 // For making sure all fields are accounted for and no fields are duplicated.
6474 mem.set(Zir.Inst.Index, found_fields, 0);6648 const found_fields = try gpa.alloc(Zir.Inst.Index, struct_obj.fields.count());
6649 defer gpa.free(found_fields);
6650 mem.set(Zir.Inst.Index, found_fields, 0);
6651
6652 // The init values to use for the struct instance.
6653 const field_inits = try gpa.alloc(Air.Inst.Ref, struct_obj.fields.count());
6654 defer gpa.free(field_inits);
6655
6656 var field_i: u32 = 0;
6657 var extra_index = extra.end;
6658
6659 while (field_i < extra.data.fields_len) : (field_i += 1) {
6660 const item = sema.code.extraData(Zir.Inst.StructInit.Item, extra_index);
6661 extra_index = item.end;
6662
6663 const field_type_data = zir_datas[item.data.field_type].pl_node;
6664 const field_src: LazySrcLoc = .{ .node_offset_back2tok = field_type_data.src_node };
6665 const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;
6666 const field_name = sema.code.nullTerminatedString(field_type_extra.name_start);
6667 const field_index = struct_obj.fields.getIndex(field_name) orelse
6668 return sema.failWithBadFieldAccess(block, struct_obj, field_src, field_name);
6669 if (found_fields[field_index] != 0) {
6670 const other_field_type = found_fields[field_index];
6671 const other_field_type_data = zir_datas[other_field_type].pl_node;
6672 const other_field_src: LazySrcLoc = .{ .node_offset_back2tok = other_field_type_data.src_node };
6673 const msg = msg: {
6674 const msg = try mod.errMsg(&block.base, field_src, "duplicate field", .{});
6675 errdefer msg.destroy(gpa);
6676 try mod.errNote(&block.base, other_field_src, msg, "other field here", .{});
6677 break :msg msg;
6678 };
6679 return mod.failWithOwnedErrorMsg(&block.base, msg);
6680 }
6681 found_fields[field_index] = item.data.field_type;
6682 field_inits[field_index] = sema.resolveInst(item.data.init);
6683 }
64756684
6476 // The init values to use for the struct instance.6685 var root_msg: ?*Module.ErrorMsg = null;
6477 const field_inits = try gpa.alloc(Air.Inst.Ref, struct_obj.fields.count());
6478 defer gpa.free(field_inits);
64796686
6480 var field_i: u32 = 0;6687 for (found_fields) |field_type_inst, i| {
6481 var extra_index = extra.end;6688 if (field_type_inst != 0) continue;
6482
6483 while (field_i < extra.data.fields_len) : (field_i += 1) {
6484 const item = sema.code.extraData(Zir.Inst.StructInit.Item, extra_index);
6485 extra_index = item.end;
64866689
6487 const field_type_data = zir_datas[item.data.field_type].pl_node;6690 // Check if the field has a default init.
6488 const field_src: LazySrcLoc = .{ .node_offset_back2tok = field_type_data.src_node };6691 const field = struct_obj.fields.values()[i];
6489 const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;6692 if (field.default_val.tag() == .unreachable_value) {
6490 const field_name = sema.code.nullTerminatedString(field_type_extra.name_start);6693 const field_name = struct_obj.fields.keys()[i];
6491 const field_index = struct_obj.fields.getIndex(field_name) orelse6694 const template = "missing struct field: {s}";
6492 return sema.failWithBadFieldAccess(block, struct_obj, field_src, field_name);6695 const args = .{field_name};
6493 if (found_fields[field_index] != 0) {6696 if (root_msg) |msg| {
6494 const other_field_type = found_fields[field_index];6697 try mod.errNote(&block.base, src, msg, template, args);
6495 const other_field_type_data = zir_datas[other_field_type].pl_node;6698 } else {
6496 const other_field_src: LazySrcLoc = .{ .node_offset_back2tok = other_field_type_data.src_node };6699 root_msg = try mod.errMsg(&block.base, src, template, args);
6497 const msg = msg: {6700 }
6498 const msg = try mod.errMsg(&block.base, field_src, "duplicate field", .{});6701 } else {
6499 errdefer msg.destroy(gpa);6702 field_inits[i] = try sema.addConstant(field.ty, field.default_val);
6500 try mod.errNote(&block.base, other_field_src, msg, "other field here", .{});6703 }
6501 break :msg msg;6704 }
6502 };6705 if (root_msg) |msg| {
6706 const fqn = try struct_obj.getFullyQualifiedName(gpa);
6707 defer gpa.free(fqn);
6708 try mod.errNoteNonLazy(
6709 struct_obj.srcLoc(),
6710 msg,
6711 "struct '{s}' declared here",
6712 .{fqn},
6713 );
6503 return mod.failWithOwnedErrorMsg(&block.base, msg);6714 return mod.failWithOwnedErrorMsg(&block.base, msg);
6504 }6715 }
6505 found_fields[field_index] = item.data.field_type;
6506 field_inits[field_index] = sema.resolveInst(item.data.init);
6507 }
65086716
6509 var root_msg: ?*Module.ErrorMsg = null;6717 if (is_ref) {
6718 return mod.fail(&block.base, src, "TODO: Sema.zirStructInit is_ref=true", .{});
6719 }
65106720
6511 for (found_fields) |field_type_inst, i| {6721 const is_comptime = for (field_inits) |field_init| {
6512 if (field_type_inst != 0) continue;6722 if (!(try sema.isComptimeKnown(block, src, field_init))) {
65136723 break false;
6514 // Check if the field has a default init.
6515 const field = struct_obj.fields.values()[i];
6516 if (field.default_val.tag() == .unreachable_value) {
6517 const field_name = struct_obj.fields.keys()[i];
6518 const template = "missing struct field: {s}";
6519 const args = .{field_name};
6520 if (root_msg) |msg| {
6521 try mod.errNote(&block.base, src, msg, template, args);
6522 } else {
6523 root_msg = try mod.errMsg(&block.base, src, template, args);
6524 }6724 }
6525 } else {6725 } else true;
6526 field_inits[i] = try sema.addConstant(field.ty, field.default_val);6726
6727 if (is_comptime) {
6728 const values = try sema.arena.alloc(Value, field_inits.len);
6729 for (field_inits) |field_init, i| {
6730 values[i] = (sema.resolveMaybeUndefVal(block, src, field_init) catch unreachable).?;
6731 }
6732 return sema.addConstant(resolved_ty, try Value.Tag.@"struct".create(sema.arena, values.ptr));
6527 }6733 }
6528 }
6529 if (root_msg) |msg| {
6530 const fqn = try struct_obj.getFullyQualifiedName(gpa);
6531 defer gpa.free(fqn);
6532 try mod.errNoteNonLazy(
6533 struct_obj.srcLoc(),
6534 msg,
6535 "struct '{s}' declared here",
6536 .{fqn},
6537 );
6538 return mod.failWithOwnedErrorMsg(&block.base, msg);
6539 }
65406734
6541 if (is_ref) {6735 return mod.fail(&block.base, src, "TODO: Sema.zirStructInit for runtime-known struct values", .{});
6542 return mod.fail(&block.base, src, "TODO: Sema.zirStructInit is_ref=true", .{});6736 } else if (resolved_ty.cast(Type.Payload.Union)) |union_payload| {
6543 }6737 const union_obj = union_payload.data;
6738
6739 if (extra.data.fields_len != 1) {
6740 return sema.mod.fail(&block.base, src, "union initialization expects exactly one field", .{});
6741 }
65446742
6545 const is_comptime = for (field_inits) |field_init| {6743 const item = sema.code.extraData(Zir.Inst.StructInit.Item, extra.end);
6546 if (!(try sema.isComptimeKnown(block, src, field_init))) {6744
6547 break false;6745 const field_type_data = zir_datas[item.data.field_type].pl_node;
6746 const field_src: LazySrcLoc = .{ .node_offset_back2tok = field_type_data.src_node };
6747 const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;
6748 const field_name = sema.code.nullTerminatedString(field_type_extra.name_start);
6749 const field_index = union_obj.fields.getIndex(field_name) orelse
6750 return sema.failWithBadUnionFieldAccess(block, union_obj, field_src, field_name);
6751
6752 if (is_ref) {
6753 return mod.fail(&block.base, src, "TODO: Sema.zirStructInit is_ref=true union", .{});
6548 }6754 }
6549 } else true;
65506755
6551 if (is_comptime) {6756 const init_inst = sema.resolveInst(item.data.init);
6552 const values = try sema.arena.alloc(Value, field_inits.len);6757 if (try sema.resolveMaybeUndefVal(block, field_src, init_inst)) |val| {
6553 for (field_inits) |field_init, i| {6758 return sema.addConstant(
6554 values[i] = (sema.resolveMaybeUndefVal(block, src, field_init) catch unreachable).?;6759 resolved_ty,
6760 try Value.Tag.@"union".create(sema.arena, .{
6761 .tag = try Value.Tag.int_u64.create(sema.arena, field_index),
6762 .val = val,
6763 }),
6764 );
6555 }6765 }
6556 return sema.addConstant(struct_ty, try Value.Tag.@"struct".create(sema.arena, values.ptr));6766 return mod.fail(&block.base, src, "TODO: Sema.zirStructInit for runtime-known union values", .{});
6557 }6767 }
65586768 unreachable;
6559 return mod.fail(&block.base, src, "TODO: Sema.zirStructInit for runtime-known struct values", .{});
6560}6769}
65616770
6562fn zirStructInitAnon(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: bool) CompileError!Air.Inst.Ref {6771fn zirStructInitAnon(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: bool) CompileError!Air.Inst.Ref {
...@@ -6594,17 +6803,25 @@ fn zirFieldType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileE...@@ -6594,17 +6803,25 @@ fn zirFieldType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileE
6594 const extra = sema.code.extraData(Zir.Inst.FieldType, inst_data.payload_index).data;6803 const extra = sema.code.extraData(Zir.Inst.FieldType, inst_data.payload_index).data;
6595 const src = inst_data.src();6804 const src = inst_data.src();
6596 const field_name = sema.code.nullTerminatedString(extra.name_start);6805 const field_name = sema.code.nullTerminatedString(extra.name_start);
6597 const unresolved_struct_type = try sema.resolveType(block, src, extra.container_type);6806 const unresolved_ty = try sema.resolveType(block, src, extra.container_type);
6598 if (unresolved_struct_type.zigTypeTag() != .Struct) {6807 const resolved_ty = try sema.resolveTypeFields(block, src, unresolved_ty);
6599 return sema.mod.fail(&block.base, src, "expected struct; found '{}'", .{6808 switch (resolved_ty.zigTypeTag()) {
6600 unresolved_struct_type,6809 .Struct => {
6601 });6810 const struct_obj = resolved_ty.castTag(.@"struct").?.data;
6811 const field = struct_obj.fields.get(field_name) orelse
6812 return sema.failWithBadFieldAccess(block, struct_obj, src, field_name);
6813 return sema.addType(field.ty);
6814 },
6815 .Union => {
6816 const union_obj = resolved_ty.cast(Type.Payload.Union).?.data;
6817 const field = union_obj.fields.get(field_name) orelse
6818 return sema.failWithBadUnionFieldAccess(block, union_obj, src, field_name);
6819 return sema.addType(field.ty);
6820 },
6821 else => return sema.mod.fail(&block.base, src, "expected struct or union; found '{}'", .{
6822 resolved_ty,
6823 }),
6602 }6824 }
6603 const struct_ty = try sema.resolveTypeFields(block, src, unresolved_struct_type);
6604 const struct_obj = struct_ty.castTag(.@"struct").?.data;
6605 const field = struct_obj.fields.get(field_name) orelse
6606 return sema.failWithBadFieldAccess(block, struct_obj, src, field_name);
6607 return sema.addType(field.ty);
6608}6825}
66096826
6610fn zirErrorReturnTrace(6827fn zirErrorReturnTrace(
...@@ -6679,7 +6896,54 @@ fn zirTagName(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileErr...@@ -6679,7 +6896,54 @@ fn zirTagName(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileErr
6679fn zirReify(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {6896fn zirReify(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
6680 const inst_data = sema.code.instructions.items(.data)[inst].un_node;6897 const inst_data = sema.code.instructions.items(.data)[inst].un_node;
6681 const src = inst_data.src();6898 const src = inst_data.src();
6682 return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify", .{});6899 const type_info_ty = try sema.getBuiltinType(block, src, "TypeInfo");
6900 const uncasted_operand = sema.resolveInst(inst_data.operand);
6901 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
6902 const type_info = try sema.coerce(block, type_info_ty, uncasted_operand, operand_src);
6903 const val = try sema.resolveConstValue(block, operand_src, type_info);
6904 const union_val = val.cast(Value.Payload.Union).?.data;
6905 const TypeInfoTag = std.meta.Tag(std.builtin.TypeInfo);
6906 const tag_index = @intCast(std.meta.Tag(TypeInfoTag), union_val.tag.toUnsignedInt());
6907 switch (@intToEnum(std.builtin.TypeId, tag_index)) {
6908 .Type => return Air.Inst.Ref.type_type,
6909 .Void => return Air.Inst.Ref.void_type,
6910 .Bool => return Air.Inst.Ref.bool_type,
6911 .NoReturn => return Air.Inst.Ref.noreturn_type,
6912 .Int => {
6913 const struct_val = union_val.val.castTag(.@"struct").?.data;
6914 // TODO use reflection instead of magic numbers here
6915 const signedness_val = struct_val[0];
6916 const bits_val = struct_val[1];
6917
6918 const signedness = signedness_val.toEnum(std.builtin.Signedness);
6919 const bits = @intCast(u16, bits_val.toUnsignedInt());
6920 const ty = switch (signedness) {
6921 .signed => try Type.Tag.int_signed.create(sema.arena, bits),
6922 .unsigned => try Type.Tag.int_unsigned.create(sema.arena, bits),
6923 };
6924 return sema.addType(ty);
6925 },
6926 .Float => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for Float", .{}),
6927 .Pointer => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for Pointer", .{}),
6928 .Array => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for Array", .{}),
6929 .Struct => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for Struct", .{}),
6930 .ComptimeFloat => return Air.Inst.Ref.comptime_float_type,
6931 .ComptimeInt => return Air.Inst.Ref.comptime_int_type,
6932 .Undefined => return Air.Inst.Ref.undefined_type,
6933 .Null => return Air.Inst.Ref.null_type,
6934 .Optional => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for Optional", .{}),
6935 .ErrorUnion => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for ErrorUnion", .{}),
6936 .ErrorSet => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for ErrorSet", .{}),
6937 .Enum => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for Enum", .{}),
6938 .Union => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for Union", .{}),
6939 .Fn => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for Fn", .{}),
6940 .BoundFn => @panic("TODO delete BoundFn from the language"),
6941 .Opaque => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for Opaque", .{}),
6942 .Frame => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for Frame", .{}),
6943 .AnyFrame => return Air.Inst.Ref.anyframe_type,
6944 .Vector => return sema.mod.fail(&block.base, src, "TODO: Sema.zirReify for Vector", .{}),
6945 .EnumLiteral => return Air.Inst.Ref.enum_literal_type,
6946 }
6683}6947}
66846948
6685fn zirTypeName(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {6949fn zirTypeName(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
...@@ -7855,14 +8119,29 @@ fn structFieldPtr(...@@ -7855,14 +8119,29 @@ fn structFieldPtr(
7855 }8119 }
78568120
7857 try sema.requireRuntimeBlock(block, src);8121 try sema.requireRuntimeBlock(block, src);
8122 const tag: Air.Inst.Tag = switch (field_index) {
8123 0 => .struct_field_ptr_index_0,
8124 1 => .struct_field_ptr_index_1,
8125 2 => .struct_field_ptr_index_2,
8126 3 => .struct_field_ptr_index_3,
8127 else => {
8128 return block.addInst(.{
8129 .tag = .struct_field_ptr,
8130 .data = .{ .ty_pl = .{
8131 .ty = try sema.addType(ptr_field_ty),
8132 .payload = try sema.addExtra(Air.StructField{
8133 .struct_operand = struct_ptr,
8134 .field_index = @intCast(u32, field_index),
8135 }),
8136 } },
8137 });
8138 },
8139 };
7858 return block.addInst(.{8140 return block.addInst(.{
7859 .tag = .struct_field_ptr,8141 .tag = tag,
7860 .data = .{ .ty_pl = .{8142 .data = .{ .ty_op = .{
7861 .ty = try sema.addType(ptr_field_ty),8143 .ty = try sema.addType(ptr_field_ty),
7862 .payload = try sema.addExtra(Air.StructField{8144 .operand = struct_ptr,
7863 .struct_operand = struct_ptr,
7864 .field_index = @intCast(u32, field_index),
7865 }),
7866 } },8145 } },
7867 });8146 });
7868}8147}
...@@ -8099,24 +8378,35 @@ fn elemPtrArray(...@@ -8099,24 +8378,35 @@ fn elemPtrArray(
8099 elem_index: Air.Inst.Ref,8378 elem_index: Air.Inst.Ref,
8100 elem_index_src: LazySrcLoc,8379 elem_index_src: LazySrcLoc,
8101) CompileError!Air.Inst.Ref {8380) CompileError!Air.Inst.Ref {
8381 const array_ptr_ty = sema.typeOf(array_ptr);
8382 const pointee_type = array_ptr_ty.elemType().elemType();
8383 const result_ty = if (array_ptr_ty.ptrIsMutable())
8384 try Type.Tag.single_mut_pointer.create(sema.arena, pointee_type)
8385 else
8386 try Type.Tag.single_const_pointer.create(sema.arena, pointee_type);
8387
8102 if (try sema.resolveDefinedValue(block, src, array_ptr)) |array_ptr_val| {8388 if (try sema.resolveDefinedValue(block, src, array_ptr)) |array_ptr_val| {
8103 if (try sema.resolveDefinedValue(block, src, elem_index)) |index_val| {8389 if (try sema.resolveDefinedValue(block, elem_index_src, elem_index)) |index_val| {
8104 // Both array pointer and index are compile-time known.8390 // Both array pointer and index are compile-time known.
8105 const index_u64 = index_val.toUnsignedInt();8391 const index_u64 = index_val.toUnsignedInt();
8106 // @intCast here because it would have been impossible to construct a value that8392 // @intCast here because it would have been impossible to construct a value that
8107 // required a larger index.8393 // required a larger index.
8108 const elem_ptr = try array_ptr_val.elemPtr(sema.arena, @intCast(usize, index_u64));8394 const elem_ptr = try array_ptr_val.elemPtr(sema.arena, @intCast(usize, index_u64));
8109 const pointee_type = sema.typeOf(array_ptr).elemType().elemType();8395 return sema.addConstant(result_ty, elem_ptr);
8110
8111 return sema.addConstant(
8112 try Type.Tag.single_const_pointer.create(sema.arena, pointee_type),
8113 elem_ptr,
8114 );
8115 }8396 }
8116 }8397 }
8117 _ = elem_index;8398 // TODO safety check for array bounds
8118 _ = elem_index_src;8399 try sema.requireRuntimeBlock(block, src);
8119 return sema.mod.fail(&block.base, src, "TODO implement more analyze elemptr for arrays", .{});8400 return block.addInst(.{
8401 .tag = .ptr_elem_ptr,
8402 .data = .{ .ty_pl = .{
8403 .ty = try sema.addType(result_ty),
8404 .payload = try sema.addExtra(Air.Bin{
8405 .lhs = array_ptr,
8406 .rhs = elem_index,
8407 }),
8408 } },
8409 });
8120}8410}
81218411
8122fn coerce(8412fn coerce(
...@@ -8528,9 +8818,12 @@ fn analyzeRef(...@@ -8528,9 +8818,12 @@ fn analyzeRef(
85288818
8529 try sema.requireRuntimeBlock(block, src);8819 try sema.requireRuntimeBlock(block, src);
8530 const ptr_type = try Module.simplePtrType(sema.arena, operand_ty, false, .One);8820 const ptr_type = try Module.simplePtrType(sema.arena, operand_ty, false, .One);
8531 const alloc = try block.addTy(.alloc, ptr_type);8821 const mut_ptr_type = try Module.simplePtrType(sema.arena, operand_ty, true, .One);
8822 const alloc = try block.addTy(.alloc, mut_ptr_type);
8532 try sema.storePtr(block, src, alloc, operand);8823 try sema.storePtr(block, src, alloc, operand);
8533 return alloc;8824
8825 // TODO: Replace with sema.coerce when that supports adding pointer constness.
8826 return sema.bitcast(block, ptr_type, alloc, src);
8534}8827}
85358828
8536fn analyzeLoad(8829fn analyzeLoad(
...@@ -8895,7 +9188,7 @@ fn wrapOptional(...@@ -8895,7 +9188,7 @@ fn wrapOptional(
8895 inst_src: LazySrcLoc,9188 inst_src: LazySrcLoc,
8896) !Air.Inst.Ref {9189) !Air.Inst.Ref {
8897 if (try sema.resolveMaybeUndefVal(block, inst_src, inst)) |val| {9190 if (try sema.resolveMaybeUndefVal(block, inst_src, inst)) |val| {
8898 return sema.addConstant(dest_type, val);9191 return sema.addConstant(dest_type, try Value.Tag.opt_payload.create(sema.arena, val));
8899 }9192 }
89009193
8901 try sema.requireRuntimeBlock(block, inst_src);9194 try sema.requireRuntimeBlock(block, inst_src);
...@@ -9124,22 +9417,62 @@ pub fn resolveTypeLayout(...@@ -9124,22 +9417,62 @@ pub fn resolveTypeLayout(
9124 }9417 }
9125}9418}
91269419
9127fn resolveTypeFields(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, ty: Type) CompileError!Type {9420/// `sema` and `block` are expected to be the same ones used for the `Decl`.
9421pub fn resolveDeclFields(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, ty: Type) !void {
9128 switch (ty.tag()) {9422 switch (ty.tag()) {
9129 .@"struct" => {9423 .@"struct" => {
9130 const struct_obj = ty.castTag(.@"struct").?.data;9424 const struct_obj = ty.castTag(.@"struct").?.data;
9425 if (struct_obj.owner_decl.namespace != sema.owner_decl.namespace) return;
9131 switch (struct_obj.status) {9426 switch (struct_obj.status) {
9132 .none => {},9427 .none => {},
9133 .field_types_wip => {9428 .field_types_wip => {
9134 return sema.mod.fail(&block.base, src, "struct {} depends on itself", .{ty});9429 return sema.mod.fail(&block.base, src, "struct {} depends on itself", .{ty});
9135 },9430 },
9136 .have_field_types, .have_layout, .layout_wip => return ty,9431 .have_field_types, .have_layout, .layout_wip => return,
9137 }9432 }
9433 const prev_namespace = sema.namespace;
9434 sema.namespace = &struct_obj.namespace;
9435 defer sema.namespace = prev_namespace;
9436
9138 struct_obj.status = .field_types_wip;9437 struct_obj.status = .field_types_wip;
9139 try sema.mod.analyzeStructFields(struct_obj);9438 try sema.analyzeStructFields(block, struct_obj);
9140 struct_obj.status = .have_field_types;9439 struct_obj.status = .have_field_types;
9141 return ty;
9142 },9440 },
9441 .@"union", .union_tagged => {
9442 const union_obj = ty.cast(Type.Payload.Union).?.data;
9443 if (union_obj.owner_decl.namespace != sema.owner_decl.namespace) return;
9444 switch (union_obj.status) {
9445 .none => {},
9446 .field_types_wip => {
9447 return sema.mod.fail(&block.base, src, "union {} depends on itself", .{ty});
9448 },
9449 .have_field_types, .have_layout, .layout_wip => return,
9450 }
9451 const prev_namespace = sema.namespace;
9452 sema.namespace = &union_obj.namespace;
9453 defer sema.namespace = prev_namespace;
9454
9455 union_obj.status = .field_types_wip;
9456 try sema.analyzeUnionFields(block, union_obj);
9457 union_obj.status = .have_field_types;
9458 },
9459 else => return,
9460 }
9461}
9462
9463fn resolveTypeFields(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, ty: Type) CompileError!Type {
9464 switch (ty.tag()) {
9465 .@"struct" => {
9466 const struct_obj = ty.castTag(.@"struct").?.data;
9467 switch (struct_obj.status) {
9468 .none => unreachable,
9469 .field_types_wip => {
9470 return sema.mod.fail(&block.base, src, "struct {} depends on itself", .{ty});
9471 },
9472 .have_field_types, .have_layout, .layout_wip => return ty,
9473 }
9474 },
9475 .type_info => return sema.resolveBuiltinTypeFields(block, src, "TypeInfo"),
9143 .extern_options => return sema.resolveBuiltinTypeFields(block, src, "ExternOptions"),9476 .extern_options => return sema.resolveBuiltinTypeFields(block, src, "ExternOptions"),
9144 .export_options => return sema.resolveBuiltinTypeFields(block, src, "ExportOptions"),9477 .export_options => return sema.resolveBuiltinTypeFields(block, src, "ExportOptions"),
9145 .atomic_ordering => return sema.resolveBuiltinTypeFields(block, src, "AtomicOrdering"),9478 .atomic_ordering => return sema.resolveBuiltinTypeFields(block, src, "AtomicOrdering"),
...@@ -9152,18 +9485,12 @@ fn resolveTypeFields(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, ty: Type...@@ -9152,18 +9485,12 @@ fn resolveTypeFields(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, ty: Type
9152 .@"union", .union_tagged => {9485 .@"union", .union_tagged => {
9153 const union_obj = ty.cast(Type.Payload.Union).?.data;9486 const union_obj = ty.cast(Type.Payload.Union).?.data;
9154 switch (union_obj.status) {9487 switch (union_obj.status) {
9155 .none => {},9488 .none => unreachable,
9156 .field_types_wip => {9489 .field_types_wip => {
9157 return sema.mod.fail(&block.base, src, "union {} depends on itself", .{9490 return sema.mod.fail(&block.base, src, "union {} depends on itself", .{ty});
9158 ty,
9159 });
9160 },9491 },
9161 .have_field_types, .have_layout, .layout_wip => return ty,9492 .have_field_types, .have_layout, .layout_wip => return ty,
9162 }9493 }
9163 union_obj.status = .field_types_wip;
9164 try sema.mod.analyzeUnionFields(union_obj);
9165 union_obj.status = .have_field_types;
9166 return ty;
9167 },9494 },
9168 else => return ty,9495 else => return ty,
9169 }9496 }
...@@ -9179,6 +9506,265 @@ fn resolveBuiltinTypeFields(...@@ -9179,6 +9506,265 @@ fn resolveBuiltinTypeFields(
9179 return sema.resolveTypeFields(block, src, resolved_ty);9506 return sema.resolveTypeFields(block, src, resolved_ty);
9180}9507}
91819508
9509fn analyzeStructFields(
9510 sema: *Sema,
9511 block: *Scope.Block,
9512 struct_obj: *Module.Struct,
9513) CompileError!void {
9514 const tracy = trace(@src());
9515 defer tracy.end();
9516
9517 const gpa = sema.gpa;
9518 const zir = sema.code;
9519 const extended = zir.instructions.items(.data)[struct_obj.zir_index].extended;
9520 assert(extended.opcode == .struct_decl);
9521 const small = @bitCast(Zir.Inst.StructDecl.Small, extended.small);
9522 var extra_index: usize = extended.operand;
9523
9524 const src: LazySrcLoc = .{ .node_offset = struct_obj.node_offset };
9525 extra_index += @boolToInt(small.has_src_node);
9526
9527 const body_len = if (small.has_body_len) blk: {
9528 const body_len = zir.extra[extra_index];
9529 extra_index += 1;
9530 break :blk body_len;
9531 } else 0;
9532
9533 const fields_len = if (small.has_fields_len) blk: {
9534 const fields_len = zir.extra[extra_index];
9535 extra_index += 1;
9536 break :blk fields_len;
9537 } else 0;
9538
9539 const decls_len = if (small.has_decls_len) decls_len: {
9540 const decls_len = zir.extra[extra_index];
9541 extra_index += 1;
9542 break :decls_len decls_len;
9543 } else 0;
9544
9545 // Skip over decls.
9546 var decls_it = zir.declIteratorInner(extra_index, decls_len);
9547 while (decls_it.next()) |_| {}
9548 extra_index = decls_it.extra_index;
9549
9550 const body = zir.extra[extra_index..][0..body_len];
9551 if (fields_len == 0) {
9552 assert(body.len == 0);
9553 return;
9554 }
9555 extra_index += body.len;
9556
9557 var decl_arena = struct_obj.owner_decl.value_arena.?.promote(gpa);
9558 defer struct_obj.owner_decl.value_arena.?.* = decl_arena.state;
9559
9560 try struct_obj.fields.ensureTotalCapacity(&decl_arena.allocator, fields_len);
9561
9562 if (body.len != 0) {
9563 _ = try sema.analyzeBody(block, body);
9564 }
9565
9566 const bits_per_field = 4;
9567 const fields_per_u32 = 32 / bits_per_field;
9568 const bit_bags_count = std.math.divCeil(usize, fields_len, fields_per_u32) catch unreachable;
9569 var bit_bag_index: usize = extra_index;
9570 extra_index += bit_bags_count;
9571 var cur_bit_bag: u32 = undefined;
9572 var field_i: u32 = 0;
9573 while (field_i < fields_len) : (field_i += 1) {
9574 if (field_i % fields_per_u32 == 0) {
9575 cur_bit_bag = zir.extra[bit_bag_index];
9576 bit_bag_index += 1;
9577 }
9578 const has_align = @truncate(u1, cur_bit_bag) != 0;
9579 cur_bit_bag >>= 1;
9580 const has_default = @truncate(u1, cur_bit_bag) != 0;
9581 cur_bit_bag >>= 1;
9582 const is_comptime = @truncate(u1, cur_bit_bag) != 0;
9583 cur_bit_bag >>= 1;
9584 const unused = @truncate(u1, cur_bit_bag) != 0;
9585 cur_bit_bag >>= 1;
9586
9587 _ = unused;
9588
9589 const field_name_zir = zir.nullTerminatedString(zir.extra[extra_index]);
9590 extra_index += 1;
9591 const field_type_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
9592 extra_index += 1;
9593
9594 // This string needs to outlive the ZIR code.
9595 const field_name = try decl_arena.allocator.dupe(u8, field_name_zir);
9596 const field_ty: Type = if (field_type_ref == .none)
9597 Type.initTag(.noreturn)
9598 else
9599 // TODO: if we need to report an error here, use a source location
9600 // that points to this type expression rather than the struct.
9601 // But only resolve the source location if we need to emit a compile error.
9602 try sema.resolveType(block, src, field_type_ref);
9603
9604 const gop = struct_obj.fields.getOrPutAssumeCapacity(field_name);
9605 assert(!gop.found_existing);
9606 gop.value_ptr.* = .{
9607 .ty = try field_ty.copy(&decl_arena.allocator),
9608 .abi_align = Value.initTag(.abi_align_default),
9609 .default_val = Value.initTag(.unreachable_value),
9610 .is_comptime = is_comptime,
9611 .offset = undefined,
9612 };
9613
9614 if (has_align) {
9615 const align_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
9616 extra_index += 1;
9617 // TODO: if we need to report an error here, use a source location
9618 // that points to this alignment expression rather than the struct.
9619 // But only resolve the source location if we need to emit a compile error.
9620 const abi_align_val = (try sema.resolveInstConst(block, src, align_ref)).val;
9621 gop.value_ptr.abi_align = try abi_align_val.copy(&decl_arena.allocator);
9622 }
9623 if (has_default) {
9624 const default_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
9625 extra_index += 1;
9626 const default_inst = sema.resolveInst(default_ref);
9627 // TODO: if we need to report an error here, use a source location
9628 // that points to this default value expression rather than the struct.
9629 // But only resolve the source location if we need to emit a compile error.
9630 const default_val = (try sema.resolveMaybeUndefVal(block, src, default_inst)) orelse
9631 return sema.failWithNeededComptime(block, src);
9632 gop.value_ptr.default_val = try default_val.copy(&decl_arena.allocator);
9633 }
9634 }
9635}
9636
9637fn analyzeUnionFields(
9638 sema: *Sema,
9639 block: *Scope.Block,
9640 union_obj: *Module.Union,
9641) CompileError!void {
9642 const tracy = trace(@src());
9643 defer tracy.end();
9644
9645 const gpa = sema.gpa;
9646 const zir = sema.code;
9647 const extended = zir.instructions.items(.data)[union_obj.zir_index].extended;
9648 assert(extended.opcode == .union_decl);
9649 const small = @bitCast(Zir.Inst.UnionDecl.Small, extended.small);
9650 var extra_index: usize = extended.operand;
9651
9652 const src: LazySrcLoc = .{ .node_offset = union_obj.node_offset };
9653 extra_index += @boolToInt(small.has_src_node);
9654
9655 if (small.has_tag_type) {
9656 extra_index += 1;
9657 }
9658
9659 const body_len = if (small.has_body_len) blk: {
9660 const body_len = zir.extra[extra_index];
9661 extra_index += 1;
9662 break :blk body_len;
9663 } else 0;
9664
9665 const fields_len = if (small.has_fields_len) blk: {
9666 const fields_len = zir.extra[extra_index];
9667 extra_index += 1;
9668 break :blk fields_len;
9669 } else 0;
9670
9671 const decls_len = if (small.has_decls_len) decls_len: {
9672 const decls_len = zir.extra[extra_index];
9673 extra_index += 1;
9674 break :decls_len decls_len;
9675 } else 0;
9676
9677 // Skip over decls.
9678 var decls_it = zir.declIteratorInner(extra_index, decls_len);
9679 while (decls_it.next()) |_| {}
9680 extra_index = decls_it.extra_index;
9681
9682 const body = zir.extra[extra_index..][0..body_len];
9683 if (fields_len == 0) {
9684 assert(body.len == 0);
9685 return;
9686 }
9687 extra_index += body.len;
9688
9689 var decl_arena = union_obj.owner_decl.value_arena.?.promote(gpa);
9690 defer union_obj.owner_decl.value_arena.?.* = decl_arena.state;
9691
9692 try union_obj.fields.ensureCapacity(&decl_arena.allocator, fields_len);
9693
9694 if (body.len != 0) {
9695 _ = try sema.analyzeBody(block, body);
9696 }
9697
9698 const bits_per_field = 4;
9699 const fields_per_u32 = 32 / bits_per_field;
9700 const bit_bags_count = std.math.divCeil(usize, fields_len, fields_per_u32) catch unreachable;
9701 var bit_bag_index: usize = extra_index;
9702 extra_index += bit_bags_count;
9703 var cur_bit_bag: u32 = undefined;
9704 var field_i: u32 = 0;
9705 while (field_i < fields_len) : (field_i += 1) {
9706 if (field_i % fields_per_u32 == 0) {
9707 cur_bit_bag = zir.extra[bit_bag_index];
9708 bit_bag_index += 1;
9709 }
9710 const has_type = @truncate(u1, cur_bit_bag) != 0;
9711 cur_bit_bag >>= 1;
9712 const has_align = @truncate(u1, cur_bit_bag) != 0;
9713 cur_bit_bag >>= 1;
9714 const has_tag = @truncate(u1, cur_bit_bag) != 0;
9715 cur_bit_bag >>= 1;
9716 const unused = @truncate(u1, cur_bit_bag) != 0;
9717 cur_bit_bag >>= 1;
9718 _ = unused;
9719
9720 const field_name_zir = zir.nullTerminatedString(zir.extra[extra_index]);
9721 extra_index += 1;
9722
9723 const field_type_ref: Zir.Inst.Ref = if (has_type) blk: {
9724 const field_type_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
9725 extra_index += 1;
9726 break :blk field_type_ref;
9727 } else .none;
9728
9729 const align_ref: Zir.Inst.Ref = if (has_align) blk: {
9730 const align_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
9731 extra_index += 1;
9732 break :blk align_ref;
9733 } else .none;
9734
9735 if (has_tag) {
9736 extra_index += 1;
9737 }
9738
9739 // This string needs to outlive the ZIR code.
9740 const field_name = try decl_arena.allocator.dupe(u8, field_name_zir);
9741 const field_ty: Type = if (field_type_ref == .none)
9742 Type.initTag(.void)
9743 else
9744 // TODO: if we need to report an error here, use a source location
9745 // that points to this type expression rather than the union.
9746 // But only resolve the source location if we need to emit a compile error.
9747 try sema.resolveType(block, src, field_type_ref);
9748
9749 const gop = union_obj.fields.getOrPutAssumeCapacity(field_name);
9750 assert(!gop.found_existing);
9751 gop.value_ptr.* = .{
9752 .ty = try field_ty.copy(&decl_arena.allocator),
9753 .abi_align = Value.initTag(.abi_align_default),
9754 };
9755
9756 if (align_ref != .none) {
9757 // TODO: if we need to report an error here, use a source location
9758 // that points to this alignment expression rather than the struct.
9759 // But only resolve the source location if we need to emit a compile error.
9760 const abi_align_val = (try sema.resolveInstConst(block, src, align_ref)).val;
9761 gop.value_ptr.abi_align = try abi_align_val.copy(&decl_arena.allocator);
9762 }
9763 }
9764
9765 // TODO resolve the union tag_type_ref
9766}
9767
9182fn getBuiltin(9768fn getBuiltin(
9183 sema: *Sema,9769 sema: *Sema,
9184 block: *Scope.Block,9770 block: *Scope.Block,
...@@ -9291,6 +9877,7 @@ fn typeHasOnePossibleValue(...@@ -9291,6 +9877,7 @@ fn typeHasOnePossibleValue(
9291 .call_options,9877 .call_options,
9292 .export_options,9878 .export_options,
9293 .extern_options,9879 .extern_options,
9880 .type_info,
9294 .@"anyframe",9881 .@"anyframe",
9295 .anyframe_T,9882 .anyframe_T,
9296 .many_const_pointer,9883 .many_const_pointer,
...@@ -9475,6 +10062,7 @@ pub fn addType(sema: *Sema, ty: Type) !Air.Inst.Ref {...@@ -9475,6 +10062,7 @@ pub fn addType(sema: *Sema, ty: Type) !Air.Inst.Ref {
9475 .call_options => return .call_options_type,10062 .call_options => return .call_options_type,
9476 .export_options => return .export_options_type,10063 .export_options => return .export_options_type,
9477 .extern_options => return .extern_options_type,10064 .extern_options => return .extern_options_type,
10065 .type_info => return .type_info_type,
9478 .manyptr_u8 => return .manyptr_u8_type,10066 .manyptr_u8 => return .manyptr_u8_type,
9479 .manyptr_const_u8 => return .manyptr_const_u8_type,10067 .manyptr_const_u8 => return .manyptr_const_u8_type,
9480 .fn_noreturn_no_args => return .fn_noreturn_no_args_type,10068 .fn_noreturn_no_args => return .fn_noreturn_no_args_type,
src/TypedValue.zig+12-3
...@@ -23,9 +23,18 @@ pub const Managed = struct {...@@ -23,9 +23,18 @@ pub const Managed = struct {
23};23};
2424
25/// Assumes arena allocation. Does a recursive copy.25/// Assumes arena allocation. Does a recursive copy.
26pub fn copy(self: TypedValue, allocator: *Allocator) error{OutOfMemory}!TypedValue {26pub fn copy(self: TypedValue, arena: *Allocator) error{OutOfMemory}!TypedValue {
27 return TypedValue{27 return TypedValue{
28 .ty = try self.ty.copy(allocator),28 .ty = try self.ty.copy(arena),
29 .val = try self.val.copy(allocator),29 .val = try self.val.copy(arena),
30 };30 };
31}31}
32
33pub fn eql(a: TypedValue, b: TypedValue) bool {
34 if (!a.ty.eql(b.ty)) return false;
35 return a.val.eql(b.val, a.ty);
36}
37
38pub fn hash(tv: TypedValue, hasher: *std.hash.Wyhash) void {
39 return tv.val.hash(tv.ty, hasher);
40}
src/Zir.zig+12-4
...@@ -495,12 +495,15 @@ pub const Inst = struct {...@@ -495,12 +495,15 @@ pub const Inst = struct {
495 /// Uses the `ptr_type` union field.495 /// Uses the `ptr_type` union field.
496 ptr_type,496 ptr_type,
497 /// Slice operation `lhs[rhs..]`. No sentinel and no end offset.497 /// Slice operation `lhs[rhs..]`. No sentinel and no end offset.
498 /// Returns a pointer to the subslice.
498 /// Uses the `pl_node` field. AST node is the slice syntax. Payload is `SliceStart`.499 /// Uses the `pl_node` field. AST node is the slice syntax. Payload is `SliceStart`.
499 slice_start,500 slice_start,
500 /// Slice operation `array_ptr[start..end]`. No sentinel.501 /// Slice operation `array_ptr[start..end]`. No sentinel.
502 /// Returns a pointer to the subslice.
501 /// Uses the `pl_node` field. AST node is the slice syntax. Payload is `SliceEnd`.503 /// Uses the `pl_node` field. AST node is the slice syntax. Payload is `SliceEnd`.
502 slice_end,504 slice_end,
503 /// Slice operation `array_ptr[start..end:sentinel]`.505 /// Slice operation `array_ptr[start..end:sentinel]`.
506 /// Returns a pointer to the subslice.
504 /// Uses the `pl_node` field. AST node is the slice syntax. Payload is `SliceSentinel`.507 /// Uses the `pl_node` field. AST node is the slice syntax. Payload is `SliceSentinel`.
505 slice_sentinel,508 slice_sentinel,
506 /// Write a value to a pointer. For loading, see `load`.509 /// Write a value to a pointer. For loading, see `load`.
...@@ -687,14 +690,14 @@ pub const Inst = struct {...@@ -687,14 +690,14 @@ pub const Inst = struct {
687 /// A struct literal with a specified type, with no fields.690 /// A struct literal with a specified type, with no fields.
688 /// Uses the `un_node` field.691 /// Uses the `un_node` field.
689 struct_init_empty,692 struct_init_empty,
690 /// Given a struct, union, or enum, and a field name as a string index,693 /// Given a struct or union, and a field name as a string index,
691 /// returns the field type. Uses the `pl_node` field. Payload is `FieldType`.694 /// returns the field type. Uses the `pl_node` field. Payload is `FieldType`.
692 field_type,695 field_type,
693 /// Given a struct, union, or enum, and a field name as a Ref,696 /// Given a struct or union, and a field name as a Ref,
694 /// returns the field type. Uses the `pl_node` field. Payload is `FieldTypeRef`.697 /// returns the field type. Uses the `pl_node` field. Payload is `FieldTypeRef`.
695 field_type_ref,698 field_type_ref,
696 /// Finalizes a typed struct initialization, performs validation, and returns the699 /// Finalizes a typed struct or union initialization, performs validation, and returns the
697 /// struct value.700 /// struct or union value.
698 /// Uses the `pl_node` field. Payload is `StructInit`.701 /// Uses the `pl_node` field. Payload is `StructInit`.
699 struct_init,702 struct_init,
700 /// Struct initialization syntax, make the result a pointer.703 /// Struct initialization syntax, make the result a pointer.
...@@ -1703,6 +1706,7 @@ pub const Inst = struct {...@@ -1703,6 +1706,7 @@ pub const Inst = struct {
1703 call_options_type,1706 call_options_type,
1704 export_options_type,1707 export_options_type,
1705 extern_options_type,1708 extern_options_type,
1709 type_info_type,
1706 manyptr_u8_type,1710 manyptr_u8_type,
1707 manyptr_const_u8_type,1711 manyptr_const_u8_type,
1708 fn_noreturn_no_args_type,1712 fn_noreturn_no_args_type,
...@@ -1973,6 +1977,10 @@ pub const Inst = struct {...@@ -1973,6 +1977,10 @@ pub const Inst = struct {
1973 .ty = Type.initTag(.type),1977 .ty = Type.initTag(.type),
1974 .val = Value.initTag(.extern_options_type),1978 .val = Value.initTag(.extern_options_type),
1975 },1979 },
1980 .type_info_type = .{
1981 .ty = Type.initTag(.type),
1982 .val = Value.initTag(.type_info_type),
1983 },
19761984
1977 .undef = .{1985 .undef = .{
1978 .ty = Type.initTag(.@"undefined"),1986 .ty = Type.initTag(.@"undefined"),
src/codegen.zig+155-28
...@@ -822,6 +822,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -822,6 +822,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
822 .bit_and => try self.airBitAnd(inst),822 .bit_and => try self.airBitAnd(inst),
823 .bit_or => try self.airBitOr(inst),823 .bit_or => try self.airBitOr(inst),
824 .xor => try self.airXor(inst),824 .xor => try self.airXor(inst),
825 .shr => try self.airShr(inst),
826 .shl => try self.airShl(inst),
825827
826 .alloc => try self.airAlloc(inst),828 .alloc => try self.airAlloc(inst),
827 .arg => try self.airArg(inst),829 .arg => try self.airArg(inst),
...@@ -853,6 +855,12 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -853,6 +855,12 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
853 .store => try self.airStore(inst),855 .store => try self.airStore(inst),
854 .struct_field_ptr=> try self.airStructFieldPtr(inst),856 .struct_field_ptr=> try self.airStructFieldPtr(inst),
855 .struct_field_val=> try self.airStructFieldVal(inst),857 .struct_field_val=> try self.airStructFieldVal(inst),
858
859 .struct_field_ptr_index_0 => try self.airStructFieldPtrIndex(inst, 0),
860 .struct_field_ptr_index_1 => try self.airStructFieldPtrIndex(inst, 1),
861 .struct_field_ptr_index_2 => try self.airStructFieldPtrIndex(inst, 2),
862 .struct_field_ptr_index_3 => try self.airStructFieldPtrIndex(inst, 3),
863
856 .switch_br => try self.airSwitch(inst),864 .switch_br => try self.airSwitch(inst),
857 .slice_ptr => try self.airSlicePtr(inst),865 .slice_ptr => try self.airSlicePtr(inst),
858 .slice_len => try self.airSliceLen(inst),866 .slice_len => try self.airSliceLen(inst),
...@@ -860,6 +868,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -860,6 +868,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
860 .slice_elem_val => try self.airSliceElemVal(inst),868 .slice_elem_val => try self.airSliceElemVal(inst),
861 .ptr_slice_elem_val => try self.airPtrSliceElemVal(inst),869 .ptr_slice_elem_val => try self.airPtrSliceElemVal(inst),
862 .ptr_elem_val => try self.airPtrElemVal(inst),870 .ptr_elem_val => try self.airPtrElemVal(inst),
871 .ptr_elem_ptr => try self.airPtrElemPtr(inst),
863 .ptr_ptr_elem_val => try self.airPtrPtrElemVal(inst),872 .ptr_ptr_elem_val => try self.airPtrPtrElemVal(inst),
864873
865 .constant => unreachable, // excluded from function bodies874 .constant => unreachable, // excluded from function bodies
...@@ -970,6 +979,20 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -970,6 +979,20 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
970 log.debug("%{d} => {}", .{ inst, result });979 log.debug("%{d} => {}", .{ inst, result });
971 const branch = &self.branch_stack.items[self.branch_stack.items.len - 1];980 const branch = &self.branch_stack.items[self.branch_stack.items.len - 1];
972 branch.inst_table.putAssumeCapacityNoClobber(inst, result);981 branch.inst_table.putAssumeCapacityNoClobber(inst, result);
982
983 switch (result) {
984 .register => |reg| {
985 // In some cases (such as bitcast), an operand
986 // may be the same MCValue as the result. If
987 // that operand died and was a register, it
988 // was freed by processDeath. We have to
989 // "re-allocate" the register.
990 if (self.register_manager.isRegFree(reg)) {
991 self.register_manager.getRegAssumeFree(reg, inst);
992 }
993 },
994 else => {},
995 }
973 }996 }
974 self.finishAirBookkeeping();997 self.finishAirBookkeeping();
975 }998 }
...@@ -1272,6 +1295,24 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -1272,6 +1295,24 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
1272 return self.finishAir(inst, result, .{ bin_op.lhs, bin_op.rhs, .none });1295 return self.finishAir(inst, result, .{ bin_op.lhs, bin_op.rhs, .none });
1273 }1296 }
12741297
1298 fn airShl(self: *Self, inst: Air.Inst.Index) !void {
1299 const bin_op = self.air.instructions.items(.data)[inst].bin_op;
1300 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else switch (arch) {
1301 .arm, .armeb => try self.genArmBinOp(inst, bin_op.lhs, bin_op.rhs, .shl),
1302 else => return self.fail("TODO implement shl for {}", .{self.target.cpu.arch}),
1303 };
1304 return self.finishAir(inst, result, .{ bin_op.lhs, bin_op.rhs, .none });
1305 }
1306
1307 fn airShr(self: *Self, inst: Air.Inst.Index) !void {
1308 const bin_op = self.air.instructions.items(.data)[inst].bin_op;
1309 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else switch (arch) {
1310 .arm, .armeb => try self.genArmBinOp(inst, bin_op.lhs, bin_op.rhs, .shr),
1311 else => return self.fail("TODO implement shr for {}", .{self.target.cpu.arch}),
1312 };
1313 return self.finishAir(inst, result, .{ bin_op.lhs, bin_op.rhs, .none });
1314 }
1315
1275 fn airOptionalPayload(self: *Self, inst: Air.Inst.Index) !void {1316 fn airOptionalPayload(self: *Self, inst: Air.Inst.Index) !void {
1276 const ty_op = self.air.instructions.items(.data)[inst].ty_op;1317 const ty_op = self.air.instructions.items(.data)[inst].ty_op;
1277 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else switch (arch) {1318 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else switch (arch) {
...@@ -1399,6 +1440,15 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -1399,6 +1440,15 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
1399 return self.finishAir(inst, result, .{ bin_op.lhs, bin_op.rhs, .none });1440 return self.finishAir(inst, result, .{ bin_op.lhs, bin_op.rhs, .none });
1400 }1441 }
14011442
1443 fn airPtrElemPtr(self: *Self, inst: Air.Inst.Index) !void {
1444 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;
1445 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
1446 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else switch (arch) {
1447 else => return self.fail("TODO implement ptr_elem_ptr for {}", .{self.target.cpu.arch}),
1448 };
1449 return self.finishAir(inst, result, .{ extra.lhs, extra.rhs, .none });
1450 }
1451
1402 fn airPtrPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {1452 fn airPtrPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
1403 const is_volatile = false; // TODO1453 const is_volatile = false; // TODO
1404 const bin_op = self.air.instructions.items(.data)[inst].bin_op;1454 const bin_op = self.air.instructions.items(.data)[inst].bin_op;
...@@ -1439,7 +1489,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -1439,7 +1489,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
1439 return true;1489 return true;
1440 }1490 }
14411491
1442 fn load(self: *Self, dst_mcv: MCValue, ptr: MCValue, ptr_ty: Type) !void {1492 fn load(self: *Self, dst_mcv: MCValue, ptr: MCValue, ptr_ty: Type) InnerError!void {
1443 const elem_ty = ptr_ty.elemType();1493 const elem_ty = ptr_ty.elemType();
1444 switch (ptr) {1494 switch (ptr) {
1445 .none => unreachable,1495 .none => unreachable,
...@@ -1456,11 +1506,25 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -1456,11 +1506,25 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
1456 .embedded_in_code => {1506 .embedded_in_code => {
1457 return self.fail("TODO implement loading from MCValue.embedded_in_code", .{});1507 return self.fail("TODO implement loading from MCValue.embedded_in_code", .{});
1458 },1508 },
1459 .register => {1509 .register => |reg| {
1460 return self.fail("TODO implement loading from MCValue.register", .{});1510 switch (arch) {
1511 .arm, .armeb => switch (dst_mcv) {
1512 .dead => unreachable,
1513 .undef => unreachable,
1514 .compare_flags_signed, .compare_flags_unsigned => unreachable,
1515 .embedded_in_code => unreachable,
1516 .register => |dst_reg| {
1517 writeInt(u32, try self.code.addManyAsArray(4), Instruction.ldr(.al, dst_reg, reg, .{ .offset = Instruction.Offset.none }).toU32());
1518 },
1519 else => return self.fail("TODO load from register into {}", .{dst_mcv}),
1520 },
1521 else => return self.fail("TODO implement loading from MCValue.register for {}", .{arch}),
1522 }
1461 },1523 },
1462 .memory => {1524 .memory => |addr| {
1463 return self.fail("TODO implement loading from MCValue.memory", .{});1525 const reg = try self.register_manager.allocReg(null, &.{});
1526 try self.genSetReg(ptr_ty, reg, .{ .memory = addr });
1527 try self.load(dst_mcv, .{ .register = reg }, ptr_ty);
1464 },1528 },
1465 .stack_offset => {1529 .stack_offset => {
1466 return self.fail("TODO implement loading from MCValue.stack_offset", .{});1530 return self.fail("TODO implement loading from MCValue.stack_offset", .{});
...@@ -1534,7 +1598,18 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -1534,7 +1598,18 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
1534 fn airStructFieldPtr(self: *Self, inst: Air.Inst.Index) !void {1598 fn airStructFieldPtr(self: *Self, inst: Air.Inst.Index) !void {
1535 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;1599 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;
1536 const extra = self.air.extraData(Air.StructField, ty_pl.payload).data;1600 const extra = self.air.extraData(Air.StructField, ty_pl.payload).data;
1537 _ = extra;1601 return self.structFieldPtr(extra.struct_operand, ty_pl.ty, extra.field_index);
1602 }
1603
1604 fn airStructFieldPtrIndex(self: *Self, inst: Air.Inst.Index, index: u8) !void {
1605 const ty_op = self.air.instructions.items(.data)[inst].ty_op;
1606 return self.structFieldPtr(ty_op.operand, ty_op.ty, index);
1607 }
1608 fn structFieldPtr(self: *Self, operand: Air.Inst.Ref, ty: Air.Inst.Ref, index: u32) !void {
1609 _ = self;
1610 _ = operand;
1611 _ = ty;
1612 _ = index;
1538 return self.fail("TODO implement codegen struct_field_ptr", .{});1613 return self.fail("TODO implement codegen struct_field_ptr", .{});
1539 //return self.finishAir(inst, result, .{ extra.struct_ptr, .none, .none });1614 //return self.finishAir(inst, result, .{ extra.struct_ptr, .none, .none });
1540 }1615 }
...@@ -1572,15 +1647,53 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -1572,15 +1647,53 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
1572 }1647 }
15731648
1574 fn genArmBinOp(self: *Self, inst: Air.Inst.Index, op_lhs: Air.Inst.Ref, op_rhs: Air.Inst.Ref, op: Air.Inst.Tag) !MCValue {1649 fn genArmBinOp(self: *Self, inst: Air.Inst.Index, op_lhs: Air.Inst.Ref, op_rhs: Air.Inst.Ref, op: Air.Inst.Tag) !MCValue {
1650 // In the case of bitshifts, the type of rhs is different
1651 // from the resulting type
1652 const ty = self.air.typeOf(op_lhs);
1653
1654 switch (ty.zigTypeTag()) {
1655 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
1656 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
1657 .Bool => {
1658 return self.genArmBinIntOp(inst, op_lhs, op_rhs, op, 1, .unsigned);
1659 },
1660 .Int => {
1661 const int_info = ty.intInfo(self.target.*);
1662 return self.genArmBinIntOp(inst, op_lhs, op_rhs, op, int_info.bits, int_info.signedness);
1663 },
1664 else => unreachable,
1665 }
1666 }
1667
1668 fn genArmBinIntOp(
1669 self: *Self,
1670 inst: Air.Inst.Index,
1671 op_lhs: Air.Inst.Ref,
1672 op_rhs: Air.Inst.Ref,
1673 op: Air.Inst.Tag,
1674 bits: u16,
1675 signedness: std.builtin.Signedness,
1676 ) !MCValue {
1677 if (bits > 32) {
1678 return self.fail("TODO ARM binary operations on integers > u32/i32", .{});
1679 }
1680
1575 const lhs = try self.resolveInst(op_lhs);1681 const lhs = try self.resolveInst(op_lhs);
1576 const rhs = try self.resolveInst(op_rhs);1682 const rhs = try self.resolveInst(op_rhs);
15771683
1578 const lhs_is_register = lhs == .register;1684 const lhs_is_register = lhs == .register;
1579 const rhs_is_register = rhs == .register;1685 const rhs_is_register = rhs == .register;
1580 const lhs_should_be_register = try self.armOperandShouldBeRegister(lhs);1686 const lhs_should_be_register = switch (op) {
1687 .shr, .shl => true,
1688 else => try self.armOperandShouldBeRegister(lhs),
1689 };
1581 const rhs_should_be_register = try self.armOperandShouldBeRegister(rhs);1690 const rhs_should_be_register = try self.armOperandShouldBeRegister(rhs);
1582 const reuse_lhs = lhs_is_register and self.reuseOperand(inst, op_lhs, 0, lhs);1691 const reuse_lhs = lhs_is_register and self.reuseOperand(inst, op_lhs, 0, lhs);
1583 const reuse_rhs = !reuse_lhs and rhs_is_register and self.reuseOperand(inst, op_rhs, 1, rhs);1692 const reuse_rhs = !reuse_lhs and rhs_is_register and self.reuseOperand(inst, op_rhs, 1, rhs);
1693 const can_swap_lhs_and_rhs = switch (op) {
1694 .shr, .shl => false,
1695 else => true,
1696 };
15841697
1585 // Destination must be a register1698 // Destination must be a register
1586 var dst_mcv: MCValue = undefined;1699 var dst_mcv: MCValue = undefined;
...@@ -1597,7 +1710,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -1597,7 +1710,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
1597 branch.inst_table.putAssumeCapacity(Air.refToIndex(op_rhs).?, rhs_mcv);1710 branch.inst_table.putAssumeCapacity(Air.refToIndex(op_rhs).?, rhs_mcv);
1598 }1711 }
1599 dst_mcv = lhs;1712 dst_mcv = lhs;
1600 } else if (reuse_rhs) {1713 } else if (reuse_rhs and can_swap_lhs_and_rhs) {
1601 // Allocate 0 or 1 registers1714 // Allocate 0 or 1 registers
1602 if (!lhs_is_register and lhs_should_be_register) {1715 if (!lhs_is_register and lhs_should_be_register) {
1603 lhs_mcv = MCValue{ .register = try self.register_manager.allocReg(Air.refToIndex(op_lhs).?, &.{rhs.register}) };1716 lhs_mcv = MCValue{ .register = try self.register_manager.allocReg(Air.refToIndex(op_lhs).?, &.{rhs.register}) };
...@@ -1636,7 +1749,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -1636,7 +1749,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
1636 dst_mcv = MCValue{ .register = try self.register_manager.allocReg(inst, &.{}) };1749 dst_mcv = MCValue{ .register = try self.register_manager.allocReg(inst, &.{}) };
1637 lhs_mcv = dst_mcv;1750 lhs_mcv = dst_mcv;
1638 }1751 }
1639 } else if (rhs_should_be_register) {1752 } else if (rhs_should_be_register and can_swap_lhs_and_rhs) {
1640 // LHS is immediate1753 // LHS is immediate
1641 if (rhs_is_register) {1754 if (rhs_is_register) {
1642 dst_mcv = MCValue{ .register = try self.register_manager.allocReg(inst, &.{rhs.register}) };1755 dst_mcv = MCValue{ .register = try self.register_manager.allocReg(inst, &.{rhs.register}) };
...@@ -1663,6 +1776,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -1663,6 +1776,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
1663 rhs_mcv,1776 rhs_mcv,
1664 swap_lhs_and_rhs,1777 swap_lhs_and_rhs,
1665 op,1778 op,
1779 signedness,
1666 );1780 );
1667 return dst_mcv;1781 return dst_mcv;
1668 }1782 }
...@@ -1674,6 +1788,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -1674,6 +1788,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
1674 rhs_mcv: MCValue,1788 rhs_mcv: MCValue,
1675 swap_lhs_and_rhs: bool,1789 swap_lhs_and_rhs: bool,
1676 op: Air.Inst.Tag,1790 op: Air.Inst.Tag,
1791 signedness: std.builtin.Signedness,
1677 ) !void {1792 ) !void {
1678 assert(lhs_mcv == .register or rhs_mcv == .register);1793 assert(lhs_mcv == .register or rhs_mcv == .register);
16791794
...@@ -1719,6 +1834,27 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -1719,6 +1834,27 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
1719 .cmp_eq => {1834 .cmp_eq => {
1720 writeInt(u32, try self.code.addManyAsArray(4), Instruction.cmp(.al, op1, operand).toU32());1835 writeInt(u32, try self.code.addManyAsArray(4), Instruction.cmp(.al, op1, operand).toU32());
1721 },1836 },
1837 .shl => {
1838 assert(!swap_lhs_and_rhs);
1839 const shift_amout = switch (operand) {
1840 .Register => |reg_op| Instruction.ShiftAmount.reg(@intToEnum(Register, reg_op.rm)),
1841 .Immediate => |imm_op| Instruction.ShiftAmount.imm(@intCast(u5, imm_op.imm)),
1842 };
1843 writeInt(u32, try self.code.addManyAsArray(4), Instruction.lsl(.al, dst_reg, op1, shift_amout).toU32());
1844 },
1845 .shr => {
1846 assert(!swap_lhs_and_rhs);
1847 const shift_amout = switch (operand) {
1848 .Register => |reg_op| Instruction.ShiftAmount.reg(@intToEnum(Register, reg_op.rm)),
1849 .Immediate => |imm_op| Instruction.ShiftAmount.imm(@intCast(u5, imm_op.imm)),
1850 };
1851
1852 const shr = switch (signedness) {
1853 .signed => Instruction.asr,
1854 .unsigned => Instruction.lsr,
1855 };
1856 writeInt(u32, try self.code.addManyAsArray(4), shr(.al, dst_reg, op1, shift_amout).toU32());
1857 },
1722 else => unreachable, // not a binary instruction1858 else => unreachable, // not a binary instruction
1723 }1859 }
1724 }1860 }
...@@ -2969,7 +3105,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -2969,7 +3105,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
2969 }3105 }
29703106
2971 // The destination register is not present in the cmp instruction3107 // The destination register is not present in the cmp instruction
2972 try self.genArmBinOpCode(undefined, lhs_mcv, rhs_mcv, false, .cmp_eq);3108 // The signedness of the integer does not matter for the cmp instruction
3109 try self.genArmBinOpCode(undefined, lhs_mcv, rhs_mcv, false, .cmp_eq, undefined);
29733110
2974 break :result switch (ty.isSignedInt()) {3111 break :result switch (ty.isSignedInt()) {
2975 true => MCValue{ .compare_flags_signed = op },3112 true => MCValue{ .compare_flags_signed = op },
...@@ -3792,15 +3929,10 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -3792,15 +3929,10 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
3792 else => return self.fail("TODO implement memset", .{}),3929 else => return self.fail("TODO implement memset", .{}),
3793 }3930 }
3794 },3931 },
3795 .compare_flags_unsigned => |op| {3932 .compare_flags_unsigned,
3796 _ = op;3933 .compare_flags_signed,
3797 return self.fail("TODO implement set stack variable with compare flags value (unsigned)", .{});3934 .immediate,
3798 },3935 => {
3799 .compare_flags_signed => |op| {
3800 _ = op;
3801 return self.fail("TODO implement set stack variable with compare flags value (signed)", .{});
3802 },
3803 .immediate => {
3804 const reg = try self.copyToTmpRegister(ty, mcv);3936 const reg = try self.copyToTmpRegister(ty, mcv);
3805 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });3937 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
3806 },3938 },
...@@ -3968,15 +4100,10 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {...@@ -3968,15 +4100,10 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
3968 else => return self.fail("TODO implement memset", .{}),4100 else => return self.fail("TODO implement memset", .{}),
3969 }4101 }
3970 },4102 },
3971 .compare_flags_unsigned => |op| {4103 .compare_flags_unsigned,
3972 _ = op;4104 .compare_flags_signed,
3973 return self.fail("TODO implement set stack variable with compare flags value (unsigned)", .{});4105 .immediate,
3974 },4106 => {
3975 .compare_flags_signed => |op| {
3976 _ = op;
3977 return self.fail("TODO implement set stack variable with compare flags value (signed)", .{});
3978 },
3979 .immediate => {
3980 const reg = try self.copyToTmpRegister(ty, mcv);4107 const reg = try self.copyToTmpRegister(ty, mcv);
3981 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });4108 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
3982 },4109 },
src/codegen/arm.zig+172-34
...@@ -192,7 +192,7 @@ pub const c_abi_int_return_regs = [_]Register{ .r0, .r1 };...@@ -192,7 +192,7 @@ pub const c_abi_int_return_regs = [_]Register{ .r0, .r1 };
192192
193/// Represents an instruction in the ARM instruction set architecture193/// Represents an instruction in the ARM instruction set architecture
194pub const Instruction = union(enum) {194pub const Instruction = union(enum) {
195 DataProcessing: packed struct {195 data_processing: packed struct {
196 // Note to self: The order of the fields top-to-bottom is196 // Note to self: The order of the fields top-to-bottom is
197 // right-to-left in the actual 32-bit int representation197 // right-to-left in the actual 32-bit int representation
198 op2: u12,198 op2: u12,
...@@ -204,7 +204,7 @@ pub const Instruction = union(enum) {...@@ -204,7 +204,7 @@ pub const Instruction = union(enum) {
204 fixed: u2 = 0b00,204 fixed: u2 = 0b00,
205 cond: u4,205 cond: u4,
206 },206 },
207 Multiply: packed struct {207 multiply: packed struct {
208 rn: u4,208 rn: u4,
209 fixed_1: u4 = 0b1001,209 fixed_1: u4 = 0b1001,
210 rm: u4,210 rm: u4,
...@@ -215,7 +215,7 @@ pub const Instruction = union(enum) {...@@ -215,7 +215,7 @@ pub const Instruction = union(enum) {
215 fixed_2: u6 = 0b000000,215 fixed_2: u6 = 0b000000,
216 cond: u4,216 cond: u4,
217 },217 },
218 MultiplyLong: packed struct {218 multiply_long: packed struct {
219 rn: u4,219 rn: u4,
220 fixed_1: u4 = 0b1001,220 fixed_1: u4 = 0b1001,
221 rm: u4,221 rm: u4,
...@@ -227,7 +227,17 @@ pub const Instruction = union(enum) {...@@ -227,7 +227,17 @@ pub const Instruction = union(enum) {
227 fixed_2: u5 = 0b00001,227 fixed_2: u5 = 0b00001,
228 cond: u4,228 cond: u4,
229 },229 },
230 SingleDataTransfer: packed struct {230 integer_saturating_arithmetic: packed struct {
231 rm: u4,
232 fixed_1: u8 = 0b0000_0101,
233 rd: u4,
234 rn: u4,
235 fixed_2: u1 = 0b0,
236 opc: u2,
237 fixed_3: u5 = 0b00010,
238 cond: u4,
239 },
240 single_data_transfer: packed struct {
231 offset: u12,241 offset: u12,
232 rd: u4,242 rd: u4,
233 rn: u4,243 rn: u4,
...@@ -240,7 +250,7 @@ pub const Instruction = union(enum) {...@@ -240,7 +250,7 @@ pub const Instruction = union(enum) {
240 fixed: u2 = 0b01,250 fixed: u2 = 0b01,
241 cond: u4,251 cond: u4,
242 },252 },
243 ExtraLoadStore: packed struct {253 extra_load_store: packed struct {
244 imm4l: u4,254 imm4l: u4,
245 fixed_1: u1 = 0b1,255 fixed_1: u1 = 0b1,
246 op2: u2,256 op2: u2,
...@@ -256,7 +266,7 @@ pub const Instruction = union(enum) {...@@ -256,7 +266,7 @@ pub const Instruction = union(enum) {
256 fixed_3: u3 = 0b000,266 fixed_3: u3 = 0b000,
257 cond: u4,267 cond: u4,
258 },268 },
259 BlockDataTransfer: packed struct {269 block_data_transfer: packed struct {
260 register_list: u16,270 register_list: u16,
261 rn: u4,271 rn: u4,
262 load_store: u1,272 load_store: u1,
...@@ -267,25 +277,25 @@ pub const Instruction = union(enum) {...@@ -267,25 +277,25 @@ pub const Instruction = union(enum) {
267 fixed: u3 = 0b100,277 fixed: u3 = 0b100,
268 cond: u4,278 cond: u4,
269 },279 },
270 Branch: packed struct {280 branch: packed struct {
271 offset: u24,281 offset: u24,
272 link: u1,282 link: u1,
273 fixed: u3 = 0b101,283 fixed: u3 = 0b101,
274 cond: u4,284 cond: u4,
275 },285 },
276 BranchExchange: packed struct {286 branch_exchange: packed struct {
277 rn: u4,287 rn: u4,
278 fixed_1: u1 = 0b1,288 fixed_1: u1 = 0b1,
279 link: u1,289 link: u1,
280 fixed_2: u22 = 0b0001_0010_1111_1111_1111_00,290 fixed_2: u22 = 0b0001_0010_1111_1111_1111_00,
281 cond: u4,291 cond: u4,
282 },292 },
283 SupervisorCall: packed struct {293 supervisor_call: packed struct {
284 comment: u24,294 comment: u24,
285 fixed: u4 = 0b1111,295 fixed: u4 = 0b1111,
286 cond: u4,296 cond: u4,
287 },297 },
288 Breakpoint: packed struct {298 breakpoint: packed struct {
289 imm4: u4,299 imm4: u4,
290 fixed_1: u4 = 0b0111,300 fixed_1: u4 = 0b0111,
291 imm12: u12,301 imm12: u12,
...@@ -293,7 +303,7 @@ pub const Instruction = union(enum) {...@@ -293,7 +303,7 @@ pub const Instruction = union(enum) {
293 },303 },
294304
295 /// Represents the possible operations which can be performed by a305 /// Represents the possible operations which can be performed by a
296 /// DataProcessing instruction306 /// Data Processing instruction
297 const Opcode = enum(u4) {307 const Opcode = enum(u4) {
298 // Rd := Op1 AND Op2308 // Rd := Op1 AND Op2
299 @"and",309 @"and",
...@@ -530,16 +540,17 @@ pub const Instruction = union(enum) {...@@ -530,16 +540,17 @@ pub const Instruction = union(enum) {
530540
531 pub fn toU32(self: Instruction) u32 {541 pub fn toU32(self: Instruction) u32 {
532 return switch (self) {542 return switch (self) {
533 .DataProcessing => |v| @bitCast(u32, v),543 .data_processing => |v| @bitCast(u32, v),
534 .Multiply => |v| @bitCast(u32, v),544 .multiply => |v| @bitCast(u32, v),
535 .MultiplyLong => |v| @bitCast(u32, v),545 .multiply_long => |v| @bitCast(u32, v),
536 .SingleDataTransfer => |v| @bitCast(u32, v),546 .integer_saturating_arithmetic => |v| @bitCast(u32, v),
537 .ExtraLoadStore => |v| @bitCast(u32, v),547 .single_data_transfer => |v| @bitCast(u32, v),
538 .BlockDataTransfer => |v| @bitCast(u32, v),548 .extra_load_store => |v| @bitCast(u32, v),
539 .Branch => |v| @bitCast(u32, v),549 .block_data_transfer => |v| @bitCast(u32, v),
540 .BranchExchange => |v| @bitCast(u32, v),550 .branch => |v| @bitCast(u32, v),
541 .SupervisorCall => |v| @bitCast(u32, v),551 .branch_exchange => |v| @bitCast(u32, v),
542 .Breakpoint => |v| @intCast(u32, v.imm4) | (@intCast(u32, v.fixed_1) << 4) | (@intCast(u32, v.imm12) << 8) | (@intCast(u32, v.fixed_2_and_cond) << 20),552 .supervisor_call => |v| @bitCast(u32, v),
553 .breakpoint => |v| @intCast(u32, v.imm4) | (@intCast(u32, v.fixed_1) << 4) | (@intCast(u32, v.imm12) << 8) | (@intCast(u32, v.fixed_2_and_cond) << 20),
543 };554 };
544 }555 }
545556
...@@ -554,7 +565,7 @@ pub const Instruction = union(enum) {...@@ -554,7 +565,7 @@ pub const Instruction = union(enum) {
554 op2: Operand,565 op2: Operand,
555 ) Instruction {566 ) Instruction {
556 return Instruction{567 return Instruction{
557 .DataProcessing = .{568 .data_processing = .{
558 .cond = @enumToInt(cond),569 .cond = @enumToInt(cond),
559 .i = @boolToInt(op2 == .Immediate),570 .i = @boolToInt(op2 == .Immediate),
560 .opcode = @enumToInt(opcode),571 .opcode = @enumToInt(opcode),
...@@ -573,7 +584,7 @@ pub const Instruction = union(enum) {...@@ -573,7 +584,7 @@ pub const Instruction = union(enum) {
573 top: bool,584 top: bool,
574 ) Instruction {585 ) Instruction {
575 return Instruction{586 return Instruction{
576 .DataProcessing = .{587 .data_processing = .{
577 .cond = @enumToInt(cond),588 .cond = @enumToInt(cond),
578 .i = 1,589 .i = 1,
579 .opcode = if (top) 0b1010 else 0b1000,590 .opcode = if (top) 0b1010 else 0b1000,
...@@ -594,7 +605,7 @@ pub const Instruction = union(enum) {...@@ -594,7 +605,7 @@ pub const Instruction = union(enum) {
594 ra: ?Register,605 ra: ?Register,
595 ) Instruction {606 ) Instruction {
596 return Instruction{607 return Instruction{
597 .Multiply = .{608 .multiply = .{
598 .cond = @enumToInt(cond),609 .cond = @enumToInt(cond),
599 .accumulate = @boolToInt(ra != null),610 .accumulate = @boolToInt(ra != null),
600 .set_cond = set_cond,611 .set_cond = set_cond,
...@@ -617,7 +628,7 @@ pub const Instruction = union(enum) {...@@ -617,7 +628,7 @@ pub const Instruction = union(enum) {
617 rn: Register,628 rn: Register,
618 ) Instruction {629 ) Instruction {
619 return Instruction{630 return Instruction{
620 .MultiplyLong = .{631 .multiply_long = .{
621 .cond = @enumToInt(cond),632 .cond = @enumToInt(cond),
622 .unsigned = signed,633 .unsigned = signed,
623 .accumulate = accumulate,634 .accumulate = accumulate,
...@@ -630,6 +641,24 @@ pub const Instruction = union(enum) {...@@ -630,6 +641,24 @@ pub const Instruction = union(enum) {
630 };641 };
631 }642 }
632643
644 fn integerSaturationArithmetic(
645 cond: Condition,
646 rd: Register,
647 rm: Register,
648 rn: Register,
649 opc: u2,
650 ) Instruction {
651 return Instruction{
652 .integer_saturating_arithmetic = .{
653 .rm = rm.id(),
654 .rd = rd.id(),
655 .rn = rn.id(),
656 .opc = opc,
657 .cond = @enumToInt(cond),
658 },
659 };
660 }
661
633 fn singleDataTransfer(662 fn singleDataTransfer(
634 cond: Condition,663 cond: Condition,
635 rd: Register,664 rd: Register,
...@@ -642,7 +671,7 @@ pub const Instruction = union(enum) {...@@ -642,7 +671,7 @@ pub const Instruction = union(enum) {
642 load_store: u1,671 load_store: u1,
643 ) Instruction {672 ) Instruction {
644 return Instruction{673 return Instruction{
645 .SingleDataTransfer = .{674 .single_data_transfer = .{
646 .cond = @enumToInt(cond),675 .cond = @enumToInt(cond),
647 .rn = rn.id(),676 .rn = rn.id(),
648 .rd = rd.id(),677 .rd = rd.id(),
...@@ -678,7 +707,7 @@ pub const Instruction = union(enum) {...@@ -678,7 +707,7 @@ pub const Instruction = union(enum) {
678 };707 };
679708
680 return Instruction{709 return Instruction{
681 .ExtraLoadStore = .{710 .extra_load_store = .{
682 .imm4l = imm4l,711 .imm4l = imm4l,
683 .op2 = op2,712 .op2 = op2,
684 .imm4h = imm4h,713 .imm4h = imm4h,
...@@ -705,7 +734,7 @@ pub const Instruction = union(enum) {...@@ -705,7 +734,7 @@ pub const Instruction = union(enum) {
705 load_store: u1,734 load_store: u1,
706 ) Instruction {735 ) Instruction {
707 return Instruction{736 return Instruction{
708 .BlockDataTransfer = .{737 .block_data_transfer = .{
709 .register_list = @bitCast(u16, reg_list),738 .register_list = @bitCast(u16, reg_list),
710 .rn = rn.id(),739 .rn = rn.id(),
711 .load_store = load_store,740 .load_store = load_store,
...@@ -720,7 +749,7 @@ pub const Instruction = union(enum) {...@@ -720,7 +749,7 @@ pub const Instruction = union(enum) {
720749
721 fn branch(cond: Condition, offset: i26, link: u1) Instruction {750 fn branch(cond: Condition, offset: i26, link: u1) Instruction {
722 return Instruction{751 return Instruction{
723 .Branch = .{752 .branch = .{
724 .cond = @enumToInt(cond),753 .cond = @enumToInt(cond),
725 .link = link,754 .link = link,
726 .offset = @bitCast(u24, @intCast(i24, offset >> 2)),755 .offset = @bitCast(u24, @intCast(i24, offset >> 2)),
...@@ -730,7 +759,7 @@ pub const Instruction = union(enum) {...@@ -730,7 +759,7 @@ pub const Instruction = union(enum) {
730759
731 fn branchExchange(cond: Condition, rn: Register, link: u1) Instruction {760 fn branchExchange(cond: Condition, rn: Register, link: u1) Instruction {
732 return Instruction{761 return Instruction{
733 .BranchExchange = .{762 .branch_exchange = .{
734 .cond = @enumToInt(cond),763 .cond = @enumToInt(cond),
735 .link = link,764 .link = link,
736 .rn = rn.id(),765 .rn = rn.id(),
...@@ -740,7 +769,7 @@ pub const Instruction = union(enum) {...@@ -740,7 +769,7 @@ pub const Instruction = union(enum) {
740769
741 fn supervisorCall(cond: Condition, comment: u24) Instruction {770 fn supervisorCall(cond: Condition, comment: u24) Instruction {
742 return Instruction{771 return Instruction{
743 .SupervisorCall = .{772 .supervisor_call = .{
744 .cond = @enumToInt(cond),773 .cond = @enumToInt(cond),
745 .comment = comment,774 .comment = comment,
746 },775 },
...@@ -749,7 +778,7 @@ pub const Instruction = union(enum) {...@@ -749,7 +778,7 @@ pub const Instruction = union(enum) {
749778
750 fn breakpoint(imm: u16) Instruction {779 fn breakpoint(imm: u16) Instruction {
751 return Instruction{780 return Instruction{
752 .Breakpoint = .{781 .breakpoint = .{
753 .imm12 = @truncate(u12, imm >> 4),782 .imm12 = @truncate(u12, imm >> 4),
754 .imm4 = @truncate(u4, imm),783 .imm4 = @truncate(u4, imm),
755 },784 },
...@@ -873,6 +902,24 @@ pub const Instruction = union(enum) {...@@ -873,6 +902,24 @@ pub const Instruction = union(enum) {
873 return dataProcessing(cond, .mvn, 1, rd, .r0, op2);902 return dataProcessing(cond, .mvn, 1, rd, .r0, op2);
874 }903 }
875904
905 // Integer Saturating Arithmetic
906
907 pub fn qadd(cond: Condition, rd: Register, rm: Register, rn: Register) Instruction {
908 return integerSaturationArithmetic(cond, rd, rm, rn, 0b00);
909 }
910
911 pub fn qsub(cond: Condition, rd: Register, rm: Register, rn: Register) Instruction {
912 return integerSaturationArithmetic(cond, rd, rm, rn, 0b01);
913 }
914
915 pub fn qdadd(cond: Condition, rd: Register, rm: Register, rn: Register) Instruction {
916 return integerSaturationArithmetic(cond, rd, rm, rn, 0b10);
917 }
918
919 pub fn qdsub(cond: Condition, rd: Register, rm: Register, rn: Register) Instruction {
920 return integerSaturationArithmetic(cond, rd, rm, rn, 0b11);
921 }
922
876 // movw and movt923 // movw and movt
877924
878 pub fn movw(cond: Condition, rd: Register, imm: u16) Instruction {925 pub fn movw(cond: Condition, rd: Register, imm: u16) Instruction {
...@@ -887,7 +934,7 @@ pub const Instruction = union(enum) {...@@ -887,7 +934,7 @@ pub const Instruction = union(enum) {
887934
888 pub fn mrs(cond: Condition, rd: Register, psr: Psr) Instruction {935 pub fn mrs(cond: Condition, rd: Register, psr: Psr) Instruction {
889 return Instruction{936 return Instruction{
890 .DataProcessing = .{937 .data_processing = .{
891 .cond = @enumToInt(cond),938 .cond = @enumToInt(cond),
892 .i = 0,939 .i = 0,
893 .opcode = if (psr == .spsr) 0b1010 else 0b1000,940 .opcode = if (psr == .spsr) 0b1010 else 0b1000,
...@@ -901,7 +948,7 @@ pub const Instruction = union(enum) {...@@ -901,7 +948,7 @@ pub const Instruction = union(enum) {
901948
902 pub fn msr(cond: Condition, psr: Psr, op: Operand) Instruction {949 pub fn msr(cond: Condition, psr: Psr, op: Operand) Instruction {
903 return Instruction{950 return Instruction{
904 .DataProcessing = .{951 .data_processing = .{
905 .cond = @enumToInt(cond),952 .cond = @enumToInt(cond),
906 .i = 0,953 .i = 0,
907 .opcode = if (psr == .spsr) 0b1011 else 0b1001,954 .opcode = if (psr == .spsr) 0b1011 else 0b1001,
...@@ -1142,6 +1189,79 @@ pub const Instruction = union(enum) {...@@ -1142,6 +1189,79 @@ pub const Instruction = union(enum) {
1142 return stmdb(cond, .sp, true, @bitCast(RegisterList, register_list));1189 return stmdb(cond, .sp, true, @bitCast(RegisterList, register_list));
1143 }1190 }
1144 }1191 }
1192
1193 pub const ShiftAmount = union(enum) {
1194 immediate: u5,
1195 register: Register,
1196
1197 pub fn imm(immediate: u5) ShiftAmount {
1198 return .{
1199 .immediate = immediate,
1200 };
1201 }
1202
1203 pub fn reg(register: Register) ShiftAmount {
1204 return .{
1205 .register = register,
1206 };
1207 }
1208 };
1209
1210 pub fn lsl(cond: Condition, rd: Register, rm: Register, shift: ShiftAmount) Instruction {
1211 return switch (shift) {
1212 .immediate => |imm| mov(cond, rd, Operand.reg(rm, Operand.Shift.imm(imm, .logical_left))),
1213 .register => |reg| mov(cond, rd, Operand.reg(rm, Operand.Shift.reg(reg, .logical_left))),
1214 };
1215 }
1216
1217 pub fn lsr(cond: Condition, rd: Register, rm: Register, shift: ShiftAmount) Instruction {
1218 return switch (shift) {
1219 .immediate => |imm| mov(cond, rd, Operand.reg(rm, Operand.Shift.imm(imm, .logical_right))),
1220 .register => |reg| mov(cond, rd, Operand.reg(rm, Operand.Shift.reg(reg, .logical_right))),
1221 };
1222 }
1223
1224 pub fn asr(cond: Condition, rd: Register, rm: Register, shift: ShiftAmount) Instruction {
1225 return switch (shift) {
1226 .immediate => |imm| mov(cond, rd, Operand.reg(rm, Operand.Shift.imm(imm, .arithmetic_right))),
1227 .register => |reg| mov(cond, rd, Operand.reg(rm, Operand.Shift.reg(reg, .arithmetic_right))),
1228 };
1229 }
1230
1231 pub fn ror(cond: Condition, rd: Register, rm: Register, shift: ShiftAmount) Instruction {
1232 return switch (shift) {
1233 .immediate => |imm| mov(cond, rd, Operand.reg(rm, Operand.Shift.imm(imm, .rotate_right))),
1234 .register => |reg| mov(cond, rd, Operand.reg(rm, Operand.Shift.reg(reg, .rotate_right))),
1235 };
1236 }
1237
1238 pub fn lsls(cond: Condition, rd: Register, rm: Register, shift: ShiftAmount) Instruction {
1239 return switch (shift) {
1240 .immediate => |imm| movs(cond, rd, Operand.reg(rm, Operand.Shift.imm(imm, .logical_left))),
1241 .register => |reg| movs(cond, rd, Operand.reg(rm, Operand.Shift.reg(reg, .logical_left))),
1242 };
1243 }
1244
1245 pub fn lsrs(cond: Condition, rd: Register, rm: Register, shift: ShiftAmount) Instruction {
1246 return switch (shift) {
1247 .immediate => |imm| movs(cond, rd, Operand.reg(rm, Operand.Shift.imm(imm, .logical_right))),
1248 .register => |reg| movs(cond, rd, Operand.reg(rm, Operand.Shift.reg(reg, .logical_right))),
1249 };
1250 }
1251
1252 pub fn asrs(cond: Condition, rd: Register, rm: Register, shift: ShiftAmount) Instruction {
1253 return switch (shift) {
1254 .immediate => |imm| movs(cond, rd, Operand.reg(rm, Operand.Shift.imm(imm, .arithmetic_right))),
1255 .register => |reg| movs(cond, rd, Operand.reg(rm, Operand.Shift.reg(reg, .arithmetic_right))),
1256 };
1257 }
1258
1259 pub fn rors(cond: Condition, rd: Register, rm: Register, shift: ShiftAmount) Instruction {
1260 return switch (shift) {
1261 .immediate => |imm| movs(cond, rd, Operand.reg(rm, Operand.Shift.imm(imm, .rotate_right))),
1262 .register => |reg| movs(cond, rd, Operand.reg(rm, Operand.Shift.reg(reg, .rotate_right))),
1263 };
1264 }
1145};1265};
11461266
1147test "serialize instructions" {1267test "serialize instructions" {
...@@ -1221,6 +1341,10 @@ test "serialize instructions" {...@@ -1221,6 +1341,10 @@ test "serialize instructions" {
1221 .inst = Instruction.ldmea(.al, .r4, true, .{ .r2 = true, .r5 = true }),1341 .inst = Instruction.ldmea(.al, .r4, true, .{ .r2 = true, .r5 = true }),
1222 .expected = 0b1110_100_1_0_0_1_1_0100_0000000000100100,1342 .expected = 0b1110_100_1_0_0_1_1_0100_0000000000100100,
1223 },1343 },
1344 .{ // qadd r0, r7, r8
1345 .inst = Instruction.qadd(.al, .r0, .r7, .r8),
1346 .expected = 0b1110_00010_00_0_1000_0000_0000_0101_0111,
1347 },
1224 };1348 };
12251349
1226 for (testcases) |case| {1350 for (testcases) |case| {
...@@ -1262,6 +1386,20 @@ test "aliases" {...@@ -1262,6 +1386,20 @@ test "aliases" {
1262 .actual = Instruction.push(.al, .{ .r0, .r2 }),1386 .actual = Instruction.push(.al, .{ .r0, .r2 }),
1263 .expected = Instruction.stmdb(.al, .sp, true, .{ .r0 = true, .r2 = true }),1387 .expected = Instruction.stmdb(.al, .sp, true, .{ .r0 = true, .r2 = true }),
1264 },1388 },
1389 .{ // lsl r4, r5, #5
1390 .actual = Instruction.lsl(.al, .r4, .r5, Instruction.ShiftAmount.imm(5)),
1391 .expected = Instruction.mov(.al, .r4, Instruction.Operand.reg(
1392 .r5,
1393 Instruction.Operand.Shift.imm(5, .logical_left),
1394 )),
1395 },
1396 .{ // asrs r1, r1, r3
1397 .actual = Instruction.asrs(.al, .r1, .r1, Instruction.ShiftAmount.reg(.r3)),
1398 .expected = Instruction.movs(.al, .r1, Instruction.Operand.reg(
1399 .r1,
1400 Instruction.Operand.Shift.reg(.r3, .arithmetic_right),
1401 )),
1402 },
1265 };1403 };
12661404
1267 for (testcases) |case| {1405 for (testcases) |case| {
src/codegen/c.zig+45-10
...@@ -319,18 +319,20 @@ pub const DeclGen = struct {...@@ -319,18 +319,20 @@ pub const DeclGen = struct {
319 .Bool => return writer.print("{}", .{val.toBool()}),319 .Bool => return writer.print("{}", .{val.toBool()}),
320 .Optional => {320 .Optional => {
321 var opt_buf: Type.Payload.ElemType = undefined;321 var opt_buf: Type.Payload.ElemType = undefined;
322 const child_type = t.optionalChild(&opt_buf);322 const payload_type = t.optionalChild(&opt_buf);
323 if (t.isPtrLikeOptional()) {323 if (t.isPtrLikeOptional()) {
324 return dg.renderValue(writer, child_type, val);324 return dg.renderValue(writer, payload_type, val);
325 }325 }
326 try writer.writeByte('(');326 try writer.writeByte('(');
327 try dg.renderType(writer, t);327 try dg.renderType(writer, t);
328 if (val.tag() == .null_value) {328 try writer.writeAll("){");
329 try writer.writeAll("){ .is_null = true }");329 if (val.castTag(.opt_payload)) |pl| {
330 } else {330 const payload_val = pl.data;
331 try writer.writeAll("){ .is_null = false, .payload = ");331 try writer.writeAll(" .is_null = false, .payload = ");
332 try dg.renderValue(writer, child_type, val);332 try dg.renderValue(writer, payload_type, payload_val);
333 try writer.writeAll(" }");333 try writer.writeAll(" }");
334 } else {
335 try writer.writeAll(" .is_null = true }");
334 }336 }
335 },337 },
336 .ErrorSet => {338 .ErrorSet => {
...@@ -871,6 +873,9 @@ fn genBody(o: *Object, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfM...@@ -871,6 +873,9 @@ fn genBody(o: *Object, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfM
871 .bit_or => try airBinOp(o, inst, " | "),873 .bit_or => try airBinOp(o, inst, " | "),
872 .xor => try airBinOp(o, inst, " ^ "),874 .xor => try airBinOp(o, inst, " ^ "),
873875
876 .shr => try airBinOp(o, inst, " >> "),
877 .shl => try airBinOp(o, inst, " << "),
878
874 .not => try airNot( o, inst),879 .not => try airNot( o, inst),
875880
876 .optional_payload => try airOptionalPayload(o, inst),881 .optional_payload => try airOptionalPayload(o, inst),
...@@ -904,12 +909,19 @@ fn genBody(o: *Object, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfM...@@ -904,12 +909,19 @@ fn genBody(o: *Object, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfM
904 .switch_br => try airSwitchBr(o, inst),909 .switch_br => try airSwitchBr(o, inst),
905 .wrap_optional => try airWrapOptional(o, inst),910 .wrap_optional => try airWrapOptional(o, inst),
906 .struct_field_ptr => try airStructFieldPtr(o, inst),911 .struct_field_ptr => try airStructFieldPtr(o, inst),
912
913 .struct_field_ptr_index_0 => try airStructFieldPtrIndex(o, inst, 0),
914 .struct_field_ptr_index_1 => try airStructFieldPtrIndex(o, inst, 1),
915 .struct_field_ptr_index_2 => try airStructFieldPtrIndex(o, inst, 2),
916 .struct_field_ptr_index_3 => try airStructFieldPtrIndex(o, inst, 3),
917
907 .struct_field_val => try airStructFieldVal(o, inst),918 .struct_field_val => try airStructFieldVal(o, inst),
908 .slice_ptr => try airSliceField(o, inst, ".ptr;\n"),919 .slice_ptr => try airSliceField(o, inst, ".ptr;\n"),
909 .slice_len => try airSliceField(o, inst, ".len;\n"),920 .slice_len => try airSliceField(o, inst, ".len;\n"),
910921
911 .ptr_elem_val => try airPtrElemVal(o, inst, "["),922 .ptr_elem_val => try airPtrElemVal(o, inst, "["),
912 .ptr_ptr_elem_val => try airPtrElemVal(o, inst, "[0]["),923 .ptr_ptr_elem_val => try airPtrElemVal(o, inst, "[0]["),
924 .ptr_elem_ptr => try airPtrElemPtr(o, inst),
913 .slice_elem_val => try airSliceElemVal(o, inst, "["),925 .slice_elem_val => try airSliceElemVal(o, inst, "["),
914 .ptr_slice_elem_val => try airSliceElemVal(o, inst, "[0]["),926 .ptr_slice_elem_val => try airSliceElemVal(o, inst, "[0]["),
915927
...@@ -957,6 +969,13 @@ fn airPtrElemVal(o: *Object, inst: Air.Inst.Index, prefix: []const u8) !CValue {...@@ -957,6 +969,13 @@ fn airPtrElemVal(o: *Object, inst: Air.Inst.Index, prefix: []const u8) !CValue {
957 return o.dg.fail("TODO: C backend: airPtrElemVal", .{});969 return o.dg.fail("TODO: C backend: airPtrElemVal", .{});
958}970}
959971
972fn airPtrElemPtr(o: *Object, inst: Air.Inst.Index) !CValue {
973 if (o.liveness.isUnused(inst))
974 return CValue.none;
975
976 return o.dg.fail("TODO: C backend: airPtrElemPtr", .{});
977}
978
960fn airSliceElemVal(o: *Object, inst: Air.Inst.Index, prefix: []const u8) !CValue {979fn airSliceElemVal(o: *Object, inst: Air.Inst.Index, prefix: []const u8) !CValue {
961 const is_volatile = false; // TODO980 const is_volatile = false; // TODO
962 if (!is_volatile and o.liveness.isUnused(inst))981 if (!is_volatile and o.liveness.isUnused(inst))
...@@ -1638,15 +1657,31 @@ fn airOptionalPayload(o: *Object, inst: Air.Inst.Index) !CValue {...@@ -1638,15 +1657,31 @@ fn airOptionalPayload(o: *Object, inst: Air.Inst.Index) !CValue {
16381657
1639fn airStructFieldPtr(o: *Object, inst: Air.Inst.Index) !CValue {1658fn airStructFieldPtr(o: *Object, inst: Air.Inst.Index) !CValue {
1640 if (o.liveness.isUnused(inst))1659 if (o.liveness.isUnused(inst))
1641 return CValue.none;1660 // TODO this @as is needed because of a stage1 bug
1661 return @as(CValue, CValue.none);
16421662
1643 const ty_pl = o.air.instructions.items(.data)[inst].ty_pl;1663 const ty_pl = o.air.instructions.items(.data)[inst].ty_pl;
1644 const extra = o.air.extraData(Air.StructField, ty_pl.payload).data;1664 const extra = o.air.extraData(Air.StructField, ty_pl.payload).data;
1645 const writer = o.writer();
1646 const struct_ptr = try o.resolveInst(extra.struct_operand);1665 const struct_ptr = try o.resolveInst(extra.struct_operand);
1647 const struct_ptr_ty = o.air.typeOf(extra.struct_operand);1666 const struct_ptr_ty = o.air.typeOf(extra.struct_operand);
1667 return structFieldPtr(o, inst, struct_ptr_ty, struct_ptr, extra.field_index);
1668}
1669
1670fn airStructFieldPtrIndex(o: *Object, inst: Air.Inst.Index, index: u8) !CValue {
1671 if (o.liveness.isUnused(inst))
1672 // TODO this @as is needed because of a stage1 bug
1673 return @as(CValue, CValue.none);
1674
1675 const ty_op = o.air.instructions.items(.data)[inst].ty_op;
1676 const struct_ptr = try o.resolveInst(ty_op.operand);
1677 const struct_ptr_ty = o.air.typeOf(ty_op.operand);
1678 return structFieldPtr(o, inst, struct_ptr_ty, struct_ptr, index);
1679}
1680
1681fn structFieldPtr(o: *Object, inst: Air.Inst.Index, struct_ptr_ty: Type, struct_ptr: CValue, index: u32) !CValue {
1682 const writer = o.writer();
1648 const struct_obj = struct_ptr_ty.elemType().castTag(.@"struct").?.data;1683 const struct_obj = struct_ptr_ty.elemType().castTag(.@"struct").?.data;
1649 const field_name = struct_obj.fields.keys()[extra.field_index];1684 const field_name = struct_obj.fields.keys()[index];
16501685
1651 const inst_ty = o.air.typeOfIndex(inst);1686 const inst_ty = o.air.typeOfIndex(inst);
1652 const local = try o.allocLocal(inst_ty, .Const);1687 const local = try o.allocLocal(inst_ty, .Const);
src/codegen/llvm.zig+98-22
...@@ -434,6 +434,8 @@ pub const Object = struct {...@@ -434,6 +434,8 @@ pub const Object = struct {
434 },434 },
435 else => |e| return e,435 else => |e| return e,
436 };436 };
437 const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
438 try self.updateDeclExports(module, decl, decl_exports);
437 }439 }
438440
439 pub fn updateDeclExports(441 pub fn updateDeclExports(
...@@ -442,7 +444,9 @@ pub const Object = struct {...@@ -442,7 +444,9 @@ pub const Object = struct {
442 decl: *const Module.Decl,444 decl: *const Module.Decl,
443 exports: []const *Module.Export,445 exports: []const *Module.Export,
444 ) !void {446 ) !void {
445 const llvm_fn = self.llvm_module.getNamedFunction(decl.name).?;447 // If the module does not already have the function, we ignore this function call
448 // because we call `updateDeclExports` at the end of `updateFunc` and `updateDecl`.
449 const llvm_fn = self.llvm_module.getNamedFunction(decl.name) orelse return;
446 const is_extern = decl.val.tag() == .extern_fn;450 const is_extern = decl.val.tag() == .extern_fn;
447 if (is_extern or exports.len != 0) {451 if (is_extern or exports.len != 0) {
448 llvm_fn.setLinkage(.External);452 llvm_fn.setLinkage(.External);
...@@ -808,27 +812,22 @@ pub const DeclGen = struct {...@@ -808,27 +812,22 @@ pub const DeclGen = struct {
808 return self.todo("handle more array values", .{});812 return self.todo("handle more array values", .{});
809 },813 },
810 .Optional => {814 .Optional => {
811 if (!tv.ty.isPtrLikeOptional()) {815 if (tv.ty.isPtrLikeOptional()) {
812 var buf: Type.Payload.ElemType = undefined;
813 const child_type = tv.ty.optionalChild(&buf);
814 const llvm_child_type = try self.llvmType(child_type);
815
816 if (tv.val.tag() == .null_value) {
817 var optional_values: [2]*const llvm.Value = .{
818 llvm_child_type.constNull(),
819 self.context.intType(1).constNull(),
820 };
821 return self.context.constStruct(&optional_values, optional_values.len, .False);
822 } else {
823 var optional_values: [2]*const llvm.Value = .{
824 try self.genTypedValue(.{ .ty = child_type, .val = tv.val }),
825 self.context.intType(1).constAllOnes(),
826 };
827 return self.context.constStruct(&optional_values, optional_values.len, .False);
828 }
829 } else {
830 return self.todo("implement const of optional pointer", .{});816 return self.todo("implement const of optional pointer", .{});
831 }817 }
818 var buf: Type.Payload.ElemType = undefined;
819 const payload_type = tv.ty.optionalChild(&buf);
820 const is_pl = !tv.val.isNull();
821 const llvm_i1 = self.context.intType(1);
822
823 const fields: [2]*const llvm.Value = .{
824 try self.genTypedValue(.{
825 .ty = payload_type,
826 .val = if (tv.val.castTag(.opt_payload)) |pl| pl.data else Value.initTag(.undef),
827 }),
828 if (is_pl) llvm_i1.constAllOnes() else llvm_i1.constNull(),
829 };
830 return self.context.constStruct(&fields, fields.len, .False);
832 },831 },
833 .Fn => {832 .Fn => {
834 const fn_decl = switch (tv.val.tag()) {833 const fn_decl = switch (tv.val.tag()) {
...@@ -995,6 +994,9 @@ pub const FuncGen = struct {...@@ -995,6 +994,9 @@ pub const FuncGen = struct {
995 .bit_or, .bool_or => try self.airOr(inst),994 .bit_or, .bool_or => try self.airOr(inst),
996 .xor => try self.airXor(inst),995 .xor => try self.airXor(inst),
997996
997 .shl => try self.airShl(inst),
998 .shr => try self.airShr(inst),
999
998 .cmp_eq => try self.airCmp(inst, .eq),1000 .cmp_eq => try self.airCmp(inst, .eq),
999 .cmp_gt => try self.airCmp(inst, .gt),1001 .cmp_gt => try self.airCmp(inst, .gt),
1000 .cmp_gte => try self.airCmp(inst, .gte),1002 .cmp_gte => try self.airCmp(inst, .gte),
...@@ -1037,9 +1039,15 @@ pub const FuncGen = struct {...@@ -1037,9 +1039,15 @@ pub const FuncGen = struct {
1037 .struct_field_ptr => try self.airStructFieldPtr(inst),1039 .struct_field_ptr => try self.airStructFieldPtr(inst),
1038 .struct_field_val => try self.airStructFieldVal(inst),1040 .struct_field_val => try self.airStructFieldVal(inst),
10391041
1042 .struct_field_ptr_index_0 => try self.airStructFieldPtrIndex(inst, 0),
1043 .struct_field_ptr_index_1 => try self.airStructFieldPtrIndex(inst, 1),
1044 .struct_field_ptr_index_2 => try self.airStructFieldPtrIndex(inst, 2),
1045 .struct_field_ptr_index_3 => try self.airStructFieldPtrIndex(inst, 3),
1046
1040 .slice_elem_val => try self.airSliceElemVal(inst),1047 .slice_elem_val => try self.airSliceElemVal(inst),
1041 .ptr_slice_elem_val => try self.airPtrSliceElemVal(inst),1048 .ptr_slice_elem_val => try self.airPtrSliceElemVal(inst),
1042 .ptr_elem_val => try self.airPtrElemVal(inst),1049 .ptr_elem_val => try self.airPtrElemVal(inst),
1050 .ptr_elem_ptr => try self.airPtrElemPtr(inst),
1043 .ptr_ptr_elem_val => try self.airPtrPtrElemVal(inst),1051 .ptr_ptr_elem_val => try self.airPtrPtrElemVal(inst),
10441052
1045 .optional_payload => try self.airOptionalPayload(inst, false),1053 .optional_payload => try self.airOptionalPayload(inst, false),
...@@ -1295,11 +1303,35 @@ pub const FuncGen = struct {...@@ -1295,11 +1303,35 @@ pub const FuncGen = struct {
1295 const bin_op = self.air.instructions.items(.data)[inst].bin_op;1303 const bin_op = self.air.instructions.items(.data)[inst].bin_op;
1296 const base_ptr = try self.resolveInst(bin_op.lhs);1304 const base_ptr = try self.resolveInst(bin_op.lhs);
1297 const rhs = try self.resolveInst(bin_op.rhs);1305 const rhs = try self.resolveInst(bin_op.rhs);
1298 const indices: [1]*const llvm.Value = .{rhs};1306 const ptr = if (self.air.typeOf(bin_op.lhs).isSinglePointer()) ptr: {
1299 const ptr = self.builder.buildInBoundsGEP(base_ptr, &indices, indices.len, "");1307 // If this is a single-item pointer to an array, we need another index in the GEP.
1308 const indices: [2]*const llvm.Value = .{ self.context.intType(32).constNull(), rhs };
1309 break :ptr self.builder.buildInBoundsGEP(base_ptr, &indices, indices.len, "");
1310 } else ptr: {
1311 const indices: [1]*const llvm.Value = .{rhs};
1312 break :ptr self.builder.buildInBoundsGEP(base_ptr, &indices, indices.len, "");
1313 };
1300 return self.builder.buildLoad(ptr, "");1314 return self.builder.buildLoad(ptr, "");
1301 }1315 }
13021316
1317 fn airPtrElemPtr(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
1318 if (self.liveness.isUnused(inst))
1319 return null;
1320
1321 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;
1322 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
1323 const base_ptr = try self.resolveInst(bin_op.lhs);
1324 const rhs = try self.resolveInst(bin_op.rhs);
1325 if (self.air.typeOf(bin_op.lhs).isSinglePointer()) {
1326 // If this is a single-item pointer to an array, we need another index in the GEP.
1327 const indices: [2]*const llvm.Value = .{ self.context.intType(32).constNull(), rhs };
1328 return self.builder.buildInBoundsGEP(base_ptr, &indices, indices.len, "");
1329 } else {
1330 const indices: [1]*const llvm.Value = .{rhs};
1331 return self.builder.buildInBoundsGEP(base_ptr, &indices, indices.len, "");
1332 }
1333 }
1334
1303 fn airPtrPtrElemVal(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {1335 fn airPtrPtrElemVal(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
1304 const is_volatile = false; // TODO1336 const is_volatile = false; // TODO
1305 if (!is_volatile and self.liveness.isUnused(inst))1337 if (!is_volatile and self.liveness.isUnused(inst))
...@@ -1325,6 +1357,15 @@ pub const FuncGen = struct {...@@ -1325,6 +1357,15 @@ pub const FuncGen = struct {
1325 return self.builder.buildStructGEP(struct_ptr, field_index, "");1357 return self.builder.buildStructGEP(struct_ptr, field_index, "");
1326 }1358 }
13271359
1360 fn airStructFieldPtrIndex(self: *FuncGen, inst: Air.Inst.Index, field_index: c_uint) !?*const llvm.Value {
1361 if (self.liveness.isUnused(inst))
1362 return null;
1363
1364 const ty_op = self.air.instructions.items(.data)[inst].ty_op;
1365 const struct_ptr = try self.resolveInst(ty_op.operand);
1366 return self.builder.buildStructGEP(struct_ptr, field_index, "");
1367 }
1368
1328 fn airStructFieldVal(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {1369 fn airStructFieldVal(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
1329 if (self.liveness.isUnused(inst))1370 if (self.liveness.isUnused(inst))
1330 return null;1371 return null;
...@@ -1739,6 +1780,41 @@ pub const FuncGen = struct {...@@ -1739,6 +1780,41 @@ pub const FuncGen = struct {
1739 return self.builder.buildXor(lhs, rhs, "");1780 return self.builder.buildXor(lhs, rhs, "");
1740 }1781 }
17411782
1783 fn airShl(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
1784 if (self.liveness.isUnused(inst))
1785 return null;
1786 const bin_op = self.air.instructions.items(.data)[inst].bin_op;
1787 const lhs = try self.resolveInst(bin_op.lhs);
1788 const rhs = try self.resolveInst(bin_op.rhs);
1789 const lhs_type = self.air.typeOf(bin_op.lhs);
1790 const tg = self.dg.module.getTarget();
1791 const casted_rhs = if (self.air.typeOf(bin_op.rhs).bitSize(tg) < lhs_type.bitSize(tg))
1792 self.builder.buildZExt(rhs, try self.dg.llvmType(lhs_type), "")
1793 else
1794 rhs;
1795 return self.builder.buildShl(lhs, casted_rhs, "");
1796 }
1797
1798 fn airShr(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
1799 if (self.liveness.isUnused(inst))
1800 return null;
1801 const bin_op = self.air.instructions.items(.data)[inst].bin_op;
1802 const lhs = try self.resolveInst(bin_op.lhs);
1803 const rhs = try self.resolveInst(bin_op.rhs);
1804 const lhs_type = self.air.typeOf(bin_op.lhs);
1805 const tg = self.dg.module.getTarget();
1806 const casted_rhs = if (self.air.typeOf(bin_op.rhs).bitSize(tg) < lhs_type.bitSize(tg))
1807 self.builder.buildZExt(rhs, try self.dg.llvmType(lhs_type), "")
1808 else
1809 rhs;
1810
1811 if (self.air.typeOfIndex(inst).isSignedInt()) {
1812 return self.builder.buildAShr(lhs, casted_rhs, "");
1813 } else {
1814 return self.builder.buildLShr(lhs, casted_rhs, "");
1815 }
1816 }
1817
1742 fn airIntCast(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {1818 fn airIntCast(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
1743 if (self.liveness.isUnused(inst))1819 if (self.liveness.isUnused(inst))
1744 return null;1820 return null;
src/codegen/llvm/bindings.zig+17
...@@ -291,6 +291,14 @@ pub const Builder = opaque {...@@ -291,6 +291,14 @@ pub const Builder = opaque {
291 pub const getInsertBlock = LLVMGetInsertBlock;291 pub const getInsertBlock = LLVMGetInsertBlock;
292 extern fn LLVMGetInsertBlock(Builder: *const Builder) *const BasicBlock;292 extern fn LLVMGetInsertBlock(Builder: *const Builder) *const BasicBlock;
293293
294 pub const buildZExt = LLVMBuildZExt;
295 extern fn LLVMBuildZExt(
296 *const Builder,
297 Value: *const Value,
298 DestTy: *const Type,
299 Name: [*:0]const u8,
300 ) *const Value;
301
294 pub const buildCall = LLVMBuildCall;302 pub const buildCall = LLVMBuildCall;
295 extern fn LLVMBuildCall(303 extern fn LLVMBuildCall(
296 *const Builder,304 *const Builder,
...@@ -382,6 +390,15 @@ pub const Builder = opaque {...@@ -382,6 +390,15 @@ pub const Builder = opaque {
382 pub const buildAnd = LLVMBuildAnd;390 pub const buildAnd = LLVMBuildAnd;
383 extern fn LLVMBuildAnd(*const Builder, LHS: *const Value, RHS: *const Value, Name: [*:0]const u8) *const Value;391 extern fn LLVMBuildAnd(*const Builder, LHS: *const Value, RHS: *const Value, Name: [*:0]const u8) *const Value;
384392
393 pub const buildLShr = LLVMBuildLShr;
394 extern fn LLVMBuildLShr(*const Builder, LHS: *const Value, RHS: *const Value, Name: [*:0]const u8) *const Value;
395
396 pub const buildAShr = LLVMBuildAShr;
397 extern fn LLVMBuildAShr(*const Builder, LHS: *const Value, RHS: *const Value, Name: [*:0]const u8) *const Value;
398
399 pub const buildShl = LLVMBuildShl;
400 extern fn LLVMBuildShl(*const Builder, LHS: *const Value, RHS: *const Value, Name: [*:0]const u8) *const Value;
401
385 pub const buildOr = LLVMBuildOr;402 pub const buildOr = LLVMBuildOr;
386 extern fn LLVMBuildOr(*const Builder, LHS: *const Value, RHS: *const Value, Name: [*:0]const u8) *const Value;403 extern fn LLVMBuildOr(*const Builder, LHS: *const Value, RHS: *const Value, Name: [*:0]const u8) *const Value;
387404
src/codegen/wasm.zig+19-7
...@@ -862,6 +862,10 @@ pub const Context = struct {...@@ -862,6 +862,10 @@ pub const Context = struct {
862 .ret => self.airRet(inst),862 .ret => self.airRet(inst),
863 .store => self.airStore(inst),863 .store => self.airStore(inst),
864 .struct_field_ptr => self.airStructFieldPtr(inst),864 .struct_field_ptr => self.airStructFieldPtr(inst),
865 .struct_field_ptr_index_0 => self.airStructFieldPtrIndex(inst, 0),
866 .struct_field_ptr_index_1 => self.airStructFieldPtrIndex(inst, 1),
867 .struct_field_ptr_index_2 => self.airStructFieldPtrIndex(inst, 2),
868 .struct_field_ptr_index_3 => self.airStructFieldPtrIndex(inst, 3),
865 .switch_br => self.airSwitchBr(inst),869 .switch_br => self.airSwitchBr(inst),
866 .unreach => self.airUnreachable(inst),870 .unreach => self.airUnreachable(inst),
867 .wrap_optional => self.airWrapOptional(inst),871 .wrap_optional => self.airWrapOptional(inst),
...@@ -1198,7 +1202,12 @@ pub const Context = struct {...@@ -1198,7 +1202,12 @@ pub const Context = struct {
11981202
1199 // When constant has value 'null', set is_null local to '1'1203 // When constant has value 'null', set is_null local to '1'
1200 // and payload to '0'1204 // and payload to '0'
1201 if (val.tag() == .null_value) {1205 if (val.castTag(.opt_payload)) |pl| {
1206 const payload_val = pl.data;
1207 try writer.writeByte(wasm.opcode(.i32_const));
1208 try leb.writeILEB128(writer, @as(i32, 0));
1209 try self.emitConstant(payload_val, payload_type);
1210 } else {
1202 try writer.writeByte(wasm.opcode(.i32_const));1211 try writer.writeByte(wasm.opcode(.i32_const));
1203 try leb.writeILEB128(writer, @as(i32, 1));1212 try leb.writeILEB128(writer, @as(i32, 1));
12041213
...@@ -1208,10 +1217,6 @@ pub const Context = struct {...@@ -1208,10 +1217,6 @@ pub const Context = struct {
1208 });1217 });
1209 try writer.writeByte(wasm.opcode(opcode));1218 try writer.writeByte(wasm.opcode(opcode));
1210 try leb.writeULEB128(writer, @as(u32, 0));1219 try leb.writeULEB128(writer, @as(u32, 0));
1211 } else {
1212 try writer.writeByte(wasm.opcode(.i32_const));
1213 try leb.writeILEB128(writer, @as(i32, 0));
1214 try self.emitConstant(val, payload_type);
1215 }1220 }
1216 },1221 },
1217 else => |zig_type| return self.fail("Wasm TODO: emitConstant for zigTypeTag {s}", .{zig_type}),1222 else => |zig_type| return self.fail("Wasm TODO: emitConstant for zigTypeTag {s}", .{zig_type}),
...@@ -1440,8 +1445,15 @@ pub const Context = struct {...@@ -1440,8 +1445,15 @@ pub const Context = struct {
1440 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;1445 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;
1441 const extra = self.air.extraData(Air.StructField, ty_pl.payload);1446 const extra = self.air.extraData(Air.StructField, ty_pl.payload);
1442 const struct_ptr = self.resolveInst(extra.data.struct_operand);1447 const struct_ptr = self.resolveInst(extra.data.struct_operand);
14431448 return structFieldPtr(struct_ptr, extra.data.field_index);
1444 return WValue{ .local = struct_ptr.multi_value.index + @intCast(u32, extra.data.field_index) };1449 }
1450 fn airStructFieldPtrIndex(self: *Context, inst: Air.Inst.Index, index: u32) InnerError!WValue {
1451 const ty_op = self.air.instructions.items(.data)[inst].ty_op;
1452 const struct_ptr = self.resolveInst(ty_op.operand);
1453 return structFieldPtr(struct_ptr, index);
1454 }
1455 fn structFieldPtr(struct_ptr: WValue, index: u32) InnerError!WValue {
1456 return WValue{ .local = struct_ptr.multi_value.index + index };
1445 }1457 }
14461458
1447 fn airSwitchBr(self: *Context, inst: Air.Inst.Index) InnerError!WValue {1459 fn airSwitchBr(self: *Context, inst: Air.Inst.Index) InnerError!WValue {
src/link/Wasm.zig+2-6
...@@ -765,12 +765,8 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void {...@@ -765,12 +765,8 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void {
765 if (self.base.options.wasi_exec_model == .reactor) {765 if (self.base.options.wasi_exec_model == .reactor) {
766 // Reactor execution model does not have _start so lld doesn't look for it.766 // Reactor execution model does not have _start so lld doesn't look for it.
767 try argv.append("--no-entry");767 try argv.append("--no-entry");
768 // Make sure "_initialize" is exported even if this is pure Zig WASI reactor768 // Make sure "_initialize" and other used-defined functions are exported if this is WASI reactor.
769 // where WASM_SYMBOL_EXPORTED flag in LLVM is not set on _initialize.769 try argv.append("--export-dynamic");
770 try argv.appendSlice(&[_][]const u8{
771 "--export",
772 "_initialize",
773 });
774 }770 }
775 } else {771 } else {
776 try argv.append("--no-entry"); // So lld doesn't look for _start.772 try argv.append("--no-entry"); // So lld doesn't look for _start.
src/main.zig+1
...@@ -2492,6 +2492,7 @@ fn cmdTranslateC(comp: *Compilation, arena: *Allocator, enable_cache: bool) !voi...@@ -2492,6 +2492,7 @@ fn cmdTranslateC(comp: *Compilation, arena: *Allocator, enable_cache: bool) !voi
24922492
2493 const digest = if (try man.hit()) man.final() else digest: {2493 const digest = if (try man.hit()) man.final() else digest: {
2494 var argv = std.ArrayList([]const u8).init(arena);2494 var argv = std.ArrayList([]const u8).init(arena);
2495 try argv.append(""); // argv[0] is program name, actual args start at [1]
24952496
2496 var zig_cache_tmp_dir = try comp.local_cache_directory.handle.makeOpenPath("tmp", .{});2497 var zig_cache_tmp_dir = try comp.local_cache_directory.handle.makeOpenPath("tmp", .{});
2497 defer zig_cache_tmp_dir.close();2498 defer zig_cache_tmp_dir.close();
src/mingw.zig+17-19
...@@ -187,27 +187,25 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {...@@ -187,27 +187,25 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {
187 };187 };
188 }188 }
189 } else if (target.cpu.arch.isARM()) {189 } else if (target.cpu.arch.isARM()) {
190 if (target.cpu.arch.ptrBitWidth() == 32) {190 for (mingwex_arm32_src) |dep| {
191 for (mingwex_arm32_src) |dep| {191 (try c_source_files.addOne()).* = .{
192 (try c_source_files.addOne()).* = .{192 .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{
193 .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{193 "libc", "mingw", dep,
194 "libc", "mingw", dep,194 }),
195 }),195 .extra_flags = extra_flags,
196 .extra_flags = extra_flags,196 };
197 };197 }
198 }198 } else if (target.cpu.arch.isAARCH64()) {
199 } else {199 for (mingwex_arm64_src) |dep| {
200 for (mingwex_arm64_src) |dep| {200 (try c_source_files.addOne()).* = .{
201 (try c_source_files.addOne()).* = .{201 .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{
202 .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{202 "libc", "mingw", dep,
203 "libc", "mingw", dep,203 }),
204 }),204 .extra_flags = extra_flags,
205 .extra_flags = extra_flags,205 };
206 };
207 }
208 }206 }
209 } else {207 } else {
210 unreachable;208 @panic("unsupported arch");
211 }209 }
212 return comp.build_crt_file("mingwex", .Lib, c_source_files.items);210 return comp.build_crt_file("mingwex", .Lib, c_source_files.items);
213 },211 },
src/print_air.zig+19-3
...@@ -127,6 +127,8 @@ const Writer = struct {...@@ -127,6 +127,8 @@ const Writer = struct {
127 .ptr_slice_elem_val,127 .ptr_slice_elem_val,
128 .ptr_elem_val,128 .ptr_elem_val,
129 .ptr_ptr_elem_val,129 .ptr_ptr_elem_val,
130 .shl,
131 .shr,
130 => try w.writeBinOp(s, inst),132 => try w.writeBinOp(s, inst),
131133
132 .is_null,134 .is_null,
...@@ -167,12 +169,17 @@ const Writer = struct {...@@ -167,12 +169,17 @@ const Writer = struct {
167 .wrap_errunion_err,169 .wrap_errunion_err,
168 .slice_ptr,170 .slice_ptr,
169 .slice_len,171 .slice_len,
172 .struct_field_ptr_index_0,
173 .struct_field_ptr_index_1,
174 .struct_field_ptr_index_2,
175 .struct_field_ptr_index_3,
170 => try w.writeTyOp(s, inst),176 => try w.writeTyOp(s, inst),
171177
172 .block,178 .block,
173 .loop,179 .loop,
174 => try w.writeBlock(s, inst),180 => try w.writeBlock(s, inst),
175181
182 .ptr_elem_ptr => try w.writePtrElemPtr(s, inst),
176 .struct_field_ptr => try w.writeStructField(s, inst),183 .struct_field_ptr => try w.writeStructField(s, inst),
177 .struct_field_val => try w.writeStructField(s, inst),184 .struct_field_val => try w.writeStructField(s, inst),
178 .constant => try w.writeConstant(s, inst),185 .constant => try w.writeConstant(s, inst),
...@@ -237,10 +244,19 @@ const Writer = struct {...@@ -237,10 +244,19 @@ const Writer = struct {
237244
238 fn writeStructField(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {245 fn writeStructField(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
239 const ty_pl = w.air.instructions.items(.data)[inst].ty_pl;246 const ty_pl = w.air.instructions.items(.data)[inst].ty_pl;
240 const extra = w.air.extraData(Air.StructField, ty_pl.payload);247 const extra = w.air.extraData(Air.StructField, ty_pl.payload).data;
241248
242 try w.writeOperand(s, inst, 0, extra.data.struct_operand);249 try w.writeOperand(s, inst, 0, extra.struct_operand);
243 try s.print(", {d}", .{extra.data.field_index});250 try s.print(", {d}", .{extra.field_index});
251 }
252
253 fn writePtrElemPtr(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
254 const ty_pl = w.air.instructions.items(.data)[inst].ty_pl;
255 const extra = w.air.extraData(Air.Bin, ty_pl.payload).data;
256
257 try w.writeOperand(s, inst, 0, extra.lhs);
258 try s.writeAll(", ");
259 try w.writeOperand(s, inst, 0, extra.rhs);
244 }260 }
245261
246 fn writeConstant(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {262 fn writeConstant(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
src/stage1/all_types.hpp+1
...@@ -1125,6 +1125,7 @@ struct AstNodeContainerInitExpr {...@@ -1125,6 +1125,7 @@ struct AstNodeContainerInitExpr {
11251125
1126struct AstNodeIdentifier {1126struct AstNodeIdentifier {
1127 Buf *name;1127 Buf *name;
1128 bool is_at_syntax;
1128};1129};
11291130
1130struct AstNodeEnumLiteral {1131struct AstNodeEnumLiteral {
src/stage1/analyze.cpp-48
...@@ -3918,12 +3918,6 @@ static void add_top_level_decl(CodeGen *g, ScopeDecls *decls_scope, Tld *tld) {...@@ -3918,12 +3918,6 @@ static void add_top_level_decl(CodeGen *g, ScopeDecls *decls_scope, Tld *tld) {
3918 add_error_note(g, msg, other_tld->source_node, buf_sprintf("previous definition here"));3918 add_error_note(g, msg, other_tld->source_node, buf_sprintf("previous definition here"));
3919 return;3919 return;
3920 }3920 }
3921
3922 ZigType *type;
3923 if (get_primitive_type(g, tld->name, &type) != ErrorPrimitiveTypeNotFound) {
3924 add_node_error(g, tld->source_node,
3925 buf_sprintf("declaration shadows primitive type '%s'", buf_ptr(tld->name)));
3926 }
3927 }3921 }
3928}3922}
39293923
...@@ -4170,48 +4164,6 @@ ZigVar *add_variable(CodeGen *g, AstNode *source_node, Scope *parent_scope, Buf...@@ -4170,48 +4164,6 @@ ZigVar *add_variable(CodeGen *g, AstNode *source_node, Scope *parent_scope, Buf
4170 variable_entry->var_type = g->builtin_types.entry_invalid;4164 variable_entry->var_type = g->builtin_types.entry_invalid;
4171 } else {4165 } else {
4172 variable_entry->align_bytes = get_abi_alignment(g, var_type);4166 variable_entry->align_bytes = get_abi_alignment(g, var_type);
4173
4174 ZigVar *existing_var = find_variable(g, parent_scope, name, nullptr);
4175 if (existing_var && !existing_var->shadowable) {
4176 if (existing_var->var_type == nullptr || !type_is_invalid(existing_var->var_type)) {
4177 ErrorMsg *msg = add_node_error(g, source_node,
4178 buf_sprintf("redeclaration of variable '%s'", buf_ptr(name)));
4179 add_error_note(g, msg, existing_var->decl_node, buf_sprintf("previous declaration here"));
4180 }
4181 variable_entry->var_type = g->builtin_types.entry_invalid;
4182 } else {
4183 ZigType *type;
4184 if (get_primitive_type(g, name, &type) != ErrorPrimitiveTypeNotFound) {
4185 add_node_error(g, source_node,
4186 buf_sprintf("variable shadows primitive type '%s'", buf_ptr(name)));
4187 variable_entry->var_type = g->builtin_types.entry_invalid;
4188 } else {
4189 Scope *search_scope = nullptr;
4190 if (src_tld == nullptr) {
4191 search_scope = parent_scope;
4192 } else if (src_tld->parent_scope != nullptr && src_tld->parent_scope->parent != nullptr) {
4193 search_scope = src_tld->parent_scope->parent;
4194 }
4195 if (search_scope != nullptr) {
4196 Tld *tld = find_decl(g, search_scope, name);
4197 if (tld != nullptr && tld != src_tld) {
4198 bool want_err_msg = true;
4199 if (tld->id == TldIdVar) {
4200 ZigVar *var = reinterpret_cast<TldVar *>(tld)->var;
4201 if (var != nullptr && var->var_type != nullptr && type_is_invalid(var->var_type)) {
4202 want_err_msg = false;
4203 }
4204 }
4205 if (want_err_msg) {
4206 ErrorMsg *msg = add_node_error(g, source_node,
4207 buf_sprintf("redefinition of '%s'", buf_ptr(name)));
4208 add_error_note(g, msg, tld->source_node, buf_sprintf("previous definition here"));
4209 }
4210 variable_entry->var_type = g->builtin_types.entry_invalid;
4211 }
4212 }
4213 }
4214 }
4215 }4167 }
42164168
4217 Scope *child_scope;4169 Scope *child_scope;
src/stage1/astgen.cpp+57-54
...@@ -3194,30 +3194,6 @@ ZigVar *create_local_var(CodeGen *codegen, AstNode *node, Scope *parent_scope,...@@ -3194,30 +3194,6 @@ ZigVar *create_local_var(CodeGen *codegen, AstNode *node, Scope *parent_scope,
3194 add_error_note(codegen, msg, existing_var->decl_node, buf_sprintf("previous declaration here"));3194 add_error_note(codegen, msg, existing_var->decl_node, buf_sprintf("previous declaration here"));
3195 }3195 }
3196 variable_entry->var_type = codegen->builtin_types.entry_invalid;3196 variable_entry->var_type = codegen->builtin_types.entry_invalid;
3197 } else {
3198 ZigType *type;
3199 if (get_primitive_type(codegen, name, &type) != ErrorPrimitiveTypeNotFound) {
3200 add_node_error(codegen, node,
3201 buf_sprintf("variable shadows primitive type '%s'", buf_ptr(name)));
3202 variable_entry->var_type = codegen->builtin_types.entry_invalid;
3203 } else {
3204 Tld *tld = find_decl(codegen, parent_scope, name);
3205 if (tld != nullptr) {
3206 bool want_err_msg = true;
3207 if (tld->id == TldIdVar) {
3208 ZigVar *var = reinterpret_cast<TldVar *>(tld)->var;
3209 if (var != nullptr && var->var_type != nullptr && type_is_invalid(var->var_type)) {
3210 want_err_msg = false;
3211 }
3212 }
3213 if (want_err_msg) {
3214 ErrorMsg *msg = add_node_error(codegen, node,
3215 buf_sprintf("redefinition of '%s'", buf_ptr(name)));
3216 add_error_note(codegen, msg, tld->source_node, buf_sprintf("previous definition here"));
3217 }
3218 variable_entry->var_type = codegen->builtin_types.entry_invalid;
3219 }
3220 }
3221 }3197 }
3222 }3198 }
3223 } else {3199 } else {
...@@ -3832,35 +3808,38 @@ static Stage1ZirInst *astgen_identifier(Stage1AstGen *ag, Scope *scope, AstNode...@@ -3832,35 +3808,38 @@ static Stage1ZirInst *astgen_identifier(Stage1AstGen *ag, Scope *scope, AstNode
3832 Error err;3808 Error err;
3833 assert(node->type == NodeTypeIdentifier);3809 assert(node->type == NodeTypeIdentifier);
38343810
3835 Buf *variable_name = node_identifier_buf(node);3811 bool is_at_syntax;
38363812 Buf *variable_name = node_identifier_buf2(node, &is_at_syntax);
3837 if (buf_eql_str(variable_name, "_")) {3813
3838 if (lval == LValAssign) {3814 if (!is_at_syntax) {
3839 Stage1ZirInstConst *const_instruction = ir_build_instruction<Stage1ZirInstConst>(ag, scope, node);3815 if (buf_eql_str(variable_name, "_")) {
3840 const_instruction->value = ag->codegen->pass1_arena->create<ZigValue>();3816 if (lval == LValAssign) {
3841 const_instruction->value->type = get_pointer_to_type(ag->codegen,3817 Stage1ZirInstConst *const_instruction = ir_build_instruction<Stage1ZirInstConst>(ag, scope, node);
3842 ag->codegen->builtin_types.entry_void, false);3818 const_instruction->value = ag->codegen->pass1_arena->create<ZigValue>();
3843 const_instruction->value->special = ConstValSpecialStatic;3819 const_instruction->value->type = get_pointer_to_type(ag->codegen,
3844 const_instruction->value->data.x_ptr.special = ConstPtrSpecialDiscard;3820 ag->codegen->builtin_types.entry_void, false);
3845 return &const_instruction->base;3821 const_instruction->value->special = ConstValSpecialStatic;
3822 const_instruction->value->data.x_ptr.special = ConstPtrSpecialDiscard;
3823 return &const_instruction->base;
3824 }
3846 }3825 }
3847 }
38483826
3849 ZigType *primitive_type;3827 ZigType *primitive_type;
3850 if ((err = get_primitive_type(ag->codegen, variable_name, &primitive_type))) {3828 if ((err = get_primitive_type(ag->codegen, variable_name, &primitive_type))) {
3851 if (err == ErrorOverflow) {3829 if (err == ErrorOverflow) {
3852 add_node_error(ag->codegen, node,3830 add_node_error(ag->codegen, node,
3853 buf_sprintf("primitive integer type '%s' exceeds maximum bit width of 65535",3831 buf_sprintf("primitive integer type '%s' exceeds maximum bit width of 65535",
3854 buf_ptr(variable_name)));3832 buf_ptr(variable_name)));
3855 return ag->codegen->invalid_inst_src;3833 return ag->codegen->invalid_inst_src;
3856 }3834 }
3857 assert(err == ErrorPrimitiveTypeNotFound);3835 assert(err == ErrorPrimitiveTypeNotFound);
3858 } else {
3859 Stage1ZirInst *value = ir_build_const_type(ag, scope, node, primitive_type);
3860 if (lval == LValPtr || lval == LValAssign) {
3861 return ir_build_ref_src(ag, scope, node, value);
3862 } else {3836 } else {
3863 return ir_expr_wrap(ag, scope, value, result_loc);3837 Stage1ZirInst *value = ir_build_const_type(ag, scope, node, primitive_type);
3838 if (lval == LValPtr || lval == LValAssign) {
3839 return ir_build_ref_src(ag, scope, node, value);
3840 } else {
3841 return ir_expr_wrap(ag, scope, value, result_loc);
3842 }
3864 }3843 }
3865 }3844 }
38663845
...@@ -3875,7 +3854,31 @@ static Stage1ZirInst *astgen_identifier(Stage1AstGen *ag, Scope *scope, AstNode...@@ -3875,7 +3854,31 @@ static Stage1ZirInst *astgen_identifier(Stage1AstGen *ag, Scope *scope, AstNode
3875 }3854 }
3876 }3855 }
38773856
3878 Tld *tld = find_decl(ag->codegen, scope, variable_name);3857 Tld *tld = nullptr;
3858 {
3859 Scope *s = scope;
3860 while (s) {
3861 if (s->id == ScopeIdDecls) {
3862 ScopeDecls *decls_scope = (ScopeDecls *)s;
3863
3864 Tld *result = find_container_decl(ag->codegen, decls_scope, variable_name);
3865 if (result != nullptr) {
3866 if (tld != nullptr && tld != result) {
3867 ErrorMsg *msg = add_node_error(ag->codegen, node,
3868 buf_sprintf("ambiguous reference"));
3869 add_error_note(ag->codegen, msg, tld->source_node,
3870 buf_sprintf("declared here"));
3871 add_error_note(ag->codegen, msg, result->source_node,
3872 buf_sprintf("also declared here"));
3873 return ag->codegen->invalid_inst_src;
3874 }
3875 tld = result;
3876 }
3877 }
3878 s = s->parent;
3879 }
3880 }
3881
3879 if (tld) {3882 if (tld) {
3880 Stage1ZirInst *decl_ref = ir_build_decl_ref(ag, scope, node, tld, lval);3883 Stage1ZirInst *decl_ref = ir_build_decl_ref(ag, scope, node, tld, lval);
3881 if (lval == LValPtr || lval == LValAssign) {3884 if (lval == LValPtr || lval == LValAssign) {
...@@ -4653,17 +4656,17 @@ static Stage1ZirInst *astgen_builtin_fn_call(Stage1AstGen *ag, Scope *scope, Ast...@@ -4653,17 +4656,17 @@ static Stage1ZirInst *astgen_builtin_fn_call(Stage1AstGen *ag, Scope *scope, Ast
46534656
4654 AstNode *arg1_node = node->data.fn_call_expr.params.at(1);4657 AstNode *arg1_node = node->data.fn_call_expr.params.at(1);
4655 Stage1ZirInst *arg1_value = astgen_node(ag, arg1_node, scope);4658 Stage1ZirInst *arg1_value = astgen_node(ag, arg1_node, scope);
4656 if (arg0_value == ag->codegen->invalid_inst_src)4659 if (arg1_value == ag->codegen->invalid_inst_src)
4657 return arg1_value;4660 return arg1_value;
46584661
4659 AstNode *arg2_node = node->data.fn_call_expr.params.at(2);4662 AstNode *arg2_node = node->data.fn_call_expr.params.at(2);
4660 Stage1ZirInst *arg2_value = astgen_node(ag, arg2_node, scope);4663 Stage1ZirInst *arg2_value = astgen_node(ag, arg2_node, scope);
4661 if (arg1_value == ag->codegen->invalid_inst_src)4664 if (arg2_value == ag->codegen->invalid_inst_src)
4662 return arg2_value;4665 return arg2_value;
46634666
4664 AstNode *arg3_node = node->data.fn_call_expr.params.at(3);4667 AstNode *arg3_node = node->data.fn_call_expr.params.at(3);
4665 Stage1ZirInst *arg3_value = astgen_node(ag, arg3_node, scope);4668 Stage1ZirInst *arg3_value = astgen_node(ag, arg3_node, scope);
4666 if (arg2_value == ag->codegen->invalid_inst_src)4669 if (arg3_value == ag->codegen->invalid_inst_src)
4667 return arg3_value;4670 return arg3_value;
46684671
4669 Stage1ZirInst *select = ir_build_select(ag, scope, node,4672 Stage1ZirInst *select = ir_build_select(ag, scope, node,
src/stage1/ir.cpp+25-14
...@@ -20007,29 +20007,24 @@ static Stage1AirInst *ir_analyze_instruction_truncate(IrAnalyze *ira, Stage1ZirI...@@ -20007,29 +20007,24 @@ static Stage1AirInst *ir_analyze_instruction_truncate(IrAnalyze *ira, Stage1ZirI
20007 return ir_build_truncate_gen(ira, instruction->base.scope, instruction->base.source_node, dest_type, target);20007 return ir_build_truncate_gen(ira, instruction->base.scope, instruction->base.source_node, dest_type, target);
20008}20008}
2000920009
20010static Stage1AirInst *ir_analyze_instruction_int_cast(IrAnalyze *ira, Stage1ZirInstIntCast *instruction) {20010static Stage1AirInst *ir_analyze_int_cast(IrAnalyze *ira, Scope *scope, AstNode *source_node,
20011 ZigType *dest_type = ir_resolve_type(ira, instruction->dest_type->child);20011 ZigType *dest_type, AstNode *dest_type_src_node,
20012 if (type_is_invalid(dest_type))20012 Stage1AirInst *target, AstNode *target_src_node)
20013 return ira->codegen->invalid_inst_gen;20013{
20014
20015 ZigType *scalar_dest_type = (dest_type->id == ZigTypeIdVector) ?20014 ZigType *scalar_dest_type = (dest_type->id == ZigTypeIdVector) ?
20016 dest_type->data.vector.elem_type : dest_type;20015 dest_type->data.vector.elem_type : dest_type;
2001720016
20018 if (scalar_dest_type->id != ZigTypeIdInt && scalar_dest_type->id != ZigTypeIdComptimeInt) {20017 if (scalar_dest_type->id != ZigTypeIdInt && scalar_dest_type->id != ZigTypeIdComptimeInt) {
20019 ir_add_error_node(ira, instruction->dest_type->source_node,20018 ir_add_error_node(ira, dest_type_src_node,
20020 buf_sprintf("expected integer type, found '%s'", buf_ptr(&scalar_dest_type->name)));20019 buf_sprintf("expected integer type, found '%s'", buf_ptr(&scalar_dest_type->name)));
20021 return ira->codegen->invalid_inst_gen;20020 return ira->codegen->invalid_inst_gen;
20022 }20021 }
2002320022
20024 Stage1AirInst *target = instruction->target->child;
20025 if (type_is_invalid(target->value->type))
20026 return ira->codegen->invalid_inst_gen;
20027
20028 ZigType *scalar_target_type = (target->value->type->id == ZigTypeIdVector) ?20023 ZigType *scalar_target_type = (target->value->type->id == ZigTypeIdVector) ?
20029 target->value->type->data.vector.elem_type : target->value->type;20024 target->value->type->data.vector.elem_type : target->value->type;
2003020025
20031 if (scalar_target_type->id != ZigTypeIdInt && scalar_target_type->id != ZigTypeIdComptimeInt) {20026 if (scalar_target_type->id != ZigTypeIdInt && scalar_target_type->id != ZigTypeIdComptimeInt) {
20032 ir_add_error_node(ira, instruction->target->source_node, buf_sprintf("expected integer type, found '%s'",20027 ir_add_error_node(ira, target_src_node, buf_sprintf("expected integer type, found '%s'",
20033 buf_ptr(&scalar_target_type->name)));20028 buf_ptr(&scalar_target_type->name)));
20034 return ira->codegen->invalid_inst_gen;20029 return ira->codegen->invalid_inst_gen;
20035 }20030 }
...@@ -20039,10 +20034,24 @@ static Stage1AirInst *ir_analyze_instruction_int_cast(IrAnalyze *ira, Stage1ZirI...@@ -20039,10 +20034,24 @@ static Stage1AirInst *ir_analyze_instruction_int_cast(IrAnalyze *ira, Stage1ZirI
20039 if (val == nullptr)20034 if (val == nullptr)
20040 return ira->codegen->invalid_inst_gen;20035 return ira->codegen->invalid_inst_gen;
2004120036
20042 return ir_implicit_cast2(ira, instruction->target->scope, instruction->target->source_node, target, dest_type);20037 return ir_implicit_cast2(ira, scope, target_src_node, target, dest_type);
20043 }20038 }
2004420039
20045 return ir_analyze_widen_or_shorten(ira, instruction->base.scope, instruction->base.source_node, target, dest_type);20040 return ir_analyze_widen_or_shorten(ira, scope, source_node, target, dest_type);
20041}
20042
20043static Stage1AirInst *ir_analyze_instruction_int_cast(IrAnalyze *ira, Stage1ZirInstIntCast *instruction) {
20044 ZigType *dest_type = ir_resolve_type(ira, instruction->dest_type->child);
20045 if (type_is_invalid(dest_type))
20046 return ira->codegen->invalid_inst_gen;
20047
20048 Stage1AirInst *target = instruction->target->child;
20049 if (type_is_invalid(target->value->type))
20050 return ira->codegen->invalid_inst_gen;
20051
20052 return ir_analyze_int_cast(ira, instruction->base.scope, instruction->base.source_node,
20053 dest_type, instruction->dest_type->source_node,
20054 target, instruction->target->source_node);
20046}20055}
2004720056
20048static Stage1AirInst *ir_analyze_instruction_float_cast(IrAnalyze *ira, Stage1ZirInstFloatCast *instruction) {20057static Stage1AirInst *ir_analyze_instruction_float_cast(IrAnalyze *ira, Stage1ZirInstFloatCast *instruction) {
...@@ -24282,7 +24291,9 @@ static Stage1AirInst *ir_analyze_instruction_int_to_enum(IrAnalyze *ira, Stage1Z...@@ -24282,7 +24291,9 @@ static Stage1AirInst *ir_analyze_instruction_int_to_enum(IrAnalyze *ira, Stage1Z
24282 if (type_is_invalid(target->value->type))24291 if (type_is_invalid(target->value->type))
24283 return ira->codegen->invalid_inst_gen;24292 return ira->codegen->invalid_inst_gen;
2428424293
24285 Stage1AirInst *casted_target = ir_implicit_cast(ira, target, tag_type);24294 Stage1AirInst *casted_target = ir_analyze_int_cast(ira, instruction->base.scope,
24295 instruction->base.source_node, tag_type, instruction->dest_type->source_node,
24296 target, instruction->target->source_node);
24286 if (type_is_invalid(casted_target->value->type))24297 if (type_is_invalid(casted_target->value->type))
24287 return ira->codegen->invalid_inst_gen;24298 return ira->codegen->invalid_inst_gen;
2428824299
src/stage1/parser.cpp+16-3
...@@ -3482,8 +3482,7 @@ Error source_char_literal(const char *source, uint32_t *result, size_t *bad_inde...@@ -3482,8 +3482,7 @@ Error source_char_literal(const char *source, uint32_t *result, size_t *bad_inde
3482 }3482 }
3483}3483}
34843484
34853485static Buf *token_identifier_buf2(RootStruct *root_struct, TokenIndex token, bool *is_at_syntax) {
3486Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {
3487 Error err;3486 Error err;
3488 const char *source = buf_ptr(root_struct->source_code);3487 const char *source = buf_ptr(root_struct->source_code);
3489 size_t byte_offset = root_struct->token_locs[token].offset;3488 size_t byte_offset = root_struct->token_locs[token].offset;
...@@ -3495,6 +3494,7 @@ Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {...@@ -3495,6 +3494,7 @@ Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {
3495 assert(source[byte_offset] != '.'); // wrong token index3494 assert(source[byte_offset] != '.'); // wrong token index
34963495
3497 if (source[byte_offset] == '@') {3496 if (source[byte_offset] == '@') {
3497 *is_at_syntax = true;
3498 size_t bad_index;3498 size_t bad_index;
3499 Buf *str = buf_alloc();3499 Buf *str = buf_alloc();
3500 if ((err = source_string_literal_buf(source + byte_offset + 1, str, &bad_index))) {3500 if ((err = source_string_literal_buf(source + byte_offset + 1, str, &bad_index))) {
...@@ -3503,6 +3503,7 @@ Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {...@@ -3503,6 +3503,7 @@ Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {
3503 }3503 }
3504 return str;3504 return str;
3505 } else {3505 } else {
3506 *is_at_syntax = false;
3506 size_t start = byte_offset;3507 size_t start = byte_offset;
3507 for (;; byte_offset += 1) {3508 for (;; byte_offset += 1) {
3508 if (source[byte_offset] == 0) break;3509 if (source[byte_offset] == 0) break;
...@@ -3519,7 +3520,17 @@ Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {...@@ -3519,7 +3520,17 @@ Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {
3519 }3520 }
3520}3521}
35213522
3523Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {
3524 bool trash;
3525 return token_identifier_buf2(root_struct, token, &trash);
3526}
3527
3522Buf *node_identifier_buf(AstNode *node) {3528Buf *node_identifier_buf(AstNode *node) {
3529 bool trash;
3530 return node_identifier_buf2(node, &trash);
3531}
3532
3533Buf *node_identifier_buf2(AstNode *node, bool *is_at_syntax) {
3523 assert(node->type == NodeTypeIdentifier);3534 assert(node->type == NodeTypeIdentifier);
3524 // Currently, stage1 runs astgen for every comptime function call,3535 // Currently, stage1 runs astgen for every comptime function call,
3525 // resulting the allocation here wasting memory. As a workaround until3536 // resulting the allocation here wasting memory. As a workaround until
...@@ -3527,8 +3538,10 @@ Buf *node_identifier_buf(AstNode *node) {...@@ -3527,8 +3538,10 @@ Buf *node_identifier_buf(AstNode *node) {
3527 // we memoize the result into the AST here.3538 // we memoize the result into the AST here.
3528 if (node->data.identifier.name == nullptr) {3539 if (node->data.identifier.name == nullptr) {
3529 RootStruct *root_struct = node->owner->data.structure.root_struct;3540 RootStruct *root_struct = node->owner->data.structure.root_struct;
3530 node->data.identifier.name = token_identifier_buf(root_struct, node->main_token);3541 node->data.identifier.name = token_identifier_buf2(root_struct, node->main_token,
3542 &node->data.identifier.is_at_syntax);
3531 }3543 }
3544 *is_at_syntax = node->data.identifier.is_at_syntax;
3532 return node->data.identifier.name;3545 return node->data.identifier.name;
3533}3546}
35343547
src/stage1/parser.hpp+1
...@@ -19,6 +19,7 @@ void ast_print(AstNode *node, int indent);...@@ -19,6 +19,7 @@ void ast_print(AstNode *node, int indent);
19void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *context), void *context);19void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *context), void *context);
2020
21Buf *node_identifier_buf(AstNode *node);21Buf *node_identifier_buf(AstNode *node);
22Buf *node_identifier_buf2(AstNode *node, bool *is_at_syntax);
2223
23Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token);24Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token);
2425
src/stage1/target.cpp+1-1
...@@ -925,7 +925,7 @@ bool target_has_valgrind_support(const ZigTarget *target) {...@@ -925,7 +925,7 @@ bool target_has_valgrind_support(const ZigTarget *target) {
925 case ZigLLVM_UnknownArch:925 case ZigLLVM_UnknownArch:
926 zig_unreachable();926 zig_unreachable();
927 case ZigLLVM_x86_64:927 case ZigLLVM_x86_64:
928 return (target->os == OsLinux || target_os_is_darwin(target->os) || target->os == OsSolaris ||928 return (target->os == OsLinux || target->os == OsSolaris ||
929 (target->os == OsWindows && target->abi != ZigLLVM_MSVC));929 (target->os == OsWindows && target->abi != ZigLLVM_MSVC));
930 default:930 default:
931 return false;931 return false;
src/target.zig+1-1
...@@ -166,7 +166,7 @@ pub fn isSingleThreaded(target: std.Target) bool {...@@ -166,7 +166,7 @@ pub fn isSingleThreaded(target: std.Target) bool {
166pub fn hasValgrindSupport(target: std.Target) bool {166pub fn hasValgrindSupport(target: std.Target) bool {
167 switch (target.cpu.arch) {167 switch (target.cpu.arch) {
168 .x86_64 => {168 .x86_64 => {
169 return target.os.tag == .linux or target.isDarwin() or target.os.tag == .solaris or169 return target.os.tag == .linux or target.os.tag == .solaris or
170 (target.os.tag == .windows and target.abi != .msvc);170 (target.os.tag == .windows and target.abi != .msvc);
171 },171 },
172 else => return false,172 else => return false,
src/translate_c.zig+73-6
...@@ -719,6 +719,30 @@ fn transQualTypeMaybeInitialized(c: *Context, scope: *Scope, qt: clang.QualType,...@@ -719,6 +719,30 @@ fn transQualTypeMaybeInitialized(c: *Context, scope: *Scope, qt: clang.QualType,
719 transQualType(c, scope, qt, loc);719 transQualType(c, scope, qt, loc);
720}720}
721721
722/// This is used in global scope to convert a string literal `S` to [*c]u8:
723/// &(struct {
724/// var static = S.*;
725/// }).static;
726fn stringLiteralToCharStar(c: *Context, str: Node) Error!Node {
727 const var_name = Scope.Block.StaticInnerName;
728
729 const variables = try c.arena.alloc(Node, 1);
730 variables[0] = try Tag.mut_str.create(c.arena, .{ .name = var_name, .init = str });
731
732 const anon_struct = try Tag.@"struct".create(c.arena, .{
733 .layout = .none,
734 .fields = &.{},
735 .functions = &.{},
736 .variables = variables,
737 });
738
739 const member_access = try Tag.field_access.create(c.arena, .{
740 .lhs = anon_struct,
741 .field_name = var_name,
742 });
743 return Tag.address_of.create(c.arena, member_access);
744}
745
722/// if mangled_name is not null, this var decl was declared in a block scope.746/// if mangled_name is not null, this var decl was declared in a block scope.
723fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]const u8) Error!void {747fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]const u8) Error!void {
724 const var_name = mangled_name orelse try c.str(@ptrCast(*const clang.NamedDecl, var_decl).getName_bytes_begin());748 const var_name = mangled_name orelse try c.str(@ptrCast(*const clang.NamedDecl, var_decl).getName_bytes_begin());
...@@ -779,6 +803,8 @@ fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]co...@@ -779,6 +803,8 @@ fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]co
779 };803 };
780 if (!qualTypeIsBoolean(qual_type) and isBoolRes(init_node.?)) {804 if (!qualTypeIsBoolean(qual_type) and isBoolRes(init_node.?)) {
781 init_node = try Tag.bool_to_int.create(c.arena, init_node.?);805 init_node = try Tag.bool_to_int.create(c.arena, init_node.?);
806 } else if (init_node.?.tag() == .string_literal and qualTypeIsCharStar(qual_type)) {
807 init_node = try stringLiteralToCharStar(c, init_node.?);
782 }808 }
783 } else {809 } else {
784 init_node = Tag.undefined_literal.init();810 init_node = Tag.undefined_literal.init();
...@@ -1101,9 +1127,10 @@ fn transRecordDecl(c: *Context, scope: *Scope, record_decl: *const clang.RecordD...@@ -1101,9 +1127,10 @@ fn transRecordDecl(c: *Context, scope: *Scope, record_decl: *const clang.RecordD
1101 record_payload.* = .{1127 record_payload.* = .{
1102 .base = .{ .tag = ([2]Tag{ .@"struct", .@"union" })[@boolToInt(is_union)] },1128 .base = .{ .tag = ([2]Tag{ .@"struct", .@"union" })[@boolToInt(is_union)] },
1103 .data = .{1129 .data = .{
1104 .is_packed = is_packed,1130 .layout = if (is_packed) .@"packed" else .@"extern",
1105 .fields = try c.arena.dupe(ast.Payload.Record.Field, fields.items),1131 .fields = try c.arena.dupe(ast.Payload.Record.Field, fields.items),
1106 .functions = try c.arena.dupe(Node, functions.items),1132 .functions = try c.arena.dupe(Node, functions.items),
1133 .variables = &.{},
1107 },1134 },
1108 };1135 };
1109 break :blk Node.initPayload(&record_payload.base);1136 break :blk Node.initPayload(&record_payload.base);
...@@ -1805,6 +1832,9 @@ fn transDeclStmtOne(...@@ -1805,6 +1832,9 @@ fn transDeclStmtOne(
1805 Tag.undefined_literal.init();1832 Tag.undefined_literal.init();
1806 if (!qualTypeIsBoolean(qual_type) and isBoolRes(init_node)) {1833 if (!qualTypeIsBoolean(qual_type) and isBoolRes(init_node)) {
1807 init_node = try Tag.bool_to_int.create(c.arena, init_node);1834 init_node = try Tag.bool_to_int.create(c.arena, init_node);
1835 } else if (init_node.tag() == .string_literal and qualTypeIsCharStar(qual_type)) {
1836 const dst_type_node = try transQualType(c, scope, qual_type, loc);
1837 init_node = try removeCVQualifiers(c, dst_type_node, init_node);
1808 }1838 }
18091839
1810 const var_name: []const u8 = if (is_static_local) Scope.Block.StaticInnerName else mangled_name;1840 const var_name: []const u8 = if (is_static_local) Scope.Block.StaticInnerName else mangled_name;
...@@ -2522,9 +2552,19 @@ fn transInitListExprRecord(...@@ -2522,9 +2552,19 @@ fn transInitListExprRecord(
2522 raw_name = try mem.dupe(c.arena, u8, name);2552 raw_name = try mem.dupe(c.arena, u8, name);
2523 }2553 }
25242554
2555 var init_expr = try transExpr(c, scope, elem_expr, .used);
2556 const field_qt = field_decl.getType();
2557 if (init_expr.tag() == .string_literal and qualTypeIsCharStar(field_qt)) {
2558 if (scope.id == .root) {
2559 init_expr = try stringLiteralToCharStar(c, init_expr);
2560 } else {
2561 const dst_type_node = try transQualType(c, scope, field_qt, loc);
2562 init_expr = try removeCVQualifiers(c, dst_type_node, init_expr);
2563 }
2564 }
2525 try field_inits.append(.{2565 try field_inits.append(.{
2526 .name = raw_name,2566 .name = raw_name,
2527 .value = try transExpr(c, scope, elem_expr, .used),2567 .value = init_expr,
2528 });2568 });
2529 }2569 }
2530 if (ty_node.castTag(.identifier)) |ident_node| {2570 if (ty_node.castTag(.identifier)) |ident_node| {
...@@ -3459,6 +3499,10 @@ fn transCallExpr(c: *Context, scope: *Scope, stmt: *const clang.CallExpr, result...@@ -3459,6 +3499,10 @@ fn transCallExpr(c: *Context, scope: *Scope, stmt: *const clang.CallExpr, result
3459 const param_qt = fn_proto.getParamType(@intCast(c_uint, i));3499 const param_qt = fn_proto.getParamType(@intCast(c_uint, i));
3460 if (isBoolRes(arg) and cIsNativeInt(param_qt)) {3500 if (isBoolRes(arg) and cIsNativeInt(param_qt)) {
3461 arg = try Tag.bool_to_int.create(c.arena, arg);3501 arg = try Tag.bool_to_int.create(c.arena, arg);
3502 } else if (arg.tag() == .string_literal and qualTypeIsCharStar(param_qt)) {
3503 const loc = @ptrCast(*const clang.Stmt, stmt).getBeginLoc();
3504 const dst_type_node = try transQualType(c, scope, param_qt, loc);
3505 arg = try removeCVQualifiers(c, dst_type_node, arg);
3462 }3506 }
3463 }3507 }
3464 },3508 },
...@@ -3835,6 +3879,12 @@ fn transCreateCompoundAssign(...@@ -3835,6 +3879,12 @@ fn transCreateCompoundAssign(
3835 return block_scope.complete(c);3879 return block_scope.complete(c);
3836}3880}
38373881
3882// Casting away const or volatile requires us to use @intToPtr
3883fn removeCVQualifiers(c: *Context, dst_type_node: Node, expr: Node) Error!Node {
3884 const ptr_to_int = try Tag.ptr_to_int.create(c.arena, expr);
3885 return Tag.int_to_ptr.create(c.arena, .{ .lhs = dst_type_node, .rhs = ptr_to_int });
3886}
3887
3838fn transCPtrCast(3888fn transCPtrCast(
3839 c: *Context,3889 c: *Context,
3840 scope: *Scope,3890 scope: *Scope,
...@@ -3854,10 +3904,7 @@ fn transCPtrCast(...@@ -3854,10 +3904,7 @@ fn transCPtrCast(
3854 (src_child_type.isVolatileQualified() and3904 (src_child_type.isVolatileQualified() and
3855 !child_type.isVolatileQualified())))3905 !child_type.isVolatileQualified())))
3856 {3906 {
3857 // Casting away const or volatile requires us to use @intToPtr3907 return removeCVQualifiers(c, dst_type_node, expr);
3858 const ptr_to_int = try Tag.ptr_to_int.create(c.arena, expr);
3859 const int_to_ptr = try Tag.int_to_ptr.create(c.arena, .{ .lhs = dst_type_node, .rhs = ptr_to_int });
3860 return int_to_ptr;
3861 } else {3908 } else {
3862 // Implicit downcasting from higher to lower alignment values is forbidden,3909 // Implicit downcasting from higher to lower alignment values is forbidden,
3863 // use @alignCast to side-step this problem3910 // use @alignCast to side-step this problem
...@@ -4217,6 +4264,26 @@ fn typeIsOpaque(c: *Context, ty: *const clang.Type, loc: clang.SourceLocation) b...@@ -4217,6 +4264,26 @@ fn typeIsOpaque(c: *Context, ty: *const clang.Type, loc: clang.SourceLocation) b
4217 }4264 }
4218}4265}
42194266
4267/// plain `char *` (not const; not explicitly signed or unsigned)
4268fn qualTypeIsCharStar(qt: clang.QualType) bool {
4269 if (qualTypeIsPtr(qt)) {
4270 const child_qt = qualTypeCanon(qt).getPointeeType();
4271 return cIsUnqualifiedChar(child_qt) and !child_qt.isConstQualified();
4272 }
4273 return false;
4274}
4275
4276/// C `char` without explicit signed or unsigned qualifier
4277fn cIsUnqualifiedChar(qt: clang.QualType) bool {
4278 const c_type = qualTypeCanon(qt);
4279 if (c_type.getTypeClass() != .Builtin) return false;
4280 const builtin_ty = @ptrCast(*const clang.BuiltinType, c_type);
4281 return switch (builtin_ty.getKind()) {
4282 .Char_S, .Char_U => true,
4283 else => false,
4284 };
4285}
4286
4220fn cIsInteger(qt: clang.QualType) bool {4287fn cIsInteger(qt: clang.QualType) bool {
4221 return cIsSignedInteger(qt) or cIsUnsignedInteger(qt);4288 return cIsSignedInteger(qt) or cIsUnsignedInteger(qt);
4222}4289}
src/translate_c/ast.zig+49-17
...@@ -62,6 +62,8 @@ pub const Node = extern union {...@@ -62,6 +62,8 @@ pub const Node = extern union {
62 var_decl,62 var_decl,
63 /// const name = struct { init }63 /// const name = struct { init }
64 static_local_var,64 static_local_var,
65 /// var name = init.*
66 mut_str,
65 func,67 func,
66 warning,68 warning,
67 @"struct",69 @"struct",
...@@ -361,7 +363,7 @@ pub const Node = extern union {...@@ -361,7 +363,7 @@ pub const Node = extern union {
361 .array_type, .null_sentinel_array_type => Payload.Array,363 .array_type, .null_sentinel_array_type => Payload.Array,
362 .arg_redecl, .alias, .fail_decl => Payload.ArgRedecl,364 .arg_redecl, .alias, .fail_decl => Payload.ArgRedecl,
363 .log2_int_type => Payload.Log2IntType,365 .log2_int_type => Payload.Log2IntType,
364 .var_simple, .pub_var_simple, .static_local_var => Payload.SimpleVarDecl,366 .var_simple, .pub_var_simple, .static_local_var, .mut_str => Payload.SimpleVarDecl,
365 .enum_constant => Payload.EnumConstant,367 .enum_constant => Payload.EnumConstant,
366 .array_filler => Payload.ArrayFiller,368 .array_filler => Payload.ArrayFiller,
367 .pub_inline_fn => Payload.PubInlineFn,369 .pub_inline_fn => Payload.PubInlineFn,
...@@ -558,9 +560,10 @@ pub const Payload = struct {...@@ -558,9 +560,10 @@ pub const Payload = struct {
558 pub const Record = struct {560 pub const Record = struct {
559 base: Payload,561 base: Payload,
560 data: struct {562 data: struct {
561 is_packed: bool,563 layout: enum { @"packed", @"extern", none },
562 fields: []Field,564 fields: []Field,
563 functions: []Node,565 functions: []Node,
566 variables: []Node,
564 },567 },
565568
566 pub const Field = struct {569 pub const Field = struct {
...@@ -925,23 +928,23 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {...@@ -925,23 +928,23 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
925 return renderCall(c, lhs, payload.args);928 return renderCall(c, lhs, payload.args);
926 },929 },
927 .null_literal => return c.addNode(.{930 .null_literal => return c.addNode(.{
928 .tag = .null_literal,931 .tag = .identifier,
929 .main_token = try c.addToken(.keyword_null, "null"),932 .main_token = try c.addToken(.identifier, "null"),
930 .data = undefined,933 .data = undefined,
931 }),934 }),
932 .undefined_literal => return c.addNode(.{935 .undefined_literal => return c.addNode(.{
933 .tag = .undefined_literal,936 .tag = .identifier,
934 .main_token = try c.addToken(.keyword_undefined, "undefined"),937 .main_token = try c.addToken(.identifier, "undefined"),
935 .data = undefined,938 .data = undefined,
936 }),939 }),
937 .true_literal => return c.addNode(.{940 .true_literal => return c.addNode(.{
938 .tag = .true_literal,941 .tag = .identifier,
939 .main_token = try c.addToken(.keyword_true, "true"),942 .main_token = try c.addToken(.identifier, "true"),
940 .data = undefined,943 .data = undefined,
941 }),944 }),
942 .false_literal => return c.addNode(.{945 .false_literal => return c.addNode(.{
943 .tag = .false_literal,946 .tag = .identifier,
944 .main_token = try c.addToken(.keyword_false, "false"),947 .main_token = try c.addToken(.identifier, "false"),
945 .data = undefined,948 .data = undefined,
946 }),949 }),
947 .zero_literal => return c.addNode(.{950 .zero_literal => return c.addNode(.{
...@@ -1229,6 +1232,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {...@@ -1229,6 +1232,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
1229 },1232 },
1230 });1233 });
1231 _ = try c.addToken(.r_brace, "}");1234 _ = try c.addToken(.r_brace, "}");
1235 _ = try c.addToken(.semicolon, ";");
12321236
1233 return c.addNode(.{1237 return c.addNode(.{
1234 .tag = .simple_var_decl,1238 .tag = .simple_var_decl,
...@@ -1239,6 +1243,29 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {...@@ -1239,6 +1243,29 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
1239 },1243 },
1240 });1244 });
1241 },1245 },
1246 .mut_str => {
1247 const payload = node.castTag(.mut_str).?.data;
1248
1249 const var_tok = try c.addToken(.keyword_var, "var");
1250 _ = try c.addIdentifier(payload.name);
1251 _ = try c.addToken(.equal, "=");
1252
1253 const deref = try c.addNode(.{
1254 .tag = .deref,
1255 .data = .{
1256 .lhs = try renderNodeGrouped(c, payload.init),
1257 .rhs = undefined,
1258 },
1259 .main_token = try c.addToken(.period_asterisk, ".*"),
1260 });
1261 _ = try c.addToken(.semicolon, ";");
1262
1263 return c.addNode(.{
1264 .tag = .simple_var_decl,
1265 .main_token = var_tok,
1266 .data = .{ .lhs = 0, .rhs = deref },
1267 });
1268 },
1242 .var_decl => return renderVar(c, node),1269 .var_decl => return renderVar(c, node),
1243 .arg_redecl, .alias => {1270 .arg_redecl, .alias => {
1244 const payload = @fieldParentPtr(Payload.ArgRedecl, "base", node.ptr_otherwise).data;1271 const payload = @fieldParentPtr(Payload.ArgRedecl, "base", node.ptr_otherwise).data;
...@@ -1572,8 +1599,8 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {...@@ -1572,8 +1599,8 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
1572 const while_tok = try c.addToken(.keyword_while, "while");1599 const while_tok = try c.addToken(.keyword_while, "while");
1573 _ = try c.addToken(.l_paren, "(");1600 _ = try c.addToken(.l_paren, "(");
1574 const cond = try c.addNode(.{1601 const cond = try c.addNode(.{
1575 .tag = .true_literal,1602 .tag = .identifier,
1576 .main_token = try c.addToken(.keyword_true, "true"),1603 .main_token = try c.addToken(.identifier, "true"),
1577 .data = undefined,1604 .data = undefined,
1578 });1605 });
1579 _ = try c.addToken(.r_paren, ")");1606 _ = try c.addToken(.r_paren, ")");
...@@ -1952,9 +1979,9 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {...@@ -1952,9 +1979,9 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
19521979
1953fn renderRecord(c: *Context, node: Node) !NodeIndex {1980fn renderRecord(c: *Context, node: Node) !NodeIndex {
1954 const payload = @fieldParentPtr(Payload.Record, "base", node.ptr_otherwise).data;1981 const payload = @fieldParentPtr(Payload.Record, "base", node.ptr_otherwise).data;
1955 if (payload.is_packed)1982 if (payload.layout == .@"packed")
1956 _ = try c.addToken(.keyword_packed, "packed")1983 _ = try c.addToken(.keyword_packed, "packed")
1957 else1984 else if (payload.layout == .@"extern")
1958 _ = try c.addToken(.keyword_extern, "extern");1985 _ = try c.addToken(.keyword_extern, "extern");
1959 const kind_tok = if (node.tag() == .@"struct")1986 const kind_tok = if (node.tag() == .@"struct")
1960 try c.addToken(.keyword_struct, "struct")1987 try c.addToken(.keyword_struct, "struct")
...@@ -1963,8 +1990,9 @@ fn renderRecord(c: *Context, node: Node) !NodeIndex {...@@ -1963,8 +1990,9 @@ fn renderRecord(c: *Context, node: Node) !NodeIndex {
19631990
1964 _ = try c.addToken(.l_brace, "{");1991 _ = try c.addToken(.l_brace, "{");
19651992
1993 const num_vars = payload.variables.len;
1966 const num_funcs = payload.functions.len;1994 const num_funcs = payload.functions.len;
1967 const total_members = payload.fields.len + num_funcs;1995 const total_members = payload.fields.len + num_vars + num_funcs;
1968 const members = try c.gpa.alloc(NodeIndex, std.math.max(total_members, 2));1996 const members = try c.gpa.alloc(NodeIndex, std.math.max(total_members, 2));
1969 defer c.gpa.free(members);1997 defer c.gpa.free(members);
1970 members[0] = 0;1998 members[0] = 0;
...@@ -2006,8 +2034,11 @@ fn renderRecord(c: *Context, node: Node) !NodeIndex {...@@ -2006,8 +2034,11 @@ fn renderRecord(c: *Context, node: Node) !NodeIndex {
2006 });2034 });
2007 _ = try c.addToken(.comma, ",");2035 _ = try c.addToken(.comma, ",");
2008 }2036 }
2037 for (payload.variables) |variable, i| {
2038 members[payload.fields.len + i] = try renderNode(c, variable);
2039 }
2009 for (payload.functions) |function, i| {2040 for (payload.functions) |function, i| {
2010 members[payload.fields.len + i] = try renderNode(c, function);2041 members[payload.fields.len + num_vars + i] = try renderNode(c, function);
2011 }2042 }
2012 _ = try c.addToken(.r_brace, "}");2043 _ = try c.addToken(.r_brace, "}");
20132044
...@@ -2140,7 +2171,7 @@ fn renderNullSentinelArrayType(c: *Context, len: usize, elem_type: Node) !NodeIn...@@ -2140,7 +2171,7 @@ fn renderNullSentinelArrayType(c: *Context, len: usize, elem_type: Node) !NodeIn
2140fn addSemicolonIfNeeded(c: *Context, node: Node) !void {2171fn addSemicolonIfNeeded(c: *Context, node: Node) !void {
2141 switch (node.tag()) {2172 switch (node.tag()) {
2142 .warning => unreachable,2173 .warning => unreachable,
2143 .var_decl, .var_simple, .arg_redecl, .alias, .block, .empty_block, .block_single, .@"switch" => {},2174 .var_decl, .var_simple, .arg_redecl, .alias, .block, .empty_block, .block_single, .@"switch", .static_local_var, .mut_str => {},
2144 .while_true => {2175 .while_true => {
2145 const payload = node.castTag(.while_true).?.data;2176 const payload = node.castTag(.while_true).?.data;
2146 return addSemicolonIfNotBlock(c, payload);2177 return addSemicolonIfNotBlock(c, payload);
...@@ -2235,6 +2266,7 @@ fn renderNodeGrouped(c: *Context, node: Node) !NodeIndex {...@@ -2235,6 +2266,7 @@ fn renderNodeGrouped(c: *Context, node: Node) !NodeIndex {
2235 .offset_of,2266 .offset_of,
2236 .shuffle,2267 .shuffle,
2237 .static_local_var,2268 .static_local_var,
2269 .mut_str,
2238 => {2270 => {
2239 // no grouping needed2271 // no grouping needed
2240 return renderNode(c, node);2272 return renderNode(c, node);
src/type.zig+39
...@@ -133,6 +133,7 @@ pub const Type = extern union {...@@ -133,6 +133,7 @@ pub const Type = extern union {
133133
134 .@"union",134 .@"union",
135 .union_tagged,135 .union_tagged,
136 .type_info,
136 => return .Union,137 => return .Union,
137138
138 .var_args_param => unreachable, // can be any type139 .var_args_param => unreachable, // can be any type
...@@ -248,6 +249,30 @@ pub const Type = extern union {...@@ -248,6 +249,30 @@ pub const Type = extern union {
248 };249 };
249 }250 }
250251
252 pub fn ptrIsMutable(ty: Type) bool {
253 return switch (ty.tag()) {
254 .single_const_pointer_to_comptime_int,
255 .const_slice_u8,
256 .single_const_pointer,
257 .many_const_pointer,
258 .manyptr_const_u8,
259 .c_const_pointer,
260 .const_slice,
261 => false,
262
263 .single_mut_pointer,
264 .many_mut_pointer,
265 .manyptr_u8,
266 .c_mut_pointer,
267 .mut_slice,
268 => true,
269
270 .pointer => ty.castTag(.pointer).?.data.mutable,
271
272 else => unreachable,
273 };
274 }
275
251 pub fn ptrInfo(self: Type) Payload.Pointer {276 pub fn ptrInfo(self: Type) Payload.Pointer {
252 switch (self.tag()) {277 switch (self.tag()) {
253 .single_const_pointer_to_comptime_int => return .{ .data = .{278 .single_const_pointer_to_comptime_int => return .{ .data = .{
...@@ -717,6 +742,7 @@ pub const Type = extern union {...@@ -717,6 +742,7 @@ pub const Type = extern union {
717 .call_options,742 .call_options,
718 .export_options,743 .export_options,
719 .extern_options,744 .extern_options,
745 .type_info,
720 .@"anyframe",746 .@"anyframe",
721 .generic_poison,747 .generic_poison,
722 => unreachable,748 => unreachable,
...@@ -928,6 +954,7 @@ pub const Type = extern union {...@@ -928,6 +954,7 @@ pub const Type = extern union {
928 .call_options => return writer.writeAll("std.builtin.CallOptions"),954 .call_options => return writer.writeAll("std.builtin.CallOptions"),
929 .export_options => return writer.writeAll("std.builtin.ExportOptions"),955 .export_options => return writer.writeAll("std.builtin.ExportOptions"),
930 .extern_options => return writer.writeAll("std.builtin.ExternOptions"),956 .extern_options => return writer.writeAll("std.builtin.ExternOptions"),
957 .type_info => return writer.writeAll("std.builtin.TypeInfo"),
931 .function => {958 .function => {
932 const payload = ty.castTag(.function).?.data;959 const payload = ty.castTag(.function).?.data;
933 try writer.writeAll("fn(");960 try writer.writeAll("fn(");
...@@ -1178,6 +1205,7 @@ pub const Type = extern union {...@@ -1178,6 +1205,7 @@ pub const Type = extern union {
1178 .comptime_int,1205 .comptime_int,
1179 .comptime_float,1206 .comptime_float,
1180 .enum_literal,1207 .enum_literal,
1208 .type_info,
1181 => true,1209 => true,
11821210
1183 .var_args_param => unreachable,1211 .var_args_param => unreachable,
...@@ -1269,6 +1297,7 @@ pub const Type = extern union {...@@ -1269,6 +1297,7 @@ pub const Type = extern union {
1269 .call_options => return Value.initTag(.call_options_type),1297 .call_options => return Value.initTag(.call_options_type),
1270 .export_options => return Value.initTag(.export_options_type),1298 .export_options => return Value.initTag(.export_options_type),
1271 .extern_options => return Value.initTag(.extern_options_type),1299 .extern_options => return Value.initTag(.extern_options_type),
1300 .type_info => return Value.initTag(.type_info_type),
1272 .inferred_alloc_const => unreachable,1301 .inferred_alloc_const => unreachable,
1273 .inferred_alloc_mut => unreachable,1302 .inferred_alloc_mut => unreachable,
1274 else => return Value.Tag.ty.create(allocator, self),1303 else => return Value.Tag.ty.create(allocator, self),
...@@ -1409,6 +1438,7 @@ pub const Type = extern union {...@@ -1409,6 +1438,7 @@ pub const Type = extern union {
1409 .empty_struct,1438 .empty_struct,
1410 .empty_struct_literal,1439 .empty_struct_literal,
1411 .@"opaque",1440 .@"opaque",
1441 .type_info,
1412 => false,1442 => false,
14131443
1414 .inferred_alloc_const => unreachable,1444 .inferred_alloc_const => unreachable,
...@@ -1636,6 +1666,7 @@ pub const Type = extern union {...@@ -1636,6 +1666,7 @@ pub const Type = extern union {
1636 .inferred_alloc_mut,1666 .inferred_alloc_mut,
1637 .@"opaque",1667 .@"opaque",
1638 .var_args_param,1668 .var_args_param,
1669 .type_info,
1639 => unreachable,1670 => unreachable,
16401671
1641 .generic_poison => unreachable,1672 .generic_poison => unreachable,
...@@ -1667,6 +1698,7 @@ pub const Type = extern union {...@@ -1667,6 +1698,7 @@ pub const Type = extern union {
1667 .@"opaque" => unreachable,1698 .@"opaque" => unreachable,
1668 .var_args_param => unreachable,1699 .var_args_param => unreachable,
1669 .generic_poison => unreachable,1700 .generic_poison => unreachable,
1701 .type_info => unreachable,
16701702
1671 .@"struct" => {1703 .@"struct" => {
1672 const s = self.castTag(.@"struct").?.data;1704 const s = self.castTag(.@"struct").?.data;
...@@ -1978,6 +2010,7 @@ pub const Type = extern union {...@@ -1978,6 +2010,7 @@ pub const Type = extern union {
1978 .call_options,2010 .call_options,
1979 .export_options,2011 .export_options,
1980 .extern_options,2012 .extern_options,
2013 .type_info,
1981 => @panic("TODO at some point we gotta resolve builtin types"),2014 => @panic("TODO at some point we gotta resolve builtin types"),
1982 };2015 };
1983 }2016 }
...@@ -2691,6 +2724,7 @@ pub const Type = extern union {...@@ -2691,6 +2724,7 @@ pub const Type = extern union {
2691 .call_options,2724 .call_options,
2692 .export_options,2725 .export_options,
2693 .extern_options,2726 .extern_options,
2727 .type_info,
2694 .@"anyframe",2728 .@"anyframe",
2695 .anyframe_T,2729 .anyframe_T,
2696 .many_const_pointer,2730 .many_const_pointer,
...@@ -2778,6 +2812,7 @@ pub const Type = extern union {...@@ -2778,6 +2812,7 @@ pub const Type = extern union {
2778 return switch (self.tag()) {2812 return switch (self.tag()) {
2779 .@"struct" => &self.castTag(.@"struct").?.data.namespace,2813 .@"struct" => &self.castTag(.@"struct").?.data.namespace,
2780 .enum_full => &self.castTag(.enum_full).?.data.namespace,2814 .enum_full => &self.castTag(.enum_full).?.data.namespace,
2815 .enum_nonexhaustive => &self.castTag(.enum_nonexhaustive).?.data.namespace,
2781 .empty_struct => self.castTag(.empty_struct).?.data,2816 .empty_struct => self.castTag(.empty_struct).?.data,
2782 .@"opaque" => &self.castTag(.@"opaque").?.data,2817 .@"opaque" => &self.castTag(.@"opaque").?.data,
2783 .@"union" => &self.castTag(.@"union").?.data.namespace,2818 .@"union" => &self.castTag(.@"union").?.data.namespace,
...@@ -3022,6 +3057,7 @@ pub const Type = extern union {...@@ -3022,6 +3057,7 @@ pub const Type = extern union {
3022 .call_options,3057 .call_options,
3023 .export_options,3058 .export_options,
3024 .extern_options,3059 .extern_options,
3060 .type_info,
3025 => @panic("TODO resolve std.builtin types"),3061 => @panic("TODO resolve std.builtin types"),
3026 else => unreachable,3062 else => unreachable,
3027 }3063 }
...@@ -3058,6 +3094,7 @@ pub const Type = extern union {...@@ -3058,6 +3094,7 @@ pub const Type = extern union {
3058 .call_options,3094 .call_options,
3059 .export_options,3095 .export_options,
3060 .extern_options,3096 .extern_options,
3097 .type_info,
3061 => @panic("TODO resolve std.builtin types"),3098 => @panic("TODO resolve std.builtin types"),
3062 else => unreachable,3099 else => unreachable,
3063 }3100 }
...@@ -3167,6 +3204,7 @@ pub const Type = extern union {...@@ -3167,6 +3204,7 @@ pub const Type = extern union {
3167 call_options,3204 call_options,
3168 export_options,3205 export_options,
3169 extern_options,3206 extern_options,
3207 type_info,
3170 manyptr_u8,3208 manyptr_u8,
3171 manyptr_const_u8,3209 manyptr_const_u8,
3172 fn_noreturn_no_args,3210 fn_noreturn_no_args,
...@@ -3289,6 +3327,7 @@ pub const Type = extern union {...@@ -3289,6 +3327,7 @@ pub const Type = extern union {
3289 .call_options,3327 .call_options,
3290 .export_options,3328 .export_options,
3291 .extern_options,3329 .extern_options,
3330 .type_info,
3292 .@"anyframe",3331 .@"anyframe",
3293 => @compileError("Type Tag " ++ @tagName(t) ++ " has no payload"),3332 => @compileError("Type Tag " ++ @tagName(t) ++ " has no payload"),
32943333
src/value.zig+128-9
...@@ -68,6 +68,7 @@ pub const Value = extern union {...@@ -68,6 +68,7 @@ pub const Value = extern union {
68 call_options_type,68 call_options_type,
69 export_options_type,69 export_options_type,
70 extern_options_type,70 extern_options_type,
71 type_info_type,
71 manyptr_u8_type,72 manyptr_u8_type,
72 manyptr_const_u8_type,73 manyptr_const_u8_type,
73 fn_noreturn_no_args_type,74 fn_noreturn_no_args_type,
...@@ -132,12 +133,21 @@ pub const Value = extern union {...@@ -132,12 +133,21 @@ pub const Value = extern union {
132 /// When the type is error union:133 /// When the type is error union:
133 /// * If the tag is `.@"error"`, the error union is an error.134 /// * If the tag is `.@"error"`, the error union is an error.
134 /// * If the tag is `.eu_payload`, the error union is a payload.135 /// * If the tag is `.eu_payload`, the error union is a payload.
135 /// * A nested error such as `((anyerror!T1)!T2)` in which the the outer error union136 /// * A nested error such as `anyerror!(anyerror!T)` in which the the outer error union
136 /// is non-error, but the inner error union is an error, is represented as137 /// is non-error, but the inner error union is an error, is represented as
137 /// a tag of `.eu_payload`, with a sub-tag of `.@"error"`.138 /// a tag of `.eu_payload`, with a sub-tag of `.@"error"`.
138 eu_payload,139 eu_payload,
139 /// A pointer to the payload of an error union, based on a pointer to an error union.140 /// A pointer to the payload of an error union, based on a pointer to an error union.
140 eu_payload_ptr,141 eu_payload_ptr,
142 /// When the type is optional:
143 /// * If the tag is `.null_value`, the optional is null.
144 /// * If the tag is `.opt_payload`, the optional is a payload.
145 /// * A nested optional such as `??T` in which the the outer optional
146 /// is non-null, but the inner optional is null, is represented as
147 /// a tag of `.opt_payload`, with a sub-tag of `.null_value`.
148 opt_payload,
149 /// A pointer to the payload of an optional, based on a pointer to an optional.
150 opt_payload_ptr,
141 /// An instance of a struct.151 /// An instance of a struct.
142 @"struct",152 @"struct",
143 /// An instance of a union.153 /// An instance of a union.
...@@ -221,6 +231,7 @@ pub const Value = extern union {...@@ -221,6 +231,7 @@ pub const Value = extern union {
221 .call_options_type,231 .call_options_type,
222 .export_options_type,232 .export_options_type,
223 .extern_options_type,233 .extern_options_type,
234 .type_info_type,
224 .generic_poison,235 .generic_poison,
225 => @compileError("Value Tag " ++ @tagName(t) ++ " has no payload"),236 => @compileError("Value Tag " ++ @tagName(t) ++ " has no payload"),
226237
...@@ -236,6 +247,8 @@ pub const Value = extern union {...@@ -236,6 +247,8 @@ pub const Value = extern union {
236 .repeated,247 .repeated,
237 .eu_payload,248 .eu_payload,
238 .eu_payload_ptr,249 .eu_payload_ptr,
250 .opt_payload,
251 .opt_payload_ptr,
239 => Payload.SubValue,252 => Payload.SubValue,
240253
241 .bytes,254 .bytes,
...@@ -402,6 +415,7 @@ pub const Value = extern union {...@@ -402,6 +415,7 @@ pub const Value = extern union {
402 .call_options_type,415 .call_options_type,
403 .export_options_type,416 .export_options_type,
404 .extern_options_type,417 .extern_options_type,
418 .type_info_type,
405 .generic_poison,419 .generic_poison,
406 => unreachable,420 => unreachable,
407421
...@@ -456,7 +470,12 @@ pub const Value = extern union {...@@ -456,7 +470,12 @@ pub const Value = extern union {
456 return Value{ .ptr_otherwise = &new_payload.base };470 return Value{ .ptr_otherwise = &new_payload.base };
457 },471 },
458 .bytes => return self.copyPayloadShallow(allocator, Payload.Bytes),472 .bytes => return self.copyPayloadShallow(allocator, Payload.Bytes),
459 .repeated, .eu_payload, .eu_payload_ptr => {473 .repeated,
474 .eu_payload,
475 .eu_payload_ptr,
476 .opt_payload,
477 .opt_payload_ptr,
478 => {
460 const payload = self.cast(Payload.SubValue).?;479 const payload = self.cast(Payload.SubValue).?;
461 const new_payload = try allocator.create(Payload.SubValue);480 const new_payload = try allocator.create(Payload.SubValue);
462 new_payload.* = .{481 new_payload.* = .{
...@@ -585,6 +604,7 @@ pub const Value = extern union {...@@ -585,6 +604,7 @@ pub const Value = extern union {
585 .call_options_type => return out_stream.writeAll("std.builtin.CallOptions"),604 .call_options_type => return out_stream.writeAll("std.builtin.CallOptions"),
586 .export_options_type => return out_stream.writeAll("std.builtin.ExportOptions"),605 .export_options_type => return out_stream.writeAll("std.builtin.ExportOptions"),
587 .extern_options_type => return out_stream.writeAll("std.builtin.ExternOptions"),606 .extern_options_type => return out_stream.writeAll("std.builtin.ExternOptions"),
607 .type_info_type => return out_stream.writeAll("std.builtin.TypeInfo"),
588 .abi_align_default => return out_stream.writeAll("(default ABI alignment)"),608 .abi_align_default => return out_stream.writeAll("(default ABI alignment)"),
589609
590 .empty_struct_value => return out_stream.writeAll("struct {}{}"),610 .empty_struct_value => return out_stream.writeAll("struct {}{}"),
...@@ -652,12 +672,20 @@ pub const Value = extern union {...@@ -652,12 +672,20 @@ pub const Value = extern union {
652 try out_stream.writeAll("(eu_payload) ");672 try out_stream.writeAll("(eu_payload) ");
653 val = val.castTag(.eu_payload).?.data;673 val = val.castTag(.eu_payload).?.data;
654 },674 },
675 .opt_payload => {
676 try out_stream.writeAll("(opt_payload) ");
677 val = val.castTag(.opt_payload).?.data;
678 },
655 .inferred_alloc => return out_stream.writeAll("(inferred allocation value)"),679 .inferred_alloc => return out_stream.writeAll("(inferred allocation value)"),
656 .inferred_alloc_comptime => return out_stream.writeAll("(inferred comptime allocation value)"),680 .inferred_alloc_comptime => return out_stream.writeAll("(inferred comptime allocation value)"),
657 .eu_payload_ptr => {681 .eu_payload_ptr => {
658 try out_stream.writeAll("(eu_payload_ptr)");682 try out_stream.writeAll("(eu_payload_ptr)");
659 val = val.castTag(.eu_payload_ptr).?.data;683 val = val.castTag(.eu_payload_ptr).?.data;
660 },684 },
685 .opt_payload_ptr => {
686 try out_stream.writeAll("(opt_payload_ptr)");
687 val = val.castTag(.opt_payload_ptr).?.data;
688 },
661 };689 };
662 }690 }
663691
...@@ -743,6 +771,7 @@ pub const Value = extern union {...@@ -743,6 +771,7 @@ pub const Value = extern union {
743 .call_options_type => Type.initTag(.call_options),771 .call_options_type => Type.initTag(.call_options),
744 .export_options_type => Type.initTag(.export_options),772 .export_options_type => Type.initTag(.export_options),
745 .extern_options_type => Type.initTag(.extern_options),773 .extern_options_type => Type.initTag(.extern_options),
774 .type_info_type => Type.initTag(.type_info),
746775
747 .int_type => {776 .int_type => {
748 const payload = self.castTag(.int_type).?.data;777 const payload = self.castTag(.int_type).?.data;
...@@ -771,6 +800,38 @@ pub const Value = extern union {...@@ -771,6 +800,38 @@ pub const Value = extern union {
771 }800 }
772 }801 }
773802
803 pub fn enumToInt(val: Value, ty: Type, buffer: *Payload.U64) Value {
804 if (val.castTag(.enum_field_index)) |enum_field_payload| {
805 const field_index = enum_field_payload.data;
806 switch (ty.tag()) {
807 .enum_full, .enum_nonexhaustive => {
808 const enum_full = ty.cast(Type.Payload.EnumFull).?.data;
809 if (enum_full.values.count() != 0) {
810 return enum_full.values.keys()[field_index];
811 } else {
812 // Field index and integer values are the same.
813 buffer.* = .{
814 .base = .{ .tag = .int_u64 },
815 .data = field_index,
816 };
817 return Value.initPayload(&buffer.base);
818 }
819 },
820 .enum_simple => {
821 // Field index and integer values are the same.
822 buffer.* = .{
823 .base = .{ .tag = .int_u64 },
824 .data = field_index,
825 };
826 return Value.initPayload(&buffer.base);
827 },
828 else => unreachable,
829 }
830 }
831 // Assume it is already an integer and return it directly.
832 return val;
833 }
834
774 /// Asserts the value is an integer.835 /// Asserts the value is an integer.
775 pub fn toBigInt(self: Value, space: *BigIntSpace) BigIntConst {836 pub fn toBigInt(self: Value, space: *BigIntSpace) BigIntConst {
776 switch (self.tag()) {837 switch (self.tag()) {
...@@ -1127,7 +1188,10 @@ pub const Value = extern union {...@@ -1127,7 +1188,10 @@ pub const Value = extern union {
1127 }1188 }
11281189
1129 pub fn hash(val: Value, ty: Type, hasher: *std.hash.Wyhash) void {1190 pub fn hash(val: Value, ty: Type, hasher: *std.hash.Wyhash) void {
1130 switch (ty.zigTypeTag()) {1191 const zig_ty_tag = ty.zigTypeTag();
1192 std.hash.autoHash(hasher, zig_ty_tag);
1193
1194 switch (zig_ty_tag) {
1131 .BoundFn => unreachable, // TODO remove this from the language1195 .BoundFn => unreachable, // TODO remove this from the language
11321196
1133 .Void,1197 .Void,
...@@ -1152,7 +1216,10 @@ pub const Value = extern union {...@@ -1152,7 +1216,10 @@ pub const Value = extern union {
1152 }1216 }
1153 },1217 },
1154 .Float, .ComptimeFloat => {1218 .Float, .ComptimeFloat => {
1155 @panic("TODO implement hashing float values");1219 // TODO double check the lang spec. should we to bitwise hashing here,
1220 // or a hash that normalizes the float value?
1221 const float = val.toFloat(f128);
1222 std.hash.autoHash(hasher, @bitCast(u128, float));
1156 },1223 },
1157 .Pointer => {1224 .Pointer => {
1158 @panic("TODO implement hashing pointer values");1225 @panic("TODO implement hashing pointer values");
...@@ -1164,7 +1231,15 @@ pub const Value = extern union {...@@ -1164,7 +1231,15 @@ pub const Value = extern union {
1164 @panic("TODO implement hashing struct values");1231 @panic("TODO implement hashing struct values");
1165 },1232 },
1166 .Optional => {1233 .Optional => {
1167 @panic("TODO implement hashing optional values");1234 if (val.castTag(.opt_payload)) |payload| {
1235 std.hash.autoHash(hasher, true); // non-null
1236 const sub_val = payload.data;
1237 var buffer: Type.Payload.ElemType = undefined;
1238 const sub_ty = ty.optionalChild(&buffer);
1239 sub_val.hash(sub_ty, hasher);
1240 } else {
1241 std.hash.autoHash(hasher, false); // non-null
1242 }
1168 },1243 },
1169 .ErrorUnion => {1244 .ErrorUnion => {
1170 @panic("TODO implement hashing error union values");1245 @panic("TODO implement hashing error union values");
...@@ -1173,7 +1248,16 @@ pub const Value = extern union {...@@ -1173,7 +1248,16 @@ pub const Value = extern union {
1173 @panic("TODO implement hashing error set values");1248 @panic("TODO implement hashing error set values");
1174 },1249 },
1175 .Enum => {1250 .Enum => {
1176 @panic("TODO implement hashing enum values");1251 var enum_space: Payload.U64 = undefined;
1252 const int_val = val.enumToInt(ty, &enum_space);
1253
1254 var space: BigIntSpace = undefined;
1255 const big = int_val.toBigInt(&space);
1256
1257 std.hash.autoHash(hasher, big.positive);
1258 for (big.limbs) |limb| {
1259 std.hash.autoHash(hasher, limb);
1260 }
1177 },1261 },
1178 .Union => {1262 .Union => {
1179 @panic("TODO implement hashing union values");1263 @panic("TODO implement hashing union values");
...@@ -1252,6 +1336,11 @@ pub const Value = extern union {...@@ -1252,6 +1336,11 @@ pub const Value = extern union {
1252 const err_union_val = (try err_union_ptr.pointerDeref(allocator)) orelse return null;1336 const err_union_val = (try err_union_ptr.pointerDeref(allocator)) orelse return null;
1253 break :blk err_union_val.castTag(.eu_payload).?.data;1337 break :blk err_union_val.castTag(.eu_payload).?.data;
1254 },1338 },
1339 .opt_payload_ptr => blk: {
1340 const opt_ptr = self.castTag(.opt_payload_ptr).?.data;
1341 const opt_val = (try opt_ptr.pointerDeref(allocator)) orelse return null;
1342 break :blk opt_val.castTag(.opt_payload).?.data;
1343 },
12551344
1256 .zero,1345 .zero,
1257 .one,1346 .one,
...@@ -1349,13 +1438,14 @@ pub const Value = extern union {...@@ -1349,13 +1438,14 @@ pub const Value = extern union {
1349 /// Valid for all types. Asserts the value is not undefined and not unreachable.1438 /// Valid for all types. Asserts the value is not undefined and not unreachable.
1350 pub fn isNull(self: Value) bool {1439 pub fn isNull(self: Value) bool {
1351 return switch (self.tag()) {1440 return switch (self.tag()) {
1441 .null_value => true,
1442 .opt_payload => false,
1443
1352 .undef => unreachable,1444 .undef => unreachable,
1353 .unreachable_value => unreachable,1445 .unreachable_value => unreachable,
1354 .inferred_alloc => unreachable,1446 .inferred_alloc => unreachable,
1355 .inferred_alloc_comptime => unreachable,1447 .inferred_alloc_comptime => unreachable,
1356 .null_value => true,1448 else => unreachable,
1357
1358 else => false,
1359 };1449 };
1360 }1450 }
13611451
...@@ -1385,6 +1475,10 @@ pub const Value = extern union {...@@ -1385,6 +1475,10 @@ pub const Value = extern union {
1385 return switch (val.tag()) {1475 return switch (val.tag()) {
1386 .eu_payload => true,1476 .eu_payload => true,
1387 else => false,1477 else => false,
1478
1479 .undef => unreachable,
1480 .inferred_alloc => unreachable,
1481 .inferred_alloc_comptime => unreachable,
1388 };1482 };
1389 }1483 }
13901484
...@@ -1514,6 +1608,31 @@ pub const Value = extern union {...@@ -1514,6 +1608,31 @@ pub const Value = extern union {
1514 return Tag.int_u64.create(arena, truncated);1608 return Tag.int_u64.create(arena, truncated);
1515 }1609 }
15161610
1611 pub fn shr(lhs: Value, rhs: Value, allocator: *Allocator) !Value {
1612 // TODO is this a performance issue? maybe we should try the operation without
1613 // resorting to BigInt first.
1614 var lhs_space: Value.BigIntSpace = undefined;
1615 const lhs_bigint = lhs.toBigInt(&lhs_space);
1616 const shift = rhs.toUnsignedInt();
1617 const limbs = try allocator.alloc(
1618 std.math.big.Limb,
1619 lhs_bigint.limbs.len - (shift / (@sizeOf(std.math.big.Limb) * 8)),
1620 );
1621 var result_bigint = BigIntMutable{
1622 .limbs = limbs,
1623 .positive = undefined,
1624 .len = undefined,
1625 };
1626 result_bigint.shiftRight(lhs_bigint, shift);
1627 const result_limbs = result_bigint.limbs[0..result_bigint.len];
1628
1629 if (result_bigint.positive) {
1630 return Value.Tag.int_big_positive.create(allocator, result_limbs);
1631 } else {
1632 return Value.Tag.int_big_negative.create(allocator, result_limbs);
1633 }
1634 }
1635
1517 pub fn floatAdd(1636 pub fn floatAdd(
1518 lhs: Value,1637 lhs: Value,
1519 rhs: Value,1638 rhs: Value,
test/behavior.zig+2-1
...@@ -9,12 +9,13 @@ test {...@@ -9,12 +9,13 @@ test {
9 _ = @import("behavior/pointers.zig");9 _ = @import("behavior/pointers.zig");
10 _ = @import("behavior/if.zig");10 _ = @import("behavior/if.zig");
11 _ = @import("behavior/cast.zig");11 _ = @import("behavior/cast.zig");
12 _ = @import("behavior/array.zig");
1213
13 if (!builtin.zig_is_stage2) {14 if (!builtin.zig_is_stage2) {
14 // Tests that only pass for stage1.15 // Tests that only pass for stage1.
15 _ = @import("behavior/align.zig");16 _ = @import("behavior/align.zig");
16 _ = @import("behavior/alignof.zig");17 _ = @import("behavior/alignof.zig");
17 _ = @import("behavior/array.zig");18 _ = @import("behavior/array_stage1.zig");
18 if (builtin.os.tag != .wasi) {19 if (builtin.os.tag != .wasi) {
19 _ = @import("behavior/asm.zig");20 _ = @import("behavior/asm.zig");
20 _ = @import("behavior/async_fn.zig");21 _ = @import("behavior/async_fn.zig");
test/behavior/array.zig-484
...@@ -3,487 +3,3 @@ const testing = std.testing;...@@ -3,487 +3,3 @@ const testing = std.testing;
3const mem = std.mem;3const mem = std.mem;
4const expect = testing.expect;4const expect = testing.expect;
5const expectEqual = testing.expectEqual;5const expectEqual = testing.expectEqual;
6
7test "arrays" {
8 var array: [5]u32 = undefined;
9
10 var i: u32 = 0;
11 while (i < 5) {
12 array[i] = i + 1;
13 i = array[i];
14 }
15
16 i = 0;
17 var accumulator = @as(u32, 0);
18 while (i < 5) {
19 accumulator += array[i];
20
21 i += 1;
22 }
23
24 try expect(accumulator == 15);
25 try expect(getArrayLen(&array) == 5);
26}
27fn getArrayLen(a: []const u32) usize {
28 return a.len;
29}
30
31test "array with sentinels" {
32 const S = struct {
33 fn doTheTest(is_ct: bool) !void {
34 if (is_ct) {
35 var zero_sized: [0:0xde]u8 = [_:0xde]u8{};
36 // Disabled at runtime because of
37 // https://github.com/ziglang/zig/issues/4372
38 try expectEqual(@as(u8, 0xde), zero_sized[0]);
39 var reinterpreted = @ptrCast(*[1]u8, &zero_sized);
40 try expectEqual(@as(u8, 0xde), reinterpreted[0]);
41 }
42 var arr: [3:0x55]u8 = undefined;
43 // Make sure the sentinel pointer is pointing after the last element
44 if (!is_ct) {
45 const sentinel_ptr = @ptrToInt(&arr[3]);
46 const last_elem_ptr = @ptrToInt(&arr[2]);
47 try expectEqual(@as(usize, 1), sentinel_ptr - last_elem_ptr);
48 }
49 // Make sure the sentinel is writeable
50 arr[3] = 0x55;
51 }
52 };
53
54 try S.doTheTest(false);
55 comptime try S.doTheTest(true);
56}
57
58test "void arrays" {
59 var array: [4]void = undefined;
60 array[0] = void{};
61 array[1] = array[2];
62 try expect(@sizeOf(@TypeOf(array)) == 0);
63 try expect(array.len == 4);
64}
65
66test "array literal" {
67 const hex_mult = [_]u16{
68 4096,
69 256,
70 16,
71 1,
72 };
73
74 try expect(hex_mult.len == 4);
75 try expect(hex_mult[1] == 256);
76}
77
78test "array dot len const expr" {
79 try expect(comptime x: {
80 break :x some_array.len == 4;
81 });
82}
83
84const ArrayDotLenConstExpr = struct {
85 y: [some_array.len]u8,
86};
87const some_array = [_]u8{
88 0,
89 1,
90 2,
91 3,
92};
93
94test "nested arrays" {
95 const array_of_strings = [_][]const u8{
96 "hello",
97 "this",
98 "is",
99 "my",
100 "thing",
101 };
102 for (array_of_strings) |s, i| {
103 if (i == 0) try expect(mem.eql(u8, s, "hello"));
104 if (i == 1) try expect(mem.eql(u8, s, "this"));
105 if (i == 2) try expect(mem.eql(u8, s, "is"));
106 if (i == 3) try expect(mem.eql(u8, s, "my"));
107 if (i == 4) try expect(mem.eql(u8, s, "thing"));
108 }
109}
110
111var s_array: [8]Sub = undefined;
112const Sub = struct {
113 b: u8,
114};
115const Str = struct {
116 a: []Sub,
117};
118test "set global var array via slice embedded in struct" {
119 var s = Str{ .a = s_array[0..] };
120
121 s.a[0].b = 1;
122 s.a[1].b = 2;
123 s.a[2].b = 3;
124
125 try expect(s_array[0].b == 1);
126 try expect(s_array[1].b == 2);
127 try expect(s_array[2].b == 3);
128}
129
130test "array literal with specified size" {
131 var array = [2]u8{
132 1,
133 2,
134 };
135 try expect(array[0] == 1);
136 try expect(array[1] == 2);
137}
138
139test "array len field" {
140 var arr = [4]u8{ 0, 0, 0, 0 };
141 var ptr = &arr;
142 try expect(arr.len == 4);
143 comptime try expect(arr.len == 4);
144 try expect(ptr.len == 4);
145 comptime try expect(ptr.len == 4);
146}
147
148test "single-item pointer to array indexing and slicing" {
149 try testSingleItemPtrArrayIndexSlice();
150 comptime try testSingleItemPtrArrayIndexSlice();
151}
152
153fn testSingleItemPtrArrayIndexSlice() !void {
154 {
155 var array: [4]u8 = "aaaa".*;
156 doSomeMangling(&array);
157 try expect(mem.eql(u8, "azya", &array));
158 }
159 {
160 var array = "aaaa".*;
161 doSomeMangling(&array);
162 try expect(mem.eql(u8, "azya", &array));
163 }
164}
165
166fn doSomeMangling(array: *[4]u8) void {
167 array[1] = 'z';
168 array[2..3][0] = 'y';
169}
170
171test "implicit cast single-item pointer" {
172 try testImplicitCastSingleItemPtr();
173 comptime try testImplicitCastSingleItemPtr();
174}
175
176fn testImplicitCastSingleItemPtr() !void {
177 var byte: u8 = 100;
178 const slice = @as(*[1]u8, &byte)[0..];
179 slice[0] += 1;
180 try expect(byte == 101);
181}
182
183fn testArrayByValAtComptime(b: [2]u8) u8 {
184 return b[0];
185}
186
187test "comptime evalutating function that takes array by value" {
188 const arr = [_]u8{ 0, 1 };
189 _ = comptime testArrayByValAtComptime(arr);
190 _ = comptime testArrayByValAtComptime(arr);
191}
192
193test "implicit comptime in array type size" {
194 var arr: [plusOne(10)]bool = undefined;
195 try expect(arr.len == 11);
196}
197
198fn plusOne(x: u32) u32 {
199 return x + 1;
200}
201
202test "runtime initialize array elem and then implicit cast to slice" {
203 var two: i32 = 2;
204 const x: []const i32 = &[_]i32{two};
205 try expect(x[0] == 2);
206}
207
208test "array literal as argument to function" {
209 const S = struct {
210 fn entry(two: i32) !void {
211 try foo(&[_]i32{
212 1,
213 2,
214 3,
215 });
216 try foo(&[_]i32{
217 1,
218 two,
219 3,
220 });
221 try foo2(true, &[_]i32{
222 1,
223 2,
224 3,
225 });
226 try foo2(true, &[_]i32{
227 1,
228 two,
229 3,
230 });
231 }
232 fn foo(x: []const i32) !void {
233 try expect(x[0] == 1);
234 try expect(x[1] == 2);
235 try expect(x[2] == 3);
236 }
237 fn foo2(trash: bool, x: []const i32) !void {
238 try expect(trash);
239 try expect(x[0] == 1);
240 try expect(x[1] == 2);
241 try expect(x[2] == 3);
242 }
243 };
244 try S.entry(2);
245 comptime try S.entry(2);
246}
247
248test "double nested array to const slice cast in array literal" {
249 const S = struct {
250 fn entry(two: i32) !void {
251 const cases = [_][]const []const i32{
252 &[_][]const i32{&[_]i32{1}},
253 &[_][]const i32{&[_]i32{ 2, 3 }},
254 &[_][]const i32{
255 &[_]i32{4},
256 &[_]i32{ 5, 6, 7 },
257 },
258 };
259 try check(&cases);
260
261 const cases2 = [_][]const i32{
262 &[_]i32{1},
263 &[_]i32{ two, 3 },
264 };
265 try expect(cases2.len == 2);
266 try expect(cases2[0].len == 1);
267 try expect(cases2[0][0] == 1);
268 try expect(cases2[1].len == 2);
269 try expect(cases2[1][0] == 2);
270 try expect(cases2[1][1] == 3);
271
272 const cases3 = [_][]const []const i32{
273 &[_][]const i32{&[_]i32{1}},
274 &[_][]const i32{&[_]i32{ two, 3 }},
275 &[_][]const i32{
276 &[_]i32{4},
277 &[_]i32{ 5, 6, 7 },
278 },
279 };
280 try check(&cases3);
281 }
282
283 fn check(cases: []const []const []const i32) !void {
284 try expect(cases.len == 3);
285 try expect(cases[0].len == 1);
286 try expect(cases[0][0].len == 1);
287 try expect(cases[0][0][0] == 1);
288 try expect(cases[1].len == 1);
289 try expect(cases[1][0].len == 2);
290 try expect(cases[1][0][0] == 2);
291 try expect(cases[1][0][1] == 3);
292 try expect(cases[2].len == 2);
293 try expect(cases[2][0].len == 1);
294 try expect(cases[2][0][0] == 4);
295 try expect(cases[2][1].len == 3);
296 try expect(cases[2][1][0] == 5);
297 try expect(cases[2][1][1] == 6);
298 try expect(cases[2][1][2] == 7);
299 }
300 };
301 try S.entry(2);
302 comptime try S.entry(2);
303}
304
305test "read/write through global variable array of struct fields initialized via array mult" {
306 const S = struct {
307 fn doTheTest() !void {
308 try expect(storage[0].term == 1);
309 storage[0] = MyStruct{ .term = 123 };
310 try expect(storage[0].term == 123);
311 }
312
313 pub const MyStruct = struct {
314 term: usize,
315 };
316
317 var storage: [1]MyStruct = [_]MyStruct{MyStruct{ .term = 1 }} ** 1;
318 };
319 try S.doTheTest();
320}
321
322test "implicit cast zero sized array ptr to slice" {
323 {
324 var b = "".*;
325 const c: []const u8 = &b;
326 try expect(c.len == 0);
327 }
328 {
329 var b: [0]u8 = "".*;
330 const c: []const u8 = &b;
331 try expect(c.len == 0);
332 }
333}
334
335test "anonymous list literal syntax" {
336 const S = struct {
337 fn doTheTest() !void {
338 var array: [4]u8 = .{ 1, 2, 3, 4 };
339 try expect(array[0] == 1);
340 try expect(array[1] == 2);
341 try expect(array[2] == 3);
342 try expect(array[3] == 4);
343 }
344 };
345 try S.doTheTest();
346 comptime try S.doTheTest();
347}
348
349test "anonymous literal in array" {
350 const S = struct {
351 const Foo = struct {
352 a: usize = 2,
353 b: usize = 4,
354 };
355 fn doTheTest() !void {
356 var array: [2]Foo = .{
357 .{ .a = 3 },
358 .{ .b = 3 },
359 };
360 try expect(array[0].a == 3);
361 try expect(array[0].b == 4);
362 try expect(array[1].a == 2);
363 try expect(array[1].b == 3);
364 }
365 };
366 try S.doTheTest();
367 comptime try S.doTheTest();
368}
369
370test "access the null element of a null terminated array" {
371 const S = struct {
372 fn doTheTest() !void {
373 var array: [4:0]u8 = .{ 'a', 'o', 'e', 'u' };
374 try expect(array[4] == 0);
375 var len: usize = 4;
376 try expect(array[len] == 0);
377 }
378 };
379 try S.doTheTest();
380 comptime try S.doTheTest();
381}
382
383test "type deduction for array subscript expression" {
384 const S = struct {
385 fn doTheTest() !void {
386 var array = [_]u8{ 0x55, 0xAA };
387 var v0 = true;
388 try expectEqual(@as(u8, 0xAA), array[if (v0) 1 else 0]);
389 var v1 = false;
390 try expectEqual(@as(u8, 0x55), array[if (v1) 1 else 0]);
391 }
392 };
393 try S.doTheTest();
394 comptime try S.doTheTest();
395}
396
397test "sentinel element count towards the ABI size calculation" {
398 const S = struct {
399 fn doTheTest() !void {
400 const T = packed struct {
401 fill_pre: u8 = 0x55,
402 data: [0:0]u8 = undefined,
403 fill_post: u8 = 0xAA,
404 };
405 var x = T{};
406 var as_slice = mem.asBytes(&x);
407 try expectEqual(@as(usize, 3), as_slice.len);
408 try expectEqual(@as(u8, 0x55), as_slice[0]);
409 try expectEqual(@as(u8, 0xAA), as_slice[2]);
410 }
411 };
412
413 try S.doTheTest();
414 comptime try S.doTheTest();
415}
416
417test "zero-sized array with recursive type definition" {
418 const U = struct {
419 fn foo(comptime T: type, comptime n: usize) type {
420 return struct {
421 s: [n]T,
422 x: usize = n,
423 };
424 }
425 };
426
427 const S = struct {
428 list: U.foo(@This(), 0),
429 };
430
431 var t: S = .{ .list = .{ .s = undefined } };
432 try expectEqual(@as(usize, 0), t.list.x);
433}
434
435test "type coercion of anon struct literal to array" {
436 const S = struct {
437 const U = union {
438 a: u32,
439 b: bool,
440 c: []const u8,
441 };
442
443 fn doTheTest() !void {
444 var x1: u8 = 42;
445 const t1 = .{ x1, 56, 54 };
446 var arr1: [3]u8 = t1;
447 try expect(arr1[0] == 42);
448 try expect(arr1[1] == 56);
449 try expect(arr1[2] == 54);
450
451 var x2: U = .{ .a = 42 };
452 const t2 = .{ x2, .{ .b = true }, .{ .c = "hello" } };
453 var arr2: [3]U = t2;
454 try expect(arr2[0].a == 42);
455 try expect(arr2[1].b == true);
456 try expect(mem.eql(u8, arr2[2].c, "hello"));
457 }
458 };
459 try S.doTheTest();
460 comptime try S.doTheTest();
461}
462
463test "type coercion of pointer to anon struct literal to pointer to array" {
464 const S = struct {
465 const U = union {
466 a: u32,
467 b: bool,
468 c: []const u8,
469 };
470
471 fn doTheTest() !void {
472 var x1: u8 = 42;
473 const t1 = &.{ x1, 56, 54 };
474 var arr1: *const [3]u8 = t1;
475 try expect(arr1[0] == 42);
476 try expect(arr1[1] == 56);
477 try expect(arr1[2] == 54);
478
479 var x2: U = .{ .a = 42 };
480 const t2 = &.{ x2, .{ .b = true }, .{ .c = "hello" } };
481 var arr2: *const [3]U = t2;
482 try expect(arr2[0].a == 42);
483 try expect(arr2[1].b == true);
484 try expect(mem.eql(u8, arr2[2].c, "hello"));
485 }
486 };
487 try S.doTheTest();
488 comptime try S.doTheTest();
489}
test/behavior/array_stage1.zig created+489
...@@ -0,0 +1,489 @@
1const std = @import("std");
2const testing = std.testing;
3const mem = std.mem;
4const expect = testing.expect;
5const expectEqual = testing.expectEqual;
6
7test "arrays" {
8 var array: [5]u32 = undefined;
9
10 var i: u32 = 0;
11 while (i < 5) {
12 array[i] = i + 1;
13 i = array[i];
14 }
15
16 i = 0;
17 var accumulator = @as(u32, 0);
18 while (i < 5) {
19 accumulator += array[i];
20
21 i += 1;
22 }
23
24 try expect(accumulator == 15);
25 try expect(getArrayLen(&array) == 5);
26}
27fn getArrayLen(a: []const u32) usize {
28 return a.len;
29}
30
31test "array with sentinels" {
32 const S = struct {
33 fn doTheTest(is_ct: bool) !void {
34 if (is_ct) {
35 var zero_sized: [0:0xde]u8 = [_:0xde]u8{};
36 // Disabled at runtime because of
37 // https://github.com/ziglang/zig/issues/4372
38 try expectEqual(@as(u8, 0xde), zero_sized[0]);
39 var reinterpreted = @ptrCast(*[1]u8, &zero_sized);
40 try expectEqual(@as(u8, 0xde), reinterpreted[0]);
41 }
42 var arr: [3:0x55]u8 = undefined;
43 // Make sure the sentinel pointer is pointing after the last element
44 if (!is_ct) {
45 const sentinel_ptr = @ptrToInt(&arr[3]);
46 const last_elem_ptr = @ptrToInt(&arr[2]);
47 try expectEqual(@as(usize, 1), sentinel_ptr - last_elem_ptr);
48 }
49 // Make sure the sentinel is writeable
50 arr[3] = 0x55;
51 }
52 };
53
54 try S.doTheTest(false);
55 comptime try S.doTheTest(true);
56}
57
58test "void arrays" {
59 var array: [4]void = undefined;
60 array[0] = void{};
61 array[1] = array[2];
62 try expect(@sizeOf(@TypeOf(array)) == 0);
63 try expect(array.len == 4);
64}
65
66test "array literal" {
67 const hex_mult = [_]u16{
68 4096,
69 256,
70 16,
71 1,
72 };
73
74 try expect(hex_mult.len == 4);
75 try expect(hex_mult[1] == 256);
76}
77
78test "array dot len const expr" {
79 try expect(comptime x: {
80 break :x some_array.len == 4;
81 });
82}
83
84const ArrayDotLenConstExpr = struct {
85 y: [some_array.len]u8,
86};
87const some_array = [_]u8{
88 0,
89 1,
90 2,
91 3,
92};
93
94test "nested arrays" {
95 const array_of_strings = [_][]const u8{
96 "hello",
97 "this",
98 "is",
99 "my",
100 "thing",
101 };
102 for (array_of_strings) |s, i| {
103 if (i == 0) try expect(mem.eql(u8, s, "hello"));
104 if (i == 1) try expect(mem.eql(u8, s, "this"));
105 if (i == 2) try expect(mem.eql(u8, s, "is"));
106 if (i == 3) try expect(mem.eql(u8, s, "my"));
107 if (i == 4) try expect(mem.eql(u8, s, "thing"));
108 }
109}
110
111var s_array: [8]Sub = undefined;
112const Sub = struct {
113 b: u8,
114};
115const Str = struct {
116 a: []Sub,
117};
118test "set global var array via slice embedded in struct" {
119 var s = Str{ .a = s_array[0..] };
120
121 s.a[0].b = 1;
122 s.a[1].b = 2;
123 s.a[2].b = 3;
124
125 try expect(s_array[0].b == 1);
126 try expect(s_array[1].b == 2);
127 try expect(s_array[2].b == 3);
128}
129
130test "array literal with specified size" {
131 var array = [2]u8{
132 1,
133 2,
134 };
135 try expect(array[0] == 1);
136 try expect(array[1] == 2);
137}
138
139test "array len field" {
140 var arr = [4]u8{ 0, 0, 0, 0 };
141 var ptr = &arr;
142 try expect(arr.len == 4);
143 comptime try expect(arr.len == 4);
144 try expect(ptr.len == 4);
145 comptime try expect(ptr.len == 4);
146}
147
148test "single-item pointer to array indexing and slicing" {
149 try testSingleItemPtrArrayIndexSlice();
150 comptime try testSingleItemPtrArrayIndexSlice();
151}
152
153fn testSingleItemPtrArrayIndexSlice() !void {
154 {
155 var array: [4]u8 = "aaaa".*;
156 doSomeMangling(&array);
157 try expect(mem.eql(u8, "azya", &array));
158 }
159 {
160 var array = "aaaa".*;
161 doSomeMangling(&array);
162 try expect(mem.eql(u8, "azya", &array));
163 }
164}
165
166fn doSomeMangling(array: *[4]u8) void {
167 array[1] = 'z';
168 array[2..3][0] = 'y';
169}
170
171test "implicit cast single-item pointer" {
172 try testImplicitCastSingleItemPtr();
173 comptime try testImplicitCastSingleItemPtr();
174}
175
176fn testImplicitCastSingleItemPtr() !void {
177 var byte: u8 = 100;
178 const slice = @as(*[1]u8, &byte)[0..];
179 slice[0] += 1;
180 try expect(byte == 101);
181}
182
183fn testArrayByValAtComptime(b: [2]u8) u8 {
184 return b[0];
185}
186
187test "comptime evalutating function that takes array by value" {
188 const arr = [_]u8{ 0, 1 };
189 _ = comptime testArrayByValAtComptime(arr);
190 _ = comptime testArrayByValAtComptime(arr);
191}
192
193test "implicit comptime in array type size" {
194 var arr: [plusOne(10)]bool = undefined;
195 try expect(arr.len == 11);
196}
197
198fn plusOne(x: u32) u32 {
199 return x + 1;
200}
201
202test "runtime initialize array elem and then implicit cast to slice" {
203 var two: i32 = 2;
204 const x: []const i32 = &[_]i32{two};
205 try expect(x[0] == 2);
206}
207
208test "array literal as argument to function" {
209 const S = struct {
210 fn entry(two: i32) !void {
211 try foo(&[_]i32{
212 1,
213 2,
214 3,
215 });
216 try foo(&[_]i32{
217 1,
218 two,
219 3,
220 });
221 try foo2(true, &[_]i32{
222 1,
223 2,
224 3,
225 });
226 try foo2(true, &[_]i32{
227 1,
228 two,
229 3,
230 });
231 }
232 fn foo(x: []const i32) !void {
233 try expect(x[0] == 1);
234 try expect(x[1] == 2);
235 try expect(x[2] == 3);
236 }
237 fn foo2(trash: bool, x: []const i32) !void {
238 try expect(trash);
239 try expect(x[0] == 1);
240 try expect(x[1] == 2);
241 try expect(x[2] == 3);
242 }
243 };
244 try S.entry(2);
245 comptime try S.entry(2);
246}
247
248test "double nested array to const slice cast in array literal" {
249 const S = struct {
250 fn entry(two: i32) !void {
251 const cases = [_][]const []const i32{
252 &[_][]const i32{&[_]i32{1}},
253 &[_][]const i32{&[_]i32{ 2, 3 }},
254 &[_][]const i32{
255 &[_]i32{4},
256 &[_]i32{ 5, 6, 7 },
257 },
258 };
259 try check(&cases);
260
261 const cases2 = [_][]const i32{
262 &[_]i32{1},
263 &[_]i32{ two, 3 },
264 };
265 try expect(cases2.len == 2);
266 try expect(cases2[0].len == 1);
267 try expect(cases2[0][0] == 1);
268 try expect(cases2[1].len == 2);
269 try expect(cases2[1][0] == 2);
270 try expect(cases2[1][1] == 3);
271
272 const cases3 = [_][]const []const i32{
273 &[_][]const i32{&[_]i32{1}},
274 &[_][]const i32{&[_]i32{ two, 3 }},
275 &[_][]const i32{
276 &[_]i32{4},
277 &[_]i32{ 5, 6, 7 },
278 },
279 };
280 try check(&cases3);
281 }
282
283 fn check(cases: []const []const []const i32) !void {
284 try expect(cases.len == 3);
285 try expect(cases[0].len == 1);
286 try expect(cases[0][0].len == 1);
287 try expect(cases[0][0][0] == 1);
288 try expect(cases[1].len == 1);
289 try expect(cases[1][0].len == 2);
290 try expect(cases[1][0][0] == 2);
291 try expect(cases[1][0][1] == 3);
292 try expect(cases[2].len == 2);
293 try expect(cases[2][0].len == 1);
294 try expect(cases[2][0][0] == 4);
295 try expect(cases[2][1].len == 3);
296 try expect(cases[2][1][0] == 5);
297 try expect(cases[2][1][1] == 6);
298 try expect(cases[2][1][2] == 7);
299 }
300 };
301 try S.entry(2);
302 comptime try S.entry(2);
303}
304
305test "read/write through global variable array of struct fields initialized via array mult" {
306 const S = struct {
307 fn doTheTest() !void {
308 try expect(storage[0].term == 1);
309 storage[0] = MyStruct{ .term = 123 };
310 try expect(storage[0].term == 123);
311 }
312
313 pub const MyStruct = struct {
314 term: usize,
315 };
316
317 var storage: [1]MyStruct = [_]MyStruct{MyStruct{ .term = 1 }} ** 1;
318 };
319 try S.doTheTest();
320}
321
322test "implicit cast zero sized array ptr to slice" {
323 {
324 var b = "".*;
325 const c: []const u8 = &b;
326 try expect(c.len == 0);
327 }
328 {
329 var b: [0]u8 = "".*;
330 const c: []const u8 = &b;
331 try expect(c.len == 0);
332 }
333}
334
335test "anonymous list literal syntax" {
336 const S = struct {
337 fn doTheTest() !void {
338 var array: [4]u8 = .{ 1, 2, 3, 4 };
339 try expect(array[0] == 1);
340 try expect(array[1] == 2);
341 try expect(array[2] == 3);
342 try expect(array[3] == 4);
343 }
344 };
345 try S.doTheTest();
346 comptime try S.doTheTest();
347}
348
349test "anonymous literal in array" {
350 const S = struct {
351 const Foo = struct {
352 a: usize = 2,
353 b: usize = 4,
354 };
355 fn doTheTest() !void {
356 var array: [2]Foo = .{
357 .{ .a = 3 },
358 .{ .b = 3 },
359 };
360 try expect(array[0].a == 3);
361 try expect(array[0].b == 4);
362 try expect(array[1].a == 2);
363 try expect(array[1].b == 3);
364 }
365 };
366 try S.doTheTest();
367 comptime try S.doTheTest();
368}
369
370test "access the null element of a null terminated array" {
371 const S = struct {
372 fn doTheTest() !void {
373 var array: [4:0]u8 = .{ 'a', 'o', 'e', 'u' };
374 try expect(array[4] == 0);
375 var len: usize = 4;
376 try expect(array[len] == 0);
377 }
378 };
379 try S.doTheTest();
380 comptime try S.doTheTest();
381}
382
383test "type deduction for array subscript expression" {
384 const S = struct {
385 fn doTheTest() !void {
386 var array = [_]u8{ 0x55, 0xAA };
387 var v0 = true;
388 try expectEqual(@as(u8, 0xAA), array[if (v0) 1 else 0]);
389 var v1 = false;
390 try expectEqual(@as(u8, 0x55), array[if (v1) 1 else 0]);
391 }
392 };
393 try S.doTheTest();
394 comptime try S.doTheTest();
395}
396
397test "sentinel element count towards the ABI size calculation" {
398 const S = struct {
399 fn doTheTest() !void {
400 const T = packed struct {
401 fill_pre: u8 = 0x55,
402 data: [0:0]u8 = undefined,
403 fill_post: u8 = 0xAA,
404 };
405 var x = T{};
406 var as_slice = mem.asBytes(&x);
407 try expectEqual(@as(usize, 3), as_slice.len);
408 try expectEqual(@as(u8, 0x55), as_slice[0]);
409 try expectEqual(@as(u8, 0xAA), as_slice[2]);
410 }
411 };
412
413 try S.doTheTest();
414 comptime try S.doTheTest();
415}
416
417test "zero-sized array with recursive type definition" {
418 const U = struct {
419 fn foo(comptime T: type, comptime n: usize) type {
420 return struct {
421 s: [n]T,
422 x: usize = n,
423 };
424 }
425 };
426
427 const S = struct {
428 list: U.foo(@This(), 0),
429 };
430
431 var t: S = .{ .list = .{ .s = undefined } };
432 try expectEqual(@as(usize, 0), t.list.x);
433}
434
435test "type coercion of anon struct literal to array" {
436 const S = struct {
437 const U = union {
438 a: u32,
439 b: bool,
440 c: []const u8,
441 };
442
443 fn doTheTest() !void {
444 var x1: u8 = 42;
445 const t1 = .{ x1, 56, 54 };
446 var arr1: [3]u8 = t1;
447 try expect(arr1[0] == 42);
448 try expect(arr1[1] == 56);
449 try expect(arr1[2] == 54);
450
451 var x2: U = .{ .a = 42 };
452 const t2 = .{ x2, .{ .b = true }, .{ .c = "hello" } };
453 var arr2: [3]U = t2;
454 try expect(arr2[0].a == 42);
455 try expect(arr2[1].b == true);
456 try expect(mem.eql(u8, arr2[2].c, "hello"));
457 }
458 };
459 try S.doTheTest();
460 comptime try S.doTheTest();
461}
462
463test "type coercion of pointer to anon struct literal to pointer to array" {
464 const S = struct {
465 const U = union {
466 a: u32,
467 b: bool,
468 c: []const u8,
469 };
470
471 fn doTheTest() !void {
472 var x1: u8 = 42;
473 const t1 = &.{ x1, 56, 54 };
474 var arr1: *const [3]u8 = t1;
475 try expect(arr1[0] == 42);
476 try expect(arr1[1] == 56);
477 try expect(arr1[2] == 54);
478
479 var x2: U = .{ .a = 42 };
480 const t2 = &.{ x2, .{ .b = true }, .{ .c = "hello" } };
481 var arr2: *const [3]U = t2;
482 try expect(arr2[0].a == 42);
483 try expect(arr2[1].b == true);
484 try expect(mem.eql(u8, arr2[2].c, "hello"));
485 }
486 };
487 try S.doTheTest();
488 comptime try S.doTheTest();
489}
test/behavior/enum.zig+1-1
...@@ -203,7 +203,7 @@ test "int to enum" {...@@ -203,7 +203,7 @@ test "int to enum" {
203 try testIntToEnumEval(3);203 try testIntToEnumEval(3);
204}204}
205fn testIntToEnumEval(x: i32) !void {205fn testIntToEnumEval(x: i32) !void {
206 try expect(@intToEnum(IntToEnumNumber, @intCast(u3, x)) == IntToEnumNumber.Three);206 try expect(@intToEnum(IntToEnumNumber, x) == IntToEnumNumber.Three);
207}207}
208const IntToEnumNumber = enum {208const IntToEnumNumber = enum {
209 Zero,209 Zero,
test/behavior/error.zig+6-6
...@@ -412,19 +412,19 @@ test "function pointer with return type that is error union with payload which i...@@ -412,19 +412,19 @@ test "function pointer with return type that is error union with payload which i
412test "return result loc as peer result loc in inferred error set function" {412test "return result loc as peer result loc in inferred error set function" {
413 const S = struct {413 const S = struct {
414 fn doTheTest() !void {414 fn doTheTest() !void {
415 if (foo(2)) |x| {415 if (quux(2)) |x| {
416 try expect(x.Two);416 try expect(x.Two);
417 } else |e| switch (e) {417 } else |e| switch (e) {
418 error.Whatever => @panic("fail"),418 error.Whatever => @panic("fail"),
419 }419 }
420 try expectError(error.Whatever, foo(99));420 try expectError(error.Whatever, quux(99));
421 }421 }
422 const FormValue = union(enum) {422 const FormValue = union(enum) {
423 One: void,423 One: void,
424 Two: bool,424 Two: bool,
425 };425 };
426426
427 fn foo(id: u64) !FormValue {427 fn quux(id: u64) !FormValue {
428 return switch (id) {428 return switch (id) {
429 2 => FormValue{ .Two = true },429 2 => FormValue{ .Two = true },
430 1 => FormValue{ .One = {} },430 1 => FormValue{ .One = {} },
...@@ -452,11 +452,11 @@ test "error payload type is correctly resolved" {...@@ -452,11 +452,11 @@ test "error payload type is correctly resolved" {
452452
453test "error union comptime caching" {453test "error union comptime caching" {
454 const S = struct {454 const S = struct {
455 fn foo(comptime arg: anytype) void {455 fn quux(comptime arg: anytype) void {
456 arg catch {};456 arg catch {};
457 }457 }
458 };458 };
459459
460 S.foo(@as(anyerror!void, {}));460 S.quux(@as(anyerror!void, {}));
461 S.foo(@as(anyerror!void, {}));461 S.quux(@as(anyerror!void, {}));
462}462}
test/behavior/eval.zig+31
...@@ -130,3 +130,34 @@ test "no undeclared identifier error in unanalyzed branches" {...@@ -130,3 +130,34 @@ test "no undeclared identifier error in unanalyzed branches" {
130 lol_this_doesnt_exist = nonsense;130 lol_this_doesnt_exist = nonsense;
131 }131 }
132}132}
133
134test "a type constructed in a global expression" {
135 var l: List = undefined;
136 l.array[0] = 10;
137 l.array[1] = 11;
138 l.array[2] = 12;
139 const ptr = @ptrCast([*]u8, &l.array);
140 try expect(ptr[0] == 10);
141 try expect(ptr[1] == 11);
142 try expect(ptr[2] == 12);
143}
144
145const List = blk: {
146 const T = [10]u8;
147 break :blk struct {
148 array: T,
149 };
150};
151
152test "comptime function with the same args is memoized" {
153 comptime {
154 try expect(MakeType(i32) == MakeType(i32));
155 try expect(MakeType(i32) != MakeType(f64));
156 }
157}
158
159fn MakeType(comptime T: type) type {
160 return struct {
161 field: T,
162 };
163}
test/behavior/eval_stage1.zig-13
...@@ -356,19 +356,6 @@ test "binary math operator in partially inlined function" {...@@ -356,19 +356,6 @@ test "binary math operator in partially inlined function" {
356 try expect(s[3] == 0xd0e0f10);356 try expect(s[3] == 0xd0e0f10);
357}357}
358358
359test "comptime function with the same args is memoized" {
360 comptime {
361 try expect(MakeType(i32) == MakeType(i32));
362 try expect(MakeType(i32) != MakeType(f64));
363 }
364}
365
366fn MakeType(comptime T: type) type {
367 return struct {
368 field: T,
369 };
370}
371
372test "comptime function with mutable pointer is not memoized" {359test "comptime function with mutable pointer is not memoized" {
373 comptime {360 comptime {
374 var x: i32 = 1;361 var x: i32 = 1;
test/behavior/generics.zig+39
...@@ -78,3 +78,42 @@ fn max_i32(a: i32, b: i32) i32 {...@@ -78,3 +78,42 @@ fn max_i32(a: i32, b: i32) i32 {
78fn max_f64(a: f64, b: f64) f64 {78fn max_f64(a: f64, b: f64) f64 {
79 return max_anytype(a, b);79 return max_anytype(a, b);
80}80}
81
82test "type constructed by comptime function call" {
83 var l: SimpleList(10) = undefined;
84 l.array[0] = 10;
85 l.array[1] = 11;
86 l.array[2] = 12;
87 const ptr = @ptrCast([*]u8, &l.array);
88 try expect(ptr[0] == 10);
89 try expect(ptr[1] == 11);
90 try expect(ptr[2] == 12);
91}
92
93fn SimpleList(comptime L: usize) type {
94 var T = u8;
95 return struct {
96 array: [L]T,
97 };
98}
99
100test "function with return type type" {
101 var list: List(i32) = undefined;
102 var list2: List(i32) = undefined;
103 list.length = 10;
104 list2.length = 10;
105 try expect(list.prealloc_items.len == 8);
106 try expect(list2.prealloc_items.len == 8);
107}
108
109pub fn List(comptime T: type) type {
110 return SmallList(T, 8);
111}
112
113pub fn SmallList(comptime T: type, comptime STATIC_SIZE: usize) type {
114 return struct {
115 items: []T,
116 length: usize,
117 prealloc_items: [STATIC_SIZE]T,
118 };
119}
test/behavior/generics_stage1.zig-21
...@@ -3,27 +3,6 @@ const testing = std.testing;...@@ -3,27 +3,6 @@ const testing = std.testing;
3const expect = testing.expect;3const expect = testing.expect;
4const expectEqual = testing.expectEqual;4const expectEqual = testing.expectEqual;
55
6pub fn List(comptime T: type) type {
7 return SmallList(T, 8);
8}
9
10pub fn SmallList(comptime T: type, comptime STATIC_SIZE: usize) type {
11 return struct {
12 items: []T,
13 length: usize,
14 prealloc_items: [STATIC_SIZE]T,
15 };
16}
17
18test "function with return type type" {
19 var list: List(i32) = undefined;
20 var list2: List(i32) = undefined;
21 list.length = 10;
22 list2.length = 10;
23 try expect(list.prealloc_items.len == 8);
24 try expect(list2.prealloc_items.len == 8);
25}
26
27test "generic struct" {6test "generic struct" {
28 var a1 = GenNode(i32){7 var a1 = GenNode(i32){
29 .value = 13,8 .value = 13,
test/behavior/misc.zig+33
...@@ -505,3 +505,36 @@ test "lazy typeInfo value as generic parameter" {...@@ -505,3 +505,36 @@ test "lazy typeInfo value as generic parameter" {
505 };505 };
506 S.foo(@typeInfo(@TypeOf(.{})));506 S.foo(@typeInfo(@TypeOf(.{})));
507}507}
508
509fn A() type {
510 return struct {
511 b: B(),
512
513 const Self = @This();
514
515 fn B() type {
516 return struct {
517 const Self = @This();
518 };
519 }
520 };
521}
522test "non-ambiguous reference of shadowed decls" {
523 try expect(A().B().Self != A().Self);
524}
525
526test "use of declaration with same name as primitive" {
527 const S = struct {
528 const @"u8" = u16;
529 const alias = @"u8";
530 };
531 const a: S.u8 = 300;
532 try expect(a == 300);
533
534 const b: S.alias = 300;
535 try expect(b == 300);
536
537 const @"u8" = u16;
538 const c: @"u8" = 300;
539 try expect(c == 300);
540}
test/behavior/struct.zig+2-2
...@@ -162,14 +162,14 @@ const MemberFnRand = struct {...@@ -162,14 +162,14 @@ const MemberFnRand = struct {
162};162};
163163
164test "return struct byval from function" {164test "return struct byval from function" {
165 const bar = makeBar(1234, 5678);165 const bar = makeBar2(1234, 5678);
166 try expect(bar.y == 5678);166 try expect(bar.y == 5678);
167}167}
168const Bar = struct {168const Bar = struct {
169 x: i32,169 x: i32,
170 y: i32,170 y: i32,
171};171};
172fn makeBar(x: i32, y: i32) Bar {172fn makeBar2(x: i32, y: i32) Bar {
173 return Bar{173 return Bar{
174 .x = x,174 .x = x,
175 .y = y,175 .y = y,
test/cases.zig+1-1
...@@ -26,7 +26,7 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -26,7 +26,7 @@ pub fn addCases(ctx: *TestContext) !void {
26 var case = ctx.exe("hello world with updates", linux_x64);26 var case = ctx.exe("hello world with updates", linux_x64);
2727
28 case.addError("", &[_][]const u8{28 case.addError("", &[_][]const u8{
29 ":95:9: error: struct 'tmp.tmp' has no member named 'main'",29 ":90:9: error: struct 'tmp.tmp' has no member named 'main'",
30 });30 });
3131
32 // Incorrect return type32 // Incorrect return type
test/compare_output.zig+2-20
...@@ -585,16 +585,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -585,16 +585,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
585 \\ comptime format: []const u8,585 \\ comptime format: []const u8,
586 \\ args: anytype,586 \\ args: anytype,
587 \\) void {587 \\) void {
588 \\ const level_txt = switch (level) {588 \\ const level_txt = comptime level.asText();
589 \\ .emerg => "emergency",
590 \\ .alert => "alert",
591 \\ .crit => "critical",
592 \\ .err => "error",
593 \\ .warn => "warning",
594 \\ .notice => "notice",
595 \\ .info => "info",
596 \\ .debug => "debug",
597 \\ };
598 \\ const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";589 \\ const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
599 \\ const stdout = std.io.getStdOut().writer();590 \\ const stdout = std.io.getStdOut().writer();
600 \\ nosuspend stdout.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;591 \\ nosuspend stdout.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;
...@@ -638,16 +629,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -638,16 +629,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
638 \\ comptime format: []const u8,629 \\ comptime format: []const u8,
639 \\ args: anytype,630 \\ args: anytype,
640 \\) void {631 \\) void {
641 \\ const level_txt = switch (level) {632 \\ const level_txt = comptime level.asText();
642 \\ .emerg => "emergency",
643 \\ .alert => "alert",
644 \\ .crit => "critical",
645 \\ .err => "error",
646 \\ .warn => "warning",
647 \\ .notice => "notice",
648 \\ .info => "info",
649 \\ .debug => "debug",
650 \\ };
651 \\ const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";633 \\ const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
652 \\ const stdout = std.io.getStdOut().writer();634 \\ const stdout = std.io.getStdOut().writer();
653 \\ nosuspend stdout.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;635 \\ nosuspend stdout.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;
test/compile_errors.zig+41-24
...@@ -6969,29 +6969,24 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -6969,29 +6969,24 @@ pub fn addCases(ctx: *TestContext) !void {
6969 "tmp.zig:2:30: error: cannot set section of local variable 'foo'",6969 "tmp.zig:2:30: error: cannot set section of local variable 'foo'",
6970 });6970 });
69716971
6972 ctx.objErrStage1("inner struct member shadowing outer struct member",6972 ctx.objErrStage1("ambiguous decl reference",
6973 \\fn A() type {6973 \\fn foo() void {}
6974 \\ return struct {6974 \\fn bar() void {
6975 \\ b: B(),6975 \\ const S = struct {
6976 \\6976 \\ fn baz() void {
6977 \\ const Self = @This();6977 \\ foo();
6978 \\
6979 \\ fn B() type {
6980 \\ return struct {
6981 \\ const Self = @This();
6982 \\ };
6983 \\ }6978 \\ }
6979 \\ fn foo() void {}
6984 \\ };6980 \\ };
6981 \\ S.baz();
6985 \\}6982 \\}
6986 \\comptime {6983 \\export fn entry() void {
6987 \\ assert(A().B().Self != A().Self);6984 \\ bar();
6988 \\}
6989 \\fn assert(ok: bool) void {
6990 \\ if (!ok) unreachable;
6991 \\}6985 \\}
6992 , &[_][]const u8{6986 , &[_][]const u8{
6993 "tmp.zig:9:17: error: redefinition of 'Self'",6987 "tmp.zig:5:13: error: ambiguous reference",
6994 "tmp.zig:5:9: note: previous definition here",6988 "tmp.zig:7:9: note: declared here",
6989 "tmp.zig:1:1: note: also declared here",
6995 });6990 });
69966991
6997 ctx.objErrStage1("while expected bool, got optional",6992 ctx.objErrStage1("while expected bool, got optional",
...@@ -7263,14 +7258,36 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -7263,14 +7258,36 @@ pub fn addCases(ctx: *TestContext) !void {
7263 "tmp.zig:2:17: error: expected type 'u3', found 'u8'",7258 "tmp.zig:2:17: error: expected type 'u3', found 'u8'",
7264 });7259 });
72657260
7266 ctx.objErrStage1("globally shadowing a primitive type",7261 ctx.objErrStage1("locally shadowing a primitive type",
7267 \\const u16 = u8;7262 \\export fn foo() void {
7263 \\ const u8 = u16;
7264 \\ const a: u8 = 300;
7265 \\ _ = a;
7266 \\}
7267 , &[_][]const u8{
7268 "tmp.zig:2:11: error: name shadows primitive 'u8'",
7269 "tmp.zig:2:11: note: consider using @\"u8\" to disambiguate",
7270 });
7271
7272 ctx.objErrStage1("primitives take precedence over declarations",
7273 \\const @"u8" = u16;
7274 \\export fn entry() void {
7275 \\ const a: u8 = 300;
7276 \\ _ = a;
7277 \\}
7278 , &[_][]const u8{
7279 "tmp.zig:3:19: error: integer value 300 cannot be coerced to type 'u8'",
7280 });
7281
7282 ctx.objErrStage1("declaration with same name as primitive must use special syntax",
7283 \\const u8 = u16;
7268 \\export fn entry() void {7284 \\export fn entry() void {
7269 \\ const a: u16 = 300;7285 \\ const a: u8 = 300;
7270 \\ _ = a;7286 \\ _ = a;
7271 \\}7287 \\}
7272 , &[_][]const u8{7288 , &[_][]const u8{
7273 "tmp.zig:1:1: error: declaration shadows primitive type 'u16'",7289 "tmp.zig:1:7: error: name shadows primitive 'u8'",
7290 "tmp.zig:1:7: note: consider using @\"u8\" to disambiguate",
7274 });7291 });
72757292
7276 ctx.objErrStage1("implicitly increasing pointer alignment",7293 ctx.objErrStage1("implicitly increasing pointer alignment",
...@@ -7691,12 +7708,12 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -7691,12 +7708,12 @@ pub fn addCases(ctx: *TestContext) !void {
7691 \\};7708 \\};
7692 \\7709 \\
7693 \\export fn entry() void {7710 \\export fn entry() void {
7694 \\ var y = @as(u3, 3);7711 \\ var y = @as(f32, 3);
7695 \\ var x = @intToEnum(Small, y);7712 \\ var x = @intToEnum(Small, y);
7696 \\ _ = x;7713 \\ _ = x;
7697 \\}7714 \\}
7698 , &[_][]const u8{7715 , &[_][]const u8{
7699 "tmp.zig:10:31: error: expected type 'u2', found 'u3'",7716 "tmp.zig:10:31: error: expected integer type, found 'f32'",
7700 });7717 });
77017718
7702 ctx.objErrStage1("union fields with value assignments",7719 ctx.objErrStage1("union fields with value assignments",
test/run_translated_c.zig+18
...@@ -1749,4 +1749,22 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {...@@ -1749,4 +1749,22 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {
1749 \\ return 0;1749 \\ return 0;
1750 \\}1750 \\}
1751 , "");1751 , "");
1752
1753 cases.add("Allow non-const char* string literals. Issue #9126",
1754 \\#include <stdlib.h>
1755 \\int func(char *x) { return x[0]; }
1756 \\struct S { char *member; };
1757 \\struct S global_struct = { .member = "global" };
1758 \\char *g = "global";
1759 \\int main(void) {
1760 \\ if (g[0] != 'g') abort();
1761 \\ if (global_struct.member[0] != 'g') abort();
1762 \\ char *string = "hello";
1763 \\ if (string[0] != 'h') abort();
1764 \\ struct S s = {.member = "hello"};
1765 \\ if (s.member[0] != 'h') abort();
1766 \\ if (func("foo") != 'f') abort();
1767 \\ return 0;
1768 \\}
1769 , "");
1752}1770}
test/stage2/arm.zig+102
...@@ -204,6 +204,48 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -204,6 +204,48 @@ pub fn addCases(ctx: *TestContext) !void {
204 ,204 ,
205 "123456",205 "123456",
206 );206 );
207
208 // Bit Shift Left
209 case.addCompareOutput(
210 \\pub fn main() void {
211 \\ var x: u32 = 1;
212 \\ assert(x << 1 == 2);
213 \\
214 \\ x <<= 1;
215 \\ assert(x << 2 == 8);
216 \\ assert(x << 3 == 16);
217 \\}
218 \\
219 \\pub fn assert(ok: bool) void {
220 \\ if (!ok) unreachable; // assertion failure
221 \\}
222 ,
223 "",
224 );
225
226 // Bit Shift Right
227 case.addCompareOutput(
228 \\pub fn main() void {
229 \\ var a: u32 = 1024;
230 \\ assert(a >> 1 == 512);
231 \\
232 \\ a >>= 1;
233 \\ assert(a >> 2 == 128);
234 \\ assert(a >> 3 == 64);
235 \\ assert(a >> 4 == 32);
236 \\ assert(a >> 5 == 16);
237 \\ assert(a >> 6 == 8);
238 \\ assert(a >> 7 == 4);
239 \\ assert(a >> 8 == 2);
240 \\ assert(a >> 9 == 1);
241 \\}
242 \\
243 \\pub fn assert(ok: bool) void {
244 \\ if (!ok) unreachable; // assertion failure
245 \\}
246 ,
247 "",
248 );
207 }249 }
208250
209 {251 {
...@@ -319,6 +361,22 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -319,6 +361,22 @@ pub fn addCases(ctx: *TestContext) !void {
319 ,361 ,
320 "",362 "",
321 );363 );
364
365 case.addCompareOutput(
366 \\const Number = enum { one, two, three };
367 \\
368 \\pub fn main() void {
369 \\ var x: Number = .one;
370 \\ var y = Number.two;
371 \\ assert(@enumToInt(x) < @enumToInt(y));
372 \\}
373 \\
374 \\fn assert(ok: bool) void {
375 \\ if (!ok) unreachable; // assertion failure
376 \\}
377 ,
378 "",
379 );
322 }380 }
323381
324 {382 {
...@@ -429,4 +487,48 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -429,4 +487,48 @@ pub fn addCases(ctx: *TestContext) !void {
429 "",487 "",
430 );488 );
431 }489 }
490
491 {
492 var case = ctx.exe("print u32s", linux_arm);
493 case.addCompareOutput(
494 \\pub fn main() void {
495 \\ printNumberHex(0x00000000);
496 \\ printNumberHex(0xaaaaaaaa);
497 \\ printNumberHex(0xdeadbeef);
498 \\ printNumberHex(0x31415926);
499 \\}
500 \\
501 \\fn printNumberHex(x: u32) void {
502 \\ var i: u5 = 28;
503 \\ while (true) : (i -= 4) {
504 \\ const digit = (x >> i) & 0xf;
505 \\ asm volatile ("svc #0"
506 \\ :
507 \\ : [number] "{r7}" (4),
508 \\ [arg1] "{r0}" (1),
509 \\ [arg2] "{r1}" (@ptrToInt("0123456789abcdef") + digit),
510 \\ [arg3] "{r2}" (1)
511 \\ : "memory"
512 \\ );
513 \\
514 \\ if (i == 0) break;
515 \\ }
516 \\ asm volatile ("svc #0"
517 \\ :
518 \\ : [number] "{r7}" (4),
519 \\ [arg1] "{r0}" (1),
520 \\ [arg2] "{r1}" (@ptrToInt("\n")),
521 \\ [arg3] "{r2}" (1)
522 \\ : "memory"
523 \\ );
524 \\}
525 ,
526 \\00000000
527 \\aaaaaaaa
528 \\deadbeef
529 \\31415926
530 \\
531 ,
532 );
533 }
432}534}
test/stage2/cbe.zig+38
...@@ -555,6 +555,19 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -555,6 +555,19 @@ pub fn addCases(ctx: *TestContext) !void {
555 \\ return p.y - p.x - p.x;555 \\ return p.y - p.x - p.x;
556 \\}556 \\}
557 , "");557 , "");
558 case.addCompareOutput(
559 \\const Point = struct { x: i32, y: i32, z: i32, a: i32, b: i32 };
560 \\pub export fn main() c_int {
561 \\ var p: Point = .{
562 \\ .x = 18,
563 \\ .y = 24,
564 \\ .z = 1,
565 \\ .a = 2,
566 \\ .b = 3,
567 \\ };
568 \\ return p.y - p.x - p.z - p.a - p.b;
569 \\}
570 , "");
558 }571 }
559572
560 {573 {
...@@ -808,6 +821,31 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -808,6 +821,31 @@ pub fn addCases(ctx: *TestContext) !void {
808 });821 });
809 }822 }
810823
824 {
825 var case = ctx.exeFromCompiledC("shift right + left", .{});
826 case.addCompareOutput(
827 \\pub export fn main() c_int {
828 \\ var i: u32 = 16;
829 \\ assert(i >> 1, 8);
830 \\ return 0;
831 \\}
832 \\fn assert(a: u32, b: u32) void {
833 \\ if (a != b) unreachable;
834 \\}
835 , "");
836
837 case.addCompareOutput(
838 \\pub export fn main() c_int {
839 \\ var i: u32 = 16;
840 \\ assert(i << 1, 32);
841 \\ return 0;
842 \\}
843 \\fn assert(a: u32, b: u32) void {
844 \\ if (a != b) unreachable;
845 \\}
846 , "");
847 }
848
811 {849 {
812 var case = ctx.exeFromCompiledC("inferred error sets", .{});850 var case = ctx.exeFromCompiledC("inferred error sets", .{});
813851
test/stage2/darwin.zig+1-1
...@@ -14,7 +14,7 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -14,7 +14,7 @@ pub fn addCases(ctx: *TestContext) !void {
14 {14 {
15 var case = ctx.exe("hello world with updates", target);15 var case = ctx.exe("hello world with updates", target);
16 case.addError("", &[_][]const u8{16 case.addError("", &[_][]const u8{
17 ":95:9: error: struct 'tmp.tmp' has no member named 'main'",17 ":90:9: error: struct 'tmp.tmp' has no member named 'main'",
18 });18 });
1919
20 // Incorrect return type20 // Incorrect return type
test/stage2/llvm.zig+25
...@@ -28,6 +28,31 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -28,6 +28,31 @@ pub fn addCases(ctx: *TestContext) !void {
28 , "");28 , "");
29 }29 }
3030
31 {
32 var case = ctx.exeUsingLlvmBackend("shift right + left", linux_x64);
33
34 case.addCompareOutput(
35 \\pub export fn main() c_int {
36 \\ var i: u32 = 16;
37 \\ assert(i >> 1, 8);
38 \\ return 0;
39 \\}
40 \\fn assert(a: u32, b: u32) void {
41 \\ if (a != b) unreachable;
42 \\}
43 , "");
44 case.addCompareOutput(
45 \\pub export fn main() c_int {
46 \\ var i: u32 = 16;
47 \\ assert(i << 1, 32);
48 \\ return 0;
49 \\}
50 \\fn assert(a: u32, b: u32) void {
51 \\ if (a != b) unreachable;
52 \\}
53 , "");
54 }
55
31 {56 {
32 var case = ctx.exeUsingLlvmBackend("llvm hello world", linux_x64);57 var case = ctx.exeUsingLlvmBackend("llvm hello world", linux_x64);
3358
tools/update-license-headers.zig created+47
...@@ -0,0 +1,47 @@
1const std = @import("std");
2
3/// This script replaces a matching license header from .zig source files in a directory tree
4/// with the `new_header` below.
5const new_header = "";
6
7pub fn main() !void {
8 var progress = std.Progress{};
9 const root_node = try progress.start("", 0);
10 defer root_node.end();
11
12 var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
13 const arena = &arena_allocator.allocator;
14
15 const args = try std.process.argsAlloc(arena);
16 const path_to_walk = args[1];
17 const dir = try std.fs.cwd().openDir(path_to_walk, .{ .iterate = true });
18
19 var walker = try dir.walk(arena);
20 defer walker.deinit();
21
22 var buffer: [500]u8 = undefined;
23 const expected_header = buffer[0..try std.io.getStdIn().readAll(&buffer)];
24
25 while (try walker.next()) |entry| {
26 if (!std.mem.endsWith(u8, entry.basename, ".zig"))
27 continue;
28
29 var node = root_node.start(entry.basename, 0);
30 node.activate();
31 defer node.end();
32
33 const source = try dir.readFileAlloc(arena, entry.path, 20 * 1024 * 1024);
34 if (!std.mem.startsWith(u8, source, expected_header)) {
35 std.debug.print("no match: {s}\n", .{entry.path});
36 continue;
37 }
38
39 const truncated_source = source[expected_header.len..];
40
41 const new_source = try arena.alloc(u8, truncated_source.len + new_header.len);
42 std.mem.copy(u8, new_source, new_header);
43 std.mem.copy(u8, new_source[new_header.len..], truncated_source);
44
45 try dir.writeFile(entry.path, new_source);
46 }
47}