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
426426 "${CMAKE_SOURCE_DIR}/lib/std/os.zig"
427427 "${CMAKE_SOURCE_DIR}/lib/std/os/bits.zig"
428428 "${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"
430430 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux/netlink.zig"
431431 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux/prctl.zig"
432432 "${CMAKE_SOURCE_DIR}/lib/std/os/bits/linux/securebits.zig"
build.zig+40-28
......@@ -17,8 +17,10 @@ pub fn build(b: *Builder) !void {
1717 b.setPreferredReleaseMode(.ReleaseFast);
1818 const mode = b.standardReleaseOptions();
1919 const target = b.standardTargetOptions(.{});
20 const single_threaded = b.option(bool, "single-threaded", "Build artifacts that run in single threaded mode") orelse false;
2021
2122 var docgen_exe = b.addExecutable("docgen", "doc/docgen.zig");
23 docgen_exe.single_threaded = single_threaded;
2224
2325 const rel_zig_exe = try fs.path.relative(b.allocator, b.build_root, b.zig_exe);
2426 const langref_out_path = fs.path.join(
......@@ -41,6 +43,7 @@ pub fn build(b: *Builder) !void {
4143 var test_stage2 = b.addTest("src/test.zig");
4244 test_stage2.setBuildMode(mode);
4345 test_stage2.addPackagePath("test_cases", "test/cases.zig");
46 test_stage2.single_threaded = single_threaded;
4447
4548 const fmt_build_zig = b.addFmt(&[_][]const u8{"build.zig"});
4649
......@@ -104,10 +107,15 @@ pub fn build(b: *Builder) !void {
104107 exe.setTarget(target);
105108 toolchain_step.dependOn(&exe.step);
106109 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);
111119 if (enable_llvm) {
112120 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 {
131139 softfloat.addIncludeDir("deps/SoftFloat-3e/source/8086");
132140 softfloat.addIncludeDir("deps/SoftFloat-3e/source/include");
133141 softfloat.addCSourceFiles(&softfloat_sources, &[_][]const u8{ "-std=c99", "-O3" });
142 softfloat.single_threaded = single_threaded;
134143
135144 exe.linkLibrary(softfloat);
136145 test_stage2.linkLibrary(softfloat);
......@@ -213,15 +222,15 @@ pub fn build(b: *Builder) !void {
213222 },
214223 }
215224 };
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
218227 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);
222 exe.addBuildOption(bool, "enable_tracy", tracy != null);
223 exe.addBuildOption(bool, "is_stage1", is_stage1);
224 exe.addBuildOption(bool, "omit_stage2", omit_stage2);
230 exe_options.addOption(bool, "enable_logging", enable_logging);
231 exe_options.addOption(bool, "enable_tracy", tracy != null);
232 exe_options.addOption(bool, "is_stage1", is_stage1);
233 exe_options.addOption(bool, "omit_stage2", omit_stage2);
225234 if (tracy) |tracy_path| {
226235 const client_cpp = fs.path.join(
227236 b.allocator,
......@@ -243,20 +252,23 @@ pub fn build(b: *Builder) !void {
243252 const is_darling_enabled = b.option(bool, "enable-darling", "[Experimental] Use Darling to run cross compiled macOS tests") orelse false;
244253 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);
247 test_stage2.addBuildOption(bool, "skip_non_native", skip_non_native);
248 test_stage2.addBuildOption(bool, "skip_compile_errors", skip_compile_errors);
249 test_stage2.addBuildOption(bool, "is_stage1", is_stage1);
250 test_stage2.addBuildOption(bool, "omit_stage2", omit_stage2);
251 test_stage2.addBuildOption(bool, "have_llvm", enable_llvm);
252 test_stage2.addBuildOption(bool, "enable_qemu", is_qemu_enabled);
253 test_stage2.addBuildOption(bool, "enable_wine", is_wine_enabled);
254 test_stage2.addBuildOption(bool, "enable_wasmtime", is_wasmtime_enabled);
255 test_stage2.addBuildOption(u32, "mem_leak_frames", mem_leak_frames * 2);
256 test_stage2.addBuildOption(bool, "enable_darling", is_darling_enabled);
257 test_stage2.addBuildOption(?[]const u8, "glibc_multi_install_dir", glibc_multi_dir);
258 test_stage2.addBuildOption([:0]const u8, "version", try b.allocator.dupeZ(u8, version));
259 test_stage2.addBuildOption(std.SemanticVersion, "semver", semver);
255 const test_stage2_options = b.addOptions();
256 test_stage2.addOptions("build_options", test_stage2_options);
257
258 test_stage2_options.addOption(bool, "enable_logging", enable_logging);
259 test_stage2_options.addOption(bool, "skip_non_native", skip_non_native);
260 test_stage2_options.addOption(bool, "skip_compile_errors", skip_compile_errors);
261 test_stage2_options.addOption(bool, "is_stage1", is_stage1);
262 test_stage2_options.addOption(bool, "omit_stage2", omit_stage2);
263 test_stage2_options.addOption(bool, "have_llvm", enable_llvm);
264 test_stage2_options.addOption(bool, "enable_qemu", is_qemu_enabled);
265 test_stage2_options.addOption(bool, "enable_wine", is_wine_enabled);
266 test_stage2_options.addOption(bool, "enable_wasmtime", is_wasmtime_enabled);
267 test_stage2_options.addOption(u32, "mem_leak_frames", mem_leak_frames * 2);
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
261273 const test_stage2_step = b.step("test-stage2", "Run the stage2 compiler tests");
262274 test_stage2_step.dependOn(&test_stage2.step);
......@@ -296,7 +308,7 @@ pub fn build(b: *Builder) !void {
296308 "behavior",
297309 "Run the behavior tests",
298310 modes,
299 false,
311 false, // skip_single_threaded
300312 skip_non_native,
301313 skip_libc,
302314 is_wine_enabled,
......@@ -313,9 +325,9 @@ pub fn build(b: *Builder) !void {
313325 "compiler-rt",
314326 "Run the compiler_rt tests",
315327 modes,
316 true,
328 true, // skip_single_threaded
317329 skip_non_native,
318 true,
330 true, // skip_libc
319331 is_wine_enabled,
320332 is_qemu_enabled,
321333 is_wasmtime_enabled,
......@@ -330,9 +342,9 @@ pub fn build(b: *Builder) !void {
330342 "minilibc",
331343 "Run the mini libc tests",
332344 modes,
333 true,
345 true, // skip_single_threaded
334346 skip_non_native,
335 true,
347 true, // skip_libc
336348 is_wine_enabled,
337349 is_qemu_enabled,
338350 is_wasmtime_enabled,
doc/docgen.zig+14-15
......@@ -887,16 +887,6 @@ fn tokenizeAndPrintRaw(
887887 next_tok_is_fn = true;
888888 },
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
900890 .string_literal,
901891 .multiline_string_literal_line,
902892 .char_literal,
......@@ -921,9 +911,18 @@ fn tokenizeAndPrintRaw(
921911 },
922912
923913 .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) {
925924 try out.writeAll("<span class=\"tok-fn\">");
926 try writeEscaped(out, src[token.loc.start..token.loc.end]);
925 try writeEscaped(out, tok_bytes);
927926 try out.writeAll("</span>");
928927 } else {
929928 const is_int = blk: {
......@@ -938,12 +937,12 @@ fn tokenizeAndPrintRaw(
938937 }
939938 break :blk true;
940939 };
941 if (is_int or isType(src[token.loc.start..token.loc.end])) {
940 if (is_int or isType(tok_bytes)) {
942941 try out.writeAll("<span class=\"tok-type\">");
943 try writeEscaped(out, src[token.loc.start..token.loc.end]);
942 try writeEscaped(out, tok_bytes);
944943 try out.writeAll("</span>");
945944 } else {
946 try writeEscaped(out, src[token.loc.start..token.loc.end]);
945 try writeEscaped(out, tok_bytes);
947946 }
948947 }
949948 },
doc/langref.html.in+42-21
......@@ -38,15 +38,20 @@
3838 .file {
3939 text-decoration: underline;
4040 }
41 pre,code {
42 font-size: 12pt;
43 }
4441 pre > code {
4542 display: block;
4643 overflow: auto;
4744 padding: 0.5em;
4845 color: #333;
4946 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;
5055 }
5156 .table-wrapper {
5257 width: 100%;
......@@ -95,6 +100,7 @@
95100 #contents {
96101 max-width: 60em;
97102 margin: auto;
103 line-height: 1.5;
98104 }
99105
100106 #toc {
......@@ -153,6 +159,11 @@
153159 pre > code {
154160 color: #ccc;
155161 background: #222;
162 border-color: #444;
163 }
164 code {
165 background-color: #222;
166 border-color: #444;
156167 }
157168 .tok-kw {
158169 color: #eee;
......@@ -3152,7 +3163,9 @@ test "switch using enum literals" {
31523163 It must specify a tag type and cannot consume every enumeration value.
31533164 </p>
31543165 <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.
31563169 </p>
31573170 <p>
31583171 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" {
66346647 <p>
66356648 When a function is called, a frame is pushed to the stack,
66366649 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.
66386651 </p>
66396652 <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,
66416654 followed by an {#syntax#}await{#endsyntax#} completion. Its frame is
66426655 provided explicitly by the caller, and it can be suspended and resumed any number of times.
66436656 </p>
66446657 <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>
66456665 Zig infers that a function is {#syntax#}async{#endsyntax#} when it observes that the function contains
66466666 a <strong>suspension point</strong>. Async functions can be called the same as normal functions. A
66476667 function call of an async function is a suspend point.
......@@ -6744,7 +6764,14 @@ fn testResumeFromSuspend(my_result: *i32) void {
67446764 {#header_open|Async and Await#}
67456765 <p>
67466766 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.
67486775 </p>
67496776 {#code_begin|test#}
67506777const std = @import("std");
......@@ -6779,7 +6806,9 @@ fn func() void {
67796806 </p>
67806807 <p>
67816808 {#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.
67836812 </p>
67846813 <p>
67856814 There is a common misconception that {#syntax#}await{#endsyntax#} resumes the target function.
......@@ -7945,7 +7974,7 @@ test "@hasDecl" {
79457974 {#header_close#}
79467975
79477976 {#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>
79497978 <p>
79507979 Converts an integer into an {#link|enum#} value.
79517980 </p>
......@@ -11535,11 +11564,7 @@ PrimaryTypeExpr
1153511564 / INTEGER
1153611565 / KEYWORD_comptime TypeExpr
1153711566 / KEYWORD_error DOT IDENTIFIER
11538 / KEYWORD_false
11539 / KEYWORD_null
1154011567 / KEYWORD_anyframe
11541 / KEYWORD_true
11542 / KEYWORD_undefined
1154311568 / KEYWORD_unreachable
1154411569 / STRINGLITERAL
1154511570 / SwitchExpr
......@@ -11908,7 +11933,6 @@ KEYWORD_errdefer &lt;- 'errdefer' end_of_word
1190811933KEYWORD_error &lt;- 'error' end_of_word
1190911934KEYWORD_export &lt;- 'export' end_of_word
1191011935KEYWORD_extern &lt;- 'extern' end_of_word
11911KEYWORD_false &lt;- 'false' end_of_word
1191211936KEYWORD_fn &lt;- 'fn' end_of_word
1191311937KEYWORD_for &lt;- 'for' end_of_word
1191411938KEYWORD_if &lt;- 'if' end_of_word
......@@ -11916,7 +11940,6 @@ KEYWORD_inline &lt;- 'inline' end_of_word
1191611940KEYWORD_noalias &lt;- 'noalias' end_of_word
1191711941KEYWORD_nosuspend &lt;- 'nosuspend' end_of_word
1191811942KEYWORD_noinline &lt;- 'noinline' end_of_word
11919KEYWORD_null &lt;- 'null' end_of_word
1192011943KEYWORD_opaque &lt;- 'opaque' end_of_word
1192111944KEYWORD_or &lt;- 'or' end_of_word
1192211945KEYWORD_orelse &lt;- 'orelse' end_of_word
......@@ -11930,9 +11953,7 @@ KEYWORD_suspend &lt;- 'suspend' end_of_word
1193011953KEYWORD_switch &lt;- 'switch' end_of_word
1193111954KEYWORD_test &lt;- 'test' end_of_word
1193211955KEYWORD_threadlocal &lt;- 'threadlocal' end_of_word
11933KEYWORD_true &lt;- 'true' end_of_word
1193411956KEYWORD_try &lt;- 'try' end_of_word
11935KEYWORD_undefined &lt;- 'undefined' end_of_word
1193611957KEYWORD_union &lt;- 'union' end_of_word
1193711958KEYWORD_unreachable &lt;- 'unreachable' end_of_word
1193811959KEYWORD_usingnamespace &lt;- 'usingnamespace' end_of_word
......@@ -11945,13 +11966,13 @@ keyword &lt;- KEYWORD_align / KEYWORD_allowzero / KEYWORD_and / KEYWORD_anyframe
1194511966 / KEYWORD_break / KEYWORD_callconv / KEYWORD_catch / KEYWORD_comptime
1194611967 / KEYWORD_const / KEYWORD_continue / KEYWORD_defer / KEYWORD_else
1194711968 / KEYWORD_enum / KEYWORD_errdefer / KEYWORD_error / KEYWORD_export
11948 / KEYWORD_extern / KEYWORD_false / KEYWORD_fn / KEYWORD_for / KEYWORD_if
11969 / KEYWORD_extern / KEYWORD_fn / KEYWORD_for / KEYWORD_if
1194911970 / KEYWORD_inline / KEYWORD_noalias / KEYWORD_nosuspend / KEYWORD_noinline
11950 / KEYWORD_null / KEYWORD_opaque / KEYWORD_or / KEYWORD_orelse / KEYWORD_packed
11971 / KEYWORD_opaque / KEYWORD_or / KEYWORD_orelse / KEYWORD_packed
1195111972 / KEYWORD_pub / KEYWORD_resume / KEYWORD_return / KEYWORD_linksection
1195211973 / KEYWORD_struct / KEYWORD_suspend / KEYWORD_switch
11953 / KEYWORD_test / KEYWORD_threadlocal / KEYWORD_true / KEYWORD_try
11954 / KEYWORD_undefined / KEYWORD_union / KEYWORD_unreachable
11974 / KEYWORD_test / KEYWORD_threadlocal / KEYWORD_try
11975 / KEYWORD_union / KEYWORD_unreachable
1195511976 / KEYWORD_usingnamespace / KEYWORD_var / KEYWORD_volatile / KEYWORD_while
1195611977</code></pre>
1195711978 {#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 @@
125125# endif
126126// Feature macros for disabling pre ABI v1 features. All of these options
127127// are deprecated.
128# if defined(__FreeBSD__)
128# if defined(__FreeBSD__) || defined(__DragonFly__)
129129# define _LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR
130130# endif
131131#endif
......@@ -380,7 +380,7 @@
380380# if __ANDROID_API__ >= 29
381381# define _LIBCPP_HAS_TIMESPEC_GET
382382# endif
383# elif defined(__Fuchsia__) || defined(__wasi__) || defined(__NetBSD__)
383# elif defined(__Fuchsia__) || defined(__wasi__) || defined(__NetBSD__) || defined(__DragonFly__)
384384# define _LIBCPP_HAS_ALIGNED_ALLOC
385385# define _LIBCPP_HAS_QUICK_EXIT
386386# define _LIBCPP_HAS_TIMESPEC_GET
......@@ -938,11 +938,11 @@ typedef unsigned int char32_t;
938938#endif
939939
940940#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__)
942942#define _LIBCPP_LOCALE__L_EXTENSIONS 1
943943#endif
944944
945#ifdef __FreeBSD__
945#if defined(__FreeBSD__) || defined(__DragonFly__)
946946#define _DECLARE_C99_LDBL_MATH 1
947947#endif
948948
......@@ -970,11 +970,11 @@ typedef unsigned int char32_t;
970970# define _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
971971#endif
972972
973#if defined(__APPLE__) || defined(__FreeBSD__)
973#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__)
974974#define _LIBCPP_HAS_DEFAULTRUNELOCALE
975975#endif
976976
977#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__sun__)
977#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__) || defined(__sun__)
978978#define _LIBCPP_WCTYPE_IS_MASK
979979#endif
980980
......@@ -1138,6 +1138,7 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
11381138 defined(__wasi__) || \
11391139 defined(__NetBSD__) || \
11401140 defined(__OpenBSD__) || \
1141 defined(__DragonFly__) || \
11411142 defined(__NuttX__) || \
11421143 defined(__linux__) || \
11431144 defined(__GNU__) || \
lib/libcxx/include/__locale+3-3
......@@ -35,7 +35,7 @@
3535# include <__support/newlib/xlocale.h>
3636#elif defined(__OpenBSD__)
3737# include <__support/openbsd/xlocale.h>
38#elif (defined(__APPLE__) || defined(__FreeBSD__) \
38#elif (defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__) \
3939 || defined(__EMSCRIPTEN__) || defined(__IBMCPP__))
4040# include <xlocale.h>
4141#elif defined(__Fuchsia__)
......@@ -450,10 +450,10 @@ public:
450450 static const mask blank = _BLANK;
451451 static const mask __regex_word = 0x80;
452452# 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__)
454454# ifdef __APPLE__
455455 typedef __uint32_t mask;
456# elif defined(__FreeBSD__)
456# elif defined(__FreeBSD__) || defined(__DragonFly__)
457457 typedef unsigned long mask;
458458# elif defined(__EMSCRIPTEN__) || defined(__NetBSD__)
459459 typedef unsigned short mask;
lib/libcxx/include/locale+1-1
......@@ -228,7 +228,7 @@ _LIBCPP_PUSH_MACROS
228228
229229_LIBCPP_BEGIN_NAMESPACE_STD
230230
231#if defined(__APPLE__) || defined(__FreeBSD__)
231#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__)
232232# define _LIBCPP_GET_C_LOCALE 0
233233#elif defined(__CloudABI__) || defined(__NetBSD__)
234234# define _LIBCPP_GET_C_LOCALE LC_C_LOCALE
lib/libcxx/src/locale.cpp+1-1
......@@ -1133,7 +1133,7 @@ ctype<char>::classic_table() noexcept
11331133const ctype<char>::mask*
11341134ctype<char>::classic_table() noexcept
11351135{
1136#if defined(__APPLE__) || defined(__FreeBSD__)
1136#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__DragonFly__)
11371137 return _DefaultRuneLocale.__runetype;
11381138#elif defined(__NetBSD__)
11391139 return _C_ctype_tab_ + 1;
lib/std/Progress.zig-6
......@@ -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
71//! This API non-allocating, non-fallible, and thread-safe.
82//! The tradeoff is that users of this API must provide the storage
93//! for each `Progress.Node`.
lib/std/SemanticVersion.zig-6
......@@ -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
71//! A software version formatted according to the Semantic Version 2 specification.
82//!
93//! See: https://semver.org
lib/std/Thread.zig+87-87
......@@ -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
71//! This struct represents a kernel thread, and acts as a namespace for concurrency
82//! primitives that operate on kernel threads. For concurrency primitives that support
93//! both evented I/O and async I/O, see the respective names in the top level std namespace.
104
115const std = @import("std.zig");
6const builtin = @import("builtin");
127const os = std.os;
138const assert = std.debug.assert;
14const target = std.Target.current;
9const target = builtin.target;
1510const Atomic = std.atomic.Atomic;
1611
1712pub const AutoResetEvent = @import("Thread/AutoResetEvent.zig");
......@@ -24,7 +19,8 @@ pub const Condition = @import("Thread/Condition.zig");
2419
2520pub 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
2925const Thread = @This();
3026const Impl = if (target.os.tag == .windows)
......@@ -38,7 +34,7 @@ else
3834
3935impl: Impl,
4036
41pub const max_name_len = switch (std.Target.current.os.tag) {
37pub const max_name_len = switch (target.os.tag) {
4238 .linux => 15,
4339 .windows => 31,
4440 .macos, .ios, .watchos, .tvos => 63,
......@@ -64,20 +60,21 @@ pub fn setName(self: Thread, name: []const u8) SetNameError!void {
6460 break :blk name_buf[0..name.len :0];
6561 };
6662
67 switch (std.Target.current.os.tag) {
63 switch (target.os.tag) {
6864 .linux => if (use_pthreads) {
6965 const err = std.c.pthread_setname_np(self.getHandle(), name_with_terminator.ptr);
70 return switch (err) {
71 0 => {},
72 os.ERANGE => unreachable,
73 else => return os.unexpectedErrno(err),
74 };
66 switch (err) {
67 .SUCCESS => return,
68 .RANGE => unreachable,
69 else => |e| return os.unexpectedErrno(e),
70 }
7571 } 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?
7673 const err = try os.prctl(.SET_NAME, .{@ptrToInt(name_with_terminator.ptr)});
77 return switch (err) {
78 0 => {},
79 else => return os.unexpectedErrno(err),
80 };
74 switch (@intToEnum(os.E, err)) {
75 .SUCCESS => return,
76 else => |e| return os.unexpectedErrno(e),
77 }
8178 } else {
8279 var buf: [32]u8 = undefined;
8380 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 {
8784
8885 try file.writer().writeAll(name);
8986 },
90 .windows => if (std.Target.current.os.isAtLeast(.windows, .win10_rs1)) |res| {
87 .windows => if (target.os.isAtLeast(.windows, .win10_rs1)) |res| {
9188 // SetThreadDescription is only available since version 1607, which is 10.0.14393.795
9289 // See https://en.wikipedia.org/wiki/Microsoft_Windows_SDK
9390 if (!res) {
......@@ -110,24 +107,25 @@ pub fn setName(self: Thread, name: []const u8) SetNameError!void {
110107 if (self.getHandle() != std.c.pthread_self()) return error.Unsupported;
111108
112109 const err = std.c.pthread_setname_np(name_with_terminator.ptr);
113 return switch (err) {
114 0 => {},
115 else => return os.unexpectedErrno(err),
116 };
110 switch (err) {
111 .SUCCESS => return,
112 else => |e| return os.unexpectedErrno(e),
113 }
117114 },
118115 .netbsd => if (use_pthreads) {
119116 const err = std.c.pthread_setname_np(self.getHandle(), name_with_terminator.ptr, null);
120 return switch (err) {
121 0 => {},
122 os.EINVAL => unreachable,
123 os.ESRCH => unreachable,
124 os.ENOMEM => unreachable,
125 else => return os.unexpectedErrno(err),
126 };
117 switch (err) {
118 .SUCCESS => return,
119 .INVAL => unreachable,
120 .SRCH => unreachable,
121 .NOMEM => unreachable,
122 else => |e| return os.unexpectedErrno(e),
123 }
127124 },
128125 .freebsd, .openbsd => if (use_pthreads) {
129126 // 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
132130 std.c.pthread_set_name_np(self.getHandle(), name_with_terminator.ptr);
133131 },
......@@ -151,20 +149,20 @@ pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]co
151149 buffer_ptr[max_name_len] = 0;
152150 var buffer = std.mem.span(buffer_ptr);
153151
154 switch (std.Target.current.os.tag) {
155 .linux => if (use_pthreads and comptime std.Target.current.abi.isGnu()) {
152 switch (target.os.tag) {
153 .linux => if (use_pthreads and is_gnu) {
156154 const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);
157 return switch (err) {
158 0 => std.mem.sliceTo(buffer, 0),
159 os.ERANGE => unreachable,
160 else => return os.unexpectedErrno(err),
161 };
155 switch (err) {
156 .SUCCESS => return std.mem.sliceTo(buffer, 0),
157 .RANGE => unreachable,
158 else => |e| return os.unexpectedErrno(e),
159 }
162160 } else if (use_pthreads and self.getHandle() == std.c.pthread_self()) {
163161 const err = try os.prctl(.GET_NAME, .{@ptrToInt(buffer.ptr)});
164 return switch (err) {
165 0 => std.mem.sliceTo(buffer, 0),
166 else => return os.unexpectedErrno(err),
167 };
162 switch (@intToEnum(os.E, err)) {
163 .SUCCESS => return std.mem.sliceTo(buffer, 0),
164 else => |e| return os.unexpectedErrno(e),
165 }
168166 } else if (!use_pthreads) {
169167 var buf: [32]u8 = undefined;
170168 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
179177 // musl doesn't provide pthread_getname_np and there's no way to retrieve the thread id of an arbitrary thread.
180178 return error.Unsupported;
181179 },
182 .windows => if (std.Target.current.os.isAtLeast(.windows, .win10_rs1)) |res| {
180 .windows => if (target.os.isAtLeast(.windows, .win10_rs1)) |res| {
183181 // GetThreadDescription is only available since version 1607, which is 10.0.14393.795
184182 // See https://en.wikipedia.org/wiki/Microsoft_Windows_SDK
185183 if (!res) {
......@@ -198,20 +196,20 @@ pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]co
198196 },
199197 .macos, .ios, .watchos, .tvos => if (use_pthreads) {
200198 const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);
201 return switch (err) {
202 0 => std.mem.sliceTo(buffer, 0),
203 os.ESRCH => unreachable,
204 else => return os.unexpectedErrno(err),
205 };
199 switch (err) {
200 .SUCCESS => return std.mem.sliceTo(buffer, 0),
201 .SRCH => unreachable,
202 else => |e| return os.unexpectedErrno(e),
203 }
206204 },
207205 .netbsd => if (use_pthreads) {
208206 const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);
209 return switch (err) {
210 0 => std.mem.sliceTo(buffer, 0),
211 os.EINVAL => unreachable,
212 os.ESRCH => unreachable,
213 else => return os.unexpectedErrno(err),
214 };
207 switch (err) {
208 .SUCCESS => return std.mem.sliceTo(buffer, 0),
209 .INVAL => unreachable,
210 .SRCH => unreachable,
211 else => |e| return os.unexpectedErrno(e),
212 }
215213 },
216214 .freebsd, .openbsd => if (use_pthreads) {
217215 // Use pthread_get_name_np for FreeBSD because pthread_getname_np is FreeBSD 12.2+ only.
......@@ -288,7 +286,7 @@ pub const SpawnError = error{
288286/// The caller must eventually either call `join()` to wait for the thread to finish and free its resources
289287/// or call `detach()` to excuse the caller from calling `join()` and have the thread clean up its resources on completion`.
290288pub fn spawn(config: SpawnConfig, comptime function: anytype, args: anytype) SpawnError!Thread {
291 if (std.builtin.single_threaded) {
289 if (builtin.single_threaded) {
292290 @compileError("Cannot spawn thread when building in single-threaded mode");
293291 }
294292
......@@ -611,13 +609,13 @@ const PosixThreadImpl = struct {
611609 errdefer allocator.destroy(args_ptr);
612610
613611 var attr: c.pthread_attr_t = undefined;
614 if (c.pthread_attr_init(&attr) != 0) return error.SystemResources;
615 defer assert(c.pthread_attr_destroy(&attr) == 0);
612 if (c.pthread_attr_init(&attr) != .SUCCESS) return error.SystemResources;
613 defer assert(c.pthread_attr_destroy(&attr) == .SUCCESS);
616614
617615 // Use the same set of parameters used by the libc-less impl.
618616 const stack_size = std.math.max(config.stack_size, 16 * 1024);
619 assert(c.pthread_attr_setstacksize(&attr, stack_size) == 0);
620 assert(c.pthread_attr_setguardsize(&attr, std.mem.page_size) == 0);
617 assert(c.pthread_attr_setstacksize(&attr, stack_size) == .SUCCESS);
618 assert(c.pthread_attr_setguardsize(&attr, std.mem.page_size) == .SUCCESS);
621619
622620 var handle: c.pthread_t = undefined;
623621 switch (c.pthread_create(
......@@ -626,10 +624,10 @@ const PosixThreadImpl = struct {
626624 Instance.entryFn,
627625 if (@sizeOf(Args) > 1) @ptrCast(*c_void, args_ptr) else undefined,
628626 )) {
629 0 => return Impl{ .handle = handle },
630 os.EAGAIN => return error.SystemResources,
631 os.EPERM => unreachable,
632 os.EINVAL => unreachable,
627 .SUCCESS => return Impl{ .handle = handle },
628 .AGAIN => return error.SystemResources,
629 .PERM => unreachable,
630 .INVAL => unreachable,
633631 else => |err| return os.unexpectedErrno(err),
634632 }
635633 }
......@@ -640,19 +638,19 @@ const PosixThreadImpl = struct {
640638
641639 fn detach(self: Impl) void {
642640 switch (c.pthread_detach(self.handle)) {
643 0 => {},
644 os.EINVAL => unreachable, // thread handle is not joinable
645 os.ESRCH => unreachable, // thread handle is invalid
641 .SUCCESS => {},
642 .INVAL => unreachable, // thread handle is not joinable
643 .SRCH => unreachable, // thread handle is invalid
646644 else => unreachable,
647645 }
648646 }
649647
650648 fn join(self: Impl) void {
651649 switch (c.pthread_join(self.handle, null)) {
652 0 => {},
653 os.EINVAL => unreachable, // thread handle is not joinable (or another thread is already joining in)
654 os.ESRCH => unreachable, // thread handle is invalid
655 os.EDEADLK => unreachable, // two threads tried to join each other
650 .SUCCESS => {},
651 .INVAL => unreachable, // thread handle is not joinable (or another thread is already joining in)
652 .SRCH => unreachable, // thread handle is invalid
653 .DEADLK => unreachable, // two threads tried to join each other
656654 else => unreachable,
657655 }
658656 }
......@@ -806,8 +804,10 @@ const LinuxThreadImpl = struct {
806804 \\ 1:
807805 \\ cmp %%sp, 0
808806 \\ beq 2f
807 \\ nop
809808 \\ restore
810809 \\ ba 1f
810 \\ nop
811811 \\ 2:
812812 \\ mov 73, %%g1
813813 \\ mov %[ptr], %%o0
......@@ -937,13 +937,13 @@ const LinuxThreadImpl = struct {
937937 tls_ptr,
938938 &instance.thread.child_tid.value,
939939 ))) {
940 0 => return Impl{ .thread = &instance.thread },
941 os.EAGAIN => return error.ThreadQuotaExceeded,
942 os.EINVAL => unreachable,
943 os.ENOMEM => return error.SystemResources,
944 os.ENOSPC => unreachable,
945 os.EPERM => unreachable,
946 os.EUSERS => unreachable,
940 .SUCCESS => return Impl{ .thread = &instance.thread },
941 .AGAIN => return error.ThreadQuotaExceeded,
942 .INVAL => unreachable,
943 .NOMEM => return error.SystemResources,
944 .NOSPC => unreachable,
945 .PERM => unreachable,
946 .USERS => unreachable,
947947 else => |err| return os.unexpectedErrno(err),
948948 }
949949 }
......@@ -982,9 +982,9 @@ const LinuxThreadImpl = struct {
982982 tid,
983983 null,
984984 ))) {
985 0 => continue,
986 os.EINTR => continue,
987 os.EAGAIN => continue,
985 .SUCCESS => continue,
986 .INTR => continue,
987 .AGAIN => continue,
988988 else => unreachable,
989989 }
990990 }
......@@ -1011,7 +1011,7 @@ fn testThreadName(thread: *Thread) !void {
10111011}
10121012
10131013test "setName, getName" {
1014 if (std.builtin.single_threaded) return error.SkipZigTest;
1014 if (builtin.single_threaded) return error.SkipZigTest;
10151015
10161016 const Context = struct {
10171017 start_wait_event: ResetEvent = undefined,
......@@ -1029,7 +1029,7 @@ test "setName, getName" {
10291029 // Wait for the main thread to have set the thread field in the context.
10301030 ctx.start_wait_event.wait();
10311031
1032 switch (std.Target.current.os.tag) {
1032 switch (target.os.tag) {
10331033 .windows => testThreadName(&ctx.thread) catch |err| switch (err) {
10341034 error.Unsupported => return error.SkipZigTest,
10351035 else => return err,
......@@ -1054,7 +1054,7 @@ test "setName, getName" {
10541054 context.start_wait_event.set();
10551055 context.test_done_event.wait();
10561056
1057 switch (std.Target.current.os.tag) {
1057 switch (target.os.tag) {
10581058 .macos, .ios, .watchos, .tvos => {
10591059 const res = thread.setName("foobar");
10601060 try std.testing.expectError(error.Unsupported, res);
......@@ -1063,7 +1063,7 @@ test "setName, getName" {
10631063 error.Unsupported => return error.SkipZigTest,
10641064 else => return err,
10651065 },
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()) {
10671067 try thread.setName("foobar");
10681068
10691069 var name_buffer: [max_name_len:0]u8 = undefined;
......@@ -1096,7 +1096,7 @@ fn testIncrementNotify(value: *usize, event: *ResetEvent) void {
10961096}
10971097
10981098test "Thread.join" {
1099 if (std.builtin.single_threaded) return error.SkipZigTest;
1099 if (builtin.single_threaded) return error.SkipZigTest;
11001100
11011101 var value: usize = 0;
11021102 var event: ResetEvent = undefined;
......@@ -1110,7 +1110,7 @@ test "Thread.join" {
11101110}
11111111
11121112test "Thread.detach" {
1113 if (std.builtin.single_threaded) return error.SkipZigTest;
1113 if (builtin.single_threaded) return error.SkipZigTest;
11141114
11151115 var value: usize = 0;
11161116 var event: ResetEvent = undefined;
lib/std/Thread/AutoResetEvent.zig-6
......@@ -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
71//! Similar to `StaticResetEvent` but on `set()` it also (atomically) does `reset()`.
82//! Unlike StaticResetEvent, `wait()` can only be called by one thread (MPSC-like).
93//!
lib/std/Thread/Condition.zig+8-14
......@@ -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
71//! A condition provides a way for a kernel thread to block until it is signaled
82//! to wake up. Spurious wakeups are possible.
93//! This API supports static initialization and does not require deinitialization.
......@@ -81,17 +75,17 @@ pub const PthreadCondition = struct {
8175
8276 pub fn wait(cond: *PthreadCondition, mutex: *Mutex) void {
8377 const rc = std.c.pthread_cond_wait(&cond.cond, &mutex.impl.pthread_mutex);
84 assert(rc == 0);
78 assert(rc == .SUCCESS);
8579 }
8680
8781 pub fn signal(cond: *PthreadCondition) void {
8882 const rc = std.c.pthread_cond_signal(&cond.cond);
89 assert(rc == 0);
83 assert(rc == .SUCCESS);
9084 }
9185
9286 pub fn broadcast(cond: *PthreadCondition) void {
9387 const rc = std.c.pthread_cond_broadcast(&cond.cond);
94 assert(rc == 0);
88 assert(rc == .SUCCESS);
9589 }
9690};
9791
......@@ -115,9 +109,9 @@ pub const AtomicCondition = struct {
115109 0,
116110 null,
117111 ))) {
118 0 => {},
119 std.os.EINTR => {},
120 std.os.EAGAIN => {},
112 .SUCCESS => {},
113 .INTR => {},
114 .AGAIN => {},
121115 else => unreachable,
122116 }
123117 },
......@@ -136,8 +130,8 @@ pub const AtomicCondition = struct {
136130 linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,
137131 1,
138132 ))) {
139 0 => {},
140 std.os.EFAULT => {},
133 .SUCCESS => {},
134 .FAULT => {},
141135 else => unreachable,
142136 }
143137 },
lib/std/Thread/Futex.zig+39-45
......@@ -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
71//! Futex is a mechanism used to block (`wait`) and unblock (`wake`) threads using a 32bit memory address as hints.
82//! Blocking a thread is acknowledged only if the 32bit memory address is equal to a given value.
93//! This check helps avoid block/unblock deadlocks which occur if a `wake()` happens before a `wait()`.
......@@ -152,12 +146,12 @@ const LinuxFutex = struct {
152146 @bitCast(i32, expect),
153147 ts_ptr,
154148 ))) {
155 0 => {}, // notified by `wake()`
156 std.os.EINTR => {}, // spurious wakeup
157 std.os.EAGAIN => {}, // ptr.* != expect
158 std.os.ETIMEDOUT => return error.TimedOut,
159 std.os.EINVAL => {}, // possibly timeout overflow
160 std.os.EFAULT => unreachable,
149 .SUCCESS => {}, // notified by `wake()`
150 .INTR => {}, // spurious wakeup
151 .AGAIN => {}, // ptr.* != expect
152 .TIMEDOUT => return error.TimedOut,
153 .INVAL => {}, // possibly timeout overflow
154 .FAULT => unreachable,
161155 else => unreachable,
162156 }
163157 }
......@@ -168,9 +162,9 @@ const LinuxFutex = struct {
168162 linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,
169163 std.math.cast(i32, num_waiters) catch std.math.maxInt(i32),
170164 ))) {
171 0 => {}, // successful wake up
172 std.os.EINVAL => {}, // invalid futex_wait() on ptr done elsewhere
173 std.os.EFAULT => {}, // pointer became invalid while doing the wake
165 .SUCCESS => {}, // successful wake up
166 .INVAL => {}, // invalid futex_wait() on ptr done elsewhere
167 .FAULT => {}, // pointer became invalid while doing the wake
174168 else => unreachable,
175169 }
176170 }
......@@ -215,13 +209,13 @@ const DarwinFutex = struct {
215209 };
216210
217211 if (status >= 0) return;
218 switch (-status) {
219 darwin.EINTR => {},
212 switch (@intToEnum(std.os.E, -status)) {
213 .INTR => {},
220214 // Address of the futex is paged out. This is unlikely, but possible in theory, and
221215 // pthread/libdispatch on darwin bother to handle it. In this case we'll return
222216 // without waiting, but the caller should retry anyway.
223 darwin.EFAULT => {},
224 darwin.ETIMEDOUT => if (!timeout_overflowed) return error.TimedOut,
217 .FAULT => {},
218 .TIMEDOUT => if (!timeout_overflowed) return error.TimedOut,
225219 else => unreachable,
226220 }
227221 }
......@@ -237,11 +231,11 @@ const DarwinFutex = struct {
237231 const status = darwin.__ulock_wake(flags, addr, 0);
238232
239233 if (status >= 0) return;
240 switch (-status) {
241 darwin.EINTR => continue, // spurious wake()
242 darwin.EFAULT => continue, // address of the lock was paged out
243 darwin.ENOENT => return, // nothing was woken up
244 darwin.EALREADY => unreachable, // only for ULF_WAKE_THREAD
234 switch (@intToEnum(std.os.E, -status)) {
235 .INTR => continue, // spurious wake()
236 .FAULT => continue, // address of the lock was paged out
237 .NOENT => return, // nothing was woken up
238 .ALREADY => unreachable, // only for ULF_WAKE_THREAD
245239 else => unreachable,
246240 }
247241 }
......@@ -255,8 +249,8 @@ const PosixFutex = struct {
255249 var waiter: List.Node = undefined;
256250
257251 {
258 assert(std.c.pthread_mutex_lock(&bucket.mutex) == 0);
259 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == 0);
252 assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
253 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
260254
261255 if (ptr.load(.SeqCst) != expect) {
262256 return;
......@@ -272,8 +266,8 @@ const PosixFutex = struct {
272266 waiter.data.wait(null) catch unreachable;
273267 };
274268
275 assert(std.c.pthread_mutex_lock(&bucket.mutex) == 0);
276 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == 0);
269 assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
270 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
277271
278272 if (waiter.data.address == address) {
279273 timed_out = true;
......@@ -297,8 +291,8 @@ const PosixFutex = struct {
297291 waiter.data.notify();
298292 };
299293
300 assert(std.c.pthread_mutex_lock(&bucket.mutex) == 0);
301 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == 0);
294 assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
295 defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
302296
303297 var waiters = bucket.list.first;
304298 while (waiters) |waiter| {
......@@ -340,16 +334,13 @@ const PosixFutex = struct {
340334 };
341335
342336 fn deinit(self: *Self) void {
343 const rc = std.c.pthread_cond_destroy(&self.cond);
344 assert(rc == 0 or rc == std.os.EINVAL);
345
346 const rm = std.c.pthread_mutex_destroy(&self.mutex);
347 assert(rm == 0 or rm == std.os.EINVAL);
337 _ = std.c.pthread_cond_destroy(&self.cond);
338 _ = std.c.pthread_mutex_destroy(&self.mutex);
348339 }
349340
350341 fn wait(self: *Self, timeout: ?u64) error{TimedOut}!void {
351 assert(std.c.pthread_mutex_lock(&self.mutex) == 0);
352 defer assert(std.c.pthread_mutex_unlock(&self.mutex) == 0);
342 assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS);
343 defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS);
353344
354345 switch (self.state) {
355346 .empty => self.state = .waiting,
......@@ -378,28 +369,31 @@ const PosixFutex = struct {
378369 }
379370
380371 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);
382373 continue;
383374 };
384375
385376 const rc = std.c.pthread_cond_timedwait(&self.cond, &self.mutex, ts_ref);
386 assert(rc == 0 or rc == std.os.ETIMEDOUT);
387 if (rc == std.os.ETIMEDOUT) {
388 self.state = .empty;
389 return error.TimedOut;
377 switch (rc) {
378 .SUCCESS => {},
379 .TIMEDOUT => {
380 self.state = .empty;
381 return error.TimedOut;
382 },
383 else => unreachable,
390384 }
391385 }
392386 }
393387
394388 fn notify(self: *Self) void {
395 assert(std.c.pthread_mutex_lock(&self.mutex) == 0);
396 defer assert(std.c.pthread_mutex_unlock(&self.mutex) == 0);
389 assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS);
390 defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS);
397391
398392 switch (self.state) {
399393 .empty => self.state = .notified,
400394 .waiting => {
401395 self.state = .notified;
402 assert(std.c.pthread_cond_signal(&self.cond) == 0);
396 assert(std.c.pthread_cond_signal(&self.cond) == .SUCCESS);
403397 },
404398 .notified => unreachable,
405399 }
lib/std/Thread/Mutex.zig+16-22
......@@ -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
71//! Lock may be held only once. If the same thread tries to acquire
82//! the same mutex twice, it deadlocks. This type supports static
93//! initialization and is at most `@sizeOf(usize)` in size. When an
......@@ -143,9 +137,9 @@ pub const AtomicMutex = struct {
143137 @enumToInt(new_state),
144138 null,
145139 ))) {
146 0 => {},
147 std.os.EINTR => {},
148 std.os.EAGAIN => {},
140 .SUCCESS => {},
141 .INTR => {},
142 .AGAIN => {},
149143 else => unreachable,
150144 }
151145 },
......@@ -164,8 +158,8 @@ pub const AtomicMutex = struct {
164158 linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,
165159 1,
166160 ))) {
167 0 => {},
168 std.os.EFAULT => {},
161 .SUCCESS => {},
162 .FAULT => unreachable, // invalid pointer passed to futex_wake
169163 else => unreachable,
170164 }
171165 },
......@@ -182,10 +176,10 @@ pub const PthreadMutex = struct {
182176
183177 pub fn release(held: Held) void {
184178 switch (std.c.pthread_mutex_unlock(&held.mutex.pthread_mutex)) {
185 0 => return,
186 std.c.EINVAL => unreachable,
187 std.c.EAGAIN => unreachable,
188 std.c.EPERM => unreachable,
179 .SUCCESS => return,
180 .INVAL => unreachable,
181 .AGAIN => unreachable,
182 .PERM => unreachable,
189183 else => unreachable,
190184 }
191185 }
......@@ -195,7 +189,7 @@ pub const PthreadMutex = struct {
195189 /// the mutex is unavailable. Otherwise returns Held. Call
196190 /// release on Held.
197191 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) {
199193 return Held{ .mutex = m };
200194 } else {
201195 return null;
......@@ -206,12 +200,12 @@ pub const PthreadMutex = struct {
206200 /// held by the calling thread.
207201 pub fn acquire(m: *PthreadMutex) Held {
208202 switch (std.c.pthread_mutex_lock(&m.pthread_mutex)) {
209 0 => return Held{ .mutex = m },
210 std.c.EINVAL => unreachable,
211 std.c.EBUSY => unreachable,
212 std.c.EAGAIN => unreachable,
213 std.c.EDEADLK => unreachable,
214 std.c.EPERM => unreachable,
203 .SUCCESS => return Held{ .mutex = m },
204 .INVAL => unreachable,
205 .BUSY => unreachable,
206 .AGAIN => unreachable,
207 .DEADLK => unreachable,
208 .PERM => unreachable,
215209 else => unreachable,
216210 }
217211 }
lib/std/Thread/ResetEvent.zig+12-18
......@@ -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
71//! A thread-safe resource which supports blocking until signaled.
82//! This API is for kernel threads, not evented I/O.
93//! This API requires being initialized at runtime, and initialization
......@@ -130,7 +124,7 @@ pub const PosixEvent = struct {
130124
131125 pub fn init(ev: *PosixEvent) !void {
132126 switch (c.getErrno(c.sem_init(&ev.sem, 0, 0))) {
133 0 => return,
127 .SUCCESS => return,
134128 else => return error.SystemResources,
135129 }
136130 }
......@@ -147,9 +141,9 @@ pub const PosixEvent = struct {
147141 pub fn wait(ev: *PosixEvent) void {
148142 while (true) {
149143 switch (c.getErrno(c.sem_wait(&ev.sem))) {
150 0 => return,
151 c.EINTR => continue,
152 c.EINVAL => unreachable,
144 .SUCCESS => return,
145 .INTR => continue,
146 .INVAL => unreachable,
153147 else => unreachable,
154148 }
155149 }
......@@ -165,10 +159,10 @@ pub const PosixEvent = struct {
165159 ts.tv_nsec = @intCast(@TypeOf(ts.tv_nsec), @mod(timeout_abs, time.ns_per_s));
166160 while (true) {
167161 switch (c.getErrno(c.sem_timedwait(&ev.sem, &ts))) {
168 0 => return .event_set,
169 c.EINTR => continue,
170 c.EINVAL => unreachable,
171 c.ETIMEDOUT => return .timed_out,
162 .SUCCESS => return .event_set,
163 .INTR => continue,
164 .INVAL => unreachable,
165 .TIMEDOUT => return .timed_out,
172166 else => unreachable,
173167 }
174168 }
......@@ -177,10 +171,10 @@ pub const PosixEvent = struct {
177171 pub fn reset(ev: *PosixEvent) void {
178172 while (true) {
179173 switch (c.getErrno(c.sem_trywait(&ev.sem))) {
180 0 => continue, // Need to make it go to zero.
181 c.EINTR => continue,
182 c.EINVAL => unreachable,
183 c.EAGAIN => return, // The semaphore currently has the value zero.
174 .SUCCESS => continue, // Need to make it go to zero.
175 .INTR => continue,
176 .INVAL => unreachable,
177 .AGAIN => return, // The semaphore currently has the value zero.
184178 else => unreachable,
185179 }
186180 }
lib/std/Thread/RwLock.zig+11-19
......@@ -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
71//! A lock that supports one writer or many readers.
82//! This API is for kernel threads, not evented I/O.
93//! This API requires being initialized at runtime, and initialization
......@@ -13,7 +7,7 @@ impl: Impl,
137
148const RwLock = @This();
159const std = @import("../std.zig");
16const builtin = std.builtin;
10const builtin = @import("builtin");
1711const assert = std.debug.assert;
1812const Mutex = std.Thread.Mutex;
1913const Semaphore = std.Semaphore;
......@@ -165,43 +159,41 @@ pub const PthreadRwLock = struct {
165159 }
166160
167161 pub fn deinit(rwl: *PthreadRwLock) void {
168 const safe_rc = switch (std.builtin.os.tag) {
169 .dragonfly, .netbsd => std.os.EAGAIN,
170 else => 0,
162 const safe_rc: std.os.E = switch (builtin.os.tag) {
163 .dragonfly, .netbsd => .AGAIN,
164 else => .SUCCESS,
171165 };
172
173166 const rc = std.c.pthread_rwlock_destroy(&rwl.rwlock);
174 assert(rc == 0 or rc == safe_rc);
175
167 assert(rc == .SUCCESS or rc == safe_rc);
176168 rwl.* = undefined;
177169 }
178170
179171 pub fn tryLock(rwl: *PthreadRwLock) bool {
180 return pthread_rwlock_trywrlock(&rwl.rwlock) == 0;
172 return pthread_rwlock_trywrlock(&rwl.rwlock) == .SUCCESS;
181173 }
182174
183175 pub fn lock(rwl: *PthreadRwLock) void {
184176 const rc = pthread_rwlock_wrlock(&rwl.rwlock);
185 assert(rc == 0);
177 assert(rc == .SUCCESS);
186178 }
187179
188180 pub fn unlock(rwl: *PthreadRwLock) void {
189181 const rc = pthread_rwlock_unlock(&rwl.rwlock);
190 assert(rc == 0);
182 assert(rc == .SUCCESS);
191183 }
192184
193185 pub fn tryLockShared(rwl: *PthreadRwLock) bool {
194 return pthread_rwlock_tryrdlock(&rwl.rwlock) == 0;
186 return pthread_rwlock_tryrdlock(&rwl.rwlock) == .SUCCESS;
195187 }
196188
197189 pub fn lockShared(rwl: *PthreadRwLock) void {
198190 const rc = pthread_rwlock_rdlock(&rwl.rwlock);
199 assert(rc == 0);
191 assert(rc == .SUCCESS);
200192 }
201193
202194 pub fn unlockShared(rwl: *PthreadRwLock) void {
203195 const rc = pthread_rwlock_unlock(&rwl.rwlock);
204 assert(rc == 0);
196 assert(rc == .SUCCESS);
205197 }
206198};
207199
lib/std/Thread/Semaphore.zig-6
......@@ -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
71//! A semaphore is an unsigned integer that blocks the kernel thread if
82//! the number would become negative.
93//! This API supports static initialization and does not require deinitialization.
lib/std/Thread/StaticResetEvent.zig+5-11
......@@ -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
71//! A thread-safe resource which supports blocking until signaled.
82//! This API is for kernel threads, not evented I/O.
93//! This API is statically initializable. It cannot fail to be initialized
......@@ -201,7 +195,7 @@ pub const AtomicEvent = struct {
201195 const waiting = std.math.maxInt(i32); // wake_count
202196 const ptr = @ptrCast(*const i32, waiters);
203197 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);
205199 }
206200
207201 fn wait(waiters: *u32, timeout: ?u64) !void {
......@@ -221,10 +215,10 @@ pub const AtomicEvent = struct {
221215 const ptr = @ptrCast(*const i32, waiters);
222216 const rc = linux.futex_wait(ptr, linux.FUTEX_WAIT | linux.FUTEX_PRIVATE_FLAG, expected, ts_ptr);
223217 switch (linux.getErrno(rc)) {
224 0 => continue,
225 os.ETIMEDOUT => return error.TimedOut,
226 os.EINTR => continue,
227 os.EAGAIN => return,
218 .SUCCESS => continue,
219 .TIMEDOUT => return error.TimedOut,
220 .INTR => continue,
221 .AGAIN => return,
228222 else => unreachable,
229223 }
230224 }
lib/std/array_hash_map.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const debug = std.debug;
83const assert = debug.assert;
lib/std/array_list.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const debug = std.debug;
83const assert = debug.assert;
lib/std/ascii.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Does NOT look at the locale the way C89's toupper(3), isspace() et cetera does.
72// I could have taken only a u7 to make this clear, but it would be slower
83// It is my opinion that encodings other than UTF-8 should not be supported.
lib/std/atomic.zig-6
......@@ -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
71const std = @import("std.zig");
82const target = std.Target.current;
93
lib/std/atomic/Atomic.zig-6
......@@ -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
71const std = @import("../std.zig");
82
93const testing = std.testing;
lib/std/atomic/queue.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const assert = std.debug.assert;
lib/std/atomic/stack.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const assert = std.debug.assert;
72const builtin = std.builtin;
83const expect = std.testing.expect;
lib/std/base64.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const assert = std.debug.assert;
83const testing = std.testing;
lib/std/bit_set.zig-6
......@@ -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
71//! This file defines several variants of bit sets. A bit set
82//! is a densely stored set of integers with a known maximum,
93//! 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const StringHashMap = std.StringHashMap;
83const mem = std.mem;
lib/std/buf_set.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const StringHashMap = std.StringHashMap;
83const mem = @import("mem.zig");
lib/std/build.zig+49-230
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const builtin = std.builtin;
83const io = std.io;
......@@ -28,6 +23,7 @@ pub const WriteFileStep = @import("build/WriteFileStep.zig");
2823pub const RunStep = @import("build/RunStep.zig");
2924pub const CheckFileStep = @import("build/CheckFileStep.zig");
3025pub const InstallRawStep = @import("build/InstallRawStep.zig");
26pub const OptionsStep = @import("build/OptionsStep.zig");
3127
3228pub const Builder = struct {
3329 install_tls: TopLevelStep,
......@@ -252,6 +248,10 @@ pub const Builder = struct {
252248 return LibExeObjStep.createExecutable(builder, name, root_src);
253249 }
254250
251 pub fn addOptions(self: *Builder) *OptionsStep {
252 return OptionsStep.create(self);
253 }
254
255255 pub fn addObject(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep {
256256 return addObjectSource(self, name, convertOptionalPathToFileSource(root_src));
257257 }
......@@ -1380,16 +1380,6 @@ pub const FileSource = union(enum) {
13801380 }
13811381};
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
13931383pub const LibExeObjStep = struct {
13941384 pub const base_id = .lib_exe_obj;
13951385
......@@ -1432,15 +1422,13 @@ pub const LibExeObjStep = struct {
14321422 single_threaded: bool,
14331423 test_evented_io: bool = false,
14341424 code_model: builtin.CodeModel = .default,
1425 wasi_exec_model: ?builtin.WasiExecModel = null,
14351426
14361427 root_src: ?FileSource,
14371428 out_h_filename: []const u8,
14381429 out_lib_filename: []const u8,
14391430 out_pdb_filename: []const u8,
14401431 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
14451433 object_src: []const u8,
14461434
......@@ -1607,9 +1595,6 @@ pub const LibExeObjStep = struct {
16071595 .rpaths = ArrayList([]const u8).init(builder.allocator),
16081596 .framework_dirs = ArrayList([]const u8).init(builder.allocator),
16091597 .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),
16131598 .c_std = Builder.CStd.C99,
16141599 .override_lib_dir = null,
16151600 .main_pkg_path = null,
......@@ -1735,7 +1720,6 @@ pub const LibExeObjStep = struct {
17351720 }
17361721
17371722 pub fn linkFramework(self: *LibExeObjStep, framework_name: []const u8) void {
1738 assert(self.target.isDarwin());
17391723 // Note: No need to dupe because frameworks dupes internally.
17401724 self.frameworks.insert(framework_name) catch unreachable;
17411725 }
......@@ -2043,119 +2027,6 @@ pub const LibExeObjStep = struct {
20432027 self.linkLibraryOrObject(obj);
20442028 }
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
21592030 pub fn addSystemIncludeDir(self: *LibExeObjStep, path: []const u8) void {
21602031 self.include_dirs.append(IncludeDir{ .raw_path_system = self.builder.dupe(path) }) catch unreachable;
21612032 }
......@@ -2181,6 +2052,10 @@ pub const LibExeObjStep = struct {
21812052 self.addRecursiveBuildDeps(package);
21822053 }
21832054
2055 pub fn addOptions(self: *LibExeObjStep, package_name: []const u8, options: *OptionsStep) void {
2056 self.addPackage(options.getPackage(package_name));
2057 }
2058
21842059 fn addRecursiveBuildDeps(self: *LibExeObjStep, package: Pkg) void {
21852060 package.path.addStepDependencies(&self.step);
21862061 if (package.dependencies) |deps| {
......@@ -2247,28 +2122,6 @@ pub const LibExeObjStep = struct {
22472122 self.step.dependOn(&other.step);
22482123 self.link_objects.append(.{ .other_step = other }) catch unreachable;
22492124 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 }
22722125 }
22732126
22742127 fn makePackageCmd(self: *LibExeObjStep, pkg: Pkg, zig_args: *ArrayList([]const u8)) error{OutOfMemory}!void {
......@@ -2322,6 +2175,31 @@ pub const LibExeObjStep = struct {
23222175 if (self.root_src) |root_src| try zig_args.append(root_src.getPath(builder));
23232176
23242177 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
23252203 for (self.link_objects.items) |link_object| {
23262204 switch (link_object) {
23272205 .static_path => |static_path| try zig_args.append(static_path.getPath(builder)),
......@@ -2395,41 +2273,6 @@ pub const LibExeObjStep = struct {
23952273 }
23962274 }
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
24332276 if (self.image_base) |image_base| {
24342277 try zig_args.append("--image-base");
24352278 try zig_args.append(builder.fmt("0x{x}", .{image_base}));
......@@ -2547,6 +2390,9 @@ pub const LibExeObjStep = struct {
25472390 try zig_args.append("-mcmodel");
25482391 try zig_args.append(@tagName(self.code_model));
25492392 }
2393 if (self.wasi_exec_model) |model| {
2394 try zig_args.append(builder.fmt("-mexec-model={s}", .{@tagName(model)}));
2395 }
25502396
25512397 if (!self.target.isNative()) {
25522398 try zig_args.append("-target");
......@@ -2719,6 +2565,14 @@ pub const LibExeObjStep = struct {
27192565 zig_args.append("-framework") catch unreachable;
27202566 zig_args.append(framework.*) catch unreachable;
27212567 }
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 }
27222576 }
27232577
27242578 if (builder.sysroot) |sysroot| {
......@@ -3026,7 +2880,8 @@ pub const InstallDirStep = struct {
30262880 const self = @fieldParentPtr(InstallDirStep, "step", step);
30272881 const dest_prefix = self.builder.getInstallPath(self.options.install_dir, self.options.install_subdir);
30282882 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();
30302885 var it = try src_dir.walk(self.builder.allocator);
30312886 next_entry: while (try it.next()) |entry| {
30322887 for (self.options.exclude_extensions) |ext| {
......@@ -3131,6 +2986,7 @@ pub const Step = struct {
31312986 run,
31322987 check_file,
31332988 install_raw,
2989 options,
31342990 custom,
31352991 };
31362992
......@@ -3302,43 +3158,6 @@ test "Builder.dupePkg()" {
33023158 try std.testing.expect(dupe_deps[0].path.path.ptr != pkg_dep.path.path.ptr);
33033159}
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
33423161test "LibExeObjStep.addPackage" {
33433162 if (builtin.os.tag == .wasi) return error.SkipZigTest;
33443163
lib/std/build/CheckFileStep.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const build = std.build;
83const Step = build.Step;
lib/std/build/FmtStep.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const build = @import("../build.zig");
83const Step = build.Step;
lib/std/build/InstallRawStep.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72
83const 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const build = std.build;
lib/std/build/TranslateCStep.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const build = std.build;
83const Step = build.Step;
lib/std/build/WriteFileStep.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const build = @import("../build.zig");
83const Step = build.Step;
lib/std/builtin.zig+8-12
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72
83// These are all deprecated.
......@@ -237,7 +232,7 @@ pub const TypeInfo = union(enum) {
237232 /// This field is an optional type.
238233 /// The type of the sentinel is the element type of the pointer, which is
239234 /// 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`.
241236 sentinel: anytype,
242237
243238 /// This data structure is used by the Zig language code generation and
......@@ -259,7 +254,7 @@ pub const TypeInfo = union(enum) {
259254 /// This field is an optional type.
260255 /// The type of the sentinel is the element type of the array, which is
261256 /// 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`.
263258 sentinel: anytype,
264259 };
265260
......@@ -671,7 +666,12 @@ pub const PanicFn = fn ([]const u8, ?*StackTrace) noreturn;
671666
672667/// This function is used by the Zig language code generation and
673668/// 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
676676/// This function is used by the Zig language code generation and
677677/// 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
684684 @breakpoint();
685685 }
686686 }
687 if (@hasDecl(root, "os") and @hasDecl(root.os, "panic")) {
688 root.os.panic(msg, error_return_trace);
689 unreachable;
690 }
691687 switch (os.tag) {
692688 .freestanding => {
693689 while (true) {
lib/std/c.zig+29-34
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = std.builtin;
83const page_size = std.mem.page_size;
......@@ -35,11 +30,11 @@ pub usingnamespace switch (std.Target.current.os.tag) {
3530 else => struct {},
3631};
3732
38pub fn getErrno(rc: anytype) c_int {
33pub fn getErrno(rc: anytype) E {
3934 if (rc == -1) {
40 return _errno().*;
35 return @intToEnum(E, _errno().*);
4136 } else {
42 return 0;
37 return .SUCCESS;
4338 }
4439}
4540
......@@ -270,22 +265,22 @@ pub extern "c" fn utimes(path: [*:0]const u8, times: *[2]timeval) c_int;
270265pub extern "c" fn utimensat(dirfd: fd_t, pathname: [*:0]const u8, times: *[2]timespec, flags: u32) c_int;
271266pub 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;
274pub extern "c" fn pthread_attr_init(attr: *pthread_attr_t) c_int;
275pub extern "c" fn pthread_attr_setstack(attr: *pthread_attr_t, stackaddr: *c_void, stacksize: usize) c_int;
276pub extern "c" fn pthread_attr_setstacksize(attr: *pthread_attr_t, stacksize: usize) c_int;
277pub extern "c" fn pthread_attr_setguardsize(attr: *pthread_attr_t, guardsize: usize) c_int;
278pub extern "c" fn pthread_attr_destroy(attr: *pthread_attr_t) 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;
269pub extern "c" fn pthread_attr_init(attr: *pthread_attr_t) E;
270pub extern "c" fn pthread_attr_setstack(attr: *pthread_attr_t, stackaddr: *c_void, stacksize: usize) E;
271pub extern "c" fn pthread_attr_setstacksize(attr: *pthread_attr_t, stacksize: usize) E;
272pub extern "c" fn pthread_attr_setguardsize(attr: *pthread_attr_t, guardsize: usize) E;
273pub extern "c" fn pthread_attr_destroy(attr: *pthread_attr_t) E;
279274pub extern "c" fn pthread_self() pthread_t;
280pub extern "c" fn pthread_join(thread: pthread_t, arg_return: ?*?*c_void) c_int;
281pub extern "c" fn pthread_detach(thread: pthread_t) c_int;
275pub extern "c" fn pthread_join(thread: pthread_t, arg_return: ?*?*c_void) E;
276pub extern "c" fn pthread_detach(thread: pthread_t) E;
282277pub extern "c" fn pthread_atfork(
283278 prepare: ?fn () callconv(.C) void,
284279 parent: ?fn () callconv(.C) void,
285280 child: ?fn () callconv(.C) void,
286281) c_int;
287pub extern "c" fn pthread_key_create(key: *pthread_key_t, destructor: ?fn (value: *c_void) callconv(.C) void) c_int;
288pub extern "c" fn pthread_key_delete(key: pthread_key_t) c_int;
282pub extern "c" fn pthread_key_create(key: *pthread_key_t, destructor: ?fn (value: *c_void) callconv(.C) void) E;
283pub extern "c" fn pthread_key_delete(key: pthread_key_t) E;
289284pub extern "c" fn pthread_getspecific(key: pthread_key_t) ?*c_void;
290285pub extern "c" fn pthread_setspecific(key: pthread_key_t, value: ?*c_void) c_int;
291286pub 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(
339334) c_int;
340335
341336pub const PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{};
342pub extern "c" fn pthread_mutex_lock(mutex: *pthread_mutex_t) c_int;
343pub extern "c" fn pthread_mutex_unlock(mutex: *pthread_mutex_t) c_int;
344pub extern "c" fn pthread_mutex_trylock(mutex: *pthread_mutex_t) c_int;
345pub extern "c" fn pthread_mutex_destroy(mutex: *pthread_mutex_t) c_int;
337pub extern "c" fn pthread_mutex_lock(mutex: *pthread_mutex_t) E;
338pub extern "c" fn pthread_mutex_unlock(mutex: *pthread_mutex_t) E;
339pub extern "c" fn pthread_mutex_trylock(mutex: *pthread_mutex_t) E;
340pub extern "c" fn pthread_mutex_destroy(mutex: *pthread_mutex_t) E;
346341
347342pub 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;
349pub extern "c" fn pthread_cond_timedwait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t, noalias abstime: *const timespec) c_int;
350pub extern "c" fn pthread_cond_signal(cond: *pthread_cond_t) c_int;
351pub extern "c" fn pthread_cond_broadcast(cond: *pthread_cond_t) c_int;
352pub extern "c" fn pthread_cond_destroy(cond: *pthread_cond_t) c_int;
353
354pub extern "c" fn pthread_rwlock_destroy(rwl: *pthread_rwlock_t) callconv(.C) c_int;
355pub extern "c" fn pthread_rwlock_rdlock(rwl: *pthread_rwlock_t) callconv(.C) c_int;
356pub extern "c" fn pthread_rwlock_wrlock(rwl: *pthread_rwlock_t) callconv(.C) c_int;
357pub extern "c" fn pthread_rwlock_tryrdlock(rwl: *pthread_rwlock_t) callconv(.C) c_int;
358pub extern "c" fn pthread_rwlock_trywrlock(rwl: *pthread_rwlock_t) callconv(.C) c_int;
359pub extern "c" fn pthread_rwlock_unlock(rwl: *pthread_rwlock_t) callconv(.C) c_int;
343pub extern "c" fn pthread_cond_wait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t) E;
344pub extern "c" fn pthread_cond_timedwait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t, noalias abstime: *const timespec) E;
345pub extern "c" fn pthread_cond_signal(cond: *pthread_cond_t) E;
346pub extern "c" fn pthread_cond_broadcast(cond: *pthread_cond_t) E;
347pub extern "c" fn pthread_cond_destroy(cond: *pthread_cond_t) E;
348
349pub extern "c" fn pthread_rwlock_destroy(rwl: *pthread_rwlock_t) callconv(.C) E;
350pub extern "c" fn pthread_rwlock_rdlock(rwl: *pthread_rwlock_t) callconv(.C) E;
351pub extern "c" fn pthread_rwlock_wrlock(rwl: *pthread_rwlock_t) callconv(.C) E;
352pub extern "c" fn pthread_rwlock_tryrdlock(rwl: *pthread_rwlock_t) callconv(.C) E;
353pub extern "c" fn pthread_rwlock_trywrlock(rwl: *pthread_rwlock_t) callconv(.C) E;
354pub extern "c" fn pthread_rwlock_unlock(rwl: *pthread_rwlock_t) callconv(.C) E;
360355
361356pub const pthread_t = *opaque {};
362357pub const FILE = opaque {};
lib/std/c/darwin.zig+2-7
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const assert = std.debug.assert;
83const builtin = @import("builtin");
......@@ -193,8 +188,8 @@ pub const pthread_attr_t = extern struct {
193188
194189const pthread_t = std.c.pthread_t;
195190pub 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;
197pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) c_int;
191pub extern "c" fn pthread_setname_np(name: [*:0]const u8) E;
192pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
198193
199194pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void;
200195
lib/std/c/dragonfly.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72usingnamespace std.c;
83extern "c" threadlocal var errno: c_int;
lib/std/c/emscripten.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const pthread_mutex_t = extern struct {
72 size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(4) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
83};
lib/std/c/freebsd.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72usingnamespace std.c;
83
lib/std/c/fuchsia.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const pthread_mutex_t = extern struct {
72 size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
83};
lib/std/c/haiku.zig-6
......@@ -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
71//
82const std = @import("../std.zig");
93const builtin = std.builtin;
lib/std/c/hermit.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const pthread_mutex_t = extern struct {
72 inner: usize = ~@as(usize, 0),
83};
lib/std/c/linux.zig+2-7
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const maxInt = std.math.maxInt;
83const abi = std.Target.current.abi;
......@@ -186,8 +181,8 @@ const __SIZEOF_PTHREAD_MUTEX_T = if (os_tag == .fuchsia) 40 else switch (abi) {
186181};
187182const __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;
190pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) c_int;
184pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8) E;
185pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
191186
192187pub const RTLD_LAZY = 1;
193188pub const RTLD_NOW = 2;
lib/std/c/minix.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72pub const pthread_mutex_t = extern struct {
83 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83
......@@ -95,5 +90,5 @@ pub const pthread_attr_t = extern struct {
9590
9691pub 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;
99pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) c_int;
93pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8, arg: ?*c_void) E;
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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83
lib/std/c/solaris.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const pthread_mutex_t = extern struct {
72 __pthread_mutex_flag1: u16 = 0,
83 __pthread_mutex_flag2: u8 = 0,
lib/std/c/tokenizer.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const mem = std.mem;
83
lib/std/c/wasi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("../os/bits.zig");
72
83extern threadlocal var errno: c_int;
lib/std/c/windows.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub extern "c" fn _errno() *c_int;
72
83pub extern "c" fn _msize(memblock: ?*c_void) usize;
lib/std/child_process.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const cstr = std.cstr;
83const unicode = std.unicode;
lib/std/coff.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = std.builtin;
72const std = @import("std.zig");
83const io = std.io;
lib/std/compress.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72
83pub const deflate = @import("compress/deflate.zig");
lib/std/compress/deflate.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61//
72// Decompressor for DEFLATE data streams (RFC1951)
83//
lib/std/compress/gzip.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61//
72// Decompressor for GZIP data streams (RFC1952)
83
lib/std/compress/zlib.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61//
72// Decompressor for ZLIB data streams (RFC1950)
83
lib/std/comptime_string_map.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const mem = std.mem;
83
lib/std/crypto.zig+9-6
......@@ -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
71/// Authenticated Encryption with Associated Data
82pub const aead = struct {
93 pub const aegis = struct {
......@@ -110,7 +104,16 @@ pub const onetimeauth = struct {
110104///
111105/// Password hashing functions must be used whenever sensitive data has to be directly derived from a password.
112106pub 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
113115 pub const bcrypt = @import("crypto/bcrypt.zig");
116 pub const scrypt = @import("crypto/scrypt.zig");
114117 pub const pbkdf2 = @import("crypto/pbkdf2.zig").pbkdf2;
115118};
116119
lib/std/crypto/25519/curve25519.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const crypto = std.crypto;
83
lib/std/crypto/25519/ed25519.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const crypto = std.crypto;
83const debug = std.debug;
lib/std/crypto/25519/edwards25519.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const crypto = std.crypto;
83const debug = std.debug;
lib/std/crypto/25519/field.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const crypto = std.crypto;
83const readIntLittle = std.mem.readIntLittle;
lib/std/crypto/25519/ristretto255.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const fmt = std.fmt;
83
lib/std/crypto/25519/scalar.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const mem = std.mem;
83
lib/std/crypto/25519/x25519.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const crypto = std.crypto;
83const mem = std.mem;
lib/std/crypto/aegis.zig-6
......@@ -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
71const std = @import("std");
82const mem = std.mem;
93const assert = std.debug.assert;
lib/std/crypto/aes.zig-6
......@@ -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
71const std = @import("../std.zig");
82const testing = std.testing;
93const builtin = std.builtin;
lib/std/crypto/aes/aesni.zig-6
......@@ -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
71const std = @import("../../std.zig");
82const mem = std.mem;
93const debug = std.debug;
lib/std/crypto/aes/armcrypto.zig-6
......@@ -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
71const std = @import("../../std.zig");
82const mem = std.mem;
93const debug = std.debug;
lib/std/crypto/aes/soft.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Based on Go stdlib implementation
72
83const std = @import("../../std.zig");
lib/std/crypto/aes_gcm.zig-6
......@@ -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
71const std = @import("std");
82const assert = std.debug.assert;
93const builtin = std.builtin;
lib/std/crypto/aes_ocb.zig-6
......@@ -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
71const std = @import("std");
82const crypto = std.crypto;
93const aes = crypto.core.aes;
lib/std/crypto/bcrypt.zig+298-109
......@@ -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
71const std = @import("std");
82const crypto = std.crypto;
3const debug = std.debug;
94const fmt = std.fmt;
105const math = std.math;
116const mem = std.mem;
12const debug = std.debug;
7const pwhash = crypto.pwhash;
138const testing = std.testing;
149const utils = crypto.utils;
15const EncodingError = crypto.errors.EncodingError;
16const PasswordVerificationError = crypto.errors.PasswordVerificationError;
10
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
1818const salt_length: usize = 16;
1919const salt_str_length: usize = 22;
2020const ct_str_length: usize = 31;
2121const ct_length: usize = 24;
22const dk_length: usize = ct_length - 1;
2223
23/// Length (in bytes) of a password hash
24/// Length (in bytes) of a password hash in crypt encoding
2425pub const hash_length: usize = 60;
2526
2627const State = struct {
......@@ -139,71 +140,15 @@ const State = struct {
139140 }
140141};
141142
142// bcrypt has its own variant of base64, with its own alphabet and no padding
143const Codec = struct {
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 }
143pub const Params = struct {
144 rounds_log: u6,
204145};
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 {
207152 var state = State{};
208153 var password_buf: [73]u8 = undefined;
209154 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)
212157 var passwordZ = password_buf[0 .. trimmed_len + 1];
213158 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;
216161 var k: u64 = 0;
217162 while (k < rounds) : (k += 1) {
218163 state.expand0(passwordZ);
......@@ -230,18 +175,203 @@ fn strHashInternal(password: []const u8, rounds_log: u6, salt: [salt_length]u8)
230175 for (cdata) |c, i| {
231176 mem.writeIntBig(u32, ct[i * 4 ..][0..4], c);
232177 }
178 return ct[0..dk_length].*;
179}
233180
234 var salt_str: [salt_str_length]u8 = undefined;
235 Codec.encode(salt_str[0..], salt[0..]);
181const crypt_format = struct {
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;
238 Codec.encode(ct_str[0..], ct[0 .. ct.len - 1]);
224 fn decode(bin: []u8, b64: []const u8) EncodingError!void {
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;
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;
242 debug.assert(s.len == s_buf.len);
243 return s_buf;
244}
277/// Hash and verify passwords using the PHC format.
278const PhcFormatHasher = struct {
279 const alg_id = "bcrypt";
280 const BinValue = phc_format.BinValue;
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
246376/// Compute a hash of a password using 2^rounds_log rounds of the bcrypt key stretching function.
247377/// 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)
251381/// IMPORTANT: by design, bcrypt silently truncates passwords to 72 bytes.
252382/// If this is an issue for your application, hash the password first using a function such as SHA-512,
253383/// and then use the resulting hash as the password parameter for bcrypt.
254pub fn strHash(password: []const u8, rounds_log: u6) ![hash_length]u8 {
255 var salt: [salt_length]u8 = undefined;
256 crypto.random.bytes(&salt);
257 return strHashInternal(password, rounds_log, salt);
384pub fn strHash(
385 password: []const u8,
386 options: HashOptions,
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 }
258393}
259394
395/// Options for hash verification.
396pub const VerifyOptions = struct {
397 allocator: ?*mem.Allocator = null,
398};
399
260400/// 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 {
262 if (!mem.eql(u8, "$2", h[0..2])) return error.InvalidEncoding;
263 if (h[3] != '$' or h[6] != '$') return error.InvalidEncoding;
264 const rounds_log_str = h[4..][0..2];
265 const salt_str = h[7..][0..salt_str_length];
266 var salt: [salt_length]u8 = undefined;
267 try Codec.decode(salt[0..], salt_str[0..]);
268 const rounds_log = fmt.parseInt(u6, rounds_log_str[0..], 10) catch return error.InvalidEncoding;
269 const wanted_s = try strHashInternal(password, rounds_log, salt);
270 if (!mem.eql(u8, wanted_s[0..], h[0..])) {
271 return error.PasswordVerificationFailed;
401pub fn strVerify(
402 str: []const u8,
403 password: []const u8,
404 _: VerifyOptions,
405) Error!void {
406 if (mem.startsWith(u8, str, crypt_format.prefix)) {
407 return CryptFormatHasher.verify(str, password);
408 } else {
409 return PhcFormatHasher.verify(str, password);
272410 }
273411}
274412
......@@ -276,20 +414,71 @@ test "bcrypt codec" {
276414 var salt: [salt_length]u8 = undefined;
277415 crypto.random.bytes(&salt);
278416 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..]);
280418 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..]);
282420 try testing.expectEqualSlices(u8, salt[0..], salt2[0..]);
283421}
284422
285test "bcrypt" {
286 const s = try strHash("password", 5);
287 try strVerify(s, "password");
288 try testing.expectError(error.PasswordVerificationFailed, strVerify(s, "invalid password"));
289
290 const long_s = try strHash("password" ** 100, 5);
291 try strVerify(long_s, "password" ** 100);
292 try strVerify(long_s, "password" ** 101);
423test "bcrypt crypt format" {
424 const hash_options = HashOptions{
425 .params = .{ .rounds_log = 5 },
426 .encoding = .crypt,
427 };
428 const verify_options = VerifyOptions{};
429
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 );
295484}
lib/std/crypto/benchmark.zig+44-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// zig run benchmark.zig --release-fast --zig-lib-dir ..
72
83const std = @import("../std.zig");
......@@ -300,6 +295,43 @@ pub fn benchmarkAes8(comptime Aes: anytype, comptime count: comptime_int) !u64 {
300295 return throughput;
301296}
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
303335fn usage() void {
304336 std.debug.warn(
305337 \\throughput_test [options]
......@@ -418,4 +450,11 @@ pub fn main() !void {
418450 try stdout.print("{s:>17}: {:10} ops/s\n", .{ E.name, throughput });
419451 }
420452 }
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 }
421460}
lib/std/crypto/blake2.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const mem = std.mem;
83const math = std.math;
lib/std/crypto/blake3.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Translated from BLAKE3 reference implementation.
72// Source: https://github.com/BLAKE3-team/BLAKE3
83
lib/std/crypto/chacha20.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Based on public domain Supercop by Daniel J. Bernstein
72
83const std = @import("../std.zig");
lib/std/crypto/ghash.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61//
72// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Gimli is a 384-bit permutation designed to achieve high security with high
72// performance across a broad range of platforms, including 64-bit Intel/AMD
83// server CPUs, 64-bit and 32-bit ARM smartphone CPUs, 32-bit ARM
lib/std/crypto/hkdf.zig-6
......@@ -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
71const std = @import("../std.zig");
82const assert = std.debug.assert;
93const hmac = std.crypto.auth.hmac;
lib/std/crypto/hmac.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const crypto = std.crypto;
83const debug = std.debug;
lib/std/crypto/md5.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const mem = std.mem;
83const math = std.math;
lib/std/crypto/modes.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Based on Go stdlib implementation
72
83const std = @import("../std.zig");
lib/std/crypto/pbkdf2.zig-6
......@@ -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
71const std = @import("std");
82const mem = std.mem;
93const maxInt = std.math.maxInt;
lib/std/crypto/pcurves/p256.zig-6
......@@ -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
71const std = @import("std");
82const builtin = std.builtin;
93const crypto = std.crypto;
lib/std/crypto/pcurves/p256/field.zig-6
......@@ -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
71const std = @import("std");
82const common = @import("../common.zig");
93
lib/std/crypto/pcurves/p256/scalar.zig-6
......@@ -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
71const std = @import("std");
82const builtin = std.builtin;
93const common = @import("../common.zig");
lib/std/crypto/pcurves/tests.zig-6
......@@ -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
71const std = @import("std");
82const fmt = std.fmt;
93const 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const utils = std.crypto.utils;
83const mem = std.mem;
lib/std/crypto/salsa20.zig-6
......@@ -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
71const std = @import("std");
82const crypto = std.crypto;
93const 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const mem = std.mem;
83const math = std.math;
lib/std/crypto/sha2.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const mem = std.mem;
83const math = std.math;
lib/std/crypto/sha3.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const mem = std.mem;
83const math = std.math;
lib/std/crypto/siphash.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61//
72// SipHash is a moderately fast pseudorandom function, returning a 64-bit or 128-bit tag for an arbitrary long input.
83//
lib/std/crypto/test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const testing = std.testing;
83const fmt = std.fmt;
lib/std/crypto/tlcsprng.zig-6
......@@ -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
71//! Thread-local cryptographically secure pseudo-random number generator.
82//! This file has public declarations that are intended to be used internally
93//! by the standard library; this namespace is not intended to be exposed
lib/std/cstr.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const builtin = std.builtin;
83const debug = std.debug;
lib/std/debug.zig+2-7
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const builtin = std.builtin;
83const math = std.math;
......@@ -36,7 +31,7 @@ pub const LineInfo = struct {
3631 file_name: []const u8,
3732 allocator: ?*mem.Allocator,
3833
39 fn deinit(self: LineInfo) void {
34 pub fn deinit(self: LineInfo) void {
4035 const allocator = self.allocator orelse return;
4136 allocator.free(self.file_name);
4237 }
......@@ -47,7 +42,7 @@ pub const SymbolInfo = struct {
4742 compile_unit_name: []const u8 = "???",
4843 line_info: ?LineInfo = null,
4944
50 fn deinit(self: @This()) void {
45 pub fn deinit(self: @This()) void {
5146 if (self.line_info) |li| {
5247 li.deinit();
5348 }
lib/std/dwarf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const builtin = std.builtin;
83const debug = std.debug;
lib/std/dwarf_bits.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const TAG_padding = 0x00;
72pub const TAG_array_type = 0x01;
83pub const TAG_class_type = 0x02;
lib/std/dynamic_library.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = std.builtin;
72
83const std = @import("std.zig");
lib/std/elf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const io = std.io;
83const os = std.os;
lib/std/enums.zig-6
......@@ -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
71//! This module contains utilities and data structures for working with enums.
82
93const std = @import("std.zig");
lib/std/event.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const Channel = @import("event/channel.zig").Channel;
72pub const Future = @import("event/future.zig").Future;
83pub const Group = @import("event/group.zig").Group;
lib/std/event/batch.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const testing = std.testing;
83
lib/std/event/channel.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const assert = std.debug.assert;
lib/std/event/future.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const assert = std.debug.assert;
83const testing = std.testing;
lib/std/event/group.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const Lock = std.event.Lock;
lib/std/event/lock.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const assert = std.debug.assert;
lib/std/event/locked.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const Lock = std.event.Lock;
83
lib/std/event/loop.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const root = @import("root");
lib/std/event/rwlock.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const assert = std.debug.assert;
lib/std/event/rwlocked.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const RwLock = std.event.RwLock;
83
lib/std/event/wait_group.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const Loop = std.event.Loop;
lib/std/fifo.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// FIFO of fixed size items
72// Usually used for e.g. byte buffers
83
lib/std/fmt.zig+1-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const math = std.math;
83const assert = std.debug.assert;
......@@ -1757,6 +1752,7 @@ test "parseUnsigned" {
17571752}
17581753
17591754pub const parseFloat = @import("fmt/parse_float.zig").parseFloat;
1755pub const ParseFloatError = @import("fmt/parse_float.zig").ParseFloatError;
17601756pub const parseHexFloat = @import("fmt/parse_hex_float.zig").parseHexFloat;
17611757
17621758test {
lib/std/fmt/errol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const enum3 = @import("errol/enum3.zig").enum3;
83const enum3_data = @import("errol/enum3.zig").enum3_data;
lib/std/fmt/errol/enum3.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const enum3 = [_]u64{
72 0x4e2e2785c3a2a20b,
83 0x240a28877a09a4e1,
lib/std/fmt/errol/lookup.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const HP = struct {
72 val: f64,
83 off: f64,
lib/std/fmt/parse_float.zig+3-6
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Adapted from https://github.com/grzegorz-kraszewski/stringtofloat.
72
83// MIT License
......@@ -349,7 +344,9 @@ fn caseInEql(a: []const u8, b: []const u8) bool {
349344 return true;
350345}
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 {
353350 if (s.len == 0 or (s.len == 1 and (s[0] == '+' or s[0] == '-'))) {
354351 return error.InvalidCharacter;
355352 }
lib/std/fmt/parse_hex_float.zig-6
......@@ -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//
71// The rounding logic is inspired by LLVM's APFloat and Go's atofHex
82// implementation.
93
lib/std/fs.zig+39-35
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const root = @import("root");
72const builtin = std.builtin;
83const std = @import("std.zig");
......@@ -339,10 +334,10 @@ pub const Dir = struct {
339334 if (rc == 0) return null;
340335 if (rc < 0) {
341336 switch (os.errno(rc)) {
342 os.EBADF => unreachable, // Dir is invalid or was opened without iteration ability
343 os.EFAULT => unreachable,
344 os.ENOTDIR => unreachable,
345 os.EINVAL => unreachable,
337 .BADF => unreachable, // Dir is invalid or was opened without iteration ability
338 .FAULT => unreachable,
339 .NOTDIR => unreachable,
340 .INVAL => unreachable,
346341 else => |err| return os.unexpectedErrno(err),
347342 }
348343 }
......@@ -385,11 +380,11 @@ pub const Dir = struct {
385380 else
386381 os.system.getdents(self.dir.fd, &self.buf, self.buf.len);
387382 switch (os.errno(rc)) {
388 0 => {},
389 os.EBADF => unreachable, // Dir is invalid or was opened without iteration ability
390 os.EFAULT => unreachable,
391 os.ENOTDIR => unreachable,
392 os.EINVAL => unreachable,
383 .SUCCESS => {},
384 .BADF => unreachable, // Dir is invalid or was opened without iteration ability
385 .FAULT => unreachable,
386 .NOTDIR => unreachable,
387 .INVAL => unreachable,
393388 else => |err| return os.unexpectedErrno(err),
394389 }
395390 if (rc == 0) return null;
......@@ -457,10 +452,10 @@ pub const Dir = struct {
457452 if (rc == 0) return null;
458453 if (rc < 0) {
459454 switch (os.errno(rc)) {
460 os.EBADF => unreachable, // Dir is invalid or was opened without iteration ability
461 os.EFAULT => unreachable,
462 os.ENOTDIR => unreachable,
463 os.EINVAL => unreachable,
455 .BADF => unreachable, // Dir is invalid or was opened without iteration ability
456 .FAULT => unreachable,
457 .NOTDIR => unreachable,
458 .INVAL => unreachable,
464459 else => |err| return os.unexpectedErrno(err),
465460 }
466461 }
......@@ -522,11 +517,11 @@ pub const Dir = struct {
522517 if (self.index >= self.end_index) {
523518 const rc = os.linux.getdents64(self.dir.fd, &self.buf, self.buf.len);
524519 switch (os.linux.getErrno(rc)) {
525 0 => {},
526 os.EBADF => unreachable, // Dir is invalid or was opened without iteration ability
527 os.EFAULT => unreachable,
528 os.ENOTDIR => unreachable,
529 os.EINVAL => unreachable,
520 .SUCCESS => {},
521 .BADF => unreachable, // Dir is invalid or was opened without iteration ability
522 .FAULT => unreachable,
523 .NOTDIR => unreachable,
524 .INVAL => unreachable,
530525 else => |err| return os.unexpectedErrno(err),
531526 }
532527 if (rc == 0) return null;
......@@ -655,12 +650,12 @@ pub const Dir = struct {
655650 if (self.index >= self.end_index) {
656651 var bufused: usize = undefined;
657652 switch (w.fd_readdir(self.dir.fd, &self.buf, self.buf.len, self.cookie, &bufused)) {
658 w.ESUCCESS => {},
659 w.EBADF => unreachable, // Dir is invalid or was opened without iteration ability
660 w.EFAULT => unreachable,
661 w.ENOTDIR => unreachable,
662 w.EINVAL => unreachable,
663 w.ENOTCAPABLE => return error.AccessDenied,
653 .SUCCESS => {},
654 .BADF => unreachable, // Dir is invalid or was opened without iteration ability
655 .FAULT => unreachable,
656 .NOTDIR => unreachable,
657 .INVAL => unreachable,
658 .NOTCAPABLE => return error.AccessDenied,
664659 else => |err| return os.unexpectedErrno(err),
665660 }
666661 if (bufused == 0) return null;
......@@ -795,22 +790,31 @@ pub const Dir = struct {
795790 .kind = base.kind,
796791 };
797792 } 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 }
799797 }
800798 }
801799 return null;
802800 }
803801
804802 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 }
806808 self.stack.deinit();
807809 self.name_buffer.deinit();
808810 }
809811 };
810812
811813 /// Recursively iterates over a directory.
814 /// `self` must have been opened with `OpenDirOptions{.iterate = true}`.
812815 /// Must call `Walker.deinit` when done.
813816 /// The order of returned file system entries is undefined.
817 /// `self` will not be closed after walking it.
814818 pub fn walk(self: Dir, allocator: *Allocator) !Walker {
815819 var name_buffer = std.ArrayList(u8).init(allocator);
816820 errdefer name_buffer.deinit();
......@@ -2548,12 +2552,12 @@ fn copy_file(fd_in: os.fd_t, fd_out: os.fd_t) CopyFileError!void {
25482552 if (comptime std.Target.current.isDarwin()) {
25492553 const rc = os.system.fcopyfile(fd_in, fd_out, null, os.system.COPYFILE_DATA);
25502554 switch (os.errno(rc)) {
2551 0 => return,
2552 os.EINVAL => unreachable,
2553 os.ENOMEM => return error.SystemResources,
2555 .SUCCESS => return,
2556 .INVAL => unreachable,
2557 .NOMEM => return error.SystemResources,
25542558 // The source file is not a directory, symbolic link, or regular file.
25552559 // Try with the fallback path before giving up.
2556 os.ENOTSUP => {},
2560 .OPNOTSUPP => {},
25572561 else => |err| return os.unexpectedErrno(err),
25582562 }
25592563 }
lib/std/fs/file.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const os = std.os;
lib/std/fs/get_app_data_dir.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const unicode = std.unicode;
lib/std/fs/path.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const std = @import("../std.zig");
83const debug = std.debug;
lib/std/fs/test.zig+2-14
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const testing = std.testing;
83const builtin = std.builtin;
......@@ -909,11 +904,7 @@ test "open file with exclusive nonblocking lock twice (absolute paths)" {
909904test "walker" {
910905 if (builtin.os.tag == .wasi) return error.SkipZigTest;
911906
912 var arena = ArenaAllocator.init(testing.allocator);
913 defer arena.deinit();
914 var allocator = &arena.allocator;
915
916 var tmp = tmpDir(.{});
907 var tmp = tmpDir(.{ .iterate = true });
917908 defer tmp.cleanup();
918909
919910 // iteration order of walker is undefined, so need lookup maps to check against
......@@ -942,10 +933,7 @@ test "walker" {
942933 try tmp.dir.makePath(kv.key);
943934 }
944935
945 const tmp_path = try fs.path.join(allocator, &[_][]const u8{ "zig-cache", "tmp", tmp.sub_path[0..] });
946 const tmp_dir = try fs.cwd().openDir(tmp_path, .{ .iterate = true });
947
948 var walker = try tmp_dir.walk(testing.allocator);
936 var walker = try tmp.dir.walk(testing.allocator);
949937 defer walker.deinit();
950938
951939 var num_walked: usize = 0;
lib/std/fs/wasi.zig+4-9
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const os = std.os;
83const mem = std.mem;
......@@ -121,13 +116,13 @@ pub const PreopenList = struct {
121116 while (true) {
122117 var buf: prestat_t = undefined;
123118 switch (fd_prestat_get(fd, &buf)) {
124 ESUCCESS => {},
125 ENOTSUP => {
119 .SUCCESS => {},
120 .OPNOTSUPP => {
126121 // not a preopen, so keep going
127122 fd = try math.add(fd_t, fd, 1);
128123 continue;
129124 },
130 EBADF => {
125 .BADF => {
131126 // OK, no more fds available
132127 break;
133128 },
......@@ -137,7 +132,7 @@ pub const PreopenList = struct {
137132 const path_buf = try self.buffer.allocator.alloc(u8, preopen_len);
138133 mem.set(u8, path_buf, 0);
139134 switch (fd_prestat_dir_name(fd, path_buf.ptr, preopen_len)) {
140 ESUCCESS => {},
135 .SUCCESS => {},
141136 else => |err| return os.unexpectedErrno(err),
142137 }
143138 const preopen = Preopen.new(fd, PreopenType{ .Dir = path_buf });
lib/std/fs/watch.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = std.builtin;
83const event = std.event;
lib/std/hash.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const adler = @import("hash/adler.zig");
72pub const Adler32 = adler.Adler32;
83
lib/std/hash/adler.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Adler32 checksum.
72//
83// https://tools.ietf.org/html/rfc1950#section-9
lib/std/hash/auto_hash.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const assert = std.debug.assert;
83const mem = std.mem;
lib/std/hash/benchmark.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// zig run benchmark.zig --release-fast --zig-lib-dir ..
72
83const builtin = std.builtin;
lib/std/hash/cityhash.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = std.builtin;
83
lib/std/hash/crc.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// There are two implementations of CRC32 implemented with the following key characteristics:
72//
83// - Crc32WithPoly uses 8Kb of tables but is ~10x faster than the small method.
lib/std/hash/fnv.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// FNV1a - Fowler-Noll-Vo hash function
72//
83// FNV1a is a fast, non-cryptographic hash function with fairly good distribution properties.
lib/std/hash/murmur.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = @import("builtin");
83const testing = std.testing;
lib/std/hash/wyhash.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const mem = std.mem;
83
lib/std/hash_map.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const assert = debug.assert;
83const autoHash = std.hash.autoHash;
lib/std/heap.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const root = @import("root");
83const debug = std.debug;
lib/std/heap/arena_allocator.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const assert = std.debug.assert;
83const mem = std.mem;
lib/std/heap/general_purpose_allocator.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61//! # General Purpose Allocator
72//!
83//! ## Design Priorities
lib/std/heap/log_to_writer_allocator.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const Allocator = std.mem.Allocator;
83
lib/std/heap/logging_allocator.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const Allocator = std.mem.Allocator;
83
lib/std/io.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const builtin = std.builtin;
83const root = @import("root");
lib/std/io/bit_reader.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const io = std.io;
lib/std/io/bit_writer.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const io = std.io;
lib/std/io/buffered_atomic_file.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const mem = std.mem;
83const fs = std.fs;
lib/std/io/buffered_reader.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const io = std.io;
83const assert = std.debug.assert;
lib/std/io/buffered_writer.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const io = std.io;
83
lib/std/io/c_writer.zig+13-18
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const io = std.io;
......@@ -17,19 +12,19 @@ pub fn cWriter(c_file: *std.c.FILE) CWriter {
1712fn cWriterWrite(c_file: *std.c.FILE, bytes: []const u8) std.fs.File.WriteError!usize {
1813 const amt_written = std.c.fwrite(bytes.ptr, 1, bytes.len, c_file);
1914 if (amt_written >= 0) return amt_written;
20 switch (std.c._errno().*) {
21 0 => unreachable,
22 os.EINVAL => unreachable,
23 os.EFAULT => unreachable,
24 os.EAGAIN => unreachable, // this is a blocking API
25 os.EBADF => unreachable, // always a race condition
26 os.EDESTADDRREQ => unreachable, // connect was never called
27 os.EDQUOT => return error.DiskQuota,
28 os.EFBIG => return error.FileTooBig,
29 os.EIO => return error.InputOutput,
30 os.ENOSPC => return error.NoSpaceLeft,
31 os.EPERM => return error.AccessDenied,
32 os.EPIPE => return error.BrokenPipe,
15 switch (@intToEnum(os.E, std.c._errno().*)) {
16 .SUCCESS => unreachable,
17 .INVAL => unreachable,
18 .FAULT => unreachable,
19 .AGAIN => unreachable, // this is a blocking API
20 .BADF => unreachable, // always a race condition
21 .DESTADDRREQ => unreachable, // connect was never called
22 .DQUOT => return error.DiskQuota,
23 .FBIG => return error.FileTooBig,
24 .IO => return error.InputOutput,
25 .NOSPC => return error.NoSpaceLeft,
26 .PERM => return error.AccessDenied,
27 .PIPE => return error.BrokenPipe,
3328 else => |err| return os.unexpectedErrno(err),
3429 }
3530}
lib/std/io/change_detection_stream.zig-6
......@@ -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
71const std = @import("../std.zig");
82const io = std.io;
93const mem = std.mem;
lib/std/io/counting_reader.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const io = std.io;
83const testing = std.testing;
lib/std/io/counting_writer.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const io = std.io;
83const testing = std.testing;
lib/std/io/find_byte_writer.zig-6
......@@ -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
71const std = @import("../std.zig");
82const io = std.io;
93const assert = std.debug.assert;
lib/std/io/fixed_buffer_stream.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const io = std.io;
83const testing = std.testing;
lib/std/io/limited_reader.zig-5
......@@ -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.
61const std = @import("../std.zig");
72const io = std.io;
83const assert = std.debug.assert;
lib/std/io/multi_writer.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const io = std.io;
83const testing = std.testing;
lib/std/io/peek_stream.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const io = std.io;
83const mem = std.mem;
lib/std/io/reader.zig+17-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const math = std.math;
......@@ -143,6 +138,23 @@ pub fn Reader(
143138 return array_list.toOwnedSlice();
144139 }
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
146158 /// Allocates enough memory to read until `delimiter` or end-of-stream.
147159 /// If the allocated memory would be greater than `max_size`, returns
148160 /// `error.StreamTooLong`. If end-of-stream is found, returns the rest
lib/std/io/seekable_stream.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72
83pub fn SeekableStream(
lib/std/io/stream_source.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const io = std.io;
83
lib/std/io/test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = @import("builtin");
83const io = std.io;
lib/std/io/writer.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const assert = std.debug.assert;
83const builtin = std.builtin;
lib/std/json.zig+128-9
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// JSON parser conforming to RFC8259.
72//
83// https://tools.ietf.org/html/rfc8259
......@@ -1468,7 +1463,9 @@ pub const ParseOptions = struct {
14681463 allow_trailing_data: bool = false,
14691464};
14701465
1471fn skipValue(tokens: *TokenStream) !void {
1466const SkipValueError = error{UnexpectedJsonDepth} || TokenStream.Error;
1467
1468fn skipValue(tokens: *TokenStream) SkipValueError!void {
14721469 const original_depth = tokens.stackUsed();
14731470
14741471 // Return an error if no value is found
......@@ -1530,7 +1527,84 @@ test "skipValue" {
15301527 }
15311528}
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 {
15341608 switch (@typeInfo(T)) {
15351609 .Bool => {
15361610 return switch (token) {
......@@ -1794,7 +1868,11 @@ fn parseInternal(comptime T: type, token: Token, tokens: *TokenStream, options:
17941868 unreachable;
17951869}
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 {
17981876 const token = (try tokens.next()) orelse return error.UnexpectedEndOfJson;
17991877 const r = try parseInternal(T, token, tokens, options);
18001878 errdefer parseFree(T, r, options);
......@@ -2181,6 +2259,45 @@ test "parse into struct ignoring unknown fields" {
21812259 try testing.expectEqualSlices(u8, "zig", r.language);
21822260}
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
21842301/// A non-stream JSON parser which constructs a tree of Value's.
21852302pub const Parser = struct {
21862303 allocator: *Allocator,
......@@ -2418,10 +2535,12 @@ pub const Parser = struct {
24182535 }
24192536};
24202537
2538pub const UnescapeValidStringError = error{InvalidUnicodeHexSymbol};
2539
24212540/// Unescape a JSON string
24222541/// Only to be used on strings already validated by the parser
24232542/// (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 {
24252544 var inIndex: usize = 0;
24262545 var outIndex: usize = 0;
24272546
lib/std/json/test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// RFC 8529 conformance tests.
72//
83// Tests are taken from https://github.com/nst/JSONTestSuite
lib/std/json/write_stream.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const assert = std.debug.assert;
83const maxInt = std.math.maxInt;
lib/std/leb128.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const testing = std.testing;
83
lib/std/linked_list.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const debug = std.debug;
83const assert = debug.assert;
lib/std/log.zig+40-25
......@@ -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
71//! std.log is a standardized interface for logging which allows for the logging
82//! of programs and libraries using this interface to be formatted and filtered
93//! by the implementer of the root.log function.
......@@ -100,6 +94,23 @@ pub const Level = enum {
10094 info,
10195 /// Debug: messages only useful for debugging.
10296 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 }
103114};
104115
105116/// The default log level is based on build mode.
......@@ -145,30 +156,34 @@ fn log(
145156 if (@typeInfo(@TypeOf(root.log)) != .Fn)
146157 @compileError("Expected root.log to be a function");
147158 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;
152159 } else {
153 const level_txt = switch (message_level) {
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;
160 defaultLog(message_level, scope, format, args);
168161 }
169162 }
170163}
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
172187/// Returns a scoped logging namespace that logs all messages using the scope
173188/// provided here.
174189pub fn scoped(comptime scope: @Type(.EnumLiteral)) type {
lib/std/macho.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const mach_header = extern struct {
72 magic: u32,
83 cputype: cpu_type_t,
lib/std/math.zig+4-9
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const assert = std.debug.assert;
83const mem = std.mem;
......@@ -111,11 +106,11 @@ pub const inf = @import("math/inf.zig").inf;
111106/// the specified tolerance.
112107///
113108/// 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 small
109/// the two numbers are close enough; a good value for this parameter is a small
115110/// multiple of `epsilon(T)`.
116111///
117/// Note that this function is recommended for for comparing small numbers
118/// around zero, using `approxEqRel` is suggested otherwise.
112/// Note that this function is recommended for comparing small numbers
113/// around zero; using `approxEqRel` is suggested otherwise.
119114///
120115/// NaN values are never considered equal to any value.
121116pub 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 {
138133/// than zero.
139134///
140135/// 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 usually
136/// the two numbers are close enough; a good value for this parameter is usually
142137/// `sqrt(epsilon(T))`, meaning that the two numbers are considered equal if at
143138/// least half of the digits are equal.
144139///
lib/std/math/acos.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/acosh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/asin.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/asinh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/atan.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/atan2.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/atanh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/big.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const assert = std.debug.assert;
83
lib/std/math/big/int.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const math = std.math;
83const Limb = std.math.big.Limb;
lib/std/math/big/int_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const mem = std.mem;
83const testing = std.testing;
lib/std/math/big/rational.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const debug = std.debug;
83const math = std.math;
lib/std/math/cbrt.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/ceil.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/complex.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/abs.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/acos.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/acosh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/arg.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/asin.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/asinh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/atan.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/complex/atanh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/conj.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/cos.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/cosh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/complex/exp.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/complex/ldexp.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/complex/log.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/pow.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/proj.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/sin.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/sinh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/complex/sqrt.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/complex/tan.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const testing = std.testing;
83const math = std.math;
lib/std/math/complex/tanh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/copysign.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/cos.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from go, which is licensed under a BSD-3 license.
72// https://golang.org/LICENSE
83//
lib/std/math/cosh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/epsilon.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const math = @import("../math.zig");
72
83/// Returns the machine epsilon for type T.
lib/std/math/exp.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/exp2.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/expm1.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/expo2.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/fabs.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/floor.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/fma.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/frexp.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/hypot.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/ilogb.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/inf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const math = std.math;
83
lib/std/math/isfinite.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const math = std.math;
83const expect = std.testing.expect;
lib/std/math/isinf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const math = std.math;
83const expect = std.testing.expect;
lib/std/math/isnan.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const math = std.math;
83const expect = std.testing.expect;
lib/std/math/isnormal.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const math = std.math;
83const expect = std.testing.expect;
lib/std/math/ln.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/log.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/log10.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/log1p.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/log2.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/modf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/nan.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const math = @import("../math.zig");
72
83/// Returns the nan representation for type T.
lib/std/math/pow.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from go, which is licensed under a BSD-3 license.
72// https://golang.org/LICENSE
83//
lib/std/math/powi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Based on Rust, which is licensed under the MIT license.
72// https://github.com/rust-lang/rust/blob/360432f1e8794de58cd94f34c9c17ad65871e5b5/LICENSE-MIT
83//
lib/std/math/round.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/scalbn.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/signbit.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const math = std.math;
83const expect = std.testing.expect;
lib/std/math/sin.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from go, which is licensed under a BSD-3 license.
72// https://golang.org/LICENSE
83//
lib/std/math/sinh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/sqrt.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const math = std.math;
83const expect = std.testing.expect;
lib/std/math/tan.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from go, which is licensed under a BSD-3 license.
72// https://golang.org/LICENSE
83//
lib/std/math/tanh.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/math/trunc.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from musl, which is licensed under the MIT license:
72// https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT
83//
lib/std/mem.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const debug = std.debug;
83const assert = debug.assert;
lib/std/mem/Allocator.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61//! The standard memory allocation interface.
72
83const std = @import("../std.zig");
lib/std/meta.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const builtin = std.builtin;
83const debug = std.debug;
lib/std/meta/trailer_flags.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const meta = std.meta;
83const testing = std.testing;
lib/std/meta/trait.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const mem = std.mem;
lib/std/multi_array_list.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const assert = std.debug.assert;
83const meta = std.meta;
lib/std/net.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const builtin = @import("builtin");
83const assert = std.debug.assert;
lib/std/net/test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const builtin = std.builtin;
83const net = std.net;
lib/std/once.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const builtin = std.builtin;
83const testing = std.testing;
lib/std/os.zig+1308-1313
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// This file contains thin wrappers around OS-specific APIs, with these
72// specific goals in mind:
83// * Convert "errno"-style error codes into Zig errors.
......@@ -116,13 +111,13 @@ pub fn close(fd: fd_t) void {
116111 if (comptime std.Target.current.isDarwin()) {
117112 // This avoids the EINTR problem.
118113 switch (darwin.getErrno(darwin.@"close$NOCANCEL"(fd))) {
119 EBADF => unreachable, // Always a race condition.
114 .BADF => unreachable, // Always a race condition.
120115 else => return,
121116 }
122117 }
123118 switch (errno(system.close(fd))) {
124 EBADF => unreachable, // Always a race condition.
125 EINTR => return, // This is still a success. See https://github.com/ziglang/zig/issues/2425
119 .BADF => unreachable, // Always a race condition.
120 .INTR => return, // This is still a success. See https://github.com/ziglang/zig/issues/2425
126121 else => return,
127122 }
128123}
......@@ -159,11 +154,11 @@ pub fn getrandom(buffer: []u8) GetRandomError!void {
159154 };
160155
161156 switch (res.err) {
162 0 => buf = buf[res.num_read..],
163 EINVAL => unreachable,
164 EFAULT => unreachable,
165 EINTR => continue,
166 ENOSYS => return getRandomBytesDevURandom(buf),
157 .SUCCESS => buf = buf[res.num_read..],
158 .INVAL => unreachable,
159 .FAULT => unreachable,
160 .INTR => continue,
161 .NOSYS => return getRandomBytesDevURandom(buf),
167162 else => return unexpectedErrno(res.err),
168163 }
169164 }
......@@ -175,7 +170,7 @@ pub fn getrandom(buffer: []u8) GetRandomError!void {
175170 return;
176171 },
177172 .wasi => switch (wasi.random_get(buffer.ptr, buffer.len)) {
178 0 => return,
173 .SUCCESS => return,
179174 else => |err| return unexpectedErrno(err),
180175 },
181176 else => return getRandomBytesDevURandom(buffer),
......@@ -238,7 +233,7 @@ pub const RaiseError = UnexpectedError;
238233pub fn raise(sig: u8) RaiseError!void {
239234 if (builtin.link_libc) {
240235 switch (errno(system.raise(sig))) {
241 0 => return,
236 .SUCCESS => return,
242237 else => |err| return unexpectedErrno(err),
243238 }
244239 }
......@@ -255,7 +250,7 @@ pub fn raise(sig: u8) RaiseError!void {
255250 _ = linux.sigprocmask(SIG_SETMASK, &set, null);
256251
257252 switch (errno(rc)) {
258 0 => return,
253 .SUCCESS => return,
259254 else => |err| return unexpectedErrno(err),
260255 }
261256 }
......@@ -267,10 +262,10 @@ pub const KillError = error{PermissionDenied} || UnexpectedError;
267262
268263pub fn kill(pid: pid_t, sig: u8) KillError!void {
269264 switch (errno(system.kill(pid, sig))) {
270 0 => return,
271 EINVAL => unreachable, // invalid signal
272 EPERM => return error.PermissionDenied,
273 ESRCH => unreachable, // always a race condition
265 .SUCCESS => return,
266 .INVAL => unreachable, // invalid signal
267 .PERM => return error.PermissionDenied,
268 .SRCH => unreachable, // always a race condition
274269 else => |err| return unexpectedErrno(err),
275270 }
276271}
......@@ -342,19 +337,19 @@ pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
342337
343338 var nread: usize = undefined;
344339 switch (wasi.fd_read(fd, &iovs, iovs.len, &nread)) {
345 wasi.ESUCCESS => return nread,
346 wasi.EINTR => unreachable,
347 wasi.EINVAL => unreachable,
348 wasi.EFAULT => unreachable,
349 wasi.EAGAIN => unreachable,
350 wasi.EBADF => return error.NotOpenForReading, // Can be a race condition.
351 wasi.EIO => return error.InputOutput,
352 wasi.EISDIR => return error.IsDir,
353 wasi.ENOBUFS => return error.SystemResources,
354 wasi.ENOMEM => return error.SystemResources,
355 wasi.ECONNRESET => return error.ConnectionResetByPeer,
356 wasi.ETIMEDOUT => return error.ConnectionTimedOut,
357 wasi.ENOTCAPABLE => return error.AccessDenied,
340 .SUCCESS => return nread,
341 .INTR => unreachable,
342 .INVAL => unreachable,
343 .FAULT => unreachable,
344 .AGAIN => unreachable,
345 .BADF => return error.NotOpenForReading, // Can be a race condition.
346 .IO => return error.InputOutput,
347 .ISDIR => return error.IsDir,
348 .NOBUFS => return error.SystemResources,
349 .NOMEM => return error.SystemResources,
350 .CONNRESET => return error.ConnectionResetByPeer,
351 .TIMEDOUT => return error.ConnectionTimedOut,
352 .NOTCAPABLE => return error.AccessDenied,
358353 else => |err| return unexpectedErrno(err),
359354 }
360355 }
......@@ -370,18 +365,18 @@ pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
370365 while (true) {
371366 const rc = system.read(fd, buf.ptr, adjusted_len);
372367 switch (errno(rc)) {
373 0 => return @intCast(usize, rc),
374 EINTR => continue,
375 EINVAL => unreachable,
376 EFAULT => unreachable,
377 EAGAIN => return error.WouldBlock,
378 EBADF => return error.NotOpenForReading, // Can be a race condition.
379 EIO => return error.InputOutput,
380 EISDIR => return error.IsDir,
381 ENOBUFS => return error.SystemResources,
382 ENOMEM => return error.SystemResources,
383 ECONNRESET => return error.ConnectionResetByPeer,
384 ETIMEDOUT => return error.ConnectionTimedOut,
368 .SUCCESS => return @intCast(usize, rc),
369 .INTR => continue,
370 .INVAL => unreachable,
371 .FAULT => unreachable,
372 .AGAIN => return error.WouldBlock,
373 .BADF => return error.NotOpenForReading, // Can be a race condition.
374 .IO => return error.InputOutput,
375 .ISDIR => return error.IsDir,
376 .NOBUFS => return error.SystemResources,
377 .NOMEM => return error.SystemResources,
378 .CONNRESET => return error.ConnectionResetByPeer,
379 .TIMEDOUT => return error.ConnectionTimedOut,
385380 else => |err| return unexpectedErrno(err),
386381 }
387382 }
......@@ -407,17 +402,17 @@ pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {
407402 if (builtin.os.tag == .wasi and !builtin.link_libc) {
408403 var nread: usize = undefined;
409404 switch (wasi.fd_read(fd, iov.ptr, iov.len, &nread)) {
410 wasi.ESUCCESS => return nread,
411 wasi.EINTR => unreachable,
412 wasi.EINVAL => unreachable,
413 wasi.EFAULT => unreachable,
414 wasi.EAGAIN => unreachable, // currently not support in WASI
415 wasi.EBADF => return error.NotOpenForReading, // can be a race condition
416 wasi.EIO => return error.InputOutput,
417 wasi.EISDIR => return error.IsDir,
418 wasi.ENOBUFS => return error.SystemResources,
419 wasi.ENOMEM => return error.SystemResources,
420 wasi.ENOTCAPABLE => return error.AccessDenied,
405 .SUCCESS => return nread,
406 .INTR => unreachable,
407 .INVAL => unreachable,
408 .FAULT => unreachable,
409 .AGAIN => unreachable, // currently not support in WASI
410 .BADF => return error.NotOpenForReading, // can be a race condition
411 .IO => return error.InputOutput,
412 .ISDIR => return error.IsDir,
413 .NOBUFS => return error.SystemResources,
414 .NOMEM => return error.SystemResources,
415 .NOTCAPABLE => return error.AccessDenied,
421416 else => |err| return unexpectedErrno(err),
422417 }
423418 }
......@@ -426,16 +421,16 @@ pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {
426421 // TODO handle the case when iov_len is too large and get rid of this @intCast
427422 const rc = system.readv(fd, iov.ptr, iov_count);
428423 switch (errno(rc)) {
429 0 => return @intCast(usize, rc),
430 EINTR => continue,
431 EINVAL => unreachable,
432 EFAULT => unreachable,
433 EAGAIN => return error.WouldBlock,
434 EBADF => return error.NotOpenForReading, // can be a race condition
435 EIO => return error.InputOutput,
436 EISDIR => return error.IsDir,
437 ENOBUFS => return error.SystemResources,
438 ENOMEM => return error.SystemResources,
424 .SUCCESS => return @intCast(usize, rc),
425 .INTR => continue,
426 .INVAL => unreachable,
427 .FAULT => unreachable,
428 .AGAIN => return error.WouldBlock,
429 .BADF => return error.NotOpenForReading, // can be a race condition
430 .IO => return error.InputOutput,
431 .ISDIR => return error.IsDir,
432 .NOBUFS => return error.SystemResources,
433 .NOMEM => return error.SystemResources,
439434 else => |err| return unexpectedErrno(err),
440435 }
441436 }
......@@ -469,21 +464,21 @@ pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {
469464
470465 var nread: usize = undefined;
471466 switch (wasi.fd_pread(fd, &iovs, iovs.len, offset, &nread)) {
472 wasi.ESUCCESS => return nread,
473 wasi.EINTR => unreachable,
474 wasi.EINVAL => unreachable,
475 wasi.EFAULT => unreachable,
476 wasi.EAGAIN => unreachable,
477 wasi.EBADF => return error.NotOpenForReading, // Can be a race condition.
478 wasi.EIO => return error.InputOutput,
479 wasi.EISDIR => return error.IsDir,
480 wasi.ENOBUFS => return error.SystemResources,
481 wasi.ENOMEM => return error.SystemResources,
482 wasi.ECONNRESET => return error.ConnectionResetByPeer,
483 wasi.ENXIO => return error.Unseekable,
484 wasi.ESPIPE => return error.Unseekable,
485 wasi.EOVERFLOW => return error.Unseekable,
486 wasi.ENOTCAPABLE => return error.AccessDenied,
467 .SUCCESS => return nread,
468 .INTR => unreachable,
469 .INVAL => unreachable,
470 .FAULT => unreachable,
471 .AGAIN => unreachable,
472 .BADF => return error.NotOpenForReading, // Can be a race condition.
473 .IO => return error.InputOutput,
474 .ISDIR => return error.IsDir,
475 .NOBUFS => return error.SystemResources,
476 .NOMEM => return error.SystemResources,
477 .CONNRESET => return error.ConnectionResetByPeer,
478 .NXIO => return error.Unseekable,
479 .SPIPE => return error.Unseekable,
480 .OVERFLOW => return error.Unseekable,
481 .NOTCAPABLE => return error.AccessDenied,
487482 else => |err| return unexpectedErrno(err),
488483 }
489484 }
......@@ -505,20 +500,20 @@ pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {
505500 while (true) {
506501 const rc = pread_sym(fd, buf.ptr, adjusted_len, ioffset);
507502 switch (errno(rc)) {
508 0 => return @intCast(usize, rc),
509 EINTR => continue,
510 EINVAL => unreachable,
511 EFAULT => unreachable,
512 EAGAIN => return error.WouldBlock,
513 EBADF => return error.NotOpenForReading, // Can be a race condition.
514 EIO => return error.InputOutput,
515 EISDIR => return error.IsDir,
516 ENOBUFS => return error.SystemResources,
517 ENOMEM => return error.SystemResources,
518 ECONNRESET => return error.ConnectionResetByPeer,
519 ENXIO => return error.Unseekable,
520 ESPIPE => return error.Unseekable,
521 EOVERFLOW => return error.Unseekable,
503 .SUCCESS => return @intCast(usize, rc),
504 .INTR => continue,
505 .INVAL => unreachable,
506 .FAULT => unreachable,
507 .AGAIN => return error.WouldBlock,
508 .BADF => return error.NotOpenForReading, // Can be a race condition.
509 .IO => return error.InputOutput,
510 .ISDIR => return error.IsDir,
511 .NOBUFS => return error.SystemResources,
512 .NOMEM => return error.SystemResources,
513 .CONNRESET => return error.ConnectionResetByPeer,
514 .NXIO => return error.Unseekable,
515 .SPIPE => return error.Unseekable,
516 .OVERFLOW => return error.Unseekable,
522517 else => |err| return unexpectedErrno(err),
523518 }
524519 }
......@@ -558,15 +553,15 @@ pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {
558553 }
559554 if (std.Target.current.os.tag == .wasi and !builtin.link_libc) {
560555 switch (wasi.fd_filestat_set_size(fd, length)) {
561 wasi.ESUCCESS => return,
562 wasi.EINTR => unreachable,
563 wasi.EFBIG => return error.FileTooBig,
564 wasi.EIO => return error.InputOutput,
565 wasi.EPERM => return error.AccessDenied,
566 wasi.ETXTBSY => return error.FileBusy,
567 wasi.EBADF => unreachable, // Handle not open for writing
568 wasi.EINVAL => unreachable, // Handle not open for writing
569 wasi.ENOTCAPABLE => return error.AccessDenied,
556 .SUCCESS => return,
557 .INTR => unreachable,
558 .FBIG => return error.FileTooBig,
559 .IO => return error.InputOutput,
560 .PERM => return error.AccessDenied,
561 .TXTBSY => return error.FileBusy,
562 .BADF => unreachable, // Handle not open for writing
563 .INVAL => unreachable, // Handle not open for writing
564 .NOTCAPABLE => return error.AccessDenied,
570565 else => |err| return unexpectedErrno(err),
571566 }
572567 }
......@@ -579,14 +574,14 @@ pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {
579574
580575 const ilen = @bitCast(i64, length); // the OS treats this as unsigned
581576 switch (errno(ftruncate_sym(fd, ilen))) {
582 0 => return,
583 EINTR => continue,
584 EFBIG => return error.FileTooBig,
585 EIO => return error.InputOutput,
586 EPERM => return error.AccessDenied,
587 ETXTBSY => return error.FileBusy,
588 EBADF => unreachable, // Handle not open for writing
589 EINVAL => unreachable, // Handle not open for writing
577 .SUCCESS => return,
578 .INTR => continue,
579 .FBIG => return error.FileTooBig,
580 .IO => return error.InputOutput,
581 .PERM => return error.AccessDenied,
582 .TXTBSY => return error.FileBusy,
583 .BADF => unreachable, // Handle not open for writing
584 .INVAL => unreachable, // Handle not open for writing
590585 else => |err| return unexpectedErrno(err),
591586 }
592587 }
......@@ -620,20 +615,20 @@ pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) PReadError!usize {
620615 if (builtin.os.tag == .wasi and !builtin.link_libc) {
621616 var nread: usize = undefined;
622617 switch (wasi.fd_pread(fd, iov.ptr, iov.len, offset, &nread)) {
623 wasi.ESUCCESS => return nread,
624 wasi.EINTR => unreachable,
625 wasi.EINVAL => unreachable,
626 wasi.EFAULT => unreachable,
627 wasi.EAGAIN => unreachable,
628 wasi.EBADF => return error.NotOpenForReading, // can be a race condition
629 wasi.EIO => return error.InputOutput,
630 wasi.EISDIR => return error.IsDir,
631 wasi.ENOBUFS => return error.SystemResources,
632 wasi.ENOMEM => return error.SystemResources,
633 wasi.ENXIO => return error.Unseekable,
634 wasi.ESPIPE => return error.Unseekable,
635 wasi.EOVERFLOW => return error.Unseekable,
636 wasi.ENOTCAPABLE => return error.AccessDenied,
618 .SUCCESS => return nread,
619 .INTR => unreachable,
620 .INVAL => unreachable,
621 .FAULT => unreachable,
622 .AGAIN => unreachable,
623 .BADF => return error.NotOpenForReading, // can be a race condition
624 .IO => return error.InputOutput,
625 .ISDIR => return error.IsDir,
626 .NOBUFS => return error.SystemResources,
627 .NOMEM => return error.SystemResources,
628 .NXIO => return error.Unseekable,
629 .SPIPE => return error.Unseekable,
630 .OVERFLOW => return error.Unseekable,
631 .NOTCAPABLE => return error.AccessDenied,
637632 else => |err| return unexpectedErrno(err),
638633 }
639634 }
......@@ -649,19 +644,19 @@ pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) PReadError!usize {
649644 while (true) {
650645 const rc = preadv_sym(fd, iov.ptr, iov_count, ioffset);
651646 switch (errno(rc)) {
652 0 => return @bitCast(usize, rc),
653 EINTR => continue,
654 EINVAL => unreachable,
655 EFAULT => unreachable,
656 EAGAIN => return error.WouldBlock,
657 EBADF => return error.NotOpenForReading, // can be a race condition
658 EIO => return error.InputOutput,
659 EISDIR => return error.IsDir,
660 ENOBUFS => return error.SystemResources,
661 ENOMEM => return error.SystemResources,
662 ENXIO => return error.Unseekable,
663 ESPIPE => return error.Unseekable,
664 EOVERFLOW => return error.Unseekable,
647 .SUCCESS => return @bitCast(usize, rc),
648 .INTR => continue,
649 .INVAL => unreachable,
650 .FAULT => unreachable,
651 .AGAIN => return error.WouldBlock,
652 .BADF => return error.NotOpenForReading, // can be a race condition
653 .IO => return error.InputOutput,
654 .ISDIR => return error.IsDir,
655 .NOBUFS => return error.SystemResources,
656 .NOMEM => return error.SystemResources,
657 .NXIO => return error.Unseekable,
658 .SPIPE => return error.Unseekable,
659 .OVERFLOW => return error.Unseekable,
665660 else => |err| return unexpectedErrno(err),
666661 }
667662 }
......@@ -723,20 +718,20 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {
723718 }};
724719 var nwritten: usize = undefined;
725720 switch (wasi.fd_write(fd, &ciovs, ciovs.len, &nwritten)) {
726 wasi.ESUCCESS => return nwritten,
727 wasi.EINTR => unreachable,
728 wasi.EINVAL => unreachable,
729 wasi.EFAULT => unreachable,
730 wasi.EAGAIN => unreachable,
731 wasi.EBADF => return error.NotOpenForWriting, // can be a race condition.
732 wasi.EDESTADDRREQ => unreachable, // `connect` was never called.
733 wasi.EDQUOT => return error.DiskQuota,
734 wasi.EFBIG => return error.FileTooBig,
735 wasi.EIO => return error.InputOutput,
736 wasi.ENOSPC => return error.NoSpaceLeft,
737 wasi.EPERM => return error.AccessDenied,
738 wasi.EPIPE => return error.BrokenPipe,
739 wasi.ENOTCAPABLE => return error.AccessDenied,
721 .SUCCESS => return nwritten,
722 .INTR => unreachable,
723 .INVAL => unreachable,
724 .FAULT => unreachable,
725 .AGAIN => unreachable,
726 .BADF => return error.NotOpenForWriting, // can be a race condition.
727 .DESTADDRREQ => unreachable, // `connect` was never called.
728 .DQUOT => return error.DiskQuota,
729 .FBIG => return error.FileTooBig,
730 .IO => return error.InputOutput,
731 .NOSPC => return error.NoSpaceLeft,
732 .PERM => return error.AccessDenied,
733 .PIPE => return error.BrokenPipe,
734 .NOTCAPABLE => return error.AccessDenied,
740735 else => |err| return unexpectedErrno(err),
741736 }
742737 }
......@@ -751,20 +746,20 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {
751746 while (true) {
752747 const rc = system.write(fd, bytes.ptr, adjusted_len);
753748 switch (errno(rc)) {
754 0 => return @intCast(usize, rc),
755 EINTR => continue,
756 EINVAL => unreachable,
757 EFAULT => unreachable,
758 EAGAIN => return error.WouldBlock,
759 EBADF => return error.NotOpenForWriting, // can be a race condition.
760 EDESTADDRREQ => unreachable, // `connect` was never called.
761 EDQUOT => return error.DiskQuota,
762 EFBIG => return error.FileTooBig,
763 EIO => return error.InputOutput,
764 ENOSPC => return error.NoSpaceLeft,
765 EPERM => return error.AccessDenied,
766 EPIPE => return error.BrokenPipe,
767 ECONNRESET => return error.ConnectionResetByPeer,
749 .SUCCESS => return @intCast(usize, rc),
750 .INTR => continue,
751 .INVAL => unreachable,
752 .FAULT => unreachable,
753 .AGAIN => return error.WouldBlock,
754 .BADF => return error.NotOpenForWriting, // can be a race condition.
755 .DESTADDRREQ => unreachable, // `connect` was never called.
756 .DQUOT => return error.DiskQuota,
757 .FBIG => return error.FileTooBig,
758 .IO => return error.InputOutput,
759 .NOSPC => return error.NoSpaceLeft,
760 .PERM => return error.AccessDenied,
761 .PIPE => return error.BrokenPipe,
762 .CONNRESET => return error.ConnectionResetByPeer,
768763 else => |err| return unexpectedErrno(err),
769764 }
770765 }
......@@ -787,7 +782,7 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {
787782/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
788783/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
789784///
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.
791786pub fn writev(fd: fd_t, iov: []const iovec_const) WriteError!usize {
792787 if (std.Target.current.os.tag == .windows) {
793788 // TODO improve this to use WriteFileScatter
......@@ -798,42 +793,42 @@ pub fn writev(fd: fd_t, iov: []const iovec_const) WriteError!usize {
798793 if (builtin.os.tag == .wasi and !builtin.link_libc) {
799794 var nwritten: usize = undefined;
800795 switch (wasi.fd_write(fd, iov.ptr, iov.len, &nwritten)) {
801 wasi.ESUCCESS => return nwritten,
802 wasi.EINTR => unreachable,
803 wasi.EINVAL => unreachable,
804 wasi.EFAULT => unreachable,
805 wasi.EAGAIN => unreachable,
806 wasi.EBADF => return error.NotOpenForWriting, // can be a race condition.
807 wasi.EDESTADDRREQ => unreachable, // `connect` was never called.
808 wasi.EDQUOT => return error.DiskQuota,
809 wasi.EFBIG => return error.FileTooBig,
810 wasi.EIO => return error.InputOutput,
811 wasi.ENOSPC => return error.NoSpaceLeft,
812 wasi.EPERM => return error.AccessDenied,
813 wasi.EPIPE => return error.BrokenPipe,
814 wasi.ENOTCAPABLE => return error.AccessDenied,
796 .SUCCESS => return nwritten,
797 .INTR => unreachable,
798 .INVAL => unreachable,
799 .FAULT => unreachable,
800 .AGAIN => unreachable,
801 .BADF => return error.NotOpenForWriting, // can be a race condition.
802 .DESTADDRREQ => unreachable, // `connect` was never called.
803 .DQUOT => return error.DiskQuota,
804 .FBIG => return error.FileTooBig,
805 .IO => return error.InputOutput,
806 .NOSPC => return error.NoSpaceLeft,
807 .PERM => return error.AccessDenied,
808 .PIPE => return error.BrokenPipe,
809 .NOTCAPABLE => return error.AccessDenied,
815810 else => |err| return unexpectedErrno(err),
816811 }
817812 }
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);
820815 while (true) {
821816 const rc = system.writev(fd, iov.ptr, iov_count);
822817 switch (errno(rc)) {
823 0 => return @intCast(usize, rc),
824 EINTR => continue,
825 EINVAL => unreachable,
826 EFAULT => unreachable,
827 EAGAIN => return error.WouldBlock,
828 EBADF => return error.NotOpenForWriting, // Can be a race condition.
829 EDESTADDRREQ => unreachable, // `connect` was never called.
830 EDQUOT => return error.DiskQuota,
831 EFBIG => return error.FileTooBig,
832 EIO => return error.InputOutput,
833 ENOSPC => return error.NoSpaceLeft,
834 EPERM => return error.AccessDenied,
835 EPIPE => return error.BrokenPipe,
836 ECONNRESET => return error.ConnectionResetByPeer,
818 .SUCCESS => return @intCast(usize, rc),
819 .INTR => continue,
820 .INVAL => unreachable,
821 .FAULT => unreachable,
822 .AGAIN => return error.WouldBlock,
823 .BADF => return error.NotOpenForWriting, // Can be a race condition.
824 .DESTADDRREQ => unreachable, // `connect` was never called.
825 .DQUOT => return error.DiskQuota,
826 .FBIG => return error.FileTooBig,
827 .IO => return error.InputOutput,
828 .NOSPC => return error.NoSpaceLeft,
829 .PERM => return error.AccessDenied,
830 .PIPE => return error.BrokenPipe,
831 .CONNRESET => return error.ConnectionResetByPeer,
837832 else => |err| return unexpectedErrno(err),
838833 }
839834 }
......@@ -875,23 +870,23 @@ pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {
875870
876871 var nwritten: usize = undefined;
877872 switch (wasi.fd_pwrite(fd, &ciovs, ciovs.len, offset, &nwritten)) {
878 wasi.ESUCCESS => return nwritten,
879 wasi.EINTR => unreachable,
880 wasi.EINVAL => unreachable,
881 wasi.EFAULT => unreachable,
882 wasi.EAGAIN => unreachable,
883 wasi.EBADF => return error.NotOpenForWriting, // can be a race condition.
884 wasi.EDESTADDRREQ => unreachable, // `connect` was never called.
885 wasi.EDQUOT => return error.DiskQuota,
886 wasi.EFBIG => return error.FileTooBig,
887 wasi.EIO => return error.InputOutput,
888 wasi.ENOSPC => return error.NoSpaceLeft,
889 wasi.EPERM => return error.AccessDenied,
890 wasi.EPIPE => return error.BrokenPipe,
891 wasi.ENXIO => return error.Unseekable,
892 wasi.ESPIPE => return error.Unseekable,
893 wasi.EOVERFLOW => return error.Unseekable,
894 wasi.ENOTCAPABLE => return error.AccessDenied,
873 .SUCCESS => return nwritten,
874 .INTR => unreachable,
875 .INVAL => unreachable,
876 .FAULT => unreachable,
877 .AGAIN => unreachable,
878 .BADF => return error.NotOpenForWriting, // can be a race condition.
879 .DESTADDRREQ => unreachable, // `connect` was never called.
880 .DQUOT => return error.DiskQuota,
881 .FBIG => return error.FileTooBig,
882 .IO => return error.InputOutput,
883 .NOSPC => return error.NoSpaceLeft,
884 .PERM => return error.AccessDenied,
885 .PIPE => return error.BrokenPipe,
886 .NXIO => return error.Unseekable,
887 .SPIPE => return error.Unseekable,
888 .OVERFLOW => return error.Unseekable,
889 .NOTCAPABLE => return error.AccessDenied,
895890 else => |err| return unexpectedErrno(err),
896891 }
897892 }
......@@ -913,22 +908,22 @@ pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {
913908 while (true) {
914909 const rc = pwrite_sym(fd, bytes.ptr, adjusted_len, ioffset);
915910 switch (errno(rc)) {
916 0 => return @intCast(usize, rc),
917 EINTR => continue,
918 EINVAL => unreachable,
919 EFAULT => unreachable,
920 EAGAIN => return error.WouldBlock,
921 EBADF => return error.NotOpenForWriting, // Can be a race condition.
922 EDESTADDRREQ => unreachable, // `connect` was never called.
923 EDQUOT => return error.DiskQuota,
924 EFBIG => return error.FileTooBig,
925 EIO => return error.InputOutput,
926 ENOSPC => return error.NoSpaceLeft,
927 EPERM => return error.AccessDenied,
928 EPIPE => return error.BrokenPipe,
929 ENXIO => return error.Unseekable,
930 ESPIPE => return error.Unseekable,
931 EOVERFLOW => return error.Unseekable,
911 .SUCCESS => return @intCast(usize, rc),
912 .INTR => continue,
913 .INVAL => unreachable,
914 .FAULT => unreachable,
915 .AGAIN => return error.WouldBlock,
916 .BADF => return error.NotOpenForWriting, // Can be a race condition.
917 .DESTADDRREQ => unreachable, // `connect` was never called.
918 .DQUOT => return error.DiskQuota,
919 .FBIG => return error.FileTooBig,
920 .IO => return error.InputOutput,
921 .NOSPC => return error.NoSpaceLeft,
922 .PERM => return error.AccessDenied,
923 .PIPE => return error.BrokenPipe,
924 .NXIO => return error.Unseekable,
925 .SPIPE => return error.Unseekable,
926 .OVERFLOW => return error.Unseekable,
932927 else => |err| return unexpectedErrno(err),
933928 }
934929 }
......@@ -954,7 +949,7 @@ pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {
954949/// * Darwin
955950/// * Windows
956951///
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.
958953pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usize {
959954 const have_pwrite_but_not_pwritev = switch (std.Target.current.os.tag) {
960955 .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
971966 if (builtin.os.tag == .wasi and !builtin.link_libc) {
972967 var nwritten: usize = undefined;
973968 switch (wasi.fd_pwrite(fd, iov.ptr, iov.len, offset, &nwritten)) {
974 wasi.ESUCCESS => return nwritten,
975 wasi.EINTR => unreachable,
976 wasi.EINVAL => unreachable,
977 wasi.EFAULT => unreachable,
978 wasi.EAGAIN => unreachable,
979 wasi.EBADF => return error.NotOpenForWriting, // Can be a race condition.
980 wasi.EDESTADDRREQ => unreachable, // `connect` was never called.
981 wasi.EDQUOT => return error.DiskQuota,
982 wasi.EFBIG => return error.FileTooBig,
983 wasi.EIO => return error.InputOutput,
984 wasi.ENOSPC => return error.NoSpaceLeft,
985 wasi.EPERM => return error.AccessDenied,
986 wasi.EPIPE => return error.BrokenPipe,
987 wasi.ENXIO => return error.Unseekable,
988 wasi.ESPIPE => return error.Unseekable,
989 wasi.EOVERFLOW => return error.Unseekable,
990 wasi.ENOTCAPABLE => return error.AccessDenied,
969 .SUCCESS => return nwritten,
970 .INTR => unreachable,
971 .INVAL => unreachable,
972 .FAULT => unreachable,
973 .AGAIN => unreachable,
974 .BADF => return error.NotOpenForWriting, // Can be a race condition.
975 .DESTADDRREQ => unreachable, // `connect` was never called.
976 .DQUOT => return error.DiskQuota,
977 .FBIG => return error.FileTooBig,
978 .IO => return error.InputOutput,
979 .NOSPC => return error.NoSpaceLeft,
980 .PERM => return error.AccessDenied,
981 .PIPE => return error.BrokenPipe,
982 .NXIO => return error.Unseekable,
983 .SPIPE => return error.Unseekable,
984 .OVERFLOW => return error.Unseekable,
985 .NOTCAPABLE => return error.AccessDenied,
991986 else => |err| return unexpectedErrno(err),
992987 }
993988 }
......@@ -997,27 +992,27 @@ pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usiz
997992 else
998993 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);
1001996 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned
1002997 while (true) {
1003998 const rc = pwritev_sym(fd, iov.ptr, iov_count, ioffset);
1004999 switch (errno(rc)) {
1005 0 => return @intCast(usize, rc),
1006 EINTR => continue,
1007 EINVAL => unreachable,
1008 EFAULT => unreachable,
1009 EAGAIN => return error.WouldBlock,
1010 EBADF => return error.NotOpenForWriting, // Can be a race condition.
1011 EDESTADDRREQ => unreachable, // `connect` was never called.
1012 EDQUOT => return error.DiskQuota,
1013 EFBIG => return error.FileTooBig,
1014 EIO => return error.InputOutput,
1015 ENOSPC => return error.NoSpaceLeft,
1016 EPERM => return error.AccessDenied,
1017 EPIPE => return error.BrokenPipe,
1018 ENXIO => return error.Unseekable,
1019 ESPIPE => return error.Unseekable,
1020 EOVERFLOW => return error.Unseekable,
1000 .SUCCESS => return @intCast(usize, rc),
1001 .INTR => continue,
1002 .INVAL => unreachable,
1003 .FAULT => unreachable,
1004 .AGAIN => return error.WouldBlock,
1005 .BADF => return error.NotOpenForWriting, // Can be a race condition.
1006 .DESTADDRREQ => unreachable, // `connect` was never called.
1007 .DQUOT => return error.DiskQuota,
1008 .FBIG => return error.FileTooBig,
1009 .IO => return error.InputOutput,
1010 .NOSPC => return error.NoSpaceLeft,
1011 .PERM => return error.AccessDenied,
1012 .PIPE => return error.BrokenPipe,
1013 .NXIO => return error.Unseekable,
1014 .SPIPE => return error.Unseekable,
1015 .OVERFLOW => return error.Unseekable,
10211016 else => |err| return unexpectedErrno(err),
10221017 }
10231018 }
......@@ -1098,27 +1093,27 @@ pub fn openZ(file_path: [*:0]const u8, flags: u32, perm: mode_t) OpenError!fd_t
10981093 while (true) {
10991094 const rc = open_sym(file_path, flags, perm);
11001095 switch (errno(rc)) {
1101 0 => return @intCast(fd_t, rc),
1102 EINTR => continue,
1103
1104 EFAULT => unreachable,
1105 EINVAL => unreachable,
1106 EACCES => return error.AccessDenied,
1107 EFBIG => return error.FileTooBig,
1108 EOVERFLOW => return error.FileTooBig,
1109 EISDIR => return error.IsDir,
1110 ELOOP => return error.SymLinkLoop,
1111 EMFILE => return error.ProcessFdQuotaExceeded,
1112 ENAMETOOLONG => return error.NameTooLong,
1113 ENFILE => return error.SystemFdQuotaExceeded,
1114 ENODEV => return error.NoDevice,
1115 ENOENT => return error.FileNotFound,
1116 ENOMEM => return error.SystemResources,
1117 ENOSPC => return error.NoSpaceLeft,
1118 ENOTDIR => return error.NotDir,
1119 EPERM => return error.AccessDenied,
1120 EEXIST => return error.PathAlreadyExists,
1121 EBUSY => return error.DeviceBusy,
1096 .SUCCESS => return @intCast(fd_t, rc),
1097 .INTR => continue,
1098
1099 .FAULT => unreachable,
1100 .INVAL => unreachable,
1101 .ACCES => return error.AccessDenied,
1102 .FBIG => return error.FileTooBig,
1103 .OVERFLOW => return error.FileTooBig,
1104 .ISDIR => return error.IsDir,
1105 .LOOP => return error.SymLinkLoop,
1106 .MFILE => return error.ProcessFdQuotaExceeded,
1107 .NAMETOOLONG => return error.NameTooLong,
1108 .NFILE => return error.SystemFdQuotaExceeded,
1109 .NODEV => return error.NoDevice,
1110 .NOENT => return error.FileNotFound,
1111 .NOMEM => return error.SystemResources,
1112 .NOSPC => return error.NoSpaceLeft,
1113 .NOTDIR => return error.NotDir,
1114 .PERM => return error.AccessDenied,
1115 .EXIST => return error.PathAlreadyExists,
1116 .BUSY => return error.DeviceBusy,
11221117 else => |err| return unexpectedErrno(err),
11231118 }
11241119 }
......@@ -1193,28 +1188,28 @@ pub fn openatWasi(dir_fd: fd_t, file_path: []const u8, lookup_flags: lookupflags
11931188 while (true) {
11941189 var fd: fd_t = undefined;
11951190 switch (wasi.path_open(dir_fd, lookup_flags, file_path.ptr, file_path.len, oflags, base, inheriting, fdflags, &fd)) {
1196 wasi.ESUCCESS => return fd,
1197 wasi.EINTR => continue,
1198
1199 wasi.EFAULT => unreachable,
1200 wasi.EINVAL => unreachable,
1201 wasi.EACCES => return error.AccessDenied,
1202 wasi.EFBIG => return error.FileTooBig,
1203 wasi.EOVERFLOW => return error.FileTooBig,
1204 wasi.EISDIR => return error.IsDir,
1205 wasi.ELOOP => return error.SymLinkLoop,
1206 wasi.EMFILE => return error.ProcessFdQuotaExceeded,
1207 wasi.ENAMETOOLONG => return error.NameTooLong,
1208 wasi.ENFILE => return error.SystemFdQuotaExceeded,
1209 wasi.ENODEV => return error.NoDevice,
1210 wasi.ENOENT => return error.FileNotFound,
1211 wasi.ENOMEM => return error.SystemResources,
1212 wasi.ENOSPC => return error.NoSpaceLeft,
1213 wasi.ENOTDIR => return error.NotDir,
1214 wasi.EPERM => return error.AccessDenied,
1215 wasi.EEXIST => return error.PathAlreadyExists,
1216 wasi.EBUSY => return error.DeviceBusy,
1217 wasi.ENOTCAPABLE => return error.AccessDenied,
1191 .SUCCESS => return fd,
1192 .INTR => continue,
1193
1194 .FAULT => unreachable,
1195 .INVAL => unreachable,
1196 .ACCES => return error.AccessDenied,
1197 .FBIG => return error.FileTooBig,
1198 .OVERFLOW => return error.FileTooBig,
1199 .ISDIR => return error.IsDir,
1200 .LOOP => return error.SymLinkLoop,
1201 .MFILE => return error.ProcessFdQuotaExceeded,
1202 .NAMETOOLONG => return error.NameTooLong,
1203 .NFILE => return error.SystemFdQuotaExceeded,
1204 .NODEV => return error.NoDevice,
1205 .NOENT => return error.FileNotFound,
1206 .NOMEM => return error.SystemResources,
1207 .NOSPC => return error.NoSpaceLeft,
1208 .NOTDIR => return error.NotDir,
1209 .PERM => return error.AccessDenied,
1210 .EXIST => return error.PathAlreadyExists,
1211 .BUSY => return error.DeviceBusy,
1212 .NOTCAPABLE => return error.AccessDenied,
12181213 else => |err| return unexpectedErrno(err),
12191214 }
12201215 }
......@@ -1239,30 +1234,30 @@ pub fn openatZ(dir_fd: fd_t, file_path: [*:0]const u8, flags: u32, mode: mode_t)
12391234 while (true) {
12401235 const rc = openat_sym(dir_fd, file_path, flags, mode);
12411236 switch (errno(rc)) {
1242 0 => return @intCast(fd_t, rc),
1243 EINTR => continue,
1244
1245 EFAULT => unreachable,
1246 EINVAL => unreachable,
1247 EBADF => unreachable,
1248 EACCES => return error.AccessDenied,
1249 EFBIG => return error.FileTooBig,
1250 EOVERFLOW => return error.FileTooBig,
1251 EISDIR => return error.IsDir,
1252 ELOOP => return error.SymLinkLoop,
1253 EMFILE => return error.ProcessFdQuotaExceeded,
1254 ENAMETOOLONG => return error.NameTooLong,
1255 ENFILE => return error.SystemFdQuotaExceeded,
1256 ENODEV => return error.NoDevice,
1257 ENOENT => return error.FileNotFound,
1258 ENOMEM => return error.SystemResources,
1259 ENOSPC => return error.NoSpaceLeft,
1260 ENOTDIR => return error.NotDir,
1261 EPERM => return error.AccessDenied,
1262 EEXIST => return error.PathAlreadyExists,
1263 EBUSY => return error.DeviceBusy,
1264 EOPNOTSUPP => return error.FileLocksNotSupported,
1265 EWOULDBLOCK => return error.WouldBlock,
1237 .SUCCESS => return @intCast(fd_t, rc),
1238 .INTR => continue,
1239
1240 .FAULT => unreachable,
1241 .INVAL => unreachable,
1242 .BADF => unreachable,
1243 .ACCES => return error.AccessDenied,
1244 .FBIG => return error.FileTooBig,
1245 .OVERFLOW => return error.FileTooBig,
1246 .ISDIR => return error.IsDir,
1247 .LOOP => return error.SymLinkLoop,
1248 .MFILE => return error.ProcessFdQuotaExceeded,
1249 .NAMETOOLONG => return error.NameTooLong,
1250 .NFILE => return error.SystemFdQuotaExceeded,
1251 .NODEV => return error.NoDevice,
1252 .NOENT => return error.FileNotFound,
1253 .NOMEM => return error.SystemResources,
1254 .NOSPC => return error.NoSpaceLeft,
1255 .NOTDIR => return error.NotDir,
1256 .PERM => return error.AccessDenied,
1257 .EXIST => return error.PathAlreadyExists,
1258 .BUSY => return error.DeviceBusy,
1259 .OPNOTSUPP => return error.FileLocksNotSupported,
1260 .AGAIN => return error.WouldBlock,
12661261 else => |err| return unexpectedErrno(err),
12671262 }
12681263 }
......@@ -1286,9 +1281,9 @@ pub fn openatW(dir_fd: fd_t, file_path_w: []const u16, flags: u32, mode: mode_t)
12861281pub fn dup(old_fd: fd_t) !fd_t {
12871282 const rc = system.dup(old_fd);
12881283 return switch (errno(rc)) {
1289 0 => return @intCast(fd_t, rc),
1290 EMFILE => error.ProcessFdQuotaExceeded,
1291 EBADF => unreachable, // invalid file descriptor
1284 .SUCCESS => return @intCast(fd_t, rc),
1285 .MFILE => error.ProcessFdQuotaExceeded,
1286 .BADF => unreachable, // invalid file descriptor
12921287 else => |err| return unexpectedErrno(err),
12931288 };
12941289}
......@@ -1296,11 +1291,11 @@ pub fn dup(old_fd: fd_t) !fd_t {
12961291pub fn dup2(old_fd: fd_t, new_fd: fd_t) !void {
12971292 while (true) {
12981293 switch (errno(system.dup2(old_fd, new_fd))) {
1299 0 => return,
1300 EBUSY, EINTR => continue,
1301 EMFILE => return error.ProcessFdQuotaExceeded,
1302 EINVAL => unreachable, // invalid parameters passed to dup2
1303 EBADF => unreachable, // invalid file descriptor
1294 .SUCCESS => return,
1295 .BUSY, .INTR => continue,
1296 .MFILE => return error.ProcessFdQuotaExceeded,
1297 .INVAL => unreachable, // invalid parameters passed to dup2
1298 .BADF => unreachable, // invalid file descriptor
13041299 else => |err| return unexpectedErrno(err),
13051300 }
13061301 }
......@@ -1331,23 +1326,23 @@ pub fn execveZ(
13311326 envp: [*:null]const ?[*:0]const u8,
13321327) ExecveError {
13331328 switch (errno(system.execve(path, child_argv, envp))) {
1334 0 => unreachable,
1335 EFAULT => unreachable,
1336 E2BIG => return error.SystemResources,
1337 EMFILE => return error.ProcessFdQuotaExceeded,
1338 ENAMETOOLONG => return error.NameTooLong,
1339 ENFILE => return error.SystemFdQuotaExceeded,
1340 ENOMEM => return error.SystemResources,
1341 EACCES => return error.AccessDenied,
1342 EPERM => return error.AccessDenied,
1343 EINVAL => return error.InvalidExe,
1344 ENOEXEC => return error.InvalidExe,
1345 EIO => return error.FileSystem,
1346 ELOOP => return error.FileSystem,
1347 EISDIR => return error.IsDir,
1348 ENOENT => return error.FileNotFound,
1349 ENOTDIR => return error.NotDir,
1350 ETXTBSY => return error.FileBusy,
1329 .SUCCESS => unreachable,
1330 .FAULT => unreachable,
1331 .@"2BIG" => return error.SystemResources,
1332 .MFILE => return error.ProcessFdQuotaExceeded,
1333 .NAMETOOLONG => return error.NameTooLong,
1334 .NFILE => return error.SystemFdQuotaExceeded,
1335 .NOMEM => return error.SystemResources,
1336 .ACCES => return error.AccessDenied,
1337 .PERM => return error.AccessDenied,
1338 .INVAL => return error.InvalidExe,
1339 .NOEXEC => return error.InvalidExe,
1340 .IO => return error.FileSystem,
1341 .LOOP => return error.FileSystem,
1342 .ISDIR => return error.IsDir,
1343 .NOENT => return error.FileNotFound,
1344 .NOTDIR => return error.NotDir,
1345 .TXTBSY => return error.FileBusy,
13511346 else => |err| return unexpectedErrno(err),
13521347 }
13531348}
......@@ -1543,16 +1538,17 @@ pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 {
15431538 }
15441539
15451540 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);
15471543 } else blk: {
15481544 break :blk errno(system.getcwd(out_buffer.ptr, out_buffer.len));
15491545 };
15501546 switch (err) {
1551 0 => return mem.spanZ(std.meta.assumeSentinel(out_buffer.ptr, 0)),
1552 EFAULT => unreachable,
1553 EINVAL => unreachable,
1554 ENOENT => return error.CurrentWorkingDirectoryUnlinked,
1555 ERANGE => return error.NameTooLong,
1547 .SUCCESS => return mem.spanZ(std.meta.assumeSentinel(out_buffer.ptr, 0)),
1548 .FAULT => unreachable,
1549 .INVAL => unreachable,
1550 .NOENT => return error.CurrentWorkingDirectoryUnlinked,
1551 .RANGE => return error.NameTooLong,
15561552 else => return unexpectedErrno(err),
15571553 }
15581554}
......@@ -1601,21 +1597,21 @@ pub fn symlinkZ(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLin
16011597 @compileError("symlink is not supported on Windows; use std.os.windows.CreateSymbolicLink instead");
16021598 }
16031599 switch (errno(system.symlink(target_path, sym_link_path))) {
1604 0 => return,
1605 EFAULT => unreachable,
1606 EINVAL => unreachable,
1607 EACCES => return error.AccessDenied,
1608 EPERM => return error.AccessDenied,
1609 EDQUOT => return error.DiskQuota,
1610 EEXIST => return error.PathAlreadyExists,
1611 EIO => return error.FileSystem,
1612 ELOOP => return error.SymLinkLoop,
1613 ENAMETOOLONG => return error.NameTooLong,
1614 ENOENT => return error.FileNotFound,
1615 ENOTDIR => return error.NotDir,
1616 ENOMEM => return error.SystemResources,
1617 ENOSPC => return error.NoSpaceLeft,
1618 EROFS => return error.ReadOnlyFileSystem,
1600 .SUCCESS => return,
1601 .FAULT => unreachable,
1602 .INVAL => unreachable,
1603 .ACCES => return error.AccessDenied,
1604 .PERM => return error.AccessDenied,
1605 .DQUOT => return error.DiskQuota,
1606 .EXIST => return error.PathAlreadyExists,
1607 .IO => return error.FileSystem,
1608 .LOOP => return error.SymLinkLoop,
1609 .NAMETOOLONG => return error.NameTooLong,
1610 .NOENT => return error.FileNotFound,
1611 .NOTDIR => return error.NotDir,
1612 .NOMEM => return error.SystemResources,
1613 .NOSPC => return error.NoSpaceLeft,
1614 .ROFS => return error.ReadOnlyFileSystem,
16191615 else => |err| return unexpectedErrno(err),
16201616 }
16211617}
......@@ -1644,22 +1640,22 @@ pub const symlinkatC = @compileError("deprecated: renamed to symlinkatZ");
16441640/// See also `symlinkat`.
16451641pub fn symlinkatWasi(target_path: []const u8, newdirfd: fd_t, sym_link_path: []const u8) SymLinkError!void {
16461642 switch (wasi.path_symlink(target_path.ptr, target_path.len, newdirfd, sym_link_path.ptr, sym_link_path.len)) {
1647 wasi.ESUCCESS => {},
1648 wasi.EFAULT => unreachable,
1649 wasi.EINVAL => unreachable,
1650 wasi.EACCES => return error.AccessDenied,
1651 wasi.EPERM => return error.AccessDenied,
1652 wasi.EDQUOT => return error.DiskQuota,
1653 wasi.EEXIST => return error.PathAlreadyExists,
1654 wasi.EIO => return error.FileSystem,
1655 wasi.ELOOP => return error.SymLinkLoop,
1656 wasi.ENAMETOOLONG => return error.NameTooLong,
1657 wasi.ENOENT => return error.FileNotFound,
1658 wasi.ENOTDIR => return error.NotDir,
1659 wasi.ENOMEM => return error.SystemResources,
1660 wasi.ENOSPC => return error.NoSpaceLeft,
1661 wasi.EROFS => return error.ReadOnlyFileSystem,
1662 wasi.ENOTCAPABLE => return error.AccessDenied,
1643 .SUCCESS => {},
1644 .FAULT => unreachable,
1645 .INVAL => unreachable,
1646 .ACCES => return error.AccessDenied,
1647 .PERM => return error.AccessDenied,
1648 .DQUOT => return error.DiskQuota,
1649 .EXIST => return error.PathAlreadyExists,
1650 .IO => return error.FileSystem,
1651 .LOOP => return error.SymLinkLoop,
1652 .NAMETOOLONG => return error.NameTooLong,
1653 .NOENT => return error.FileNotFound,
1654 .NOTDIR => return error.NotDir,
1655 .NOMEM => return error.SystemResources,
1656 .NOSPC => return error.NoSpaceLeft,
1657 .ROFS => return error.ReadOnlyFileSystem,
1658 .NOTCAPABLE => return error.AccessDenied,
16631659 else => |err| return unexpectedErrno(err),
16641660 }
16651661}
......@@ -1671,21 +1667,21 @@ pub fn symlinkatZ(target_path: [*:0]const u8, newdirfd: fd_t, sym_link_path: [*:
16711667 @compileError("symlinkat is not supported on Windows; use std.os.windows.CreateSymbolicLink instead");
16721668 }
16731669 switch (errno(system.symlinkat(target_path, newdirfd, sym_link_path))) {
1674 0 => return,
1675 EFAULT => unreachable,
1676 EINVAL => unreachable,
1677 EACCES => return error.AccessDenied,
1678 EPERM => return error.AccessDenied,
1679 EDQUOT => return error.DiskQuota,
1680 EEXIST => return error.PathAlreadyExists,
1681 EIO => return error.FileSystem,
1682 ELOOP => return error.SymLinkLoop,
1683 ENAMETOOLONG => return error.NameTooLong,
1684 ENOENT => return error.FileNotFound,
1685 ENOTDIR => return error.NotDir,
1686 ENOMEM => return error.SystemResources,
1687 ENOSPC => return error.NoSpaceLeft,
1688 EROFS => return error.ReadOnlyFileSystem,
1670 .SUCCESS => return,
1671 .FAULT => unreachable,
1672 .INVAL => unreachable,
1673 .ACCES => return error.AccessDenied,
1674 .PERM => return error.AccessDenied,
1675 .DQUOT => return error.DiskQuota,
1676 .EXIST => return error.PathAlreadyExists,
1677 .IO => return error.FileSystem,
1678 .LOOP => return error.SymLinkLoop,
1679 .NAMETOOLONG => return error.NameTooLong,
1680 .NOENT => return error.FileNotFound,
1681 .NOTDIR => return error.NotDir,
1682 .NOMEM => return error.SystemResources,
1683 .NOSPC => return error.NoSpaceLeft,
1684 .ROFS => return error.ReadOnlyFileSystem,
16891685 else => |err| return unexpectedErrno(err),
16901686 }
16911687}
......@@ -1707,22 +1703,22 @@ pub const LinkError = UnexpectedError || error{
17071703
17081704pub fn linkZ(oldpath: [*:0]const u8, newpath: [*:0]const u8, flags: i32) LinkError!void {
17091705 switch (errno(system.link(oldpath, newpath, flags))) {
1710 0 => return,
1711 EACCES => return error.AccessDenied,
1712 EDQUOT => return error.DiskQuota,
1713 EEXIST => return error.PathAlreadyExists,
1714 EFAULT => unreachable,
1715 EIO => return error.FileSystem,
1716 ELOOP => return error.SymLinkLoop,
1717 EMLINK => return error.LinkQuotaExceeded,
1718 ENAMETOOLONG => return error.NameTooLong,
1719 ENOENT => return error.FileNotFound,
1720 ENOMEM => return error.SystemResources,
1721 ENOSPC => return error.NoSpaceLeft,
1722 EPERM => return error.AccessDenied,
1723 EROFS => return error.ReadOnlyFileSystem,
1724 EXDEV => return error.NotSameFileSystem,
1725 EINVAL => unreachable,
1706 .SUCCESS => return,
1707 .ACCES => return error.AccessDenied,
1708 .DQUOT => return error.DiskQuota,
1709 .EXIST => return error.PathAlreadyExists,
1710 .FAULT => unreachable,
1711 .IO => return error.FileSystem,
1712 .LOOP => return error.SymLinkLoop,
1713 .MLINK => return error.LinkQuotaExceeded,
1714 .NAMETOOLONG => return error.NameTooLong,
1715 .NOENT => return error.FileNotFound,
1716 .NOMEM => return error.SystemResources,
1717 .NOSPC => return error.NoSpaceLeft,
1718 .PERM => return error.AccessDenied,
1719 .ROFS => return error.ReadOnlyFileSystem,
1720 .XDEV => return error.NotSameFileSystem,
1721 .INVAL => unreachable,
17261722 else => |err| return unexpectedErrno(err),
17271723 }
17281724}
......@@ -1743,23 +1739,23 @@ pub fn linkatZ(
17431739 flags: i32,
17441740) LinkatError!void {
17451741 switch (errno(system.linkat(olddir, oldpath, newdir, newpath, flags))) {
1746 0 => return,
1747 EACCES => return error.AccessDenied,
1748 EDQUOT => return error.DiskQuota,
1749 EEXIST => return error.PathAlreadyExists,
1750 EFAULT => unreachable,
1751 EIO => return error.FileSystem,
1752 ELOOP => return error.SymLinkLoop,
1753 EMLINK => return error.LinkQuotaExceeded,
1754 ENAMETOOLONG => return error.NameTooLong,
1755 ENOENT => return error.FileNotFound,
1756 ENOMEM => return error.SystemResources,
1757 ENOSPC => return error.NoSpaceLeft,
1758 ENOTDIR => return error.NotDir,
1759 EPERM => return error.AccessDenied,
1760 EROFS => return error.ReadOnlyFileSystem,
1761 EXDEV => return error.NotSameFileSystem,
1762 EINVAL => unreachable,
1742 .SUCCESS => return,
1743 .ACCES => return error.AccessDenied,
1744 .DQUOT => return error.DiskQuota,
1745 .EXIST => return error.PathAlreadyExists,
1746 .FAULT => unreachable,
1747 .IO => return error.FileSystem,
1748 .LOOP => return error.SymLinkLoop,
1749 .MLINK => return error.LinkQuotaExceeded,
1750 .NAMETOOLONG => return error.NameTooLong,
1751 .NOENT => return error.FileNotFound,
1752 .NOMEM => return error.SystemResources,
1753 .NOSPC => return error.NoSpaceLeft,
1754 .NOTDIR => return error.NotDir,
1755 .PERM => return error.AccessDenied,
1756 .ROFS => return error.ReadOnlyFileSystem,
1757 .XDEV => return error.NotSameFileSystem,
1758 .INVAL => unreachable,
17631759 else => |err| return unexpectedErrno(err),
17641760 }
17651761}
......@@ -1822,20 +1818,20 @@ pub fn unlinkZ(file_path: [*:0]const u8) UnlinkError!void {
18221818 return unlinkW(file_path_w.span());
18231819 }
18241820 switch (errno(system.unlink(file_path))) {
1825 0 => return,
1826 EACCES => return error.AccessDenied,
1827 EPERM => return error.AccessDenied,
1828 EBUSY => return error.FileBusy,
1829 EFAULT => unreachable,
1830 EINVAL => unreachable,
1831 EIO => return error.FileSystem,
1832 EISDIR => return error.IsDir,
1833 ELOOP => return error.SymLinkLoop,
1834 ENAMETOOLONG => return error.NameTooLong,
1835 ENOENT => return error.FileNotFound,
1836 ENOTDIR => return error.NotDir,
1837 ENOMEM => return error.SystemResources,
1838 EROFS => return error.ReadOnlyFileSystem,
1821 .SUCCESS => return,
1822 .ACCES => return error.AccessDenied,
1823 .PERM => return error.AccessDenied,
1824 .BUSY => return error.FileBusy,
1825 .FAULT => unreachable,
1826 .INVAL => unreachable,
1827 .IO => return error.FileSystem,
1828 .ISDIR => return error.IsDir,
1829 .LOOP => return error.SymLinkLoop,
1830 .NAMETOOLONG => return error.NameTooLong,
1831 .NOENT => return error.FileNotFound,
1832 .NOTDIR => return error.NotDir,
1833 .NOMEM => return error.SystemResources,
1834 .ROFS => return error.ReadOnlyFileSystem,
18391835 else => |err| return unexpectedErrno(err),
18401836 }
18411837}
......@@ -1875,24 +1871,24 @@ pub fn unlinkatWasi(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatErro
18751871 else
18761872 wasi.path_unlink_file(dirfd, file_path.ptr, file_path.len);
18771873 switch (res) {
1878 wasi.ESUCCESS => return,
1879 wasi.EACCES => return error.AccessDenied,
1880 wasi.EPERM => return error.AccessDenied,
1881 wasi.EBUSY => return error.FileBusy,
1882 wasi.EFAULT => unreachable,
1883 wasi.EIO => return error.FileSystem,
1884 wasi.EISDIR => return error.IsDir,
1885 wasi.ELOOP => return error.SymLinkLoop,
1886 wasi.ENAMETOOLONG => return error.NameTooLong,
1887 wasi.ENOENT => return error.FileNotFound,
1888 wasi.ENOTDIR => return error.NotDir,
1889 wasi.ENOMEM => return error.SystemResources,
1890 wasi.EROFS => return error.ReadOnlyFileSystem,
1891 wasi.ENOTEMPTY => return error.DirNotEmpty,
1892 wasi.ENOTCAPABLE => return error.AccessDenied,
1893
1894 wasi.EINVAL => unreachable, // invalid flags, or pathname has . as last component
1895 wasi.EBADF => unreachable, // always a race condition
1874 .SUCCESS => return,
1875 .ACCES => return error.AccessDenied,
1876 .PERM => return error.AccessDenied,
1877 .BUSY => return error.FileBusy,
1878 .FAULT => unreachable,
1879 .IO => return error.FileSystem,
1880 .ISDIR => return error.IsDir,
1881 .LOOP => return error.SymLinkLoop,
1882 .NAMETOOLONG => return error.NameTooLong,
1883 .NOENT => return error.FileNotFound,
1884 .NOTDIR => return error.NotDir,
1885 .NOMEM => return error.SystemResources,
1886 .ROFS => return error.ReadOnlyFileSystem,
1887 .NOTEMPTY => return error.DirNotEmpty,
1888 .NOTCAPABLE => return error.AccessDenied,
1889
1890 .INVAL => unreachable, // invalid flags, or pathname has . as last component
1891 .BADF => unreachable, // always a race condition
18961892
18971893 else => |err| return unexpectedErrno(err),
18981894 }
......@@ -1905,23 +1901,23 @@ pub fn unlinkatZ(dirfd: fd_t, file_path_c: [*:0]const u8, flags: u32) UnlinkatEr
19051901 return unlinkatW(dirfd, file_path_w.span(), flags);
19061902 }
19071903 switch (errno(system.unlinkat(dirfd, file_path_c, flags))) {
1908 0 => return,
1909 EACCES => return error.AccessDenied,
1910 EPERM => return error.AccessDenied,
1911 EBUSY => return error.FileBusy,
1912 EFAULT => unreachable,
1913 EIO => return error.FileSystem,
1914 EISDIR => return error.IsDir,
1915 ELOOP => return error.SymLinkLoop,
1916 ENAMETOOLONG => return error.NameTooLong,
1917 ENOENT => return error.FileNotFound,
1918 ENOTDIR => return error.NotDir,
1919 ENOMEM => return error.SystemResources,
1920 EROFS => return error.ReadOnlyFileSystem,
1921 ENOTEMPTY => return error.DirNotEmpty,
1922
1923 EINVAL => unreachable, // invalid flags, or pathname has . as last component
1924 EBADF => unreachable, // always a race condition
1904 .SUCCESS => return,
1905 .ACCES => return error.AccessDenied,
1906 .PERM => return error.AccessDenied,
1907 .BUSY => return error.FileBusy,
1908 .FAULT => unreachable,
1909 .IO => return error.FileSystem,
1910 .ISDIR => return error.IsDir,
1911 .LOOP => return error.SymLinkLoop,
1912 .NAMETOOLONG => return error.NameTooLong,
1913 .NOENT => return error.FileNotFound,
1914 .NOTDIR => return error.NotDir,
1915 .NOMEM => return error.SystemResources,
1916 .ROFS => return error.ReadOnlyFileSystem,
1917 .NOTEMPTY => return error.DirNotEmpty,
1918
1919 .INVAL => unreachable, // invalid flags, or pathname has . as last component
1920 .BADF => unreachable, // always a race condition
19251921
19261922 else => |err| return unexpectedErrno(err),
19271923 }
......@@ -1982,25 +1978,25 @@ pub fn renameZ(old_path: [*:0]const u8, new_path: [*:0]const u8) RenameError!voi
19821978 return renameW(old_path_w.span().ptr, new_path_w.span().ptr);
19831979 }
19841980 switch (errno(system.rename(old_path, new_path))) {
1985 0 => return,
1986 EACCES => return error.AccessDenied,
1987 EPERM => return error.AccessDenied,
1988 EBUSY => return error.FileBusy,
1989 EDQUOT => return error.DiskQuota,
1990 EFAULT => unreachable,
1991 EINVAL => unreachable,
1992 EISDIR => return error.IsDir,
1993 ELOOP => return error.SymLinkLoop,
1994 EMLINK => return error.LinkQuotaExceeded,
1995 ENAMETOOLONG => return error.NameTooLong,
1996 ENOENT => return error.FileNotFound,
1997 ENOTDIR => return error.NotDir,
1998 ENOMEM => return error.SystemResources,
1999 ENOSPC => return error.NoSpaceLeft,
2000 EEXIST => return error.PathAlreadyExists,
2001 ENOTEMPTY => return error.PathAlreadyExists,
2002 EROFS => return error.ReadOnlyFileSystem,
2003 EXDEV => return error.RenameAcrossMountPoints,
1981 .SUCCESS => return,
1982 .ACCES => return error.AccessDenied,
1983 .PERM => return error.AccessDenied,
1984 .BUSY => return error.FileBusy,
1985 .DQUOT => return error.DiskQuota,
1986 .FAULT => unreachable,
1987 .INVAL => unreachable,
1988 .ISDIR => return error.IsDir,
1989 .LOOP => return error.SymLinkLoop,
1990 .MLINK => return error.LinkQuotaExceeded,
1991 .NAMETOOLONG => return error.NameTooLong,
1992 .NOENT => return error.FileNotFound,
1993 .NOTDIR => return error.NotDir,
1994 .NOMEM => return error.SystemResources,
1995 .NOSPC => return error.NoSpaceLeft,
1996 .EXIST => return error.PathAlreadyExists,
1997 .NOTEMPTY => return error.PathAlreadyExists,
1998 .ROFS => return error.ReadOnlyFileSystem,
1999 .XDEV => return error.RenameAcrossMountPoints,
20042000 else => |err| return unexpectedErrno(err),
20052001 }
20062002}
......@@ -2036,26 +2032,26 @@ pub fn renameat(
20362032/// See also `renameat`.
20372033pub fn renameatWasi(old_dir_fd: fd_t, old_path: []const u8, new_dir_fd: fd_t, new_path: []const u8) RenameError!void {
20382034 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,
2040 wasi.EACCES => return error.AccessDenied,
2041 wasi.EPERM => return error.AccessDenied,
2042 wasi.EBUSY => return error.FileBusy,
2043 wasi.EDQUOT => return error.DiskQuota,
2044 wasi.EFAULT => unreachable,
2045 wasi.EINVAL => unreachable,
2046 wasi.EISDIR => return error.IsDir,
2047 wasi.ELOOP => return error.SymLinkLoop,
2048 wasi.EMLINK => return error.LinkQuotaExceeded,
2049 wasi.ENAMETOOLONG => return error.NameTooLong,
2050 wasi.ENOENT => return error.FileNotFound,
2051 wasi.ENOTDIR => return error.NotDir,
2052 wasi.ENOMEM => return error.SystemResources,
2053 wasi.ENOSPC => return error.NoSpaceLeft,
2054 wasi.EEXIST => return error.PathAlreadyExists,
2055 wasi.ENOTEMPTY => return error.PathAlreadyExists,
2056 wasi.EROFS => return error.ReadOnlyFileSystem,
2057 wasi.EXDEV => return error.RenameAcrossMountPoints,
2058 wasi.ENOTCAPABLE => return error.AccessDenied,
2035 .SUCCESS => return,
2036 .ACCES => return error.AccessDenied,
2037 .PERM => return error.AccessDenied,
2038 .BUSY => return error.FileBusy,
2039 .DQUOT => return error.DiskQuota,
2040 .FAULT => unreachable,
2041 .INVAL => unreachable,
2042 .ISDIR => return error.IsDir,
2043 .LOOP => return error.SymLinkLoop,
2044 .MLINK => return error.LinkQuotaExceeded,
2045 .NAMETOOLONG => return error.NameTooLong,
2046 .NOENT => return error.FileNotFound,
2047 .NOTDIR => return error.NotDir,
2048 .NOMEM => return error.SystemResources,
2049 .NOSPC => return error.NoSpaceLeft,
2050 .EXIST => return error.PathAlreadyExists,
2051 .NOTEMPTY => return error.PathAlreadyExists,
2052 .ROFS => return error.ReadOnlyFileSystem,
2053 .XDEV => return error.RenameAcrossMountPoints,
2054 .NOTCAPABLE => return error.AccessDenied,
20592055 else => |err| return unexpectedErrno(err),
20602056 }
20612057}
......@@ -2074,25 +2070,25 @@ pub fn renameatZ(
20742070 }
20752071
20762072 switch (errno(system.renameat(old_dir_fd, old_path, new_dir_fd, new_path))) {
2077 0 => return,
2078 EACCES => return error.AccessDenied,
2079 EPERM => return error.AccessDenied,
2080 EBUSY => return error.FileBusy,
2081 EDQUOT => return error.DiskQuota,
2082 EFAULT => unreachable,
2083 EINVAL => unreachable,
2084 EISDIR => return error.IsDir,
2085 ELOOP => return error.SymLinkLoop,
2086 EMLINK => return error.LinkQuotaExceeded,
2087 ENAMETOOLONG => return error.NameTooLong,
2088 ENOENT => return error.FileNotFound,
2089 ENOTDIR => return error.NotDir,
2090 ENOMEM => return error.SystemResources,
2091 ENOSPC => return error.NoSpaceLeft,
2092 EEXIST => return error.PathAlreadyExists,
2093 ENOTEMPTY => return error.PathAlreadyExists,
2094 EROFS => return error.ReadOnlyFileSystem,
2095 EXDEV => return error.RenameAcrossMountPoints,
2073 .SUCCESS => return,
2074 .ACCES => return error.AccessDenied,
2075 .PERM => return error.AccessDenied,
2076 .BUSY => return error.FileBusy,
2077 .DQUOT => return error.DiskQuota,
2078 .FAULT => unreachable,
2079 .INVAL => unreachable,
2080 .ISDIR => return error.IsDir,
2081 .LOOP => return error.SymLinkLoop,
2082 .MLINK => return error.LinkQuotaExceeded,
2083 .NAMETOOLONG => return error.NameTooLong,
2084 .NOENT => return error.FileNotFound,
2085 .NOTDIR => return error.NotDir,
2086 .NOMEM => return error.SystemResources,
2087 .NOSPC => return error.NoSpaceLeft,
2088 .EXIST => return error.PathAlreadyExists,
2089 .NOTEMPTY => return error.PathAlreadyExists,
2090 .ROFS => return error.ReadOnlyFileSystem,
2091 .XDEV => return error.RenameAcrossMountPoints,
20962092 else => |err| return unexpectedErrno(err),
20972093 }
20982094}
......@@ -2172,22 +2168,22 @@ pub const mkdiratC = @compileError("deprecated: renamed to mkdiratZ");
21722168pub fn mkdiratWasi(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!void {
21732169 _ = mode;
21742170 switch (wasi.path_create_directory(dir_fd, sub_dir_path.ptr, sub_dir_path.len)) {
2175 wasi.ESUCCESS => return,
2176 wasi.EACCES => return error.AccessDenied,
2177 wasi.EBADF => unreachable,
2178 wasi.EPERM => return error.AccessDenied,
2179 wasi.EDQUOT => return error.DiskQuota,
2180 wasi.EEXIST => return error.PathAlreadyExists,
2181 wasi.EFAULT => unreachable,
2182 wasi.ELOOP => return error.SymLinkLoop,
2183 wasi.EMLINK => return error.LinkQuotaExceeded,
2184 wasi.ENAMETOOLONG => return error.NameTooLong,
2185 wasi.ENOENT => return error.FileNotFound,
2186 wasi.ENOMEM => return error.SystemResources,
2187 wasi.ENOSPC => return error.NoSpaceLeft,
2188 wasi.ENOTDIR => return error.NotDir,
2189 wasi.EROFS => return error.ReadOnlyFileSystem,
2190 wasi.ENOTCAPABLE => return error.AccessDenied,
2171 .SUCCESS => return,
2172 .ACCES => return error.AccessDenied,
2173 .BADF => unreachable,
2174 .PERM => return error.AccessDenied,
2175 .DQUOT => return error.DiskQuota,
2176 .EXIST => return error.PathAlreadyExists,
2177 .FAULT => unreachable,
2178 .LOOP => return error.SymLinkLoop,
2179 .MLINK => return error.LinkQuotaExceeded,
2180 .NAMETOOLONG => return error.NameTooLong,
2181 .NOENT => return error.FileNotFound,
2182 .NOMEM => return error.SystemResources,
2183 .NOSPC => return error.NoSpaceLeft,
2184 .NOTDIR => return error.NotDir,
2185 .ROFS => return error.ReadOnlyFileSystem,
2186 .NOTCAPABLE => return error.AccessDenied,
21912187 else => |err| return unexpectedErrno(err),
21922188 }
21932189}
......@@ -2198,21 +2194,21 @@ pub fn mkdiratZ(dir_fd: fd_t, sub_dir_path: [*:0]const u8, mode: u32) MakeDirErr
21982194 return mkdiratW(dir_fd, sub_dir_path_w.span().ptr, mode);
21992195 }
22002196 switch (errno(system.mkdirat(dir_fd, sub_dir_path, mode))) {
2201 0 => return,
2202 EACCES => return error.AccessDenied,
2203 EBADF => unreachable,
2204 EPERM => return error.AccessDenied,
2205 EDQUOT => return error.DiskQuota,
2206 EEXIST => return error.PathAlreadyExists,
2207 EFAULT => unreachable,
2208 ELOOP => return error.SymLinkLoop,
2209 EMLINK => return error.LinkQuotaExceeded,
2210 ENAMETOOLONG => return error.NameTooLong,
2211 ENOENT => return error.FileNotFound,
2212 ENOMEM => return error.SystemResources,
2213 ENOSPC => return error.NoSpaceLeft,
2214 ENOTDIR => return error.NotDir,
2215 EROFS => return error.ReadOnlyFileSystem,
2197 .SUCCESS => return,
2198 .ACCES => return error.AccessDenied,
2199 .BADF => unreachable,
2200 .PERM => return error.AccessDenied,
2201 .DQUOT => return error.DiskQuota,
2202 .EXIST => return error.PathAlreadyExists,
2203 .FAULT => unreachable,
2204 .LOOP => return error.SymLinkLoop,
2205 .MLINK => return error.LinkQuotaExceeded,
2206 .NAMETOOLONG => return error.NameTooLong,
2207 .NOENT => return error.FileNotFound,
2208 .NOMEM => return error.SystemResources,
2209 .NOSPC => return error.NoSpaceLeft,
2210 .NOTDIR => return error.NotDir,
2211 .ROFS => return error.ReadOnlyFileSystem,
22162212 else => |err| return unexpectedErrno(err),
22172213 }
22182214}
......@@ -2274,20 +2270,20 @@ pub fn mkdirZ(dir_path: [*:0]const u8, mode: u32) MakeDirError!void {
22742270 return mkdirW(dir_path_w.span(), mode);
22752271 }
22762272 switch (errno(system.mkdir(dir_path, mode))) {
2277 0 => return,
2278 EACCES => return error.AccessDenied,
2279 EPERM => return error.AccessDenied,
2280 EDQUOT => return error.DiskQuota,
2281 EEXIST => return error.PathAlreadyExists,
2282 EFAULT => unreachable,
2283 ELOOP => return error.SymLinkLoop,
2284 EMLINK => return error.LinkQuotaExceeded,
2285 ENAMETOOLONG => return error.NameTooLong,
2286 ENOENT => return error.FileNotFound,
2287 ENOMEM => return error.SystemResources,
2288 ENOSPC => return error.NoSpaceLeft,
2289 ENOTDIR => return error.NotDir,
2290 EROFS => return error.ReadOnlyFileSystem,
2273 .SUCCESS => return,
2274 .ACCES => return error.AccessDenied,
2275 .PERM => return error.AccessDenied,
2276 .DQUOT => return error.DiskQuota,
2277 .EXIST => return error.PathAlreadyExists,
2278 .FAULT => unreachable,
2279 .LOOP => return error.SymLinkLoop,
2280 .MLINK => return error.LinkQuotaExceeded,
2281 .NAMETOOLONG => return error.NameTooLong,
2282 .NOENT => return error.FileNotFound,
2283 .NOMEM => return error.SystemResources,
2284 .NOSPC => return error.NoSpaceLeft,
2285 .NOTDIR => return error.NotDir,
2286 .ROFS => return error.ReadOnlyFileSystem,
22912287 else => |err| return unexpectedErrno(err),
22922288 }
22932289}
......@@ -2346,20 +2342,20 @@ pub fn rmdirZ(dir_path: [*:0]const u8) DeleteDirError!void {
23462342 return rmdirW(dir_path_w.span());
23472343 }
23482344 switch (errno(system.rmdir(dir_path))) {
2349 0 => return,
2350 EACCES => return error.AccessDenied,
2351 EPERM => return error.AccessDenied,
2352 EBUSY => return error.FileBusy,
2353 EFAULT => unreachable,
2354 EINVAL => unreachable,
2355 ELOOP => return error.SymLinkLoop,
2356 ENAMETOOLONG => return error.NameTooLong,
2357 ENOENT => return error.FileNotFound,
2358 ENOMEM => return error.SystemResources,
2359 ENOTDIR => return error.NotDir,
2360 EEXIST => return error.DirNotEmpty,
2361 ENOTEMPTY => return error.DirNotEmpty,
2362 EROFS => return error.ReadOnlyFileSystem,
2345 .SUCCESS => return,
2346 .ACCES => return error.AccessDenied,
2347 .PERM => return error.AccessDenied,
2348 .BUSY => return error.FileBusy,
2349 .FAULT => unreachable,
2350 .INVAL => unreachable,
2351 .LOOP => return error.SymLinkLoop,
2352 .NAMETOOLONG => return error.NameTooLong,
2353 .NOENT => return error.FileNotFound,
2354 .NOMEM => return error.SystemResources,
2355 .NOTDIR => return error.NotDir,
2356 .EXIST => return error.DirNotEmpty,
2357 .NOTEMPTY => return error.DirNotEmpty,
2358 .ROFS => return error.ReadOnlyFileSystem,
23632359 else => |err| return unexpectedErrno(err),
23642360 }
23652361}
......@@ -2413,15 +2409,15 @@ pub fn chdirZ(dir_path: [*:0]const u8) ChangeCurDirError!void {
24132409 return chdirW(utf16_dir_path[0..len]);
24142410 }
24152411 switch (errno(system.chdir(dir_path))) {
2416 0 => return,
2417 EACCES => return error.AccessDenied,
2418 EFAULT => unreachable,
2419 EIO => return error.FileSystem,
2420 ELOOP => return error.SymLinkLoop,
2421 ENAMETOOLONG => return error.NameTooLong,
2422 ENOENT => return error.FileNotFound,
2423 ENOMEM => return error.SystemResources,
2424 ENOTDIR => return error.NotDir,
2412 .SUCCESS => return,
2413 .ACCES => return error.AccessDenied,
2414 .FAULT => unreachable,
2415 .IO => return error.FileSystem,
2416 .LOOP => return error.SymLinkLoop,
2417 .NAMETOOLONG => return error.NameTooLong,
2418 .NOENT => return error.FileNotFound,
2419 .NOMEM => return error.SystemResources,
2420 .NOTDIR => return error.NotDir,
24252421 else => |err| return unexpectedErrno(err),
24262422 }
24272423}
......@@ -2443,12 +2439,12 @@ pub const FchdirError = error{
24432439pub fn fchdir(dirfd: fd_t) FchdirError!void {
24442440 while (true) {
24452441 switch (errno(system.fchdir(dirfd))) {
2446 0 => return,
2447 EACCES => return error.AccessDenied,
2448 EBADF => unreachable,
2449 ENOTDIR => return error.NotDir,
2450 EINTR => continue,
2451 EIO => return error.FileSystem,
2442 .SUCCESS => return,
2443 .ACCES => return error.AccessDenied,
2444 .BADF => unreachable,
2445 .NOTDIR => return error.NotDir,
2446 .INTR => continue,
2447 .IO => return error.FileSystem,
24522448 else => |err| return unexpectedErrno(err),
24532449 }
24542450 }
......@@ -2501,16 +2497,16 @@ pub fn readlinkZ(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8
25012497 }
25022498 const rc = system.readlink(file_path, out_buffer.ptr, out_buffer.len);
25032499 switch (errno(rc)) {
2504 0 => return out_buffer[0..@bitCast(usize, rc)],
2505 EACCES => return error.AccessDenied,
2506 EFAULT => unreachable,
2507 EINVAL => unreachable,
2508 EIO => return error.FileSystem,
2509 ELOOP => return error.SymLinkLoop,
2510 ENAMETOOLONG => return error.NameTooLong,
2511 ENOENT => return error.FileNotFound,
2512 ENOMEM => return error.SystemResources,
2513 ENOTDIR => return error.NotDir,
2500 .SUCCESS => return out_buffer[0..@bitCast(usize, rc)],
2501 .ACCES => return error.AccessDenied,
2502 .FAULT => unreachable,
2503 .INVAL => unreachable,
2504 .IO => return error.FileSystem,
2505 .LOOP => return error.SymLinkLoop,
2506 .NAMETOOLONG => return error.NameTooLong,
2507 .NOENT => return error.FileNotFound,
2508 .NOMEM => return error.SystemResources,
2509 .NOTDIR => return error.NotDir,
25142510 else => |err| return unexpectedErrno(err),
25152511 }
25162512}
......@@ -2537,17 +2533,17 @@ pub const readlinkatC = @compileError("deprecated: renamed to readlinkatZ");
25372533pub fn readlinkatWasi(dirfd: fd_t, file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {
25382534 var bufused: usize = undefined;
25392535 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],
2541 wasi.EACCES => return error.AccessDenied,
2542 wasi.EFAULT => unreachable,
2543 wasi.EINVAL => unreachable,
2544 wasi.EIO => return error.FileSystem,
2545 wasi.ELOOP => return error.SymLinkLoop,
2546 wasi.ENAMETOOLONG => return error.NameTooLong,
2547 wasi.ENOENT => return error.FileNotFound,
2548 wasi.ENOMEM => return error.SystemResources,
2549 wasi.ENOTDIR => return error.NotDir,
2550 wasi.ENOTCAPABLE => return error.AccessDenied,
2536 .SUCCESS => return out_buffer[0..bufused],
2537 .ACCES => return error.AccessDenied,
2538 .FAULT => unreachable,
2539 .INVAL => unreachable,
2540 .IO => return error.FileSystem,
2541 .LOOP => return error.SymLinkLoop,
2542 .NAMETOOLONG => return error.NameTooLong,
2543 .NOENT => return error.FileNotFound,
2544 .NOMEM => return error.SystemResources,
2545 .NOTDIR => return error.NotDir,
2546 .NOTCAPABLE => return error.AccessDenied,
25512547 else => |err| return unexpectedErrno(err),
25522548 }
25532549}
......@@ -2567,16 +2563,16 @@ pub fn readlinkatZ(dirfd: fd_t, file_path: [*:0]const u8, out_buffer: []u8) Read
25672563 }
25682564 const rc = system.readlinkat(dirfd, file_path, out_buffer.ptr, out_buffer.len);
25692565 switch (errno(rc)) {
2570 0 => return out_buffer[0..@bitCast(usize, rc)],
2571 EACCES => return error.AccessDenied,
2572 EFAULT => unreachable,
2573 EINVAL => unreachable,
2574 EIO => return error.FileSystem,
2575 ELOOP => return error.SymLinkLoop,
2576 ENAMETOOLONG => return error.NameTooLong,
2577 ENOENT => return error.FileNotFound,
2578 ENOMEM => return error.SystemResources,
2579 ENOTDIR => return error.NotDir,
2566 .SUCCESS => return out_buffer[0..@bitCast(usize, rc)],
2567 .ACCES => return error.AccessDenied,
2568 .FAULT => unreachable,
2569 .INVAL => unreachable,
2570 .IO => return error.FileSystem,
2571 .LOOP => return error.SymLinkLoop,
2572 .NAMETOOLONG => return error.NameTooLong,
2573 .NOENT => return error.FileNotFound,
2574 .NOMEM => return error.SystemResources,
2575 .NOTDIR => return error.NotDir,
25802576 else => |err| return unexpectedErrno(err),
25812577 }
25822578}
......@@ -2590,58 +2586,58 @@ pub const SetIdError = error{ResourceLimitReached} || SetEidError;
25902586
25912587pub fn setuid(uid: uid_t) SetIdError!void {
25922588 switch (errno(system.setuid(uid))) {
2593 0 => return,
2594 EAGAIN => return error.ResourceLimitReached,
2595 EINVAL => return error.InvalidUserId,
2596 EPERM => return error.PermissionDenied,
2589 .SUCCESS => return,
2590 .AGAIN => return error.ResourceLimitReached,
2591 .INVAL => return error.InvalidUserId,
2592 .PERM => return error.PermissionDenied,
25972593 else => |err| return unexpectedErrno(err),
25982594 }
25992595}
26002596
26012597pub fn seteuid(uid: uid_t) SetEidError!void {
26022598 switch (errno(system.seteuid(uid))) {
2603 0 => return,
2604 EINVAL => return error.InvalidUserId,
2605 EPERM => return error.PermissionDenied,
2599 .SUCCESS => return,
2600 .INVAL => return error.InvalidUserId,
2601 .PERM => return error.PermissionDenied,
26062602 else => |err| return unexpectedErrno(err),
26072603 }
26082604}
26092605
26102606pub fn setreuid(ruid: uid_t, euid: uid_t) SetIdError!void {
26112607 switch (errno(system.setreuid(ruid, euid))) {
2612 0 => return,
2613 EAGAIN => return error.ResourceLimitReached,
2614 EINVAL => return error.InvalidUserId,
2615 EPERM => return error.PermissionDenied,
2608 .SUCCESS => return,
2609 .AGAIN => return error.ResourceLimitReached,
2610 .INVAL => return error.InvalidUserId,
2611 .PERM => return error.PermissionDenied,
26162612 else => |err| return unexpectedErrno(err),
26172613 }
26182614}
26192615
26202616pub fn setgid(gid: gid_t) SetIdError!void {
26212617 switch (errno(system.setgid(gid))) {
2622 0 => return,
2623 EAGAIN => return error.ResourceLimitReached,
2624 EINVAL => return error.InvalidUserId,
2625 EPERM => return error.PermissionDenied,
2618 .SUCCESS => return,
2619 .AGAIN => return error.ResourceLimitReached,
2620 .INVAL => return error.InvalidUserId,
2621 .PERM => return error.PermissionDenied,
26262622 else => |err| return unexpectedErrno(err),
26272623 }
26282624}
26292625
26302626pub fn setegid(uid: uid_t) SetEidError!void {
26312627 switch (errno(system.setegid(uid))) {
2632 0 => return,
2633 EINVAL => return error.InvalidUserId,
2634 EPERM => return error.PermissionDenied,
2628 .SUCCESS => return,
2629 .INVAL => return error.InvalidUserId,
2630 .PERM => return error.PermissionDenied,
26352631 else => |err| return unexpectedErrno(err),
26362632 }
26372633}
26382634
26392635pub fn setregid(rgid: gid_t, egid: gid_t) SetIdError!void {
26402636 switch (errno(system.setregid(rgid, egid))) {
2641 0 => return,
2642 EAGAIN => return error.ResourceLimitReached,
2643 EINVAL => return error.InvalidUserId,
2644 EPERM => return error.PermissionDenied,
2637 .SUCCESS => return,
2638 .AGAIN => return error.ResourceLimitReached,
2639 .INVAL => return error.InvalidUserId,
2640 .PERM => return error.PermissionDenied,
26452641 else => |err| return unexpectedErrno(err),
26462642 }
26472643}
......@@ -2680,9 +2676,10 @@ pub fn isatty(handle: fd_t) bool {
26802676 while (true) {
26812677 var wsz: linux.winsize = undefined;
26822678 const fd = @bitCast(usize, @as(isize, handle));
2683 switch (linux.syscall3(.ioctl, fd, linux.TIOCGWINSZ, @ptrToInt(&wsz))) {
2684 0 => return true,
2685 EINTR => continue,
2679 const rc = linux.syscall3(.ioctl, fd, linux.TIOCGWINSZ, @ptrToInt(&wsz));
2680 switch (linux.getErrno(rc)) {
2681 .SUCCESS => return true,
2682 .INTR => continue,
26862683 else => return false,
26872684 }
26882685 }
......@@ -2777,22 +2774,22 @@ pub fn socket(domain: u32, socket_type: u32, protocol: u32) SocketError!socket_t
27772774 socket_type;
27782775 const rc = system.socket(domain, filtered_sock_type, protocol);
27792776 switch (errno(rc)) {
2780 0 => {
2777 .SUCCESS => {
27812778 const fd = @intCast(fd_t, rc);
27822779 if (!have_sock_flags) {
27832780 try setSockFlags(fd, socket_type);
27842781 }
27852782 return fd;
27862783 },
2787 EACCES => return error.PermissionDenied,
2788 EAFNOSUPPORT => return error.AddressFamilyNotSupported,
2789 EINVAL => return error.ProtocolFamilyNotAvailable,
2790 EMFILE => return error.ProcessFdQuotaExceeded,
2791 ENFILE => return error.SystemFdQuotaExceeded,
2792 ENOBUFS => return error.SystemResources,
2793 ENOMEM => return error.SystemResources,
2794 EPROTONOSUPPORT => return error.ProtocolNotSupported,
2795 EPROTOTYPE => return error.SocketTypeNotSupported,
2784 .ACCES => return error.PermissionDenied,
2785 .AFNOSUPPORT => return error.AddressFamilyNotSupported,
2786 .INVAL => return error.ProtocolFamilyNotAvailable,
2787 .MFILE => return error.ProcessFdQuotaExceeded,
2788 .NFILE => return error.SystemFdQuotaExceeded,
2789 .NOBUFS => return error.SystemResources,
2790 .NOMEM => return error.SystemResources,
2791 .PROTONOSUPPORT => return error.ProtocolNotSupported,
2792 .PROTOTYPE => return error.SocketTypeNotSupported,
27962793 else => |err| return unexpectedErrno(err),
27972794 }
27982795}
......@@ -2840,12 +2837,12 @@ pub fn shutdown(sock: socket_t, how: ShutdownHow) ShutdownError!void {
28402837 .both => SHUT_RDWR,
28412838 });
28422839 switch (errno(rc)) {
2843 0 => return,
2844 EBADF => unreachable,
2845 EINVAL => unreachable,
2846 ENOTCONN => return error.SocketNotConnected,
2847 ENOTSOCK => unreachable,
2848 ENOBUFS => return error.SystemResources,
2840 .SUCCESS => return,
2841 .BADF => unreachable,
2842 .INVAL => unreachable,
2843 .NOTCONN => return error.SocketNotConnected,
2844 .NOTSOCK => unreachable,
2845 .NOBUFS => return error.SystemResources,
28492846 else => |err| return unexpectedErrno(err),
28502847 }
28512848 }
......@@ -2924,20 +2921,20 @@ pub fn bind(sock: socket_t, addr: *const sockaddr, len: socklen_t) BindError!voi
29242921 } else {
29252922 const rc = system.bind(sock, addr, len);
29262923 switch (errno(rc)) {
2927 0 => return,
2928 EACCES => return error.AccessDenied,
2929 EADDRINUSE => return error.AddressInUse,
2930 EBADF => unreachable, // always a race condition if this error is returned
2931 EINVAL => unreachable, // invalid parameters
2932 ENOTSOCK => unreachable, // invalid `sockfd`
2933 EADDRNOTAVAIL => return error.AddressNotAvailable,
2934 EFAULT => unreachable, // invalid `addr` pointer
2935 ELOOP => return error.SymLinkLoop,
2936 ENAMETOOLONG => return error.NameTooLong,
2937 ENOENT => return error.FileNotFound,
2938 ENOMEM => return error.SystemResources,
2939 ENOTDIR => return error.NotDir,
2940 EROFS => return error.ReadOnlyFileSystem,
2924 .SUCCESS => return,
2925 .ACCES => return error.AccessDenied,
2926 .ADDRINUSE => return error.AddressInUse,
2927 .BADF => unreachable, // always a race condition if this error is returned
2928 .INVAL => unreachable, // invalid parameters
2929 .NOTSOCK => unreachable, // invalid `sockfd`
2930 .ADDRNOTAVAIL => return error.AddressNotAvailable,
2931 .FAULT => unreachable, // invalid `addr` pointer
2932 .LOOP => return error.SymLinkLoop,
2933 .NAMETOOLONG => return error.NameTooLong,
2934 .NOENT => return error.FileNotFound,
2935 .NOMEM => return error.SystemResources,
2936 .NOTDIR => return error.NotDir,
2937 .ROFS => return error.ReadOnlyFileSystem,
29412938 else => |err| return unexpectedErrno(err),
29422939 }
29432940 }
......@@ -2993,11 +2990,11 @@ pub fn listen(sock: socket_t, backlog: u31) ListenError!void {
29932990 } else {
29942991 const rc = system.listen(sock, backlog);
29952992 switch (errno(rc)) {
2996 0 => return,
2997 EADDRINUSE => return error.AddressInUse,
2998 EBADF => unreachable,
2999 ENOTSOCK => return error.FileDescriptorNotASocket,
3000 EOPNOTSUPP => return error.OperationNotSupported,
2993 .SUCCESS => return,
2994 .ADDRINUSE => return error.AddressInUse,
2995 .BADF => unreachable,
2996 .NOTSOCK => return error.FileDescriptorNotASocket,
2997 .OPNOTSUPP => return error.OperationNotSupported,
30012998 else => |err| return unexpectedErrno(err),
30022999 }
30033000 }
......@@ -3099,23 +3096,23 @@ pub fn accept(
30993096 }
31003097 } else {
31013098 switch (errno(rc)) {
3102 0 => {
3099 .SUCCESS => {
31033100 break @intCast(socket_t, rc);
31043101 },
3105 EINTR => continue,
3106 EAGAIN => return error.WouldBlock,
3107 EBADF => unreachable, // always a race condition
3108 ECONNABORTED => return error.ConnectionAborted,
3109 EFAULT => unreachable,
3110 EINVAL => return error.SocketNotListening,
3111 ENOTSOCK => unreachable,
3112 EMFILE => return error.ProcessFdQuotaExceeded,
3113 ENFILE => return error.SystemFdQuotaExceeded,
3114 ENOBUFS => return error.SystemResources,
3115 ENOMEM => return error.SystemResources,
3116 EOPNOTSUPP => unreachable,
3117 EPROTO => return error.ProtocolFailure,
3118 EPERM => return error.BlockedByFirewall,
3102 .INTR => continue,
3103 .AGAIN => return error.WouldBlock,
3104 .BADF => unreachable, // always a race condition
3105 .CONNABORTED => return error.ConnectionAborted,
3106 .FAULT => unreachable,
3107 .INVAL => return error.SocketNotListening,
3108 .NOTSOCK => unreachable,
3109 .MFILE => return error.ProcessFdQuotaExceeded,
3110 .NFILE => return error.SystemFdQuotaExceeded,
3111 .NOBUFS => return error.SystemResources,
3112 .NOMEM => return error.SystemResources,
3113 .OPNOTSUPP => unreachable,
3114 .PROTO => return error.ProtocolFailure,
3115 .PERM => return error.BlockedByFirewall,
31193116 else => |err| return unexpectedErrno(err),
31203117 }
31213118 }
......@@ -3144,13 +3141,13 @@ pub const EpollCreateError = error{
31443141pub fn epoll_create1(flags: u32) EpollCreateError!i32 {
31453142 const rc = system.epoll_create1(flags);
31463143 switch (errno(rc)) {
3147 0 => return @intCast(i32, rc),
3144 .SUCCESS => return @intCast(i32, rc),
31483145 else => |err| return unexpectedErrno(err),
31493146
3150 EINVAL => unreachable,
3151 EMFILE => return error.ProcessFdQuotaExceeded,
3152 ENFILE => return error.SystemFdQuotaExceeded,
3153 ENOMEM => return error.SystemResources,
3147 .INVAL => unreachable,
3148 .MFILE => return error.ProcessFdQuotaExceeded,
3149 .NFILE => return error.SystemFdQuotaExceeded,
3150 .NOMEM => return error.SystemResources,
31543151 }
31553152}
31563153
......@@ -3183,17 +3180,17 @@ pub const EpollCtlError = error{
31833180pub fn epoll_ctl(epfd: i32, op: u32, fd: i32, event: ?*epoll_event) EpollCtlError!void {
31843181 const rc = system.epoll_ctl(epfd, op, fd, event);
31853182 switch (errno(rc)) {
3186 0 => return,
3183 .SUCCESS => return,
31873184 else => |err| return unexpectedErrno(err),
31883185
3189 EBADF => unreachable, // always a race condition if this happens
3190 EEXIST => return error.FileDescriptorAlreadyPresentInSet,
3191 EINVAL => unreachable,
3192 ELOOP => return error.OperationCausesCircularLoop,
3193 ENOENT => return error.FileDescriptorNotRegistered,
3194 ENOMEM => return error.SystemResources,
3195 ENOSPC => return error.UserResourceLimitReached,
3196 EPERM => return error.FileDescriptorIncompatibleWithEpoll,
3186 .BADF => unreachable, // always a race condition if this happens
3187 .EXIST => return error.FileDescriptorAlreadyPresentInSet,
3188 .INVAL => unreachable,
3189 .LOOP => return error.OperationCausesCircularLoop,
3190 .NOENT => return error.FileDescriptorNotRegistered,
3191 .NOMEM => return error.SystemResources,
3192 .NOSPC => return error.UserResourceLimitReached,
3193 .PERM => return error.FileDescriptorIncompatibleWithEpoll,
31973194 }
31983195}
31993196
......@@ -3205,11 +3202,11 @@ pub fn epoll_wait(epfd: i32, events: []epoll_event, timeout: i32) usize {
32053202 // TODO get rid of the @intCast
32063203 const rc = system.epoll_wait(epfd, events.ptr, @intCast(u32, events.len), timeout);
32073204 switch (errno(rc)) {
3208 0 => return @intCast(usize, rc),
3209 EINTR => continue,
3210 EBADF => unreachable,
3211 EFAULT => unreachable,
3212 EINVAL => unreachable,
3205 .SUCCESS => return @intCast(usize, rc),
3206 .INTR => continue,
3207 .BADF => unreachable,
3208 .FAULT => unreachable,
3209 .INVAL => unreachable,
32133210 else => unreachable,
32143211 }
32153212 }
......@@ -3224,14 +3221,14 @@ pub const EventFdError = error{
32243221pub fn eventfd(initval: u32, flags: u32) EventFdError!i32 {
32253222 const rc = system.eventfd(initval, flags);
32263223 switch (errno(rc)) {
3227 0 => return @intCast(i32, rc),
3224 .SUCCESS => return @intCast(i32, rc),
32283225 else => |err| return unexpectedErrno(err),
32293226
3230 EINVAL => unreachable, // invalid parameters
3231 EMFILE => return error.ProcessFdQuotaExceeded,
3232 ENFILE => return error.SystemFdQuotaExceeded,
3233 ENODEV => return error.SystemResources,
3234 ENOMEM => return error.SystemResources,
3227 .INVAL => unreachable, // invalid parameters
3228 .MFILE => return error.ProcessFdQuotaExceeded,
3229 .NFILE => return error.SystemFdQuotaExceeded,
3230 .NODEV => return error.SystemResources,
3231 .NOMEM => return error.SystemResources,
32353232 }
32363233}
32373234
......@@ -3265,14 +3262,14 @@ pub fn getsockname(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock
32653262 } else {
32663263 const rc = system.getsockname(sock, addr, addrlen);
32673264 switch (errno(rc)) {
3268 0 => return,
3265 .SUCCESS => return,
32693266 else => |err| return unexpectedErrno(err),
32703267
3271 EBADF => unreachable, // always a race condition
3272 EFAULT => unreachable,
3273 EINVAL => unreachable, // invalid parameters
3274 ENOTSOCK => return error.FileDescriptorNotASocket,
3275 ENOBUFS => return error.SystemResources,
3268 .BADF => unreachable, // always a race condition
3269 .FAULT => unreachable,
3270 .INVAL => unreachable, // invalid parameters
3271 .NOTSOCK => return error.FileDescriptorNotASocket,
3272 .NOBUFS => return error.SystemResources,
32763273 }
32773274 }
32783275}
......@@ -3294,14 +3291,14 @@ pub fn getpeername(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSock
32943291 } else {
32953292 const rc = system.getpeername(sock, addr, addrlen);
32963293 switch (errno(rc)) {
3297 0 => return,
3294 .SUCCESS => return,
32983295 else => |err| return unexpectedErrno(err),
32993296
3300 EBADF => unreachable, // always a race condition
3301 EFAULT => unreachable,
3302 EINVAL => unreachable, // invalid parameters
3303 ENOTSOCK => return error.FileDescriptorNotASocket,
3304 ENOBUFS => return error.SystemResources,
3297 .BADF => unreachable, // always a race condition
3298 .FAULT => unreachable,
3299 .INVAL => unreachable, // invalid parameters
3300 .NOTSOCK => return error.FileDescriptorNotASocket,
3301 .NOBUFS => return error.SystemResources,
33053302 }
33063303 }
33073304}
......@@ -3384,61 +3381,61 @@ pub fn connect(sock: socket_t, sock_addr: *const sockaddr, len: socklen_t) Conne
33843381
33853382 while (true) {
33863383 switch (errno(system.connect(sock, sock_addr, len))) {
3387 0 => return,
3388 EACCES => return error.PermissionDenied,
3389 EPERM => return error.PermissionDenied,
3390 EADDRINUSE => return error.AddressInUse,
3391 EADDRNOTAVAIL => return error.AddressNotAvailable,
3392 EAFNOSUPPORT => return error.AddressFamilyNotSupported,
3393 EAGAIN, EINPROGRESS => return error.WouldBlock,
3394 EALREADY => return error.ConnectionPending,
3395 EBADF => unreachable, // sockfd is not a valid open file descriptor.
3396 ECONNREFUSED => return error.ConnectionRefused,
3397 ECONNRESET => return error.ConnectionResetByPeer,
3398 EFAULT => unreachable, // The socket structure address is outside the user's address space.
3399 EINTR => continue,
3400 EISCONN => unreachable, // The socket is already connected.
3401 ENETUNREACH => return error.NetworkUnreachable,
3402 ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
3403 EPROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
3404 ETIMEDOUT => return error.ConnectionTimedOut,
3405 ENOENT => return error.FileNotFound, // Returned when socket is AF_UNIX and the given path does not exist.
3384 .SUCCESS => return,
3385 .ACCES => return error.PermissionDenied,
3386 .PERM => return error.PermissionDenied,
3387 .ADDRINUSE => return error.AddressInUse,
3388 .ADDRNOTAVAIL => return error.AddressNotAvailable,
3389 .AFNOSUPPORT => return error.AddressFamilyNotSupported,
3390 .AGAIN, .INPROGRESS => return error.WouldBlock,
3391 .ALREADY => return error.ConnectionPending,
3392 .BADF => unreachable, // sockfd is not a valid open file descriptor.
3393 .CONNREFUSED => return error.ConnectionRefused,
3394 .CONNRESET => return error.ConnectionResetByPeer,
3395 .FAULT => unreachable, // The socket structure address is outside the user's address space.
3396 .INTR => continue,
3397 .ISCONN => unreachable, // The socket is already connected.
3398 .NETUNREACH => return error.NetworkUnreachable,
3399 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
3400 .PROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
3401 .TIMEDOUT => return error.ConnectionTimedOut,
3402 .NOENT => return error.FileNotFound, // Returned when socket is AF_UNIX and the given path does not exist.
34063403 else => |err| return unexpectedErrno(err),
34073404 }
34083405 }
34093406}
34103407
34113408pub fn getsockoptError(sockfd: fd_t) ConnectError!void {
3412 var err_code: u32 = undefined;
3409 var err_code: i32 = undefined;
34133410 var size: u32 = @sizeOf(u32);
34143411 const rc = system.getsockopt(sockfd, SOL_SOCKET, SO_ERROR, @ptrCast([*]u8, &err_code), &size);
34153412 assert(size == 4);
34163413 switch (errno(rc)) {
3417 0 => switch (err_code) {
3418 0 => return,
3419 EACCES => return error.PermissionDenied,
3420 EPERM => return error.PermissionDenied,
3421 EADDRINUSE => return error.AddressInUse,
3422 EADDRNOTAVAIL => return error.AddressNotAvailable,
3423 EAFNOSUPPORT => return error.AddressFamilyNotSupported,
3424 EAGAIN => return error.SystemResources,
3425 EALREADY => return error.ConnectionPending,
3426 EBADF => unreachable, // sockfd is not a valid open file descriptor.
3427 ECONNREFUSED => return error.ConnectionRefused,
3428 EFAULT => unreachable, // The socket structure address is outside the user's address space.
3429 EISCONN => unreachable, // The socket is already connected.
3430 ENETUNREACH => return error.NetworkUnreachable,
3431 ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
3432 EPROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
3433 ETIMEDOUT => return error.ConnectionTimedOut,
3434 ECONNRESET => return error.ConnectionResetByPeer,
3414 .SUCCESS => switch (@intToEnum(E, err_code)) {
3415 .SUCCESS => return,
3416 .ACCES => return error.PermissionDenied,
3417 .PERM => return error.PermissionDenied,
3418 .ADDRINUSE => return error.AddressInUse,
3419 .ADDRNOTAVAIL => return error.AddressNotAvailable,
3420 .AFNOSUPPORT => return error.AddressFamilyNotSupported,
3421 .AGAIN => return error.SystemResources,
3422 .ALREADY => return error.ConnectionPending,
3423 .BADF => unreachable, // sockfd is not a valid open file descriptor.
3424 .CONNREFUSED => return error.ConnectionRefused,
3425 .FAULT => unreachable, // The socket structure address is outside the user's address space.
3426 .ISCONN => unreachable, // The socket is already connected.
3427 .NETUNREACH => return error.NetworkUnreachable,
3428 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
3429 .PROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
3430 .TIMEDOUT => return error.ConnectionTimedOut,
3431 .CONNRESET => return error.ConnectionResetByPeer,
34353432 else => |err| return unexpectedErrno(err),
34363433 },
3437 EBADF => 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.
3439 EINVAL => unreachable,
3440 ENOPROTOOPT => unreachable, // The option is unknown at the level indicated.
3441 ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
3434 .BADF => unreachable, // The argument sockfd is not a valid file descriptor.
3435 .FAULT => unreachable, // The address pointed to by optval or optlen is not in a valid part of the process address space.
3436 .INVAL => unreachable,
3437 .NOPROTOOPT => unreachable, // The option is unknown at the level indicated.
3438 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
34423439 else => |err| return unexpectedErrno(err),
34433440 }
34443441}
......@@ -3454,13 +3451,13 @@ pub fn waitpid(pid: pid_t, flags: u32) WaitPidResult {
34543451 while (true) {
34553452 const rc = system.waitpid(pid, &status, if (builtin.link_libc) @intCast(c_int, flags) else flags);
34563453 switch (errno(rc)) {
3457 0 => return .{
3454 .SUCCESS => return .{
34583455 .pid = @intCast(pid_t, rc),
34593456 .status = @bitCast(u32, status),
34603457 },
3461 EINTR => continue,
3462 ECHILD => unreachable, // The process specified does not exist. It would be a race condition to handle this error.
3463 EINVAL => unreachable, // Invalid flags.
3458 .INTR => continue,
3459 .CHILD => unreachable, // The process specified does not exist. It would be a race condition to handle this error.
3460 .INVAL => unreachable, // Invalid flags.
34643461 else => unreachable,
34653462 }
34663463 }
......@@ -3484,12 +3481,12 @@ pub fn fstat(fd: fd_t) FStatError!Stat {
34843481 if (builtin.os.tag == .wasi and !builtin.link_libc) {
34853482 var stat: wasi.filestat_t = undefined;
34863483 switch (wasi.fd_filestat_get(fd, &stat)) {
3487 wasi.ESUCCESS => return Stat.fromFilestat(stat),
3488 wasi.EINVAL => unreachable,
3489 wasi.EBADF => unreachable, // Always a race condition.
3490 wasi.ENOMEM => return error.SystemResources,
3491 wasi.EACCES => return error.AccessDenied,
3492 wasi.ENOTCAPABLE => return error.AccessDenied,
3484 .SUCCESS => return Stat.fromFilestat(stat),
3485 .INVAL => unreachable,
3486 .BADF => unreachable, // Always a race condition.
3487 .NOMEM => return error.SystemResources,
3488 .ACCES => return error.AccessDenied,
3489 .NOTCAPABLE => return error.AccessDenied,
34933490 else => |err| return unexpectedErrno(err),
34943491 }
34953492 }
......@@ -3504,11 +3501,11 @@ pub fn fstat(fd: fd_t) FStatError!Stat {
35043501
35053502 var stat = mem.zeroes(Stat);
35063503 switch (errno(fstat_sym(fd, &stat))) {
3507 0 => return stat,
3508 EINVAL => unreachable,
3509 EBADF => unreachable, // Always a race condition.
3510 ENOMEM => return error.SystemResources,
3511 EACCES => return error.AccessDenied,
3504 .SUCCESS => return stat,
3505 .INVAL => unreachable,
3506 .BADF => unreachable, // Always a race condition.
3507 .NOMEM => return error.SystemResources,
3508 .ACCES => return error.AccessDenied,
35123509 else => |err| return unexpectedErrno(err),
35133510 }
35143511}
......@@ -3536,16 +3533,16 @@ pub const fstatatC = @compileError("deprecated: renamed to fstatatZ");
35363533pub fn fstatatWasi(dirfd: fd_t, pathname: []const u8, flags: u32) FStatAtError!Stat {
35373534 var stat: wasi.filestat_t = undefined;
35383535 switch (wasi.path_filestat_get(dirfd, flags, pathname.ptr, pathname.len, &stat)) {
3539 wasi.ESUCCESS => return Stat.fromFilestat(stat),
3540 wasi.EINVAL => unreachable,
3541 wasi.EBADF => unreachable, // Always a race condition.
3542 wasi.ENOMEM => return error.SystemResources,
3543 wasi.EACCES => return error.AccessDenied,
3544 wasi.EFAULT => unreachable,
3545 wasi.ENAMETOOLONG => return error.NameTooLong,
3546 wasi.ENOENT => return error.FileNotFound,
3547 wasi.ENOTDIR => return error.FileNotFound,
3548 wasi.ENOTCAPABLE => return error.AccessDenied,
3536 .SUCCESS => return Stat.fromFilestat(stat),
3537 .INVAL => unreachable,
3538 .BADF => unreachable, // Always a race condition.
3539 .NOMEM => return error.SystemResources,
3540 .ACCES => return error.AccessDenied,
3541 .FAULT => unreachable,
3542 .NAMETOOLONG => return error.NameTooLong,
3543 .NOENT => return error.FileNotFound,
3544 .NOTDIR => return error.FileNotFound,
3545 .NOTCAPABLE => return error.AccessDenied,
35493546 else => |err| return unexpectedErrno(err),
35503547 }
35513548}
......@@ -3560,17 +3557,17 @@ pub fn fstatatZ(dirfd: fd_t, pathname: [*:0]const u8, flags: u32) FStatAtError!S
35603557
35613558 var stat = mem.zeroes(Stat);
35623559 switch (errno(fstatat_sym(dirfd, pathname, &stat, flags))) {
3563 0 => return stat,
3564 EINVAL => unreachable,
3565 EBADF => unreachable, // Always a race condition.
3566 ENOMEM => return error.SystemResources,
3567 EACCES => return error.AccessDenied,
3568 EPERM => return error.AccessDenied,
3569 EFAULT => unreachable,
3570 ENAMETOOLONG => return error.NameTooLong,
3571 ELOOP => return error.SymLinkLoop,
3572 ENOENT => return error.FileNotFound,
3573 ENOTDIR => return error.FileNotFound,
3560 .SUCCESS => return stat,
3561 .INVAL => unreachable,
3562 .BADF => unreachable, // Always a race condition.
3563 .NOMEM => return error.SystemResources,
3564 .ACCES => return error.AccessDenied,
3565 .PERM => return error.AccessDenied,
3566 .FAULT => unreachable,
3567 .NAMETOOLONG => return error.NameTooLong,
3568 .LOOP => return error.SymLinkLoop,
3569 .NOENT => return error.FileNotFound,
3570 .NOTDIR => return error.FileNotFound,
35743571 else => |err| return unexpectedErrno(err),
35753572 }
35763573}
......@@ -3586,9 +3583,9 @@ pub const KQueueError = error{
35863583pub fn kqueue() KQueueError!i32 {
35873584 const rc = system.kqueue();
35883585 switch (errno(rc)) {
3589 0 => return @intCast(i32, rc),
3590 EMFILE => return error.ProcessFdQuotaExceeded,
3591 ENFILE => return error.SystemFdQuotaExceeded,
3586 .SUCCESS => return @intCast(i32, rc),
3587 .MFILE => return error.ProcessFdQuotaExceeded,
3588 .NFILE => return error.SystemFdQuotaExceeded,
35923589 else => |err| return unexpectedErrno(err),
35933590 }
35943591}
......@@ -3627,15 +3624,15 @@ pub fn kevent(
36273624 timeout,
36283625 );
36293626 switch (errno(rc)) {
3630 0 => return @intCast(usize, rc),
3631 EACCES => return error.AccessDenied,
3632 EFAULT => unreachable,
3633 EBADF => unreachable, // Always a race condition.
3634 EINTR => continue,
3635 EINVAL => unreachable,
3636 ENOENT => return error.EventNotFound,
3637 ENOMEM => return error.SystemResources,
3638 ESRCH => return error.ProcessNotFound,
3627 .SUCCESS => return @intCast(usize, rc),
3628 .ACCES => return error.AccessDenied,
3629 .FAULT => unreachable,
3630 .BADF => unreachable, // Always a race condition.
3631 .INTR => continue,
3632 .INVAL => unreachable,
3633 .NOENT => return error.EventNotFound,
3634 .NOMEM => return error.SystemResources,
3635 .SRCH => return error.ProcessNotFound,
36393636 else => unreachable,
36403637 }
36413638 }
......@@ -3651,11 +3648,11 @@ pub const INotifyInitError = error{
36513648pub fn inotify_init1(flags: u32) INotifyInitError!i32 {
36523649 const rc = system.inotify_init1(flags);
36533650 switch (errno(rc)) {
3654 0 => return @intCast(i32, rc),
3655 EINVAL => unreachable,
3656 EMFILE => return error.ProcessFdQuotaExceeded,
3657 ENFILE => return error.SystemFdQuotaExceeded,
3658 ENOMEM => return error.SystemResources,
3651 .SUCCESS => return @intCast(i32, rc),
3652 .INVAL => unreachable,
3653 .MFILE => return error.ProcessFdQuotaExceeded,
3654 .NFILE => return error.SystemFdQuotaExceeded,
3655 .NOMEM => return error.SystemResources,
36593656 else => |err| return unexpectedErrno(err),
36603657 }
36613658}
......@@ -3681,16 +3678,16 @@ pub const inotify_add_watchC = @compileError("deprecated: renamed to inotify_add
36813678pub fn inotify_add_watchZ(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) INotifyAddWatchError!i32 {
36823679 const rc = system.inotify_add_watch(inotify_fd, pathname, mask);
36833680 switch (errno(rc)) {
3684 0 => return @intCast(i32, rc),
3685 EACCES => return error.AccessDenied,
3686 EBADF => unreachable,
3687 EFAULT => unreachable,
3688 EINVAL => unreachable,
3689 ENAMETOOLONG => return error.NameTooLong,
3690 ENOENT => return error.FileNotFound,
3691 ENOMEM => return error.SystemResources,
3692 ENOSPC => return error.UserResourceLimitReached,
3693 ENOTDIR => return error.NotDir,
3681 .SUCCESS => return @intCast(i32, rc),
3682 .ACCES => return error.AccessDenied,
3683 .BADF => unreachable,
3684 .FAULT => unreachable,
3685 .INVAL => unreachable,
3686 .NAMETOOLONG => return error.NameTooLong,
3687 .NOENT => return error.FileNotFound,
3688 .NOMEM => return error.SystemResources,
3689 .NOSPC => return error.UserResourceLimitReached,
3690 .NOTDIR => return error.NotDir,
36943691 else => |err| return unexpectedErrno(err),
36953692 }
36963693}
......@@ -3698,9 +3695,9 @@ pub fn inotify_add_watchZ(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) I
36983695/// remove an existing watch from an inotify instance
36993696pub fn inotify_rm_watch(inotify_fd: i32, wd: i32) void {
37003697 switch (errno(system.inotify_rm_watch(inotify_fd, wd))) {
3701 0 => return,
3702 EBADF => unreachable,
3703 EINVAL => unreachable,
3698 .SUCCESS => return,
3699 .BADF => unreachable,
3700 .INVAL => unreachable,
37043701 else => unreachable,
37053702 }
37063703}
......@@ -3723,10 +3720,10 @@ pub const MProtectError = error{
37233720pub fn mprotect(memory: []align(mem.page_size) u8, protection: u32) MProtectError!void {
37243721 assert(mem.isAligned(memory.len, mem.page_size));
37253722 switch (errno(system.mprotect(memory.ptr, memory.len, protection))) {
3726 0 => return,
3727 EINVAL => unreachable,
3728 EACCES => return error.AccessDenied,
3729 ENOMEM => return error.OutOfMemory,
3723 .SUCCESS => return,
3724 .INVAL => unreachable,
3725 .ACCES => return error.AccessDenied,
3726 .NOMEM => return error.OutOfMemory,
37303727 else => |err| return unexpectedErrno(err),
37313728 }
37323729}
......@@ -3736,9 +3733,9 @@ pub const ForkError = error{SystemResources} || UnexpectedError;
37363733pub fn fork() ForkError!pid_t {
37373734 const rc = system.fork();
37383735 switch (errno(rc)) {
3739 0 => return @intCast(pid_t, rc),
3740 EAGAIN => return error.SystemResources,
3741 ENOMEM => return error.SystemResources,
3736 .SUCCESS => return @intCast(pid_t, rc),
3737 .AGAIN => return error.SystemResources,
3738 .NOMEM => return error.SystemResources,
37423739 else => |err| return unexpectedErrno(err),
37433740 }
37443741}
......@@ -3782,22 +3779,23 @@ pub fn mmap(
37823779 const rc = mmap_sym(ptr, length, prot, flags, fd, ioffset);
37833780 const err = if (builtin.link_libc) blk: {
37843781 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().*);
37863783 } else blk: {
37873784 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];
37893786 break :blk err;
37903787 };
37913788 switch (err) {
3792 ETXTBSY => return error.AccessDenied,
3793 EACCES => return error.AccessDenied,
3794 EPERM => return error.PermissionDenied,
3795 EAGAIN => return error.LockedMemoryLimitExceeded,
3796 EBADF => unreachable, // Always a race condition.
3797 EOVERFLOW => unreachable, // The number of pages used for length + offset would overflow.
3798 ENODEV => return error.MemoryMappingNotSupported,
3799 EINVAL => unreachable, // Invalid parameters to mmap()
3800 ENOMEM => return error.OutOfMemory,
3789 .SUCCESS => unreachable,
3790 .TXTBSY => return error.AccessDenied,
3791 .ACCES => return error.AccessDenied,
3792 .PERM => return error.PermissionDenied,
3793 .AGAIN => return error.LockedMemoryLimitExceeded,
3794 .BADF => unreachable, // Always a race condition.
3795 .OVERFLOW => unreachable, // The number of pages used for length + offset would overflow.
3796 .NODEV => return error.MemoryMappingNotSupported,
3797 .INVAL => unreachable, // Invalid parameters to mmap()
3798 .NOMEM => return error.OutOfMemory,
38013799 else => return unexpectedErrno(err),
38023800 }
38033801}
......@@ -3810,9 +3808,9 @@ pub fn mmap(
38103808/// * The Windows function, VirtualFree, has this restriction.
38113809pub fn munmap(memory: []align(mem.page_size) const u8) void {
38123810 switch (errno(system.munmap(memory.ptr, memory.len))) {
3813 0 => return,
3814 EINVAL => unreachable, // Invalid parameters.
3815 ENOMEM => unreachable, // Attempted to unmap a region in the middle of an existing mapping.
3811 .SUCCESS => return,
3812 .INVAL => unreachable, // Invalid parameters.
3813 .NOMEM => unreachable, // Attempted to unmap a region in the middle of an existing mapping.
38163814 else => unreachable,
38173815 }
38183816}
......@@ -3854,18 +3852,18 @@ pub fn accessZ(path: [*:0]const u8, mode: u32) AccessError!void {
38543852 return;
38553853 }
38563854 switch (errno(system.access(path, mode))) {
3857 0 => return,
3858 EACCES => return error.PermissionDenied,
3859 EROFS => return error.ReadOnlyFileSystem,
3860 ELOOP => return error.SymLinkLoop,
3861 ETXTBSY => return error.FileBusy,
3862 ENOTDIR => return error.FileNotFound,
3863 ENOENT => return error.FileNotFound,
3864 ENAMETOOLONG => return error.NameTooLong,
3865 EINVAL => unreachable,
3866 EFAULT => unreachable,
3867 EIO => return error.InputOutput,
3868 ENOMEM => return error.SystemResources,
3855 .SUCCESS => return,
3856 .ACCES => return error.PermissionDenied,
3857 .ROFS => return error.ReadOnlyFileSystem,
3858 .LOOP => return error.SymLinkLoop,
3859 .TXTBSY => return error.FileBusy,
3860 .NOTDIR => return error.FileNotFound,
3861 .NOENT => return error.FileNotFound,
3862 .NAMETOOLONG => return error.NameTooLong,
3863 .INVAL => unreachable,
3864 .FAULT => unreachable,
3865 .IO => return error.InputOutput,
3866 .NOMEM => return error.SystemResources,
38693867 else => |err| return unexpectedErrno(err),
38703868 }
38713869}
......@@ -3905,18 +3903,18 @@ pub fn faccessatZ(dirfd: fd_t, path: [*:0]const u8, mode: u32, flags: u32) Acces
39053903 return faccessatW(dirfd, path_w.span().ptr, mode, flags);
39063904 }
39073905 switch (errno(system.faccessat(dirfd, path, mode, flags))) {
3908 0 => return,
3909 EACCES => return error.PermissionDenied,
3910 EROFS => return error.ReadOnlyFileSystem,
3911 ELOOP => return error.SymLinkLoop,
3912 ETXTBSY => return error.FileBusy,
3913 ENOTDIR => return error.FileNotFound,
3914 ENOENT => return error.FileNotFound,
3915 ENAMETOOLONG => return error.NameTooLong,
3916 EINVAL => unreachable,
3917 EFAULT => unreachable,
3918 EIO => return error.InputOutput,
3919 ENOMEM => return error.SystemResources,
3906 .SUCCESS => return,
3907 .ACCES => return error.PermissionDenied,
3908 .ROFS => return error.ReadOnlyFileSystem,
3909 .LOOP => return error.SymLinkLoop,
3910 .TXTBSY => return error.FileBusy,
3911 .NOTDIR => return error.FileNotFound,
3912 .NOENT => return error.FileNotFound,
3913 .NAMETOOLONG => return error.NameTooLong,
3914 .INVAL => unreachable,
3915 .FAULT => unreachable,
3916 .IO => return error.InputOutput,
3917 .NOMEM => return error.SystemResources,
39203918 else => |err| return unexpectedErrno(err),
39213919 }
39223920}
......@@ -3972,11 +3970,11 @@ pub const PipeError = error{
39723970pub fn pipe() PipeError![2]fd_t {
39733971 var fds: [2]fd_t = undefined;
39743972 switch (errno(system.pipe(&fds))) {
3975 0 => return fds,
3976 EINVAL => unreachable, // Invalid parameters to pipe()
3977 EFAULT => unreachable, // Invalid fds pointer
3978 ENFILE => return error.SystemFdQuotaExceeded,
3979 EMFILE => return error.ProcessFdQuotaExceeded,
3973 .SUCCESS => return fds,
3974 .INVAL => unreachable, // Invalid parameters to pipe()
3975 .FAULT => unreachable, // Invalid fds pointer
3976 .NFILE => return error.SystemFdQuotaExceeded,
3977 .MFILE => return error.ProcessFdQuotaExceeded,
39803978 else => |err| return unexpectedErrno(err),
39813979 }
39823980}
......@@ -3985,11 +3983,11 @@ pub fn pipe2(flags: u32) PipeError![2]fd_t {
39853983 if (@hasDecl(system, "pipe2")) {
39863984 var fds: [2]fd_t = undefined;
39873985 switch (errno(system.pipe2(&fds, flags))) {
3988 0 => return fds,
3989 EINVAL => unreachable, // Invalid flags
3990 EFAULT => unreachable, // Invalid fds pointer
3991 ENFILE => return error.SystemFdQuotaExceeded,
3992 EMFILE => return error.ProcessFdQuotaExceeded,
3986 .SUCCESS => return fds,
3987 .INVAL => unreachable, // Invalid flags
3988 .FAULT => unreachable, // Invalid fds pointer
3989 .NFILE => return error.SystemFdQuotaExceeded,
3990 .MFILE => return error.ProcessFdQuotaExceeded,
39933991 else => |err| return unexpectedErrno(err),
39943992 }
39953993 }
......@@ -4008,9 +4006,9 @@ pub fn pipe2(flags: u32) PipeError![2]fd_t {
40084006 if (flags & O_CLOEXEC != 0) {
40094007 for (fds) |fd| {
40104008 switch (errno(system.fcntl(fd, F_SETFD, @as(u32, FD_CLOEXEC)))) {
4011 0 => {},
4012 EINVAL => unreachable, // Invalid flags
4013 EBADF => unreachable, // Always a race condition
4009 .SUCCESS => {},
4010 .INVAL => unreachable, // Invalid flags
4011 .BADF => unreachable, // Always a race condition
40144012 else => |err| return unexpectedErrno(err),
40154013 }
40164014 }
......@@ -4021,9 +4019,9 @@ pub fn pipe2(flags: u32) PipeError![2]fd_t {
40214019 if (new_flags != 0) {
40224020 for (fds) |fd| {
40234021 switch (errno(system.fcntl(fd, F_SETFL, new_flags))) {
4024 0 => {},
4025 EINVAL => unreachable, // Invalid flags
4026 EBADF => unreachable, // Always a race condition
4022 .SUCCESS => {},
4023 .INVAL => unreachable, // Invalid flags
4024 .BADF => unreachable, // Always a race condition
40274025 else => |err| return unexpectedErrno(err),
40284026 }
40294027 }
......@@ -4055,11 +4053,11 @@ pub fn sysctl(
40554053
40564054 const name_len = math.cast(c_uint, name.len) catch return error.NameTooLong;
40574055 switch (errno(system.sysctl(name.ptr, name_len, oldp, oldlenp, newp, newlen))) {
4058 0 => return,
4059 EFAULT => unreachable,
4060 EPERM => return error.PermissionDenied,
4061 ENOMEM => return error.SystemResources,
4062 ENOENT => return error.UnknownName,
4056 .SUCCESS => return,
4057 .FAULT => unreachable,
4058 .PERM => return error.PermissionDenied,
4059 .NOMEM => return error.SystemResources,
4060 .NOENT => return error.UnknownName,
40634061 else => |err| return unexpectedErrno(err),
40644062 }
40654063}
......@@ -4081,19 +4079,19 @@ pub fn sysctlbynameZ(
40814079 }
40824080
40834081 switch (errno(system.sysctlbyname(name, oldp, oldlenp, newp, newlen))) {
4084 0 => return,
4085 EFAULT => unreachable,
4086 EPERM => return error.PermissionDenied,
4087 ENOMEM => return error.SystemResources,
4088 ENOENT => return error.UnknownName,
4082 .SUCCESS => return,
4083 .FAULT => unreachable,
4084 .PERM => return error.PermissionDenied,
4085 .NOMEM => return error.SystemResources,
4086 .NOENT => return error.UnknownName,
40894087 else => |err| return unexpectedErrno(err),
40904088 }
40914089}
40924090
40934091pub fn gettimeofday(tv: ?*timeval, tz: ?*timezone) void {
40944092 switch (errno(system.gettimeofday(tv, tz))) {
4095 0 => return,
4096 EINVAL => unreachable,
4093 .SUCCESS => return,
4094 .INVAL => unreachable,
40974095 else => unreachable,
40984096 }
40994097}
......@@ -4111,12 +4109,12 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
41114109 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
41124110 var result: u64 = undefined;
41134111 switch (errno(system.llseek(fd, offset, &result, SEEK_SET))) {
4114 0 => return,
4115 EBADF => unreachable, // always a race condition
4116 EINVAL => return error.Unseekable,
4117 EOVERFLOW => return error.Unseekable,
4118 ESPIPE => return error.Unseekable,
4119 ENXIO => return error.Unseekable,
4112 .SUCCESS => return,
4113 .BADF => unreachable, // always a race condition
4114 .INVAL => return error.Unseekable,
4115 .OVERFLOW => return error.Unseekable,
4116 .SPIPE => return error.Unseekable,
4117 .NXIO => return error.Unseekable,
41204118 else => |err| return unexpectedErrno(err),
41214119 }
41224120 }
......@@ -4126,13 +4124,13 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
41264124 if (builtin.os.tag == .wasi and !builtin.link_libc) {
41274125 var new_offset: wasi.filesize_t = undefined;
41284126 switch (wasi.fd_seek(fd, @bitCast(wasi.filedelta_t, offset), wasi.WHENCE_SET, &new_offset)) {
4129 wasi.ESUCCESS => return,
4130 wasi.EBADF => unreachable, // always a race condition
4131 wasi.EINVAL => return error.Unseekable,
4132 wasi.EOVERFLOW => return error.Unseekable,
4133 wasi.ESPIPE => return error.Unseekable,
4134 wasi.ENXIO => return error.Unseekable,
4135 wasi.ENOTCAPABLE => return error.AccessDenied,
4127 .SUCCESS => return,
4128 .BADF => unreachable, // always a race condition
4129 .INVAL => return error.Unseekable,
4130 .OVERFLOW => return error.Unseekable,
4131 .SPIPE => return error.Unseekable,
4132 .NXIO => return error.Unseekable,
4133 .NOTCAPABLE => return error.AccessDenied,
41364134 else => |err| return unexpectedErrno(err),
41374135 }
41384136 }
......@@ -4144,12 +4142,12 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
41444142
41454143 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned
41464144 switch (errno(lseek_sym(fd, ioffset, SEEK_SET))) {
4147 0 => return,
4148 EBADF => unreachable, // always a race condition
4149 EINVAL => return error.Unseekable,
4150 EOVERFLOW => return error.Unseekable,
4151 ESPIPE => return error.Unseekable,
4152 ENXIO => return error.Unseekable,
4145 .SUCCESS => return,
4146 .BADF => unreachable, // always a race condition
4147 .INVAL => return error.Unseekable,
4148 .OVERFLOW => return error.Unseekable,
4149 .SPIPE => return error.Unseekable,
4150 .NXIO => return error.Unseekable,
41534151 else => |err| return unexpectedErrno(err),
41544152 }
41554153}
......@@ -4159,12 +4157,12 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
41594157 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
41604158 var result: u64 = undefined;
41614159 switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_CUR))) {
4162 0 => return,
4163 EBADF => unreachable, // always a race condition
4164 EINVAL => return error.Unseekable,
4165 EOVERFLOW => return error.Unseekable,
4166 ESPIPE => return error.Unseekable,
4167 ENXIO => return error.Unseekable,
4160 .SUCCESS => return,
4161 .BADF => unreachable, // always a race condition
4162 .INVAL => return error.Unseekable,
4163 .OVERFLOW => return error.Unseekable,
4164 .SPIPE => return error.Unseekable,
4165 .NXIO => return error.Unseekable,
41684166 else => |err| return unexpectedErrno(err),
41694167 }
41704168 }
......@@ -4174,13 +4172,13 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
41744172 if (builtin.os.tag == .wasi and !builtin.link_libc) {
41754173 var new_offset: wasi.filesize_t = undefined;
41764174 switch (wasi.fd_seek(fd, offset, wasi.WHENCE_CUR, &new_offset)) {
4177 wasi.ESUCCESS => return,
4178 wasi.EBADF => unreachable, // always a race condition
4179 wasi.EINVAL => return error.Unseekable,
4180 wasi.EOVERFLOW => return error.Unseekable,
4181 wasi.ESPIPE => return error.Unseekable,
4182 wasi.ENXIO => return error.Unseekable,
4183 wasi.ENOTCAPABLE => return error.AccessDenied,
4175 .SUCCESS => return,
4176 .BADF => unreachable, // always a race condition
4177 .INVAL => return error.Unseekable,
4178 .OVERFLOW => return error.Unseekable,
4179 .SPIPE => return error.Unseekable,
4180 .NXIO => return error.Unseekable,
4181 .NOTCAPABLE => return error.AccessDenied,
41844182 else => |err| return unexpectedErrno(err),
41854183 }
41864184 }
......@@ -4191,12 +4189,12 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
41914189
41924190 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned
41934191 switch (errno(lseek_sym(fd, ioffset, SEEK_CUR))) {
4194 0 => return,
4195 EBADF => unreachable, // always a race condition
4196 EINVAL => return error.Unseekable,
4197 EOVERFLOW => return error.Unseekable,
4198 ESPIPE => return error.Unseekable,
4199 ENXIO => return error.Unseekable,
4192 .SUCCESS => return,
4193 .BADF => unreachable, // always a race condition
4194 .INVAL => return error.Unseekable,
4195 .OVERFLOW => return error.Unseekable,
4196 .SPIPE => return error.Unseekable,
4197 .NXIO => return error.Unseekable,
42004198 else => |err| return unexpectedErrno(err),
42014199 }
42024200}
......@@ -4206,12 +4204,12 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
42064204 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
42074205 var result: u64 = undefined;
42084206 switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_END))) {
4209 0 => return,
4210 EBADF => unreachable, // always a race condition
4211 EINVAL => return error.Unseekable,
4212 EOVERFLOW => return error.Unseekable,
4213 ESPIPE => return error.Unseekable,
4214 ENXIO => return error.Unseekable,
4207 .SUCCESS => return,
4208 .BADF => unreachable, // always a race condition
4209 .INVAL => return error.Unseekable,
4210 .OVERFLOW => return error.Unseekable,
4211 .SPIPE => return error.Unseekable,
4212 .NXIO => return error.Unseekable,
42154213 else => |err| return unexpectedErrno(err),
42164214 }
42174215 }
......@@ -4221,13 +4219,13 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
42214219 if (builtin.os.tag == .wasi and !builtin.link_libc) {
42224220 var new_offset: wasi.filesize_t = undefined;
42234221 switch (wasi.fd_seek(fd, offset, wasi.WHENCE_END, &new_offset)) {
4224 wasi.ESUCCESS => return,
4225 wasi.EBADF => unreachable, // always a race condition
4226 wasi.EINVAL => return error.Unseekable,
4227 wasi.EOVERFLOW => return error.Unseekable,
4228 wasi.ESPIPE => return error.Unseekable,
4229 wasi.ENXIO => return error.Unseekable,
4230 wasi.ENOTCAPABLE => return error.AccessDenied,
4222 .SUCCESS => return,
4223 .BADF => unreachable, // always a race condition
4224 .INVAL => return error.Unseekable,
4225 .OVERFLOW => return error.Unseekable,
4226 .SPIPE => return error.Unseekable,
4227 .NXIO => return error.Unseekable,
4228 .NOTCAPABLE => return error.AccessDenied,
42314229 else => |err| return unexpectedErrno(err),
42324230 }
42334231 }
......@@ -4238,12 +4236,12 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
42384236
42394237 const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned
42404238 switch (errno(lseek_sym(fd, ioffset, SEEK_END))) {
4241 0 => return,
4242 EBADF => unreachable, // always a race condition
4243 EINVAL => return error.Unseekable,
4244 EOVERFLOW => return error.Unseekable,
4245 ESPIPE => return error.Unseekable,
4246 ENXIO => return error.Unseekable,
4239 .SUCCESS => return,
4240 .BADF => unreachable, // always a race condition
4241 .INVAL => return error.Unseekable,
4242 .OVERFLOW => return error.Unseekable,
4243 .SPIPE => return error.Unseekable,
4244 .NXIO => return error.Unseekable,
42474245 else => |err| return unexpectedErrno(err),
42484246 }
42494247}
......@@ -4253,12 +4251,12 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {
42534251 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
42544252 var result: u64 = undefined;
42554253 switch (errno(system.llseek(fd, 0, &result, SEEK_CUR))) {
4256 0 => return result,
4257 EBADF => unreachable, // always a race condition
4258 EINVAL => return error.Unseekable,
4259 EOVERFLOW => return error.Unseekable,
4260 ESPIPE => return error.Unseekable,
4261 ENXIO => return error.Unseekable,
4254 .SUCCESS => return result,
4255 .BADF => unreachable, // always a race condition
4256 .INVAL => return error.Unseekable,
4257 .OVERFLOW => return error.Unseekable,
4258 .SPIPE => return error.Unseekable,
4259 .NXIO => return error.Unseekable,
42624260 else => |err| return unexpectedErrno(err),
42634261 }
42644262 }
......@@ -4268,13 +4266,13 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {
42684266 if (builtin.os.tag == .wasi and !builtin.link_libc) {
42694267 var new_offset: wasi.filesize_t = undefined;
42704268 switch (wasi.fd_seek(fd, 0, wasi.WHENCE_CUR, &new_offset)) {
4271 wasi.ESUCCESS => return new_offset,
4272 wasi.EBADF => unreachable, // always a race condition
4273 wasi.EINVAL => return error.Unseekable,
4274 wasi.EOVERFLOW => return error.Unseekable,
4275 wasi.ESPIPE => return error.Unseekable,
4276 wasi.ENXIO => return error.Unseekable,
4277 wasi.ENOTCAPABLE => return error.AccessDenied,
4269 .SUCCESS => return new_offset,
4270 .BADF => unreachable, // always a race condition
4271 .INVAL => return error.Unseekable,
4272 .OVERFLOW => return error.Unseekable,
4273 .SPIPE => return error.Unseekable,
4274 .NXIO => return error.Unseekable,
4275 .NOTCAPABLE => return error.AccessDenied,
42784276 else => |err| return unexpectedErrno(err),
42794277 }
42804278 }
......@@ -4285,12 +4283,12 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {
42854283
42864284 const rc = lseek_sym(fd, 0, SEEK_CUR);
42874285 switch (errno(rc)) {
4288 0 => return @bitCast(u64, rc),
4289 EBADF => unreachable, // always a race condition
4290 EINVAL => return error.Unseekable,
4291 EOVERFLOW => return error.Unseekable,
4292 ESPIPE => return error.Unseekable,
4293 ENXIO => return error.Unseekable,
4286 .SUCCESS => return @bitCast(u64, rc),
4287 .BADF => unreachable, // always a race condition
4288 .INVAL => return error.Unseekable,
4289 .OVERFLOW => return error.Unseekable,
4290 .SPIPE => return error.Unseekable,
4291 .NXIO => return error.Unseekable,
42944292 else => |err| return unexpectedErrno(err),
42954293 }
42964294}
......@@ -4306,15 +4304,15 @@ pub fn fcntl(fd: fd_t, cmd: i32, arg: usize) FcntlError!usize {
43064304 while (true) {
43074305 const rc = system.fcntl(fd, cmd, arg);
43084306 switch (errno(rc)) {
4309 0 => return @intCast(usize, rc),
4310 EINTR => continue,
4311 EACCES => return error.Locked,
4312 EBADF => unreachable,
4313 EBUSY => return error.FileBusy,
4314 EINVAL => unreachable, // invalid parameters
4315 EPERM => return error.PermissionDenied,
4316 EMFILE => return error.ProcessFdQuotaExceeded,
4317 ENOTDIR => unreachable, // invalid parameter
4307 .SUCCESS => return @intCast(usize, rc),
4308 .INTR => continue,
4309 .ACCES => return error.Locked,
4310 .BADF => unreachable,
4311 .BUSY => return error.FileBusy,
4312 .INVAL => unreachable, // invalid parameters
4313 .PERM => return error.PermissionDenied,
4314 .MFILE => return error.ProcessFdQuotaExceeded,
4315 .NOTDIR => unreachable, // invalid parameter
43184316 else => |err| return unexpectedErrno(err),
43194317 }
43204318 }
......@@ -4381,12 +4379,12 @@ pub fn flock(fd: fd_t, operation: i32) FlockError!void {
43814379 while (true) {
43824380 const rc = system.flock(fd, operation);
43834381 switch (errno(rc)) {
4384 0 => return,
4385 EBADF => unreachable,
4386 EINTR => continue,
4387 EINVAL => unreachable, // invalid parameters
4388 ENOLCK => return error.SystemResources,
4389 EWOULDBLOCK => return error.WouldBlock, // TODO: integrate with async instead of just returning an error
4382 .SUCCESS => return,
4383 .BADF => unreachable,
4384 .INTR => continue,
4385 .INVAL => unreachable, // invalid parameters
4386 .NOLCK => return error.SystemResources,
4387 .AGAIN => return error.WouldBlock, // TODO: integrate with async instead of just returning an error
43904388 else => |err| return unexpectedErrno(err),
43914389 }
43924390 }
......@@ -4456,17 +4454,18 @@ pub fn realpathZ(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealP
44564454
44574455 return getFdPath(fd, out_buffer);
44584456 }
4459 const result_path = std.c.realpath(pathname, out_buffer) orelse switch (std.c._errno().*) {
4460 EINVAL => unreachable,
4461 EBADF => unreachable,
4462 EFAULT => unreachable,
4463 EACCES => return error.AccessDenied,
4464 ENOENT => return error.FileNotFound,
4465 ENOTSUP => return error.NotSupported,
4466 ENOTDIR => return error.NotDir,
4467 ENAMETOOLONG => return error.NameTooLong,
4468 ELOOP => return error.SymLinkLoop,
4469 EIO => return error.InputOutput,
4457 const result_path = std.c.realpath(pathname, out_buffer) orelse switch (@intToEnum(E, std.c._errno().*)) {
4458 .SUCCESS => unreachable,
4459 .INVAL => unreachable,
4460 .BADF => unreachable,
4461 .FAULT => unreachable,
4462 .ACCES => return error.AccessDenied,
4463 .NOENT => return error.FileNotFound,
4464 .OPNOTSUPP => return error.NotSupported,
4465 .NOTDIR => return error.NotDir,
4466 .NAMETOOLONG => return error.NameTooLong,
4467 .LOOP => return error.SymLinkLoop,
4468 .IO => return error.InputOutput,
44704469 else => |err| return unexpectedErrno(err),
44714470 };
44724471 return mem.spanZ(result_path);
......@@ -4528,8 +4527,8 @@ pub fn getFdPath(fd: fd_t, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
45284527 // the path to the file descriptor.
45294528 @memset(out_buffer, 0, MAX_PATH_BYTES);
45304529 switch (errno(system.fcntl(fd, F_GETPATH, out_buffer))) {
4531 0 => {},
4532 EBADF => return error.FileNotFound,
4530 .SUCCESS => {},
4531 .BADF => return error.FileNotFound,
45334532 // TODO man pages for fcntl on macOS don't really tell you what
45344533 // errno values to expect when command is F_GETPATH...
45354534 else => |err| return unexpectedErrno(err),
......@@ -4562,13 +4561,13 @@ pub fn nanosleep(seconds: u64, nanoseconds: u64) void {
45624561 var rem: timespec = undefined;
45634562 while (true) {
45644563 switch (errno(system.nanosleep(&req, &rem))) {
4565 EFAULT => unreachable,
4566 EINVAL => {
4564 .FAULT => unreachable,
4565 .INVAL => {
45674566 // Sometimes Darwin returns EINVAL for no reason.
45684567 // We treat it as a spurious wakeup.
45694568 return;
45704569 },
4571 EINTR => {
4570 .INTR => {
45724571 req = rem;
45734572 continue;
45744573 },
......@@ -4668,13 +4667,13 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {
46684667 if (std.Target.current.os.tag == .wasi and !builtin.link_libc) {
46694668 var ts: timestamp_t = undefined;
46704669 switch (system.clock_time_get(@bitCast(u32, clk_id), 1, &ts)) {
4671 0 => {
4670 .SUCCESS => {
46724671 tp.* = .{
46734672 .tv_sec = @intCast(i64, ts / std.time.ns_per_s),
46744673 .tv_nsec = @intCast(isize, ts % std.time.ns_per_s),
46754674 };
46764675 },
4677 EINVAL => return error.UnsupportedClock,
4676 .INVAL => return error.UnsupportedClock,
46784677 else => |err| return unexpectedErrno(err),
46794678 }
46804679 return;
......@@ -4698,9 +4697,9 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {
46984697 }
46994698
47004699 switch (errno(system.clock_gettime(clk_id, tp))) {
4701 0 => return,
4702 EFAULT => unreachable,
4703 EINVAL => return error.UnsupportedClock,
4700 .SUCCESS => return,
4701 .FAULT => unreachable,
4702 .INVAL => return error.UnsupportedClock,
47044703 else => |err| return unexpectedErrno(err),
47054704 }
47064705}
......@@ -4709,20 +4708,20 @@ pub fn clock_getres(clk_id: i32, res: *timespec) ClockGetTimeError!void {
47094708 if (std.Target.current.os.tag == .wasi and !builtin.link_libc) {
47104709 var ts: timestamp_t = undefined;
47114710 switch (system.clock_res_get(@bitCast(u32, clk_id), &ts)) {
4712 0 => res.* = .{
4711 .SUCCESS => res.* = .{
47134712 .tv_sec = @intCast(i64, ts / std.time.ns_per_s),
47144713 .tv_nsec = @intCast(isize, ts % std.time.ns_per_s),
47154714 },
4716 EINVAL => return error.UnsupportedClock,
4715 .INVAL => return error.UnsupportedClock,
47174716 else => |err| return unexpectedErrno(err),
47184717 }
47194718 return;
47204719 }
47214720
47224721 switch (errno(system.clock_getres(clk_id, res))) {
4723 0 => return,
4724 EFAULT => unreachable,
4725 EINVAL => return error.UnsupportedClock,
4722 .SUCCESS => return,
4723 .FAULT => unreachable,
4724 .INVAL => return error.UnsupportedClock,
47264725 else => |err| return unexpectedErrno(err),
47274726 }
47284727}
......@@ -4732,11 +4731,11 @@ pub const SchedGetAffinityError = error{PermissionDenied} || UnexpectedError;
47324731pub fn sched_getaffinity(pid: pid_t) SchedGetAffinityError!cpu_set_t {
47334732 var set: cpu_set_t = undefined;
47344733 switch (errno(system.sched_getaffinity(pid, @sizeOf(cpu_set_t), &set))) {
4735 0 => return set,
4736 EFAULT => unreachable,
4737 EINVAL => unreachable,
4738 ESRCH => unreachable,
4739 EPERM => return error.PermissionDenied,
4734 .SUCCESS => return set,
4735 .FAULT => unreachable,
4736 .INVAL => unreachable,
4737 .SRCH => unreachable,
4738 .PERM => return error.PermissionDenied,
47404739 else => |err| return unexpectedErrno(err),
47414740 }
47424741}
......@@ -4768,13 +4767,9 @@ pub const UnexpectedError = error{
47684767
47694768/// Call this when you made a syscall or something that sets errno
47704769/// and you get an unexpected error.
4771pub fn unexpectedErrno(err: anytype) UnexpectedError {
4772 if (@typeInfo(@TypeOf(err)) != .Int) {
4773 @compileError("err is expected to be an integer");
4774 }
4775
4770pub fn unexpectedErrno(err: E) UnexpectedError {
47764771 if (unexpected_error_tracing) {
4777 std.debug.warn("unexpected errno: {d}\n", .{err});
4772 std.debug.warn("unexpected errno: {d}\n", .{@enumToInt(err)});
47784773 std.debug.dumpCurrentStackTrace(null);
47794774 }
47804775 return error.Unexpected;
......@@ -4790,11 +4785,11 @@ pub const SigaltstackError = error{
47904785
47914786pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {
47924787 switch (errno(system.sigaltstack(ss, old_ss))) {
4793 0 => return,
4794 EFAULT => unreachable,
4795 EINVAL => unreachable,
4796 ENOMEM => return error.SizeTooSmall,
4797 EPERM => return error.PermissionDenied,
4788 .SUCCESS => return,
4789 .FAULT => unreachable,
4790 .INVAL => unreachable,
4791 .NOMEM => return error.SizeTooSmall,
4792 .PERM => return error.PermissionDenied,
47984793 else => |err| return unexpectedErrno(err),
47994794 }
48004795}
......@@ -4802,9 +4797,9 @@ pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {
48024797/// Examine and change a signal action.
48034798pub fn sigaction(sig: u6, act: ?*const Sigaction, oact: ?*Sigaction) void {
48044799 switch (errno(system.sigaction(sig, act, oact))) {
4805 0 => return,
4806 EFAULT => unreachable,
4807 EINVAL => unreachable,
4800 .SUCCESS => return,
4801 .FAULT => unreachable,
4802 .INVAL => unreachable,
48084803 else => unreachable,
48094804 }
48104805}
......@@ -4841,25 +4836,25 @@ pub fn futimens(fd: fd_t, times: *const [2]timespec) FutimensError!void {
48414836 const atim = times[0].toTimestamp();
48424837 const mtim = times[1].toTimestamp();
48434838 switch (wasi.fd_filestat_set_times(fd, atim, mtim, wasi.FILESTAT_SET_ATIM | wasi.FILESTAT_SET_MTIM)) {
4844 wasi.ESUCCESS => return,
4845 wasi.EACCES => return error.AccessDenied,
4846 wasi.EPERM => return error.PermissionDenied,
4847 wasi.EBADF => unreachable, // always a race condition
4848 wasi.EFAULT => unreachable,
4849 wasi.EINVAL => unreachable,
4850 wasi.EROFS => return error.ReadOnlyFileSystem,
4839 .SUCCESS => return,
4840 .ACCES => return error.AccessDenied,
4841 .PERM => return error.PermissionDenied,
4842 .BADF => unreachable, // always a race condition
4843 .FAULT => unreachable,
4844 .INVAL => unreachable,
4845 .ROFS => return error.ReadOnlyFileSystem,
48514846 else => |err| return unexpectedErrno(err),
48524847 }
48534848 }
48544849
48554850 switch (errno(system.futimens(fd, times))) {
4856 0 => return,
4857 EACCES => return error.AccessDenied,
4858 EPERM => return error.PermissionDenied,
4859 EBADF => unreachable, // always a race condition
4860 EFAULT => unreachable,
4861 EINVAL => unreachable,
4862 EROFS => return error.ReadOnlyFileSystem,
4851 .SUCCESS => return,
4852 .ACCES => return error.AccessDenied,
4853 .PERM => return error.PermissionDenied,
4854 .BADF => unreachable, // always a race condition
4855 .FAULT => unreachable,
4856 .INVAL => unreachable,
4857 .ROFS => return error.ReadOnlyFileSystem,
48634858 else => |err| return unexpectedErrno(err),
48644859 }
48654860}
......@@ -4869,10 +4864,10 @@ pub const GetHostNameError = error{PermissionDenied} || UnexpectedError;
48694864pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {
48704865 if (builtin.link_libc) {
48714866 switch (errno(system.gethostname(name_buffer, name_buffer.len))) {
4872 0 => return mem.spanZ(std.meta.assumeSentinel(name_buffer, 0)),
4873 EFAULT => unreachable,
4874 ENAMETOOLONG => unreachable, // HOST_NAME_MAX prevents this
4875 EPERM => return error.PermissionDenied,
4867 .SUCCESS => return mem.spanZ(std.meta.assumeSentinel(name_buffer, 0)),
4868 .FAULT => unreachable,
4869 .NAMETOOLONG => unreachable, // HOST_NAME_MAX prevents this
4870 .PERM => return error.PermissionDenied,
48764871 else => |err| return unexpectedErrno(err),
48774872 }
48784873 }
......@@ -4889,8 +4884,8 @@ pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {
48894884pub fn uname() utsname {
48904885 var uts: utsname = undefined;
48914886 switch (errno(system.uname(&uts))) {
4892 0 => return uts,
4893 EFAULT => unreachable,
4887 .SUCCESS => return uts,
4888 .FAULT => unreachable,
48944889 else => unreachable,
48954890 }
48964891}
......@@ -5049,33 +5044,33 @@ pub fn sendmsg(
50495044 }
50505045 } else {
50515046 switch (errno(rc)) {
5052 0 => return @intCast(usize, rc),
5053
5054 EACCES => return error.AccessDenied,
5055 EAGAIN => return error.WouldBlock,
5056 EALREADY => return error.FastOpenAlreadyInProgress,
5057 EBADF => unreachable, // always a race condition
5058 ECONNRESET => return error.ConnectionResetByPeer,
5059 EDESTADDRREQ => 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.
5061 EINTR => continue,
5062 EINVAL => unreachable, // Invalid argument passed.
5063 EISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified
5064 EMSGSIZE => return error.MessageTooBig,
5065 ENOBUFS => return error.SystemResources,
5066 ENOMEM => return error.SystemResources,
5067 ENOTSOCK => 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.
5069 EPIPE => return error.BrokenPipe,
5070 EAFNOSUPPORT => return error.AddressFamilyNotSupported,
5071 ELOOP => return error.SymLinkLoop,
5072 ENAMETOOLONG => return error.NameTooLong,
5073 ENOENT => return error.FileNotFound,
5074 ENOTDIR => return error.NotDir,
5075 EHOSTUNREACH => return error.NetworkUnreachable,
5076 ENETUNREACH => return error.NetworkUnreachable,
5077 ENOTCONN => return error.SocketNotConnected,
5078 ENETDOWN => return error.NetworkSubsystemFailed,
5047 .SUCCESS => return @intCast(usize, rc),
5048
5049 .ACCES => return error.AccessDenied,
5050 .AGAIN => return error.WouldBlock,
5051 .ALREADY => return error.FastOpenAlreadyInProgress,
5052 .BADF => unreachable, // always a race condition
5053 .CONNRESET => return error.ConnectionResetByPeer,
5054 .DESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set.
5055 .FAULT => unreachable, // An invalid user space address was specified for an argument.
5056 .INTR => continue,
5057 .INVAL => unreachable, // Invalid argument passed.
5058 .ISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified
5059 .MSGSIZE => return error.MessageTooBig,
5060 .NOBUFS => return error.SystemResources,
5061 .NOMEM => return error.SystemResources,
5062 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
5063 .OPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type.
5064 .PIPE => return error.BrokenPipe,
5065 .AFNOSUPPORT => return error.AddressFamilyNotSupported,
5066 .LOOP => return error.SymLinkLoop,
5067 .NAMETOOLONG => return error.NameTooLong,
5068 .NOENT => return error.FileNotFound,
5069 .NOTDIR => return error.NotDir,
5070 .HOSTUNREACH => return error.NetworkUnreachable,
5071 .NETUNREACH => return error.NetworkUnreachable,
5072 .NOTCONN => return error.SocketNotConnected,
5073 .NETDOWN => return error.NetworkSubsystemFailed,
50795074 else => |err| return unexpectedErrno(err),
50805075 }
50815076 }
......@@ -5149,33 +5144,33 @@ pub fn sendto(
51495144 }
51505145 } else {
51515146 switch (errno(rc)) {
5152 0 => return @intCast(usize, rc),
5153
5154 EACCES => return error.AccessDenied,
5155 EAGAIN => return error.WouldBlock,
5156 EALREADY => return error.FastOpenAlreadyInProgress,
5157 EBADF => unreachable, // always a race condition
5158 ECONNRESET => return error.ConnectionResetByPeer,
5159 EDESTADDRREQ => 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.
5161 EINTR => continue,
5162 EINVAL => unreachable, // Invalid argument passed.
5163 EISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified
5164 EMSGSIZE => return error.MessageTooBig,
5165 ENOBUFS => return error.SystemResources,
5166 ENOMEM => return error.SystemResources,
5167 ENOTSOCK => 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.
5169 EPIPE => return error.BrokenPipe,
5170 EAFNOSUPPORT => return error.AddressFamilyNotSupported,
5171 ELOOP => return error.SymLinkLoop,
5172 ENAMETOOLONG => return error.NameTooLong,
5173 ENOENT => return error.FileNotFound,
5174 ENOTDIR => return error.NotDir,
5175 EHOSTUNREACH => return error.NetworkUnreachable,
5176 ENETUNREACH => return error.NetworkUnreachable,
5177 ENOTCONN => return error.SocketNotConnected,
5178 ENETDOWN => return error.NetworkSubsystemFailed,
5147 .SUCCESS => return @intCast(usize, rc),
5148
5149 .ACCES => return error.AccessDenied,
5150 .AGAIN => return error.WouldBlock,
5151 .ALREADY => return error.FastOpenAlreadyInProgress,
5152 .BADF => unreachable, // always a race condition
5153 .CONNRESET => return error.ConnectionResetByPeer,
5154 .DESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set.
5155 .FAULT => unreachable, // An invalid user space address was specified for an argument.
5156 .INTR => continue,
5157 .INVAL => unreachable, // Invalid argument passed.
5158 .ISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified
5159 .MSGSIZE => return error.MessageTooBig,
5160 .NOBUFS => return error.SystemResources,
5161 .NOMEM => return error.SystemResources,
5162 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
5163 .OPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type.
5164 .PIPE => return error.BrokenPipe,
5165 .AFNOSUPPORT => return error.AddressFamilyNotSupported,
5166 .LOOP => return error.SymLinkLoop,
5167 .NAMETOOLONG => return error.NameTooLong,
5168 .NOENT => return error.FileNotFound,
5169 .NOTDIR => return error.NotDir,
5170 .HOSTUNREACH => return error.NetworkUnreachable,
5171 .NETUNREACH => return error.NetworkUnreachable,
5172 .NOTCONN => return error.SocketNotConnected,
5173 .NETDOWN => return error.NetworkSubsystemFailed,
51795174 else => |err| return unexpectedErrno(err),
51805175 }
51815176 }
......@@ -5312,7 +5307,7 @@ pub fn sendfile(
53125307 var offset: off_t = @bitCast(off_t, in_offset);
53135308 const rc = sendfile_sym(out_fd, in_fd, &offset, adjusted_count);
53145309 switch (errno(rc)) {
5315 0 => {
5310 .SUCCESS => {
53165311 const amt = @bitCast(usize, rc);
53175312 total_written += amt;
53185313 if (in_len == 0 and amt == 0) {
......@@ -5325,12 +5320,12 @@ pub fn sendfile(
53255320 }
53265321 },
53275322
5328 EBADF => unreachable, // Always a race condition.
5329 EFAULT => unreachable, // Segmentation fault.
5330 EOVERFLOW => unreachable, // We avoid passing too large of a `count`.
5331 ENOTCONN => unreachable, // `out_fd` is an unconnected socket.
5323 .BADF => unreachable, // Always a race condition.
5324 .FAULT => unreachable, // Segmentation fault.
5325 .OVERFLOW => unreachable, // We avoid passing too large of a `count`.
5326 .NOTCONN => unreachable, // `out_fd` is an unconnected socket.
53325327
5333 EINVAL, ENOSYS => {
5328 .INVAL, .NOSYS => {
53345329 // EINVAL could be any of the following situations:
53355330 // * Descriptor is not valid or locked
53365331 // * an mmap(2)-like operation is not available for in_fd
......@@ -5340,17 +5335,17 @@ pub fn sendfile(
53405335 // manually, the same as ENOSYS.
53415336 break :sf;
53425337 },
5343 EAGAIN => if (std.event.Loop.instance) |loop| {
5338 .AGAIN => if (std.event.Loop.instance) |loop| {
53445339 loop.waitUntilFdWritable(out_fd);
53455340 continue;
53465341 } else {
53475342 return error.WouldBlock;
53485343 },
5349 EIO => return error.InputOutput,
5350 EPIPE => return error.BrokenPipe,
5351 ENOMEM => return error.SystemResources,
5352 ENXIO => return error.Unseekable,
5353 ESPIPE => return error.Unseekable,
5344 .IO => return error.InputOutput,
5345 .PIPE => return error.BrokenPipe,
5346 .NOMEM => return error.SystemResources,
5347 .NXIO => return error.Unseekable,
5348 .SPIPE => return error.Unseekable,
53545349 else => |err| {
53555350 unexpectedErrno(err) catch {};
53565351 break :sf;
......@@ -5392,13 +5387,13 @@ pub fn sendfile(
53925387 const err = errno(system.sendfile(in_fd, out_fd, offset, adjusted_count, hdtr, &sbytes, flags));
53935388 const amt = @bitCast(usize, sbytes);
53945389 switch (err) {
5395 0 => return amt,
5390 .SUCCESS => return amt,
53965391
5397 EBADF => unreachable, // Always a race condition.
5398 EFAULT => unreachable, // Segmentation fault.
5399 ENOTCONN => unreachable, // `out_fd` is an unconnected socket.
5392 .BADF => unreachable, // Always a race condition.
5393 .FAULT => unreachable, // Segmentation fault.
5394 .NOTCONN => unreachable, // `out_fd` is an unconnected socket.
54005395
5401 EINVAL, EOPNOTSUPP, ENOTSOCK, ENOSYS => {
5396 .INVAL, .OPNOTSUPP, .NOTSOCK, .NOSYS => {
54025397 // EINVAL could be any of the following situations:
54035398 // * The fd argument is not a regular file.
54045399 // * The s argument is not a SOCK_STREAM type socket.
......@@ -5408,9 +5403,9 @@ pub fn sendfile(
54085403 break :sf;
54095404 },
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) {
54145409 return amt;
54155410 } else if (std.event.Loop.instance) |loop| {
54165411 loop.waitUntilFdWritable(out_fd);
......@@ -5419,7 +5414,7 @@ pub fn sendfile(
54195414 return error.WouldBlock;
54205415 },
54215416
5422 EBUSY => if (amt != 0) {
5417 .BUSY => if (amt != 0) {
54235418 return amt;
54245419 } else if (std.event.Loop.instance) |loop| {
54255420 loop.waitUntilFdReadable(in_fd);
......@@ -5428,9 +5423,9 @@ pub fn sendfile(
54285423 return error.WouldBlock;
54295424 },
54305425
5431 EIO => return error.InputOutput,
5432 ENOBUFS => return error.SystemResources,
5433 EPIPE => return error.BrokenPipe,
5426 .IO => return error.InputOutput,
5427 .NOBUFS => return error.SystemResources,
5428 .PIPE => return error.BrokenPipe,
54345429
54355430 else => {
54365431 unexpectedErrno(err) catch {};
......@@ -5471,18 +5466,18 @@ pub fn sendfile(
54715466 const err = errno(system.sendfile(in_fd, out_fd, signed_offset, &sbytes, hdtr, flags));
54725467 const amt = @bitCast(usize, sbytes);
54735468 switch (err) {
5474 0 => return amt,
5469 .SUCCESS => return amt,
54755470
5476 EBADF => unreachable, // Always a race condition.
5477 EFAULT => unreachable, // Segmentation fault.
5478 EINVAL => unreachable,
5479 ENOTCONN => unreachable, // `out_fd` is an unconnected socket.
5471 .BADF => unreachable, // Always a race condition.
5472 .FAULT => unreachable, // Segmentation fault.
5473 .INVAL => unreachable,
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) {
54865481 return amt;
54875482 } else if (std.event.Loop.instance) |loop| {
54885483 loop.waitUntilFdWritable(out_fd);
......@@ -5491,8 +5486,8 @@ pub fn sendfile(
54915486 return error.WouldBlock;
54925487 },
54935488
5494 EIO => return error.InputOutput,
5495 EPIPE => return error.BrokenPipe,
5489 .IO => return error.InputOutput,
5490 .PIPE => return error.BrokenPipe,
54965491
54975492 else => {
54985493 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
55955590
55965591 const rc = system.copy_file_range(fd_in, &off_in_copy, fd_out, &off_out_copy, len, flags);
55975592 switch (system.getErrno(rc)) {
5598 0 => return @intCast(usize, rc),
5599 EBADF => return error.FilesOpenedWithWrongFlags,
5600 EFBIG => return error.FileTooBig,
5601 EIO => return error.InputOutput,
5602 EISDIR => return error.IsDir,
5603 ENOMEM => return error.OutOfMemory,
5604 ENOSPC => return error.NoSpaceLeft,
5605 EOVERFLOW => return error.Unseekable,
5606 EPERM => return error.PermissionDenied,
5607 ETXTBSY => return error.FileBusy,
5593 .SUCCESS => return @intCast(usize, rc),
5594 .BADF => return error.FilesOpenedWithWrongFlags,
5595 .FBIG => return error.FileTooBig,
5596 .IO => return error.InputOutput,
5597 .ISDIR => return error.IsDir,
5598 .NOMEM => return error.OutOfMemory,
5599 .NOSPC => return error.NoSpaceLeft,
5600 .OVERFLOW => return error.Unseekable,
5601 .PERM => return error.PermissionDenied,
5602 .TXTBSY => return error.FileBusy,
56085603 // these may not be regular files, try fallback
5609 EINVAL => {},
5604 .INVAL => {},
56105605 // support for cross-filesystem copy added in Linux 5.3, use fallback
5611 EXDEV => {},
5606 .XDEV => {},
56125607 // syscall added in Linux 4.5, use fallback
5613 ENOSYS => {
5608 .NOSYS => {
56145609 has_copy_file_range_syscall.store(false, .Monotonic);
56155610 },
56165611 else => |err| return unexpectedErrno(err),
......@@ -5652,11 +5647,11 @@ pub fn poll(fds: []pollfd, timeout: i32) PollError!usize {
56525647 }
56535648 } else {
56545649 switch (errno(rc)) {
5655 0 => return @intCast(usize, rc),
5656 EFAULT => unreachable,
5657 EINTR => continue,
5658 EINVAL => unreachable,
5659 ENOMEM => return error.SystemResources,
5650 .SUCCESS => return @intCast(usize, rc),
5651 .FAULT => unreachable,
5652 .INTR => continue,
5653 .INVAL => unreachable,
5654 .NOMEM => return error.SystemResources,
56605655 else => |err| return unexpectedErrno(err),
56615656 }
56625657 }
......@@ -5681,11 +5676,11 @@ pub fn ppoll(fds: []pollfd, timeout: ?*const timespec, mask: ?*const sigset_t) P
56815676 }
56825677 const rc = system.ppoll(fds.ptr, fds.len, ts_ptr, mask);
56835678 switch (errno(rc)) {
5684 0 => return @intCast(usize, rc),
5685 EFAULT => unreachable,
5686 EINTR => return error.SignalInterrupt,
5687 EINVAL => unreachable,
5688 ENOMEM => return error.SystemResources,
5679 .SUCCESS => return @intCast(usize, rc),
5680 .FAULT => unreachable,
5681 .INTR => return error.SignalInterrupt,
5682 .INVAL => unreachable,
5683 .NOMEM => return error.SystemResources,
56895684 else => |err| return unexpectedErrno(err),
56905685 }
56915686}
......@@ -5750,17 +5745,17 @@ pub fn recvfrom(
57505745 }
57515746 } else {
57525747 switch (errno(rc)) {
5753 0 => return @intCast(usize, rc),
5754 EBADF => unreachable, // always a race condition
5755 EFAULT => unreachable,
5756 EINVAL => unreachable,
5757 ENOTCONN => unreachable,
5758 ENOTSOCK => unreachable,
5759 EINTR => continue,
5760 EAGAIN => return error.WouldBlock,
5761 ENOMEM => return error.SystemResources,
5762 ECONNREFUSED => return error.ConnectionRefused,
5763 ECONNRESET => return error.ConnectionResetByPeer,
5748 .SUCCESS => return @intCast(usize, rc),
5749 .BADF => unreachable, // always a race condition
5750 .FAULT => unreachable,
5751 .INVAL => unreachable,
5752 .NOTCONN => unreachable,
5753 .NOTSOCK => unreachable,
5754 .INTR => continue,
5755 .AGAIN => return error.WouldBlock,
5756 .NOMEM => return error.SystemResources,
5757 .CONNREFUSED => return error.ConnectionRefused,
5758 .CONNRESET => return error.ConnectionResetByPeer,
57645759 else => |err| return unexpectedErrno(err),
57655760 }
57665761 }
......@@ -5830,8 +5825,8 @@ pub fn sched_yield() SchedYieldError!void {
58305825 return;
58315826 }
58325827 switch (errno(system.sched_yield())) {
5833 0 => return,
5834 ENOSYS => return error.SystemCannotYield,
5828 .SUCCESS => return,
5829 .NOSYS => return error.SystemCannotYield,
58355830 else => return error.SystemCannotYield,
58365831 }
58375832}
......@@ -5874,17 +5869,17 @@ pub fn setsockopt(fd: socket_t, level: u32, optname: u32, opt: []const u8) SetSo
58745869 return;
58755870 } else {
58765871 switch (errno(system.setsockopt(fd, level, optname, opt.ptr, @intCast(socklen_t, opt.len)))) {
5877 0 => {},
5878 EBADF => unreachable, // always a race condition
5879 ENOTSOCK => unreachable, // always a race condition
5880 EINVAL => unreachable,
5881 EFAULT => unreachable,
5882 EDOM => return error.TimeoutTooBig,
5883 EISCONN => return error.AlreadyConnected,
5884 ENOPROTOOPT => return error.InvalidProtocolOption,
5885 ENOMEM => return error.SystemResources,
5886 ENOBUFS => return error.SystemResources,
5887 EPERM => return error.PermissionDenied,
5872 .SUCCESS => {},
5873 .BADF => unreachable, // always a race condition
5874 .NOTSOCK => unreachable, // always a race condition
5875 .INVAL => unreachable,
5876 .FAULT => unreachable,
5877 .DOM => return error.TimeoutTooBig,
5878 .ISCONN => return error.AlreadyConnected,
5879 .NOPROTOOPT => return error.InvalidProtocolOption,
5880 .NOMEM => return error.SystemResources,
5881 .NOBUFS => return error.SystemResources,
5882 .PERM => return error.PermissionDenied,
58885883 else => |err| return unexpectedErrno(err),
58895884 }
58905885 }
......@@ -5909,13 +5904,13 @@ pub fn memfd_createZ(name: [*:0]const u8, flags: u32) MemFdCreateError!fd_t {
59095904 const getErrno = if (use_c) std.c.getErrno else linux.getErrno;
59105905 const rc = sys.memfd_create(name, flags);
59115906 switch (getErrno(rc)) {
5912 0 => return @intCast(fd_t, rc),
5913 EFAULT => unreachable, // name has invalid memory
5914 EINVAL => unreachable, // name/flags are faulty
5915 ENFILE => return error.SystemFdQuotaExceeded,
5916 EMFILE => return error.ProcessFdQuotaExceeded,
5917 ENOMEM => return error.OutOfMemory,
5918 ENOSYS => return error.SystemOutdated,
5907 .SUCCESS => return @intCast(fd_t, rc),
5908 .FAULT => unreachable, // name has invalid memory
5909 .INVAL => unreachable, // name/flags are faulty
5910 .NFILE => return error.SystemFdQuotaExceeded,
5911 .MFILE => return error.ProcessFdQuotaExceeded,
5912 .NOMEM => return error.OutOfMemory,
5913 .NOSYS => return error.SystemOutdated,
59195914 else => |err| return unexpectedErrno(err),
59205915 }
59215916}
......@@ -5940,9 +5935,9 @@ pub fn getrusage(who: i32) rusage {
59405935 var result: rusage = undefined;
59415936 const rc = system.getrusage(who, &result);
59425937 switch (errno(rc)) {
5943 0 => return result,
5944 EINVAL => unreachable,
5945 EFAULT => unreachable,
5938 .SUCCESS => return result,
5939 .INVAL => unreachable,
5940 .FAULT => unreachable,
59465941 else => unreachable,
59475942 }
59485943}
......@@ -5953,10 +5948,10 @@ pub fn tcgetattr(handle: fd_t) TermiosGetError!termios {
59535948 while (true) {
59545949 var term: termios = undefined;
59555950 switch (errno(system.tcgetattr(handle, &term))) {
5956 0 => return term,
5957 EINTR => continue,
5958 EBADF => unreachable,
5959 ENOTTY => return error.NotATerminal,
5951 .SUCCESS => return term,
5952 .INTR => continue,
5953 .BADF => unreachable,
5954 .NOTTY => return error.NotATerminal,
59605955 else => |err| return unexpectedErrno(err),
59615956 }
59625957 }
......@@ -5967,12 +5962,12 @@ pub const TermiosSetError = TermiosGetError || error{ProcessOrphaned};
59675962pub fn tcsetattr(handle: fd_t, optional_action: TCSA, termios_p: termios) TermiosSetError!void {
59685963 while (true) {
59695964 switch (errno(system.tcsetattr(handle, optional_action, &termios_p))) {
5970 0 => return,
5971 EBADF => unreachable,
5972 EINTR => continue,
5973 EINVAL => unreachable,
5974 ENOTTY => return error.NotATerminal,
5975 EIO => return error.ProcessOrphaned,
5965 .SUCCESS => return,
5966 .BADF => unreachable,
5967 .INTR => continue,
5968 .INVAL => unreachable,
5969 .NOTTY => return error.NotATerminal,
5970 .IO => return error.ProcessOrphaned,
59765971 else => |err| return unexpectedErrno(err),
59775972 }
59785973 }
......@@ -5986,15 +5981,15 @@ pub const IoCtl_SIOCGIFINDEX_Error = error{
59865981pub fn ioctl_SIOCGIFINDEX(fd: fd_t, ifr: *ifreq) IoCtl_SIOCGIFINDEX_Error!void {
59875982 while (true) {
59885983 switch (errno(system.ioctl(fd, SIOCGIFINDEX, @ptrToInt(ifr)))) {
5989 0 => return,
5990 EINVAL => unreachable, // Bad parameters.
5991 ENOTTY => unreachable,
5992 ENXIO => unreachable,
5993 EBADF => unreachable, // Always a race condition.
5994 EFAULT => unreachable, // Bad pointer parameter.
5995 EINTR => continue,
5996 EIO => return error.FileSystem,
5997 ENODEV => return error.InterfaceNotFound,
5984 .SUCCESS => return,
5985 .INVAL => unreachable, // Bad parameters.
5986 .NOTTY => unreachable,
5987 .NXIO => unreachable,
5988 .BADF => unreachable, // Always a race condition.
5989 .FAULT => unreachable, // Bad pointer parameter.
5990 .INTR => continue,
5991 .IO => return error.FileSystem,
5992 .NODEV => return error.InterfaceNotFound,
59985993 else => |err| return unexpectedErrno(err),
59995994 }
60005995 }
......@@ -6003,13 +5998,13 @@ pub fn ioctl_SIOCGIFINDEX(fd: fd_t, ifr: *ifreq) IoCtl_SIOCGIFINDEX_Error!void {
60035998pub fn signalfd(fd: fd_t, mask: *const sigset_t, flags: u32) !fd_t {
60045999 const rc = system.signalfd(fd, mask, flags);
60056000 switch (errno(rc)) {
6006 0 => return @intCast(fd_t, rc),
6007 EBADF, EINVAL => unreachable,
6008 ENFILE => return error.SystemFdQuotaExceeded,
6009 ENOMEM => return error.SystemResources,
6010 EMFILE => return error.ProcessResources,
6011 ENODEV => return error.InodeMountFail,
6012 ENOSYS => return error.SystemOutdated,
6001 .SUCCESS => return @intCast(fd_t, rc),
6002 .BADF, .INVAL => unreachable,
6003 .NFILE => return error.SystemFdQuotaExceeded,
6004 .NOMEM => return error.SystemResources,
6005 .MFILE => return error.ProcessResources,
6006 .NODEV => return error.InodeMountFail,
6007 .NOSYS => return error.SystemOutdated,
60136008 else => |err| return unexpectedErrno(err),
60146009 }
60156010}
......@@ -6030,11 +6025,11 @@ pub fn sync() void {
60306025pub fn syncfs(fd: fd_t) SyncError!void {
60316026 const rc = system.syncfs(fd);
60326027 switch (errno(rc)) {
6033 0 => return,
6034 EBADF, EINVAL, EROFS => unreachable,
6035 EIO => return error.InputOutput,
6036 ENOSPC => return error.NoSpaceLeft,
6037 EDQUOT => return error.DiskQuota,
6028 .SUCCESS => return,
6029 .BADF, .INVAL, .ROFS => unreachable,
6030 .IO => return error.InputOutput,
6031 .NOSPC => return error.NoSpaceLeft,
6032 .DQUOT => return error.DiskQuota,
60386033 else => |err| return unexpectedErrno(err),
60396034 }
60406035}
......@@ -6054,11 +6049,11 @@ pub fn fsync(fd: fd_t) SyncError!void {
60546049 }
60556050 const rc = system.fsync(fd);
60566051 switch (errno(rc)) {
6057 0 => return,
6058 EBADF, EINVAL, EROFS => unreachable,
6059 EIO => return error.InputOutput,
6060 ENOSPC => return error.NoSpaceLeft,
6061 EDQUOT => return error.DiskQuota,
6052 .SUCCESS => return,
6053 .BADF, .INVAL, .ROFS => unreachable,
6054 .IO => return error.InputOutput,
6055 .NOSPC => return error.NoSpaceLeft,
6056 .DQUOT => return error.DiskQuota,
60626057 else => |err| return unexpectedErrno(err),
60636058 }
60646059}
......@@ -6073,11 +6068,11 @@ pub fn fdatasync(fd: fd_t) SyncError!void {
60736068 }
60746069 const rc = system.fdatasync(fd);
60756070 switch (errno(rc)) {
6076 0 => return,
6077 EBADF, EINVAL, EROFS => unreachable,
6078 EIO => return error.InputOutput,
6079 ENOSPC => return error.NoSpaceLeft,
6080 EDQUOT => return error.DiskQuota,
6071 .SUCCESS => return,
6072 .BADF, .INVAL, .ROFS => unreachable,
6073 .IO => return error.InputOutput,
6074 .NOSPC => return error.NoSpaceLeft,
6075 .DQUOT => return error.DiskQuota,
60816076 else => |err| return unexpectedErrno(err),
60826077 }
60836078}
......@@ -6111,15 +6106,15 @@ pub fn prctl(option: PR, args: anytype) PrctlError!u31 {
61116106
61126107 const rc = system.prctl(@enumToInt(option), buf[0], buf[1], buf[2], buf[3]);
61136108 switch (errno(rc)) {
6114 0 => return @intCast(u31, rc),
6115 EACCES => return error.AccessDenied,
6116 EBADF => return error.InvalidFileDescriptor,
6117 EFAULT => return error.InvalidAddress,
6118 EINVAL => unreachable,
6119 ENODEV, ENXIO => return error.UnsupportedFeature,
6120 EOPNOTSUPP => return error.OperationNotSupported,
6121 EPERM, EBUSY => return error.PermissionDenied,
6122 ERANGE => unreachable,
6109 .SUCCESS => return @intCast(u31, rc),
6110 .ACCES => return error.AccessDenied,
6111 .BADF => return error.InvalidFileDescriptor,
6112 .FAULT => return error.InvalidAddress,
6113 .INVAL => unreachable,
6114 .NODEV, .NXIO => return error.UnsupportedFeature,
6115 .OPNOTSUPP => return error.OperationNotSupported,
6116 .PERM, .BUSY => return error.PermissionDenied,
6117 .RANGE => unreachable,
61236118 else => |err| return unexpectedErrno(err),
61246119 }
61256120}
......@@ -6134,9 +6129,9 @@ pub fn getrlimit(resource: rlimit_resource) GetrlimitError!rlimit {
61346129
61356130 var limits: rlimit = undefined;
61366131 switch (errno(getrlimit_sym(resource, &limits))) {
6137 0 => return limits,
6138 EFAULT => unreachable, // bogus pointer
6139 EINVAL => unreachable,
6132 .SUCCESS => return limits,
6133 .FAULT => unreachable, // bogus pointer
6134 .INVAL => unreachable,
61406135 else => |err| return unexpectedErrno(err),
61416136 }
61426137}
......@@ -6150,10 +6145,10 @@ pub fn setrlimit(resource: rlimit_resource, limits: rlimit) SetrlimitError!void
61506145 system.setrlimit;
61516146
61526147 switch (errno(setrlimit_sym(resource, &limits))) {
6153 0 => return,
6154 EFAULT => unreachable, // bogus pointer
6155 EINVAL => return error.LimitTooBig, // this could also mean "invalid resource", but that would be unreachable
6156 EPERM => return error.PermissionDenied,
6148 .SUCCESS => return,
6149 .FAULT => unreachable, // bogus pointer
6150 .INVAL => return error.LimitTooBig, // this could also mean "invalid resource", but that would be unreachable
6151 .PERM => return error.PermissionDenied,
61576152 else => |err| return unexpectedErrno(err),
61586153 }
61596154}
......@@ -6194,14 +6189,14 @@ pub const MadviseError = error{
61946189/// This syscall is optional and is sometimes configured to be disabled.
61956190pub fn madvise(ptr: [*]align(mem.page_size) u8, length: usize, advice: u32) MadviseError!void {
61966191 switch (errno(system.madvise(ptr, length, advice))) {
6197 0 => return,
6198 EACCES => return error.AccessDenied,
6199 EAGAIN => return error.SystemResources,
6200 EBADF => unreachable, // The map exists, but the area maps something that isn't a file.
6201 EINVAL => return error.InvalidSyscall,
6202 EIO => return error.WouldExceedMaximumResidentSetSize,
6203 ENOMEM => return error.OutOfMemory,
6204 ENOSYS => return error.MadviseUnavailable,
6192 .SUCCESS => return,
6193 .ACCES => return error.AccessDenied,
6194 .AGAIN => return error.SystemResources,
6195 .BADF => unreachable, // The map exists, but the area maps something that isn't a file.
6196 .INVAL => return error.InvalidSyscall,
6197 .IO => return error.WouldExceedMaximumResidentSetSize,
6198 .NOMEM => return error.OutOfMemory,
6199 .NOSYS => return error.MadviseUnavailable,
62056200 else => |err| return unexpectedErrno(err),
62066201 }
62076202}
lib/std/os/bits.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61//! Platform-dependent types and values that are used along with OS-specific APIs.
72//! These are imported into `std.c`, `std.os`, and `std.os.linux`.
83//! 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const assert = std.debug.assert;
83const maxInt = std.math.maxInt;
......@@ -235,6 +230,7 @@ pub const host_t = mach_port_t;
235230pub const CALENDAR_CLOCK = 1;
236231
237232pub const PATH_MAX = 1024;
233pub const IOV_MAX = 16;
238234
239235pub const STDIN_FILENO = 0;
240236pub const STDOUT_FILENO = 1;
......@@ -865,337 +861,342 @@ pub fn WIFSIGNALED(x: u32) bool {
865861 return wstatus(x) != wstopped and wstatus(x) != 0;
866862}
867863
868/// Operation not permitted
869pub const EPERM = 1;
864pub const E = enum(u16) {
865 /// No error occurred.
866 SUCCESS = 0,
870867
871/// No such file or directory
872pub const ENOENT = 2;
868 /// Operation not permitted
869 PERM = 1,
873870
874/// No such process
875pub const ESRCH = 3;
871 /// No such file or directory
872 NOENT = 2,
876873
877/// Interrupted system call
878pub const EINTR = 4;
874 /// No such process
875 SRCH = 3,
879876
880/// Input/output error
881pub const EIO = 5;
877 /// Interrupted system call
878 INTR = 4,
882879
883/// Device not configured
884pub const ENXIO = 6;
880 /// Input/output error
881 IO = 5,
885882
886/// Argument list too long
887pub const E2BIG = 7;
883 /// Device not configured
884 NXIO = 6,
888885
889/// Exec format error
890pub const ENOEXEC = 8;
886 /// Argument list too long
887 @"2BIG" = 7,
891888
892/// Bad file descriptor
893pub const EBADF = 9;
889 /// Exec format error
890 NOEXEC = 8,
894891
895/// No child processes
896pub const ECHILD = 10;
892 /// Bad file descriptor
893 BADF = 9,
897894
898/// Resource deadlock avoided
899pub const EDEADLK = 11;
895 /// No child processes
896 CHILD = 10,
900897
901/// Cannot allocate memory
902pub const ENOMEM = 12;
898 /// Resource deadlock avoided
899 DEADLK = 11,
903900
904/// Permission denied
905pub const EACCES = 13;
901 /// Cannot allocate memory
902 NOMEM = 12,
906903
907/// Bad address
908pub const EFAULT = 14;
904 /// Permission denied
905 ACCES = 13,
909906
910/// Block device required
911pub const ENOTBLK = 15;
907 /// Bad address
908 FAULT = 14,
912909
913/// Device / Resource busy
914pub const EBUSY = 16;
910 /// Block device required
911 NOTBLK = 15,
915912
916/// File exists
917pub const EEXIST = 17;
913 /// Device / Resource busy
914 BUSY = 16,
918915
919/// Cross-device link
920pub const EXDEV = 18;
916 /// File exists
917 EXIST = 17,
921918
922/// Operation not supported by device
923pub const ENODEV = 19;
919 /// Cross-device link
920 XDEV = 18,
924921
925/// Not a directory
926pub const ENOTDIR = 20;
922 /// Operation not supported by device
923 NODEV = 19,
927924
928/// Is a directory
929pub const EISDIR = 21;
925 /// Not a directory
926 NOTDIR = 20,
930927
931/// Invalid argument
932pub const EINVAL = 22;
928 /// Is a directory
929 ISDIR = 21,
933930
934/// Too many open files in system
935pub const ENFILE = 23;
931 /// Invalid argument
932 INVAL = 22,
936933
937/// Too many open files
938pub const EMFILE = 24;
934 /// Too many open files in system
935 NFILE = 23,
939936
940/// Inappropriate ioctl for device
941pub const ENOTTY = 25;
937 /// Too many open files
938 MFILE = 24,
942939
943/// Text file busy
944pub const ETXTBSY = 26;
940 /// Inappropriate ioctl for device
941 NOTTY = 25,
945942
946/// File too large
947pub const EFBIG = 27;
943 /// Text file busy
944 TXTBSY = 26,
948945
949/// No space left on device
950pub const ENOSPC = 28;
946 /// File too large
947 FBIG = 27,
951948
952/// Illegal seek
953pub const ESPIPE = 29;
949 /// No space left on device
950 NOSPC = 28,
954951
955/// Read-only file system
956pub const EROFS = 30;
952 /// Illegal seek
953 SPIPE = 29,
957954
958/// Too many links
959pub const EMLINK = 31;
960/// Broken pipe
955 /// Read-only file system
956 ROFS = 30,
961957
962// math software
963pub const EPIPE = 32;
958 /// Too many links
959 MLINK = 31,
964960
965/// Numerical argument out of domain
966pub const EDOM = 33;
967/// Result too large
961 /// Broken pipe
962 PIPE = 32,
968963
969// non-blocking and interrupt i/o
970pub const ERANGE = 34;
964 // math software
971965
972/// Resource temporarily unavailable
973pub const EAGAIN = 35;
966 /// Numerical argument out of domain
967 DOM = 33,
974968
975/// Operation would block
976pub const EWOULDBLOCK = EAGAIN;
969 /// Result too large
970 RANGE = 34,
977971
978/// Operation now in progress
979pub const EINPROGRESS = 36;
980/// Operation already in progress
972 // non-blocking and interrupt i/o
981973
982// ipc/network software -- argument errors
983pub const EALREADY = 37;
974 /// Resource temporarily unavailable
975 /// This is the same code used for `WOULDBLOCK`.
976 AGAIN = 35,
984977
985/// Socket operation on non-socket
986pub const ENOTSOCK = 38;
978 /// Operation now in progress
979 INPROGRESS = 36,
987980
988/// Destination address required
989pub const EDESTADDRREQ = 39;
981 /// Operation already in progress
982 ALREADY = 37,
990983
991/// Message too long
992pub const EMSGSIZE = 40;
984 // ipc/network software -- argument errors
993985
994/// Protocol wrong type for socket
995pub const EPROTOTYPE = 41;
986 /// Socket operation on non-socket
987 NOTSOCK = 38,
996988
997/// Protocol not available
998pub const ENOPROTOOPT = 42;
989 /// Destination address required
990 DESTADDRREQ = 39,
999991
1000/// Protocol not supported
1001pub const EPROTONOSUPPORT = 43;
992 /// Message too long
993 MSGSIZE = 40,
1002994
1003/// Socket type not supported
1004pub const ESOCKTNOSUPPORT = 44;
995 /// Protocol wrong type for socket
996 PROTOTYPE = 41,
1005997
1006/// Operation not supported
1007pub const ENOTSUP = 45;
998 /// Protocol not available
999 NOPROTOOPT = 42,
10081000
1009/// Operation not supported. Alias of `ENOTSUP`.
1010pub const EOPNOTSUPP = ENOTSUP;
1001 /// Protocol not supported
1002 PROTONOSUPPORT = 43,
10111003
1012/// Protocol family not supported
1013pub const EPFNOSUPPORT = 46;
1004 /// Socket type not supported
1005 SOCKTNOSUPPORT = 44,
10141006
1015/// Address family not supported by protocol family
1016pub const EAFNOSUPPORT = 47;
1007 /// Operation not supported
1008 /// The same code is used for `NOTSUP`.
1009 OPNOTSUPP = 45,
10171010
1018/// Address already in use
1019pub const EADDRINUSE = 48;
1020/// Can't assign requested address
1011 /// Protocol family not supported
1012 PFNOSUPPORT = 46,
10211013
1022// ipc/network software -- operational errors
1023pub const EADDRNOTAVAIL = 49;
1014 /// Address family not supported by protocol family
1015 AFNOSUPPORT = 47,
10241016
1025/// Network is down
1026pub const ENETDOWN = 50;
1017 /// Address already in use
1018 ADDRINUSE = 48,
1019 /// Can't assign requested address
10271020
1028/// Network is unreachable
1029pub const ENETUNREACH = 51;
1021 // ipc/network software -- operational errors
1022 ADDRNOTAVAIL = 49,
10301023
1031/// Network dropped connection on reset
1032pub const ENETRESET = 52;
1024 /// Network is down
1025 NETDOWN = 50,
10331026
1034/// Software caused connection abort
1035pub const ECONNABORTED = 53;
1027 /// Network is unreachable
1028 NETUNREACH = 51,
10361029
1037/// Connection reset by peer
1038pub const ECONNRESET = 54;
1030 /// Network dropped connection on reset
1031 NETRESET = 52,
10391032
1040/// No buffer space available
1041pub const ENOBUFS = 55;
1033 /// Software caused connection abort
1034 CONNABORTED = 53,
10421035
1043/// Socket is already connected
1044pub const EISCONN = 56;
1036 /// Connection reset by peer
1037 CONNRESET = 54,
10451038
1046/// Socket is not connected
1047pub const ENOTCONN = 57;
1039 /// No buffer space available
1040 NOBUFS = 55,
10481041
1049/// Can't send after socket shutdown
1050pub const ESHUTDOWN = 58;
1042 /// Socket is already connected
1043 ISCONN = 56,
10511044
1052/// Too many references: can't splice
1053pub const ETOOMANYREFS = 59;
1045 /// Socket is not connected
1046 NOTCONN = 57,
10541047
1055/// Operation timed out
1056pub const ETIMEDOUT = 60;
1048 /// Can't send after socket shutdown
1049 SHUTDOWN = 58,
10571050
1058/// Connection refused
1059pub const ECONNREFUSED = 61;
1051 /// Too many references: can't splice
1052 TOOMANYREFS = 59,
10601053
1061/// Too many levels of symbolic links
1062pub const ELOOP = 62;
1054 /// Operation timed out
1055 TIMEDOUT = 60,
10631056
1064/// File name too long
1065pub const ENAMETOOLONG = 63;
1057 /// Connection refused
1058 CONNREFUSED = 61,
10661059
1067/// Host is down
1068pub const EHOSTDOWN = 64;
1060 /// Too many levels of symbolic links
1061 LOOP = 62,
10691062
1070/// No route to host
1071pub const EHOSTUNREACH = 65;
1072/// Directory not empty
1063 /// File name too long
1064 NAMETOOLONG = 63,
10731065
1074// quotas & mush
1075pub const ENOTEMPTY = 66;
1066 /// Host is down
1067 HOSTDOWN = 64,
10761068
1077/// Too many processes
1078pub const EPROCLIM = 67;
1069 /// No route to host
1070 HOSTUNREACH = 65,
1071 /// Directory not empty
10791072
1080/// Too many users
1081pub const EUSERS = 68;
1082/// Disc quota exceeded
1073 // quotas & mush
1074 NOTEMPTY = 66,
10831075
1084// Network File System
1085pub const EDQUOT = 69;
1076 /// Too many processes
1077 PROCLIM = 67,
10861078
1087/// Stale NFS file handle
1088pub const ESTALE = 70;
1079 /// Too many users
1080 USERS = 68,
1081 /// Disc quota exceeded
10891082
1090/// Too many levels of remote in path
1091pub const EREMOTE = 71;
1083 // Network File System
1084 DQUOT = 69,
10921085
1093/// RPC struct is bad
1094pub const EBADRPC = 72;
1086 /// Stale NFS file handle
1087 STALE = 70,
10951088
1096/// RPC version wrong
1097pub const ERPCMISMATCH = 73;
1089 /// Too many levels of remote in path
1090 REMOTE = 71,
10981091
1099/// RPC prog. not avail
1100pub const EPROGUNAVAIL = 74;
1092 /// RPC struct is bad
1093 BADRPC = 72,
11011094
1102/// Program version wrong
1103pub const EPROGMISMATCH = 75;
1095 /// RPC version wrong
1096 RPCMISMATCH = 73,
11041097
1105/// Bad procedure for program
1106pub const EPROCUNAVAIL = 76;
1098 /// RPC prog. not avail
1099 PROGUNAVAIL = 74,
11071100
1108/// No locks available
1109pub const ENOLCK = 77;
1101 /// Program version wrong
1102 PROGMISMATCH = 75,
11101103
1111/// Function not implemented
1112pub const ENOSYS = 78;
1104 /// Bad procedure for program
1105 PROCUNAVAIL = 76,
11131106
1114/// Inappropriate file type or format
1115pub const EFTYPE = 79;
1107 /// No locks available
1108 NOLCK = 77,
11161109
1117/// Authentication error
1118pub const EAUTH = 80;
1119/// Need authenticator
1110 /// Function not implemented
1111 NOSYS = 78,
11201112
1121// Intelligent device errors
1122pub const ENEEDAUTH = 81;
1113 /// Inappropriate file type or format
1114 FTYPE = 79,
11231115
1124/// Device power is off
1125pub const EPWROFF = 82;
1116 /// Authentication error
1117 AUTH = 80,
11261118
1127/// Device error, e.g. paper out
1128pub const EDEVERR = 83;
1129/// Value too large to be stored in data type
1119 /// Need authenticator
1120 NEEDAUTH = 81,
11301121
1131// Program loading errors
1132pub const EOVERFLOW = 84;
1122 // Intelligent device errors
11331123
1134/// Bad executable
1135pub const EBADEXEC = 85;
1124 /// Device power is off
1125 PWROFF = 82,
11361126
1137/// Bad CPU type in executable
1138pub const EBADARCH = 86;
1127 /// Device error, e.g. paper out
1128 DEVERR = 83,
11391129
1140/// Shared library version mismatch
1141pub const ESHLIBVERS = 87;
1130 /// Value too large to be stored in data type
1131 OVERFLOW = 84,
11421132
1143/// Malformed Macho file
1144pub const EBADMACHO = 88;
1133 // Program loading errors
11451134
1146/// Operation canceled
1147pub const ECANCELED = 89;
1135 /// Bad executable
1136 BADEXEC = 85,
11481137
1149/// Identifier removed
1150pub const EIDRM = 90;
1138 /// Bad CPU type in executable
1139 BADARCH = 86,
11511140
1152/// No message of desired type
1153pub const ENOMSG = 91;
1141 /// Shared library version mismatch
1142 SHLIBVERS = 87,
11541143
1155/// Illegal byte sequence
1156pub const EILSEQ = 92;
1144 /// Malformed Macho file
1145 BADMACHO = 88,
11571146
1158/// Attribute not found
1159pub const ENOATTR = 93;
1147 /// Operation canceled
1148 CANCELED = 89,
11601149
1161/// Bad message
1162pub const EBADMSG = 94;
1150 /// Identifier removed
1151 IDRM = 90,
11631152
1164/// Reserved
1165pub const EMULTIHOP = 95;
1153 /// No message of desired type
1154 NOMSG = 91,
11661155
1167/// No message available on STREAM
1168pub const ENODATA = 96;
1156 /// Illegal byte sequence
1157 ILSEQ = 92,
11691158
1170/// Reserved
1171pub const ENOLINK = 97;
1159 /// Attribute not found
1160 NOATTR = 93,
11721161
1173/// No STREAM resources
1174pub const ENOSR = 98;
1162 /// Bad message
1163 BADMSG = 94,
11751164
1176/// Not a STREAM
1177pub const ENOSTR = 99;
1165 /// Reserved
1166 MULTIHOP = 95,
11781167
1179/// Protocol error
1180pub const EPROTO = 100;
1168 /// No message available on STREAM
1169 NODATA = 96,
11811170
1182/// STREAM ioctl timeout
1183pub const ETIME = 101;
1171 /// Reserved
1172 NOLINK = 97,
11841173
1185/// No such policy registered
1186pub const ENOPOLICY = 103;
1174 /// No STREAM resources
1175 NOSR = 98,
11871176
1188/// State not recoverable
1189pub const ENOTRECOVERABLE = 104;
1177 /// Not a STREAM
1178 NOSTR = 99,
11901179
1191/// Previous owner died
1192pub const EOWNERDEAD = 105;
1180 /// Protocol error
1181 PROTO = 100,
11931182
1194/// Interface output queue is full
1195pub const EQFULL = 106;
1183 /// STREAM ioctl timeout
1184 TIME = 101,
11961185
1197/// Must be equal largest errno
1198pub const ELAST = 106;
1186 /// No such policy registered
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
12001201pub const SIGSTKSZ = 131072;
12011202pub const MINSIGSTKSZ = 32768;
lib/std/os/bits/dragonfly.zig+103-102
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const maxInt = std.math.maxInt;
83
......@@ -25,103 +20,108 @@ pub const gid_t = u32;
2520pub const time_t = isize;
2621pub const suseconds_t = c_long;
2722
28pub const ENOTSUP = EOPNOTSUPP;
29pub const EWOULDBLOCK = EAGAIN;
30pub const EPERM = 1;
31pub const ENOENT = 2;
32pub const ESRCH = 3;
33pub const EINTR = 4;
34pub const EIO = 5;
35pub const ENXIO = 6;
36pub const E2BIG = 7;
37pub const ENOEXEC = 8;
38pub const EBADF = 9;
39pub const ECHILD = 10;
40pub const EDEADLK = 11;
41pub const ENOMEM = 12;
42pub const EACCES = 13;
43pub const EFAULT = 14;
44pub const ENOTBLK = 15;
45pub const EBUSY = 16;
46pub const EEXIST = 17;
47pub const EXDEV = 18;
48pub const ENODEV = 19;
49pub const ENOTDIR = 20;
50pub const EISDIR = 21;
51pub const EINVAL = 22;
52pub const ENFILE = 23;
53pub const EMFILE = 24;
54pub const ENOTTY = 25;
55pub const ETXTBSY = 26;
56pub const EFBIG = 27;
57pub const ENOSPC = 28;
58pub const ESPIPE = 29;
59pub const EROFS = 30;
60pub const EMLINK = 31;
61pub const EPIPE = 32;
62pub const EDOM = 33;
63pub const ERANGE = 34;
64pub const EAGAIN = 35;
65pub const EINPROGRESS = 36;
66pub const EALREADY = 37;
67pub const ENOTSOCK = 38;
68pub const EDESTADDRREQ = 39;
69pub const EMSGSIZE = 40;
70pub const EPROTOTYPE = 41;
71pub const ENOPROTOOPT = 42;
72pub const EPROTONOSUPPORT = 43;
73pub const ESOCKTNOSUPPORT = 44;
74pub const EOPNOTSUPP = 45;
75pub const EPFNOSUPPORT = 46;
76pub const EAFNOSUPPORT = 47;
77pub const EADDRINUSE = 48;
78pub const EADDRNOTAVAIL = 49;
79pub const ENETDOWN = 50;
80pub const ENETUNREACH = 51;
81pub const ENETRESET = 52;
82pub const ECONNABORTED = 53;
83pub const ECONNRESET = 54;
84pub const ENOBUFS = 55;
85pub const EISCONN = 56;
86pub const ENOTCONN = 57;
87pub const ESHUTDOWN = 58;
88pub const ETOOMANYREFS = 59;
89pub const ETIMEDOUT = 60;
90pub const ECONNREFUSED = 61;
91pub const ELOOP = 62;
92pub const ENAMETOOLONG = 63;
93pub const EHOSTDOWN = 64;
94pub const EHOSTUNREACH = 65;
95pub const ENOTEMPTY = 66;
96pub const EPROCLIM = 67;
97pub const EUSERS = 68;
98pub const EDQUOT = 69;
99pub const ESTALE = 70;
100pub const EREMOTE = 71;
101pub const EBADRPC = 72;
102pub const ERPCMISMATCH = 73;
103pub const EPROGUNAVAIL = 74;
104pub const EPROGMISMATCH = 75;
105pub const EPROCUNAVAIL = 76;
106pub const ENOLCK = 77;
107pub const ENOSYS = 78;
108pub const EFTYPE = 79;
109pub const EAUTH = 80;
110pub const ENEEDAUTH = 81;
111pub const EIDRM = 82;
112pub const ENOMSG = 83;
113pub const EOVERFLOW = 84;
114pub const ECANCELED = 85;
115pub const EILSEQ = 86;
116pub const ENOATTR = 87;
117pub const EDOOFUS = 88;
118pub const EBADMSG = 89;
119pub const EMULTIHOP = 90;
120pub const ENOLINK = 91;
121pub const EPROTO = 92;
122pub const ENOMEDIUM = 93;
123pub const ELAST = 99;
124pub const EASYNC = 99;
23pub const E = enum(u16) {
24 /// No error occurred.
25 SUCCESS = 0,
26
27 PERM = 1,
28 NOENT = 2,
29 SRCH = 3,
30 INTR = 4,
31 IO = 5,
32 NXIO = 6,
33 @"2BIG" = 7,
34 NOEXEC = 8,
35 BADF = 9,
36 CHILD = 10,
37 DEADLK = 11,
38 NOMEM = 12,
39 ACCES = 13,
40 FAULT = 14,
41 NOTBLK = 15,
42 BUSY = 16,
43 EXIST = 17,
44 XDEV = 18,
45 NODEV = 19,
46 NOTDIR = 20,
47 ISDIR = 21,
48 INVAL = 22,
49 NFILE = 23,
50 MFILE = 24,
51 NOTTY = 25,
52 TXTBSY = 26,
53 FBIG = 27,
54 NOSPC = 28,
55 SPIPE = 29,
56 ROFS = 30,
57 MLINK = 31,
58 PIPE = 32,
59 DOM = 33,
60 RANGE = 34,
61 /// This code is also used for `WOULDBLOCK`.
62 AGAIN = 35,
63 INPROGRESS = 36,
64 ALREADY = 37,
65 NOTSOCK = 38,
66 DESTADDRREQ = 39,
67 MSGSIZE = 40,
68 PROTOTYPE = 41,
69 NOPROTOOPT = 42,
70 PROTONOSUPPORT = 43,
71 SOCKTNOSUPPORT = 44,
72 /// This code is also used for `NOTSUP`.
73 OPNOTSUPP = 45,
74 PFNOSUPPORT = 46,
75 AFNOSUPPORT = 47,
76 ADDRINUSE = 48,
77 ADDRNOTAVAIL = 49,
78 NETDOWN = 50,
79 NETUNREACH = 51,
80 NETRESET = 52,
81 CONNABORTED = 53,
82 CONNRESET = 54,
83 NOBUFS = 55,
84 ISCONN = 56,
85 NOTCONN = 57,
86 SHUTDOWN = 58,
87 TOOMANYREFS = 59,
88 TIMEDOUT = 60,
89 CONNREFUSED = 61,
90 LOOP = 62,
91 NAMETOOLONG = 63,
92 HOSTDOWN = 64,
93 HOSTUNREACH = 65,
94 NOTEMPTY = 66,
95 PROCLIM = 67,
96 USERS = 68,
97 DQUOT = 69,
98 STALE = 70,
99 REMOTE = 71,
100 BADRPC = 72,
101 RPCMISMATCH = 73,
102 PROGUNAVAIL = 74,
103 PROGMISMATCH = 75,
104 PROCUNAVAIL = 76,
105 NOLCK = 77,
106 NOSYS = 78,
107 FTYPE = 79,
108 AUTH = 80,
109 NEEDAUTH = 81,
110 IDRM = 82,
111 NOMSG = 83,
112 OVERFLOW = 84,
113 CANCELED = 85,
114 ILSEQ = 86,
115 NOATTR = 87,
116 DOOFUS = 88,
117 BADMSG = 89,
118 MULTIHOP = 90,
119 NOLINK = 91,
120 PROTO = 92,
121 NOMEDIUM = 93,
122 ASYNC = 99,
123 _,
124};
125125
126126pub const STDIN_FILENO = 0;
127127pub const STDOUT_FILENO = 1;
......@@ -168,6 +168,7 @@ pub const SA_NOCLDWAIT = 0x0020;
168168pub const SA_SIGINFO = 0x0040;
169169
170170pub const PATH_MAX = 1024;
171pub const IOV_MAX = KERN_IOV_MAX;
171172
172173pub const ino_t = c_ulong;
173174
lib/std/os/bits/freebsd.zig+130-126
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const builtin = @import("builtin");
83const maxInt = std.math.maxInt;
......@@ -238,8 +233,10 @@ pub const CTL_DEBUG = 5;
238233
239234pub const KERN_PROC = 14; // struct: process entries
240235pub const KERN_PROC_PATHNAME = 12; // path to executable
236pub const KERN_IOV_MAX = 35;
241237
242238pub const PATH_MAX = 1024;
239pub const IOV_MAX = KERN_IOV_MAX;
243240
244241pub const STDIN_FILENO = 0;
245242pub const STDOUT_FILENO = 1;
......@@ -885,127 +882,134 @@ pub usingnamespace switch (builtin.target.cpu.arch) {
885882 else => struct {},
886883};
887884
888pub const EPERM = 1; // Operation not permitted
889pub const ENOENT = 2; // No such file or directory
890pub const ESRCH = 3; // No such process
891pub const EINTR = 4; // Interrupted system call
892pub const EIO = 5; // Input/output error
893pub const ENXIO = 6; // Device not configured
894pub const E2BIG = 7; // Argument list too long
895pub const ENOEXEC = 8; // Exec format error
896pub const EBADF = 9; // Bad file descriptor
897pub const ECHILD = 10; // No child processes
898pub const EDEADLK = 11; // Resource deadlock avoided
899// 11 was EAGAIN
900pub const ENOMEM = 12; // Cannot allocate memory
901pub const EACCES = 13; // Permission denied
902pub const EFAULT = 14; // Bad address
903pub const ENOTBLK = 15; // Block device required
904pub const EBUSY = 16; // Device busy
905pub const EEXIST = 17; // File exists
906pub const EXDEV = 18; // Cross-device link
907pub const ENODEV = 19; // Operation not supported by device
908pub const ENOTDIR = 20; // Not a directory
909pub const EISDIR = 21; // Is a directory
910pub const EINVAL = 22; // Invalid argument
911pub const ENFILE = 23; // Too many open files in system
912pub const EMFILE = 24; // Too many open files
913pub const ENOTTY = 25; // Inappropriate ioctl for device
914pub const ETXTBSY = 26; // Text file busy
915pub const EFBIG = 27; // File too large
916pub const ENOSPC = 28; // No space left on device
917pub const ESPIPE = 29; // Illegal seek
918pub const EROFS = 30; // Read-only filesystem
919pub const EMLINK = 31; // Too many links
920pub const EPIPE = 32; // Broken pipe
921
922// math software
923pub const EDOM = 33; // Numerical argument out of domain
924pub const ERANGE = 34; // Result too large
925
926// non-blocking and interrupt i/o
927pub const EAGAIN = 35; // Resource temporarily unavailable
928pub const EWOULDBLOCK = EAGAIN; // Operation would block
929pub const EINPROGRESS = 36; // Operation now in progress
930pub const EALREADY = 37; // Operation already in progress
931
932// ipc/network software -- argument errors
933pub const ENOTSOCK = 38; // Socket operation on non-socket
934pub const EDESTADDRREQ = 39; // Destination address required
935pub const EMSGSIZE = 40; // Message too long
936pub const EPROTOTYPE = 41; // Protocol wrong type for socket
937pub const ENOPROTOOPT = 42; // Protocol not available
938pub const EPROTONOSUPPORT = 43; // Protocol not supported
939pub const ESOCKTNOSUPPORT = 44; // Socket type not supported
940pub const EOPNOTSUPP = 45; // Operation not supported
941pub const ENOTSUP = EOPNOTSUPP; // Operation not supported
942pub const EPFNOSUPPORT = 46; // Protocol family not supported
943pub const EAFNOSUPPORT = 47; // Address family not supported by protocol family
944pub const EADDRINUSE = 48; // Address already in use
945pub const EADDRNOTAVAIL = 49; // Can't assign requested address
946
947// ipc/network software -- operational errors
948pub const ENETDOWN = 50; // Network is down
949pub const ENETUNREACH = 51; // Network is unreachable
950pub const ENETRESET = 52; // Network dropped connection on reset
951pub const ECONNABORTED = 53; // Software caused connection abort
952pub const ECONNRESET = 54; // Connection reset by peer
953pub const ENOBUFS = 55; // No buffer space available
954pub const EISCONN = 56; // Socket is already connected
955pub const ENOTCONN = 57; // Socket is not connected
956pub const ESHUTDOWN = 58; // Can't send after socket shutdown
957pub const ETOOMANYREFS = 59; // Too many references: can't splice
958pub const ETIMEDOUT = 60; // Operation timed out
959pub const ECONNREFUSED = 61; // Connection refused
960
961pub const ELOOP = 62; // Too many levels of symbolic links
962pub const ENAMETOOLONG = 63; // File name too long
963
964// should be rearranged
965pub const EHOSTDOWN = 64; // Host is down
966pub const EHOSTUNREACH = 65; // No route to host
967pub const ENOTEMPTY = 66; // Directory not empty
968
969// quotas & mush
970pub const EPROCLIM = 67; // Too many processes
971pub const EUSERS = 68; // Too many users
972pub const EDQUOT = 69; // Disc quota exceeded
973
974// Network File System
975pub const ESTALE = 70; // Stale NFS file handle
976pub const EREMOTE = 71; // Too many levels of remote in path
977pub const EBADRPC = 72; // RPC struct is bad
978pub const ERPCMISMATCH = 73; // RPC version wrong
979pub const EPROGUNAVAIL = 74; // RPC prog. not avail
980pub const EPROGMISMATCH = 75; // Program version wrong
981pub const EPROCUNAVAIL = 76; // Bad procedure for program
982
983pub const ENOLCK = 77; // No locks available
984pub const ENOSYS = 78; // Function not implemented
985
986pub const EFTYPE = 79; // Inappropriate file type or format
987pub const EAUTH = 80; // Authentication error
988pub const ENEEDAUTH = 81; // Need authenticator
989pub const EIDRM = 82; // Identifier removed
990pub const ENOMSG = 83; // No message of desired type
991pub const EOVERFLOW = 84; // Value too large to be stored in data type
992pub const ECANCELED = 85; // Operation canceled
993pub const EILSEQ = 86; // Illegal byte sequence
994pub const ENOATTR = 87; // Attribute not found
995
996pub const EDOOFUS = 88; // Programming error
997
998pub const EBADMSG = 89; // Bad message
999pub const EMULTIHOP = 90; // Multihop attempted
1000pub const ENOLINK = 91; // Link has been severed
1001pub const EPROTO = 92; // Protocol error
1002
1003pub const ENOTCAPABLE = 93; // Capabilities insufficient
1004pub const ECAPMODE = 94; // Not permitted in capability mode
1005pub const ENOTRECOVERABLE = 95; // State not recoverable
1006pub const EOWNERDEAD = 96; // Previous owner died
1007
1008pub const ELAST = 96; // Must be equal largest errno
885pub const E = enum(u16) {
886 /// No error occurred.
887 SUCCESS = 0,
888
889 PERM = 1, // Operation not permitted
890 NOENT = 2, // No such file or directory
891 SRCH = 3, // No such process
892 INTR = 4, // Interrupted system call
893 IO = 5, // Input/output error
894 NXIO = 6, // Device not configured
895 @"2BIG" = 7, // Argument list too long
896 NOEXEC = 8, // Exec format error
897 BADF = 9, // Bad file descriptor
898 CHILD = 10, // No child processes
899 DEADLK = 11, // Resource deadlock avoided
900 // 11 was AGAIN
901 NOMEM = 12, // Cannot allocate memory
902 ACCES = 13, // Permission denied
903 FAULT = 14, // Bad address
904 NOTBLK = 15, // Block device required
905 BUSY = 16, // Device busy
906 EXIST = 17, // File exists
907 XDEV = 18, // Cross-device link
908 NODEV = 19, // Operation not supported by device
909 NOTDIR = 20, // Not a directory
910 ISDIR = 21, // Is a directory
911 INVAL = 22, // Invalid argument
912 NFILE = 23, // Too many open files in system
913 MFILE = 24, // Too many open files
914 NOTTY = 25, // Inappropriate ioctl for device
915 TXTBSY = 26, // Text file busy
916 FBIG = 27, // File too large
917 NOSPC = 28, // No space left on device
918 SPIPE = 29, // Illegal seek
919 ROFS = 30, // Read-only filesystem
920 MLINK = 31, // Too many links
921 PIPE = 32, // Broken pipe
922
923 // math software
924 DOM = 33, // Numerical argument out of domain
925 RANGE = 34, // Result too large
926
927 // non-blocking and interrupt i/o
928
929 /// Resource temporarily unavailable
930 /// This code is also used for `WOULDBLOCK`: operation would block.
931 AGAIN = 35,
932 INPROGRESS = 36, // Operation now in progress
933 ALREADY = 37, // Operation already in progress
934
935 // ipc/network software -- argument errors
936 NOTSOCK = 38, // Socket operation on non-socket
937 DESTADDRREQ = 39, // Destination address required
938 MSGSIZE = 40, // Message too long
939 PROTOTYPE = 41, // Protocol wrong type for socket
940 NOPROTOOPT = 42, // Protocol not available
941 PROTONOSUPPORT = 43, // Protocol not supported
942 SOCKTNOSUPPORT = 44, // Socket type not supported
943 /// Operation not supported
944 /// This code is also used for `NOTSUP`.
945 OPNOTSUPP = 45,
946 PFNOSUPPORT = 46, // Protocol family not supported
947 AFNOSUPPORT = 47, // Address family not supported by protocol family
948 ADDRINUSE = 48, // Address already in use
949 ADDRNOTAVAIL = 49, // Can't assign requested address
950
951 // ipc/network software -- operational errors
952 NETDOWN = 50, // Network is down
953 NETUNREACH = 51, // Network is unreachable
954 NETRESET = 52, // Network dropped connection on reset
955 CONNABORTED = 53, // Software caused connection abort
956 CONNRESET = 54, // Connection reset by peer
957 NOBUFS = 55, // No buffer space available
958 ISCONN = 56, // Socket is already connected
959 NOTCONN = 57, // Socket is not connected
960 SHUTDOWN = 58, // Can't send after socket shutdown
961 TOOMANYREFS = 59, // Too many references: can't splice
962 TIMEDOUT = 60, // Operation timed out
963 CONNREFUSED = 61, // Connection refused
964
965 LOOP = 62, // Too many levels of symbolic links
966 NAMETOOLONG = 63, // File name too long
967
968 // should be rearranged
969 HOSTDOWN = 64, // Host is down
970 HOSTUNREACH = 65, // No route to host
971 NOTEMPTY = 66, // Directory not empty
972
973 // quotas & mush
974 PROCLIM = 67, // Too many processes
975 USERS = 68, // Too many users
976 DQUOT = 69, // Disc quota exceeded
977
978 // Network File System
979 STALE = 70, // Stale NFS file handle
980 REMOTE = 71, // Too many levels of remote in path
981 BADRPC = 72, // RPC struct is bad
982 RPCMISMATCH = 73, // RPC version wrong
983 PROGUNAVAIL = 74, // RPC prog. not avail
984 PROGMISMATCH = 75, // Program version wrong
985 PROCUNAVAIL = 76, // Bad procedure for program
986
987 NOLCK = 77, // No locks available
988 NOSYS = 78, // Function not implemented
989
990 FTYPE = 79, // Inappropriate file type or format
991 AUTH = 80, // Authentication error
992 NEEDAUTH = 81, // Need authenticator
993 IDRM = 82, // Identifier removed
994 NOMSG = 83, // No message of desired type
995 OVERFLOW = 84, // Value too large to be stored in data type
996 CANCELED = 85, // Operation canceled
997 ILSEQ = 86, // Illegal byte sequence
998 NOATTR = 87, // Attribute not found
999
1000 DOOFUS = 88, // Programming error
1001
1002 BADMSG = 89, // Bad message
1003 MULTIHOP = 90, // Multihop attempted
1004 NOLINK = 91, // Link has been severed
1005 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
10101014pub const MINSIGSTKSZ = switch (builtin.target.cpu.arch) {
10111015 .i386, .x86_64 => 2048,
lib/std/os/bits/haiku.zig+124-124
......@@ -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.
61const std = @import("../../std.zig");
72const maxInt = std.math.maxInt;
83
......@@ -734,125 +729,130 @@ pub const sigset_t = extern struct {
734729 __bits: [_SIG_WORDS]u32,
735730};
736731
737pub const EPERM = -0x7ffffff1; // Operation not permitted
738pub const ENOENT = -0x7fff9ffd; // No such file or directory
739pub const ESRCH = -0x7fff8ff3; // No such process
740pub const EINTR = -0x7ffffff6; // Interrupted system call
741pub const EIO = -0x7fffffff; // Input/output error
742pub const ENXIO = -0x7fff8ff5; // Device not configured
743pub const E2BIG = -0x7fff8fff; // Argument list too long
744pub const ENOEXEC = -0x7fffecfe; // Exec format error
745pub const ECHILD = -0x7fff8ffe; // No child processes
746pub const EDEADLK = -0x7fff8ffd; // Resource deadlock avoided
747pub const ENOMEM = -0x80000000; // Cannot allocate memory
748pub const EACCES = -0x7ffffffe; // Permission denied
749pub const EFAULT = -0x7fffecff; // Bad address
750pub const EBUSY = -0x7ffffff2; // Device busy
751pub const EEXIST = -0x7fff9ffe; // File exists
752pub const EXDEV = -0x7fff9ff5; // Cross-device link
753pub const ENODEV = -0x7fff8ff9; // Operation not supported by device
754pub const ENOTDIR = -0x7fff9ffb; // Not a directory
755pub const EISDIR = -0x7fff9ff7; // Is a directory
756pub const EINVAL = -0x7ffffffb; // Invalid argument
757pub const ENFILE = -0x7fff8ffa; // Too many open files in system
758pub const EMFILE = -0x7fff9ff6; // Too many open files
759pub const ENOTTY = -0x7fff8ff6; // Inappropriate ioctl for device
760pub const ETXTBSY = -0x7fff8fc5; // Text file busy
761pub const EFBIG = -0x7fff8ffc; // File too large
762pub const ENOSPC = -0x7fff9ff9; // No space left on device
763pub const ESPIPE = -0x7fff8ff4; // Illegal seek
764pub const EROFS = -0x7fff9ff8; // Read-only filesystem
765pub const EMLINK = -0x7fff8ffb; // Too many links
766pub const EPIPE = -0x7fff9ff3; // Broken pipe
767pub const EBADF = -0x7fffa000; // Bad file descriptor
768
769// math software
770pub const EDOM = 33; // Numerical argument out of domain
771pub const ERANGE = 34; // Result too large
772
773// non-blocking and interrupt i/o
774pub const EAGAIN = -0x7ffffff5;
775pub const EWOULDBLOCK = -0x7ffffff5;
776pub const EINPROGRESS = -0x7fff8fdc;
777pub const EALREADY = -0x7fff8fdb;
778
779// ipc/network software -- argument errors
780pub const ENOTSOCK = 38; // Socket operation on non-socket
781pub const EDESTADDRREQ = 39; // Destination address required
782pub const EMSGSIZE = 40; // Message too long
783pub const EPROTOTYPE = 41; // Protocol wrong type for socket
784pub const ENOPROTOOPT = 42; // Protocol not available
785pub const EPROTONOSUPPORT = 43; // Protocol not supported
786pub const ESOCKTNOSUPPORT = 44; // Socket type not supported
787pub const EOPNOTSUPP = 45; // Operation not supported
788pub const ENOTSUP = EOPNOTSUPP; // Operation not supported
789pub const EPFNOSUPPORT = 46; // Protocol family not supported
790pub const EAFNOSUPPORT = 47; // Address family not supported by protocol family
791pub const EADDRINUSE = 48; // Address already in use
792pub const EADDRNOTAVAIL = 49; // Can't assign requested address
793
794// ipc/network software -- operational errors
795pub const ENETDOWN = 50; // Network is down
796pub const ENETUNREACH = 51; // Network is unreachable
797pub const ENETRESET = 52; // Network dropped connection on reset
798pub const ECONNABORTED = 53; // Software caused connection abort
799pub const ECONNRESET = 54; // Connection reset by peer
800pub const ENOBUFS = 55; // No buffer space available
801pub const EISCONN = 56; // Socket is already connected
802pub const ENOTCONN = 57; // Socket is not connected
803pub const ESHUTDOWN = 58; // Can't send after socket shutdown
804pub const ETOOMANYREFS = 59; // Too many references: can't splice
805pub const ETIMEDOUT = 60; // Operation timed out
806pub const ECONNREFUSED = 61; // Connection refused
807
808pub const ELOOP = 62; // Too many levels of symbolic links
809pub const ENAMETOOLONG = 63; // File name too long
810
811// should be rearranged
812pub const EHOSTDOWN = 64; // Host is down
813pub const EHOSTUNREACH = 65; // No route to host
814pub const ENOTEMPTY = 66; // Directory not empty
815
816// quotas & mush
817pub const EPROCLIM = 67; // Too many processes
818pub const EUSERS = 68; // Too many users
819pub const EDQUOT = 69; // Disc quota exceeded
820
821// Network File System
822pub const ESTALE = 70; // Stale NFS file handle
823pub const EREMOTE = 71; // Too many levels of remote in path
824pub const EBADRPC = 72; // RPC struct is bad
825pub const ERPCMISMATCH = 73; // RPC version wrong
826pub const EPROGUNAVAIL = 74; // RPC prog. not avail
827pub const EPROGMISMATCH = 75; // Program version wrong
828pub const EPROCUNAVAIL = 76; // Bad procedure for program
829
830pub const ENOLCK = 77; // No locks available
831pub const ENOSYS = 78; // Function not implemented
832
833pub const EFTYPE = 79; // Inappropriate file type or format
834pub const EAUTH = 80; // Authentication error
835pub const ENEEDAUTH = 81; // Need authenticator
836pub const EIDRM = 82; // Identifier removed
837pub const ENOMSG = 83; // No message of desired type
838pub const EOVERFLOW = 84; // Value too large to be stored in data type
839pub const ECANCELED = 85; // Operation canceled
840pub const EILSEQ = 86; // Illegal byte sequence
841pub const ENOATTR = 87; // Attribute not found
842
843pub const EDOOFUS = 88; // Programming error
844
845pub const EBADMSG = 89; // Bad message
846pub const EMULTIHOP = 90; // Multihop attempted
847pub const ENOLINK = 91; // Link has been severed
848pub const EPROTO = 92; // Protocol error
849
850pub const ENOTCAPABLE = 93; // Capabilities insufficient
851pub const ECAPMODE = 94; // Not permitted in capability mode
852pub const ENOTRECOVERABLE = 95; // State not recoverable
853pub const EOWNERDEAD = 96; // Previous owner died
854
855pub const ELAST = 96; // Must be equal largest errno
732pub const E = enum(i32) {
733 /// No error occurred.
734 SUCCESS = 0,
735 PERM = -0x7ffffff1, // Operation not permitted
736 NOENT = -0x7fff9ffd, // No such file or directory
737 SRCH = -0x7fff8ff3, // No such process
738 INTR = -0x7ffffff6, // Interrupted system call
739 IO = -0x7fffffff, // Input/output error
740 NXIO = -0x7fff8ff5, // Device not configured
741 @"2BIG" = -0x7fff8fff, // Argument list too long
742 NOEXEC = -0x7fffecfe, // Exec format error
743 CHILD = -0x7fff8ffe, // No child processes
744 DEADLK = -0x7fff8ffd, // Resource deadlock avoided
745 NOMEM = -0x80000000, // Cannot allocate memory
746 ACCES = -0x7ffffffe, // Permission denied
747 FAULT = -0x7fffecff, // Bad address
748 BUSY = -0x7ffffff2, // Device busy
749 EXIST = -0x7fff9ffe, // File exists
750 XDEV = -0x7fff9ff5, // Cross-device link
751 NODEV = -0x7fff8ff9, // Operation not supported by device
752 NOTDIR = -0x7fff9ffb, // Not a directory
753 ISDIR = -0x7fff9ff7, // Is a directory
754 INVAL = -0x7ffffffb, // Invalid argument
755 NFILE = -0x7fff8ffa, // Too many open files in system
756 MFILE = -0x7fff9ff6, // Too many open files
757 NOTTY = -0x7fff8ff6, // Inappropriate ioctl for device
758 TXTBSY = -0x7fff8fc5, // Text file busy
759 FBIG = -0x7fff8ffc, // File too large
760 NOSPC = -0x7fff9ff9, // No space left on device
761 SPIPE = -0x7fff8ff4, // Illegal seek
762 ROFS = -0x7fff9ff8, // Read-only filesystem
763 MLINK = -0x7fff8ffb, // Too many links
764 PIPE = -0x7fff9ff3, // Broken pipe
765 BADF = -0x7fffa000, // Bad file descriptor
766
767 // math software
768 DOM = 33, // Numerical argument out of domain
769 RANGE = 34, // Result too large
770
771 // non-blocking and interrupt i/o
772
773 /// Also used for `WOULDBLOCK`.
774 AGAIN = -0x7ffffff5,
775 INPROGRESS = -0x7fff8fdc,
776 ALREADY = -0x7fff8fdb,
777
778 // ipc/network software -- argument errors
779 NOTSOCK = 38, // Socket operation on non-socket
780 DESTADDRREQ = 39, // Destination address required
781 MSGSIZE = 40, // Message too long
782 PROTOTYPE = 41, // Protocol wrong type for socket
783 NOPROTOOPT = 42, // Protocol not available
784 PROTONOSUPPORT = 43, // Protocol not supported
785 SOCKTNOSUPPORT = 44, // Socket type not supported
786 /// Also used for `NOTSUP`.
787 OPNOTSUPP = 45, // Operation not supported
788 PFNOSUPPORT = 46, // Protocol family not supported
789 AFNOSUPPORT = 47, // Address family not supported by protocol family
790 ADDRINUSE = 48, // Address already in use
791 ADDRNOTAVAIL = 49, // Can't assign requested address
792
793 // ipc/network software -- operational errors
794 NETDOWN = 50, // Network is down
795 NETUNREACH = 51, // Network is unreachable
796 NETRESET = 52, // Network dropped connection on reset
797 CONNABORTED = 53, // Software caused connection abort
798 CONNRESET = 54, // Connection reset by peer
799 NOBUFS = 55, // No buffer space available
800 ISCONN = 56, // Socket is already connected
801 NOTCONN = 57, // Socket is not connected
802 SHUTDOWN = 58, // Can't send after socket shutdown
803 TOOMANYREFS = 59, // Too many references: can't splice
804 TIMEDOUT = 60, // Operation timed out
805 CONNREFUSED = 61, // Connection refused
806
807 LOOP = 62, // Too many levels of symbolic links
808 NAMETOOLONG = 63, // File name too long
809
810 // should be rearranged
811 HOSTDOWN = 64, // Host is down
812 HOSTUNREACH = 65, // No route to host
813 NOTEMPTY = 66, // Directory not empty
814
815 // quotas & mush
816 PROCLIM = 67, // Too many processes
817 USERS = 68, // Too many users
818 DQUOT = 69, // Disc quota exceeded
819
820 // Network File System
821 STALE = 70, // Stale NFS file handle
822 REMOTE = 71, // Too many levels of remote in path
823 BADRPC = 72, // RPC struct is bad
824 RPCMISMATCH = 73, // RPC version wrong
825 PROGUNAVAIL = 74, // RPC prog. not avail
826 PROGMISMATCH = 75, // Program version wrong
827 PROCUNAVAIL = 76, // Bad procedure for program
828
829 NOLCK = 77, // No locks available
830 NOSYS = 78, // Function not implemented
831
832 FTYPE = 79, // Inappropriate file type or format
833 AUTH = 80, // Authentication error
834 NEEDAUTH = 81, // Need authenticator
835 IDRM = 82, // Identifier removed
836 NOMSG = 83, // No message of desired type
837 OVERFLOW = 84, // Value too large to be stored in data type
838 CANCELED = 85, // Operation canceled
839 ILSEQ = 86, // Illegal byte sequence
840 NOATTR = 87, // Attribute not found
841
842 DOOFUS = 88, // Programming error
843
844 BADMSG = 89, // Bad message
845 MULTIHOP = 90, // Multihop attempted
846 NOLINK = 91, // Link has been severed
847 PROTO = 92, // Protocol error
848
849 NOTCAPABLE = 93, // Capabilities insufficient
850 CAPMODE = 94, // Not permitted in capability mode
851 NOTRECOVERABLE = 95, // State not recoverable
852 OWNERDEAD = 96, // Previous owner died
853
854 _,
855};
856856
857857pub const MINSIGSTKSZ = switch (builtin.cpu.arch) {
858858 .i386, .x86_64 => 2048,
lib/std/os/bits/linux.zig+17-9
......@@ -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.
61const std = @import("../../std.zig");
72const maxInt = std.math.maxInt;
83const arch = @import("builtin").target.cpu.arch;
94pub usingnamespace @import("posix.zig");
105
11pub usingnamespace switch (arch) {
12 .mips, .mipsel => @import("linux/errno-mips.zig"),
13 .sparc, .sparcel, .sparcv9 => @import("linux/errno-sparc.zig"),
14 else => @import("linux/errno-generic.zig"),
6pub const E = switch (arch) {
7 .mips, .mipsel => @import("linux/errno/mips.zig").E,
8 .sparc, .sparcel, .sparcv9 => @import("linux/errno/sparc.zig").E,
9 else => @import("linux/errno/generic.zig").E,
1510};
1611
1712pub usingnamespace switch (arch) {
......@@ -887,6 +882,7 @@ pub const CLONE_VM = 0x00000100;
887882pub const CLONE_FS = 0x00000200;
888883pub const CLONE_FILES = 0x00000400;
889884pub const CLONE_SIGHAND = 0x00000800;
885pub const CLONE_PIDFD = 0x00001000;
890886pub const CLONE_PTRACE = 0x00002000;
891887pub const CLONE_VFORK = 0x00004000;
892888pub const CLONE_PARENT = 0x00008000;
......@@ -911,6 +907,8 @@ pub const CLONE_IO = 0x80000000;
911907
912908/// Clear any signal handler and reset to SIG_DFL.
913909pub const CLONE_CLEAR_SIGHAND = 0x100000000;
910/// Clone into a specific cgroup given the right permissions.
911pub const CLONE_INTO_CGROUP = 0x200000000;
914912
915913// 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);
11311129
11321130pub const empty_sigset = [_]u32{0} ** @typeInfo(sigset_t).Array.len;
11331131
1132pub const SFD_CLOEXEC = O_CLOEXEC;
1133pub const SFD_NONBLOCK = O_NONBLOCK;
1134
11341135pub const signalfd_siginfo = extern struct {
11351136 signo: u32,
11361137 errno: i32,
......@@ -1659,6 +1660,13 @@ pub const io_uring_cqe = extern struct {
16591660 /// result code for this event
16601661 res: i32,
16611662 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 }
16621670};
16631671
16641672// io_uring_cqe.flags
lib/std/os/bits/linux/arm-eabi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// arm-eabi-specific declarations that are intended to be imported into the POSIX namespace.
72const std = @import("../../../std.zig");
83const linux = std.os.linux;
lib/std/os/bits/linux/arm64.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// arm64-specific declarations that are intended to be imported into the POSIX namespace.
72// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// i386-specific declarations that are intended to be imported into the POSIX namespace.
72// This does include Linux-only APIs.
83
lib/std/os/bits/linux/mips.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../../std.zig");
72const linux = std.os.linux;
83const socklen_t = linux.socklen_t;
lib/std/os/bits/linux/netlink.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("../linux.zig");
72
83/// Routing/device hook
lib/std/os/bits/linux/powerpc.zig-6
......@@ -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
71const std = @import("../../../std.zig");
82const linux = std.os.linux;
93const socklen_t = linux.socklen_t;
lib/std/os/bits/linux/powerpc64.zig-6
......@@ -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
71const std = @import("../../../std.zig");
82const linux = std.os.linux;
93const socklen_t = linux.socklen_t;
lib/std/os/bits/linux/prctl.zig-6
......@@ -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
71pub const PR = enum(i32) {
82 SET_PDEATHSIG = 1,
93 GET_PDEATHSIG = 2,
lib/std/os/bits/linux/riscv64.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// riscv64-specific declarations that are intended to be imported into the POSIX namespace.
72const std = @import("../../../std.zig");
83const uid_t = std.os.linux.uid_t;
lib/std/os/bits/linux/securebits.zig-6
......@@ -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
71fn issecure_mask(comptime x: comptime_int) comptime_int {
82 return 1 << x;
93}
lib/std/os/bits/linux/x86_64.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// x86-64-specific declarations that are intended to be imported into the POSIX namespace.
72const std = @import("../../../std.zig");
83const pid_t = linux.pid_t;
lib/std/os/bits/linux/xdp.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("../linux.zig");
72
83pub const XDP_SHARED_UMEM = (1 << 0);
lib/std/os/bits/netbsd.zig+140-139
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const builtin = std.builtin;
83const maxInt = std.math.maxInt;
......@@ -405,8 +400,10 @@ pub const CTL_DEBUG = 5;
405400
406401pub const KERN_PROC_ARGS = 48; // struct: process argv/env
407402pub const KERN_PROC_PATHNAME = 5; // path to executable
403pub const KERN_IOV_MAX = 38;
408404
409405pub const PATH_MAX = 1024;
406pub const IOV_MAX = KERN_IOV_MAX;
410407
411408pub const STDIN_FILENO = 0;
412409pub const STDOUT_FILENO = 1;
......@@ -931,140 +928,144 @@ pub const ucontext_t = extern struct {
931928 ]u32,
932929};
933930
934pub const EPERM = 1; // Operation not permitted
935pub const ENOENT = 2; // No such file or directory
936pub const ESRCH = 3; // No such process
937pub const EINTR = 4; // Interrupted system call
938pub const EIO = 5; // Input/output error
939pub const ENXIO = 6; // Device not configured
940pub const E2BIG = 7; // Argument list too long
941pub const ENOEXEC = 8; // Exec format error
942pub const EBADF = 9; // Bad file descriptor
943pub const ECHILD = 10; // No child processes
944pub const EDEADLK = 11; // Resource deadlock avoided
945// 11 was EAGAIN
946pub const ENOMEM = 12; // Cannot allocate memory
947pub const EACCES = 13; // Permission denied
948pub const EFAULT = 14; // Bad address
949pub const ENOTBLK = 15; // Block device required
950pub const EBUSY = 16; // Device busy
951pub const EEXIST = 17; // File exists
952pub const EXDEV = 18; // Cross-device link
953pub const ENODEV = 19; // Operation not supported by device
954pub const ENOTDIR = 20; // Not a directory
955pub const EISDIR = 21; // Is a directory
956pub const EINVAL = 22; // Invalid argument
957pub const ENFILE = 23; // Too many open files in system
958pub const EMFILE = 24; // Too many open files
959pub const ENOTTY = 25; // Inappropriate ioctl for device
960pub const ETXTBSY = 26; // Text file busy
961pub const EFBIG = 27; // File too large
962pub const ENOSPC = 28; // No space left on device
963pub const ESPIPE = 29; // Illegal seek
964pub const EROFS = 30; // Read-only file system
965pub const EMLINK = 31; // Too many links
966pub const EPIPE = 32; // Broken pipe
967
968// math software
969pub const EDOM = 33; // Numerical argument out of domain
970pub const ERANGE = 34; // Result too large or too small
971
972// non-blocking and interrupt i/o
973pub const EAGAIN = 35; // Resource temporarily unavailable
974pub const EWOULDBLOCK = EAGAIN; // Operation would block
975pub const EINPROGRESS = 36; // Operation now in progress
976pub const EALREADY = 37; // Operation already in progress
977
978// ipc/network software -- argument errors
979pub const ENOTSOCK = 38; // Socket operation on non-socket
980pub const EDESTADDRREQ = 39; // Destination address required
981pub const EMSGSIZE = 40; // Message too long
982pub const EPROTOTYPE = 41; // Protocol wrong type for socket
983pub const ENOPROTOOPT = 42; // Protocol option not available
984pub const EPROTONOSUPPORT = 43; // Protocol not supported
985pub const ESOCKTNOSUPPORT = 44; // Socket type not supported
986pub const EOPNOTSUPP = 45; // Operation not supported
987pub const EPFNOSUPPORT = 46; // Protocol family not supported
988pub const EAFNOSUPPORT = 47; // Address family not supported by protocol family
989pub const EADDRINUSE = 48; // Address already in use
990pub const EADDRNOTAVAIL = 49; // Can't assign requested address
991
992// ipc/network software -- operational errors
993pub const ENETDOWN = 50; // Network is down
994pub const ENETUNREACH = 51; // Network is unreachable
995pub const ENETRESET = 52; // Network dropped connection on reset
996pub const ECONNABORTED = 53; // Software caused connection abort
997pub const ECONNRESET = 54; // Connection reset by peer
998pub const ENOBUFS = 55; // No buffer space available
999pub const EISCONN = 56; // Socket is already connected
1000pub const ENOTCONN = 57; // Socket is not connected
1001pub const ESHUTDOWN = 58; // Can't send after socket shutdown
1002pub const ETOOMANYREFS = 59; // Too many references: can't splice
1003pub const ETIMEDOUT = 60; // Operation timed out
1004pub const ECONNREFUSED = 61; // Connection refused
1005
1006pub const ELOOP = 62; // Too many levels of symbolic links
1007pub const ENAMETOOLONG = 63; // File name too long
1008
1009// should be rearranged
1010pub const EHOSTDOWN = 64; // Host is down
1011pub const EHOSTUNREACH = 65; // No route to host
1012pub const ENOTEMPTY = 66; // Directory not empty
1013
1014// quotas & mush
1015pub const EPROCLIM = 67; // Too many processes
1016pub const EUSERS = 68; // Too many users
1017pub const EDQUOT = 69; // Disc quota exceeded
1018
1019// Network File System
1020pub const ESTALE = 70; // Stale NFS file handle
1021pub const EREMOTE = 71; // Too many levels of remote in path
1022pub const EBADRPC = 72; // RPC struct is bad
1023pub const ERPCMISMATCH = 73; // RPC version wrong
1024pub const EPROGUNAVAIL = 74; // RPC prog. not avail
1025pub const EPROGMISMATCH = 75; // Program version wrong
1026pub const EPROCUNAVAIL = 76; // Bad procedure for program
1027
1028pub const ENOLCK = 77; // No locks available
1029pub const ENOSYS = 78; // Function not implemented
1030
1031pub const EFTYPE = 79; // Inappropriate file type or format
1032pub const EAUTH = 80; // Authentication error
1033pub const ENEEDAUTH = 81; // Need authenticator
1034
1035// SystemV IPC
1036pub const EIDRM = 82; // Identifier removed
1037pub const ENOMSG = 83; // No message of desired type
1038pub const EOVERFLOW = 84; // Value too large to be stored in data type
1039
1040// Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995
1041pub const EILSEQ = 85; // Illegal byte sequence
1042
1043// From IEEE Std 1003.1-2001
1044// Base, Realtime, Threads or Thread Priority Scheduling option errors
1045pub const ENOTSUP = 86; // Not supported
1046
1047// Realtime option errors
1048pub const ECANCELED = 87; // Operation canceled
1049
1050// Realtime, XSI STREAMS option errors
1051pub const EBADMSG = 88; // Bad or Corrupt message
1052
1053// XSI STREAMS option errors
1054pub const ENODATA = 89; // No message available
1055pub const ENOSR = 90; // No STREAM resources
1056pub const ENOSTR = 91; // Not a STREAM
1057pub const ETIME = 92; // STREAM ioctl timeout
1058
1059// File system extended attribute errors
1060pub const ENOATTR = 93; // Attribute not found
1061
1062// Realtime, XSI STREAMS option errors
1063pub const EMULTIHOP = 94; // Multihop attempted
1064pub const ENOLINK = 95; // Link has been severed
1065pub const EPROTO = 96; // Protocol error
1066
1067pub const ELAST = 96; // Must equal largest errno
931pub const E = enum(u16) {
932 /// No error occurred.
933 SUCCESS = 0,
934 PERM = 1, // Operation not permitted
935 NOENT = 2, // No such file or directory
936 SRCH = 3, // No such process
937 INTR = 4, // Interrupted system call
938 IO = 5, // Input/output error
939 NXIO = 6, // Device not configured
940 @"2BIG" = 7, // Argument list too long
941 NOEXEC = 8, // Exec format error
942 BADF = 9, // Bad file descriptor
943 CHILD = 10, // No child processes
944 DEADLK = 11, // Resource deadlock avoided
945 // 11 was AGAIN
946 NOMEM = 12, // Cannot allocate memory
947 ACCES = 13, // Permission denied
948 FAULT = 14, // Bad address
949 NOTBLK = 15, // Block device required
950 BUSY = 16, // Device busy
951 EXIST = 17, // File exists
952 XDEV = 18, // Cross-device link
953 NODEV = 19, // Operation not supported by device
954 NOTDIR = 20, // Not a directory
955 ISDIR = 21, // Is a directory
956 INVAL = 22, // Invalid argument
957 NFILE = 23, // Too many open files in system
958 MFILE = 24, // Too many open files
959 NOTTY = 25, // Inappropriate ioctl for device
960 TXTBSY = 26, // Text file busy
961 FBIG = 27, // File too large
962 NOSPC = 28, // No space left on device
963 SPIPE = 29, // Illegal seek
964 ROFS = 30, // Read-only file system
965 MLINK = 31, // Too many links
966 PIPE = 32, // Broken pipe
967
968 // math software
969 DOM = 33, // Numerical argument out of domain
970 RANGE = 34, // Result too large or too small
971
972 // non-blocking and interrupt i/o
973 // also: WOULDBLOCK: operation would block
974 AGAIN = 35, // Resource temporarily unavailable
975 INPROGRESS = 36, // Operation now in progress
976 ALREADY = 37, // Operation already in progress
977
978 // ipc/network software -- argument errors
979 NOTSOCK = 38, // Socket operation on non-socket
980 DESTADDRREQ = 39, // Destination address required
981 MSGSIZE = 40, // Message too long
982 PROTOTYPE = 41, // Protocol wrong type for socket
983 NOPROTOOPT = 42, // Protocol option not available
984 PROTONOSUPPORT = 43, // Protocol not supported
985 SOCKTNOSUPPORT = 44, // Socket type not supported
986 OPNOTSUPP = 45, // Operation not supported
987 PFNOSUPPORT = 46, // Protocol family not supported
988 AFNOSUPPORT = 47, // Address family not supported by protocol family
989 ADDRINUSE = 48, // Address already in use
990 ADDRNOTAVAIL = 49, // Can't assign requested address
991
992 // ipc/network software -- operational errors
993 NETDOWN = 50, // Network is down
994 NETUNREACH = 51, // Network is unreachable
995 NETRESET = 52, // Network dropped connection on reset
996 CONNABORTED = 53, // Software caused connection abort
997 CONNRESET = 54, // Connection reset by peer
998 NOBUFS = 55, // No buffer space available
999 ISCONN = 56, // Socket is already connected
1000 NOTCONN = 57, // Socket is not connected
1001 SHUTDOWN = 58, // Can't send after socket shutdown
1002 TOOMANYREFS = 59, // Too many references: can't splice
1003 TIMEDOUT = 60, // Operation timed out
1004 CONNREFUSED = 61, // Connection refused
1005
1006 LOOP = 62, // Too many levels of symbolic links
1007 NAMETOOLONG = 63, // File name too long
1008
1009 // should be rearranged
1010 HOSTDOWN = 64, // Host is down
1011 HOSTUNREACH = 65, // No route to host
1012 NOTEMPTY = 66, // Directory not empty
1013
1014 // quotas & mush
1015 PROCLIM = 67, // Too many processes
1016 USERS = 68, // Too many users
1017 DQUOT = 69, // Disc quota exceeded
1018
1019 // Network File System
1020 STALE = 70, // Stale NFS file handle
1021 REMOTE = 71, // Too many levels of remote in path
1022 BADRPC = 72, // RPC struct is bad
1023 RPCMISMATCH = 73, // RPC version wrong
1024 PROGUNAVAIL = 74, // RPC prog. not avail
1025 PROGMISMATCH = 75, // Program version wrong
1026 PROCUNAVAIL = 76, // Bad procedure for program
1027
1028 NOLCK = 77, // No locks available
1029 NOSYS = 78, // Function not implemented
1030
1031 FTYPE = 79, // Inappropriate file type or format
1032 AUTH = 80, // Authentication error
1033 NEEDAUTH = 81, // Need authenticator
1034
1035 // SystemV IPC
1036 IDRM = 82, // Identifier removed
1037 NOMSG = 83, // No message of desired type
1038 OVERFLOW = 84, // Value too large to be stored in data type
1039
1040 // Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995
1041 ILSEQ = 85, // Illegal byte sequence
1042
1043 // From IEEE Std 1003.1-2001
1044 // Base, Realtime, Threads or Thread Priority Scheduling option errors
1045 NOTSUP = 86, // Not supported
1046
1047 // Realtime option errors
1048 CANCELED = 87, // Operation canceled
1049
1050 // Realtime, XSI STREAMS option errors
1051 BADMSG = 88, // Bad or Corrupt message
1052
1053 // XSI STREAMS option errors
1054 NODATA = 89, // No message available
1055 NOSR = 90, // No STREAM resources
1056 NOSTR = 91, // Not a STREAM
1057 TIME = 92, // STREAM ioctl timeout
1058
1059 // File system extended attribute errors
1060 NOATTR = 93, // Attribute not found
1061
1062 // Realtime, XSI STREAMS option errors
1063 MULTIHOP = 94, // Multihop attempted
1064 NOLINK = 95, // Link has been severed
1065 PROTO = 96, // Protocol error
1066
1067 _,
1068};
10681069
10691070pub const MINSIGSTKSZ = 8192;
10701071pub const SIGSTKSZ = MINSIGSTKSZ + 32768;
lib/std/os/bits/openbsd.zig+124-124
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const builtin = std.builtin;
83const maxInt = std.math.maxInt;
......@@ -295,6 +290,7 @@ pub const AI_NUMERICSERV = 16;
295290pub const AI_ADDRCONFIG = 64;
296291
297292pub const PATH_MAX = 1024;
293pub const IOV_MAX = 1024;
298294
299295pub const STDIN_FILENO = 0;
300296pub const STDOUT_FILENO = 1;
......@@ -824,125 +820,129 @@ pub usingnamespace switch (builtin.target.cpu.arch) {
824820pub const sigset_t = c_uint;
825821pub const empty_sigset: sigset_t = 0;
826822
827pub const EPERM = 1; // Operation not permitted
828pub const ENOENT = 2; // No such file or directory
829pub const ESRCH = 3; // No such process
830pub const EINTR = 4; // Interrupted system call
831pub const EIO = 5; // Input/output error
832pub const ENXIO = 6; // Device not configured
833pub const E2BIG = 7; // Argument list too long
834pub const ENOEXEC = 8; // Exec format error
835pub const EBADF = 9; // Bad file descriptor
836pub const ECHILD = 10; // No child processes
837pub const EDEADLK = 11; // Resource deadlock avoided
838// 11 was EAGAIN
839pub const ENOMEM = 12; // Cannot allocate memory
840pub const EACCES = 13; // Permission denied
841pub const EFAULT = 14; // Bad address
842pub const ENOTBLK = 15; // Block device required
843pub const EBUSY = 16; // Device busy
844pub const EEXIST = 17; // File exists
845pub const EXDEV = 18; // Cross-device link
846pub const ENODEV = 19; // Operation not supported by device
847pub const ENOTDIR = 20; // Not a directory
848pub const EISDIR = 21; // Is a directory
849pub const EINVAL = 22; // Invalid argument
850pub const ENFILE = 23; // Too many open files in system
851pub const EMFILE = 24; // Too many open files
852pub const ENOTTY = 25; // Inappropriate ioctl for device
853pub const ETXTBSY = 26; // Text file busy
854pub const EFBIG = 27; // File too large
855pub const ENOSPC = 28; // No space left on device
856pub const ESPIPE = 29; // Illegal seek
857pub const EROFS = 30; // Read-only file system
858pub const EMLINK = 31; // Too many links
859pub const EPIPE = 32; // Broken pipe
860
861// math software
862pub const EDOM = 33; // Numerical argument out of domain
863pub const ERANGE = 34; // Result too large or too small
864
865// non-blocking and interrupt i/o
866pub const EAGAIN = 35; // Resource temporarily unavailable
867pub const EWOULDBLOCK = EAGAIN; // Operation would block
868pub const EINPROGRESS = 36; // Operation now in progress
869pub const EALREADY = 37; // Operation already in progress
870
871// ipc/network software -- argument errors
872pub const ENOTSOCK = 38; // Socket operation on non-socket
873pub const EDESTADDRREQ = 39; // Destination address required
874pub const EMSGSIZE = 40; // Message too long
875pub const EPROTOTYPE = 41; // Protocol wrong type for socket
876pub const ENOPROTOOPT = 42; // Protocol option not available
877pub const EPROTONOSUPPORT = 43; // Protocol not supported
878pub const ESOCKTNOSUPPORT = 44; // Socket type not supported
879pub const EOPNOTSUPP = 45; // Operation not supported
880pub const EPFNOSUPPORT = 46; // Protocol family not supported
881pub const EAFNOSUPPORT = 47; // Address family not supported by protocol family
882pub const EADDRINUSE = 48; // Address already in use
883pub const EADDRNOTAVAIL = 49; // Can't assign requested address
884
885// ipc/network software -- operational errors
886pub const ENETDOWN = 50; // Network is down
887pub const ENETUNREACH = 51; // Network is unreachable
888pub const ENETRESET = 52; // Network dropped connection on reset
889pub const ECONNABORTED = 53; // Software caused connection abort
890pub const ECONNRESET = 54; // Connection reset by peer
891pub const ENOBUFS = 55; // No buffer space available
892pub const EISCONN = 56; // Socket is already connected
893pub const ENOTCONN = 57; // Socket is not connected
894pub const ESHUTDOWN = 58; // Can't send after socket shutdown
895pub const ETOOMANYREFS = 59; // Too many references: can't splice
896pub const ETIMEDOUT = 60; // Operation timed out
897pub const ECONNREFUSED = 61; // Connection refused
898
899pub const ELOOP = 62; // Too many levels of symbolic links
900pub const ENAMETOOLONG = 63; // File name too long
901
902// should be rearranged
903pub const EHOSTDOWN = 64; // Host is down
904pub const EHOSTUNREACH = 65; // No route to host
905pub const ENOTEMPTY = 66; // Directory not empty
906
907// quotas & mush
908pub const EPROCLIM = 67; // Too many processes
909pub const EUSERS = 68; // Too many users
910pub const EDQUOT = 69; // Disc quota exceeded
911
912// Network File System
913pub const ESTALE = 70; // Stale NFS file handle
914pub const EREMOTE = 71; // Too many levels of remote in path
915pub const EBADRPC = 72; // RPC struct is bad
916pub const ERPCMISMATCH = 73; // RPC version wrong
917pub const EPROGUNAVAIL = 74; // RPC prog. not avail
918pub const EPROGMISMATCH = 75; // Program version wrong
919pub const EPROCUNAVAIL = 76; // Bad procedure for program
920
921pub const ENOLCK = 77; // No locks available
922pub const ENOSYS = 78; // Function not implemented
923
924pub const EFTYPE = 79; // Inappropriate file type or format
925pub const EAUTH = 80; // Authentication error
926pub const ENEEDAUTH = 81; // Need authenticator
927pub const EIPSEC = 82; // IPsec processing failure
928pub const ENOATTR = 83; // Attribute not found
929
930// Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995
931pub const EILSEQ = 84; // Illegal byte sequence
932
933pub const ENOMEDIUM = 85; // No medium found
934pub const EMEDIUMTYPE = 86; // Wrong medium type
935pub const EOVERFLOW = 87; // Value too large to be stored in data type
936pub const ECANCELED = 88; // Operation canceled
937pub const EIDRM = 89; // Identifier removed
938pub const ENOMSG = 90; // No message of desired type
939pub const ENOTSUP = 91; // Not supported
940pub const EBADMSG = 92; // Bad or Corrupt message
941pub const ENOTRECOVERABLE = 93; // State not recoverable
942pub const EOWNERDEAD = 94; // Previous owner died
943pub const EPROTO = 95; // Protocol error
944
945pub const ELAST = 95; // Must equal largest errno
823pub const E = enum(u16) {
824 /// No error occurred.
825 SUCCESS = 0,
826 PERM = 1, // Operation not permitted
827 NOENT = 2, // No such file or directory
828 SRCH = 3, // No such process
829 INTR = 4, // Interrupted system call
830 IO = 5, // Input/output error
831 NXIO = 6, // Device not configured
832 @"2BIG" = 7, // Argument list too long
833 NOEXEC = 8, // Exec format error
834 BADF = 9, // Bad file descriptor
835 CHILD = 10, // No child processes
836 DEADLK = 11, // Resource deadlock avoided
837 // 11 was AGAIN
838 NOMEM = 12, // Cannot allocate memory
839 ACCES = 13, // Permission denied
840 FAULT = 14, // Bad address
841 NOTBLK = 15, // Block device required
842 BUSY = 16, // Device busy
843 EXIST = 17, // File exists
844 XDEV = 18, // Cross-device link
845 NODEV = 19, // Operation not supported by device
846 NOTDIR = 20, // Not a directory
847 ISDIR = 21, // Is a directory
848 INVAL = 22, // Invalid argument
849 NFILE = 23, // Too many open files in system
850 MFILE = 24, // Too many open files
851 NOTTY = 25, // Inappropriate ioctl for device
852 TXTBSY = 26, // Text file busy
853 FBIG = 27, // File too large
854 NOSPC = 28, // No space left on device
855 SPIPE = 29, // Illegal seek
856 ROFS = 30, // Read-only file system
857 MLINK = 31, // Too many links
858 PIPE = 32, // Broken pipe
859
860 // math software
861 DOM = 33, // Numerical argument out of domain
862 RANGE = 34, // Result too large or too small
863
864 // non-blocking and interrupt i/o
865 // also: WOULDBLOCK: operation would block
866 AGAIN = 35, // Resource temporarily unavailable
867 INPROGRESS = 36, // Operation now in progress
868 ALREADY = 37, // Operation already in progress
869
870 // ipc/network software -- argument errors
871 NOTSOCK = 38, // Socket operation on non-socket
872 DESTADDRREQ = 39, // Destination address required
873 MSGSIZE = 40, // Message too long
874 PROTOTYPE = 41, // Protocol wrong type for socket
875 NOPROTOOPT = 42, // Protocol option not available
876 PROTONOSUPPORT = 43, // Protocol not supported
877 SOCKTNOSUPPORT = 44, // Socket type not supported
878 OPNOTSUPP = 45, // Operation not supported
879 PFNOSUPPORT = 46, // Protocol family not supported
880 AFNOSUPPORT = 47, // Address family not supported by protocol family
881 ADDRINUSE = 48, // Address already in use
882 ADDRNOTAVAIL = 49, // Can't assign requested address
883
884 // ipc/network software -- operational errors
885 NETDOWN = 50, // Network is down
886 NETUNREACH = 51, // Network is unreachable
887 NETRESET = 52, // Network dropped connection on reset
888 CONNABORTED = 53, // Software caused connection abort
889 CONNRESET = 54, // Connection reset by peer
890 NOBUFS = 55, // No buffer space available
891 ISCONN = 56, // Socket is already connected
892 NOTCONN = 57, // Socket is not connected
893 SHUTDOWN = 58, // Can't send after socket shutdown
894 TOOMANYREFS = 59, // Too many references: can't splice
895 TIMEDOUT = 60, // Operation timed out
896 CONNREFUSED = 61, // Connection refused
897
898 LOOP = 62, // Too many levels of symbolic links
899 NAMETOOLONG = 63, // File name too long
900
901 // should be rearranged
902 HOSTDOWN = 64, // Host is down
903 HOSTUNREACH = 65, // No route to host
904 NOTEMPTY = 66, // Directory not empty
905
906 // quotas & mush
907 PROCLIM = 67, // Too many processes
908 USERS = 68, // Too many users
909 DQUOT = 69, // Disc quota exceeded
910
911 // Network File System
912 STALE = 70, // Stale NFS file handle
913 REMOTE = 71, // Too many levels of remote in path
914 BADRPC = 72, // RPC struct is bad
915 RPCMISMATCH = 73, // RPC version wrong
916 PROGUNAVAIL = 74, // RPC prog. not avail
917 PROGMISMATCH = 75, // Program version wrong
918 PROCUNAVAIL = 76, // Bad procedure for program
919
920 NOLCK = 77, // No locks available
921 NOSYS = 78, // Function not implemented
922
923 FTYPE = 79, // Inappropriate file type or format
924 AUTH = 80, // Authentication error
925 NEEDAUTH = 81, // Need authenticator
926 IPSEC = 82, // IPsec processing failure
927 NOATTR = 83, // Attribute not found
928
929 // Wide/multibyte-character handling, ISO/IEC 9899/AMD1:1995
930 ILSEQ = 84, // Illegal byte sequence
931
932 NOMEDIUM = 85, // No medium found
933 MEDIUMTYPE = 86, // Wrong medium type
934 OVERFLOW = 87, // Value too large to be stored in data type
935 CANCELED = 88, // Operation canceled
936 IDRM = 89, // Identifier removed
937 NOMSG = 90, // No message of desired type
938 NOTSUP = 91, // Not supported
939 BADMSG = 92, // Bad or Corrupt message
940 NOTRECOVERABLE = 93, // State not recoverable
941 OWNERDEAD = 94, // Previous owner died
942 PROTO = 95, // Protocol error
943
944 _,
945};
946946
947947const _MAX_PAGE_SHIFT = switch (builtin.target.cpu.arch) {
948948 .i386 => 12,
lib/std/os/bits/posix.zig-6
......@@ -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
71pub const iovec = extern struct {
82 iov_base: [*]u8,
93 iov_len: usize,
lib/std/os/bits/wasi.zig+85-85
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Convenience types and consts used by std.os module
72const builtin = @import("builtin");
83const posix = @import("posix.zig");
......@@ -76,6 +71,8 @@ pub const kernel_stat = struct {
7671 }
7772};
7873
74pub const IOV_MAX = 1024;
75
7976pub const AT_REMOVEDIR: u32 = 0x4;
8077pub const AT_FDCWD: fd_t = -2;
8178
......@@ -109,86 +106,89 @@ pub const dirent_t = extern struct {
109106 d_type: filetype_t,
110107};
111108
112pub const errno_t = u16;
113pub const ESUCCESS: errno_t = 0;
114pub const E2BIG: errno_t = 1;
115pub const EACCES: errno_t = 2;
116pub const EADDRINUSE: errno_t = 3;
117pub const EADDRNOTAVAIL: errno_t = 4;
118pub const EAFNOSUPPORT: errno_t = 5;
119pub const EAGAIN: errno_t = 6;
120pub const EWOULDBLOCK = EAGAIN;
121pub const EALREADY: errno_t = 7;
122pub const EBADF: errno_t = 8;
123pub const EBADMSG: errno_t = 9;
124pub const EBUSY: errno_t = 10;
125pub const ECANCELED: errno_t = 11;
126pub const ECHILD: errno_t = 12;
127pub const ECONNABORTED: errno_t = 13;
128pub const ECONNREFUSED: errno_t = 14;
129pub const ECONNRESET: errno_t = 15;
130pub const EDEADLK: errno_t = 16;
131pub const EDESTADDRREQ: errno_t = 17;
132pub const EDOM: errno_t = 18;
133pub const EDQUOT: errno_t = 19;
134pub const EEXIST: errno_t = 20;
135pub const EFAULT: errno_t = 21;
136pub const EFBIG: errno_t = 22;
137pub const EHOSTUNREACH: errno_t = 23;
138pub const EIDRM: errno_t = 24;
139pub const EILSEQ: errno_t = 25;
140pub const EINPROGRESS: errno_t = 26;
141pub const EINTR: errno_t = 27;
142pub const EINVAL: errno_t = 28;
143pub const EIO: errno_t = 29;
144pub const EISCONN: errno_t = 30;
145pub const EISDIR: errno_t = 31;
146pub const ELOOP: errno_t = 32;
147pub const EMFILE: errno_t = 33;
148pub const EMLINK: errno_t = 34;
149pub const EMSGSIZE: errno_t = 35;
150pub const EMULTIHOP: errno_t = 36;
151pub const ENAMETOOLONG: errno_t = 37;
152pub const ENETDOWN: errno_t = 38;
153pub const ENETRESET: errno_t = 39;
154pub const ENETUNREACH: errno_t = 40;
155pub const ENFILE: errno_t = 41;
156pub const ENOBUFS: errno_t = 42;
157pub const ENODEV: errno_t = 43;
158pub const ENOENT: errno_t = 44;
159pub const ENOEXEC: errno_t = 45;
160pub const ENOLCK: errno_t = 46;
161pub const ENOLINK: errno_t = 47;
162pub const ENOMEM: errno_t = 48;
163pub const ENOMSG: errno_t = 49;
164pub const ENOPROTOOPT: errno_t = 50;
165pub const ENOSPC: errno_t = 51;
166pub const ENOSYS: errno_t = 52;
167pub const ENOTCONN: errno_t = 53;
168pub const ENOTDIR: errno_t = 54;
169pub const ENOTEMPTY: errno_t = 55;
170pub const ENOTRECOVERABLE: errno_t = 56;
171pub const ENOTSOCK: errno_t = 57;
172pub const ENOTSUP: errno_t = 58;
173pub const EOPNOTSUPP = ENOTSUP;
174pub const ENOTTY: errno_t = 59;
175pub const ENXIO: errno_t = 60;
176pub const EOVERFLOW: errno_t = 61;
177pub const EOWNERDEAD: errno_t = 62;
178pub const EPERM: errno_t = 63;
179pub const EPIPE: errno_t = 64;
180pub const EPROTO: errno_t = 65;
181pub const EPROTONOSUPPORT: errno_t = 66;
182pub const EPROTOTYPE: errno_t = 67;
183pub const ERANGE: errno_t = 68;
184pub const EROFS: errno_t = 69;
185pub const ESPIPE: errno_t = 70;
186pub const ESRCH: errno_t = 71;
187pub const ESTALE: errno_t = 72;
188pub const ETIMEDOUT: errno_t = 73;
189pub const ETXTBSY: errno_t = 74;
190pub const EXDEV: errno_t = 75;
191pub const ENOTCAPABLE: errno_t = 76;
109pub const errno_t = enum(u16) {
110 SUCCESS = 0,
111 @"2BIG" = 1,
112 ACCES = 2,
113 ADDRINUSE = 3,
114 ADDRNOTAVAIL = 4,
115 AFNOSUPPORT = 5,
116 /// This is also the error code used for `WOULDBLOCK`.
117 AGAIN = 6,
118 ALREADY = 7,
119 BADF = 8,
120 BADMSG = 9,
121 BUSY = 10,
122 CANCELED = 11,
123 CHILD = 12,
124 CONNABORTED = 13,
125 CONNREFUSED = 14,
126 CONNRESET = 15,
127 DEADLK = 16,
128 DESTADDRREQ = 17,
129 DOM = 18,
130 DQUOT = 19,
131 EXIST = 20,
132 FAULT = 21,
133 FBIG = 22,
134 HOSTUNREACH = 23,
135 IDRM = 24,
136 ILSEQ = 25,
137 INPROGRESS = 26,
138 INTR = 27,
139 INVAL = 28,
140 IO = 29,
141 ISCONN = 30,
142 ISDIR = 31,
143 LOOP = 32,
144 MFILE = 33,
145 MLINK = 34,
146 MSGSIZE = 35,
147 MULTIHOP = 36,
148 NAMETOOLONG = 37,
149 NETDOWN = 38,
150 NETRESET = 39,
151 NETUNREACH = 40,
152 NFILE = 41,
153 NOBUFS = 42,
154 NODEV = 43,
155 NOENT = 44,
156 NOEXEC = 45,
157 NOLCK = 46,
158 NOLINK = 47,
159 NOMEM = 48,
160 NOMSG = 49,
161 NOPROTOOPT = 50,
162 NOSPC = 51,
163 NOSYS = 52,
164 NOTCONN = 53,
165 NOTDIR = 54,
166 NOTEMPTY = 55,
167 NOTRECOVERABLE = 56,
168 NOTSOCK = 57,
169 /// This is also the code used for `NOTSUP`.
170 OPNOTSUPP = 58,
171 NOTTY = 59,
172 NXIO = 60,
173 OVERFLOW = 61,
174 OWNERDEAD = 62,
175 PERM = 63,
176 PIPE = 64,
177 PROTO = 65,
178 PROTONOSUPPORT = 66,
179 PROTOTYPE = 67,
180 RANGE = 68,
181 ROFS = 69,
182 SPIPE = 70,
183 SRCH = 71,
184 STALE = 72,
185 TIMEDOUT = 73,
186 TXTBSY = 74,
187 XDEV = 75,
188 NOTCAPABLE = 76,
189 _,
190};
191pub const E = errno_t;
192192
193193pub const event_t = extern struct {
194194 userdata: userdata_t,
lib/std/os/bits/windows.zig+90-91
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// The reference for these types and values is Microsoft Windows's ucrt (Universal C RunTime).
72
83usingnamespace @import("../windows/bits.zig");
......@@ -87,93 +82,97 @@ pub const SEEK_SET = 0;
8782pub const SEEK_CUR = 1;
8883pub const SEEK_END = 2;
8984
90pub const EPERM = 1;
91pub const ENOENT = 2;
92pub const ESRCH = 3;
93pub const EINTR = 4;
94pub const EIO = 5;
95pub const ENXIO = 6;
96pub const E2BIG = 7;
97pub const ENOEXEC = 8;
98pub const EBADF = 9;
99pub const ECHILD = 10;
100pub const EAGAIN = 11;
101pub const ENOMEM = 12;
102pub const EACCES = 13;
103pub const EFAULT = 14;
104pub const EBUSY = 16;
105pub const EEXIST = 17;
106pub const EXDEV = 18;
107pub const ENODEV = 19;
108pub const ENOTDIR = 20;
109pub const EISDIR = 21;
110pub const ENFILE = 23;
111pub const EMFILE = 24;
112pub const ENOTTY = 25;
113pub const EFBIG = 27;
114pub const ENOSPC = 28;
115pub const ESPIPE = 29;
116pub const EROFS = 30;
117pub const EMLINK = 31;
118pub const EPIPE = 32;
119pub const EDOM = 33;
120pub const EDEADLK = 36;
121pub const ENAMETOOLONG = 38;
122pub const ENOLCK = 39;
123pub const ENOSYS = 40;
124pub const ENOTEMPTY = 41;
125
126pub const EINVAL = 22;
127pub const ERANGE = 34;
128pub const EILSEQ = 42;
129pub const STRUNCATE = 80;
85pub const E = enum(u16) {
86 /// No error occurred.
87 SUCCESS = 0,
88 PERM = 1,
89 NOENT = 2,
90 SRCH = 3,
91 INTR = 4,
92 IO = 5,
93 NXIO = 6,
94 @"2BIG" = 7,
95 NOEXEC = 8,
96 BADF = 9,
97 CHILD = 10,
98 AGAIN = 11,
99 NOMEM = 12,
100 ACCES = 13,
101 FAULT = 14,
102 BUSY = 16,
103 EXIST = 17,
104 XDEV = 18,
105 NODEV = 19,
106 NOTDIR = 20,
107 ISDIR = 21,
108 NFILE = 23,
109 MFILE = 24,
110 NOTTY = 25,
111 FBIG = 27,
112 NOSPC = 28,
113 SPIPE = 29,
114 ROFS = 30,
115 MLINK = 31,
116 PIPE = 32,
117 DOM = 33,
118 /// Also means `DEADLOCK`.
119 DEADLK = 36,
120 NAMETOOLONG = 38,
121 NOLCK = 39,
122 NOSYS = 40,
123 NOTEMPTY = 41,
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 versions
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;
175pub const STRUNCATE = 80;
177176
178177pub const F_OK = 0;
179178
lib/std/os/darwin.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72pub usingnamespace std.c;
83pub usingnamespace @import("bits.zig");
lib/std/os/dragonfly.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72pub usingnamespace std.c;
83pub usingnamespace @import("bits.zig");
lib/std/os/freebsd.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72pub usingnamespace std.c;
83pub usingnamespace @import("bits.zig");
lib/std/os/haiku.zig-5
......@@ -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.
61const std = @import("../std.zig");
72pub usingnamespace std.c;
83pub usingnamespace @import("bits.zig");
lib/std/os/linux.zig+8-12
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// This file provides the system interface functions for Linux matching those
72// that are provided by libc, whether or not libc is linked. The following
83// abstractions are made:
......@@ -91,9 +86,10 @@ fn splitValue64(val: i64) [2]u32 {
9186}
9287
9388/// 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 {
9590 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);
9793}
9894
9995pub fn dup(old: i32) usize {
......@@ -281,7 +277,7 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of
281277 if (@hasField(SYS, "mmap2")) {
282278 // Make sure the offset is also specified in multiples of page size
283279 if ((offset & (MMAP2_UNIT - 1)) != 0)
284 return @bitCast(usize, @as(isize, -EINVAL));
280 return @bitCast(usize, -@as(isize, @enumToInt(E.INVAL)));
285281
286282 return syscall6(
287283 .mmap2,
......@@ -746,7 +742,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) usize {
746742 const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);
747743 const rc = f(clk_id, tp);
748744 switch (rc) {
749 0, @bitCast(usize, @as(isize, -EINVAL)) => return rc,
745 0, @bitCast(usize, -@as(isize, @enumToInt(E.INVAL))) => return rc,
750746 else => {},
751747 }
752748 }
......@@ -764,7 +760,7 @@ fn init_vdso_clock_gettime(clk: i32, ts: *timespec) callconv(.C) usize {
764760 const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);
765761 return f(clk, ts);
766762 }
767 return @bitCast(usize, @as(isize, -ENOSYS));
763 return @bitCast(usize, -@as(isize, @enumToInt(E.NOSYS)));
768764}
769765
770766pub 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
961957 .sparc, .sparcv9 => syscall5(.rt_sigaction, sig, ksa_arg, oldksa_arg, @ptrToInt(ksa.restorer), mask_size),
962958 else => syscall4(.rt_sigaction, sig, ksa_arg, oldksa_arg, mask_size),
963959 };
964 if (getErrno(result) != 0) return result;
960 if (getErrno(result) != .SUCCESS) return result;
965961
966962 if (oact) |old| {
967963 old.handler.handler = oldksa.handler;
......@@ -1202,7 +1198,7 @@ pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *S
12021198 @ptrToInt(statx_buf),
12031199 );
12041200 }
1205 return @bitCast(usize, @as(isize, -ENOSYS));
1201 return @bitCast(usize, -@as(isize, @enumToInt(E.NOSYS)));
12061202}
12071203
12081204pub fn listxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize {
lib/std/os/linux/arm-eabi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("../bits/linux.zig");
72
83pub fn syscall0(number: SYS) usize {
lib/std/os/linux/arm64.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("../bits/linux.zig");
72
83pub fn syscall0(number: SYS) usize {
lib/std/os/linux/bpf.zig+31-36
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace std.os.linux;
72const std = @import("../../std.zig");
83const errno = getErrno;
......@@ -1508,13 +1503,13 @@ pub fn map_create(map_type: MapType, key_size: u32, value_size: u32, max_entries
15081503 attr.map_create.max_entries = max_entries;
15091504
15101505 const rc = bpf(.map_create, &attr, @sizeOf(MapCreateAttr));
1511 return switch (errno(rc)) {
1512 0 => @intCast(fd_t, rc),
1513 EINVAL => error.MapTypeOrAttrInvalid,
1514 ENOMEM => error.SystemResources,
1515 EPERM => error.AccessDenied,
1516 else => |err| unexpectedErrno(err),
1517 };
1506 switch (errno(rc)) {
1507 .SUCCESS => return @intCast(fd_t, rc),
1508 .INVAL => return error.MapTypeOrAttrInvalid,
1509 .NOMEM => return error.SystemResources,
1510 .PERM => return error.AccessDenied,
1511 else => |err| return unexpectedErrno(err),
1512 }
15181513}
15191514
15201515test "map_create" {
......@@ -1533,12 +1528,12 @@ pub fn map_lookup_elem(fd: fd_t, key: []const u8, value: []u8) !void {
15331528
15341529 const rc = bpf(.map_lookup_elem, &attr, @sizeOf(MapElemAttr));
15351530 switch (errno(rc)) {
1536 0 => return,
1537 EBADF => return error.BadFd,
1538 EFAULT => unreachable,
1539 EINVAL => return error.FieldInAttrNeedsZeroing,
1540 ENOENT => return error.NotFound,
1541 EPERM => return error.AccessDenied,
1531 .SUCCESS => return,
1532 .BADF => return error.BadFd,
1533 .FAULT => unreachable,
1534 .INVAL => return error.FieldInAttrNeedsZeroing,
1535 .NOENT => return error.NotFound,
1536 .PERM => return error.AccessDenied,
15421537 else => |err| return unexpectedErrno(err),
15431538 }
15441539}
......@@ -1555,13 +1550,13 @@ pub fn map_update_elem(fd: fd_t, key: []const u8, value: []const u8, flags: u64)
15551550
15561551 const rc = bpf(.map_update_elem, &attr, @sizeOf(MapElemAttr));
15571552 switch (errno(rc)) {
1558 0 => return,
1559 E2BIG => return error.ReachedMaxEntries,
1560 EBADF => return error.BadFd,
1561 EFAULT => unreachable,
1562 EINVAL => return error.FieldInAttrNeedsZeroing,
1563 ENOMEM => return error.SystemResources,
1564 EPERM => return error.AccessDenied,
1553 .SUCCESS => return,
1554 .@"2BIG" => return error.ReachedMaxEntries,
1555 .BADF => return error.BadFd,
1556 .FAULT => unreachable,
1557 .INVAL => return error.FieldInAttrNeedsZeroing,
1558 .NOMEM => return error.SystemResources,
1559 .PERM => return error.AccessDenied,
15651560 else => |err| return unexpectedErrno(err),
15661561 }
15671562}
......@@ -1576,12 +1571,12 @@ pub fn map_delete_elem(fd: fd_t, key: []const u8) !void {
15761571
15771572 const rc = bpf(.map_delete_elem, &attr, @sizeOf(MapElemAttr));
15781573 switch (errno(rc)) {
1579 0 => return,
1580 EBADF => return error.BadFd,
1581 EFAULT => unreachable,
1582 EINVAL => return error.FieldInAttrNeedsZeroing,
1583 ENOENT => return error.NotFound,
1584 EPERM => return error.AccessDenied,
1574 .SUCCESS => return,
1575 .BADF => return error.BadFd,
1576 .FAULT => unreachable,
1577 .INVAL => return error.FieldInAttrNeedsZeroing,
1578 .NOENT => return error.NotFound,
1579 .PERM => return error.AccessDenied,
15851580 else => |err| return unexpectedErrno(err),
15861581 }
15871582}
......@@ -1639,11 +1634,11 @@ pub fn prog_load(
16391634
16401635 const rc = bpf(.prog_load, &attr, @sizeOf(ProgLoadAttr));
16411636 return switch (errno(rc)) {
1642 0 => @intCast(fd_t, rc),
1643 EACCES => error.UnsafeProgram,
1644 EFAULT => unreachable,
1645 EINVAL => error.InvalidProgram,
1646 EPERM => error.AccessDenied,
1637 .SUCCESS => @intCast(fd_t, rc),
1638 .ACCES => error.UnsafeProgram,
1639 .FAULT => unreachable,
1640 .INVAL => error.InvalidProgram,
1641 .PERM => error.AccessDenied,
16471642 else => |err| unexpectedErrno(err),
16481643 };
16491644}
lib/std/os/linux/bpf/btf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const magic = 0xeb9f;
72const version = 1;
83
lib/std/os/linux/bpf/btf_ext.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const Header = packed struct {
72 magic: u16,
83 version: u8,
lib/std/os/linux/bpf/helpers.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const kern = @import("kern.zig");
72
83// in BPF, all the helper calls
lib/std/os/linux/bpf/kern.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../../std.zig");
72
83const in_bpf_program = switch (std.builtin.cpu.arch) {
lib/std/os/linux/i386.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("../bits/linux.zig");
72
83pub fn syscall0(number: SYS) usize {
lib/std/os/linux/io_uring.zig+44-49
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const assert = std.debug.assert;
83const builtin = std.builtin;
......@@ -54,19 +49,19 @@ pub const IO_Uring = struct {
5449
5550 const res = linux.io_uring_setup(entries, p);
5651 switch (linux.getErrno(res)) {
57 0 => {},
58 linux.EFAULT => return error.ParamsOutsideAccessibleAddressSpace,
52 .SUCCESS => {},
53 .FAULT => return error.ParamsOutsideAccessibleAddressSpace,
5954 // The resv array contains non-zero data, p.flags contains an unsupported flag,
6055 // entries out of bounds, IORING_SETUP_SQ_AFF was specified without IORING_SETUP_SQPOLL,
6156 // or IORING_SETUP_CQSIZE was specified but io_uring_params.cq_entries was invalid:
62 linux.EINVAL => return error.ArgumentsInvalid,
63 linux.EMFILE => return error.ProcessFdQuotaExceeded,
64 linux.ENFILE => return error.SystemFdQuotaExceeded,
65 linux.ENOMEM => return error.SystemResources,
57 .INVAL => return error.ArgumentsInvalid,
58 .MFILE => return error.ProcessFdQuotaExceeded,
59 .NFILE => return error.SystemFdQuotaExceeded,
60 .NOMEM => return error.SystemResources,
6661 // IORING_SETUP_SQPOLL was specified but effective user ID lacks sufficient privileges,
6762 // or a container seccomp policy prohibits io_uring syscalls:
68 linux.EPERM => return error.PermissionDenied,
69 linux.ENOSYS => return error.SystemOutdated,
63 .PERM => return error.PermissionDenied,
64 .NOSYS => return error.SystemOutdated,
7065 else => |errno| return os.unexpectedErrno(errno),
7166 }
7267 const fd = @intCast(os.fd_t, res);
......@@ -180,31 +175,31 @@ pub const IO_Uring = struct {
180175 assert(self.fd >= 0);
181176 const res = linux.io_uring_enter(self.fd, to_submit, min_complete, flags, null);
182177 switch (linux.getErrno(res)) {
183 0 => {},
178 .SUCCESS => {},
184179 // The kernel was unable to allocate memory or ran out of resources for the request.
185180 // The application should wait for some completions and try again:
186 linux.EAGAIN => return error.SystemResources,
181 .AGAIN => return error.SystemResources,
187182 // 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,
189184 // The file descriptor is valid, but the ring is not in the right state.
190185 // See io_uring_register(2) for how to enable the ring.
191 linux.EBADFD => return error.FileDescriptorInBadState,
186 .BADFD => return error.FileDescriptorInBadState,
192187 // The application attempted to overcommit the number of requests it can have pending.
193188 // The application should wait for some completions and try again:
194 linux.EBUSY => return error.CompletionQueueOvercommitted,
189 .BUSY => return error.CompletionQueueOvercommitted,
195190 // 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,
197192 // The buffer is outside the process' accessible address space, or IORING_OP_READ_FIXED
198193 // or IORING_OP_WRITE_FIXED was specified but no buffers were registered, or the range
199194 // described by `addr` and `len` is not within the buffer registered at `buf_index`:
200 linux.EFAULT => return error.BufferInvalid,
201 linux.ENXIO => return error.RingShuttingDown,
195 .FAULT => return error.BufferInvalid,
196 .NXIO => return error.RingShuttingDown,
202197 // The kernel believes our `self.fd` does not refer to an io_uring instance,
203198 // or the opcode is valid but not supported by this kernel (more likely):
204 linux.EOPNOTSUPP => return error.OpcodeNotSupported,
199 .OPNOTSUPP => return error.OpcodeNotSupported,
205200 // The operation was interrupted by a delivery of a signal before it could complete.
206201 // This can happen while waiting for events with IORING_ENTER_GETEVENTS:
207 linux.EINTR => return error.SignalInterrupt,
202 .INTR => return error.SignalInterrupt,
208203 else => |errno| return os.unexpectedErrno(errno),
209204 }
210205 return @intCast(u32, res);
......@@ -681,22 +676,22 @@ pub const IO_Uring = struct {
681676
682677 fn handle_registration_result(res: usize) !void {
683678 switch (linux.getErrno(res)) {
684 0 => {},
679 .SUCCESS => {},
685680 // One or more fds in the array are invalid, or the kernel does not support sparse sets:
686 linux.EBADF => return error.FileDescriptorInvalid,
687 linux.EBUSY => return error.FilesAlreadyRegistered,
688 linux.EINVAL => return error.FilesEmpty,
681 .BADF => return error.FileDescriptorInvalid,
682 .BUSY => return error.FilesAlreadyRegistered,
683 .INVAL => return error.FilesEmpty,
689684 // Adding `nr_args` file references would exceed the maximum allowed number of files the
690685 // user is allowed to have according to the per-user RLIMIT_NOFILE resource limit and
691686 // the CAP_SYS_RESOURCE capability is not set, or `nr_args` exceeds the maximum allowed
692687 // 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,
694689 // Insufficient kernel resources, or the caller had a non-zero RLIMIT_MEMLOCK soft
695690 // resource limit but tried to lock more memory than the limit permitted (not enforced
696691 // when the process is privileged with CAP_IPC_LOCK):
697 linux.ENOMEM => return error.SystemResources,
692 .NOMEM => return error.SystemResources,
698693 // 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,
700695 else => |errno| return os.unexpectedErrno(errno),
701696 }
702697 }
......@@ -706,8 +701,8 @@ pub const IO_Uring = struct {
706701 assert(self.fd >= 0);
707702 const res = linux.io_uring_register(self.fd, .UNREGISTER_FILES, null, 0);
708703 switch (linux.getErrno(res)) {
709 0 => {},
710 linux.ENXIO => return error.FilesNotRegistered,
704 .SUCCESS => {},
705 .NXIO => return error.FilesNotRegistered,
711706 else => |errno| return os.unexpectedErrno(errno),
712707 }
713708 }
......@@ -1272,8 +1267,8 @@ test "write/read" {
12721267 const cqe_read = try ring.copy_cqe();
12731268 // Prior to Linux Kernel 5.6 this is the only way to test for read/write support:
12741269 // https://lwn.net/Articles/809820/
1275 if (cqe_write.res == -linux.EINVAL) return error.SkipZigTest;
1276 if (cqe_read.res == -linux.EINVAL) return error.SkipZigTest;
1270 if (cqe_write.err() == .INVAL) return error.SkipZigTest;
1271 if (cqe_read.err() == .INVAL) return error.SkipZigTest;
12771272 try testing.expectEqual(linux.io_uring_cqe{
12781273 .user_data = 0x11111111,
12791274 .res = buffer_write.len,
......@@ -1322,11 +1317,11 @@ test "openat" {
13221317
13231318 const cqe_openat = try ring.copy_cqe();
13241319 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;
13261321 // AT_FDCWD is not fully supported before kernel 5.6:
13271322 // See https://lore.kernel.org/io-uring/20200207155039.12819-1-axboe@kernel.dk/T/
13281323 // 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) {
13301325 return error.SkipZigTest;
13311326 }
13321327 if (cqe_openat.res <= 0) std.debug.print("\ncqe_openat.res={}\n", .{cqe_openat.res});
......@@ -1357,7 +1352,7 @@ test "close" {
13571352 try testing.expectEqual(@as(u32, 1), try ring.submit());
13581353
13591354 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;
13611356 try testing.expectEqual(linux.io_uring_cqe{
13621357 .user_data = 0x44444444,
13631358 .res = 0,
......@@ -1397,9 +1392,9 @@ test "accept/connect/send/recv" {
13971392 try testing.expectEqual(@as(u32, 1), try ring.submit());
13981393
13991394 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;
14011396 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
14041399 // The accept/connect CQEs may arrive in any order, the connect CQE will sometimes come first:
14051400 if (cqe_accept.user_data == 0xcccccccc and cqe_connect.user_data == 0xaaaaaaaa) {
......@@ -1425,7 +1420,7 @@ test "accept/connect/send/recv" {
14251420 try testing.expectEqual(@as(u32, 2), try ring.submit());
14261421
14271422 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;
14291424 try testing.expectEqual(linux.io_uring_cqe{
14301425 .user_data = 0xeeeeeeee,
14311426 .res = buffer_send.len,
......@@ -1433,7 +1428,7 @@ test "accept/connect/send/recv" {
14331428 }, cqe_send);
14341429
14351430 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;
14371432 try testing.expectEqual(linux.io_uring_cqe{
14381433 .user_data = 0xffffffff,
14391434 .res = buffer_recv.len,
......@@ -1466,7 +1461,7 @@ test "timeout (after a relative time)" {
14661461
14671462 try testing.expectEqual(linux.io_uring_cqe{
14681463 .user_data = 0x55555555,
1469 .res = -linux.ETIME,
1464 .res = -@as(i32, @enumToInt(linux.E.TIME)),
14701465 .flags = 0,
14711466 }, cqe);
14721467
......@@ -1535,14 +1530,14 @@ test "timeout_remove" {
15351530 // We use IORING_FEAT_RW_CUR_POS as a safety check here to make sure we are at least pre-5.6.
15361531 // We don't want to skip this test for newer kernels.
15371532 if (cqe_timeout.user_data == 0x99999999 and
1538 cqe_timeout.res == -linux.EBADF and
1533 cqe_timeout.err() == .BADF and
15391534 (ring.features & linux.IORING_FEAT_RW_CUR_POS) == 0)
15401535 {
15411536 return error.SkipZigTest;
15421537 }
15431538 try testing.expectEqual(linux.io_uring_cqe{
15441539 .user_data = 0x88888888,
1545 .res = -linux.ECANCELED,
1540 .res = -@as(i32, @enumToInt(linux.E.CANCELED)),
15461541 .flags = 0,
15471542 }, cqe_timeout);
15481543
......@@ -1578,15 +1573,15 @@ test "fallocate" {
15781573 try testing.expectEqual(@as(u32, 1), try ring.submit());
15791574
15801575 const cqe = try ring.copy_cqe();
1581 switch (-cqe.res) {
1582 0 => {},
1576 switch (cqe.err()) {
1577 .SUCCESS => {},
15831578 // This kernel's io_uring does not yet implement fallocate():
1584 linux.EINVAL => return error.SkipZigTest,
1579 .INVAL => return error.SkipZigTest,
15851580 // This kernel does not implement fallocate():
1586 linux.ENOSYS => return error.SkipZigTest,
1581 .NOSYS => return error.SkipZigTest,
15871582 // The filesystem containing the file referred to by fd does not support this operation;
15881583 // 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,
15901585 else => |errno| std.debug.panic("unhandled errno: {}", .{errno}),
15911586 }
15921587 try testing.expectEqual(linux.io_uring_cqe{
lib/std/os/linux/mips.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("../bits/linux.zig");
72
83pub fn syscall0(number: SYS) usize {
lib/std/os/linux/powerpc.zig-6
......@@ -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
71usingnamespace @import("../bits/linux.zig");
82
93pub fn syscall0(number: SYS) usize {
lib/std/os/linux/powerpc64.zig-6
......@@ -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
71usingnamespace @import("../bits/linux.zig");
82
93pub fn syscall0(number: SYS) usize {
lib/std/os/linux/riscv64.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("../bits/linux.zig");
72
83pub 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:
169169
170170pub 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 {
173175 return asm volatile ("t 0x6d"
174176 :
175177 : [number] "{g1}" (@enumToInt(SYS.rt_sigreturn))
lib/std/os/linux/test.zig+15-20
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const builtin = std.builtin;
83const linux = std.os.linux;
......@@ -22,9 +17,9 @@ test "fallocate" {
2217
2318 const len: i64 = 65536;
2419 switch (linux.getErrno(linux.fallocate(file.handle, 0, 0, len))) {
25 0 => {},
26 linux.ENOSYS => return error.SkipZigTest,
27 linux.EOPNOTSUPP => return error.SkipZigTest,
20 .SUCCESS => {},
21 .NOSYS => return error.SkipZigTest,
22 .OPNOTSUPP => return error.SkipZigTest,
2823 else => |errno| std.debug.panic("unhandled errno: {}", .{errno}),
2924 }
3025
......@@ -37,11 +32,11 @@ test "getpid" {
3732
3833test "timer" {
3934 const epoll_fd = linux.epoll_create();
40 var err: usize = linux.getErrno(epoll_fd);
41 try expect(err == 0);
35 var err: linux.E = linux.getErrno(epoll_fd);
36 try expect(err == .SUCCESS);
4237
4338 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
4641 const time_interval = linux.timespec{
4742 .tv_sec = 0,
......@@ -53,22 +48,22 @@ test "timer" {
5348 .it_value = time_interval,
5449 };
5550
56 err = linux.timerfd_settime(@intCast(i32, timer_fd), 0, &new_time, null);
57 try expect(err == 0);
51 err = linux.getErrno(linux.timerfd_settime(@intCast(i32, timer_fd), 0, &new_time, null));
52 try expect(err == .SUCCESS);
5853
5954 var event = linux.epoll_event{
6055 .events = linux.EPOLLIN | linux.EPOLLOUT | linux.EPOLLET,
6156 .data = linux.epoll_data{ .ptr = 0 },
6257 };
6358
64 err = linux.epoll_ctl(@intCast(i32, epoll_fd), linux.EPOLL_CTL_ADD, @intCast(i32, timer_fd), &event);
65 try expect(err == 0);
59 err = linux.getErrno(linux.epoll_ctl(@intCast(i32, epoll_fd), linux.EPOLL_CTL_ADD, @intCast(i32, timer_fd), &event));
60 try expect(err == .SUCCESS);
6661
6762 const events_one: linux.epoll_event = undefined;
6863 var events = [_]linux.epoll_event{events_one} ** 8;
6964
70 // TODO implicit cast from *[N]T to [*]T
71 err = linux.epoll_wait(@intCast(i32, epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1);
65 err = linux.getErrno(linux.epoll_wait(@intCast(i32, epoll_fd), &events, 8, -1));
66 try expect(err == .SUCCESS);
7267}
7368
7469test "statx" {
......@@ -81,15 +76,15 @@ test "statx" {
8176
8277 var statx_buf: linux.Statx = undefined;
8378 switch (linux.getErrno(linux.statx(file.handle, "", linux.AT_EMPTY_PATH, linux.STATX_BASIC_STATS, &statx_buf))) {
84 0 => {},
79 .SUCCESS => {},
8580 // The statx syscall was only introduced in linux 4.11
86 linux.ENOSYS => return error.SkipZigTest,
81 .NOSYS => return error.SkipZigTest,
8782 else => unreachable,
8883 }
8984
9085 var stat_buf: linux.kernel_stat = undefined;
9186 switch (linux.getErrno(linux.fstatat(file.handle, "", &stat_buf, linux.AT_EMPTY_PATH))) {
92 0 => {},
87 .SUCCESS => {},
9388 else => unreachable,
9489 }
9590
lib/std/os/linux/thumb.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("../bits/linux.zig");
72
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const os = std.os;
83const mem = std.mem;
lib/std/os/linux/vdso.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72const elf = std.elf;
83const linux = std.os.linux;
lib/std/os/linux/x86_64.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("../bits/linux.zig");
72
83pub fn syscall0(number: SYS) usize {
lib/std/os/netbsd.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72pub usingnamespace std.c;
83pub usingnamespace @import("bits.zig");
lib/std/os/openbsd.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72pub usingnamespace std.c;
83pub usingnamespace @import("bits.zig");
lib/std/os/test.zig+14-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const os = std.os;
83const testing = std.testing;
......@@ -786,3 +781,17 @@ test "dup & dup2" {
786781 var buf: [7]u8 = undefined;
787782 try testing.expectEqualStrings("dupdup2", buf[0..try file.readAll(&buf)]);
788783}
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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72
83/// A protocol is an interface identified by a GUID.
lib/std/os/uefi/protocols.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const LoadedImageProtocol = @import("protocols/loaded_image_protocol.zig").LoadedImageProtocol;
72pub 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Event = uefi.Event;
83const Guid = uefi.Guid;
lib/std/os/uefi/protocols/device_path_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83
lib/std/os/uefi/protocols/edid_active_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83
lib/std/os/uefi/protocols/edid_discovered_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83
lib/std/os/uefi/protocols/edid_override_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Handle = uefi.Handle;
lib/std/os/uefi/protocols/file_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Time = uefi.Time;
lib/std/os/uefi/protocols/graphics_output_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Status = uefi.Status;
lib/std/os/uefi/protocols/hii.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83
lib/std/os/uefi/protocols/hii_database_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Status = uefi.Status;
lib/std/os/uefi/protocols/hii_popup_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Status = uefi.Status;
lib/std/os/uefi/protocols/ip6_config_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Event = uefi.Event;
lib/std/os/uefi/protocols/ip6_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Event = uefi.Event;
lib/std/os/uefi/protocols/ip6_service_binding_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Handle = uefi.Handle;
83const Guid = uefi.Guid;
lib/std/os/uefi/protocols/loaded_image_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Handle = uefi.Handle;
lib/std/os/uefi/protocols/managed_network_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Event = uefi.Event;
lib/std/os/uefi/protocols/managed_network_service_binding_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Handle = uefi.Handle;
83const Guid = uefi.Guid;
lib/std/os/uefi/protocols/rng_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Status = uefi.Status;
lib/std/os/uefi/protocols/shell_parameters_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const FileHandle = uefi.FileHandle;
lib/std/os/uefi/protocols/simple_file_system_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const FileProtocol = uefi.protocols.FileProtocol;
lib/std/os/uefi/protocols/simple_network_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Event = uefi.Event;
83const Guid = uefi.Guid;
lib/std/os/uefi/protocols/simple_pointer_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Event = uefi.Event;
83const Guid = uefi.Guid;
lib/std/os/uefi/protocols/simple_text_input_ex_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Event = uefi.Event;
83const Guid = uefi.Guid;
lib/std/os/uefi/protocols/simple_text_input_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Event = uefi.Event;
83const Guid = uefi.Guid;
lib/std/os/uefi/protocols/simple_text_output_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Status = uefi.Status;
lib/std/os/uefi/protocols/udp6_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const Event = uefi.Event;
lib/std/os/uefi/protocols/udp6_service_binding_protocol.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Handle = uefi.Handle;
83const Guid = uefi.Guid;
lib/std/os/uefi/status.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const high_bit = 1 << @typeInfo(usize).Int.bits - 1;
72
83pub const Status = enum(usize) {
lib/std/os/uefi/tables.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const AllocateType = @import("tables/boot_services.zig").AllocateType;
72pub const BootServices = @import("tables/boot_services.zig").BootServices;
83pub const ConfigurationTable = @import("tables/configuration_table.zig").ConfigurationTable;
lib/std/os/uefi/tables/boot_services.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Event = uefi.Event;
83const Guid = uefi.Guid;
lib/std/os/uefi/tables/configuration_table.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83
lib/std/os/uefi/tables/runtime_services.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const Guid = uefi.Guid;
83const TableHeader = uefi.tables.TableHeader;
lib/std/os/uefi/tables/system_table.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const uefi = @import("std").os.uefi;
72const BootServices = uefi.tables.BootServices;
83const ConfigurationTable = uefi.tables.ConfigurationTable;
lib/std/os/uefi/tables/table_header.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const TableHeader = extern struct {
72 signature: u64,
83 revision: u32,
lib/std/os/wasi.zig+1-6
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// wasi_snapshot_preview1 spec available (in witx format) here:
72// * typenames -- https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/witx/typenames.witx
83// * 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
8378pub extern "wasi_snapshot_preview1" fn sock_shutdown(sock: fd_t, how: sdflags_t) errno_t;
8479
8580/// 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 {
8782 return r;
8883}
lib/std/os/windows.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// This file contains thin wrappers around Windows-specific APIs, with these
72// specific goals in mind:
83// * Convert "errno"-style error codes into Zig errors.
lib/std/os/windows/advapi32.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("bits.zig");
72
83pub extern "advapi32" fn RegOpenKeyExW(
lib/std/os/windows/bits.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Platform-dependent types and values that are used along with OS-specific APIs.
72
83const std = @import("../../std.zig");
lib/std/os/windows/gdi32.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("bits.zig");
72
83pub const PIXELFORMATDESCRIPTOR = extern struct {
lib/std/os/windows/kernel32.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("bits.zig");
72
83pub 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const NEUTRAL = 0x00;
72pub const INVARIANT = 0x7f;
83pub const AFRIKAANS = 0x36;
lib/std/os/windows/ntdll.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("bits.zig");
72
83pub extern "NtDll" fn RtlGetVersion(
lib/std/os/windows/ntstatus.zig-6
......@@ -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
71/// NTSTATUS codes from https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/596a1078-e883-4972-9bbc-49e60bebca55?
82pub const NTSTATUS = enum(u32) {
93 /// The caller specified WaitAny for WaitType and one of the dispatcher
lib/std/os/windows/ole32.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("bits.zig");
72
83pub extern "ole32" fn CoTaskMemFree(pv: LPVOID) callconv(WINAPI) void;
lib/std/os/windows/psapi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("bits.zig");
72
83pub extern "psapi" fn EmptyWorkingSet(hProcess: HANDLE) callconv(WINAPI) BOOL;
lib/std/os/windows/shell32.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("bits.zig");
72
83pub 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const NEUTRAL = 0x00;
72pub const DEFAULT = 0x01;
83pub const SYS_DEFAULT = 0x02;
lib/std/os/windows/test.zig-5
......@@ -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.
61const std = @import("../../std.zig");
72const builtin = @import("builtin");
83const windows = std.os.windows;
lib/std/os/windows/user32.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("bits.zig");
72const std = @import("std");
83const builtin = std.builtin;
lib/std/os/windows/win32error.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Codes are from https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/18d8fbe8-a967-4f1c-ae50-99ca8e491d2d
72pub const Win32Error = enum(u16) {
83 /// The operation completed successfully.
lib/std/os/windows/winmm.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61usingnamespace @import("bits.zig");
72
83pub const MMRESULT = UINT;
lib/std/os/windows/ws2_32.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../../std.zig");
72usingnamespace @import("bits.zig");
83
lib/std/packed_int_array.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = @import("builtin");
83const debug = std.debug;
lib/std/pdb.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = std.builtin;
72const std = @import("std.zig");
83const io = std.io;
lib/std/priority_dequeue.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const Allocator = std.mem.Allocator;
83const assert = std.debug.assert;
lib/std/priority_queue.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const Allocator = std.mem.Allocator;
83const assert = std.debug.assert;
lib/std/process.zig+4-9
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const builtin = std.builtin;
83const os = std.os;
......@@ -93,7 +88,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
9388 var environ_buf_size: usize = undefined;
9489
9590 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) {
9792 return os.unexpectedErrno(environ_sizes_get_ret);
9893 }
9994
......@@ -103,7 +98,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
10398 defer allocator.free(environ_buf);
10499
105100 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) {
107102 return os.unexpectedErrno(environ_get_ret);
108103 }
109104
......@@ -255,7 +250,7 @@ pub const ArgIteratorWasi = struct {
255250 var buf_size: usize = undefined;
256251
257252 switch (w.args_sizes_get(&count, &buf_size)) {
258 w.ESUCCESS => {},
253 .SUCCESS => {},
259254 else => |err| return os.unexpectedErrno(err),
260255 }
261256
......@@ -265,7 +260,7 @@ pub const ArgIteratorWasi = struct {
265260 var argv_buf = try allocator.alloc(u8, buf_size);
266261
267262 switch (w.args_get(argv.ptr, argv_buf.ptr)) {
268 w.ESUCCESS => {},
263 .SUCCESS => {},
269264 else => |err| return os.unexpectedErrno(err),
270265 }
271266
lib/std/rand.zig-6
......@@ -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
71//! The engines provided here should be initialized from an external source.
82//! For a thread-local cryptographically secure pseudo random number generator,
93//! use `std.crypto.random`.
lib/std/rand/Gimli.zig-6
......@@ -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
71//! CSPRNG
82
93const std = @import("std");
lib/std/rand/Isaac64.zig-6
......@@ -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
71//! ISAAC64 - http://www.burtleburtle.net/bob/rand/isaacafa.html
82//!
93//! Follows the general idea of the implementation from here with a few shortcuts.
lib/std/rand/Pcg.zig-6
......@@ -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
71//! PCG32 - http://www.pcg-random.org/
82//!
93//! PRNG
lib/std/rand/Sfc64.zig-6
......@@ -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
71//! Sfc64 pseudo-random number generator from Practically Random.
82//! Fastest engine of pracrand and smallest footprint.
93//! See http://pracrand.sourceforge.net/
lib/std/rand/Xoroshiro128.zig-6
......@@ -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
71//! Xoroshiro128+ - http://xoroshiro.di.unimi.it/
82//!
93//! PRNG
lib/std/rand/Xoshiro256.zig-6
......@@ -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
71//! Xoshiro256++ - http://xoroshiro.di.unimi.it/
82//!
93//! PRNG
lib/std/rand/ziggurat.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Implements ZIGNOR [1].
72//
83// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to Generate Normal Random Samples*]
lib/std/sort.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const assert = std.debug.assert;
83const testing = std.testing;
lib/std/special/build_runner.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const root = @import("@build");
72const std = @import("std");
83const builtin = @import("builtin");
lib/std/special/c.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// This is Zig's multi-target implementation of libc.
72// When builtin.link_libc is true, we need to export all the functions and
83// provide an entire C API.
lib/std/special/compiler_rt.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = std.builtin;
83const is_test = builtin.is_test;
lib/std/special/compiler_rt/addXf3.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// ARM specific builtins
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/ashldi3_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __ashldi3 = @import("shift.zig").__ashldi3;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/ashlti3_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __ashlti3 = @import("shift.zig").__ashlti3;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/ashrdi3_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __ashrdi3 = @import("shift.zig").__ashrdi3;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/ashrti3_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __ashrti3 = @import("shift.zig").__ashrti3;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/atomics.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = std.builtin;
83const arch = std.Target.current.cpu.arch;
lib/std/special/compiler_rt/aulldiv.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72
83pub fn _alldiv(a: i64, b: i64) callconv(.Stdcall) i64 {
lib/std/special/compiler_rt/aullrem.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72
83pub fn _allrem(a: i64, b: i64) callconv(.Stdcall) i64 {
lib/std/special/compiler_rt/clear_cache.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const arch = std.builtin.cpu.arch;
83const os = std.builtin.os.tag;
lib/std/special/compiler_rt/clzsi2.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = std.builtin;
83
lib/std/special/compiler_rt/clzsi2_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const clzsi2 = @import("clzsi2.zig");
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/compareXf2.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/divtf3_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const math = std.math;
83const testing = std.testing;
lib/std/special/compiler_rt/divti3.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const udivmod = @import("udivmod.zig").udivmod;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/divti3_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __divti3 = @import("divti3.zig").__divti3;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/emutls.zig+3-9
......@@ -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.
71// __emutls_get_address specific builtin
82//
93// derived work from LLVM Compiler Infrastructure - release 8.0 (MIT)
......@@ -201,7 +195,7 @@ const current_thread_storage = struct {
201195
202196 /// Initialize pthread_key_t.
203197 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) {
205199 abort();
206200 }
207201 }
......@@ -248,14 +242,14 @@ const emutls_control = extern struct {
248242
249243 /// Simple wrapper for global lock.
250244 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) {
252246 abort();
253247 }
254248 }
255249
256250 /// Simple wrapper for global unlock.
257251 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) {
259253 abort();
260254 }
261255 }
lib/std/special/compiler_rt/extendXfYf2.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = @import("builtin");
83const is_test = builtin.is_test;
lib/std/special/compiler_rt/extendXfYf2_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const __extendhfsf2 = @import("extendXfYf2.zig").__extendhfsf2;
83const __extendhftf2 = @import("extendXfYf2.zig").__extendhftf2;
lib/std/special/compiler_rt/fixdfdi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixint = @import("fixint.zig").fixint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixdfdi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixdfdi = @import("fixdfdi.zig").__fixdfdi;
72const std = @import("std");
83const math = std.math;
lib/std/special/compiler_rt/fixdfsi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixint = @import("fixint.zig").fixint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixdfsi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixdfsi = @import("fixdfsi.zig").__fixdfsi;
72const std = @import("std");
83const math = std.math;
lib/std/special/compiler_rt/fixdfti.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixint = @import("fixint.zig").fixint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixdfti_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixdfti = @import("fixdfti.zig").__fixdfti;
72const std = @import("std");
83const math = std.math;
lib/std/special/compiler_rt/fixint.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const is_test = @import("builtin").is_test;
72const std = @import("std");
83const math = std.math;
lib/std/special/compiler_rt/fixint_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const is_test = @import("builtin").is_test;
72const std = @import("std");
83const math = std.math;
lib/std/special/compiler_rt/fixsfdi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixint = @import("fixint.zig").fixint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixsfdi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixsfdi = @import("fixsfdi.zig").__fixsfdi;
72const std = @import("std");
83const math = std.math;
lib/std/special/compiler_rt/fixsfsi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixint = @import("fixint.zig").fixint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixsfsi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixsfsi = @import("fixsfsi.zig").__fixsfsi;
72const std = @import("std");
83const math = std.math;
lib/std/special/compiler_rt/fixsfti.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixint = @import("fixint.zig").fixint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixsfti_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixsfti = @import("fixsfti.zig").__fixsfti;
72const std = @import("std");
83const math = std.math;
lib/std/special/compiler_rt/fixtfdi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixint = @import("fixint.zig").fixint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixtfdi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixtfdi = @import("fixtfdi.zig").__fixtfdi;
72const std = @import("std");
83const math = std.math;
lib/std/special/compiler_rt/fixtfsi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixint = @import("fixint.zig").fixint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixtfsi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixtfsi = @import("fixtfsi.zig").__fixtfsi;
72const std = @import("std");
83const math = std.math;
lib/std/special/compiler_rt/fixtfti.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixint = @import("fixint.zig").fixint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixtfti_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixtfti = @import("fixtfti.zig").__fixtfti;
72const std = @import("std");
83const math = std.math;
lib/std/special/compiler_rt/fixuint.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const is_test = @import("builtin").is_test;
72const Log2Int = @import("std").math.Log2Int;
83
lib/std/special/compiler_rt/fixunsdfdi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixuint = @import("fixuint.zig").fixuint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunsdfdi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixunsdfdi = @import("fixunsdfdi.zig").__fixunsdfdi;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunsdfsi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixuint = @import("fixuint.zig").fixuint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunsdfsi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixunsdfsi = @import("fixunsdfsi.zig").__fixunsdfsi;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunsdfti.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixuint = @import("fixuint.zig").fixuint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunsdfti_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixunsdfti = @import("fixunsdfti.zig").__fixunsdfti;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunssfdi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixuint = @import("fixuint.zig").fixuint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunssfdi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixunssfdi = @import("fixunssfdi.zig").__fixunssfdi;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunssfsi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixuint = @import("fixuint.zig").fixuint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunssfsi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixunssfsi = @import("fixunssfsi.zig").__fixunssfsi;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunssfti.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixuint = @import("fixuint.zig").fixuint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunssfti_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixunssfti = @import("fixunssfti.zig").__fixunssfti;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunstfdi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixuint = @import("fixuint.zig").fixuint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunstfdi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixunstfdi = @import("fixunstfdi.zig").__fixunstfdi;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunstfsi.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixuint = @import("fixuint.zig").fixuint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunstfsi_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixunstfsi = @import("fixunstfsi.zig").__fixunstfsi;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/fixunstfti.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const fixuint = @import("fixuint.zig").fixuint;
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/fixunstfti_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __fixunstfti = @import("fixunstfti.zig").__fixunstfti;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatXisf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const std = @import("std");
83const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/floatdidf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const std = @import("std");
83
lib/std/special/compiler_rt/floatdidf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floatdidf = @import("floatdidf.zig").__floatdidf;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatdisf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floatdisf = @import("floatXisf.zig").__floatdisf;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatditf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const is_test = builtin.is_test;
83const std = @import("std");
lib/std/special/compiler_rt/floatditf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floatditf = @import("floatditf.zig").__floatditf;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatsiXf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const std = @import("std");
83const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/floattidf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const is_test = builtin.is_test;
83const std = @import("std");
lib/std/special/compiler_rt/floattidf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floattidf = @import("floattidf.zig").__floattidf;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floattisf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floattisf = @import("floatXisf.zig").__floattisf;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floattitf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const is_test = builtin.is_test;
83const std = @import("std");
lib/std/special/compiler_rt/floattitf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floattitf = @import("floattitf.zig").__floattitf;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatundidf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const std = @import("std");
83
lib/std/special/compiler_rt/floatundidf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floatundidf = @import("floatundidf.zig").__floatundidf;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatundisf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const std = @import("std");
83const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/floatunditf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const is_test = builtin.is_test;
83const std = @import("std");
lib/std/special/compiler_rt/floatunditf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floatunditf = @import("floatunditf.zig").__floatunditf;
72
83fn test__floatunditf(a: u64, expected_hi: u64, expected_lo: u64) !void {
lib/std/special/compiler_rt/floatunsidf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const std = @import("std");
83const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/floatunsisf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const std = @import("std");
83const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/floatunsitf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const is_test = builtin.is_test;
83const std = @import("std");
lib/std/special/compiler_rt/floatunsitf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floatunsitf = @import("floatunsitf.zig").__floatunsitf;
72
83fn test__floatunsitf(a: u32, expected_hi: u64, expected_lo: u64) !void {
lib/std/special/compiler_rt/floatuntidf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const is_test = builtin.is_test;
83const std = @import("std");
lib/std/special/compiler_rt/floatuntidf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floatuntidf = @import("floatuntidf.zig").__floatuntidf;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatuntisf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const is_test = builtin.is_test;
83const std = @import("std");
lib/std/special/compiler_rt/floatuntisf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floatuntisf = @import("floatuntisf.zig").__floatuntisf;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/floatuntitf.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const is_test = builtin.is_test;
83const std = @import("std");
lib/std/special/compiler_rt/floatuntitf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __floatuntitf = @import("floatuntitf.zig").__floatuntitf;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/int.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Builtin functions that operate on integer types
72const builtin = @import("builtin");
83const testing = @import("std").testing;
lib/std/special/compiler_rt/lshrdi3_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __lshrdi3 = @import("shift.zig").__lshrdi3;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/lshrti3_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __lshrti3 = @import("shift.zig").__lshrti3;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/modti3.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __modti3 = @import("modti3.zig").__modti3;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/mulXf3.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Ported from:
72//
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const is_test = std.builtin.is_test;
83const native_endian = std.Target.current.cpu.arch.endian();
lib/std/special/compiler_rt/muldi3_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __muldi3 = @import("muldi3.zig").__muldi3;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/mulodi4.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const compiler_rt = @import("../compiler_rt.zig");
83const maxInt = std.math.maxInt;
lib/std/special/compiler_rt/mulodi4_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __mulodi4 = @import("mulodi4.zig").__mulodi4;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/muloti4.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const compiler_rt = @import("../compiler_rt.zig");
83
lib/std/special/compiler_rt/muloti4_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __muloti4 = @import("muloti4.zig").__muloti4;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/multi3.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const compiler_rt = @import("../compiler_rt.zig");
72const std = @import("std");
83const is_test = std.builtin.is_test;
lib/std/special/compiler_rt/multi3_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __multi3 = @import("multi3.zig").__multi3;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/negXf2.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72
83pub fn __negsf2(a: f32) callconv(.C) f32 {
lib/std/special/compiler_rt/popcountdi2.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const compiler_rt = @import("../compiler_rt.zig");
83
lib/std/special/compiler_rt/popcountdi2_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __popcountdi2 = @import("popcountdi2.zig").__popcountdi2;
72const testing = @import("std").testing;
83
lib/std/special/compiler_rt/shift.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const Log2Int = std.math.Log2Int;
83const native_endian = std.Target.current.cpu.arch.endian();
lib/std/special/compiler_rt/sparc.zig-5
......@@ -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.
61//
72// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const native_arch = @import("std").Target.current.cpu.arch;
72
83// 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// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72
83pub fn __truncsfhf2(a: f32) callconv(.C) u16 {
lib/std/special/compiler_rt/truncXfYf2_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const __truncsfhf2 = @import("truncXfYf2.zig").__truncsfhf2;
72
83fn test__truncsfhf2(a: u32, expected: u16) !void {
lib/std/special/compiler_rt/udivmod.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const is_test = builtin.is_test;
83const native_endian = @import("std").Target.current.cpu.arch.endian();
lib/std/special/compiler_rt/udivmoddi4_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Disable formatting to avoid unnecessary source repository bloat.
72// zig fmt: off
83const __udivmoddi4 = @import("int.zig").__udivmoddi4;
lib/std/special/compiler_rt/udivmodti4.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const udivmod = @import("udivmod.zig").udivmod;
72const builtin = @import("builtin");
83const compiler_rt = @import("../compiler_rt.zig");
lib/std/special/compiler_rt/udivmodti4_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// Disable formatting to avoid unnecessary source repository bloat.
72// zig fmt: off
83const __udivmodti4 = @import("udivmodti4.zig").__udivmodti4;
lib/std/special/compiler_rt/udivti3.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const udivmodti4 = @import("udivmodti4.zig");
72const builtin = @import("builtin");
83
lib/std/special/compiler_rt/umodti3.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const udivmodti4 = @import("udivmodti4.zig");
72const builtin = @import("builtin");
83const compiler_rt = @import("../compiler_rt.zig");
lib/std/special/ssp.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61//
72// Small Zig reimplementation of gcc's libssp.
83//
lib/std/special/test_runner.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const io = std.io;
83const builtin = @import("builtin");
lib/std/start.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61// This file is included in the compilation unit when exporting an executable.
72
83const root = @import("root");
lib/std/start_windows_tls.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = @import("builtin");
83
lib/std/std.zig+1-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61pub const ArrayHashMap = array_hash_map.ArrayHashMap;
72pub const ArrayHashMapUnmanaged = array_hash_map.ArrayHashMapUnmanaged;
83pub const ArrayList = @import("array_list.zig").ArrayList;
......@@ -13,6 +8,7 @@ pub const AutoArrayHashMap = array_hash_map.AutoArrayHashMap;
138pub const AutoArrayHashMapUnmanaged = array_hash_map.AutoArrayHashMapUnmanaged;
149pub const AutoHashMap = hash_map.AutoHashMap;
1510pub const AutoHashMapUnmanaged = hash_map.AutoHashMapUnmanaged;
11pub const BoundedArray = @import("bounded_array.zig").BoundedArray;
1612pub const BufMap = @import("buf_map.zig").BufMap;
1713pub const BufSet = @import("buf_set.zig").BufSet;
1814pub const ChildProcess = @import("child_process.zig").ChildProcess;
lib/std/target.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const mem = std.mem;
83const builtin = std.builtin;
lib/std/testing.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72
83const math = std.math;
lib/std/testing/failing_allocator.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const mem = std.mem;
83
lib/std/time.zig+1-6
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const builtin = std.builtin;
83const assert = std.debug.assert;
......@@ -92,7 +87,7 @@ pub fn nanoTimestamp() i128 {
9287 if (builtin.os.tag == .wasi and !builtin.link_libc) {
9388 var ns: os.wasi.timestamp_t = undefined;
9489 const err = os.wasi.clock_time_get(os.wasi.CLOCK_REALTIME, 1, &ns);
95 assert(err == os.wasi.ESUCCESS);
90 assert(err == .SUCCESS);
9691 return ns;
9792 }
9893 var ts: os.timespec = undefined;
lib/std/time/epoch.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61//! Epoch reference times in terms of their difference from
72//! UTC 1970-01-01 in seconds.
83
lib/std/unicode.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("./std.zig");
72const builtin = std.builtin;
83const assert = std.debug.assert;
lib/std/unicode/throughput_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const builtin = std.builtin;
83const time = std.time;
lib/std/valgrind.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const builtin = @import("builtin");
72const std = @import("std.zig");
83const math = std.math;
lib/std/valgrind/callgrind.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const valgrind = std.valgrind;
83
lib/std/valgrind/memcheck.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const testing = std.testing;
83const valgrind = std.valgrind;
lib/std/wasm.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const testing = @import("std.zig").testing;
72
83// TODO: Add support for multi-byte ops (e.g. table operations)
lib/std/x.zig-6
......@@ -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
71const std = @import("std.zig");
82
93pub const os = struct {
lib/std/x/net/ip.zig-6
......@@ -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
71const std = @import("../../std.zig");
82
93const fmt = std.fmt;
lib/std/x/net/tcp.zig-6
......@@ -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
71const std = @import("../../std.zig");
82
93const io = std.io;
lib/std/x/os/net.zig-6
......@@ -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
71const std = @import("../../std.zig");
82
93const os = std.os;
lib/std/x/os/socket.zig-6
......@@ -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
71const std = @import("../../std.zig");
82const net = @import("net.zig");
93
lib/std/x/os/socket_posix.zig+49-55
......@@ -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
71const std = @import("../../std.zig");
82
93const os = std.os;
......@@ -82,32 +76,32 @@ pub fn Mixin(comptime Socket: type) type {
8276 while (true) {
8377 const rc = os.system.sendmsg(self.fd, &msg, @intCast(c_int, flags));
8478 return switch (os.errno(rc)) {
85 0 => return @intCast(usize, rc),
86 os.EACCES => error.AccessDenied,
87 os.EAGAIN => error.WouldBlock,
88 os.EALREADY => error.FastOpenAlreadyInProgress,
89 os.EBADF => unreachable, // always a race condition
90 os.ECONNRESET => error.ConnectionResetByPeer,
91 os.EDESTADDRREQ => 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.
93 os.EINTR => continue,
94 os.EINVAL => unreachable, // Invalid argument passed.
95 os.EISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified
96 os.EMSGSIZE => error.MessageTooBig,
97 os.ENOBUFS => error.SystemResources,
98 os.ENOMEM => error.SystemResources,
99 os.ENOTSOCK => 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.
101 os.EPIPE => error.BrokenPipe,
102 os.EAFNOSUPPORT => error.AddressFamilyNotSupported,
103 os.ELOOP => error.SymLinkLoop,
104 os.ENAMETOOLONG => error.NameTooLong,
105 os.ENOENT => error.FileNotFound,
106 os.ENOTDIR => error.NotDir,
107 os.EHOSTUNREACH => error.NetworkUnreachable,
108 os.ENETUNREACH => error.NetworkUnreachable,
109 os.ENOTCONN => error.SocketNotConnected,
110 os.ENETDOWN => error.NetworkSubsystemFailed,
79 .SUCCESS => return @intCast(usize, rc),
80 .ACCES => error.AccessDenied,
81 .AGAIN => error.WouldBlock,
82 .ALREADY => error.FastOpenAlreadyInProgress,
83 .BADF => unreachable, // always a race condition
84 .CONNRESET => error.ConnectionResetByPeer,
85 .DESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set.
86 .FAULT => unreachable, // An invalid user space address was specified for an argument.
87 .INTR => continue,
88 .INVAL => unreachable, // Invalid argument passed.
89 .ISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified
90 .MSGSIZE => error.MessageTooBig,
91 .NOBUFS => error.SystemResources,
92 .NOMEM => error.SystemResources,
93 .NOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
94 .OPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type.
95 .PIPE => error.BrokenPipe,
96 .AFNOSUPPORT => error.AddressFamilyNotSupported,
97 .LOOP => error.SymLinkLoop,
98 .NAMETOOLONG => error.NameTooLong,
99 .NOENT => error.FileNotFound,
100 .NOTDIR => error.NotDir,
101 .HOSTUNREACH => error.NetworkUnreachable,
102 .NETUNREACH => error.NetworkUnreachable,
103 .NOTCONN => error.SocketNotConnected,
104 .NETDOWN => error.NetworkSubsystemFailed,
111105 else => |err| os.unexpectedErrno(err),
112106 };
113107 }
......@@ -120,17 +114,17 @@ pub fn Mixin(comptime Socket: type) type {
120114 while (true) {
121115 const rc = os.system.recvmsg(self.fd, msg, @intCast(c_int, flags));
122116 return switch (os.errno(rc)) {
123 0 => @intCast(usize, rc),
124 os.EBADF => unreachable, // always a race condition
125 os.EFAULT => unreachable,
126 os.EINVAL => unreachable,
127 os.ENOTCONN => unreachable,
128 os.ENOTSOCK => unreachable,
129 os.EINTR => continue,
130 os.EAGAIN => error.WouldBlock,
131 os.ENOMEM => error.SystemResources,
132 os.ECONNREFUSED => error.ConnectionRefused,
133 os.ECONNRESET => error.ConnectionResetByPeer,
117 .SUCCESS => @intCast(usize, rc),
118 .BADF => unreachable, // always a race condition
119 .FAULT => unreachable,
120 .INVAL => unreachable,
121 .NOTCONN => unreachable,
122 .NOTSOCK => unreachable,
123 .INTR => continue,
124 .AGAIN => error.WouldBlock,
125 .NOMEM => error.SystemResources,
126 .CONNREFUSED => error.ConnectionRefused,
127 .CONNRESET => error.ConnectionResetByPeer,
134128 else => |err| os.unexpectedErrno(err),
135129 };
136130 }
......@@ -164,12 +158,12 @@ pub fn Mixin(comptime Socket: type) type {
164158
165159 const rc = os.system.getsockopt(self.fd, os.SOL_SOCKET, os.SO_RCVBUF, mem.asBytes(&value), &value_len);
166160 return switch (os.errno(rc)) {
167 0 => value,
168 os.EBADF => error.BadFileDescriptor,
169 os.EFAULT => error.InvalidAddressSpace,
170 os.EINVAL => error.InvalidSocketOption,
171 os.ENOPROTOOPT => error.UnknownSocketOption,
172 os.ENOTSOCK => error.NotASocket,
161 .SUCCESS => value,
162 .BADF => error.BadFileDescriptor,
163 .FAULT => error.InvalidAddressSpace,
164 .INVAL => error.InvalidSocketOption,
165 .NOPROTOOPT => error.UnknownSocketOption,
166 .NOTSOCK => error.NotASocket,
173167 else => |err| os.unexpectedErrno(err),
174168 };
175169 }
......@@ -181,12 +175,12 @@ pub fn Mixin(comptime Socket: type) type {
181175
182176 const rc = os.system.getsockopt(self.fd, os.SOL_SOCKET, os.SO_SNDBUF, mem.asBytes(&value), &value_len);
183177 return switch (os.errno(rc)) {
184 0 => value,
185 os.EBADF => error.BadFileDescriptor,
186 os.EFAULT => error.InvalidAddressSpace,
187 os.EINVAL => error.InvalidSocketOption,
188 os.ENOPROTOOPT => error.UnknownSocketOption,
189 os.ENOTSOCK => error.NotASocket,
178 .SUCCESS => value,
179 .BADF => error.BadFileDescriptor,
180 .FAULT => error.InvalidAddressSpace,
181 .INVAL => error.InvalidSocketOption,
182 .NOPROTOOPT => error.UnknownSocketOption,
183 .NOTSOCK => error.NotASocket,
190184 else => |err| os.unexpectedErrno(err),
191185 };
192186 }
lib/std/x/os/socket_windows.zig-6
......@@ -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
71const std = @import("../../std.zig");
82const net = @import("net.zig");
93
lib/std/zig.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std.zig");
72const tokenizer = @import("zig/tokenizer.zig");
83const fmt = @import("zig/fmt.zig");
lib/std/zig/ast.zig-21
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const assert = std.debug.assert;
83const testing = std.testing;
......@@ -351,10 +346,6 @@ pub const Tree = struct {
351346 .char_literal,
352347 .integer_literal,
353348 .float_literal,
354 .false_literal,
355 .true_literal,
356 .null_literal,
357 .undefined_literal,
358349 .unreachable_literal,
359350 .string_literal,
360351 .multiline_string_literal,
......@@ -716,10 +707,6 @@ pub const Tree = struct {
716707 .char_literal,
717708 .integer_literal,
718709 .float_literal,
719 .false_literal,
720 .true_literal,
721 .null_literal,
722 .undefined_literal,
723710 .unreachable_literal,
724711 .identifier,
725712 .deref,
......@@ -2762,14 +2749,6 @@ pub const Node = struct {
27622749 /// Both lhs and rhs unused.
27632750 float_literal,
27642751 /// 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.
27732752 unreachable_literal,
27742753 /// Both lhs and rhs unused.
27752754 /// Most identifiers will not have explicit AST nodes, however for expressions
lib/std/zig/c_builtins.zig-6
......@@ -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
71const std = @import("std");
82
93pub inline fn __builtin_bswap16(val: u16) u16 {
lib/std/zig/c_translation.zig-6
......@@ -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
71const std = @import("std");
82const testing = std.testing;
93const math = std.math;
lib/std/zig/cross_target.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const assert = std.debug.assert;
83const Target = std.Target;
lib/std/zig/parse.zig-41
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const assert = std.debug.assert;
83const Allocator = std.mem.Allocator;
......@@ -2231,11 +2226,7 @@ const Parser = struct {
22312226 /// / INTEGER
22322227 /// / KEYWORD_comptime TypeExpr
22332228 /// / KEYWORD_error DOT IDENTIFIER
2234 /// / KEYWORD_false
2235 /// / KEYWORD_null
22362229 /// / KEYWORD_anyframe
2237 /// / KEYWORD_true
2238 /// / KEYWORD_undefined
22392230 /// / KEYWORD_unreachable
22402231 /// / STRINGLITERAL
22412232 /// / SwitchExpr
......@@ -2278,38 +2269,6 @@ const Parser = struct {
22782269 .rhs = undefined,
22792270 },
22802271 }),
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 }),
23132272 .keyword_unreachable => return p.addNode(.{
23142273 .tag = .unreachable_literal,
23152274 .main_token = p.nextToken(),
lib/std/zig/parser_test.zig-6
......@@ -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
71test "zig fmt: preserves clobbers in inline asm with stray comma" {
82 try testTransform(
93 \\fn foo() void {
lib/std/zig/perf_test.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const mem = std.mem;
83const warn = std.debug.warn;
lib/std/zig/render.zig-9
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const assert = std.debug.assert;
83const mem = std.mem;
......@@ -192,11 +187,7 @@ fn renderExpression(gpa: *Allocator, ais: *Ais, tree: ast.Tree, node: ast.Node.I
192187 .integer_literal,
193188 .float_literal,
194189 .char_literal,
195 .true_literal,
196 .false_literal,
197 .null_literal,
198190 .unreachable_literal,
199 .undefined_literal,
200191 .anyframe_literal,
201192 .string_literal,
202193 => return renderToken(ais, tree, main_tokens[node], space),
lib/std/zig/string_literal.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const assert = std.debug.assert;
83
lib/std/zig/system.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const elf = std.elf;
83const mem = std.mem;
lib/std/zig/system/darwin.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const mem = std.mem;
83const Allocator = mem.Allocator;
lib/std/zig/system/darwin/macos.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const assert = std.debug.assert;
83const mem = std.mem;
lib/std/zig/system/windows.zig-5
......@@ -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.
61const std = @import("std");
72
83pub const WindowsVersion = std.Target.Os.WindowsVersion;
lib/std/zig/system/x86.zig-5
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("std");
72const Target = std.Target;
83const CrossTarget = std.zig.CrossTarget;
lib/std/zig/tokenizer.zig-17
......@@ -1,8 +1,3 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2021 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
61const std = @import("../std.zig");
72const mem = std.mem;
83
......@@ -37,7 +32,6 @@ pub const Token = struct {
3732 .{ "error", .keyword_error },
3833 .{ "export", .keyword_export },
3934 .{ "extern", .keyword_extern },
40 .{ "false", .keyword_false },
4135 .{ "fn", .keyword_fn },
4236 .{ "for", .keyword_for },
4337 .{ "if", .keyword_if },
......@@ -45,7 +39,6 @@ pub const Token = struct {
4539 .{ "noalias", .keyword_noalias },
4640 .{ "noinline", .keyword_noinline },
4741 .{ "nosuspend", .keyword_nosuspend },
48 .{ "null", .keyword_null },
4942 .{ "opaque", .keyword_opaque },
5043 .{ "or", .keyword_or },
5144 .{ "orelse", .keyword_orelse },
......@@ -59,9 +52,7 @@ pub const Token = struct {
5952 .{ "switch", .keyword_switch },
6053 .{ "test", .keyword_test },
6154 .{ "threadlocal", .keyword_threadlocal },
62 .{ "true", .keyword_true },
6355 .{ "try", .keyword_try },
64 .{ "undefined", .keyword_undefined },
6556 .{ "union", .keyword_union },
6657 .{ "unreachable", .keyword_unreachable },
6758 .{ "usingnamespace", .keyword_usingnamespace },
......@@ -162,7 +153,6 @@ pub const Token = struct {
162153 keyword_error,
163154 keyword_export,
164155 keyword_extern,
165 keyword_false,
166156 keyword_fn,
167157 keyword_for,
168158 keyword_if,
......@@ -170,7 +160,6 @@ pub const Token = struct {
170160 keyword_noalias,
171161 keyword_noinline,
172162 keyword_nosuspend,
173 keyword_null,
174163 keyword_opaque,
175164 keyword_or,
176165 keyword_orelse,
......@@ -184,9 +173,7 @@ pub const Token = struct {
184173 keyword_switch,
185174 keyword_test,
186175 keyword_threadlocal,
187 keyword_true,
188176 keyword_try,
189 keyword_undefined,
190177 keyword_union,
191178 keyword_unreachable,
192179 keyword_usingnamespace,
......@@ -285,7 +272,6 @@ pub const Token = struct {
285272 .keyword_error => "error",
286273 .keyword_export => "export",
287274 .keyword_extern => "extern",
288 .keyword_false => "false",
289275 .keyword_fn => "fn",
290276 .keyword_for => "for",
291277 .keyword_if => "if",
......@@ -293,7 +279,6 @@ pub const Token = struct {
293279 .keyword_noalias => "noalias",
294280 .keyword_noinline => "noinline",
295281 .keyword_nosuspend => "nosuspend",
296 .keyword_null => "null",
297282 .keyword_opaque => "opaque",
298283 .keyword_or => "or",
299284 .keyword_orelse => "orelse",
......@@ -307,9 +292,7 @@ pub const Token = struct {
307292 .keyword_switch => "switch",
308293 .keyword_test => "test",
309294 .keyword_threadlocal => "threadlocal",
310 .keyword_true => "true",
311295 .keyword_try => "try",
312 .keyword_undefined => "undefined",
313296 .keyword_union => "union",
314297 .keyword_unreachable => "unreachable",
315298 .keyword_usingnamespace => "usingnamespace",
src/Air.zig+31-2
......@@ -94,6 +94,12 @@ pub const Inst = struct {
9494 /// Result type is the same as both operands.
9595 /// Uses the `bin_op` field.
9696 bit_or,
97 /// Shift right. `>>`
98 /// Uses the `bin_op` field.
99 shr,
100 /// Shift left. `<<`
101 /// Uses the `bin_op` field.
102 shl,
97103 /// Bitwise XOR. `^`
98104 /// Uses the `bin_op` field.
99105 xor,
......@@ -258,6 +264,13 @@ pub const Inst = struct {
258264 /// Given a pointer to a struct and a field index, returns a pointer to the field.
259265 /// Uses the `ty_pl` field, payload is `StructField`.
260266 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,
261274 /// Given a byval struct and a field index, returns the field byval.
262275 /// Uses the `ty_pl` field, payload is `StructField`.
263276 struct_field_val,
......@@ -280,6 +293,10 @@ pub const Inst = struct {
280293 /// Result type is the element type of the pointer operand.
281294 /// Uses the `bin_op` field.
282295 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,
283300 /// Given a pointer to a pointer, and element index, return the element value of the inner
284301 /// pointer at that index.
285302 /// Result type is the element type of the inner pointer operand.
......@@ -404,6 +421,11 @@ pub const StructField = struct {
404421 field_index: u32,
405422};
406423
424pub const Bin = struct {
425 lhs: Inst.Ref,
426 rhs: Inst.Ref,
427};
428
407429/// Trailing:
408430/// 0. `Inst.Ref` for every outputs_len
409431/// 1. `Inst.Ref` for every inputs_len
......@@ -445,6 +467,8 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {
445467 .xor,
446468 .ptr_add,
447469 .ptr_sub,
470 .shr,
471 .shl,
448472 => return air.typeOf(datas[inst].bin_op.lhs),
449473
450474 .cmp_lt,
......@@ -474,6 +498,7 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {
474498 .constant,
475499 .struct_field_ptr,
476500 .struct_field_val,
501 .ptr_elem_ptr,
477502 => return air.getRefType(datas[inst].ty_pl.ty),
478503
479504 .not,
......@@ -492,6 +517,10 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {
492517 .wrap_errunion_payload,
493518 .wrap_errunion_err,
494519 .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,
495524 => return air.getRefType(datas[inst].ty_op.ty),
496525
497526 .loop,
......@@ -519,8 +548,8 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {
519548 },
520549
521550 .slice_elem_val, .ptr_elem_val => {
522 const slice_ty = air.typeOf(datas[inst].bin_op.lhs);
523 return slice_ty.elemType();
551 const ptr_ty = air.typeOf(datas[inst].bin_op.lhs);
552 return ptr_ty.elemType();
524553 },
525554 .ptr_slice_elem_val, .ptr_ptr_elem_val => {
526555 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
370370 .bool_not,
371371 .address_of,
372372 .float_literal,
373 .undefined_literal,
374 .true_literal,
375 .false_literal,
376 .null_literal,
377373 .optional_type,
378374 .block,
379375 .block_semicolon,
......@@ -698,7 +694,13 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr
698694 .lhs = lhs,
699695 .start = start,
700696 });
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 }
702704 },
703705 .slice => {
704706 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
710712 .start = start,
711713 .end = end,
712714 });
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 }
714722 },
715723 .slice_sentinel => {
716724 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
724732 .end = end,
725733 .sentinel = sentinel,
726734 });
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 }
728742 },
729743
730744 .deref => {
......@@ -741,10 +755,6 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr
741755 const result = try expr(gz, scope, .ref, node_datas[node].lhs);
742756 return rvalue(gz, rl, result, node);
743757 },
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),
748758 .optional_type => {
749759 const operand = try typeExpr(gz, scope, node_datas[node].lhs);
750760 const result = try gz.addUnNode(.optional_type, operand, node);
......@@ -2367,7 +2377,7 @@ fn varDecl(
23672377 }
23682378 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
23722382 if (var_decl.ast.init_node == 0) {
23732383 return astgen.failNode(node, "variables must be initialized", .{});
......@@ -2873,7 +2883,7 @@ fn fnDecl(
28732883 };
28742884 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
28782888 // We insert this at the beginning so that its instruction index marks the
28792889 // start of the top level declaration.
......@@ -2934,12 +2944,13 @@ fn fnDecl(
29342944 } else false;
29352945
29362946 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))
29382949 break :blk 0;
29392950
29402951 const param_name = try astgen.identAsString(name_token);
29412952 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);
29432954 }
29442955 break :blk param_name;
29452956 } else if (!is_extern) {
......@@ -3142,7 +3153,7 @@ fn globalVarDecl(
31423153 const name_token = var_decl.ast.mut_token + 1;
31433154 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
31473158 var block_scope: GenZir = .{
31483159 .parent = scope,
......@@ -5017,7 +5028,7 @@ fn ifExpr(
50175028 const token_name_str = tree.tokenSlice(token_name_index);
50185029 if (mem.eql(u8, "_", token_name_str))
50195030 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);
50215032 payload_val_scope = .{
50225033 .parent = &then_scope.base,
50235034 .gen_zir = &then_scope,
......@@ -5036,11 +5047,12 @@ fn ifExpr(
50365047 .optional_payload_unsafe_ptr
50375048 else
50385049 .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))
50405052 break :s &then_scope.base;
50415053 const payload_inst = try then_scope.addUnNode(tag, cond.inst, node);
50425054 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);
50445056 payload_val_scope = .{
50455057 .parent = &then_scope.base,
50465058 .gen_zir = &then_scope,
......@@ -5082,7 +5094,7 @@ fn ifExpr(
50825094 const error_token_str = tree.tokenSlice(error_token);
50835095 if (mem.eql(u8, "_", error_token_str))
50845096 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);
50865098 payload_val_scope = .{
50875099 .parent = &else_scope.base,
50885100 .gen_zir = &else_scope,
......@@ -5273,11 +5285,12 @@ fn whileExpr(
52735285 .err_union_payload_unsafe;
52745286 const payload_inst = try then_scope.addUnNode(tag, cond.inst, node);
52755287 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))
52775290 break :s &then_scope.base;
52785291 const payload_name_loc = payload_token + @boolToInt(payload_is_ref);
52795292 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);
52815294 payload_val_scope = .{
52825295 .parent = &then_scope.base,
52835296 .gen_zir = &then_scope,
......@@ -5298,9 +5311,10 @@ fn whileExpr(
52985311 .optional_payload_unsafe;
52995312 const payload_inst = try then_scope.addUnNode(tag, cond.inst, node);
53005313 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))
53025316 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);
53045318 payload_val_scope = .{
53055319 .parent = &then_scope.base,
53065320 .gen_zir = &then_scope,
......@@ -5356,9 +5370,10 @@ fn whileExpr(
53565370 .err_union_code;
53575371 const payload_inst = try else_scope.addUnNode(tag, cond.inst, node);
53585372 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, "_"))
53605375 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);
53625377 payload_val_scope = .{
53635378 .parent = &else_scope.base,
53645379 .gen_zir = &else_scope,
......@@ -5418,12 +5433,19 @@ fn forExpr(
54185433 if (for_full.label_token) |label_token| {
54195434 try astgen.checkLabelRedefinition(scope, label_token);
54205435 }
5436
54215437 // Set up variables and constants.
54225438 const is_inline = parent_gz.force_comptime or for_full.inline_token != null;
54235439 const tree = astgen.tree;
54245440 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);
54275449 const len = try parent_gz.addUnNode(.indexable_ptr_len, array_ptr, for_full.ast.cond_expr);
54285450
54295451 const index_ptr = blk: {
......@@ -5498,7 +5520,7 @@ fn forExpr(
54985520 const name_str_index = try astgen.identAsString(ident);
54995521 const tag: Zir.Inst.Tag = if (is_ptr) .elem_ptr else .elem_val;
55005522 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);
55025524 payload_val_scope = .{
55035525 .parent = &then_scope.base,
55045526 .gen_zir = &then_scope,
......@@ -5518,11 +5540,12 @@ fn forExpr(
55185540 ident + 2
55195541 else
55205542 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, "_")) {
55225545 return astgen.failTok(index_token, "discard of index capture; omit it instead", .{});
55235546 }
55245547 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);
55265549 index_scope = .{
55275550 .parent = payload_sub_scope,
55285551 .gen_zir = &then_scope,
......@@ -6294,34 +6317,36 @@ fn identifier(
62946317 }
62956318 const ident_name = try astgen.identifierTokenString(ident_token);
62966319
6297 if (simple_types.get(ident_name)) |zir_const_ref| {
6298 return rvalue(gz, rl, zir_const_ref, ident);
6299 }
6320 if (ident_name_raw[0] != '@') {
6321 if (simple_types.get(ident_name)) |zir_const_ref| {
6322 return rvalue(gz, rl, zir_const_ref, ident);
6323 }
63006324
6301 if (ident_name.len >= 2) integer: {
6302 const first_c = ident_name[0];
6303 if (first_c == 'i' or first_c == 'u') {
6304 const signedness: std.builtin.Signedness = switch (first_c == 'i') {
6305 true => .signed,
6306 false => .unsigned,
6307 };
6308 const bit_count = std.fmt.parseInt(u16, ident_name[1..], 10) catch |err| switch (err) {
6309 error.Overflow => return astgen.failNode(
6310 ident,
6311 "primitive integer type '{s}' exceeds maximum bit width of 65535",
6312 .{ident_name},
6313 ),
6314 error.InvalidCharacter => break :integer,
6315 };
6316 const result = try gz.add(.{
6317 .tag = .int_type,
6318 .data = .{ .int_type = .{
6319 .src_node = gz.nodeIndexToRelative(ident),
6320 .signedness = signedness,
6321 .bit_count = bit_count,
6322 } },
6323 });
6324 return rvalue(gz, rl, result, ident);
6325 if (ident_name.len >= 2) integer: {
6326 const first_c = ident_name[0];
6327 if (first_c == 'i' or first_c == 'u') {
6328 const signedness: std.builtin.Signedness = switch (first_c == 'i') {
6329 true => .signed,
6330 false => .unsigned,
6331 };
6332 const bit_count = std.fmt.parseInt(u16, ident_name[1..], 10) catch |err| switch (err) {
6333 error.Overflow => return astgen.failNode(
6334 ident,
6335 "primitive integer type '{s}' exceeds maximum bit width of 65535",
6336 .{ident_name},
6337 ),
6338 error.InvalidCharacter => break :integer,
6339 };
6340 const result = try gz.add(.{
6341 .tag = .int_type,
6342 .data = .{ .int_type = .{
6343 .src_node = gz.nodeIndexToRelative(ident),
6344 .signedness = signedness,
6345 .bit_count = bit_count,
6346 } },
6347 });
6348 return rvalue(gz, rl, result, ident);
6349 }
63256350 }
63266351 }
63276352
......@@ -7102,38 +7127,38 @@ fn builtinCall(
71027127 .bit_size_of => return simpleUnOpType(gz, scope, rl, node, params[0], .bit_size_of),
71037128 .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),
7106 .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),
7108 .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),
7110 .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),
7112 .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),
7114 .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),
7116 .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),
7118 .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),
7120 .sin => return simpleUnOp(gz, scope, rl, node, .none, params[0], .sin),
7121 .cos => return simpleUnOp(gz, scope, rl, node, .none, params[0], .cos),
7122 .exp => return simpleUnOp(gz, scope, rl, node, .none, params[0], .exp),
7123 .exp2 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .exp2),
7124 .log => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log),
7125 .log2 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log2),
7126 .log10 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log10),
7127 .fabs => return simpleUnOp(gz, scope, rl, node, .none, params[0], .fabs),
7128 .floor => return simpleUnOp(gz, scope, rl, node, .none, params[0], .floor),
7129 .ceil => return simpleUnOp(gz, scope, rl, node, .none, params[0], .ceil),
7130 .trunc => return simpleUnOp(gz, scope, rl, node, .none, params[0], .trunc),
7131 .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),
7133 .Type => return simpleUnOp(gz, scope, rl, node, .none, params[0], .reify),
7134 .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),
7136 .frame_size => return simpleUnOp(gz, scope, rl, node, .none, params[0], .frame_size),
7130 .ptr_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .ptr_to_int),
7131 .error_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .error_to_int),
7132 .int_to_error => return simpleUnOp(gz, scope, rl, node, .{ .ty = .u16_type }, params[0], .int_to_error),
7133 .compile_error => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .compile_error),
7134 .set_eval_branch_quota => return simpleUnOp(gz, scope, rl, node, .{ .ty = .u32_type }, params[0], .set_eval_branch_quota),
7135 .enum_to_int => return simpleUnOp(gz, scope, rl, node, .none, params[0], .enum_to_int),
7136 .bool_to_int => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .bool_to_int),
7137 .embed_file => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .embed_file),
7138 .error_name => return simpleUnOp(gz, scope, rl, node, .{ .ty = .anyerror_type }, params[0], .error_name),
7139 .panic => return simpleUnOp(gz, scope, rl, node, .{ .ty = .const_slice_u8_type }, params[0], .panic),
7140 .set_align_stack => return simpleUnOp(gz, scope, rl, node, align_rl, params[0], .set_align_stack),
7141 .set_cold => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .set_cold),
7142 .set_float_mode => return simpleUnOp(gz, scope, rl, node, .{ .coerced_ty = .float_mode_type }, params[0], .set_float_mode),
7143 .set_runtime_safety => return simpleUnOp(gz, scope, rl, node, bool_rl, params[0], .set_runtime_safety),
7144 .sqrt => return simpleUnOp(gz, scope, rl, node, .none, params[0], .sqrt),
7145 .sin => return simpleUnOp(gz, scope, rl, node, .none, params[0], .sin),
7146 .cos => return simpleUnOp(gz, scope, rl, node, .none, params[0], .cos),
7147 .exp => return simpleUnOp(gz, scope, rl, node, .none, params[0], .exp),
7148 .exp2 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .exp2),
7149 .log => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log),
7150 .log2 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log2),
7151 .log10 => return simpleUnOp(gz, scope, rl, node, .none, params[0], .log10),
7152 .fabs => return simpleUnOp(gz, scope, rl, node, .none, params[0], .fabs),
7153 .floor => return simpleUnOp(gz, scope, rl, node, .none, params[0], .floor),
7154 .ceil => return simpleUnOp(gz, scope, rl, node, .none, params[0], .ceil),
7155 .trunc => return simpleUnOp(gz, scope, rl, node, .none, params[0], .trunc),
7156 .round => return simpleUnOp(gz, scope, rl, node, .none, params[0], .round),
7157 .tag_name => return simpleUnOp(gz, scope, rl, node, .none, params[0], .tag_name),
7158 .Type => return simpleUnOp(gz, scope, rl, node, .{ .coerced_ty = .type_info_type }, params[0], .reify),
7159 .type_name => return simpleUnOp(gz, scope, rl, node, .none, params[0], .type_name),
7160 .Frame => return simpleUnOp(gz, scope, rl, node, .none, params[0], .frame_type),
7161 .frame_size => return simpleUnOp(gz, scope, rl, node, .none, params[0], .frame_size),
71377162
71387163 .float_to_int => return typeCast(gz, scope, rl, node, params[0], params[1], .float_to_int),
71397164 .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)
78197844 .string_literal,
78207845 .multiline_string_literal,
78217846 .char_literal,
7822 .true_literal,
7823 .false_literal,
7824 .null_literal,
7825 .undefined_literal,
78267847 .unreachable_literal,
78277848 .identifier,
78287849 .error_set_decl,
......@@ -8059,10 +8080,6 @@ fn nodeMayEvalToError(tree: *const ast.Tree, start_node: ast.Node.Index) enum {
80598080 .string_literal,
80608081 .multiline_string_literal,
80618082 .char_literal,
8062 .true_literal,
8063 .false_literal,
8064 .null_literal,
8065 .undefined_literal,
80668083 .unreachable_literal,
80678084 .error_set_decl,
80688085 .container_decl,
......@@ -8232,10 +8249,6 @@ fn nodeImpliesRuntimeBits(tree: *const ast.Tree, start_node: ast.Node.Index) boo
82328249 .string_literal,
82338250 .multiline_string_literal,
82348251 .char_literal,
8235 .true_literal,
8236 .false_literal,
8237 .null_literal,
8238 .undefined_literal,
82398252 .unreachable_literal,
82408253 .identifier,
82418254 .error_set_decl,
......@@ -10006,8 +10019,21 @@ fn declareNewName(
1000610019 start_scope: *Scope,
1000710020 name_index: u32,
1000810021 node: ast.Node.Index,
10022 name_token: ast.TokenIndex,
1000910023) !void {
1001010024 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
1001110037 var scope = start_scope;
1001210038 while (true) {
1001310039 switch (scope.tag) {
......@@ -10019,7 +10045,7 @@ fn declareNewName(
1001910045 const ns = scope.cast(Scope.Namespace).?;
1002010046 const gop = try ns.decls.getOrPut(gpa, name_index);
1002110047 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)));
1002310049 defer gpa.free(name);
1002410050 return astgen.failNodeNotes(node, "redeclaration of '{s}'", .{
1002510051 name,
......@@ -10035,21 +10061,45 @@ fn declareNewName(
1003510061 }
1003610062}
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.
1003910078fn detectLocalShadowing(
1004010079 astgen: *AstGen,
1004110080 scope: *Scope,
1004210081 ident_name: u32,
1004310082 name_token: ast.TokenIndex,
10083 token_bytes: []const u8,
1004410084) !void {
1004510085 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
1004710096 var s = scope;
1004810097 while (true) switch (s.tag) {
1004910098 .local_val => {
1005010099 const local_val = s.cast(Scope.LocalVal).?;
1005110100 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);
1005310103 defer gpa.free(name);
1005410104 return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{
1005510105 @tagName(local_val.id_cat), name,
......@@ -10066,7 +10116,8 @@ fn detectLocalShadowing(
1006610116 .local_ptr => {
1006710117 const local_ptr = s.cast(Scope.LocalPtr).?;
1006810118 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);
1007010121 defer gpa.free(name);
1007110122 return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{
1007210123 @tagName(local_ptr.id_cat), name,
......@@ -10086,7 +10137,8 @@ fn detectLocalShadowing(
1008610137 s = ns.parent;
1008710138 continue;
1008810139 };
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);
1009010142 defer gpa.free(name);
1009110143 return astgen.failTokNotes(name_token, "local shadows declaration of '{s}'", .{
1009210144 name,
src/Compilation.zig+1
......@@ -2557,6 +2557,7 @@ pub fn cImport(comp: *Compilation, c_src: []const u8) !CImportResult {
25572557 var argv = std.ArrayList([]const u8).init(comp.gpa);
25582558 defer argv.deinit();
25592559
2560 try argv.append(""); // argv[0] is program name, actual args start at [1]
25602561 try comp.addTranslateCCArgs(arena, &argv, .c, out_dep_path);
25612562
25622563 try argv.append(out_h_path);
src/Liveness.zig+10
......@@ -249,6 +249,8 @@ fn analyzeInst(
249249 .ptr_slice_elem_val,
250250 .ptr_elem_val,
251251 .ptr_ptr_elem_val,
252 .shl,
253 .shr,
252254 => {
253255 const o = inst_datas[inst].bin_op;
254256 return trackOperands(a, new_set, inst, main_tomb, .{ o.lhs, o.rhs, .none });
......@@ -280,6 +282,10 @@ fn analyzeInst(
280282 .wrap_errunion_err,
281283 .slice_ptr,
282284 .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,
283289 => {
284290 const o = inst_datas[inst].ty_op;
285291 return trackOperands(a, new_set, inst, main_tomb, .{ o.operand, .none, .none });
......@@ -328,6 +334,10 @@ fn analyzeInst(
328334 const extra = a.air.extraData(Air.StructField, inst_datas[inst].ty_pl.payload).data;
329335 return trackOperands(a, new_set, inst, main_tomb, .{ extra.struct_operand, .none, .none });
330336 },
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 },
331341 .br => {
332342 const br = inst_datas[inst].br;
333343 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) = .{},
6666/// to the same function.
6767monomorphed_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
6973/// We optimize memory usage for a compilation with no compile errors by storing the
7074/// error messages and mapping outside of `Decl`.
7175/// The ErrorMsg memory is owned by the decl, using Module's general purpose allocator.
......@@ -157,6 +161,60 @@ const MonomorphedFuncsContext = struct {
157161 }
158162};
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
160218/// A `Module` has zero or one of these depending on whether `-femit-h` is enabled.
161219pub const GlobalEmitH = struct {
162220 /// Where to put the output.
......@@ -554,8 +612,8 @@ pub const Decl = struct {
554612 assert(struct_obj.owner_decl == decl);
555613 return &struct_obj.namespace;
556614 },
557 .enum_full => {
558 const enum_obj = ty.castTag(.enum_full).?.data;
615 .enum_full, .enum_nonexhaustive => {
616 const enum_obj = ty.cast(Type.Payload.EnumFull).?.data;
559617 assert(enum_obj.owner_decl == decl);
560618 return &enum_obj.namespace;
561619 },
......@@ -660,6 +718,7 @@ pub const Struct = struct {
660718 /// is necessary to determine whether it has bits at runtime.
661719 known_has_bits: bool,
662720
721 /// The `Type` and `Value` memory is owned by the arena of the Struct's owner_decl.
663722 pub const Field = struct {
664723 /// Uses `noreturn` to indicate `anytype`.
665724 /// undefined until `status` is `have_field_types` or `have_layout`.
......@@ -2254,15 +2313,26 @@ pub fn deinit(mod: *Module) void {
22542313 }
22552314 mod.export_owners.deinit(gpa);
22562315
2257 var it = mod.global_error_set.keyIterator();
2258 while (it.next()) |key| {
2259 gpa.free(key.*);
2316 {
2317 var it = mod.global_error_set.keyIterator();
2318 while (it.next()) |key| {
2319 gpa.free(key.*);
2320 }
2321 mod.global_error_set.deinit(gpa);
22602322 }
2261 mod.global_error_set.deinit(gpa);
22622323
22632324 mod.error_name_list.deinit(gpa);
22642325 mod.test_functions.deinit(gpa);
22652326 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 }
22662336}
22672337
22682338fn freeExportList(gpa: *Allocator, export_list: []*Export) void {
......@@ -3091,6 +3161,9 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
30913161 if (linksection_ref == .none) break :blk Value.initTag(.null_value);
30923162 break :blk (try sema.resolveInstConst(&block_scope, src, linksection_ref)).val;
30933163 };
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.
30943167 try sema.resolveTypeLayout(&block_scope, src, decl_tv.ty);
30953168
30963169 // 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 {
31933266 if (type_changed and mod.emit_h != null) {
31943267 try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl });
31953268 }
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);
31963278 }
31973279
31983280 if (decl.is_exported) {
......@@ -4024,7 +4106,6 @@ pub fn createAnonymousDeclFromDeclNamed(
40244106 new_decl.ty = typed_value.ty;
40254107 new_decl.val = typed_value.val;
40264108 new_decl.has_tv = true;
4027 new_decl.owns_tv = true;
40284109 new_decl.analysis = .complete;
40294110 new_decl.generation = mod.generation;
40304111
......@@ -4450,309 +4531,6 @@ pub const PeerTypeCandidateSrc = union(enum) {
44504531 }
44514532};
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
47564534/// Called from `performAllTheWork`, after all AstGen workers have finished,
47574535/// and before the main semantic analysis loop begins.
47584536pub fn processOutdatedAndDeletedDecls(mod: *Module) !void {
src/Sema.zig+768-180
......@@ -649,6 +649,24 @@ fn resolveValue(
649649 return sema.failWithNeededComptime(block, src);
650650}
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
652670/// Will not return Value Tags: `variable`, `undef`. Instead they will emit compile errors.
653671/// See `resolveValue` for an alternative.
654672fn resolveConstValue(
......@@ -866,6 +884,7 @@ fn zirStructDecl(
866884 .ty = Type.initTag(.type),
867885 .val = struct_val,
868886 }, type_name);
887 new_decl.owns_tv = true;
869888 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
870889 struct_obj.* = .{
871890 .owner_decl = new_decl,
......@@ -986,6 +1005,7 @@ fn zirEnumDecl(
9861005 .ty = Type.initTag(.type),
9871006 .val = enum_val,
9881007 }, type_name);
1008 new_decl.owns_tv = true;
9891009 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
9901010
9911011 enum_obj.* = .{
......@@ -1032,25 +1052,27 @@ fn zirEnumDecl(
10321052 // We create a block for the field type instructions because they
10331053 // may need to reference Decls from inside the enum namespace.
10341054 // Within the field type, default value, and alignment expressions, the "owner decl"
1035 // should be the enum itself. Thus we need a new Sema.
1036 var enum_sema: Sema = .{
1037 .mod = mod,
1038 .gpa = gpa,
1039 .arena = &new_decl_arena.allocator,
1040 .code = sema.code,
1041 .inst_map = sema.inst_map,
1042 .owner_decl = new_decl,
1043 .namespace = &enum_obj.namespace,
1044 .owner_func = null,
1045 .func = null,
1046 .fn_ret_ty = Type.initTag(.void),
1047 .branch_quota = sema.branch_quota,
1048 .branch_count = sema.branch_count,
1049 };
1055 // should be the enum itself.
1056
1057 const prev_owner_decl = sema.owner_decl;
1058 sema.owner_decl = new_decl;
1059 defer sema.owner_decl = prev_owner_decl;
1060
1061 const prev_namespace = sema.namespace;
1062 sema.namespace = &enum_obj.namespace;
1063 defer sema.namespace = prev_namespace;
1064
1065 const prev_owner_func = sema.owner_func;
1066 sema.owner_func = null;
1067 defer sema.owner_func = prev_owner_func;
1068
1069 const prev_func = sema.func;
1070 sema.func = null;
1071 defer sema.func = prev_func;
10501072
10511073 var enum_block: Scope.Block = .{
10521074 .parent = null,
1053 .sema = &enum_sema,
1075 .sema = sema,
10541076 .src_decl = new_decl,
10551077 .instructions = .{},
10561078 .inlining = null,
......@@ -1059,11 +1081,8 @@ fn zirEnumDecl(
10591081 defer assert(enum_block.instructions.items.len == 0); // should all be comptime instructions
10601082
10611083 if (body.len != 0) {
1062 _ = try enum_sema.analyzeBody(&enum_block, body);
1084 _ = try sema.analyzeBody(&enum_block, body);
10631085 }
1064
1065 sema.branch_count = enum_sema.branch_count;
1066 sema.branch_quota = enum_sema.branch_quota;
10671086 }
10681087 var bit_bag_index: usize = body_end;
10691088 var cur_bit_bag: u32 = undefined;
......@@ -1153,6 +1172,7 @@ fn zirUnionDecl(
11531172 .ty = Type.initTag(.type),
11541173 .val = union_val,
11551174 }, type_name);
1175 new_decl.owns_tv = true;
11561176 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
11571177 union_obj.* = .{
11581178 .owner_decl = new_decl,
......@@ -1224,6 +1244,7 @@ fn zirErrorSetDecl(
12241244 .ty = Type.initTag(.type),
12251245 .val = error_set_val,
12261246 }, type_name);
1247 new_decl.owns_tv = true;
12271248 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
12281249 const names = try new_decl_arena.allocator.alloc([]const u8, fields.len);
12291250 for (fields) |str_index, i| {
......@@ -1466,8 +1487,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Inde
14661487 const ptr = sema.resolveInst(inst_data.operand);
14671488 const ptr_inst = Air.refToIndex(ptr).?;
14681489 assert(sema.air_instructions.items(.tag)[ptr_inst] == .constant);
1469 const air_datas = sema.air_instructions.items(.data);
1470 const value_index = air_datas[ptr_inst].ty_pl.payload;
1490 const value_index = sema.air_instructions.items(.data)[ptr_inst].ty_pl.payload;
14711491 const ptr_val = sema.air_values.items[value_index];
14721492 const var_is_mut = switch (sema.typeOf(ptr).tag()) {
14731493 .inferred_alloc_const => false,
......@@ -1481,7 +1501,8 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Inde
14811501
14821502 const final_elem_ty = try decl.ty.copy(sema.arena);
14831503 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
14861507 if (var_is_mut) {
14871508 sema.air_values.items[value_index] = try Value.Tag.decl_ref_mut.create(sema.arena, .{
......@@ -2562,6 +2583,19 @@ fn analyzeCall(
25622583 defer merges.results.deinit(gpa);
25632584 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
25652599 try sema.emitBackwardBranch(&child_block, call_src);
25662600
25672601 // This will have return instructions analyzed as break instructions to
......@@ -2586,12 +2620,32 @@ fn analyzeCall(
25862620 const arg_src = call_src; // TODO: better source location
25872621 const casted_arg = try sema.coerce(&child_block, param_ty, uncasted_args[arg_i], arg_src);
25882622 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
25892632 arg_i += 1;
25902633 continue;
25912634 },
25922635 .param_anytype, .param_anytype_comptime => {
25932636 // 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
25952649 arg_i += 1;
25962650 continue;
25972651 },
......@@ -2623,8 +2677,61 @@ fn analyzeCall(
26232677 sema.fn_ret_ty = fn_ret_ty;
26242678 defer sema.fn_ret_ty = parent_fn_ret_ty;
26252679
2626 _ = try sema.analyzeBody(&child_block, fn_info.body);
2627 break :res try sema.analyzeBlockBody(block, call_src, &child_block, merges);
2680 // This `res2` is here instead of directly breaking from `res` due to a stage1
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;
26282735 } else if (func_ty_info.is_generic) res: {
26292736 const func_val = try sema.resolveConstValue(block, func_src, func);
26302737 const module_fn = func_val.castTag(.function).?.data;
......@@ -3291,31 +3398,9 @@ fn zirEnumToInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileE
32913398 }
32923399
32933400 if (try sema.resolveMaybeUndefVal(block, operand_src, enum_tag)) |enum_tag_val| {
3294 if (enum_tag_val.castTag(.enum_field_index)) |enum_field_payload| {
3295 const field_index = enum_field_payload.data;
3296 switch (enum_tag_ty.tag()) {
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 }
3401 var buffer: Value.Payload.U64 = undefined;
3402 const val = enum_tag_val.enumToInt(enum_tag_ty, &buffer);
3403 return sema.addConstant(int_tag_ty, try val.copy(sema.arena));
33193404 }
33203405
33213406 try sema.requireRuntimeBlock(block, src);
......@@ -3400,7 +3485,10 @@ fn zirOptionalPayloadPtr(
34003485 return sema.mod.fail(&block.base, src, "unable to unwrap null", .{});
34013486 }
34023487 // 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 );
34043492 }
34053493 }
34063494
......@@ -3437,7 +3525,8 @@ fn zirOptionalPayload(
34373525 if (val.isNull()) {
34383526 return sema.mod.fail(&block.base, src, "unable to unwrap null", .{});
34393527 }
3440 return sema.addConstant(child_type, val);
3528 const sub_val = val.castTag(.opt_payload).?.data;
3529 return sema.addConstant(child_type, sub_val);
34413530 }
34423531
34433532 try sema.requireRuntimeBlock(block, src);
......@@ -5294,17 +5383,56 @@ fn zirShl(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!A
52945383 const tracy = trace(@src());
52955384 defer tracy.end();
52965385
5297 _ = block;
5298 _ = inst;
5299 return sema.mod.fail(&block.base, sema.src, "TODO implement zirShl", .{});
5386 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
5387 const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
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);
53005405}
53015406
53025407fn zirShr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
53035408 const tracy = trace(@src());
53045409 defer tracy.end();
53055410
5306 _ = inst;
5307 return sema.mod.fail(&block.base, sema.src, "TODO implement zirShr", .{});
5411 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
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);
53085436}
53095437
53105438fn zirBitwise(
......@@ -5975,6 +6103,28 @@ fn zirTypeInfo(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileEr
59756103 }),
59766104 );
59776105 },
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 },
59786128 else => |t| return sema.mod.fail(&block.base, src, "TODO: implement zirTypeInfo for {s}", .{
59796129 @tagName(t),
59806130 }),
......@@ -6001,13 +6151,37 @@ fn zirTypeofElem(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) Compile
60016151fn zirTypeofLog2IntType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
60026152 const inst_data = sema.code.instructions.items(.data)[inst].un_node;
60036153 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);
60056157}
60066158
60076159fn zirLog2IntType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
60086160 const inst_data = sema.code.instructions.items(.data)[inst].un_node;
60096161 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 }
60116185}
60126186
60136187fn zirTypeofPeer(
......@@ -6464,99 +6638,134 @@ fn zirStructInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref:
64646638 const first_field_type_data = zir_datas[first_item.field_type].pl_node;
64656639 const first_field_type_extra = sema.code.extraData(Zir.Inst.FieldType, first_field_type_data.payload_index).data;
64666640 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);
6468 const struct_obj = struct_ty.castTag(.@"struct").?.data;
6469
6470 // Maps field index to field_type index of where it was already initialized.
6471 // For making sure all fields are accounted for and no fields are duplicated.
6472 const found_fields = try gpa.alloc(Zir.Inst.Index, struct_obj.fields.count());
6473 defer gpa.free(found_fields);
6474 mem.set(Zir.Inst.Index, found_fields, 0);
6641 const resolved_ty = try sema.resolveTypeFields(block, src, unresolved_struct_type);
6642
6643 if (resolved_ty.castTag(.@"struct")) |struct_payload| {
6644 const struct_obj = struct_payload.data;
6645
6646 // Maps field index to field_type index of where it was already initialized.
6647 // For making sure all fields are accounted for and no fields are duplicated.
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.
6477 const field_inits = try gpa.alloc(Air.Inst.Ref, struct_obj.fields.count());
6478 defer gpa.free(field_inits);
6685 var root_msg: ?*Module.ErrorMsg = null;
64796686
6480 var field_i: u32 = 0;
6481 var extra_index = extra.end;
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;
6687 for (found_fields) |field_type_inst, i| {
6688 if (field_type_inst != 0) continue;
64866689
6487 const field_type_data = zir_datas[item.data.field_type].pl_node;
6488 const field_src: LazySrcLoc = .{ .node_offset_back2tok = field_type_data.src_node };
6489 const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;
6490 const field_name = sema.code.nullTerminatedString(field_type_extra.name_start);
6491 const field_index = struct_obj.fields.getIndex(field_name) orelse
6492 return sema.failWithBadFieldAccess(block, struct_obj, field_src, field_name);
6493 if (found_fields[field_index] != 0) {
6494 const other_field_type = found_fields[field_index];
6495 const other_field_type_data = zir_datas[other_field_type].pl_node;
6496 const other_field_src: LazySrcLoc = .{ .node_offset_back2tok = other_field_type_data.src_node };
6497 const msg = msg: {
6498 const msg = try mod.errMsg(&block.base, field_src, "duplicate field", .{});
6499 errdefer msg.destroy(gpa);
6500 try mod.errNote(&block.base, other_field_src, msg, "other field here", .{});
6501 break :msg msg;
6502 };
6690 // Check if the field has a default init.
6691 const field = struct_obj.fields.values()[i];
6692 if (field.default_val.tag() == .unreachable_value) {
6693 const field_name = struct_obj.fields.keys()[i];
6694 const template = "missing struct field: {s}";
6695 const args = .{field_name};
6696 if (root_msg) |msg| {
6697 try mod.errNote(&block.base, src, msg, template, args);
6698 } else {
6699 root_msg = try mod.errMsg(&block.base, src, template, args);
6700 }
6701 } else {
6702 field_inits[i] = try sema.addConstant(field.ty, field.default_val);
6703 }
6704 }
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 );
65036714 return mod.failWithOwnedErrorMsg(&block.base, msg);
65046715 }
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| {
6512 if (field_type_inst != 0) continue;
6513
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);
6721 const is_comptime = for (field_inits) |field_init| {
6722 if (!(try sema.isComptimeKnown(block, src, field_init))) {
6723 break false;
65246724 }
6525 } else {
6526 field_inits[i] = try sema.addConstant(field.ty, field.default_val);
6725 } else true;
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));
65276733 }
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) {
6542 return mod.fail(&block.base, src, "TODO: Sema.zirStructInit is_ref=true", .{});
6543 }
6735 return mod.fail(&block.base, src, "TODO: Sema.zirStructInit for runtime-known struct values", .{});
6736 } else if (resolved_ty.cast(Type.Payload.Union)) |union_payload| {
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| {
6546 if (!(try sema.isComptimeKnown(block, src, field_init))) {
6547 break false;
6743 const item = sema.code.extraData(Zir.Inst.StructInit.Item, extra.end);
6744
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", .{});
65486754 }
6549 } else true;
65506755
6551 if (is_comptime) {
6552 const values = try sema.arena.alloc(Value, field_inits.len);
6553 for (field_inits) |field_init, i| {
6554 values[i] = (sema.resolveMaybeUndefVal(block, src, field_init) catch unreachable).?;
6756 const init_inst = sema.resolveInst(item.data.init);
6757 if (try sema.resolveMaybeUndefVal(block, field_src, init_inst)) |val| {
6758 return sema.addConstant(
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 );
65556765 }
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", .{});
65576767 }
6558
6559 return mod.fail(&block.base, src, "TODO: Sema.zirStructInit for runtime-known struct values", .{});
6768 unreachable;
65606769}
65616770
65626771fn 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
65946803 const extra = sema.code.extraData(Zir.Inst.FieldType, inst_data.payload_index).data;
65956804 const src = inst_data.src();
65966805 const field_name = sema.code.nullTerminatedString(extra.name_start);
6597 const unresolved_struct_type = try sema.resolveType(block, src, extra.container_type);
6598 if (unresolved_struct_type.zigTypeTag() != .Struct) {
6599 return sema.mod.fail(&block.base, src, "expected struct; found '{}'", .{
6600 unresolved_struct_type,
6601 });
6806 const unresolved_ty = try sema.resolveType(block, src, extra.container_type);
6807 const resolved_ty = try sema.resolveTypeFields(block, src, unresolved_ty);
6808 switch (resolved_ty.zigTypeTag()) {
6809 .Struct => {
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 }),
66026824 }
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);
66086825}
66096826
66106827fn zirErrorReturnTrace(
......@@ -6679,7 +6896,54 @@ fn zirTagName(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileErr
66796896fn zirReify(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
66806897 const inst_data = sema.code.instructions.items(.data)[inst].un_node;
66816898 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 }
66836947}
66846948
66856949fn zirTypeName(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
......@@ -7855,14 +8119,29 @@ fn structFieldPtr(
78558119 }
78568120
78578121 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 };
78588140 return block.addInst(.{
7859 .tag = .struct_field_ptr,
7860 .data = .{ .ty_pl = .{
8141 .tag = tag,
8142 .data = .{ .ty_op = .{
78618143 .ty = try sema.addType(ptr_field_ty),
7862 .payload = try sema.addExtra(Air.StructField{
7863 .struct_operand = struct_ptr,
7864 .field_index = @intCast(u32, field_index),
7865 }),
8144 .operand = struct_ptr,
78668145 } },
78678146 });
78688147}
......@@ -8099,24 +8378,35 @@ fn elemPtrArray(
80998378 elem_index: Air.Inst.Ref,
81008379 elem_index_src: LazySrcLoc,
81018380) 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
81028388 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| {
81048390 // Both array pointer and index are compile-time known.
81058391 const index_u64 = index_val.toUnsignedInt();
81068392 // @intCast here because it would have been impossible to construct a value that
81078393 // required a larger index.
81088394 const elem_ptr = try array_ptr_val.elemPtr(sema.arena, @intCast(usize, index_u64));
8109 const pointee_type = sema.typeOf(array_ptr).elemType().elemType();
8110
8111 return sema.addConstant(
8112 try Type.Tag.single_const_pointer.create(sema.arena, pointee_type),
8113 elem_ptr,
8114 );
8395 return sema.addConstant(result_ty, elem_ptr);
81158396 }
81168397 }
8117 _ = elem_index;
8118 _ = elem_index_src;
8119 return sema.mod.fail(&block.base, src, "TODO implement more analyze elemptr for arrays", .{});
8398 // TODO safety check for array bounds
8399 try sema.requireRuntimeBlock(block, src);
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 });
81208410}
81218411
81228412fn coerce(
......@@ -8528,9 +8818,12 @@ fn analyzeRef(
85288818
85298819 try sema.requireRuntimeBlock(block, src);
85308820 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);
85328823 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);
85348827}
85358828
85368829fn analyzeLoad(
......@@ -8895,7 +9188,7 @@ fn wrapOptional(
88959188 inst_src: LazySrcLoc,
88969189) !Air.Inst.Ref {
88979190 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));
88999192 }
89009193
89019194 try sema.requireRuntimeBlock(block, inst_src);
......@@ -9124,22 +9417,62 @@ pub fn resolveTypeLayout(
91249417 }
91259418}
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 {
91289422 switch (ty.tag()) {
91299423 .@"struct" => {
91309424 const struct_obj = ty.castTag(.@"struct").?.data;
9425 if (struct_obj.owner_decl.namespace != sema.owner_decl.namespace) return;
91319426 switch (struct_obj.status) {
91329427 .none => {},
91339428 .field_types_wip => {
91349429 return sema.mod.fail(&block.base, src, "struct {} depends on itself", .{ty});
91359430 },
9136 .have_field_types, .have_layout, .layout_wip => return ty,
9431 .have_field_types, .have_layout, .layout_wip => return,
91379432 }
9433 const prev_namespace = sema.namespace;
9434 sema.namespace = &struct_obj.namespace;
9435 defer sema.namespace = prev_namespace;
9436
91389437 struct_obj.status = .field_types_wip;
9139 try sema.mod.analyzeStructFields(struct_obj);
9438 try sema.analyzeStructFields(block, struct_obj);
91409439 struct_obj.status = .have_field_types;
9141 return ty;
91429440 },
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"),
91439476 .extern_options => return sema.resolveBuiltinTypeFields(block, src, "ExternOptions"),
91449477 .export_options => return sema.resolveBuiltinTypeFields(block, src, "ExportOptions"),
91459478 .atomic_ordering => return sema.resolveBuiltinTypeFields(block, src, "AtomicOrdering"),
......@@ -9152,18 +9485,12 @@ fn resolveTypeFields(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, ty: Type
91529485 .@"union", .union_tagged => {
91539486 const union_obj = ty.cast(Type.Payload.Union).?.data;
91549487 switch (union_obj.status) {
9155 .none => {},
9488 .none => unreachable,
91569489 .field_types_wip => {
9157 return sema.mod.fail(&block.base, src, "union {} depends on itself", .{
9158 ty,
9159 });
9490 return sema.mod.fail(&block.base, src, "union {} depends on itself", .{ty});
91609491 },
91619492 .have_field_types, .have_layout, .layout_wip => return ty,
91629493 }
9163 union_obj.status = .field_types_wip;
9164 try sema.mod.analyzeUnionFields(union_obj);
9165 union_obj.status = .have_field_types;
9166 return ty;
91679494 },
91689495 else => return ty,
91699496 }
......@@ -9179,6 +9506,265 @@ fn resolveBuiltinTypeFields(
91799506 return sema.resolveTypeFields(block, src, resolved_ty);
91809507}
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
91829768fn getBuiltin(
91839769 sema: *Sema,
91849770 block: *Scope.Block,
......@@ -9291,6 +9877,7 @@ fn typeHasOnePossibleValue(
92919877 .call_options,
92929878 .export_options,
92939879 .extern_options,
9880 .type_info,
92949881 .@"anyframe",
92959882 .anyframe_T,
92969883 .many_const_pointer,
......@@ -9475,6 +10062,7 @@ pub fn addType(sema: *Sema, ty: Type) !Air.Inst.Ref {
947510062 .call_options => return .call_options_type,
947610063 .export_options => return .export_options_type,
947710064 .extern_options => return .extern_options_type,
10065 .type_info => return .type_info_type,
947810066 .manyptr_u8 => return .manyptr_u8_type,
947910067 .manyptr_const_u8 => return .manyptr_const_u8_type,
948010068 .fn_noreturn_no_args => return .fn_noreturn_no_args_type,
src/TypedValue.zig+12-3
......@@ -23,9 +23,18 @@ pub const Managed = struct {
2323};
2424
2525/// 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 {
2727 return TypedValue{
28 .ty = try self.ty.copy(allocator),
29 .val = try self.val.copy(allocator),
28 .ty = try self.ty.copy(arena),
29 .val = try self.val.copy(arena),
3030 };
3131}
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 {
495495 /// Uses the `ptr_type` union field.
496496 ptr_type,
497497 /// Slice operation `lhs[rhs..]`. No sentinel and no end offset.
498 /// Returns a pointer to the subslice.
498499 /// Uses the `pl_node` field. AST node is the slice syntax. Payload is `SliceStart`.
499500 slice_start,
500501 /// Slice operation `array_ptr[start..end]`. No sentinel.
502 /// Returns a pointer to the subslice.
501503 /// Uses the `pl_node` field. AST node is the slice syntax. Payload is `SliceEnd`.
502504 slice_end,
503505 /// Slice operation `array_ptr[start..end:sentinel]`.
506 /// Returns a pointer to the subslice.
504507 /// Uses the `pl_node` field. AST node is the slice syntax. Payload is `SliceSentinel`.
505508 slice_sentinel,
506509 /// Write a value to a pointer. For loading, see `load`.
......@@ -687,14 +690,14 @@ pub const Inst = struct {
687690 /// A struct literal with a specified type, with no fields.
688691 /// Uses the `un_node` field.
689692 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,
691694 /// returns the field type. Uses the `pl_node` field. Payload is `FieldType`.
692695 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,
694697 /// returns the field type. Uses the `pl_node` field. Payload is `FieldTypeRef`.
695698 field_type_ref,
696 /// Finalizes a typed struct initialization, performs validation, and returns the
697 /// struct value.
699 /// Finalizes a typed struct or union initialization, performs validation, and returns the
700 /// struct or union value.
698701 /// Uses the `pl_node` field. Payload is `StructInit`.
699702 struct_init,
700703 /// Struct initialization syntax, make the result a pointer.
......@@ -1703,6 +1706,7 @@ pub const Inst = struct {
17031706 call_options_type,
17041707 export_options_type,
17051708 extern_options_type,
1709 type_info_type,
17061710 manyptr_u8_type,
17071711 manyptr_const_u8_type,
17081712 fn_noreturn_no_args_type,
......@@ -1973,6 +1977,10 @@ pub const Inst = struct {
19731977 .ty = Type.initTag(.type),
19741978 .val = Value.initTag(.extern_options_type),
19751979 },
1980 .type_info_type = .{
1981 .ty = Type.initTag(.type),
1982 .val = Value.initTag(.type_info_type),
1983 },
19761984
19771985 .undef = .{
19781986 .ty = Type.initTag(.@"undefined"),
src/codegen.zig+155-28
......@@ -822,6 +822,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
822822 .bit_and => try self.airBitAnd(inst),
823823 .bit_or => try self.airBitOr(inst),
824824 .xor => try self.airXor(inst),
825 .shr => try self.airShr(inst),
826 .shl => try self.airShl(inst),
825827
826828 .alloc => try self.airAlloc(inst),
827829 .arg => try self.airArg(inst),
......@@ -853,6 +855,12 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
853855 .store => try self.airStore(inst),
854856 .struct_field_ptr=> try self.airStructFieldPtr(inst),
855857 .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
856864 .switch_br => try self.airSwitch(inst),
857865 .slice_ptr => try self.airSlicePtr(inst),
858866 .slice_len => try self.airSliceLen(inst),
......@@ -860,6 +868,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
860868 .slice_elem_val => try self.airSliceElemVal(inst),
861869 .ptr_slice_elem_val => try self.airPtrSliceElemVal(inst),
862870 .ptr_elem_val => try self.airPtrElemVal(inst),
871 .ptr_elem_ptr => try self.airPtrElemPtr(inst),
863872 .ptr_ptr_elem_val => try self.airPtrPtrElemVal(inst),
864873
865874 .constant => unreachable, // excluded from function bodies
......@@ -970,6 +979,20 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
970979 log.debug("%{d} => {}", .{ inst, result });
971980 const branch = &self.branch_stack.items[self.branch_stack.items.len - 1];
972981 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 }
973996 }
974997 self.finishAirBookkeeping();
975998 }
......@@ -1272,6 +1295,24 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
12721295 return self.finishAir(inst, result, .{ bin_op.lhs, bin_op.rhs, .none });
12731296 }
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
12751316 fn airOptionalPayload(self: *Self, inst: Air.Inst.Index) !void {
12761317 const ty_op = self.air.instructions.items(.data)[inst].ty_op;
12771318 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 {
13991440 return self.finishAir(inst, result, .{ bin_op.lhs, bin_op.rhs, .none });
14001441 }
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
14021452 fn airPtrPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
14031453 const is_volatile = false; // TODO
14041454 const bin_op = self.air.instructions.items(.data)[inst].bin_op;
......@@ -1439,7 +1489,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
14391489 return true;
14401490 }
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 {
14431493 const elem_ty = ptr_ty.elemType();
14441494 switch (ptr) {
14451495 .none => unreachable,
......@@ -1456,11 +1506,25 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
14561506 .embedded_in_code => {
14571507 return self.fail("TODO implement loading from MCValue.embedded_in_code", .{});
14581508 },
1459 .register => {
1460 return self.fail("TODO implement loading from MCValue.register", .{});
1509 .register => |reg| {
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 }
14611523 },
1462 .memory => {
1463 return self.fail("TODO implement loading from MCValue.memory", .{});
1524 .memory => |addr| {
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);
14641528 },
14651529 .stack_offset => {
14661530 return self.fail("TODO implement loading from MCValue.stack_offset", .{});
......@@ -1534,7 +1598,18 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
15341598 fn airStructFieldPtr(self: *Self, inst: Air.Inst.Index) !void {
15351599 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;
15361600 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;
15381613 return self.fail("TODO implement codegen struct_field_ptr", .{});
15391614 //return self.finishAir(inst, result, .{ extra.struct_ptr, .none, .none });
15401615 }
......@@ -1572,15 +1647,53 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
15721647 }
15731648
15741649 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
15751681 const lhs = try self.resolveInst(op_lhs);
15761682 const rhs = try self.resolveInst(op_rhs);
15771683
15781684 const lhs_is_register = lhs == .register;
15791685 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 };
15811690 const rhs_should_be_register = try self.armOperandShouldBeRegister(rhs);
15821691 const reuse_lhs = lhs_is_register and self.reuseOperand(inst, op_lhs, 0, lhs);
15831692 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
15851698 // Destination must be a register
15861699 var dst_mcv: MCValue = undefined;
......@@ -1597,7 +1710,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
15971710 branch.inst_table.putAssumeCapacity(Air.refToIndex(op_rhs).?, rhs_mcv);
15981711 }
15991712 dst_mcv = lhs;
1600 } else if (reuse_rhs) {
1713 } else if (reuse_rhs and can_swap_lhs_and_rhs) {
16011714 // Allocate 0 or 1 registers
16021715 if (!lhs_is_register and lhs_should_be_register) {
16031716 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 {
16361749 dst_mcv = MCValue{ .register = try self.register_manager.allocReg(inst, &.{}) };
16371750 lhs_mcv = dst_mcv;
16381751 }
1639 } else if (rhs_should_be_register) {
1752 } else if (rhs_should_be_register and can_swap_lhs_and_rhs) {
16401753 // LHS is immediate
16411754 if (rhs_is_register) {
16421755 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 {
16631776 rhs_mcv,
16641777 swap_lhs_and_rhs,
16651778 op,
1779 signedness,
16661780 );
16671781 return dst_mcv;
16681782 }
......@@ -1674,6 +1788,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
16741788 rhs_mcv: MCValue,
16751789 swap_lhs_and_rhs: bool,
16761790 op: Air.Inst.Tag,
1791 signedness: std.builtin.Signedness,
16771792 ) !void {
16781793 assert(lhs_mcv == .register or rhs_mcv == .register);
16791794
......@@ -1719,6 +1834,27 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
17191834 .cmp_eq => {
17201835 writeInt(u32, try self.code.addManyAsArray(4), Instruction.cmp(.al, op1, operand).toU32());
17211836 },
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 },
17221858 else => unreachable, // not a binary instruction
17231859 }
17241860 }
......@@ -2969,7 +3105,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
29693105 }
29703106
29713107 // 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
29743111 break :result switch (ty.isSignedInt()) {
29753112 true => MCValue{ .compare_flags_signed = op },
......@@ -3792,15 +3929,10 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
37923929 else => return self.fail("TODO implement memset", .{}),
37933930 }
37943931 },
3795 .compare_flags_unsigned => |op| {
3796 _ = op;
3797 return self.fail("TODO implement set stack variable with compare flags value (unsigned)", .{});
3798 },
3799 .compare_flags_signed => |op| {
3800 _ = op;
3801 return self.fail("TODO implement set stack variable with compare flags value (signed)", .{});
3802 },
3803 .immediate => {
3932 .compare_flags_unsigned,
3933 .compare_flags_signed,
3934 .immediate,
3935 => {
38043936 const reg = try self.copyToTmpRegister(ty, mcv);
38053937 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
38063938 },
......@@ -3968,15 +4100,10 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
39684100 else => return self.fail("TODO implement memset", .{}),
39694101 }
39704102 },
3971 .compare_flags_unsigned => |op| {
3972 _ = op;
3973 return self.fail("TODO implement set stack variable with compare flags value (unsigned)", .{});
3974 },
3975 .compare_flags_signed => |op| {
3976 _ = op;
3977 return self.fail("TODO implement set stack variable with compare flags value (signed)", .{});
3978 },
3979 .immediate => {
4103 .compare_flags_unsigned,
4104 .compare_flags_signed,
4105 .immediate,
4106 => {
39804107 const reg = try self.copyToTmpRegister(ty, mcv);
39814108 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
39824109 },
src/codegen/arm.zig+172-34
......@@ -192,7 +192,7 @@ pub const c_abi_int_return_regs = [_]Register{ .r0, .r1 };
192192
193193/// Represents an instruction in the ARM instruction set architecture
194194pub const Instruction = union(enum) {
195 DataProcessing: packed struct {
195 data_processing: packed struct {
196196 // Note to self: The order of the fields top-to-bottom is
197197 // right-to-left in the actual 32-bit int representation
198198 op2: u12,
......@@ -204,7 +204,7 @@ pub const Instruction = union(enum) {
204204 fixed: u2 = 0b00,
205205 cond: u4,
206206 },
207 Multiply: packed struct {
207 multiply: packed struct {
208208 rn: u4,
209209 fixed_1: u4 = 0b1001,
210210 rm: u4,
......@@ -215,7 +215,7 @@ pub const Instruction = union(enum) {
215215 fixed_2: u6 = 0b000000,
216216 cond: u4,
217217 },
218 MultiplyLong: packed struct {
218 multiply_long: packed struct {
219219 rn: u4,
220220 fixed_1: u4 = 0b1001,
221221 rm: u4,
......@@ -227,7 +227,17 @@ pub const Instruction = union(enum) {
227227 fixed_2: u5 = 0b00001,
228228 cond: u4,
229229 },
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 {
231241 offset: u12,
232242 rd: u4,
233243 rn: u4,
......@@ -240,7 +250,7 @@ pub const Instruction = union(enum) {
240250 fixed: u2 = 0b01,
241251 cond: u4,
242252 },
243 ExtraLoadStore: packed struct {
253 extra_load_store: packed struct {
244254 imm4l: u4,
245255 fixed_1: u1 = 0b1,
246256 op2: u2,
......@@ -256,7 +266,7 @@ pub const Instruction = union(enum) {
256266 fixed_3: u3 = 0b000,
257267 cond: u4,
258268 },
259 BlockDataTransfer: packed struct {
269 block_data_transfer: packed struct {
260270 register_list: u16,
261271 rn: u4,
262272 load_store: u1,
......@@ -267,25 +277,25 @@ pub const Instruction = union(enum) {
267277 fixed: u3 = 0b100,
268278 cond: u4,
269279 },
270 Branch: packed struct {
280 branch: packed struct {
271281 offset: u24,
272282 link: u1,
273283 fixed: u3 = 0b101,
274284 cond: u4,
275285 },
276 BranchExchange: packed struct {
286 branch_exchange: packed struct {
277287 rn: u4,
278288 fixed_1: u1 = 0b1,
279289 link: u1,
280290 fixed_2: u22 = 0b0001_0010_1111_1111_1111_00,
281291 cond: u4,
282292 },
283 SupervisorCall: packed struct {
293 supervisor_call: packed struct {
284294 comment: u24,
285295 fixed: u4 = 0b1111,
286296 cond: u4,
287297 },
288 Breakpoint: packed struct {
298 breakpoint: packed struct {
289299 imm4: u4,
290300 fixed_1: u4 = 0b0111,
291301 imm12: u12,
......@@ -293,7 +303,7 @@ pub const Instruction = union(enum) {
293303 },
294304
295305 /// Represents the possible operations which can be performed by a
296 /// DataProcessing instruction
306 /// Data Processing instruction
297307 const Opcode = enum(u4) {
298308 // Rd := Op1 AND Op2
299309 @"and",
......@@ -530,16 +540,17 @@ pub const Instruction = union(enum) {
530540
531541 pub fn toU32(self: Instruction) u32 {
532542 return switch (self) {
533 .DataProcessing => |v| @bitCast(u32, v),
534 .Multiply => |v| @bitCast(u32, v),
535 .MultiplyLong => |v| @bitCast(u32, v),
536 .SingleDataTransfer => |v| @bitCast(u32, v),
537 .ExtraLoadStore => |v| @bitCast(u32, v),
538 .BlockDataTransfer => |v| @bitCast(u32, v),
539 .Branch => |v| @bitCast(u32, v),
540 .BranchExchange => |v| @bitCast(u32, v),
541 .SupervisorCall => |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),
543 .data_processing => |v| @bitCast(u32, v),
544 .multiply => |v| @bitCast(u32, v),
545 .multiply_long => |v| @bitCast(u32, v),
546 .integer_saturating_arithmetic => |v| @bitCast(u32, v),
547 .single_data_transfer => |v| @bitCast(u32, v),
548 .extra_load_store => |v| @bitCast(u32, v),
549 .block_data_transfer => |v| @bitCast(u32, v),
550 .branch => |v| @bitCast(u32, v),
551 .branch_exchange => |v| @bitCast(u32, v),
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),
543554 };
544555 }
545556
......@@ -554,7 +565,7 @@ pub const Instruction = union(enum) {
554565 op2: Operand,
555566 ) Instruction {
556567 return Instruction{
557 .DataProcessing = .{
568 .data_processing = .{
558569 .cond = @enumToInt(cond),
559570 .i = @boolToInt(op2 == .Immediate),
560571 .opcode = @enumToInt(opcode),
......@@ -573,7 +584,7 @@ pub const Instruction = union(enum) {
573584 top: bool,
574585 ) Instruction {
575586 return Instruction{
576 .DataProcessing = .{
587 .data_processing = .{
577588 .cond = @enumToInt(cond),
578589 .i = 1,
579590 .opcode = if (top) 0b1010 else 0b1000,
......@@ -594,7 +605,7 @@ pub const Instruction = union(enum) {
594605 ra: ?Register,
595606 ) Instruction {
596607 return Instruction{
597 .Multiply = .{
608 .multiply = .{
598609 .cond = @enumToInt(cond),
599610 .accumulate = @boolToInt(ra != null),
600611 .set_cond = set_cond,
......@@ -617,7 +628,7 @@ pub const Instruction = union(enum) {
617628 rn: Register,
618629 ) Instruction {
619630 return Instruction{
620 .MultiplyLong = .{
631 .multiply_long = .{
621632 .cond = @enumToInt(cond),
622633 .unsigned = signed,
623634 .accumulate = accumulate,
......@@ -630,6 +641,24 @@ pub const Instruction = union(enum) {
630641 };
631642 }
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
633662 fn singleDataTransfer(
634663 cond: Condition,
635664 rd: Register,
......@@ -642,7 +671,7 @@ pub const Instruction = union(enum) {
642671 load_store: u1,
643672 ) Instruction {
644673 return Instruction{
645 .SingleDataTransfer = .{
674 .single_data_transfer = .{
646675 .cond = @enumToInt(cond),
647676 .rn = rn.id(),
648677 .rd = rd.id(),
......@@ -678,7 +707,7 @@ pub const Instruction = union(enum) {
678707 };
679708
680709 return Instruction{
681 .ExtraLoadStore = .{
710 .extra_load_store = .{
682711 .imm4l = imm4l,
683712 .op2 = op2,
684713 .imm4h = imm4h,
......@@ -705,7 +734,7 @@ pub const Instruction = union(enum) {
705734 load_store: u1,
706735 ) Instruction {
707736 return Instruction{
708 .BlockDataTransfer = .{
737 .block_data_transfer = .{
709738 .register_list = @bitCast(u16, reg_list),
710739 .rn = rn.id(),
711740 .load_store = load_store,
......@@ -720,7 +749,7 @@ pub const Instruction = union(enum) {
720749
721750 fn branch(cond: Condition, offset: i26, link: u1) Instruction {
722751 return Instruction{
723 .Branch = .{
752 .branch = .{
724753 .cond = @enumToInt(cond),
725754 .link = link,
726755 .offset = @bitCast(u24, @intCast(i24, offset >> 2)),
......@@ -730,7 +759,7 @@ pub const Instruction = union(enum) {
730759
731760 fn branchExchange(cond: Condition, rn: Register, link: u1) Instruction {
732761 return Instruction{
733 .BranchExchange = .{
762 .branch_exchange = .{
734763 .cond = @enumToInt(cond),
735764 .link = link,
736765 .rn = rn.id(),
......@@ -740,7 +769,7 @@ pub const Instruction = union(enum) {
740769
741770 fn supervisorCall(cond: Condition, comment: u24) Instruction {
742771 return Instruction{
743 .SupervisorCall = .{
772 .supervisor_call = .{
744773 .cond = @enumToInt(cond),
745774 .comment = comment,
746775 },
......@@ -749,7 +778,7 @@ pub const Instruction = union(enum) {
749778
750779 fn breakpoint(imm: u16) Instruction {
751780 return Instruction{
752 .Breakpoint = .{
781 .breakpoint = .{
753782 .imm12 = @truncate(u12, imm >> 4),
754783 .imm4 = @truncate(u4, imm),
755784 },
......@@ -873,6 +902,24 @@ pub const Instruction = union(enum) {
873902 return dataProcessing(cond, .mvn, 1, rd, .r0, op2);
874903 }
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
876923 // movw and movt
877924
878925 pub fn movw(cond: Condition, rd: Register, imm: u16) Instruction {
......@@ -887,7 +934,7 @@ pub const Instruction = union(enum) {
887934
888935 pub fn mrs(cond: Condition, rd: Register, psr: Psr) Instruction {
889936 return Instruction{
890 .DataProcessing = .{
937 .data_processing = .{
891938 .cond = @enumToInt(cond),
892939 .i = 0,
893940 .opcode = if (psr == .spsr) 0b1010 else 0b1000,
......@@ -901,7 +948,7 @@ pub const Instruction = union(enum) {
901948
902949 pub fn msr(cond: Condition, psr: Psr, op: Operand) Instruction {
903950 return Instruction{
904 .DataProcessing = .{
951 .data_processing = .{
905952 .cond = @enumToInt(cond),
906953 .i = 0,
907954 .opcode = if (psr == .spsr) 0b1011 else 0b1001,
......@@ -1142,6 +1189,79 @@ pub const Instruction = union(enum) {
11421189 return stmdb(cond, .sp, true, @bitCast(RegisterList, register_list));
11431190 }
11441191 }
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 }
11451265};
11461266
11471267test "serialize instructions" {
......@@ -1221,6 +1341,10 @@ test "serialize instructions" {
12211341 .inst = Instruction.ldmea(.al, .r4, true, .{ .r2 = true, .r5 = true }),
12221342 .expected = 0b1110_100_1_0_0_1_1_0100_0000000000100100,
12231343 },
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 },
12241348 };
12251349
12261350 for (testcases) |case| {
......@@ -1262,6 +1386,20 @@ test "aliases" {
12621386 .actual = Instruction.push(.al, .{ .r0, .r2 }),
12631387 .expected = Instruction.stmdb(.al, .sp, true, .{ .r0 = true, .r2 = true }),
12641388 },
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 },
12651403 };
12661404
12671405 for (testcases) |case| {
src/codegen/c.zig+45-10
......@@ -319,18 +319,20 @@ pub const DeclGen = struct {
319319 .Bool => return writer.print("{}", .{val.toBool()}),
320320 .Optional => {
321321 var opt_buf: Type.Payload.ElemType = undefined;
322 const child_type = t.optionalChild(&opt_buf);
322 const payload_type = t.optionalChild(&opt_buf);
323323 if (t.isPtrLikeOptional()) {
324 return dg.renderValue(writer, child_type, val);
324 return dg.renderValue(writer, payload_type, val);
325325 }
326326 try writer.writeByte('(');
327327 try dg.renderType(writer, t);
328 if (val.tag() == .null_value) {
329 try writer.writeAll("){ .is_null = true }");
330 } else {
331 try writer.writeAll("){ .is_null = false, .payload = ");
332 try dg.renderValue(writer, child_type, val);
328 try writer.writeAll("){");
329 if (val.castTag(.opt_payload)) |pl| {
330 const payload_val = pl.data;
331 try writer.writeAll(" .is_null = false, .payload = ");
332 try dg.renderValue(writer, payload_type, payload_val);
333333 try writer.writeAll(" }");
334 } else {
335 try writer.writeAll(" .is_null = true }");
334336 }
335337 },
336338 .ErrorSet => {
......@@ -871,6 +873,9 @@ fn genBody(o: *Object, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfM
871873 .bit_or => try airBinOp(o, inst, " | "),
872874 .xor => try airBinOp(o, inst, " ^ "),
873875
876 .shr => try airBinOp(o, inst, " >> "),
877 .shl => try airBinOp(o, inst, " << "),
878
874879 .not => try airNot( o, inst),
875880
876881 .optional_payload => try airOptionalPayload(o, inst),
......@@ -904,12 +909,19 @@ fn genBody(o: *Object, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfM
904909 .switch_br => try airSwitchBr(o, inst),
905910 .wrap_optional => try airWrapOptional(o, inst),
906911 .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
907918 .struct_field_val => try airStructFieldVal(o, inst),
908919 .slice_ptr => try airSliceField(o, inst, ".ptr;\n"),
909920 .slice_len => try airSliceField(o, inst, ".len;\n"),
910921
911922 .ptr_elem_val => try airPtrElemVal(o, inst, "["),
912923 .ptr_ptr_elem_val => try airPtrElemVal(o, inst, "[0]["),
924 .ptr_elem_ptr => try airPtrElemPtr(o, inst),
913925 .slice_elem_val => try airSliceElemVal(o, inst, "["),
914926 .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 {
957969 return o.dg.fail("TODO: C backend: airPtrElemVal", .{});
958970}
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
960979fn airSliceElemVal(o: *Object, inst: Air.Inst.Index, prefix: []const u8) !CValue {
961980 const is_volatile = false; // TODO
962981 if (!is_volatile and o.liveness.isUnused(inst))
......@@ -1638,15 +1657,31 @@ fn airOptionalPayload(o: *Object, inst: Air.Inst.Index) !CValue {
16381657
16391658fn airStructFieldPtr(o: *Object, inst: Air.Inst.Index) !CValue {
16401659 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
16431663 const ty_pl = o.air.instructions.items(.data)[inst].ty_pl;
16441664 const extra = o.air.extraData(Air.StructField, ty_pl.payload).data;
1645 const writer = o.writer();
16461665 const struct_ptr = try o.resolveInst(extra.struct_operand);
16471666 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();
16481683 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
16511686 const inst_ty = o.air.typeOfIndex(inst);
16521687 const local = try o.allocLocal(inst_ty, .Const);
src/codegen/llvm.zig+98-22
......@@ -434,6 +434,8 @@ pub const Object = struct {
434434 },
435435 else => |e| return e,
436436 };
437 const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
438 try self.updateDeclExports(module, decl, decl_exports);
437439 }
438440
439441 pub fn updateDeclExports(
......@@ -442,7 +444,9 @@ pub const Object = struct {
442444 decl: *const Module.Decl,
443445 exports: []const *Module.Export,
444446 ) !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;
446450 const is_extern = decl.val.tag() == .extern_fn;
447451 if (is_extern or exports.len != 0) {
448452 llvm_fn.setLinkage(.External);
......@@ -808,27 +812,22 @@ pub const DeclGen = struct {
808812 return self.todo("handle more array values", .{});
809813 },
810814 .Optional => {
811 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 {
815 if (tv.ty.isPtrLikeOptional()) {
830816 return self.todo("implement const of optional pointer", .{});
831817 }
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);
832831 },
833832 .Fn => {
834833 const fn_decl = switch (tv.val.tag()) {
......@@ -995,6 +994,9 @@ pub const FuncGen = struct {
995994 .bit_or, .bool_or => try self.airOr(inst),
996995 .xor => try self.airXor(inst),
997996
997 .shl => try self.airShl(inst),
998 .shr => try self.airShr(inst),
999
9981000 .cmp_eq => try self.airCmp(inst, .eq),
9991001 .cmp_gt => try self.airCmp(inst, .gt),
10001002 .cmp_gte => try self.airCmp(inst, .gte),
......@@ -1037,9 +1039,15 @@ pub const FuncGen = struct {
10371039 .struct_field_ptr => try self.airStructFieldPtr(inst),
10381040 .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
10401047 .slice_elem_val => try self.airSliceElemVal(inst),
10411048 .ptr_slice_elem_val => try self.airPtrSliceElemVal(inst),
10421049 .ptr_elem_val => try self.airPtrElemVal(inst),
1050 .ptr_elem_ptr => try self.airPtrElemPtr(inst),
10431051 .ptr_ptr_elem_val => try self.airPtrPtrElemVal(inst),
10441052
10451053 .optional_payload => try self.airOptionalPayload(inst, false),
......@@ -1295,11 +1303,35 @@ pub const FuncGen = struct {
12951303 const bin_op = self.air.instructions.items(.data)[inst].bin_op;
12961304 const base_ptr = try self.resolveInst(bin_op.lhs);
12971305 const rhs = try self.resolveInst(bin_op.rhs);
1298 const indices: [1]*const llvm.Value = .{rhs};
1299 const ptr = self.builder.buildInBoundsGEP(base_ptr, &indices, indices.len, "");
1306 const ptr = if (self.air.typeOf(bin_op.lhs).isSinglePointer()) ptr: {
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 };
13001314 return self.builder.buildLoad(ptr, "");
13011315 }
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
13031335 fn airPtrPtrElemVal(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
13041336 const is_volatile = false; // TODO
13051337 if (!is_volatile and self.liveness.isUnused(inst))
......@@ -1325,6 +1357,15 @@ pub const FuncGen = struct {
13251357 return self.builder.buildStructGEP(struct_ptr, field_index, "");
13261358 }
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
13281369 fn airStructFieldVal(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
13291370 if (self.liveness.isUnused(inst))
13301371 return null;
......@@ -1739,6 +1780,41 @@ pub const FuncGen = struct {
17391780 return self.builder.buildXor(lhs, rhs, "");
17401781 }
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
17421818 fn airIntCast(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
17431819 if (self.liveness.isUnused(inst))
17441820 return null;
src/codegen/llvm/bindings.zig+17
......@@ -291,6 +291,14 @@ pub const Builder = opaque {
291291 pub const getInsertBlock = LLVMGetInsertBlock;
292292 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
294302 pub const buildCall = LLVMBuildCall;
295303 extern fn LLVMBuildCall(
296304 *const Builder,
......@@ -382,6 +390,15 @@ pub const Builder = opaque {
382390 pub const buildAnd = LLVMBuildAnd;
383391 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
385402 pub const buildOr = LLVMBuildOr;
386403 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 {
862862 .ret => self.airRet(inst),
863863 .store => self.airStore(inst),
864864 .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),
865869 .switch_br => self.airSwitchBr(inst),
866870 .unreach => self.airUnreachable(inst),
867871 .wrap_optional => self.airWrapOptional(inst),
......@@ -1198,7 +1202,12 @@ pub const Context = struct {
11981202
11991203 // When constant has value 'null', set is_null local to '1'
12001204 // 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 {
12021211 try writer.writeByte(wasm.opcode(.i32_const));
12031212 try leb.writeILEB128(writer, @as(i32, 1));
12041213
......@@ -1208,10 +1217,6 @@ pub const Context = struct {
12081217 });
12091218 try writer.writeByte(wasm.opcode(opcode));
12101219 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);
12151220 }
12161221 },
12171222 else => |zig_type| return self.fail("Wasm TODO: emitConstant for zigTypeTag {s}", .{zig_type}),
......@@ -1440,8 +1445,15 @@ pub const Context = struct {
14401445 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;
14411446 const extra = self.air.extraData(Air.StructField, ty_pl.payload);
14421447 const struct_ptr = self.resolveInst(extra.data.struct_operand);
1443
1444 return WValue{ .local = struct_ptr.multi_value.index + @intCast(u32, extra.data.field_index) };
1448 return structFieldPtr(struct_ptr, 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 };
14451457 }
14461458
14471459 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 {
765765 if (self.base.options.wasi_exec_model == .reactor) {
766766 // Reactor execution model does not have _start so lld doesn't look for it.
767767 try argv.append("--no-entry");
768 // Make sure "_initialize" is exported even if this is pure Zig WASI reactor
769 // where WASM_SYMBOL_EXPORTED flag in LLVM is not set on _initialize.
770 try argv.appendSlice(&[_][]const u8{
771 "--export",
772 "_initialize",
773 });
768 // Make sure "_initialize" and other used-defined functions are exported if this is WASI reactor.
769 try argv.append("--export-dynamic");
774770 }
775771 } else {
776772 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
24922492
24932493 const digest = if (try man.hit()) man.final() else digest: {
24942494 var argv = std.ArrayList([]const u8).init(arena);
2495 try argv.append(""); // argv[0] is program name, actual args start at [1]
24952496
24962497 var zig_cache_tmp_dir = try comp.local_cache_directory.handle.makeOpenPath("tmp", .{});
24972498 defer zig_cache_tmp_dir.close();
src/mingw.zig+17-19
......@@ -187,27 +187,25 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {
187187 };
188188 }
189189 } else if (target.cpu.arch.isARM()) {
190 if (target.cpu.arch.ptrBitWidth() == 32) {
191 for (mingwex_arm32_src) |dep| {
192 (try c_source_files.addOne()).* = .{
193 .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{
194 "libc", "mingw", dep,
195 }),
196 .extra_flags = extra_flags,
197 };
198 }
199 } else {
200 for (mingwex_arm64_src) |dep| {
201 (try c_source_files.addOne()).* = .{
202 .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{
203 "libc", "mingw", dep,
204 }),
205 .extra_flags = extra_flags,
206 };
207 }
190 for (mingwex_arm32_src) |dep| {
191 (try c_source_files.addOne()).* = .{
192 .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{
193 "libc", "mingw", dep,
194 }),
195 .extra_flags = extra_flags,
196 };
197 }
198 } else if (target.cpu.arch.isAARCH64()) {
199 for (mingwex_arm64_src) |dep| {
200 (try c_source_files.addOne()).* = .{
201 .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{
202 "libc", "mingw", dep,
203 }),
204 .extra_flags = extra_flags,
205 };
208206 }
209207 } else {
210 unreachable;
208 @panic("unsupported arch");
211209 }
212210 return comp.build_crt_file("mingwex", .Lib, c_source_files.items);
213211 },
src/print_air.zig+19-3
......@@ -127,6 +127,8 @@ const Writer = struct {
127127 .ptr_slice_elem_val,
128128 .ptr_elem_val,
129129 .ptr_ptr_elem_val,
130 .shl,
131 .shr,
130132 => try w.writeBinOp(s, inst),
131133
132134 .is_null,
......@@ -167,12 +169,17 @@ const Writer = struct {
167169 .wrap_errunion_err,
168170 .slice_ptr,
169171 .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,
170176 => try w.writeTyOp(s, inst),
171177
172178 .block,
173179 .loop,
174180 => try w.writeBlock(s, inst),
175181
182 .ptr_elem_ptr => try w.writePtrElemPtr(s, inst),
176183 .struct_field_ptr => try w.writeStructField(s, inst),
177184 .struct_field_val => try w.writeStructField(s, inst),
178185 .constant => try w.writeConstant(s, inst),
......@@ -237,10 +244,19 @@ const Writer = struct {
237244
238245 fn writeStructField(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
239246 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);
243 try s.print(", {d}", .{extra.data.field_index});
249 try w.writeOperand(s, inst, 0, extra.struct_operand);
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);
244260 }
245261
246262 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 {
11251125
11261126struct AstNodeIdentifier {
11271127 Buf *name;
1128 bool is_at_syntax;
11281129};
11291130
11301131struct AstNodeEnumLiteral {
src/stage1/analyze.cpp-48
......@@ -3918,12 +3918,6 @@ static void add_top_level_decl(CodeGen *g, ScopeDecls *decls_scope, Tld *tld) {
39183918 add_error_note(g, msg, other_tld->source_node, buf_sprintf("previous definition here"));
39193919 return;
39203920 }
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 }
39273921 }
39283922}
39293923
......@@ -4170,48 +4164,6 @@ ZigVar *add_variable(CodeGen *g, AstNode *source_node, Scope *parent_scope, Buf
41704164 variable_entry->var_type = g->builtin_types.entry_invalid;
41714165 } else {
41724166 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 }
42154167 }
42164168
42174169 Scope *child_scope;
src/stage1/astgen.cpp+57-54
......@@ -3194,30 +3194,6 @@ ZigVar *create_local_var(CodeGen *codegen, AstNode *node, Scope *parent_scope,
31943194 add_error_note(codegen, msg, existing_var->decl_node, buf_sprintf("previous declaration here"));
31953195 }
31963196 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 }
32213197 }
32223198 }
32233199 } else {
......@@ -3832,35 +3808,38 @@ static Stage1ZirInst *astgen_identifier(Stage1AstGen *ag, Scope *scope, AstNode
38323808 Error err;
38333809 assert(node->type == NodeTypeIdentifier);
38343810
3835 Buf *variable_name = node_identifier_buf(node);
3836
3837 if (buf_eql_str(variable_name, "_")) {
3838 if (lval == LValAssign) {
3839 Stage1ZirInstConst *const_instruction = ir_build_instruction<Stage1ZirInstConst>(ag, scope, node);
3840 const_instruction->value = ag->codegen->pass1_arena->create<ZigValue>();
3841 const_instruction->value->type = get_pointer_to_type(ag->codegen,
3842 ag->codegen->builtin_types.entry_void, false);
3843 const_instruction->value->special = ConstValSpecialStatic;
3844 const_instruction->value->data.x_ptr.special = ConstPtrSpecialDiscard;
3845 return &const_instruction->base;
3811 bool is_at_syntax;
3812 Buf *variable_name = node_identifier_buf2(node, &is_at_syntax);
3813
3814 if (!is_at_syntax) {
3815 if (buf_eql_str(variable_name, "_")) {
3816 if (lval == LValAssign) {
3817 Stage1ZirInstConst *const_instruction = ir_build_instruction<Stage1ZirInstConst>(ag, scope, node);
3818 const_instruction->value = ag->codegen->pass1_arena->create<ZigValue>();
3819 const_instruction->value->type = get_pointer_to_type(ag->codegen,
3820 ag->codegen->builtin_types.entry_void, false);
3821 const_instruction->value->special = ConstValSpecialStatic;
3822 const_instruction->value->data.x_ptr.special = ConstPtrSpecialDiscard;
3823 return &const_instruction->base;
3824 }
38463825 }
3847 }
38483826
3849 ZigType *primitive_type;
3850 if ((err = get_primitive_type(ag->codegen, variable_name, &primitive_type))) {
3851 if (err == ErrorOverflow) {
3852 add_node_error(ag->codegen, node,
3853 buf_sprintf("primitive integer type '%s' exceeds maximum bit width of 65535",
3854 buf_ptr(variable_name)));
3855 return ag->codegen->invalid_inst_src;
3856 }
3857 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);
3827 ZigType *primitive_type;
3828 if ((err = get_primitive_type(ag->codegen, variable_name, &primitive_type))) {
3829 if (err == ErrorOverflow) {
3830 add_node_error(ag->codegen, node,
3831 buf_sprintf("primitive integer type '%s' exceeds maximum bit width of 65535",
3832 buf_ptr(variable_name)));
3833 return ag->codegen->invalid_inst_src;
3834 }
3835 assert(err == ErrorPrimitiveTypeNotFound);
38623836 } 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 }
38643843 }
38653844 }
38663845
......@@ -3875,7 +3854,31 @@ static Stage1ZirInst *astgen_identifier(Stage1AstGen *ag, Scope *scope, AstNode
38753854 }
38763855 }
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
38793882 if (tld) {
38803883 Stage1ZirInst *decl_ref = ir_build_decl_ref(ag, scope, node, tld, lval);
38813884 if (lval == LValPtr || lval == LValAssign) {
......@@ -4653,17 +4656,17 @@ static Stage1ZirInst *astgen_builtin_fn_call(Stage1AstGen *ag, Scope *scope, Ast
46534656
46544657 AstNode *arg1_node = node->data.fn_call_expr.params.at(1);
46554658 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)
46574660 return arg1_value;
46584661
46594662 AstNode *arg2_node = node->data.fn_call_expr.params.at(2);
46604663 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)
46624665 return arg2_value;
46634666
46644667 AstNode *arg3_node = node->data.fn_call_expr.params.at(3);
46654668 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)
46674670 return arg3_value;
46684671
46694672 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
2000720007 return ir_build_truncate_gen(ira, instruction->base.scope, instruction->base.source_node, dest_type, target);
2000820008}
2000920009
20010static Stage1AirInst *ir_analyze_instruction_int_cast(IrAnalyze *ira, Stage1ZirInstIntCast *instruction) {
20011 ZigType *dest_type = ir_resolve_type(ira, instruction->dest_type->child);
20012 if (type_is_invalid(dest_type))
20013 return ira->codegen->invalid_inst_gen;
20014
20010static Stage1AirInst *ir_analyze_int_cast(IrAnalyze *ira, Scope *scope, AstNode *source_node,
20011 ZigType *dest_type, AstNode *dest_type_src_node,
20012 Stage1AirInst *target, AstNode *target_src_node)
20013{
2001520014 ZigType *scalar_dest_type = (dest_type->id == ZigTypeIdVector) ?
2001620015 dest_type->data.vector.elem_type : dest_type;
2001720016
2001820017 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,
2002020019 buf_sprintf("expected integer type, found '%s'", buf_ptr(&scalar_dest_type->name)));
2002120020 return ira->codegen->invalid_inst_gen;
2002220021 }
2002320022
20024 Stage1AirInst *target = instruction->target->child;
20025 if (type_is_invalid(target->value->type))
20026 return ira->codegen->invalid_inst_gen;
20027
2002820023 ZigType *scalar_target_type = (target->value->type->id == ZigTypeIdVector) ?
2002920024 target->value->type->data.vector.elem_type : target->value->type;
2003020025
2003120026 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'",
2003320028 buf_ptr(&scalar_target_type->name)));
2003420029 return ira->codegen->invalid_inst_gen;
2003520030 }
......@@ -20039,10 +20034,24 @@ static Stage1AirInst *ir_analyze_instruction_int_cast(IrAnalyze *ira, Stage1ZirI
2003920034 if (val == nullptr)
2004020035 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);
2004320038 }
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);
2004620055}
2004720056
2004820057static 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
2428224291 if (type_is_invalid(target->value->type))
2428324292 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);
2428624297 if (type_is_invalid(casted_target->value->type))
2428724298 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
34823482 }
34833483}
34843484
3485
3486Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {
3485static Buf *token_identifier_buf2(RootStruct *root_struct, TokenIndex token, bool *is_at_syntax) {
34873486 Error err;
34883487 const char *source = buf_ptr(root_struct->source_code);
34893488 size_t byte_offset = root_struct->token_locs[token].offset;
......@@ -3495,6 +3494,7 @@ Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {
34953494 assert(source[byte_offset] != '.'); // wrong token index
34963495
34973496 if (source[byte_offset] == '@') {
3497 *is_at_syntax = true;
34983498 size_t bad_index;
34993499 Buf *str = buf_alloc();
35003500 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) {
35033503 }
35043504 return str;
35053505 } else {
3506 *is_at_syntax = false;
35063507 size_t start = byte_offset;
35073508 for (;; byte_offset += 1) {
35083509 if (source[byte_offset] == 0) break;
......@@ -3519,7 +3520,17 @@ Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {
35193520 }
35203521}
35213522
3523Buf *token_identifier_buf(RootStruct *root_struct, TokenIndex token) {
3524 bool trash;
3525 return token_identifier_buf2(root_struct, token, &trash);
3526}
3527
35223528Buf *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) {
35233534 assert(node->type == NodeTypeIdentifier);
35243535 // Currently, stage1 runs astgen for every comptime function call,
35253536 // resulting the allocation here wasting memory. As a workaround until
......@@ -3527,8 +3538,10 @@ Buf *node_identifier_buf(AstNode *node) {
35273538 // we memoize the result into the AST here.
35283539 if (node->data.identifier.name == nullptr) {
35293540 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);
35313543 }
3544 *is_at_syntax = node->data.identifier.is_at_syntax;
35323545 return node->data.identifier.name;
35333546}
35343547
src/stage1/parser.hpp+1
......@@ -19,6 +19,7 @@ void ast_print(AstNode *node, int indent);
1919void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *context), void *context);
2020
2121Buf *node_identifier_buf(AstNode *node);
22Buf *node_identifier_buf2(AstNode *node, bool *is_at_syntax);
2223
2324Buf *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) {
925925 case ZigLLVM_UnknownArch:
926926 zig_unreachable();
927927 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 ||
929929 (target->os == OsWindows && target->abi != ZigLLVM_MSVC));
930930 default:
931931 return false;
src/target.zig+1-1
......@@ -166,7 +166,7 @@ pub fn isSingleThreaded(target: std.Target) bool {
166166pub fn hasValgrindSupport(target: std.Target) bool {
167167 switch (target.cpu.arch) {
168168 .x86_64 => {
169 return target.os.tag == .linux or target.isDarwin() or target.os.tag == .solaris or
169 return target.os.tag == .linux or target.os.tag == .solaris or
170170 (target.os.tag == .windows and target.abi != .msvc);
171171 },
172172 else => return false,
src/translate_c.zig+73-6
......@@ -719,6 +719,30 @@ fn transQualTypeMaybeInitialized(c: *Context, scope: *Scope, qt: clang.QualType,
719719 transQualType(c, scope, qt, loc);
720720}
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
722746/// if mangled_name is not null, this var decl was declared in a block scope.
723747fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]const u8) Error!void {
724748 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
779803 };
780804 if (!qualTypeIsBoolean(qual_type) and isBoolRes(init_node.?)) {
781805 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.?);
782808 }
783809 } else {
784810 init_node = Tag.undefined_literal.init();
......@@ -1101,9 +1127,10 @@ fn transRecordDecl(c: *Context, scope: *Scope, record_decl: *const clang.RecordD
11011127 record_payload.* = .{
11021128 .base = .{ .tag = ([2]Tag{ .@"struct", .@"union" })[@boolToInt(is_union)] },
11031129 .data = .{
1104 .is_packed = is_packed,
1130 .layout = if (is_packed) .@"packed" else .@"extern",
11051131 .fields = try c.arena.dupe(ast.Payload.Record.Field, fields.items),
11061132 .functions = try c.arena.dupe(Node, functions.items),
1133 .variables = &.{},
11071134 },
11081135 };
11091136 break :blk Node.initPayload(&record_payload.base);
......@@ -1805,6 +1832,9 @@ fn transDeclStmtOne(
18051832 Tag.undefined_literal.init();
18061833 if (!qualTypeIsBoolean(qual_type) and isBoolRes(init_node)) {
18071834 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);
18081838 }
18091839
18101840 const var_name: []const u8 = if (is_static_local) Scope.Block.StaticInnerName else mangled_name;
......@@ -2522,9 +2552,19 @@ fn transInitListExprRecord(
25222552 raw_name = try mem.dupe(c.arena, u8, name);
25232553 }
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 }
25252565 try field_inits.append(.{
25262566 .name = raw_name,
2527 .value = try transExpr(c, scope, elem_expr, .used),
2567 .value = init_expr,
25282568 });
25292569 }
25302570 if (ty_node.castTag(.identifier)) |ident_node| {
......@@ -3459,6 +3499,10 @@ fn transCallExpr(c: *Context, scope: *Scope, stmt: *const clang.CallExpr, result
34593499 const param_qt = fn_proto.getParamType(@intCast(c_uint, i));
34603500 if (isBoolRes(arg) and cIsNativeInt(param_qt)) {
34613501 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);
34623506 }
34633507 }
34643508 },
......@@ -3835,6 +3879,12 @@ fn transCreateCompoundAssign(
38353879 return block_scope.complete(c);
38363880}
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
38383888fn transCPtrCast(
38393889 c: *Context,
38403890 scope: *Scope,
......@@ -3854,10 +3904,7 @@ fn transCPtrCast(
38543904 (src_child_type.isVolatileQualified() and
38553905 !child_type.isVolatileQualified())))
38563906 {
3857 // Casting away const or volatile requires us to use @intToPtr
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;
3907 return removeCVQualifiers(c, dst_type_node, expr);
38613908 } else {
38623909 // Implicit downcasting from higher to lower alignment values is forbidden,
38633910 // use @alignCast to side-step this problem
......@@ -4217,6 +4264,26 @@ fn typeIsOpaque(c: *Context, ty: *const clang.Type, loc: clang.SourceLocation) b
42174264 }
42184265}
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
42204287fn cIsInteger(qt: clang.QualType) bool {
42214288 return cIsSignedInteger(qt) or cIsUnsignedInteger(qt);
42224289}
src/translate_c/ast.zig+49-17
......@@ -62,6 +62,8 @@ pub const Node = extern union {
6262 var_decl,
6363 /// const name = struct { init }
6464 static_local_var,
65 /// var name = init.*
66 mut_str,
6567 func,
6668 warning,
6769 @"struct",
......@@ -361,7 +363,7 @@ pub const Node = extern union {
361363 .array_type, .null_sentinel_array_type => Payload.Array,
362364 .arg_redecl, .alias, .fail_decl => Payload.ArgRedecl,
363365 .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,
365367 .enum_constant => Payload.EnumConstant,
366368 .array_filler => Payload.ArrayFiller,
367369 .pub_inline_fn => Payload.PubInlineFn,
......@@ -558,9 +560,10 @@ pub const Payload = struct {
558560 pub const Record = struct {
559561 base: Payload,
560562 data: struct {
561 is_packed: bool,
563 layout: enum { @"packed", @"extern", none },
562564 fields: []Field,
563565 functions: []Node,
566 variables: []Node,
564567 },
565568
566569 pub const Field = struct {
......@@ -925,23 +928,23 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
925928 return renderCall(c, lhs, payload.args);
926929 },
927930 .null_literal => return c.addNode(.{
928 .tag = .null_literal,
929 .main_token = try c.addToken(.keyword_null, "null"),
931 .tag = .identifier,
932 .main_token = try c.addToken(.identifier, "null"),
930933 .data = undefined,
931934 }),
932935 .undefined_literal => return c.addNode(.{
933 .tag = .undefined_literal,
934 .main_token = try c.addToken(.keyword_undefined, "undefined"),
936 .tag = .identifier,
937 .main_token = try c.addToken(.identifier, "undefined"),
935938 .data = undefined,
936939 }),
937940 .true_literal => return c.addNode(.{
938 .tag = .true_literal,
939 .main_token = try c.addToken(.keyword_true, "true"),
941 .tag = .identifier,
942 .main_token = try c.addToken(.identifier, "true"),
940943 .data = undefined,
941944 }),
942945 .false_literal => return c.addNode(.{
943 .tag = .false_literal,
944 .main_token = try c.addToken(.keyword_false, "false"),
946 .tag = .identifier,
947 .main_token = try c.addToken(.identifier, "false"),
945948 .data = undefined,
946949 }),
947950 .zero_literal => return c.addNode(.{
......@@ -1229,6 +1232,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
12291232 },
12301233 });
12311234 _ = try c.addToken(.r_brace, "}");
1235 _ = try c.addToken(.semicolon, ";");
12321236
12331237 return c.addNode(.{
12341238 .tag = .simple_var_decl,
......@@ -1239,6 +1243,29 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
12391243 },
12401244 });
12411245 },
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 },
12421269 .var_decl => return renderVar(c, node),
12431270 .arg_redecl, .alias => {
12441271 const payload = @fieldParentPtr(Payload.ArgRedecl, "base", node.ptr_otherwise).data;
......@@ -1572,8 +1599,8 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
15721599 const while_tok = try c.addToken(.keyword_while, "while");
15731600 _ = try c.addToken(.l_paren, "(");
15741601 const cond = try c.addNode(.{
1575 .tag = .true_literal,
1576 .main_token = try c.addToken(.keyword_true, "true"),
1602 .tag = .identifier,
1603 .main_token = try c.addToken(.identifier, "true"),
15771604 .data = undefined,
15781605 });
15791606 _ = try c.addToken(.r_paren, ")");
......@@ -1952,9 +1979,9 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
19521979
19531980fn renderRecord(c: *Context, node: Node) !NodeIndex {
19541981 const payload = @fieldParentPtr(Payload.Record, "base", node.ptr_otherwise).data;
1955 if (payload.is_packed)
1982 if (payload.layout == .@"packed")
19561983 _ = try c.addToken(.keyword_packed, "packed")
1957 else
1984 else if (payload.layout == .@"extern")
19581985 _ = try c.addToken(.keyword_extern, "extern");
19591986 const kind_tok = if (node.tag() == .@"struct")
19601987 try c.addToken(.keyword_struct, "struct")
......@@ -1963,8 +1990,9 @@ fn renderRecord(c: *Context, node: Node) !NodeIndex {
19631990
19641991 _ = try c.addToken(.l_brace, "{");
19651992
1993 const num_vars = payload.variables.len;
19661994 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;
19681996 const members = try c.gpa.alloc(NodeIndex, std.math.max(total_members, 2));
19691997 defer c.gpa.free(members);
19701998 members[0] = 0;
......@@ -2006,8 +2034,11 @@ fn renderRecord(c: *Context, node: Node) !NodeIndex {
20062034 });
20072035 _ = try c.addToken(.comma, ",");
20082036 }
2037 for (payload.variables) |variable, i| {
2038 members[payload.fields.len + i] = try renderNode(c, variable);
2039 }
20092040 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);
20112042 }
20122043 _ = try c.addToken(.r_brace, "}");
20132044
......@@ -2140,7 +2171,7 @@ fn renderNullSentinelArrayType(c: *Context, len: usize, elem_type: Node) !NodeIn
21402171fn addSemicolonIfNeeded(c: *Context, node: Node) !void {
21412172 switch (node.tag()) {
21422173 .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 => {},
21442175 .while_true => {
21452176 const payload = node.castTag(.while_true).?.data;
21462177 return addSemicolonIfNotBlock(c, payload);
......@@ -2235,6 +2266,7 @@ fn renderNodeGrouped(c: *Context, node: Node) !NodeIndex {
22352266 .offset_of,
22362267 .shuffle,
22372268 .static_local_var,
2269 .mut_str,
22382270 => {
22392271 // no grouping needed
22402272 return renderNode(c, node);
src/type.zig+39
......@@ -133,6 +133,7 @@ pub const Type = extern union {
133133
134134 .@"union",
135135 .union_tagged,
136 .type_info,
136137 => return .Union,
137138
138139 .var_args_param => unreachable, // can be any type
......@@ -248,6 +249,30 @@ pub const Type = extern union {
248249 };
249250 }
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
251276 pub fn ptrInfo(self: Type) Payload.Pointer {
252277 switch (self.tag()) {
253278 .single_const_pointer_to_comptime_int => return .{ .data = .{
......@@ -717,6 +742,7 @@ pub const Type = extern union {
717742 .call_options,
718743 .export_options,
719744 .extern_options,
745 .type_info,
720746 .@"anyframe",
721747 .generic_poison,
722748 => unreachable,
......@@ -928,6 +954,7 @@ pub const Type = extern union {
928954 .call_options => return writer.writeAll("std.builtin.CallOptions"),
929955 .export_options => return writer.writeAll("std.builtin.ExportOptions"),
930956 .extern_options => return writer.writeAll("std.builtin.ExternOptions"),
957 .type_info => return writer.writeAll("std.builtin.TypeInfo"),
931958 .function => {
932959 const payload = ty.castTag(.function).?.data;
933960 try writer.writeAll("fn(");
......@@ -1178,6 +1205,7 @@ pub const Type = extern union {
11781205 .comptime_int,
11791206 .comptime_float,
11801207 .enum_literal,
1208 .type_info,
11811209 => true,
11821210
11831211 .var_args_param => unreachable,
......@@ -1269,6 +1297,7 @@ pub const Type = extern union {
12691297 .call_options => return Value.initTag(.call_options_type),
12701298 .export_options => return Value.initTag(.export_options_type),
12711299 .extern_options => return Value.initTag(.extern_options_type),
1300 .type_info => return Value.initTag(.type_info_type),
12721301 .inferred_alloc_const => unreachable,
12731302 .inferred_alloc_mut => unreachable,
12741303 else => return Value.Tag.ty.create(allocator, self),
......@@ -1409,6 +1438,7 @@ pub const Type = extern union {
14091438 .empty_struct,
14101439 .empty_struct_literal,
14111440 .@"opaque",
1441 .type_info,
14121442 => false,
14131443
14141444 .inferred_alloc_const => unreachable,
......@@ -1636,6 +1666,7 @@ pub const Type = extern union {
16361666 .inferred_alloc_mut,
16371667 .@"opaque",
16381668 .var_args_param,
1669 .type_info,
16391670 => unreachable,
16401671
16411672 .generic_poison => unreachable,
......@@ -1667,6 +1698,7 @@ pub const Type = extern union {
16671698 .@"opaque" => unreachable,
16681699 .var_args_param => unreachable,
16691700 .generic_poison => unreachable,
1701 .type_info => unreachable,
16701702
16711703 .@"struct" => {
16721704 const s = self.castTag(.@"struct").?.data;
......@@ -1978,6 +2010,7 @@ pub const Type = extern union {
19782010 .call_options,
19792011 .export_options,
19802012 .extern_options,
2013 .type_info,
19812014 => @panic("TODO at some point we gotta resolve builtin types"),
19822015 };
19832016 }
......@@ -2691,6 +2724,7 @@ pub const Type = extern union {
26912724 .call_options,
26922725 .export_options,
26932726 .extern_options,
2727 .type_info,
26942728 .@"anyframe",
26952729 .anyframe_T,
26962730 .many_const_pointer,
......@@ -2778,6 +2812,7 @@ pub const Type = extern union {
27782812 return switch (self.tag()) {
27792813 .@"struct" => &self.castTag(.@"struct").?.data.namespace,
27802814 .enum_full => &self.castTag(.enum_full).?.data.namespace,
2815 .enum_nonexhaustive => &self.castTag(.enum_nonexhaustive).?.data.namespace,
27812816 .empty_struct => self.castTag(.empty_struct).?.data,
27822817 .@"opaque" => &self.castTag(.@"opaque").?.data,
27832818 .@"union" => &self.castTag(.@"union").?.data.namespace,
......@@ -3022,6 +3057,7 @@ pub const Type = extern union {
30223057 .call_options,
30233058 .export_options,
30243059 .extern_options,
3060 .type_info,
30253061 => @panic("TODO resolve std.builtin types"),
30263062 else => unreachable,
30273063 }
......@@ -3058,6 +3094,7 @@ pub const Type = extern union {
30583094 .call_options,
30593095 .export_options,
30603096 .extern_options,
3097 .type_info,
30613098 => @panic("TODO resolve std.builtin types"),
30623099 else => unreachable,
30633100 }
......@@ -3167,6 +3204,7 @@ pub const Type = extern union {
31673204 call_options,
31683205 export_options,
31693206 extern_options,
3207 type_info,
31703208 manyptr_u8,
31713209 manyptr_const_u8,
31723210 fn_noreturn_no_args,
......@@ -3289,6 +3327,7 @@ pub const Type = extern union {
32893327 .call_options,
32903328 .export_options,
32913329 .extern_options,
3330 .type_info,
32923331 .@"anyframe",
32933332 => @compileError("Type Tag " ++ @tagName(t) ++ " has no payload"),
32943333
src/value.zig+128-9
......@@ -68,6 +68,7 @@ pub const Value = extern union {
6868 call_options_type,
6969 export_options_type,
7070 extern_options_type,
71 type_info_type,
7172 manyptr_u8_type,
7273 manyptr_const_u8_type,
7374 fn_noreturn_no_args_type,
......@@ -132,12 +133,21 @@ pub const Value = extern union {
132133 /// When the type is error union:
133134 /// * If the tag is `.@"error"`, the error union is an error.
134135 /// * 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 union
136 /// * A nested error such as `anyerror!(anyerror!T)` in which the the outer error union
136137 /// is non-error, but the inner error union is an error, is represented as
137138 /// a tag of `.eu_payload`, with a sub-tag of `.@"error"`.
138139 eu_payload,
139140 /// A pointer to the payload of an error union, based on a pointer to an error union.
140141 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,
141151 /// An instance of a struct.
142152 @"struct",
143153 /// An instance of a union.
......@@ -221,6 +231,7 @@ pub const Value = extern union {
221231 .call_options_type,
222232 .export_options_type,
223233 .extern_options_type,
234 .type_info_type,
224235 .generic_poison,
225236 => @compileError("Value Tag " ++ @tagName(t) ++ " has no payload"),
226237
......@@ -236,6 +247,8 @@ pub const Value = extern union {
236247 .repeated,
237248 .eu_payload,
238249 .eu_payload_ptr,
250 .opt_payload,
251 .opt_payload_ptr,
239252 => Payload.SubValue,
240253
241254 .bytes,
......@@ -402,6 +415,7 @@ pub const Value = extern union {
402415 .call_options_type,
403416 .export_options_type,
404417 .extern_options_type,
418 .type_info_type,
405419 .generic_poison,
406420 => unreachable,
407421
......@@ -456,7 +470,12 @@ pub const Value = extern union {
456470 return Value{ .ptr_otherwise = &new_payload.base };
457471 },
458472 .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 => {
460479 const payload = self.cast(Payload.SubValue).?;
461480 const new_payload = try allocator.create(Payload.SubValue);
462481 new_payload.* = .{
......@@ -585,6 +604,7 @@ pub const Value = extern union {
585604 .call_options_type => return out_stream.writeAll("std.builtin.CallOptions"),
586605 .export_options_type => return out_stream.writeAll("std.builtin.ExportOptions"),
587606 .extern_options_type => return out_stream.writeAll("std.builtin.ExternOptions"),
607 .type_info_type => return out_stream.writeAll("std.builtin.TypeInfo"),
588608 .abi_align_default => return out_stream.writeAll("(default ABI alignment)"),
589609
590610 .empty_struct_value => return out_stream.writeAll("struct {}{}"),
......@@ -652,12 +672,20 @@ pub const Value = extern union {
652672 try out_stream.writeAll("(eu_payload) ");
653673 val = val.castTag(.eu_payload).?.data;
654674 },
675 .opt_payload => {
676 try out_stream.writeAll("(opt_payload) ");
677 val = val.castTag(.opt_payload).?.data;
678 },
655679 .inferred_alloc => return out_stream.writeAll("(inferred allocation value)"),
656680 .inferred_alloc_comptime => return out_stream.writeAll("(inferred comptime allocation value)"),
657681 .eu_payload_ptr => {
658682 try out_stream.writeAll("(eu_payload_ptr)");
659683 val = val.castTag(.eu_payload_ptr).?.data;
660684 },
685 .opt_payload_ptr => {
686 try out_stream.writeAll("(opt_payload_ptr)");
687 val = val.castTag(.opt_payload_ptr).?.data;
688 },
661689 };
662690 }
663691
......@@ -743,6 +771,7 @@ pub const Value = extern union {
743771 .call_options_type => Type.initTag(.call_options),
744772 .export_options_type => Type.initTag(.export_options),
745773 .extern_options_type => Type.initTag(.extern_options),
774 .type_info_type => Type.initTag(.type_info),
746775
747776 .int_type => {
748777 const payload = self.castTag(.int_type).?.data;
......@@ -771,6 +800,38 @@ pub const Value = extern union {
771800 }
772801 }
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
774835 /// Asserts the value is an integer.
775836 pub fn toBigInt(self: Value, space: *BigIntSpace) BigIntConst {
776837 switch (self.tag()) {
......@@ -1127,7 +1188,10 @@ pub const Value = extern union {
11271188 }
11281189
11291190 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) {
11311195 .BoundFn => unreachable, // TODO remove this from the language
11321196
11331197 .Void,
......@@ -1152,7 +1216,10 @@ pub const Value = extern union {
11521216 }
11531217 },
11541218 .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));
11561223 },
11571224 .Pointer => {
11581225 @panic("TODO implement hashing pointer values");
......@@ -1164,7 +1231,15 @@ pub const Value = extern union {
11641231 @panic("TODO implement hashing struct values");
11651232 },
11661233 .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 }
11681243 },
11691244 .ErrorUnion => {
11701245 @panic("TODO implement hashing error union values");
......@@ -1173,7 +1248,16 @@ pub const Value = extern union {
11731248 @panic("TODO implement hashing error set values");
11741249 },
11751250 .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 }
11771261 },
11781262 .Union => {
11791263 @panic("TODO implement hashing union values");
......@@ -1252,6 +1336,11 @@ pub const Value = extern union {
12521336 const err_union_val = (try err_union_ptr.pointerDeref(allocator)) orelse return null;
12531337 break :blk err_union_val.castTag(.eu_payload).?.data;
12541338 },
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
12561345 .zero,
12571346 .one,
......@@ -1349,13 +1438,14 @@ pub const Value = extern union {
13491438 /// Valid for all types. Asserts the value is not undefined and not unreachable.
13501439 pub fn isNull(self: Value) bool {
13511440 return switch (self.tag()) {
1441 .null_value => true,
1442 .opt_payload => false,
1443
13521444 .undef => unreachable,
13531445 .unreachable_value => unreachable,
13541446 .inferred_alloc => unreachable,
13551447 .inferred_alloc_comptime => unreachable,
1356 .null_value => true,
1357
1358 else => false,
1448 else => unreachable,
13591449 };
13601450 }
13611451
......@@ -1385,6 +1475,10 @@ pub const Value = extern union {
13851475 return switch (val.tag()) {
13861476 .eu_payload => true,
13871477 else => false,
1478
1479 .undef => unreachable,
1480 .inferred_alloc => unreachable,
1481 .inferred_alloc_comptime => unreachable,
13881482 };
13891483 }
13901484
......@@ -1514,6 +1608,31 @@ pub const Value = extern union {
15141608 return Tag.int_u64.create(arena, truncated);
15151609 }
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
15171636 pub fn floatAdd(
15181637 lhs: Value,
15191638 rhs: Value,
test/behavior.zig+2-1
......@@ -9,12 +9,13 @@ test {
99 _ = @import("behavior/pointers.zig");
1010 _ = @import("behavior/if.zig");
1111 _ = @import("behavior/cast.zig");
12 _ = @import("behavior/array.zig");
1213
1314 if (!builtin.zig_is_stage2) {
1415 // Tests that only pass for stage1.
1516 _ = @import("behavior/align.zig");
1617 _ = @import("behavior/alignof.zig");
17 _ = @import("behavior/array.zig");
18 _ = @import("behavior/array_stage1.zig");
1819 if (builtin.os.tag != .wasi) {
1920 _ = @import("behavior/asm.zig");
2021 _ = @import("behavior/async_fn.zig");
test/behavior/array.zig-484
......@@ -3,487 +3,3 @@ const testing = std.testing;
33const mem = std.mem;
44const expect = testing.expect;
55const 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" {
203203 try testIntToEnumEval(3);
204204}
205205fn testIntToEnumEval(x: i32) !void {
206 try expect(@intToEnum(IntToEnumNumber, @intCast(u3, x)) == IntToEnumNumber.Three);
206 try expect(@intToEnum(IntToEnumNumber, x) == IntToEnumNumber.Three);
207207}
208208const IntToEnumNumber = enum {
209209 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
412412test "return result loc as peer result loc in inferred error set function" {
413413 const S = struct {
414414 fn doTheTest() !void {
415 if (foo(2)) |x| {
415 if (quux(2)) |x| {
416416 try expect(x.Two);
417417 } else |e| switch (e) {
418418 error.Whatever => @panic("fail"),
419419 }
420 try expectError(error.Whatever, foo(99));
420 try expectError(error.Whatever, quux(99));
421421 }
422422 const FormValue = union(enum) {
423423 One: void,
424424 Two: bool,
425425 };
426426
427 fn foo(id: u64) !FormValue {
427 fn quux(id: u64) !FormValue {
428428 return switch (id) {
429429 2 => FormValue{ .Two = true },
430430 1 => FormValue{ .One = {} },
......@@ -452,11 +452,11 @@ test "error payload type is correctly resolved" {
452452
453453test "error union comptime caching" {
454454 const S = struct {
455 fn foo(comptime arg: anytype) void {
455 fn quux(comptime arg: anytype) void {
456456 arg catch {};
457457 }
458458 };
459459
460 S.foo(@as(anyerror!void, {}));
461 S.foo(@as(anyerror!void, {}));
460 S.quux(@as(anyerror!void, {}));
461 S.quux(@as(anyerror!void, {}));
462462}
test/behavior/eval.zig+31
......@@ -130,3 +130,34 @@ test "no undeclared identifier error in unanalyzed branches" {
130130 lol_this_doesnt_exist = nonsense;
131131 }
132132}
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" {
356356 try expect(s[3] == 0xd0e0f10);
357357}
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
372359test "comptime function with mutable pointer is not memoized" {
373360 comptime {
374361 var x: i32 = 1;
test/behavior/generics.zig+39
......@@ -78,3 +78,42 @@ fn max_i32(a: i32, b: i32) i32 {
7878fn max_f64(a: f64, b: f64) f64 {
7979 return max_anytype(a, b);
8080}
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;
33const expect = testing.expect;
44const 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
276test "generic struct" {
287 var a1 = GenNode(i32){
298 .value = 13,
test/behavior/misc.zig+33
......@@ -505,3 +505,36 @@ test "lazy typeInfo value as generic parameter" {
505505 };
506506 S.foo(@typeInfo(@TypeOf(.{})));
507507}
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 {
162162};
163163
164164test "return struct byval from function" {
165 const bar = makeBar(1234, 5678);
165 const bar = makeBar2(1234, 5678);
166166 try expect(bar.y == 5678);
167167}
168168const Bar = struct {
169169 x: i32,
170170 y: i32,
171171};
172fn makeBar(x: i32, y: i32) Bar {
172fn makeBar2(x: i32, y: i32) Bar {
173173 return Bar{
174174 .x = x,
175175 .y = y,
test/cases.zig+1-1
......@@ -26,7 +26,7 @@ pub fn addCases(ctx: *TestContext) !void {
2626 var case = ctx.exe("hello world with updates", linux_x64);
2727
2828 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'",
3030 });
3131
3232 // Incorrect return type
test/compare_output.zig+2-20
......@@ -585,16 +585,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
585585 \\ comptime format: []const u8,
586586 \\ args: anytype,
587587 \\) void {
588 \\ const level_txt = switch (level) {
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 \\ };
588 \\ const level_txt = comptime level.asText();
598589 \\ const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
599590 \\ const stdout = std.io.getStdOut().writer();
600591 \\ nosuspend stdout.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;
......@@ -638,16 +629,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
638629 \\ comptime format: []const u8,
639630 \\ args: anytype,
640631 \\) void {
641 \\ const level_txt = switch (level) {
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 \\ };
632 \\ const level_txt = comptime level.asText();
651633 \\ const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
652634 \\ const stdout = std.io.getStdOut().writer();
653635 \\ 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 {
69696969 "tmp.zig:2:30: error: cannot set section of local variable 'foo'",
69706970 });
69716971
6972 ctx.objErrStage1("inner struct member shadowing outer struct member",
6973 \\fn A() type {
6974 \\ return struct {
6975 \\ b: B(),
6976 \\
6977 \\ const Self = @This();
6978 \\
6979 \\ fn B() type {
6980 \\ return struct {
6981 \\ const Self = @This();
6982 \\ };
6972 ctx.objErrStage1("ambiguous decl reference",
6973 \\fn foo() void {}
6974 \\fn bar() void {
6975 \\ const S = struct {
6976 \\ fn baz() void {
6977 \\ foo();
69836978 \\ }
6979 \\ fn foo() void {}
69846980 \\ };
6981 \\ S.baz();
69856982 \\}
6986 \\comptime {
6987 \\ assert(A().B().Self != A().Self);
6988 \\}
6989 \\fn assert(ok: bool) void {
6990 \\ if (!ok) unreachable;
6983 \\export fn entry() void {
6984 \\ bar();
69916985 \\}
69926986 , &[_][]const u8{
6993 "tmp.zig:9:17: error: redefinition of 'Self'",
6994 "tmp.zig:5:9: note: previous definition here",
6987 "tmp.zig:5:13: error: ambiguous reference",
6988 "tmp.zig:7:9: note: declared here",
6989 "tmp.zig:1:1: note: also declared here",
69956990 });
69966991
69976992 ctx.objErrStage1("while expected bool, got optional",
......@@ -7263,14 +7258,36 @@ pub fn addCases(ctx: *TestContext) !void {
72637258 "tmp.zig:2:17: error: expected type 'u3', found 'u8'",
72647259 });
72657260
7266 ctx.objErrStage1("globally shadowing a primitive type",
7267 \\const u16 = u8;
7261 ctx.objErrStage1("locally shadowing a primitive type",
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;
72687284 \\export fn entry() void {
7269 \\ const a: u16 = 300;
7285 \\ const a: u8 = 300;
72707286 \\ _ = a;
72717287 \\}
72727288 , &[_][]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",
72747291 });
72757292
72767293 ctx.objErrStage1("implicitly increasing pointer alignment",
......@@ -7691,12 +7708,12 @@ pub fn addCases(ctx: *TestContext) !void {
76917708 \\};
76927709 \\
76937710 \\export fn entry() void {
7694 \\ var y = @as(u3, 3);
7711 \\ var y = @as(f32, 3);
76957712 \\ var x = @intToEnum(Small, y);
76967713 \\ _ = x;
76977714 \\}
76987715 , &[_][]const u8{
7699 "tmp.zig:10:31: error: expected type 'u2', found 'u3'",
7716 "tmp.zig:10:31: error: expected integer type, found 'f32'",
77007717 });
77017718
77027719 ctx.objErrStage1("union fields with value assignments",
test/run_translated_c.zig+18
......@@ -1749,4 +1749,22 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {
17491749 \\ return 0;
17501750 \\}
17511751 , "");
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 , "");
17521770}
test/stage2/arm.zig+102
......@@ -204,6 +204,48 @@ pub fn addCases(ctx: *TestContext) !void {
204204 ,
205205 "123456",
206206 );
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 );
207249 }
208250
209251 {
......@@ -319,6 +361,22 @@ pub fn addCases(ctx: *TestContext) !void {
319361 ,
320362 "",
321363 );
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 );
322380 }
323381
324382 {
......@@ -429,4 +487,48 @@ pub fn addCases(ctx: *TestContext) !void {
429487 "",
430488 );
431489 }
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 }
432534}
test/stage2/cbe.zig+38
......@@ -555,6 +555,19 @@ pub fn addCases(ctx: *TestContext) !void {
555555 \\ return p.y - p.x - p.x;
556556 \\}
557557 , "");
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 , "");
558571 }
559572
560573 {
......@@ -808,6 +821,31 @@ pub fn addCases(ctx: *TestContext) !void {
808821 });
809822 }
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
811849 {
812850 var case = ctx.exeFromCompiledC("inferred error sets", .{});
813851
test/stage2/darwin.zig+1-1
......@@ -14,7 +14,7 @@ pub fn addCases(ctx: *TestContext) !void {
1414 {
1515 var case = ctx.exe("hello world with updates", target);
1616 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'",
1818 });
1919
2020 // Incorrect return type
test/stage2/llvm.zig+25
......@@ -28,6 +28,31 @@ pub fn addCases(ctx: *TestContext) !void {
2828 , "");
2929 }
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
3156 {
3257 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}