authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-06-04 02:58:55-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-06-04 02:58:55-04:00
log58ce79f9352a6139c873df6d99d1531101350e9f
tree227df3571b4ac48afc38777902251647870c5e1b
parentcb042c8343eb94a8d149fe1f5d69aa2746aa85d0
parent96164ce61377b36bcaf0c4087ca9b1ab822b9457

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


189 files changed, 9205 insertions(+), 6311 deletions(-)

build.zig+7-7
...@@ -10,7 +10,7 @@ const ArrayList = std.ArrayList;...@@ -10,7 +10,7 @@ const ArrayList = std.ArrayList;
10const Buffer = std.Buffer;10const Buffer = std.Buffer;
11const io = std.io;11const io = std.io;
1212
13pub fn build(b: &Builder) !void {13pub fn build(b: *Builder) !void {
14 const mode = b.standardReleaseOptions();14 const mode = b.standardReleaseOptions();
1515
16 var docgen_exe = b.addExecutable("docgen", "doc/docgen.zig");16 var docgen_exe = b.addExecutable("docgen", "doc/docgen.zig");
...@@ -132,7 +132,7 @@ pub fn build(b: &Builder) !void {...@@ -132,7 +132,7 @@ pub fn build(b: &Builder) !void {
132 test_step.dependOn(tests.addGenHTests(b, test_filter));132 test_step.dependOn(tests.addGenHTests(b, test_filter));
133}133}
134134
135fn dependOnLib(lib_exe_obj: &std.build.LibExeObjStep, dep: &const LibraryDep) void {135fn dependOnLib(lib_exe_obj: *std.build.LibExeObjStep, dep: *const LibraryDep) void {
136 for (dep.libdirs.toSliceConst()) |lib_dir| {136 for (dep.libdirs.toSliceConst()) |lib_dir| {
137 lib_exe_obj.addLibPath(lib_dir);137 lib_exe_obj.addLibPath(lib_dir);
138 }138 }
...@@ -147,7 +147,7 @@ fn dependOnLib(lib_exe_obj: &std.build.LibExeObjStep, dep: &const LibraryDep) vo...@@ -147,7 +147,7 @@ fn dependOnLib(lib_exe_obj: &std.build.LibExeObjStep, dep: &const LibraryDep) vo
147 }147 }
148}148}
149149
150fn addCppLib(b: &Builder, lib_exe_obj: &std.build.LibExeObjStep, cmake_binary_dir: []const u8, lib_name: []const u8) void {150fn addCppLib(b: *Builder, lib_exe_obj: *std.build.LibExeObjStep, cmake_binary_dir: []const u8, lib_name: []const u8) void {
151 const lib_prefix = if (lib_exe_obj.target.isWindows()) "" else "lib";151 const lib_prefix = if (lib_exe_obj.target.isWindows()) "" else "lib";
152 lib_exe_obj.addObjectFile(os.path.join(b.allocator, cmake_binary_dir, "zig_cpp", b.fmt("{}{}{}", lib_prefix, lib_name, lib_exe_obj.target.libFileExt())) catch unreachable);152 lib_exe_obj.addObjectFile(os.path.join(b.allocator, cmake_binary_dir, "zig_cpp", b.fmt("{}{}{}", lib_prefix, lib_name, lib_exe_obj.target.libFileExt())) catch unreachable);
153}153}
...@@ -159,7 +159,7 @@ const LibraryDep = struct {...@@ -159,7 +159,7 @@ const LibraryDep = struct {
159 includes: ArrayList([]const u8),159 includes: ArrayList([]const u8),
160};160};
161161
162fn findLLVM(b: &Builder, llvm_config_exe: []const u8) !LibraryDep {162fn findLLVM(b: *Builder, llvm_config_exe: []const u8) !LibraryDep {
163 const libs_output = try b.exec([][]const u8{163 const libs_output = try b.exec([][]const u8{
164 llvm_config_exe,164 llvm_config_exe,
165 "--libs",165 "--libs",
...@@ -217,7 +217,7 @@ fn findLLVM(b: &Builder, llvm_config_exe: []const u8) !LibraryDep {...@@ -217,7 +217,7 @@ fn findLLVM(b: &Builder, llvm_config_exe: []const u8) !LibraryDep {
217 return result;217 return result;
218}218}
219219
220pub fn installStdLib(b: &Builder, stdlib_files: []const u8) void {220pub fn installStdLib(b: *Builder, stdlib_files: []const u8) void {
221 var it = mem.split(stdlib_files, ";");221 var it = mem.split(stdlib_files, ";");
222 while (it.next()) |stdlib_file| {222 while (it.next()) |stdlib_file| {
223 const src_path = os.path.join(b.allocator, "std", stdlib_file) catch unreachable;223 const src_path = os.path.join(b.allocator, "std", stdlib_file) catch unreachable;
...@@ -226,7 +226,7 @@ pub fn installStdLib(b: &Builder, stdlib_files: []const u8) void {...@@ -226,7 +226,7 @@ pub fn installStdLib(b: &Builder, stdlib_files: []const u8) void {
226 }226 }
227}227}
228228
229pub fn installCHeaders(b: &Builder, c_header_files: []const u8) void {229pub fn installCHeaders(b: *Builder, c_header_files: []const u8) void {
230 var it = mem.split(c_header_files, ";");230 var it = mem.split(c_header_files, ";");
231 while (it.next()) |c_header_file| {231 while (it.next()) |c_header_file| {
232 const src_path = os.path.join(b.allocator, "c_headers", c_header_file) catch unreachable;232 const src_path = os.path.join(b.allocator, "c_headers", c_header_file) catch unreachable;
...@@ -235,7 +235,7 @@ pub fn installCHeaders(b: &Builder, c_header_files: []const u8) void {...@@ -235,7 +235,7 @@ pub fn installCHeaders(b: &Builder, c_header_files: []const u8) void {
235 }235 }
236}236}
237237
238fn nextValue(index: &usize, build_info: []const u8) []const u8 {238fn nextValue(index: *usize, build_info: []const u8) []const u8 {
239 const start = index.*;239 const start = index.*;
240 while (true) : (index.* += 1) {240 while (true) : (index.* += 1) {
241 switch (build_info[index.*]) {241 switch (build_info[index.*]) {
doc/docgen.zig+11-11
...@@ -104,7 +104,7 @@ const Tokenizer = struct {...@@ -104,7 +104,7 @@ const Tokenizer = struct {
104 };104 };
105 }105 }
106106
107 fn next(self: &Tokenizer) Token {107 fn next(self: *Tokenizer) Token {
108 var result = Token{108 var result = Token{
109 .id = Token.Id.Eof,109 .id = Token.Id.Eof,
110 .start = self.index,110 .start = self.index,
...@@ -196,7 +196,7 @@ const Tokenizer = struct {...@@ -196,7 +196,7 @@ const Tokenizer = struct {
196 line_end: usize,196 line_end: usize,
197 };197 };
198198
199 fn getTokenLocation(self: &Tokenizer, token: &const Token) Location {199 fn getTokenLocation(self: *Tokenizer, token: *const Token) Location {
200 var loc = Location{200 var loc = Location{
201 .line = 0,201 .line = 0,
202 .column = 0,202 .column = 0,
...@@ -221,7 +221,7 @@ const Tokenizer = struct {...@@ -221,7 +221,7 @@ const Tokenizer = struct {
221 }221 }
222};222};
223223
224fn parseError(tokenizer: &Tokenizer, token: &const Token, comptime fmt: []const u8, args: ...) error {224fn parseError(tokenizer: *Tokenizer, token: *const Token, comptime fmt: []const u8, args: ...) error {
225 const loc = tokenizer.getTokenLocation(token);225 const loc = tokenizer.getTokenLocation(token);
226 warn("{}:{}:{}: error: " ++ fmt ++ "\n", tokenizer.source_file_name, loc.line + 1, loc.column + 1, args);226 warn("{}:{}:{}: error: " ++ fmt ++ "\n", tokenizer.source_file_name, loc.line + 1, loc.column + 1, args);
227 if (loc.line_start <= loc.line_end) {227 if (loc.line_start <= loc.line_end) {
...@@ -244,13 +244,13 @@ fn parseError(tokenizer: &Tokenizer, token: &const Token, comptime fmt: []const...@@ -244,13 +244,13 @@ fn parseError(tokenizer: &Tokenizer, token: &const Token, comptime fmt: []const
244 return error.ParseError;244 return error.ParseError;
245}245}
246246
247fn assertToken(tokenizer: &Tokenizer, token: &const Token, id: Token.Id) !void {247fn assertToken(tokenizer: *Tokenizer, token: *const Token, id: Token.Id) !void {
248 if (token.id != id) {248 if (token.id != id) {
249 return parseError(tokenizer, token, "expected {}, found {}", @tagName(id), @tagName(token.id));249 return parseError(tokenizer, token, "expected {}, found {}", @tagName(id), @tagName(token.id));
250 }250 }
251}251}
252252
253fn eatToken(tokenizer: &Tokenizer, id: Token.Id) !Token {253fn eatToken(tokenizer: *Tokenizer, id: Token.Id) !Token {
254 const token = tokenizer.next();254 const token = tokenizer.next();
255 try assertToken(tokenizer, token, id);255 try assertToken(tokenizer, token, id);
256 return token;256 return token;
...@@ -317,7 +317,7 @@ const Action = enum {...@@ -317,7 +317,7 @@ const Action = enum {
317 Close,317 Close,
318};318};
319319
320fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc {320fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
321 var urls = std.HashMap([]const u8, Token, mem.hash_slice_u8, mem.eql_slice_u8).init(allocator);321 var urls = std.HashMap([]const u8, Token, mem.hash_slice_u8, mem.eql_slice_u8).init(allocator);
322 errdefer urls.deinit();322 errdefer urls.deinit();
323323
...@@ -546,7 +546,7 @@ fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc {...@@ -546,7 +546,7 @@ fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc {
546 };546 };
547}547}
548548
549fn urlize(allocator: &mem.Allocator, input: []const u8) ![]u8 {549fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {
550 var buf = try std.Buffer.initSize(allocator, 0);550 var buf = try std.Buffer.initSize(allocator, 0);
551 defer buf.deinit();551 defer buf.deinit();
552552
...@@ -566,7 +566,7 @@ fn urlize(allocator: &mem.Allocator, input: []const u8) ![]u8 {...@@ -566,7 +566,7 @@ fn urlize(allocator: &mem.Allocator, input: []const u8) ![]u8 {
566 return buf.toOwnedSlice();566 return buf.toOwnedSlice();
567}567}
568568
569fn escapeHtml(allocator: &mem.Allocator, input: []const u8) ![]u8 {569fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 {
570 var buf = try std.Buffer.initSize(allocator, 0);570 var buf = try std.Buffer.initSize(allocator, 0);
571 defer buf.deinit();571 defer buf.deinit();
572572
...@@ -608,7 +608,7 @@ test "term color" {...@@ -608,7 +608,7 @@ test "term color" {
608 assert(mem.eql(u8, result, "A<span class=\"t32\">green</span>B"));608 assert(mem.eql(u8, result, "A<span class=\"t32\">green</span>B"));
609}609}
610610
611fn termColor(allocator: &mem.Allocator, input: []const u8) ![]u8 {611fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 {
612 var buf = try std.Buffer.initSize(allocator, 0);612 var buf = try std.Buffer.initSize(allocator, 0);
613 defer buf.deinit();613 defer buf.deinit();
614614
...@@ -688,7 +688,7 @@ fn termColor(allocator: &mem.Allocator, input: []const u8) ![]u8 {...@@ -688,7 +688,7 @@ fn termColor(allocator: &mem.Allocator, input: []const u8) ![]u8 {
688 return buf.toOwnedSlice();688 return buf.toOwnedSlice();
689}689}
690690
691fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var, zig_exe: []const u8) !void {691fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var, zig_exe: []const u8) !void {
692 var code_progress_index: usize = 0;692 var code_progress_index: usize = 0;
693 for (toc.nodes) |node| {693 for (toc.nodes) |node| {
694 switch (node) {694 switch (node) {
...@@ -1036,7 +1036,7 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var...@@ -1036,7 +1036,7 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
1036 }1036 }
1037}1037}
10381038
1039fn exec(allocator: &mem.Allocator, args: []const []const u8) !os.ChildProcess.ExecResult {1039fn exec(allocator: *mem.Allocator, args: []const []const u8) !os.ChildProcess.ExecResult {
1040 const result = try os.ChildProcess.exec(allocator, args, null, null, max_doc_file_size);1040 const result = try os.ChildProcess.exec(allocator, args, null, null, max_doc_file_size);
1041 switch (result.term) {1041 switch (result.term) {
1042 os.ChildProcess.Term.Exited => |exit_code| {1042 os.ChildProcess.Term.Exited => |exit_code| {
doc/langref.html.in+133-125
...@@ -458,7 +458,7 @@ test "string literals" {...@@ -458,7 +458,7 @@ test "string literals" {
458458
459 // A C string literal is a null terminated pointer.459 // A C string literal is a null terminated pointer.
460 const null_terminated_bytes = c"hello";460 const null_terminated_bytes = c"hello";
461 assert(@typeOf(null_terminated_bytes) == &const u8);461 assert(@typeOf(null_terminated_bytes) == [*]const u8);
462 assert(null_terminated_bytes[5] == 0);462 assert(null_terminated_bytes[5] == 0);
463}463}
464 {#code_end#}464 {#code_end#}
...@@ -547,7 +547,7 @@ const c_string_literal =...@@ -547,7 +547,7 @@ const c_string_literal =
547;547;
548 {#code_end#}548 {#code_end#}
549 <p>549 <p>
550 In this example the variable <code>c_string_literal</code> has type <code>&amp;const char</code> and550 In this example the variable <code>c_string_literal</code> has type <code>[*]const char</code> and
551 has a terminating null byte.551 has a terminating null byte.
552 </p>552 </p>
553 {#see_also|@embedFile#}553 {#see_also|@embedFile#}
...@@ -1288,7 +1288,7 @@ const assert = @import("std").debug.assert;...@@ -1288,7 +1288,7 @@ const assert = @import("std").debug.assert;
1288const mem = @import("std").mem;1288const mem = @import("std").mem;
12891289
1290// array literal1290// array literal
1291const message = []u8{'h', 'e', 'l', 'l', 'o'};1291const message = []u8{ 'h', 'e', 'l', 'l', 'o' };
12921292
1293// get the size of an array1293// get the size of an array
1294comptime {1294comptime {
...@@ -1324,11 +1324,11 @@ test "modify an array" {...@@ -1324,11 +1324,11 @@ test "modify an array" {
13241324
1325// array concatenation works if the values are known1325// array concatenation works if the values are known
1326// at compile time1326// at compile time
1327const part_one = []i32{1, 2, 3, 4};1327const part_one = []i32{ 1, 2, 3, 4 };
1328const part_two = []i32{5, 6, 7, 8};1328const part_two = []i32{ 5, 6, 7, 8 };
1329const all_of_it = part_one ++ part_two;1329const all_of_it = part_one ++ part_two;
1330comptime {1330comptime {
1331 assert(mem.eql(i32, all_of_it, []i32{1,2,3,4,5,6,7,8}));1331 assert(mem.eql(i32, all_of_it, []i32{ 1, 2, 3, 4, 5, 6, 7, 8 }));
1332}1332}
13331333
1334// remember that string literals are arrays1334// remember that string literals are arrays
...@@ -1357,7 +1357,7 @@ comptime {...@@ -1357,7 +1357,7 @@ comptime {
1357var fancy_array = init: {1357var fancy_array = init: {
1358 var initial_value: [10]Point = undefined;1358 var initial_value: [10]Point = undefined;
1359 for (initial_value) |*pt, i| {1359 for (initial_value) |*pt, i| {
1360 pt.* = Point {1360 pt.* = Point{
1361 .x = i32(i),1361 .x = i32(i),
1362 .y = i32(i) * 2,1362 .y = i32(i) * 2,
1363 };1363 };
...@@ -1377,7 +1377,7 @@ test "compile-time array initalization" {...@@ -1377,7 +1377,7 @@ test "compile-time array initalization" {
1377// call a function to initialize an array1377// call a function to initialize an array
1378var more_points = []Point{makePoint(3)} ** 10;1378var more_points = []Point{makePoint(3)} ** 10;
1379fn makePoint(x: i32) Point {1379fn makePoint(x: i32) Point {
1380 return Point {1380 return Point{
1381 .x = x,1381 .x = x,
1382 .y = x * 2,1382 .y = x * 2,
1383 };1383 };
...@@ -1403,36 +1403,35 @@ test "address of syntax" {...@@ -1403,36 +1403,35 @@ test "address of syntax" {
1403 assert(x_ptr.* == 1234);1403 assert(x_ptr.* == 1234);
14041404
1405 // When you get the address of a const variable, you get a const pointer.1405 // When you get the address of a const variable, you get a const pointer.
1406 assert(@typeOf(x_ptr) == &const i32);1406 assert(@typeOf(x_ptr) == *const i32);
14071407
1408 // If you want to mutate the value, you'd need an address of a mutable variable:1408 // If you want to mutate the value, you'd need an address of a mutable variable:
1409 var y: i32 = 5678;1409 var y: i32 = 5678;
1410 const y_ptr = &y;1410 const y_ptr = &y;
1411 assert(@typeOf(y_ptr) == &i32);1411 assert(@typeOf(y_ptr) == *i32);
1412 y_ptr.* += 1;1412 y_ptr.* += 1;
1413 assert(y_ptr.* == 5679);1413 assert(y_ptr.* == 5679);
1414}1414}
14151415
1416test "pointer array access" {1416test "pointer array access" {
1417 // Pointers do not support pointer arithmetic. If you1417 // Taking an address of an individual element gives a
1418 // need such a thing, use array index syntax:1418 // pointer to a single item. This kind of pointer
1419 // does not support pointer arithmetic.
14191420
1420 var array = []u8{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};1421 var array = []u8{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
1421 const ptr = &array[1];1422 const ptr = &array[2];
1423 assert(@typeOf(ptr) == *u8);
14221424
1423 assert(array[2] == 3);1425 assert(array[2] == 3);
1424 ptr[1] += 1;1426 ptr.* += 1;
1425 assert(array[2] == 4);1427 assert(array[2] == 4);
1426}1428}
14271429
1428test "pointer slicing" {1430test "pointer slicing" {
1429 // In Zig, we prefer using slices over null-terminated pointers.1431 // In Zig, we prefer using slices over null-terminated pointers.
1430 // You can turn a pointer into a slice using slice syntax:1432 // You can turn an array into a slice using slice syntax:
1431 var array = []u8{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};1433 var array = []u8{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
1432 const ptr = &array[1];1434 const slice = array[2..4];
1433 const slice = ptr[1..3];
1434
1435 assert(slice.ptr == &ptr[1]);
1436 assert(slice.len == 2);1435 assert(slice.len == 2);
14371436
1438 // Slices have bounds checking and are therefore protected1437 // Slices have bounds checking and are therefore protected
...@@ -1455,7 +1454,7 @@ comptime {...@@ -1455,7 +1454,7 @@ comptime {
14551454
1456test "@ptrToInt and @intToPtr" {1455test "@ptrToInt and @intToPtr" {
1457 // To convert an integer address into a pointer, use @intToPtr:1456 // To convert an integer address into a pointer, use @intToPtr:
1458 const ptr = @intToPtr(&i32, 0xdeadbeef);1457 const ptr = @intToPtr(*i32, 0xdeadbeef);
14591458
1460 // To convert a pointer to an integer, use @ptrToInt:1459 // To convert a pointer to an integer, use @ptrToInt:
1461 const addr = @ptrToInt(ptr);1460 const addr = @ptrToInt(ptr);
...@@ -1467,7 +1466,7 @@ test "@ptrToInt and @intToPtr" {...@@ -1467,7 +1466,7 @@ test "@ptrToInt and @intToPtr" {
1467comptime {1466comptime {
1468 // Zig is able to do this at compile-time, as long as1467 // Zig is able to do this at compile-time, as long as
1469 // ptr is never dereferenced.1468 // ptr is never dereferenced.
1470 const ptr = @intToPtr(&i32, 0xdeadbeef);1469 const ptr = @intToPtr(*i32, 0xdeadbeef);
1471 const addr = @ptrToInt(ptr);1470 const addr = @ptrToInt(ptr);
1472 assert(@typeOf(addr) == usize);1471 assert(@typeOf(addr) == usize);
1473 assert(addr == 0xdeadbeef);1472 assert(addr == 0xdeadbeef);
...@@ -1477,17 +1476,17 @@ test "volatile" {...@@ -1477,17 +1476,17 @@ test "volatile" {
1477 // In Zig, loads and stores are assumed to not have side effects.1476 // In Zig, loads and stores are assumed to not have side effects.
1478 // If a given load or store should have side effects, such as1477 // If a given load or store should have side effects, such as
1479 // Memory Mapped Input/Output (MMIO), use `volatile`:1478 // Memory Mapped Input/Output (MMIO), use `volatile`:
1480 const mmio_ptr = @intToPtr(&volatile u8, 0x12345678);1479 const mmio_ptr = @intToPtr(*volatile u8, 0x12345678);
14811480
1482 // Now loads and stores with mmio_ptr are guaranteed to all happen1481 // Now loads and stores with mmio_ptr are guaranteed to all happen
1483 // and in the same order as in source code.1482 // and in the same order as in source code.
1484 assert(@typeOf(mmio_ptr) == &volatile u8);1483 assert(@typeOf(mmio_ptr) == *volatile u8);
1485}1484}
14861485
1487test "nullable pointers" {1486test "nullable pointers" {
1488 // Pointers cannot be null. If you want a null pointer, use the nullable1487 // Pointers cannot be null. If you want a null pointer, use the nullable
1489 // prefix `?` to make the pointer type nullable.1488 // prefix `?` to make the pointer type nullable.
1490 var ptr: ?&i32 = null;1489 var ptr: ?*i32 = null;
14911490
1492 var x: i32 = 1;1491 var x: i32 = 1;
1493 ptr = &x;1492 ptr = &x;
...@@ -1496,7 +1495,7 @@ test "nullable pointers" {...@@ -1496,7 +1495,7 @@ test "nullable pointers" {
14961495
1497 // Nullable pointers are the same size as normal pointers, because pointer1496 // Nullable pointers are the same size as normal pointers, because pointer
1498 // value 0 is used as the null value.1497 // value 0 is used as the null value.
1499 assert(@sizeOf(?&i32) == @sizeOf(&i32));1498 assert(@sizeOf(?*i32) == @sizeOf(*i32));
1500}1499}
15011500
1502test "pointer casting" {1501test "pointer casting" {
...@@ -1504,7 +1503,7 @@ test "pointer casting" {...@@ -1504,7 +1503,7 @@ test "pointer casting" {
1504 // operation that Zig cannot protect you against. Use @ptrCast only when other1503 // operation that Zig cannot protect you against. Use @ptrCast only when other
1505 // conversions are not possible.1504 // conversions are not possible.
1506 const bytes align(@alignOf(u32)) = []u8{0x12, 0x12, 0x12, 0x12};1505 const bytes align(@alignOf(u32)) = []u8{0x12, 0x12, 0x12, 0x12};
1507 const u32_ptr = @ptrCast(&const u32, &bytes[0]);1506 const u32_ptr = @ptrCast(*const u32, &bytes[0]);
1508 assert(u32_ptr.* == 0x12121212);1507 assert(u32_ptr.* == 0x12121212);
15091508
1510 // Even this example is contrived - there are better ways to do the above than1509 // Even this example is contrived - there are better ways to do the above than
...@@ -1518,7 +1517,7 @@ test "pointer casting" {...@@ -1518,7 +1517,7 @@ test "pointer casting" {
15181517
1519test "pointer child type" {1518test "pointer child type" {
1520 // pointer types have a `child` field which tells you the type they point to.1519 // pointer types have a `child` field which tells you the type they point to.
1521 assert((&u32).Child == u32);1520 assert((*u32).Child == u32);
1522}1521}
1523 {#code_end#}1522 {#code_end#}
1524 {#header_open|Alignment#}1523 {#header_open|Alignment#}
...@@ -1543,15 +1542,15 @@ const builtin = @import("builtin");...@@ -1543,15 +1542,15 @@ const builtin = @import("builtin");
1543test "variable alignment" {1542test "variable alignment" {
1544 var x: i32 = 1234;1543 var x: i32 = 1234;
1545 const align_of_i32 = @alignOf(@typeOf(x));1544 const align_of_i32 = @alignOf(@typeOf(x));
1546 assert(@typeOf(&x) == &i32);1545 assert(@typeOf(&x) == *i32);
1547 assert(&i32 == &align(align_of_i32) i32);1546 assert(*i32 == *align(align_of_i32) i32);
1548 if (builtin.arch == builtin.Arch.x86_64) {1547 if (builtin.arch == builtin.Arch.x86_64) {
1549 assert((&i32).alignment == 4);1548 assert((*i32).alignment == 4);
1550 }1549 }
1551}1550}
1552 {#code_end#}1551 {#code_end#}
1553 <p>In the same way that a <code>&amp;i32</code> can be implicitly cast to a1552 <p>In the same way that a <code>*i32</code> can be implicitly cast to a
1554 <code>&amp;const i32</code>, a pointer with a larger alignment can be implicitly1553 <code>*const i32</code>, a pointer with a larger alignment can be implicitly
1555 cast to a pointer with a smaller alignment, but not vice versa.1554 cast to a pointer with a smaller alignment, but not vice versa.
1556 </p>1555 </p>
1557 <p>1556 <p>
...@@ -1565,7 +1564,7 @@ var foo: u8 align(4) = 100;...@@ -1565,7 +1564,7 @@ var foo: u8 align(4) = 100;
15651564
1566test "global variable alignment" {1565test "global variable alignment" {
1567 assert(@typeOf(&foo).alignment == 4);1566 assert(@typeOf(&foo).alignment == 4);
1568 assert(@typeOf(&foo) == &align(4) u8);1567 assert(@typeOf(&foo) == *align(4) u8);
1569 const slice = (&foo)[0..1];1568 const slice = (&foo)[0..1];
1570 assert(@typeOf(slice) == []align(4) u8);1569 assert(@typeOf(slice) == []align(4) u8);
1571}1570}
...@@ -1610,7 +1609,7 @@ fn foo(bytes: []u8) u32 {...@@ -1610,7 +1609,7 @@ fn foo(bytes: []u8) u32 {
1610 <code>u8</code> can alias any memory.1609 <code>u8</code> can alias any memory.
1611 </p>1610 </p>
1612 <p>As an example, this code produces undefined behavior:</p>1611 <p>As an example, this code produces undefined behavior:</p>
1613 <pre><code class="zig">@ptrCast(&amp;u32, f32(12.34)).*</code></pre>1612 <pre><code class="zig">@ptrCast(*u32, f32(12.34)).*</code></pre>
1614 <p>Instead, use {#link|@bitCast#}:1613 <p>Instead, use {#link|@bitCast#}:
1615 <pre><code class="zig">@bitCast(u32, f32(12.34))</code></pre>1614 <pre><code class="zig">@bitCast(u32, f32(12.34))</code></pre>
1616 <p>As an added benefit, the <code>@bitcast</code> version works at compile-time.</p>1615 <p>As an added benefit, the <code>@bitcast</code> version works at compile-time.</p>
...@@ -1622,18 +1621,27 @@ fn foo(bytes: []u8) u32 {...@@ -1622,18 +1621,27 @@ fn foo(bytes: []u8) u32 {
1622const assert = @import("std").debug.assert;1621const assert = @import("std").debug.assert;
16231622
1624test "basic slices" {1623test "basic slices" {
1625 var array = []i32{1, 2, 3, 4};1624 var array = []i32{ 1, 2, 3, 4 };
1626 // A slice is a pointer and a length. The difference between an array and1625 // A slice is a pointer and a length. The difference between an array and
1627 // a slice is that the array's length is part of the type and known at1626 // a slice is that the array's length is part of the type and known at
1628 // compile-time, whereas the slice's length is known at runtime.1627 // compile-time, whereas the slice's length is known at runtime.
1629 // Both can be accessed with the `len` field.1628 // Both can be accessed with the `len` field.
1630 const slice = array[0..array.len];1629 const slice = array[0..array.len];
1631 assert(slice.ptr == &array[0]);1630 assert(&slice[0] == &array[0]);
1632 assert(slice.len == array.len);1631 assert(slice.len == array.len);
16331632
1633 // Using the address-of operator on a slice gives a pointer to a single
1634 // item, while using the `ptr` field gives an unknown length pointer.
1635 assert(@typeOf(slice.ptr) == [*]i32);
1636 assert(@typeOf(&slice[0]) == *i32);
1637 assert(@ptrToInt(slice.ptr) == @ptrToInt(&slice[0]));
1638
1634 // Slices have array bounds checking. If you try to access something out1639 // Slices have array bounds checking. If you try to access something out
1635 // of bounds, you'll get a safety check failure:1640 // of bounds, you'll get a safety check failure:
1636 slice[10] += 1;1641 slice[10] += 1;
1642
1643 // Note that `slice.ptr` does not invoke safety checking, while `&slice[0]`
1644 // asserts that the slice has len >= 1.
1637}1645}
1638 {#code_end#}1646 {#code_end#}
1639 <p>This is one reason we prefer slices to pointers.</p>1647 <p>This is one reason we prefer slices to pointers.</p>
...@@ -1736,7 +1744,7 @@ const Vec3 = struct {...@@ -1736,7 +1744,7 @@ const Vec3 = struct {
1736 };1744 };
1737 }1745 }
17381746
1739 pub fn dot(self: &const Vec3, other: &const Vec3) f32 {1747 pub fn dot(self: *const Vec3, other: *const Vec3) f32 {
1740 return self.x * other.x + self.y * other.y + self.z * other.z;1748 return self.x * other.x + self.y * other.y + self.z * other.z;
1741 }1749 }
1742};1750};
...@@ -1768,7 +1776,7 @@ test "struct namespaced variable" {...@@ -1768,7 +1776,7 @@ test "struct namespaced variable" {
17681776
1769// struct field order is determined by the compiler for optimal performance.1777// struct field order is determined by the compiler for optimal performance.
1770// however, you can still calculate a struct base pointer given a field pointer:1778// however, you can still calculate a struct base pointer given a field pointer:
1771fn setYBasedOnX(x: &f32, y: f32) void {1779fn setYBasedOnX(x: *f32, y: f32) void {
1772 const point = @fieldParentPtr(Point, "x", x);1780 const point = @fieldParentPtr(Point, "x", x);
1773 point.y = y;1781 point.y = y;
1774}1782}
...@@ -1786,13 +1794,13 @@ test "field parent pointer" {...@@ -1786,13 +1794,13 @@ test "field parent pointer" {
1786fn LinkedList(comptime T: type) type {1794fn LinkedList(comptime T: type) type {
1787 return struct {1795 return struct {
1788 pub const Node = struct {1796 pub const Node = struct {
1789 prev: ?&Node,1797 prev: ?*Node,
1790 next: ?&Node,1798 next: ?*Node,
1791 data: T,1799 data: T,
1792 };1800 };
17931801
1794 first: ?&Node,1802 first: ?*Node,
1795 last: ?&Node,1803 last: ?*Node,
1796 len: usize,1804 len: usize,
1797 };1805 };
1798}1806}
...@@ -2039,7 +2047,7 @@ const Variant = union(enum) {...@@ -2039,7 +2047,7 @@ const Variant = union(enum) {
2039 Int: i32,2047 Int: i32,
2040 Bool: bool,2048 Bool: bool,
20412049
2042 fn truthy(self: &const Variant) bool {2050 fn truthy(self: *const Variant) bool {
2043 return switch (self.*) {2051 return switch (self.*) {
2044 Variant.Int => |x_int| x_int != 0,2052 Variant.Int => |x_int| x_int != 0,
2045 Variant.Bool => |x_bool| x_bool,2053 Variant.Bool => |x_bool| x_bool,
...@@ -2786,7 +2794,7 @@ test "pass aggregate type by value to function" {...@@ -2786,7 +2794,7 @@ test "pass aggregate type by value to function" {
2786}2794}
2787 {#code_end#}2795 {#code_end#}
2788 <p>2796 <p>
2789 Instead, one must use <code>&amp;const</code>. Zig allows implicitly casting something2797 Instead, one must use <code>*const</code>. Zig allows implicitly casting something
2790 to a const pointer to it:2798 to a const pointer to it:
2791 </p>2799 </p>
2792 {#code_begin|test#}2800 {#code_begin|test#}
...@@ -2794,7 +2802,7 @@ const Foo = struct {...@@ -2794,7 +2802,7 @@ const Foo = struct {
2794 x: i32,2802 x: i32,
2795};2803};
27962804
2797fn bar(foo: &const Foo) void {}2805fn bar(foo: *const Foo) void {}
27982806
2799test "implicitly cast to const pointer" {2807test "implicitly cast to const pointer" {
2800 bar(Foo {.x = 12,});2808 bar(Foo {.x = 12,});
...@@ -3208,16 +3216,16 @@ struct Foo *do_a_thing(void) {...@@ -3208,16 +3216,16 @@ struct Foo *do_a_thing(void) {
3208 <p>Zig code</p>3216 <p>Zig code</p>
3209 {#code_begin|syntax#}3217 {#code_begin|syntax#}
3210// malloc prototype included for reference3218// malloc prototype included for reference
3211extern fn malloc(size: size_t) ?&u8;3219extern fn malloc(size: size_t) ?*u8;
32123220
3213fn doAThing() ?&Foo {3221fn doAThing() ?*Foo {
3214 const ptr = malloc(1234) ?? return null;3222 const ptr = malloc(1234) ?? return null;
3215 // ...3223 // ...
3216}3224}
3217 {#code_end#}3225 {#code_end#}
3218 <p>3226 <p>
3219 Here, Zig is at least as convenient, if not more, than C. And, the type of "ptr"3227 Here, Zig is at least as convenient, if not more, than C. And, the type of "ptr"
3220 is <code>&u8</code> <em>not</em> <code>?&u8</code>. The <code>??</code> operator3228 is <code>*u8</code> <em>not</em> <code>?*u8</code>. The <code>??</code> operator
3221 unwrapped the nullable type and therefore <code>ptr</code> is guaranteed to be non-null everywhere3229 unwrapped the nullable type and therefore <code>ptr</code> is guaranteed to be non-null everywhere
3222 it is used in the function.3230 it is used in the function.
3223 </p>3231 </p>
...@@ -3237,7 +3245,7 @@ fn doAThing() ?&Foo {...@@ -3237,7 +3245,7 @@ fn doAThing() ?&Foo {
3237 In Zig you can accomplish the same thing:3245 In Zig you can accomplish the same thing:
3238 </p>3246 </p>
3239 {#code_begin|syntax#}3247 {#code_begin|syntax#}
3240fn doAThing(nullable_foo: ?&Foo) void {3248fn doAThing(nullable_foo: ?*Foo) void {
3241 // do some stuff3249 // do some stuff
32423250
3243 if (nullable_foo) |foo| {3251 if (nullable_foo) |foo| {
...@@ -3713,7 +3721,7 @@ fn List(comptime T: type) type {...@@ -3713,7 +3721,7 @@ fn List(comptime T: type) type {
3713 </p>3721 </p>
3714 {#code_begin|syntax#}3722 {#code_begin|syntax#}
3715const Node = struct {3723const Node = struct {
3716 next: &Node,3724 next: *Node,
3717 name: []u8,3725 name: []u8,
3718};3726};
3719 {#code_end#}3727 {#code_end#}
...@@ -3745,7 +3753,7 @@ pub fn main() void {...@@ -3745,7 +3753,7 @@ pub fn main() void {
37453753
3746 {#code_begin|syntax#}3754 {#code_begin|syntax#}
3747/// Calls print and then flushes the buffer.3755/// Calls print and then flushes the buffer.
3748pub fn printf(self: &OutStream, comptime format: []const u8, args: ...) error!void {3756pub fn printf(self: *OutStream, comptime format: []const u8, args: ...) error!void {
3749 const State = enum {3757 const State = enum {
3750 Start,3758 Start,
3751 OpenBrace,3759 OpenBrace,
...@@ -3817,7 +3825,7 @@ pub fn printf(self: &OutStream, comptime format: []const u8, args: ...) error!vo...@@ -3817,7 +3825,7 @@ pub fn printf(self: &OutStream, comptime format: []const u8, args: ...) error!vo
3817 and emits a function that actually looks like this:3825 and emits a function that actually looks like this:
3818 </p>3826 </p>
3819 {#code_begin|syntax#}3827 {#code_begin|syntax#}
3820pub fn printf(self: &OutStream, arg0: i32, arg1: []const u8) !void {3828pub fn printf(self: *OutStream, arg0: i32, arg1: []const u8) !void {
3821 try self.write("here is a string: '");3829 try self.write("here is a string: '");
3822 try self.printValue(arg0);3830 try self.printValue(arg0);
3823 try self.write("' here is a number: ");3831 try self.write("' here is a number: ");
...@@ -3831,7 +3839,7 @@ pub fn printf(self: &OutStream, arg0: i32, arg1: []const u8) !void {...@@ -3831,7 +3839,7 @@ pub fn printf(self: &OutStream, arg0: i32, arg1: []const u8) !void {
3831 on the type:3839 on the type:
3832 </p>3840 </p>
3833 {#code_begin|syntax#}3841 {#code_begin|syntax#}
3834pub fn printValue(self: &OutStream, value: var) !void {3842pub fn printValue(self: *OutStream, value: var) !void {
3835 const T = @typeOf(value);3843 const T = @typeOf(value);
3836 if (@isInteger(T)) {3844 if (@isInteger(T)) {
3837 return self.printInt(T, value);3845 return self.printInt(T, value);
...@@ -3911,7 +3919,7 @@ pub fn main() void {...@@ -3911,7 +3919,7 @@ pub fn main() void {
3911 at compile time.3919 at compile time.
3912 </p>3920 </p>
3913 {#header_open|@addWithOverflow#}3921 {#header_open|@addWithOverflow#}
3914 <pre><code class="zig">@addWithOverflow(comptime T: type, a: T, b: T, result: &T) -&gt; bool</code></pre>3922 <pre><code class="zig">@addWithOverflow(comptime T: type, a: T, b: T, result: *T) bool</code></pre>
3915 <p>3923 <p>
3916 Performs <code>result.* = a + b</code>. If overflow or underflow occurs,3924 Performs <code>result.* = a + b</code>. If overflow or underflow occurs,
3917 stores the overflowed bits in <code>result</code> and returns <code>true</code>.3925 stores the overflowed bits in <code>result</code> and returns <code>true</code>.
...@@ -3919,7 +3927,7 @@ pub fn main() void {...@@ -3919,7 +3927,7 @@ pub fn main() void {
3919 </p>3927 </p>
3920 {#header_close#}3928 {#header_close#}
3921 {#header_open|@ArgType#}3929 {#header_open|@ArgType#}
3922 <pre><code class="zig">@ArgType(comptime T: type, comptime n: usize) -&gt; type</code></pre>3930 <pre><code class="zig">@ArgType(comptime T: type, comptime n: usize) type</code></pre>
3923 <p>3931 <p>
3924 This builtin function takes a function type and returns the type of the parameter at index <code>n</code>.3932 This builtin function takes a function type and returns the type of the parameter at index <code>n</code>.
3925 </p>3933 </p>
...@@ -3931,7 +3939,7 @@ pub fn main() void {...@@ -3931,7 +3939,7 @@ pub fn main() void {
3931 </p>3939 </p>
3932 {#header_close#}3940 {#header_close#}
3933 {#header_open|@atomicLoad#}3941 {#header_open|@atomicLoad#}
3934 <pre><code class="zig">@atomicLoad(comptime T: type, ptr: &amp;const T, comptime ordering: builtin.AtomicOrder) -&gt; T</code></pre>3942 <pre><code class="zig">@atomicLoad(comptime T: type, ptr: *const T, comptime ordering: builtin.AtomicOrder) T</code></pre>
3935 <p>3943 <p>
3936 This builtin function atomically dereferences a pointer and returns the value.3944 This builtin function atomically dereferences a pointer and returns the value.
3937 </p>3945 </p>
...@@ -3950,7 +3958,7 @@ pub fn main() void {...@@ -3950,7 +3958,7 @@ pub fn main() void {
3950 </p>3958 </p>
3951 {#header_close#}3959 {#header_close#}
3952 {#header_open|@atomicRmw#}3960 {#header_open|@atomicRmw#}
3953 <pre><code class="zig">@atomicRmw(comptime T: type, ptr: &amp;T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) -&gt; T</code></pre>3961 <pre><code class="zig">@atomicRmw(comptime T: type, ptr: *T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) T</code></pre>
3954 <p>3962 <p>
3955 This builtin function atomically modifies memory and then returns the previous value.3963 This builtin function atomically modifies memory and then returns the previous value.
3956 </p>3964 </p>
...@@ -3969,7 +3977,7 @@ pub fn main() void {...@@ -3969,7 +3977,7 @@ pub fn main() void {
3969 </p>3977 </p>
3970 {#header_close#}3978 {#header_close#}
3971 {#header_open|@bitCast#}3979 {#header_open|@bitCast#}
3972 <pre><code class="zig">@bitCast(comptime DestType: type, value: var) -&gt; DestType</code></pre>3980 <pre><code class="zig">@bitCast(comptime DestType: type, value: var) DestType</code></pre>
3973 <p>3981 <p>
3974 Converts a value of one type to another type.3982 Converts a value of one type to another type.
3975 </p>3983 </p>
...@@ -4002,9 +4010,9 @@ pub fn main() void {...@@ -4002,9 +4010,9 @@ pub fn main() void {
40024010
4003 {#header_close#}4011 {#header_close#}
4004 {#header_open|@alignCast#}4012 {#header_open|@alignCast#}
4005 <pre><code class="zig">@alignCast(comptime alignment: u29, ptr: var) -&gt; var</code></pre>4013 <pre><code class="zig">@alignCast(comptime alignment: u29, ptr: var) var</code></pre>
4006 <p>4014 <p>
4007 <code>ptr</code> can be <code>&amp;T</code>, <code>fn()</code>, <code>?&amp;T</code>,4015 <code>ptr</code> can be <code>*T</code>, <code>fn()</code>, <code>?*T</code>,
4008 <code>?fn()</code>, or <code>[]T</code>. It returns the same type as <code>ptr</code>4016 <code>?fn()</code>, or <code>[]T</code>. It returns the same type as <code>ptr</code>
4009 except with the alignment adjusted to the new value.4017 except with the alignment adjusted to the new value.
4010 </p>4018 </p>
...@@ -4013,7 +4021,7 @@ pub fn main() void {...@@ -4013,7 +4021,7 @@ pub fn main() void {
40134021
4014 {#header_close#}4022 {#header_close#}
4015 {#header_open|@alignOf#}4023 {#header_open|@alignOf#}
4016 <pre><code class="zig">@alignOf(comptime T: type) -&gt; (number literal)</code></pre>4024 <pre><code class="zig">@alignOf(comptime T: type) (number literal)</code></pre>
4017 <p>4025 <p>
4018 This function returns the number of bytes that this type should be aligned to4026 This function returns the number of bytes that this type should be aligned to
4019 for the current target to match the C ABI. When the child type of a pointer has4027 for the current target to match the C ABI. When the child type of a pointer has
...@@ -4021,7 +4029,7 @@ pub fn main() void {...@@ -4021,7 +4029,7 @@ pub fn main() void {
4021 </p>4029 </p>
4022 <pre><code class="zig">const assert = @import("std").debug.assert;4030 <pre><code class="zig">const assert = @import("std").debug.assert;
4023comptime {4031comptime {
4024 assert(&u32 == &align(@alignOf(u32)) u32);4032 assert(*u32 == *align(@alignOf(u32)) u32);
4025}</code></pre>4033}</code></pre>
4026 <p>4034 <p>
4027 The result is a target-specific compile time constant. It is guaranteed to be4035 The result is a target-specific compile time constant. It is guaranteed to be
...@@ -4049,7 +4057,7 @@ comptime {...@@ -4049,7 +4057,7 @@ comptime {
4049 {#see_also|Import from C Header File|@cInclude|@cImport|@cUndef|void#}4057 {#see_also|Import from C Header File|@cInclude|@cImport|@cUndef|void#}
4050 {#header_close#}4058 {#header_close#}
4051 {#header_open|@cImport#}4059 {#header_open|@cImport#}
4052 <pre><code class="zig">@cImport(expression) -&gt; (namespace)</code></pre>4060 <pre><code class="zig">@cImport(expression) (namespace)</code></pre>
4053 <p>4061 <p>
4054 This function parses C code and imports the functions, types, variables, and4062 This function parses C code and imports the functions, types, variables, and
4055 compatible macro definitions into the result namespace.4063 compatible macro definitions into the result namespace.
...@@ -4095,13 +4103,13 @@ comptime {...@@ -4095,13 +4103,13 @@ comptime {
4095 {#see_also|Import from C Header File|@cImport|@cDefine|@cInclude#}4103 {#see_also|Import from C Header File|@cImport|@cDefine|@cInclude#}
4096 {#header_close#}4104 {#header_close#}
4097 {#header_open|@canImplicitCast#}4105 {#header_open|@canImplicitCast#}
4098 <pre><code class="zig">@canImplicitCast(comptime T: type, value) -&gt; bool</code></pre>4106 <pre><code class="zig">@canImplicitCast(comptime T: type, value) bool</code></pre>
4099 <p>4107 <p>
4100 Returns whether a value can be implicitly casted to a given type.4108 Returns whether a value can be implicitly casted to a given type.
4101 </p>4109 </p>
4102 {#header_close#}4110 {#header_close#}
4103 {#header_open|@clz#}4111 {#header_open|@clz#}
4104 <pre><code class="zig">@clz(x: T) -&gt; U</code></pre>4112 <pre><code class="zig">@clz(x: T) U</code></pre>
4105 <p>4113 <p>
4106 This function counts the number of leading zeroes in <code>x</code> which is an integer4114 This function counts the number of leading zeroes in <code>x</code> which is an integer
4107 type <code>T</code>.4115 type <code>T</code>.
...@@ -4116,13 +4124,13 @@ comptime {...@@ -4116,13 +4124,13 @@ comptime {
41164124
4117 {#header_close#}4125 {#header_close#}
4118 {#header_open|@cmpxchgStrong#}4126 {#header_open|@cmpxchgStrong#}
4119 <pre><code class="zig">@cmpxchgStrong(comptime T: type, ptr: &T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) -&gt; ?T</code></pre>4127 <pre><code class="zig">@cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T</code></pre>
4120 <p>4128 <p>
4121 This function performs a strong atomic compare exchange operation. It's the equivalent of this code,4129 This function performs a strong atomic compare exchange operation. It's the equivalent of this code,
4122 except atomic:4130 except atomic:
4123 </p>4131 </p>
4124 {#code_begin|syntax#}4132 {#code_begin|syntax#}
4125fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_value: T) ?T {4133fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
4126 const old_value = ptr.*;4134 const old_value = ptr.*;
4127 if (old_value == expected_value) {4135 if (old_value == expected_value) {
4128 ptr.* = new_value;4136 ptr.* = new_value;
...@@ -4143,13 +4151,13 @@ fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_v...@@ -4143,13 +4151,13 @@ fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_v
4143 {#see_also|Compile Variables|cmpxchgWeak#}4151 {#see_also|Compile Variables|cmpxchgWeak#}
4144 {#header_close#}4152 {#header_close#}
4145 {#header_open|@cmpxchgWeak#}4153 {#header_open|@cmpxchgWeak#}
4146 <pre><code class="zig">@cmpxchgWeak(comptime T: type, ptr: &T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) -&gt; ?T</code></pre>4154 <pre><code class="zig">@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T</code></pre>
4147 <p>4155 <p>
4148 This function performs a weak atomic compare exchange operation. It's the equivalent of this code,4156 This function performs a weak atomic compare exchange operation. It's the equivalent of this code,
4149 except atomic:4157 except atomic:
4150 </p>4158 </p>
4151 {#code_begin|syntax#}4159 {#code_begin|syntax#}
4152fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_value: T) ?T {4160fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
4153 const old_value = ptr.*;4161 const old_value = ptr.*;
4154 if (old_value == expected_value and usuallyTrueButSometimesFalse()) {4162 if (old_value == expected_value and usuallyTrueButSometimesFalse()) {
4155 ptr.* = new_value;4163 ptr.* = new_value;
...@@ -4237,7 +4245,7 @@ test "main" {...@@ -4237,7 +4245,7 @@ test "main" {
4237 {#code_end#}4245 {#code_end#}
4238 {#header_close#}4246 {#header_close#}
4239 {#header_open|@ctz#}4247 {#header_open|@ctz#}
4240 <pre><code class="zig">@ctz(x: T) -&gt; U</code></pre>4248 <pre><code class="zig">@ctz(x: T) U</code></pre>
4241 <p>4249 <p>
4242 This function counts the number of trailing zeroes in <code>x</code> which is an integer4250 This function counts the number of trailing zeroes in <code>x</code> which is an integer
4243 type <code>T</code>.4251 type <code>T</code>.
...@@ -4251,7 +4259,7 @@ test "main" {...@@ -4251,7 +4259,7 @@ test "main" {
4251 </p>4259 </p>
4252 {#header_close#}4260 {#header_close#}
4253 {#header_open|@divExact#}4261 {#header_open|@divExact#}
4254 <pre><code class="zig">@divExact(numerator: T, denominator: T) -&gt; T</code></pre>4262 <pre><code class="zig">@divExact(numerator: T, denominator: T) T</code></pre>
4255 <p>4263 <p>
4256 Exact division. Caller guarantees <code>denominator != 0</code> and4264 Exact division. Caller guarantees <code>denominator != 0</code> and
4257 <code>@divTrunc(numerator, denominator) * denominator == numerator</code>.4265 <code>@divTrunc(numerator, denominator) * denominator == numerator</code>.
...@@ -4264,7 +4272,7 @@ test "main" {...@@ -4264,7 +4272,7 @@ test "main" {
4264 {#see_also|@divTrunc|@divFloor#}4272 {#see_also|@divTrunc|@divFloor#}
4265 {#header_close#}4273 {#header_close#}
4266 {#header_open|@divFloor#}4274 {#header_open|@divFloor#}
4267 <pre><code class="zig">@divFloor(numerator: T, denominator: T) -&gt; T</code></pre>4275 <pre><code class="zig">@divFloor(numerator: T, denominator: T) T</code></pre>
4268 <p>4276 <p>
4269 Floored division. Rounds toward negative infinity. For unsigned integers it is4277 Floored division. Rounds toward negative infinity. For unsigned integers it is
4270 the same as <code>numerator / denominator</code>. Caller guarantees <code>denominator != 0</code> and4278 the same as <code>numerator / denominator</code>. Caller guarantees <code>denominator != 0</code> and
...@@ -4278,7 +4286,7 @@ test "main" {...@@ -4278,7 +4286,7 @@ test "main" {
4278 {#see_also|@divTrunc|@divExact#}4286 {#see_also|@divTrunc|@divExact#}
4279 {#header_close#}4287 {#header_close#}
4280 {#header_open|@divTrunc#}4288 {#header_open|@divTrunc#}
4281 <pre><code class="zig">@divTrunc(numerator: T, denominator: T) -&gt; T</code></pre>4289 <pre><code class="zig">@divTrunc(numerator: T, denominator: T) T</code></pre>
4282 <p>4290 <p>
4283 Truncated division. Rounds toward zero. For unsigned integers it is4291 Truncated division. Rounds toward zero. For unsigned integers it is
4284 the same as <code>numerator / denominator</code>. Caller guarantees <code>denominator != 0</code> and4292 the same as <code>numerator / denominator</code>. Caller guarantees <code>denominator != 0</code> and
...@@ -4292,7 +4300,7 @@ test "main" {...@@ -4292,7 +4300,7 @@ test "main" {
4292 {#see_also|@divFloor|@divExact#}4300 {#see_also|@divFloor|@divExact#}
4293 {#header_close#}4301 {#header_close#}
4294 {#header_open|@embedFile#}4302 {#header_open|@embedFile#}
4295 <pre><code class="zig">@embedFile(comptime path: []const u8) -&gt; [X]u8</code></pre>4303 <pre><code class="zig">@embedFile(comptime path: []const u8) [X]u8</code></pre>
4296 <p>4304 <p>
4297 This function returns a compile time constant fixed-size array with length4305 This function returns a compile time constant fixed-size array with length
4298 equal to the byte count of the file given by <code>path</code>. The contents of the array4306 equal to the byte count of the file given by <code>path</code>. The contents of the array
...@@ -4304,19 +4312,19 @@ test "main" {...@@ -4304,19 +4312,19 @@ test "main" {
4304 {#see_also|@import#}4312 {#see_also|@import#}
4305 {#header_close#}4313 {#header_close#}
4306 {#header_open|@export#}4314 {#header_open|@export#}
4307 <pre><code class="zig">@export(comptime name: []const u8, target: var, linkage: builtin.GlobalLinkage) -&gt; []const u8</code></pre>4315 <pre><code class="zig">@export(comptime name: []const u8, target: var, linkage: builtin.GlobalLinkage) []const u8</code></pre>
4308 <p>4316 <p>
4309 Creates a symbol in the output object file.4317 Creates a symbol in the output object file.
4310 </p>4318 </p>
4311 {#header_close#}4319 {#header_close#}
4312 {#header_open|@tagName#}4320 {#header_open|@tagName#}
4313 <pre><code class="zig">@tagName(value: var) -&gt; []const u8</code></pre>4321 <pre><code class="zig">@tagName(value: var) []const u8</code></pre>
4314 <p>4322 <p>
4315 Converts an enum value or union value to a slice of bytes representing the name.4323 Converts an enum value or union value to a slice of bytes representing the name.
4316 </p>4324 </p>
4317 {#header_close#}4325 {#header_close#}
4318 {#header_open|@TagType#}4326 {#header_open|@TagType#}
4319 <pre><code class="zig">@TagType(T: type) -&gt; type</code></pre>4327 <pre><code class="zig">@TagType(T: type) type</code></pre>
4320 <p>4328 <p>
4321 For an enum, returns the integer type that is used to store the enumeration value.4329 For an enum, returns the integer type that is used to store the enumeration value.
4322 </p>4330 </p>
...@@ -4325,7 +4333,7 @@ test "main" {...@@ -4325,7 +4333,7 @@ test "main" {
4325 </p>4333 </p>
4326 {#header_close#}4334 {#header_close#}
4327 {#header_open|@errorName#}4335 {#header_open|@errorName#}
4328 <pre><code class="zig">@errorName(err: error) -&gt; []u8</code></pre>4336 <pre><code class="zig">@errorName(err: error) []u8</code></pre>
4329 <p>4337 <p>
4330 This function returns the string representation of an error. If an error4338 This function returns the string representation of an error. If an error
4331 declaration is:4339 declaration is:
...@@ -4341,7 +4349,7 @@ test "main" {...@@ -4341,7 +4349,7 @@ test "main" {
4341 </p>4349 </p>
4342 {#header_close#}4350 {#header_close#}
4343 {#header_open|@errorReturnTrace#}4351 {#header_open|@errorReturnTrace#}
4344 <pre><code class="zig">@errorReturnTrace() -&gt; ?&builtin.StackTrace</code></pre>4352 <pre><code class="zig">@errorReturnTrace() ?*builtin.StackTrace</code></pre>
4345 <p>4353 <p>
4346 If the binary is built with error return tracing, and this function is invoked in a4354 If the binary is built with error return tracing, and this function is invoked in a
4347 function that calls a function with an error or error union return type, returns a4355 function that calls a function with an error or error union return type, returns a
...@@ -4360,7 +4368,7 @@ test "main" {...@@ -4360,7 +4368,7 @@ test "main" {
4360 {#header_close#}4368 {#header_close#}
4361 {#header_open|@fieldParentPtr#}4369 {#header_open|@fieldParentPtr#}
4362 <pre><code class="zig">@fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8,4370 <pre><code class="zig">@fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8,
4363 field_ptr: &T) -&gt; &ParentType</code></pre>4371 field_ptr: *T) *ParentType</code></pre>
4364 <p>4372 <p>
4365 Given a pointer to a field, returns the base pointer of a struct.4373 Given a pointer to a field, returns the base pointer of a struct.
4366 </p>4374 </p>
...@@ -4380,7 +4388,7 @@ test "main" {...@@ -4380,7 +4388,7 @@ test "main" {
4380 </p>4388 </p>
4381 {#header_close#}4389 {#header_close#}
4382 {#header_open|@import#}4390 {#header_open|@import#}
4383 <pre><code class="zig">@import(comptime path: []u8) -&gt; (namespace)</code></pre>4391 <pre><code class="zig">@import(comptime path: []u8) (namespace)</code></pre>
4384 <p>4392 <p>
4385 This function finds a zig file corresponding to <code>path</code> and imports all the4393 This function finds a zig file corresponding to <code>path</code> and imports all the
4386 public top level declarations into the resulting namespace.4394 public top level declarations into the resulting namespace.
...@@ -4400,7 +4408,7 @@ test "main" {...@@ -4400,7 +4408,7 @@ test "main" {
4400 {#see_also|Compile Variables|@embedFile#}4408 {#see_also|Compile Variables|@embedFile#}
4401 {#header_close#}4409 {#header_close#}
4402 {#header_open|@inlineCall#}4410 {#header_open|@inlineCall#}
4403 <pre><code class="zig">@inlineCall(function: X, args: ...) -&gt; Y</code></pre>4411 <pre><code class="zig">@inlineCall(function: X, args: ...) Y</code></pre>
4404 <p>4412 <p>
4405 This calls a function, in the same way that invoking an expression with parentheses does:4413 This calls a function, in the same way that invoking an expression with parentheses does:
4406 </p>4414 </p>
...@@ -4420,19 +4428,19 @@ fn add(a: i32, b: i32) i32 { return a + b; }...@@ -4420,19 +4428,19 @@ fn add(a: i32, b: i32) i32 { return a + b; }
4420 {#see_also|@noInlineCall#}4428 {#see_also|@noInlineCall#}
4421 {#header_close#}4429 {#header_close#}
4422 {#header_open|@intToPtr#}4430 {#header_open|@intToPtr#}
4423 <pre><code class="zig">@intToPtr(comptime DestType: type, int: usize) -&gt; DestType</code></pre>4431 <pre><code class="zig">@intToPtr(comptime DestType: type, int: usize) DestType</code></pre>
4424 <p>4432 <p>
4425 Converts an integer to a pointer. To convert the other way, use {#link|@ptrToInt#}.4433 Converts an integer to a pointer. To convert the other way, use {#link|@ptrToInt#}.
4426 </p>4434 </p>
4427 {#header_close#}4435 {#header_close#}
4428 {#header_open|@IntType#}4436 {#header_open|@IntType#}
4429 <pre><code class="zig">@IntType(comptime is_signed: bool, comptime bit_count: u8) -&gt; type</code></pre>4437 <pre><code class="zig">@IntType(comptime is_signed: bool, comptime bit_count: u8) type</code></pre>
4430 <p>4438 <p>
4431 This function returns an integer type with the given signness and bit count.4439 This function returns an integer type with the given signness and bit count.
4432 </p>4440 </p>
4433 {#header_close#}4441 {#header_close#}
4434 {#header_open|@maxValue#}4442 {#header_open|@maxValue#}
4435 <pre><code class="zig">@maxValue(comptime T: type) -&gt; (number literal)</code></pre>4443 <pre><code class="zig">@maxValue(comptime T: type) (number literal)</code></pre>
4436 <p>4444 <p>
4437 This function returns the maximum value of the integer type <code>T</code>.4445 This function returns the maximum value of the integer type <code>T</code>.
4438 </p>4446 </p>
...@@ -4441,7 +4449,7 @@ fn add(a: i32, b: i32) i32 { return a + b; }...@@ -4441,7 +4449,7 @@ fn add(a: i32, b: i32) i32 { return a + b; }
4441 </p>4449 </p>
4442 {#header_close#}4450 {#header_close#}
4443 {#header_open|@memberCount#}4451 {#header_open|@memberCount#}
4444 <pre><code class="zig">@memberCount(comptime T: type) -&gt; (number literal)</code></pre>4452 <pre><code class="zig">@memberCount(comptime T: type) (number literal)</code></pre>
4445 <p>4453 <p>
4446 This function returns the number of members in a struct, enum, or union type.4454 This function returns the number of members in a struct, enum, or union type.
4447 </p>4455 </p>
...@@ -4453,7 +4461,7 @@ fn add(a: i32, b: i32) i32 { return a + b; }...@@ -4453,7 +4461,7 @@ fn add(a: i32, b: i32) i32 { return a + b; }
4453 </p>4461 </p>
4454 {#header_close#}4462 {#header_close#}
4455 {#header_open|@memberName#}4463 {#header_open|@memberName#}
4456 <pre><code class="zig">@memberName(comptime T: type, comptime index: usize) -&gt; [N]u8</code></pre>4464 <pre><code class="zig">@memberName(comptime T: type, comptime index: usize) [N]u8</code></pre>
4457 <p>Returns the field name of a struct, union, or enum.</p>4465 <p>Returns the field name of a struct, union, or enum.</p>
4458 <p>4466 <p>
4459 The result is a compile time constant.4467 The result is a compile time constant.
...@@ -4463,15 +4471,15 @@ fn add(a: i32, b: i32) i32 { return a + b; }...@@ -4463,15 +4471,15 @@ fn add(a: i32, b: i32) i32 { return a + b; }
4463 </p>4471 </p>
4464 {#header_close#}4472 {#header_close#}
4465 {#header_open|@field#}4473 {#header_open|@field#}
4466 <pre><code class="zig">@field(lhs: var, comptime field_name: []const u8) -&gt; (field)</code></pre>4474 <pre><code class="zig">@field(lhs: var, comptime field_name: []const u8) (field)</code></pre>
4467 <p>Preforms field access equivalent to <code>lhs.-&gtfield_name-&lt</code>.</p>4475 <p>Preforms field access equivalent to <code>lhs.-&gtfield_name-&lt</code>.</p>
4468 {#header_close#}4476 {#header_close#}
4469 {#header_open|@memberType#}4477 {#header_open|@memberType#}
4470 <pre><code class="zig">@memberType(comptime T: type, comptime index: usize) -&gt; type</code></pre>4478 <pre><code class="zig">@memberType(comptime T: type, comptime index: usize) type</code></pre>
4471 <p>Returns the field type of a struct or union.</p>4479 <p>Returns the field type of a struct or union.</p>
4472 {#header_close#}4480 {#header_close#}
4473 {#header_open|@memcpy#}4481 {#header_open|@memcpy#}
4474 <pre><code class="zig">@memcpy(noalias dest: &u8, noalias source: &const u8, byte_count: usize)</code></pre>4482 <pre><code class="zig">@memcpy(noalias dest: *u8, noalias source: *const u8, byte_count: usize)</code></pre>
4475 <p>4483 <p>
4476 This function copies bytes from one region of memory to another. <code>dest</code> and4484 This function copies bytes from one region of memory to another. <code>dest</code> and
4477 <code>source</code> are both pointers and must not overlap.4485 <code>source</code> are both pointers and must not overlap.
...@@ -4489,7 +4497,7 @@ fn add(a: i32, b: i32) i32 { return a + b; }...@@ -4489,7 +4497,7 @@ fn add(a: i32, b: i32) i32 { return a + b; }
4489mem.copy(u8, dest[0...byte_count], source[0...byte_count]);</code></pre>4497mem.copy(u8, dest[0...byte_count], source[0...byte_count]);</code></pre>
4490 {#header_close#}4498 {#header_close#}
4491 {#header_open|@memset#}4499 {#header_open|@memset#}
4492 <pre><code class="zig">@memset(dest: &u8, c: u8, byte_count: usize)</code></pre>4500 <pre><code class="zig">@memset(dest: *u8, c: u8, byte_count: usize)</code></pre>
4493 <p>4501 <p>
4494 This function sets a region of memory to <code>c</code>. <code>dest</code> is a pointer.4502 This function sets a region of memory to <code>c</code>. <code>dest</code> is a pointer.
4495 </p>4503 </p>
...@@ -4506,7 +4514,7 @@ mem.copy(u8, dest[0...byte_count], source[0...byte_count]);</code></pre>...@@ -4506,7 +4514,7 @@ mem.copy(u8, dest[0...byte_count], source[0...byte_count]);</code></pre>
4506mem.set(u8, dest, c);</code></pre>4514mem.set(u8, dest, c);</code></pre>
4507 {#header_close#}4515 {#header_close#}
4508 {#header_open|@minValue#}4516 {#header_open|@minValue#}
4509 <pre><code class="zig">@minValue(comptime T: type) -&gt; (number literal)</code></pre>4517 <pre><code class="zig">@minValue(comptime T: type) (number literal)</code></pre>
4510 <p>4518 <p>
4511 This function returns the minimum value of the integer type T.4519 This function returns the minimum value of the integer type T.
4512 </p>4520 </p>
...@@ -4515,7 +4523,7 @@ mem.set(u8, dest, c);</code></pre>...@@ -4515,7 +4523,7 @@ mem.set(u8, dest, c);</code></pre>
4515 </p>4523 </p>
4516 {#header_close#}4524 {#header_close#}
4517 {#header_open|@mod#}4525 {#header_open|@mod#}
4518 <pre><code class="zig">@mod(numerator: T, denominator: T) -&gt; T</code></pre>4526 <pre><code class="zig">@mod(numerator: T, denominator: T) T</code></pre>
4519 <p>4527 <p>
4520 Modulus division. For unsigned integers this is the same as4528 Modulus division. For unsigned integers this is the same as
4521 <code>numerator % denominator</code>. Caller guarantees <code>denominator &gt; 0</code>.4529 <code>numerator % denominator</code>. Caller guarantees <code>denominator &gt; 0</code>.
...@@ -4528,7 +4536,7 @@ mem.set(u8, dest, c);</code></pre>...@@ -4528,7 +4536,7 @@ mem.set(u8, dest, c);</code></pre>
4528 {#see_also|@rem#}4536 {#see_also|@rem#}
4529 {#header_close#}4537 {#header_close#}
4530 {#header_open|@mulWithOverflow#}4538 {#header_open|@mulWithOverflow#}
4531 <pre><code class="zig">@mulWithOverflow(comptime T: type, a: T, b: T, result: &T) -&gt; bool</code></pre>4539 <pre><code class="zig">@mulWithOverflow(comptime T: type, a: T, b: T, result: *T) bool</code></pre>
4532 <p>4540 <p>
4533 Performs <code>result.* = a * b</code>. If overflow or underflow occurs,4541 Performs <code>result.* = a * b</code>. If overflow or underflow occurs,
4534 stores the overflowed bits in <code>result</code> and returns <code>true</code>.4542 stores the overflowed bits in <code>result</code> and returns <code>true</code>.
...@@ -4536,7 +4544,7 @@ mem.set(u8, dest, c);</code></pre>...@@ -4536,7 +4544,7 @@ mem.set(u8, dest, c);</code></pre>
4536 </p>4544 </p>
4537 {#header_close#}4545 {#header_close#}
4538 {#header_open|@newStackCall#}4546 {#header_open|@newStackCall#}
4539 <pre><code class="zig">@newStackCall(new_stack: []u8, function: var, args: ...) -&gt; var</code></pre>4547 <pre><code class="zig">@newStackCall(new_stack: []u8, function: var, args: ...) var</code></pre>
4540 <p>4548 <p>
4541 This calls a function, in the same way that invoking an expression with parentheses does. However,4549 This calls a function, in the same way that invoking an expression with parentheses does. However,
4542 instead of using the same stack as the caller, the function uses the stack provided in the <code>new_stack</code>4550 instead of using the same stack as the caller, the function uses the stack provided in the <code>new_stack</code>
...@@ -4572,7 +4580,7 @@ fn targetFunction(x: i32) usize {...@@ -4572,7 +4580,7 @@ fn targetFunction(x: i32) usize {
4572 {#code_end#}4580 {#code_end#}
4573 {#header_close#}4581 {#header_close#}
4574 {#header_open|@noInlineCall#}4582 {#header_open|@noInlineCall#}
4575 <pre><code class="zig">@noInlineCall(function: var, args: ...) -&gt; var</code></pre>4583 <pre><code class="zig">@noInlineCall(function: var, args: ...) var</code></pre>
4576 <p>4584 <p>
4577 This calls a function, in the same way that invoking an expression with parentheses does:4585 This calls a function, in the same way that invoking an expression with parentheses does:
4578 </p>4586 </p>
...@@ -4594,13 +4602,13 @@ fn add(a: i32, b: i32) i32 {...@@ -4594,13 +4602,13 @@ fn add(a: i32, b: i32) i32 {
4594 {#see_also|@inlineCall#}4602 {#see_also|@inlineCall#}
4595 {#header_close#}4603 {#header_close#}
4596 {#header_open|@offsetOf#}4604 {#header_open|@offsetOf#}
4597 <pre><code class="zig">@offsetOf(comptime T: type, comptime field_name: [] const u8) -&gt; (number literal)</code></pre>4605 <pre><code class="zig">@offsetOf(comptime T: type, comptime field_name: [] const u8) (number literal)</code></pre>
4598 <p>4606 <p>
4599 This function returns the byte offset of a field relative to its containing struct.4607 This function returns the byte offset of a field relative to its containing struct.
4600 </p>4608 </p>
4601 {#header_close#}4609 {#header_close#}
4602 {#header_open|@OpaqueType#}4610 {#header_open|@OpaqueType#}
4603 <pre><code class="zig">@OpaqueType() -&gt; type</code></pre>4611 <pre><code class="zig">@OpaqueType() type</code></pre>
4604 <p>4612 <p>
4605 Creates a new type with an unknown size and alignment.4613 Creates a new type with an unknown size and alignment.
4606 </p>4614 </p>
...@@ -4608,12 +4616,12 @@ fn add(a: i32, b: i32) i32 {...@@ -4608,12 +4616,12 @@ fn add(a: i32, b: i32) i32 {
4608 This is typically used for type safety when interacting with C code that does not expose struct details.4616 This is typically used for type safety when interacting with C code that does not expose struct details.
4609 Example:4617 Example:
4610 </p>4618 </p>
4611 {#code_begin|test_err|expected type '&Derp', found '&Wat'#}4619 {#code_begin|test_err|expected type '*Derp', found '*Wat'#}
4612const Derp = @OpaqueType();4620const Derp = @OpaqueType();
4613const Wat = @OpaqueType();4621const Wat = @OpaqueType();
46144622
4615extern fn bar(d: &Derp) void;4623extern fn bar(d: *Derp) void;
4616export fn foo(w: &Wat) void {4624export fn foo(w: *Wat) void {
4617 bar(w);4625 bar(w);
4618}4626}
46194627
...@@ -4623,7 +4631,7 @@ test "call foo" {...@@ -4623,7 +4631,7 @@ test "call foo" {
4623 {#code_end#}4631 {#code_end#}
4624 {#header_close#}4632 {#header_close#}
4625 {#header_open|@panic#}4633 {#header_open|@panic#}
4626 <pre><code class="zig">@panic(message: []const u8) -&gt; noreturn</code></pre>4634 <pre><code class="zig">@panic(message: []const u8) noreturn</code></pre>
4627 <p>4635 <p>
4628 Invokes the panic handler function. By default the panic handler function4636 Invokes the panic handler function. By default the panic handler function
4629 calls the public <code>panic</code> function exposed in the root source file, or4637 calls the public <code>panic</code> function exposed in the root source file, or
...@@ -4639,19 +4647,19 @@ test "call foo" {...@@ -4639,19 +4647,19 @@ test "call foo" {
4639 {#see_also|Root Source File#}4647 {#see_also|Root Source File#}
4640 {#header_close#}4648 {#header_close#}
4641 {#header_open|@ptrCast#}4649 {#header_open|@ptrCast#}
4642 <pre><code class="zig">@ptrCast(comptime DestType: type, value: var) -&gt; DestType</code></pre>4650 <pre><code class="zig">@ptrCast(comptime DestType: type, value: var) DestType</code></pre>
4643 <p>4651 <p>
4644 Converts a pointer of one type to a pointer of another type.4652 Converts a pointer of one type to a pointer of another type.
4645 </p>4653 </p>
4646 {#header_close#}4654 {#header_close#}
4647 {#header_open|@ptrToInt#}4655 {#header_open|@ptrToInt#}
4648 <pre><code class="zig">@ptrToInt(value: var) -&gt; usize</code></pre>4656 <pre><code class="zig">@ptrToInt(value: var) usize</code></pre>
4649 <p>4657 <p>
4650 Converts <code>value</code> to a <code>usize</code> which is the address of the pointer. <code>value</code> can be one of these types:4658 Converts <code>value</code> to a <code>usize</code> which is the address of the pointer. <code>value</code> can be one of these types:
4651 </p>4659 </p>
4652 <ul>4660 <ul>
4653 <li><code>&amp;T</code></li>4661 <li><code>*T</code></li>
4654 <li><code>?&amp;T</code></li>4662 <li><code>?*T</code></li>
4655 <li><code>fn()</code></li>4663 <li><code>fn()</code></li>
4656 <li><code>?fn()</code></li>4664 <li><code>?fn()</code></li>
4657 </ul>4665 </ul>
...@@ -4659,7 +4667,7 @@ test "call foo" {...@@ -4659,7 +4667,7 @@ test "call foo" {
46594667
4660 {#header_close#}4668 {#header_close#}
4661 {#header_open|@rem#}4669 {#header_open|@rem#}
4662 <pre><code class="zig">@rem(numerator: T, denominator: T) -&gt; T</code></pre>4670 <pre><code class="zig">@rem(numerator: T, denominator: T) T</code></pre>
4663 <p>4671 <p>
4664 Remainder division. For unsigned integers this is the same as4672 Remainder division. For unsigned integers this is the same as
4665 <code>numerator % denominator</code>. Caller guarantees <code>denominator &gt; 0</code>.4673 <code>numerator % denominator</code>. Caller guarantees <code>denominator &gt; 0</code>.
...@@ -4776,13 +4784,13 @@ pub const FloatMode = enum {...@@ -4776,13 +4784,13 @@ pub const FloatMode = enum {
4776 {#see_also|Compile Variables#}4784 {#see_also|Compile Variables#}
4777 {#header_close#}4785 {#header_close#}
4778 {#header_open|@setGlobalSection#}4786 {#header_open|@setGlobalSection#}
4779 <pre><code class="zig">@setGlobalSection(global_variable_name, comptime section_name: []const u8) -&gt; bool</code></pre>4787 <pre><code class="zig">@setGlobalSection(global_variable_name, comptime section_name: []const u8) bool</code></pre>
4780 <p>4788 <p>
4781 Puts the global variable in the specified section.4789 Puts the global variable in the specified section.
4782 </p>4790 </p>
4783 {#header_close#}4791 {#header_close#}
4784 {#header_open|@shlExact#}4792 {#header_open|@shlExact#}
4785 <pre><code class="zig">@shlExact(value: T, shift_amt: Log2T) -&gt; T</code></pre>4793 <pre><code class="zig">@shlExact(value: T, shift_amt: Log2T) T</code></pre>
4786 <p>4794 <p>
4787 Performs the left shift operation (<code>&lt;&lt;</code>). Caller guarantees4795 Performs the left shift operation (<code>&lt;&lt;</code>). Caller guarantees
4788 that the shift will not shift any 1 bits out.4796 that the shift will not shift any 1 bits out.
...@@ -4794,7 +4802,7 @@ pub const FloatMode = enum {...@@ -4794,7 +4802,7 @@ pub const FloatMode = enum {
4794 {#see_also|@shrExact|@shlWithOverflow#}4802 {#see_also|@shrExact|@shlWithOverflow#}
4795 {#header_close#}4803 {#header_close#}
4796 {#header_open|@shlWithOverflow#}4804 {#header_open|@shlWithOverflow#}
4797 <pre><code class="zig">@shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: &T) -&gt; bool</code></pre>4805 <pre><code class="zig">@shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: *T) bool</code></pre>
4798 <p>4806 <p>
4799 Performs <code>result.* = a &lt;&lt; b</code>. If overflow or underflow occurs,4807 Performs <code>result.* = a &lt;&lt; b</code>. If overflow or underflow occurs,
4800 stores the overflowed bits in <code>result</code> and returns <code>true</code>.4808 stores the overflowed bits in <code>result</code> and returns <code>true</code>.
...@@ -4807,7 +4815,7 @@ pub const FloatMode = enum {...@@ -4807,7 +4815,7 @@ pub const FloatMode = enum {
4807 {#see_also|@shlExact|@shrExact#}4815 {#see_also|@shlExact|@shrExact#}
4808 {#header_close#}4816 {#header_close#}
4809 {#header_open|@shrExact#}4817 {#header_open|@shrExact#}
4810 <pre><code class="zig">@shrExact(value: T, shift_amt: Log2T) -&gt; T</code></pre>4818 <pre><code class="zig">@shrExact(value: T, shift_amt: Log2T) T</code></pre>
4811 <p>4819 <p>
4812 Performs the right shift operation (<code>&gt;&gt;</code>). Caller guarantees4820 Performs the right shift operation (<code>&gt;&gt;</code>). Caller guarantees
4813 that the shift will not shift any 1 bits out.4821 that the shift will not shift any 1 bits out.
...@@ -4819,7 +4827,7 @@ pub const FloatMode = enum {...@@ -4819,7 +4827,7 @@ pub const FloatMode = enum {
4819 {#see_also|@shlExact|@shlWithOverflow#}4827 {#see_also|@shlExact|@shlWithOverflow#}
4820 {#header_close#}4828 {#header_close#}
4821 {#header_open|@sizeOf#}4829 {#header_open|@sizeOf#}
4822 <pre><code class="zig">@sizeOf(comptime T: type) -&gt; (number literal)</code></pre>4830 <pre><code class="zig">@sizeOf(comptime T: type) (number literal)</code></pre>
4823 <p>4831 <p>
4824 This function returns the number of bytes it takes to store <code>T</code> in memory.4832 This function returns the number of bytes it takes to store <code>T</code> in memory.
4825 </p>4833 </p>
...@@ -4828,7 +4836,7 @@ pub const FloatMode = enum {...@@ -4828,7 +4836,7 @@ pub const FloatMode = enum {
4828 </p>4836 </p>
4829 {#header_close#}4837 {#header_close#}
4830 {#header_open|@sqrt#}4838 {#header_open|@sqrt#}
4831 <pre><code class="zig">@sqrt(comptime T: type, value: T) -&gt; T</code></pre>4839 <pre><code class="zig">@sqrt(comptime T: type, value: T) T</code></pre>
4832 <p>4840 <p>
4833 Performs the square root of a floating point number. Uses a dedicated hardware instruction4841 Performs the square root of a floating point number. Uses a dedicated hardware instruction
4834 when available. Currently only supports f32 and f64 at runtime. f128 at runtime is TODO.4842 when available. Currently only supports f32 and f64 at runtime. f128 at runtime is TODO.
...@@ -4838,7 +4846,7 @@ pub const FloatMode = enum {...@@ -4838,7 +4846,7 @@ pub const FloatMode = enum {
4838 </p>4846 </p>
4839 {#header_close#}4847 {#header_close#}
4840 {#header_open|@subWithOverflow#}4848 {#header_open|@subWithOverflow#}
4841 <pre><code class="zig">@subWithOverflow(comptime T: type, a: T, b: T, result: &T) -&gt; bool</code></pre>4849 <pre><code class="zig">@subWithOverflow(comptime T: type, a: T, b: T, result: *T) bool</code></pre>
4842 <p>4850 <p>
4843 Performs <code>result.* = a - b</code>. If overflow or underflow occurs,4851 Performs <code>result.* = a - b</code>. If overflow or underflow occurs,
4844 stores the overflowed bits in <code>result</code> and returns <code>true</code>.4852 stores the overflowed bits in <code>result</code> and returns <code>true</code>.
...@@ -4846,7 +4854,7 @@ pub const FloatMode = enum {...@@ -4846,7 +4854,7 @@ pub const FloatMode = enum {
4846 </p>4854 </p>
4847 {#header_close#}4855 {#header_close#}
4848 {#header_open|@truncate#}4856 {#header_open|@truncate#}
4849 <pre><code class="zig">@truncate(comptime T: type, integer) -&gt; T</code></pre>4857 <pre><code class="zig">@truncate(comptime T: type, integer) T</code></pre>
4850 <p>4858 <p>
4851 This function truncates bits from an integer type, resulting in a smaller4859 This function truncates bits from an integer type, resulting in a smaller
4852 integer type.4860 integer type.
...@@ -4870,7 +4878,7 @@ const b: u8 = @truncate(u8, a);...@@ -4870,7 +4878,7 @@ const b: u8 = @truncate(u8, a);
48704878
4871 {#header_close#}4879 {#header_close#}
4872 {#header_open|@typeId#}4880 {#header_open|@typeId#}
4873 <pre><code class="zig">@typeId(comptime T: type) -&gt; @import("builtin").TypeId</code></pre>4881 <pre><code class="zig">@typeId(comptime T: type) @import("builtin").TypeId</code></pre>
4874 <p>4882 <p>
4875 Returns which kind of type something is. Possible values:4883 Returns which kind of type something is. Possible values:
4876 </p>4884 </p>
...@@ -4904,7 +4912,7 @@ pub const TypeId = enum {...@@ -4904,7 +4912,7 @@ pub const TypeId = enum {
4904 {#code_end#}4912 {#code_end#}
4905 {#header_close#}4913 {#header_close#}
4906 {#header_open|@typeInfo#}4914 {#header_open|@typeInfo#}
4907 <pre><code class="zig">@typeInfo(comptime T: type) -&gt; @import("builtin").TypeInfo</code></pre>4915 <pre><code class="zig">@typeInfo(comptime T: type) @import("builtin").TypeInfo</code></pre>
4908 <p>4916 <p>
4909 Returns information on the type. Returns a value of the following union:4917 Returns information on the type. Returns a value of the following union:
4910 </p>4918 </p>
...@@ -5080,14 +5088,14 @@ pub const TypeInfo = union(TypeId) {...@@ -5080,14 +5088,14 @@ pub const TypeInfo = union(TypeId) {
5080 {#code_end#}5088 {#code_end#}
5081 {#header_close#}5089 {#header_close#}
5082 {#header_open|@typeName#}5090 {#header_open|@typeName#}
5083 <pre><code class="zig">@typeName(T: type) -&gt; []u8</code></pre>5091 <pre><code class="zig">@typeName(T: type) []u8</code></pre>
5084 <p>5092 <p>
5085 This function returns the string representation of a type.5093 This function returns the string representation of a type.
5086 </p>5094 </p>
50875095
5088 {#header_close#}5096 {#header_close#}
5089 {#header_open|@typeOf#}5097 {#header_open|@typeOf#}
5090 <pre><code class="zig">@typeOf(expression) -&gt; type</code></pre>5098 <pre><code class="zig">@typeOf(expression) type</code></pre>
5091 <p>5099 <p>
5092 This function returns a compile-time constant, which is the type of the5100 This function returns a compile-time constant, which is the type of the
5093 expression passed as an argument. The expression is evaluated.5101 expression passed as an argument. The expression is evaluated.
...@@ -5937,7 +5945,7 @@ pub const __zig_test_fn_slice = {}; // overwritten later...@@ -5937,7 +5945,7 @@ pub const __zig_test_fn_slice = {}; // overwritten later
5937 {#header_open|C String Literals#}5945 {#header_open|C String Literals#}
5938 {#code_begin|exe#}5946 {#code_begin|exe#}
5939 {#link_libc#}5947 {#link_libc#}
5940extern fn puts(&const u8) void;5948extern fn puts([*]const u8) void;
59415949
5942pub fn main() void {5950pub fn main() void {
5943 puts(c"this has a null terminator");5951 puts(c"this has a null terminator");
...@@ -5996,8 +6004,8 @@ const c = @cImport({...@@ -5996,8 +6004,8 @@ const c = @cImport({
5996 {#code_begin|syntax#}6004 {#code_begin|syntax#}
5997const base64 = @import("std").base64;6005const base64 = @import("std").base64;
59986006
5999export fn decode_base_64(dest_ptr: &u8, dest_len: usize,6007export fn decode_base_64(dest_ptr: *u8, dest_len: usize,
6000 source_ptr: &const u8, source_len: usize) usize6008 source_ptr: *const u8, source_len: usize) usize
6001{6009{
6002 const src = source_ptr[0..source_len];6010 const src = source_ptr[0..source_len];
6003 const dest = dest_ptr[0..dest_len];6011 const dest = dest_ptr[0..dest_len];
...@@ -6028,7 +6036,7 @@ int main(int argc, char **argv) {...@@ -6028,7 +6036,7 @@ int main(int argc, char **argv) {
6028 {#code_begin|syntax#}6036 {#code_begin|syntax#}
6029const Builder = @import("std").build.Builder;6037const Builder = @import("std").build.Builder;
60306038
6031pub fn build(b: &Builder) void {6039pub fn build(b: *Builder) void {
6032 const obj = b.addObject("base64", "base64.zig");6040 const obj = b.addObject("base64", "base64.zig");
60336041
6034 const exe = b.addCExecutable("test");6042 const exe = b.addCExecutable("test");
...@@ -6450,7 +6458,7 @@ ContainerInitBody = list(StructLiteralField, ",") | list(Expression, ",")...@@ -6450,7 +6458,7 @@ ContainerInitBody = list(StructLiteralField, ",") | list(Expression, ",")
64506458
6451StructLiteralField = "." Symbol "=" Expression6459StructLiteralField = "." Symbol "=" Expression
64526460
6453PrefixOp = "!" | "-" | "~" | ("*" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "??" | "-%" | "try" | "await"6461PrefixOp = "!" | "-" | "~" | (("*" | "[*]") option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "??" | "-%" | "try" | "await"
64546462
6455PrimaryExpression = Integer | Float | String | CharLiteral | KeywordLiteral | GroupedExpression | BlockExpression(BlockOrExpression) | Symbol | ("@" Symbol FnCallExpression) | ArrayType | FnProto | AsmExpression | ContainerDecl | ("continue" option(":" Symbol)) | ErrorSetDecl | PromiseType6463PrimaryExpression = Integer | Float | String | CharLiteral | KeywordLiteral | GroupedExpression | BlockExpression(BlockOrExpression) | Symbol | ("@" Symbol FnCallExpression) | ArrayType | FnProto | AsmExpression | ContainerDecl | ("continue" option(":" Symbol)) | ErrorSetDecl | PromiseType
64566464
...@@ -6544,7 +6552,7 @@ hljs.registerLanguage("zig", function(t) {...@@ -6544,7 +6552,7 @@ hljs.registerLanguage("zig", function(t) {
6544 a = t.IR + "\\s*\\(",6552 a = t.IR + "\\s*\\(",
6545 c = {6553 c = {
6546 keyword: "const align var extern stdcallcc nakedcc volatile export pub noalias inline struct packed enum union break return try catch test continue unreachable comptime and or asm defer errdefer if else switch while for fn use bool f32 f64 void type noreturn error i8 u8 i16 u16 i32 u32 i64 u64 isize usize i8w u8w i16w i32w u32w i64w u64w isizew usizew c_short c_ushort c_int c_uint c_long c_ulong c_longlong c_ulonglong",6554 keyword: "const align var extern stdcallcc nakedcc volatile export pub noalias inline struct packed enum union break return try catch test continue unreachable comptime and or asm defer errdefer if else switch while for fn use bool f32 f64 void type noreturn error i8 u8 i16 u16 i32 u32 i64 u64 isize usize i8w u8w i16w i32w u32w i64w u64w isizew usizew c_short c_ushort c_int c_uint c_long c_ulong c_longlong c_ulonglong",
6547 built_in: "atomicLoad breakpoint returnAddress frameAddress fieldParentPtr setFloatMode IntType OpaqueType compileError compileLog setCold setRuntimeSafety setEvalBranchQuota offsetOf memcpy inlineCall setGlobalLinkage setGlobalSection divTrunc divFloor enumTagName intToPtr ptrToInt panic canImplicitCast ptrCast bitCast rem mod memset sizeOf alignOf alignCast maxValue minValue memberCount memberName memberType typeOf addWithOverflow subWithOverflow mulWithOverflow shlWithOverflow shlExact shrExact cInclude cDefine cUndef ctz clz import cImport errorName embedFile cmpxchgStrong cmpxchgWeak fence divExact truncate atomicRmw sqrt field typeInfo newStackCall",6555 built_in: "atomicLoad breakpoint returnAddress frameAddress fieldParentPtr setFloatMode IntType OpaqueType compileError compileLog setCold setRuntimeSafety setEvalBranchQuota offsetOf memcpy inlineCall setGlobalLinkage setGlobalSection divTrunc divFloor enumTagName intToPtr ptrToInt panic canImplicitCast ptrCast bitCast rem mod memset sizeOf alignOf alignCast maxValue minValue memberCount memberName memberType typeOf addWithOverflow subWithOverflow mulWithOverflow shlWithOverflow shlExact shrExact cInclude cDefine cUndef ctz clz import cImport errorName embedFile cmpxchgStrong cmpxchgWeak fence divExact truncate atomicRmw sqrt field typeInfo typeName newStackCall",
6548 literal: "true false null undefined"6556 literal: "true false null undefined"
6549 },6557 },
6550 n = [e, t.CLCM, t.CBCM, s, r];6558 n = [e, t.CLCM, t.CBCM, s, r];
example/cat/main.zig+1-1
...@@ -41,7 +41,7 @@ fn usage(exe: []const u8) !void {...@@ -41,7 +41,7 @@ fn usage(exe: []const u8) !void {
41 return error.Invalid;41 return error.Invalid;
42}42}
4343
44fn cat_file(stdout: &os.File, file: &os.File) !void {44fn cat_file(stdout: *os.File, file: *os.File) !void {
45 var buf: [1024 * 4]u8 = undefined;45 var buf: [1024 * 4]u8 = undefined;
4646
47 while (true) {47 while (true) {
example/hello_world/hello_libc.zig+1-1
...@@ -7,7 +7,7 @@ const c = @cImport({...@@ -7,7 +7,7 @@ const c = @cImport({
77
8const msg = c"Hello, world!\n";8const msg = c"Hello, world!\n";
99
10export fn main(argc: c_int, argv: &&u8) c_int {10export fn main(argc: c_int, argv: **u8) c_int {
11 if (c.printf(msg) != c_int(c.strlen(msg))) return -1;11 if (c.printf(msg) != c_int(c.strlen(msg))) return -1;
1212
13 return 0;13 return 0;
example/mix_o_files/base64.zig+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const base64 = @import("std").base64;1const base64 = @import("std").base64;
22
3export fn decode_base_64(dest_ptr: &u8, dest_len: usize, source_ptr: &const u8, source_len: usize) usize {3export fn decode_base_64(dest_ptr: *u8, dest_len: usize, source_ptr: *const u8, source_len: usize) usize {
4 const src = source_ptr[0..source_len];4 const src = source_ptr[0..source_len];
5 const dest = dest_ptr[0..dest_len];5 const dest = dest_ptr[0..dest_len];
6 const base64_decoder = base64.standard_decoder_unsafe;6 const base64_decoder = base64.standard_decoder_unsafe;
example/mix_o_files/build.zig+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const Builder = @import("std").build.Builder;1const Builder = @import("std").build.Builder;
22
3pub fn build(b: &Builder) void {3pub fn build(b: *Builder) void {
4 const obj = b.addObject("base64", "base64.zig");4 const obj = b.addObject("base64", "base64.zig");
55
6 const exe = b.addCExecutable("test");6 const exe = b.addCExecutable("test");
example/shared_library/build.zig+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const Builder = @import("std").build.Builder;1const Builder = @import("std").build.Builder;
22
3pub fn build(b: &Builder) void {3pub fn build(b: *Builder) void {
4 const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0));4 const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0));
55
6 const exe = b.addCExecutable("test");6 const exe = b.addCExecutable("test");
src-self-hosted/arg.zig+6-6
...@@ -30,7 +30,7 @@ fn argInAllowedSet(maybe_set: ?[]const []const u8, arg: []const u8) bool {...@@ -30,7 +30,7 @@ fn argInAllowedSet(maybe_set: ?[]const []const u8, arg: []const u8) bool {
30}30}
3131
32// Modifies the current argument index during iteration32// Modifies the current argument index during iteration
33fn readFlagArguments(allocator: &Allocator, args: []const []const u8, required: usize, allowed_set: ?[]const []const u8, index: &usize) !FlagArg {33fn readFlagArguments(allocator: *Allocator, args: []const []const u8, required: usize, allowed_set: ?[]const []const u8, index: *usize) !FlagArg {
34 switch (required) {34 switch (required) {
35 0 => return FlagArg{ .None = undefined }, // TODO: Required to force non-tag but value?35 0 => return FlagArg{ .None = undefined }, // TODO: Required to force non-tag but value?
36 1 => {36 1 => {
...@@ -79,7 +79,7 @@ pub const Args = struct {...@@ -79,7 +79,7 @@ pub const Args = struct {
79 flags: HashMapFlags,79 flags: HashMapFlags,
80 positionals: ArrayList([]const u8),80 positionals: ArrayList([]const u8),
8181
82 pub fn parse(allocator: &Allocator, comptime spec: []const Flag, args: []const []const u8) !Args {82 pub fn parse(allocator: *Allocator, comptime spec: []const Flag, args: []const []const u8) !Args {
83 var parsed = Args{83 var parsed = Args{
84 .flags = HashMapFlags.init(allocator),84 .flags = HashMapFlags.init(allocator),
85 .positionals = ArrayList([]const u8).init(allocator),85 .positionals = ArrayList([]const u8).init(allocator),
...@@ -143,18 +143,18 @@ pub const Args = struct {...@@ -143,18 +143,18 @@ pub const Args = struct {
143 return parsed;143 return parsed;
144 }144 }
145145
146 pub fn deinit(self: &Args) void {146 pub fn deinit(self: *Args) void {
147 self.flags.deinit();147 self.flags.deinit();
148 self.positionals.deinit();148 self.positionals.deinit();
149 }149 }
150150
151 // e.g. --help151 // e.g. --help
152 pub fn present(self: &Args, name: []const u8) bool {152 pub fn present(self: *Args, name: []const u8) bool {
153 return self.flags.contains(name);153 return self.flags.contains(name);
154 }154 }
155155
156 // e.g. --name value156 // e.g. --name value
157 pub fn single(self: &Args, name: []const u8) ?[]const u8 {157 pub fn single(self: *Args, name: []const u8) ?[]const u8 {
158 if (self.flags.get(name)) |entry| {158 if (self.flags.get(name)) |entry| {
159 switch (entry.value) {159 switch (entry.value) {
160 FlagArg.Single => |inner| {160 FlagArg.Single => |inner| {
...@@ -168,7 +168,7 @@ pub const Args = struct {...@@ -168,7 +168,7 @@ pub const Args = struct {
168 }168 }
169169
170 // e.g. --names value1 value2 value3170 // e.g. --names value1 value2 value3
171 pub fn many(self: &Args, name: []const u8) ?[]const []const u8 {171 pub fn many(self: *Args, name: []const u8) ?[]const []const u8 {
172 if (self.flags.get(name)) |entry| {172 if (self.flags.get(name)) |entry| {
173 switch (entry.value) {173 switch (entry.value) {
174 FlagArg.Many => |inner| {174 FlagArg.Many => |inner| {
src-self-hosted/errmsg.zig created+87
...@@ -0,0 +1,87 @@
1const std = @import("std");
2const mem = std.mem;
3const os = std.os;
4const Token = std.zig.Token;
5const ast = std.zig.ast;
6const TokenIndex = std.zig.ast.TokenIndex;
7
8pub const Color = enum {
9 Auto,
10 Off,
11 On,
12};
13
14pub const Msg = struct {
15 path: []const u8,
16 text: []u8,
17 first_token: TokenIndex,
18 last_token: TokenIndex,
19 tree: *ast.Tree,
20};
21
22/// `path` must outlive the returned Msg
23/// `tree` must outlive the returned Msg
24/// Caller owns returned Msg and must free with `allocator`
25pub fn createFromParseError(
26 allocator: *mem.Allocator,
27 parse_error: *const ast.Error,
28 tree: *ast.Tree,
29 path: []const u8,
30) !*Msg {
31 const loc_token = parse_error.loc();
32 var text_buf = try std.Buffer.initSize(allocator, 0);
33 defer text_buf.deinit();
34
35 var out_stream = &std.io.BufferOutStream.init(&text_buf).stream;
36 try parse_error.render(&tree.tokens, out_stream);
37
38 const msg = try allocator.construct(Msg{
39 .tree = tree,
40 .path = path,
41 .text = text_buf.toOwnedSlice(),
42 .first_token = loc_token,
43 .last_token = loc_token,
44 });
45 errdefer allocator.destroy(msg);
46
47 return msg;
48}
49
50pub fn printToStream(stream: var, msg: *const Msg, color_on: bool) !void {
51 const first_token = msg.tree.tokens.at(msg.first_token);
52 const last_token = msg.tree.tokens.at(msg.last_token);
53 const start_loc = msg.tree.tokenLocationPtr(0, first_token);
54 const end_loc = msg.tree.tokenLocationPtr(first_token.end, last_token);
55 if (!color_on) {
56 try stream.print(
57 "{}:{}:{}: error: {}\n",
58 msg.path,
59 start_loc.line + 1,
60 start_loc.column + 1,
61 msg.text,
62 );
63 return;
64 }
65
66 try stream.print(
67 "{}:{}:{}: error: {}\n{}\n",
68 msg.path,
69 start_loc.line + 1,
70 start_loc.column + 1,
71 msg.text,
72 msg.tree.source[start_loc.line_start..start_loc.line_end],
73 );
74 try stream.writeByteNTimes(' ', start_loc.column);
75 try stream.writeByteNTimes('~', last_token.end - first_token.start);
76 try stream.write("\n");
77}
78
79pub fn printToFile(file: *os.File, msg: *const Msg, color: Color) !void {
80 const color_on = switch (color) {
81 Color.Auto => file.isTty(),
82 Color.On => true,
83 Color.Off => false,
84 };
85 var stream = &std.io.FileOutStream.init(file).stream;
86 return printToStream(stream, msg, color_on);
87}
src-self-hosted/introspect.zig+3-3
...@@ -7,7 +7,7 @@ const os = std.os;...@@ -7,7 +7,7 @@ const os = std.os;
7const warn = std.debug.warn;7const warn = std.debug.warn;
88
9/// Caller must free result9/// Caller must free result
10pub fn testZigInstallPrefix(allocator: &mem.Allocator, test_path: []const u8) ![]u8 {10pub fn testZigInstallPrefix(allocator: *mem.Allocator, test_path: []const u8) ![]u8 {
11 const test_zig_dir = try os.path.join(allocator, test_path, "lib", "zig");11 const test_zig_dir = try os.path.join(allocator, test_path, "lib", "zig");
12 errdefer allocator.free(test_zig_dir);12 errdefer allocator.free(test_zig_dir);
1313
...@@ -21,7 +21,7 @@ pub fn testZigInstallPrefix(allocator: &mem.Allocator, test_path: []const u8) ![...@@ -21,7 +21,7 @@ pub fn testZigInstallPrefix(allocator: &mem.Allocator, test_path: []const u8) ![
21}21}
2222
23/// Caller must free result23/// Caller must free result
24pub fn findZigLibDir(allocator: &mem.Allocator) ![]u8 {24pub fn findZigLibDir(allocator: *mem.Allocator) ![]u8 {
25 const self_exe_path = try os.selfExeDirPath(allocator);25 const self_exe_path = try os.selfExeDirPath(allocator);
26 defer allocator.free(self_exe_path);26 defer allocator.free(self_exe_path);
2727
...@@ -42,7 +42,7 @@ pub fn findZigLibDir(allocator: &mem.Allocator) ![]u8 {...@@ -42,7 +42,7 @@ pub fn findZigLibDir(allocator: &mem.Allocator) ![]u8 {
42 return error.FileNotFound;42 return error.FileNotFound;
43}43}
4444
45pub fn resolveZigLibDir(allocator: &mem.Allocator) ![]u8 {45pub fn resolveZigLibDir(allocator: *mem.Allocator) ![]u8 {
46 return findZigLibDir(allocator) catch |err| {46 return findZigLibDir(allocator) catch |err| {
47 warn(47 warn(
48 \\Unable to find zig lib directory: {}.48 \\Unable to find zig lib directory: {}.
src-self-hosted/ir.zig+1-1
...@@ -2,7 +2,7 @@ const Scope = @import("scope.zig").Scope;...@@ -2,7 +2,7 @@ const Scope = @import("scope.zig").Scope;
22
3pub const Instruction = struct {3pub const Instruction = struct {
4 id: Id,4 id: Id,
5 scope: &Scope,5 scope: *Scope,
66
7 pub const Id = enum {7 pub const Id = enum {
8 Br,8 Br,
src-self-hosted/main.zig+73-54
...@@ -15,9 +15,11 @@ const Args = arg.Args;...@@ -15,9 +15,11 @@ const Args = arg.Args;
15const Flag = arg.Flag;15const Flag = arg.Flag;
16const Module = @import("module.zig").Module;16const Module = @import("module.zig").Module;
17const Target = @import("target.zig").Target;17const Target = @import("target.zig").Target;
18const errmsg = @import("errmsg.zig");
1819
19var stderr: &io.OutStream(io.FileOutStream.Error) = undefined;20var stderr_file: os.File = undefined;
20var stdout: &io.OutStream(io.FileOutStream.Error) = undefined;21var stderr: *io.OutStream(io.FileOutStream.Error) = undefined;
22var stdout: *io.OutStream(io.FileOutStream.Error) = undefined;
2123
22const usage =24const usage =
23 \\usage: zig [command] [options]25 \\usage: zig [command] [options]
...@@ -41,7 +43,7 @@ const usage =...@@ -41,7 +43,7 @@ const usage =
4143
42const Command = struct {44const Command = struct {
43 name: []const u8,45 name: []const u8,
44 exec: fn(&Allocator, []const []const u8) error!void,46 exec: fn (*Allocator, []const []const u8) error!void,
45};47};
4648
47pub fn main() !void {49pub fn main() !void {
...@@ -51,7 +53,7 @@ pub fn main() !void {...@@ -51,7 +53,7 @@ pub fn main() !void {
51 var stdout_out_stream = std.io.FileOutStream.init(&stdout_file);53 var stdout_out_stream = std.io.FileOutStream.init(&stdout_file);
52 stdout = &stdout_out_stream.stream;54 stdout = &stdout_out_stream.stream;
5355
54 var stderr_file = try std.io.getStdErr();56 stderr_file = try std.io.getStdErr();
55 var stderr_out_stream = std.io.FileOutStream.init(&stderr_file);57 var stderr_out_stream = std.io.FileOutStream.init(&stderr_file);
56 stderr = &stderr_out_stream.stream;58 stderr = &stderr_out_stream.stream;
5759
...@@ -189,7 +191,7 @@ const missing_build_file =...@@ -189,7 +191,7 @@ const missing_build_file =
189 \\191 \\
190;192;
191193
192fn cmdBuild(allocator: &Allocator, args: []const []const u8) !void {194fn cmdBuild(allocator: *Allocator, args: []const []const u8) !void {
193 var flags = try Args.parse(allocator, args_build_spec, args);195 var flags = try Args.parse(allocator, args_build_spec, args);
194 defer flags.deinit();196 defer flags.deinit();
195197
...@@ -424,7 +426,7 @@ const args_build_generic = []Flag{...@@ -424,7 +426,7 @@ const args_build_generic = []Flag{
424 Flag.Arg1("--ver-patch"),426 Flag.Arg1("--ver-patch"),
425};427};
426428
427fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: Module.Kind) !void {429fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Module.Kind) !void {
428 var flags = try Args.parse(allocator, args_build_generic, args);430 var flags = try Args.parse(allocator, args_build_generic, args);
429 defer flags.deinit();431 defer flags.deinit();
430432
...@@ -440,18 +442,19 @@ fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: Mo...@@ -440,18 +442,19 @@ fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: Mo
440 build_mode = builtin.Mode.ReleaseSafe;442 build_mode = builtin.Mode.ReleaseSafe;
441 }443 }
442444
443 var color = Module.ErrColor.Auto;445 const color = blk: {
444 if (flags.single("color")) |color_flag| {446 if (flags.single("color")) |color_flag| {
445 if (mem.eql(u8, color_flag, "auto")) {447 if (mem.eql(u8, color_flag, "auto")) {
446 color = Module.ErrColor.Auto;448 break :blk errmsg.Color.Auto;
447 } else if (mem.eql(u8, color_flag, "on")) {449 } else if (mem.eql(u8, color_flag, "on")) {
448 color = Module.ErrColor.On;450 break :blk errmsg.Color.On;
449 } else if (mem.eql(u8, color_flag, "off")) {451 } else if (mem.eql(u8, color_flag, "off")) {
450 color = Module.ErrColor.Off;452 break :blk errmsg.Color.Off;
453 } else unreachable;
451 } else {454 } else {
452 unreachable;455 break :blk errmsg.Color.Auto;
453 }456 }
454 }457 };
455458
456 var emit_type = Module.Emit.Binary;459 var emit_type = Module.Emit.Binary;
457 if (flags.single("emit")) |emit_flag| {460 if (flags.single("emit")) |emit_flag| {
...@@ -658,19 +661,19 @@ fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: Mo...@@ -658,19 +661,19 @@ fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: Mo
658 try stderr.print("building {}: {}\n", @tagName(out_type), in_file);661 try stderr.print("building {}: {}\n", @tagName(out_type), in_file);
659}662}
660663
661fn cmdBuildExe(allocator: &Allocator, args: []const []const u8) !void {664fn cmdBuildExe(allocator: *Allocator, args: []const []const u8) !void {
662 try buildOutputType(allocator, args, Module.Kind.Exe);665 try buildOutputType(allocator, args, Module.Kind.Exe);
663}666}
664667
665// cmd:build-lib ///////////////////////////////////////////////////////////////////////////////////668// cmd:build-lib ///////////////////////////////////////////////////////////////////////////////////
666669
667fn cmdBuildLib(allocator: &Allocator, args: []const []const u8) !void {670fn cmdBuildLib(allocator: *Allocator, args: []const []const u8) !void {
668 try buildOutputType(allocator, args, Module.Kind.Lib);671 try buildOutputType(allocator, args, Module.Kind.Lib);
669}672}
670673
671// cmd:build-obj ///////////////////////////////////////////////////////////////////////////////////674// cmd:build-obj ///////////////////////////////////////////////////////////////////////////////////
672675
673fn cmdBuildObj(allocator: &Allocator, args: []const []const u8) !void {676fn cmdBuildObj(allocator: *Allocator, args: []const []const u8) !void {
674 try buildOutputType(allocator, args, Module.Kind.Obj);677 try buildOutputType(allocator, args, Module.Kind.Obj);
675}678}
676679
...@@ -683,13 +686,21 @@ const usage_fmt =...@@ -683,13 +686,21 @@ const usage_fmt =
683 \\686 \\
684 \\Options:687 \\Options:
685 \\ --help Print this help and exit688 \\ --help Print this help and exit
689 \\ --color [auto|off|on] Enable or disable colored error messages
686 \\690 \\
687 \\691 \\
688;692;
689693
690const args_fmt_spec = []Flag{Flag.Bool("--help")};694const args_fmt_spec = []Flag{
695 Flag.Bool("--help"),
696 Flag.Option("--color", []const []const u8{
697 "auto",
698 "off",
699 "on",
700 }),
701};
691702
692fn cmdFmt(allocator: &Allocator, args: []const []const u8) !void {703fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void {
693 var flags = try Args.parse(allocator, args_fmt_spec, args);704 var flags = try Args.parse(allocator, args_fmt_spec, args);
694 defer flags.deinit();705 defer flags.deinit();
695706
...@@ -703,61 +714,69 @@ fn cmdFmt(allocator: &Allocator, args: []const []const u8) !void {...@@ -703,61 +714,69 @@ fn cmdFmt(allocator: &Allocator, args: []const []const u8) !void {
703 os.exit(1);714 os.exit(1);
704 }715 }
705716
717 const color = blk: {
718 if (flags.single("color")) |color_flag| {
719 if (mem.eql(u8, color_flag, "auto")) {
720 break :blk errmsg.Color.Auto;
721 } else if (mem.eql(u8, color_flag, "on")) {
722 break :blk errmsg.Color.On;
723 } else if (mem.eql(u8, color_flag, "off")) {
724 break :blk errmsg.Color.Off;
725 } else unreachable;
726 } else {
727 break :blk errmsg.Color.Auto;
728 }
729 };
730
731 var fmt_errors = false;
706 for (flags.positionals.toSliceConst()) |file_path| {732 for (flags.positionals.toSliceConst()) |file_path| {
707 var file = try os.File.openRead(allocator, file_path);733 var file = try os.File.openRead(allocator, file_path);
708 defer file.close();734 defer file.close();
709735
710 const source_code = io.readFileAlloc(allocator, file_path) catch |err| {736 const source_code = io.readFileAlloc(allocator, file_path) catch |err| {
711 try stderr.print("unable to open '{}': {}", file_path, err);737 try stderr.print("unable to open '{}': {}", file_path, err);
738 fmt_errors = true;
712 continue;739 continue;
713 };740 };
714 defer allocator.free(source_code);741 defer allocator.free(source_code);
715742
716 var tree = std.zig.parse(allocator, source_code) catch |err| {743 var tree = std.zig.parse(allocator, source_code) catch |err| {
717 try stderr.print("error parsing file '{}': {}\n", file_path, err);744 try stderr.print("error parsing file '{}': {}\n", file_path, err);
745 fmt_errors = true;
718 continue;746 continue;
719 };747 };
720 defer tree.deinit();748 defer tree.deinit();
721749
722 var error_it = tree.errors.iterator(0);750 var error_it = tree.errors.iterator(0);
723 while (error_it.next()) |parse_error| {751 while (error_it.next()) |parse_error| {
724 const token = tree.tokens.at(parse_error.loc());752 const msg = try errmsg.createFromParseError(allocator, parse_error, &tree, file_path);
725 const loc = tree.tokenLocation(0, parse_error.loc());753 defer allocator.destroy(msg);
726 try stderr.print("{}:{}:{}: error: ", file_path, loc.line + 1, loc.column + 1);754
727 try tree.renderError(parse_error, stderr);755 try errmsg.printToFile(&stderr_file, msg, color);
728 try stderr.print("\n{}\n", source_code[loc.line_start..loc.line_end]);
729 {
730 var i: usize = 0;
731 while (i < loc.column) : (i += 1) {
732 try stderr.write(" ");
733 }
734 }
735 {
736 const caret_count = token.end - token.start;
737 var i: usize = 0;
738 while (i < caret_count) : (i += 1) {
739 try stderr.write("~");
740 }
741 }
742 try stderr.write("\n");
743 }756 }
744 if (tree.errors.len != 0) {757 if (tree.errors.len != 0) {
758 fmt_errors = true;
745 continue;759 continue;
746 }760 }
747761
748 try stderr.print("{}\n", file_path);
749
750 const baf = try io.BufferedAtomicFile.create(allocator, file_path);762 const baf = try io.BufferedAtomicFile.create(allocator, file_path);
751 defer baf.destroy();763 defer baf.destroy();
752764
753 try std.zig.render(allocator, baf.stream(), &tree);765 const anything_changed = try std.zig.render(allocator, baf.stream(), &tree);
754 try baf.finish();766 if (anything_changed) {
767 try stderr.print("{}\n", file_path);
768 try baf.finish();
769 }
770 }
771
772 if (fmt_errors) {
773 os.exit(1);
755 }774 }
756}775}
757776
758// cmd:targets /////////////////////////////////////////////////////////////////////////////////////777// cmd:targets /////////////////////////////////////////////////////////////////////////////////////
759778
760fn cmdTargets(allocator: &Allocator, args: []const []const u8) !void {779fn cmdTargets(allocator: *Allocator, args: []const []const u8) !void {
761 try stdout.write("Architectures:\n");780 try stdout.write("Architectures:\n");
762 {781 {
763 comptime var i: usize = 0;782 comptime var i: usize = 0;
...@@ -799,7 +818,7 @@ fn cmdTargets(allocator: &Allocator, args: []const []const u8) !void {...@@ -799,7 +818,7 @@ fn cmdTargets(allocator: &Allocator, args: []const []const u8) !void {
799818
800// cmd:version /////////////////////////////////////////////////////////////////////////////////////819// cmd:version /////////////////////////////////////////////////////////////////////////////////////
801820
802fn cmdVersion(allocator: &Allocator, args: []const []const u8) !void {821fn cmdVersion(allocator: *Allocator, args: []const []const u8) !void {
803 try stdout.print("{}\n", std.cstr.toSliceConst(c.ZIG_VERSION_STRING));822 try stdout.print("{}\n", std.cstr.toSliceConst(c.ZIG_VERSION_STRING));
804}823}
805824
...@@ -816,7 +835,7 @@ const usage_test =...@@ -816,7 +835,7 @@ const usage_test =
816835
817const args_test_spec = []Flag{Flag.Bool("--help")};836const args_test_spec = []Flag{Flag.Bool("--help")};
818837
819fn cmdTest(allocator: &Allocator, args: []const []const u8) !void {838fn cmdTest(allocator: *Allocator, args: []const []const u8) !void {
820 var flags = try Args.parse(allocator, args_build_spec, args);839 var flags = try Args.parse(allocator, args_build_spec, args);
821 defer flags.deinit();840 defer flags.deinit();
822841
...@@ -851,14 +870,14 @@ const usage_run =...@@ -851,14 +870,14 @@ const usage_run =
851870
852const args_run_spec = []Flag{Flag.Bool("--help")};871const args_run_spec = []Flag{Flag.Bool("--help")};
853872
854fn cmdRun(allocator: &Allocator, args: []const []const u8) !void {873fn cmdRun(allocator: *Allocator, args: []const []const u8) !void {
855 var compile_args = args;874 var compile_args = args;
856 var runtime_args: []const []const u8 = []const []const u8{};875 var runtime_args: []const []const u8 = []const []const u8{};
857876
858 for (args) |argv, i| {877 for (args) |argv, i| {
859 if (mem.eql(u8, argv, "--")) {878 if (mem.eql(u8, argv, "--")) {
860 compile_args = args[0..i];879 compile_args = args[0..i];
861 runtime_args = args[i + 1..];880 runtime_args = args[i + 1 ..];
862 break;881 break;
863 }882 }
864 }883 }
...@@ -901,7 +920,7 @@ const args_translate_c_spec = []Flag{...@@ -901,7 +920,7 @@ const args_translate_c_spec = []Flag{
901 Flag.Arg1("--output"),920 Flag.Arg1("--output"),
902};921};
903922
904fn cmdTranslateC(allocator: &Allocator, args: []const []const u8) !void {923fn cmdTranslateC(allocator: *Allocator, args: []const []const u8) !void {
905 var flags = try Args.parse(allocator, args_translate_c_spec, args);924 var flags = try Args.parse(allocator, args_translate_c_spec, args);
906 defer flags.deinit();925 defer flags.deinit();
907926
...@@ -947,7 +966,7 @@ fn cmdTranslateC(allocator: &Allocator, args: []const []const u8) !void {...@@ -947,7 +966,7 @@ fn cmdTranslateC(allocator: &Allocator, args: []const []const u8) !void {
947966
948// cmd:help ////////////////////////////////////////////////////////////////////////////////////////967// cmd:help ////////////////////////////////////////////////////////////////////////////////////////
949968
950fn cmdHelp(allocator: &Allocator, args: []const []const u8) !void {969fn cmdHelp(allocator: *Allocator, args: []const []const u8) !void {
951 try stderr.write(usage);970 try stderr.write(usage);
952}971}
953972
...@@ -970,7 +989,7 @@ const info_zen =...@@ -970,7 +989,7 @@ const info_zen =
970 \\989 \\
971;990;
972991
973fn cmdZen(allocator: &Allocator, args: []const []const u8) !void {992fn cmdZen(allocator: *Allocator, args: []const []const u8) !void {
974 try stdout.write(info_zen);993 try stdout.write(info_zen);
975}994}
976995
...@@ -985,7 +1004,7 @@ const usage_internal =...@@ -985,7 +1004,7 @@ const usage_internal =
985 \\1004 \\
986;1005;
9871006
988fn cmdInternal(allocator: &Allocator, args: []const []const u8) !void {1007fn cmdInternal(allocator: *Allocator, args: []const []const u8) !void {
989 if (args.len == 0) {1008 if (args.len == 0) {
990 try stderr.write(usage_internal);1009 try stderr.write(usage_internal);
991 os.exit(1);1010 os.exit(1);
...@@ -1007,7 +1026,7 @@ fn cmdInternal(allocator: &Allocator, args: []const []const u8) !void {...@@ -1007,7 +1026,7 @@ fn cmdInternal(allocator: &Allocator, args: []const []const u8) !void {
1007 try stderr.write(usage_internal);1026 try stderr.write(usage_internal);
1008}1027}
10091028
1010fn cmdInternalBuildInfo(allocator: &Allocator, args: []const []const u8) !void {1029fn cmdInternalBuildInfo(allocator: *Allocator, args: []const []const u8) !void {
1011 try stdout.print(1030 try stdout.print(
1012 \\ZIG_CMAKE_BINARY_DIR {}1031 \\ZIG_CMAKE_BINARY_DIR {}
1013 \\ZIG_CXX_COMPILER {}1032 \\ZIG_CXX_COMPILER {}
src-self-hosted/module.zig+19-24
...@@ -10,9 +10,10 @@ const Target = @import("target.zig").Target;...@@ -10,9 +10,10 @@ const Target = @import("target.zig").Target;
10const warn = std.debug.warn;10const warn = std.debug.warn;
11const Token = std.zig.Token;11const Token = std.zig.Token;
12const ArrayList = std.ArrayList;12const ArrayList = std.ArrayList;
13const errmsg = @import("errmsg.zig");
1314
14pub const Module = struct {15pub const Module = struct {
15 allocator: &mem.Allocator,16 allocator: *mem.Allocator,
16 name: Buffer,17 name: Buffer,
17 root_src_path: ?[]const u8,18 root_src_path: ?[]const u8,
18 module: llvm.ModuleRef,19 module: llvm.ModuleRef,
...@@ -52,10 +53,10 @@ pub const Module = struct {...@@ -52,10 +53,10 @@ pub const Module = struct {
52 windows_subsystem_windows: bool,53 windows_subsystem_windows: bool,
53 windows_subsystem_console: bool,54 windows_subsystem_console: bool,
5455
55 link_libs_list: ArrayList(&LinkLib),56 link_libs_list: ArrayList(*LinkLib),
56 libc_link_lib: ?&LinkLib,57 libc_link_lib: ?*LinkLib,
5758
58 err_color: ErrColor,59 err_color: errmsg.Color,
5960
60 verbose_tokenize: bool,61 verbose_tokenize: bool,
61 verbose_ast_tree: bool,62 verbose_ast_tree: bool,
...@@ -87,12 +88,6 @@ pub const Module = struct {...@@ -87,12 +88,6 @@ pub const Module = struct {
87 Obj,88 Obj,
88 };89 };
8990
90 pub const ErrColor = enum {
91 Auto,
92 Off,
93 On,
94 };
95
96 pub const LinkLib = struct {91 pub const LinkLib = struct {
97 name: []const u8,92 name: []const u8,
98 path: ?[]const u8,93 path: ?[]const u8,
...@@ -111,19 +106,19 @@ pub const Module = struct {...@@ -111,19 +106,19 @@ pub const Module = struct {
111 pub const CliPkg = struct {106 pub const CliPkg = struct {
112 name: []const u8,107 name: []const u8,
113 path: []const u8,108 path: []const u8,
114 children: ArrayList(&CliPkg),109 children: ArrayList(*CliPkg),
115 parent: ?&CliPkg,110 parent: ?*CliPkg,
116111
117 pub fn init(allocator: &mem.Allocator, name: []const u8, path: []const u8, parent: ?&CliPkg) !&CliPkg {112 pub fn init(allocator: *mem.Allocator, name: []const u8, path: []const u8, parent: ?*CliPkg) !*CliPkg {
118 var pkg = try allocator.create(CliPkg);113 var pkg = try allocator.create(CliPkg);
119 pkg.name = name;114 pkg.name = name;
120 pkg.path = path;115 pkg.path = path;
121 pkg.children = ArrayList(&CliPkg).init(allocator);116 pkg.children = ArrayList(*CliPkg).init(allocator);
122 pkg.parent = parent;117 pkg.parent = parent;
123 return pkg;118 return pkg;
124 }119 }
125120
126 pub fn deinit(self: &CliPkg) void {121 pub fn deinit(self: *CliPkg) void {
127 for (self.children.toSliceConst()) |child| {122 for (self.children.toSliceConst()) |child| {
128 child.deinit();123 child.deinit();
129 }124 }
...@@ -131,7 +126,7 @@ pub const Module = struct {...@@ -131,7 +126,7 @@ pub const Module = struct {
131 }126 }
132 };127 };
133128
134 pub fn create(allocator: &mem.Allocator, name: []const u8, root_src_path: ?[]const u8, target: &const Target, kind: Kind, build_mode: builtin.Mode, zig_lib_dir: []const u8, cache_dir: []const u8) !&Module {129 pub fn create(allocator: *mem.Allocator, name: []const u8, root_src_path: ?[]const u8, target: *const Target, kind: Kind, build_mode: builtin.Mode, zig_lib_dir: []const u8, cache_dir: []const u8) !*Module {
135 var name_buffer = try Buffer.init(allocator, name);130 var name_buffer = try Buffer.init(allocator, name);
136 errdefer name_buffer.deinit();131 errdefer name_buffer.deinit();
137132
...@@ -193,9 +188,9 @@ pub const Module = struct {...@@ -193,9 +188,9 @@ pub const Module = struct {
193 .link_objects = [][]const u8{},188 .link_objects = [][]const u8{},
194 .windows_subsystem_windows = false,189 .windows_subsystem_windows = false,
195 .windows_subsystem_console = false,190 .windows_subsystem_console = false,
196 .link_libs_list = ArrayList(&LinkLib).init(allocator),191 .link_libs_list = ArrayList(*LinkLib).init(allocator),
197 .libc_link_lib = null,192 .libc_link_lib = null,
198 .err_color = ErrColor.Auto,193 .err_color = errmsg.Color.Auto,
199 .darwin_frameworks = [][]const u8{},194 .darwin_frameworks = [][]const u8{},
200 .darwin_version_min = DarwinVersionMin.None,195 .darwin_version_min = DarwinVersionMin.None,
201 .test_filters = [][]const u8{},196 .test_filters = [][]const u8{},
...@@ -205,11 +200,11 @@ pub const Module = struct {...@@ -205,11 +200,11 @@ pub const Module = struct {
205 return module_ptr;200 return module_ptr;
206 }201 }
207202
208 fn dump(self: &Module) void {203 fn dump(self: *Module) void {
209 c.LLVMDumpModule(self.module);204 c.LLVMDumpModule(self.module);
210 }205 }
211206
212 pub fn destroy(self: &Module) void {207 pub fn destroy(self: *Module) void {
213 c.LLVMDisposeBuilder(self.builder);208 c.LLVMDisposeBuilder(self.builder);
214 c.LLVMDisposeModule(self.module);209 c.LLVMDisposeModule(self.module);
215 c.LLVMContextDispose(self.context);210 c.LLVMContextDispose(self.context);
...@@ -218,7 +213,7 @@ pub const Module = struct {...@@ -218,7 +213,7 @@ pub const Module = struct {
218 self.allocator.destroy(self);213 self.allocator.destroy(self);
219 }214 }
220215
221 pub fn build(self: &Module) !void {216 pub fn build(self: *Module) !void {
222 if (self.llvm_argv.len != 0) {217 if (self.llvm_argv.len != 0) {
223 var c_compatible_args = try std.cstr.NullTerminated2DArray.fromSlices(self.allocator, [][]const []const u8{218 var c_compatible_args = try std.cstr.NullTerminated2DArray.fromSlices(self.allocator, [][]const []const u8{
224 [][]const u8{"zig (LLVM option parsing)"},219 [][]const u8{"zig (LLVM option parsing)"},
...@@ -255,7 +250,7 @@ pub const Module = struct {...@@ -255,7 +250,7 @@ pub const Module = struct {
255 const out_stream = &stderr_file_out_stream.stream;250 const out_stream = &stderr_file_out_stream.stream;
256251
257 warn("====fmt:====\n");252 warn("====fmt:====\n");
258 try std.zig.render(self.allocator, out_stream, &tree);253 _ = try std.zig.render(self.allocator, out_stream, &tree);
259254
260 warn("====ir:====\n");255 warn("====ir:====\n");
261 warn("TODO\n\n");256 warn("TODO\n\n");
...@@ -264,12 +259,12 @@ pub const Module = struct {...@@ -264,12 +259,12 @@ pub const Module = struct {
264 self.dump();259 self.dump();
265 }260 }
266261
267 pub fn link(self: &Module, out_file: ?[]const u8) !void {262 pub fn link(self: *Module, out_file: ?[]const u8) !void {
268 warn("TODO link");263 warn("TODO link");
269 return error.Todo;264 return error.Todo;
270 }265 }
271266
272 pub fn addLinkLib(self: &Module, name: []const u8, provided_explicitly: bool) !&LinkLib {267 pub fn addLinkLib(self: *Module, name: []const u8, provided_explicitly: bool) !*LinkLib {
273 const is_libc = mem.eql(u8, name, "c");268 const is_libc = mem.eql(u8, name, "c");
274269
275 if (is_libc) {270 if (is_libc) {
src-self-hosted/scope.zig+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1pub const Scope = struct {1pub const Scope = struct {
2 id: Id,2 id: Id,
3 parent: &Scope,3 parent: *Scope,
44
5 pub const Id = enum {5 pub const Id = enum {
6 Decls,6 Decls,
src-self-hosted/target.zig+5-5
...@@ -11,7 +11,7 @@ pub const Target = union(enum) {...@@ -11,7 +11,7 @@ pub const Target = union(enum) {
11 Native,11 Native,
12 Cross: CrossTarget,12 Cross: CrossTarget,
1313
14 pub fn oFileExt(self: &const Target) []const u8 {14 pub fn oFileExt(self: *const Target) []const u8 {
15 const environ = switch (self.*) {15 const environ = switch (self.*) {
16 Target.Native => builtin.environ,16 Target.Native => builtin.environ,
17 Target.Cross => |t| t.environ,17 Target.Cross => |t| t.environ,
...@@ -22,28 +22,28 @@ pub const Target = union(enum) {...@@ -22,28 +22,28 @@ pub const Target = union(enum) {
22 };22 };
23 }23 }
2424
25 pub fn exeFileExt(self: &const Target) []const u8 {25 pub fn exeFileExt(self: *const Target) []const u8 {
26 return switch (self.getOs()) {26 return switch (self.getOs()) {
27 builtin.Os.windows => ".exe",27 builtin.Os.windows => ".exe",
28 else => "",28 else => "",
29 };29 };
30 }30 }
3131
32 pub fn getOs(self: &const Target) builtin.Os {32 pub fn getOs(self: *const Target) builtin.Os {
33 return switch (self.*) {33 return switch (self.*) {
34 Target.Native => builtin.os,34 Target.Native => builtin.os,
35 Target.Cross => |t| t.os,35 Target.Cross => |t| t.os,
36 };36 };
37 }37 }
3838
39 pub fn isDarwin(self: &const Target) bool {39 pub fn isDarwin(self: *const Target) bool {
40 return switch (self.getOs()) {40 return switch (self.getOs()) {
41 builtin.Os.ios, builtin.Os.macosx => true,41 builtin.Os.ios, builtin.Os.macosx => true,
42 else => false,42 else => false,
43 };43 };
44 }44 }
4545
46 pub fn isWindows(self: &const Target) bool {46 pub fn isWindows(self: *const Target) bool {
47 return switch (self.getOs()) {47 return switch (self.getOs()) {
48 builtin.Os.windows => true,48 builtin.Os.windows => true,
49 else => false,49 else => false,
src/all_types.hpp+26-17
...@@ -374,7 +374,7 @@ enum NodeType {...@@ -374,7 +374,7 @@ enum NodeType {
374 NodeTypeCharLiteral,374 NodeTypeCharLiteral,
375 NodeTypeSymbol,375 NodeTypeSymbol,
376 NodeTypePrefixOpExpr,376 NodeTypePrefixOpExpr,
377 NodeTypeAddrOfExpr,377 NodeTypePointerType,
378 NodeTypeFnCallExpr,378 NodeTypeFnCallExpr,
379 NodeTypeArrayAccessExpr,379 NodeTypeArrayAccessExpr,
380 NodeTypeSliceExpr,380 NodeTypeSliceExpr,
...@@ -616,6 +616,7 @@ enum PrefixOp {...@@ -616,6 +616,7 @@ enum PrefixOp {
616 PrefixOpNegationWrap,616 PrefixOpNegationWrap,
617 PrefixOpMaybe,617 PrefixOpMaybe,
618 PrefixOpUnwrapMaybe,618 PrefixOpUnwrapMaybe,
619 PrefixOpAddrOf,
619};620};
620621
621struct AstNodePrefixOpExpr {622struct AstNodePrefixOpExpr {
...@@ -623,7 +624,8 @@ struct AstNodePrefixOpExpr {...@@ -623,7 +624,8 @@ struct AstNodePrefixOpExpr {
623 AstNode *primary_expr;624 AstNode *primary_expr;
624};625};
625626
626struct AstNodeAddrOfExpr {627struct AstNodePointerType {
628 Token *star_token;
627 AstNode *align_expr;629 AstNode *align_expr;
628 BigInt *bit_offset_start;630 BigInt *bit_offset_start;
629 BigInt *bit_offset_end;631 BigInt *bit_offset_end;
...@@ -899,7 +901,7 @@ struct AstNode {...@@ -899,7 +901,7 @@ struct AstNode {
899 AstNodeBinOpExpr bin_op_expr;901 AstNodeBinOpExpr bin_op_expr;
900 AstNodeCatchExpr unwrap_err_expr;902 AstNodeCatchExpr unwrap_err_expr;
901 AstNodePrefixOpExpr prefix_op_expr;903 AstNodePrefixOpExpr prefix_op_expr;
902 AstNodeAddrOfExpr addr_of_expr;904 AstNodePointerType pointer_type;
903 AstNodeFnCallExpr fn_call_expr;905 AstNodeFnCallExpr fn_call_expr;
904 AstNodeArrayAccessExpr array_access_expr;906 AstNodeArrayAccessExpr array_access_expr;
905 AstNodeSliceExpr slice_expr;907 AstNodeSliceExpr slice_expr;
...@@ -972,8 +974,14 @@ struct FnTypeId {...@@ -972,8 +974,14 @@ struct FnTypeId {
972uint32_t fn_type_id_hash(FnTypeId*);974uint32_t fn_type_id_hash(FnTypeId*);
973bool fn_type_id_eql(FnTypeId *a, FnTypeId *b);975bool fn_type_id_eql(FnTypeId *a, FnTypeId *b);
974976
977enum PtrLen {
978 PtrLenUnknown,
979 PtrLenSingle,
980};
981
975struct TypeTableEntryPointer {982struct TypeTableEntryPointer {
976 TypeTableEntry *child_type;983 TypeTableEntry *child_type;
984 PtrLen ptr_len;
977 bool is_const;985 bool is_const;
978 bool is_volatile;986 bool is_volatile;
979 uint32_t alignment;987 uint32_t alignment;
...@@ -1395,6 +1403,7 @@ struct TypeId {...@@ -1395,6 +1403,7 @@ struct TypeId {
1395 union {1403 union {
1396 struct {1404 struct {
1397 TypeTableEntry *child_type;1405 TypeTableEntry *child_type;
1406 PtrLen ptr_len;
1398 bool is_const;1407 bool is_const;
1399 bool is_volatile;1408 bool is_volatile;
1400 uint32_t alignment;1409 uint32_t alignment;
...@@ -2051,7 +2060,7 @@ enum IrInstructionId {...@@ -2051,7 +2060,7 @@ enum IrInstructionId {
2051 IrInstructionIdTypeInfo,2060 IrInstructionIdTypeInfo,
2052 IrInstructionIdTypeId,2061 IrInstructionIdTypeId,
2053 IrInstructionIdSetEvalBranchQuota,2062 IrInstructionIdSetEvalBranchQuota,
2054 IrInstructionIdPtrTypeOf,2063 IrInstructionIdPtrType,
2055 IrInstructionIdAlignCast,2064 IrInstructionIdAlignCast,
2056 IrInstructionIdOpaqueType,2065 IrInstructionIdOpaqueType,
2057 IrInstructionIdSetAlignStack,2066 IrInstructionIdSetAlignStack,
...@@ -2264,6 +2273,7 @@ struct IrInstructionElemPtr {...@@ -2264,6 +2273,7 @@ struct IrInstructionElemPtr {
22642273
2265 IrInstruction *array_ptr;2274 IrInstruction *array_ptr;
2266 IrInstruction *elem_index;2275 IrInstruction *elem_index;
2276 PtrLen ptr_len;
2267 bool is_const;2277 bool is_const;
2268 bool safety_check_on;2278 bool safety_check_on;
2269};2279};
...@@ -2272,8 +2282,6 @@ struct IrInstructionVarPtr {...@@ -2272,8 +2282,6 @@ struct IrInstructionVarPtr {
2272 IrInstruction base;2282 IrInstruction base;
22732283
2274 VariableTableEntry *var;2284 VariableTableEntry *var;
2275 bool is_const;
2276 bool is_volatile;
2277};2285};
22782286
2279struct IrInstructionCall {2287struct IrInstructionCall {
...@@ -2410,6 +2418,18 @@ struct IrInstructionArrayType {...@@ -2410,6 +2418,18 @@ struct IrInstructionArrayType {
2410 IrInstruction *child_type;2418 IrInstruction *child_type;
2411};2419};
24122420
2421struct IrInstructionPtrType {
2422 IrInstruction base;
2423
2424 IrInstruction *align_value;
2425 IrInstruction *child_type;
2426 uint32_t bit_offset_start;
2427 uint32_t bit_offset_end;
2428 PtrLen ptr_len;
2429 bool is_const;
2430 bool is_volatile;
2431};
2432
2413struct IrInstructionPromiseType {2433struct IrInstructionPromiseType {
2414 IrInstruction base;2434 IrInstruction base;
24152435
...@@ -2889,17 +2909,6 @@ struct IrInstructionSetEvalBranchQuota {...@@ -2889,17 +2909,6 @@ struct IrInstructionSetEvalBranchQuota {
2889 IrInstruction *new_quota;2909 IrInstruction *new_quota;
2890};2910};
28912911
2892struct IrInstructionPtrTypeOf {
2893 IrInstruction base;
2894
2895 IrInstruction *align_value;
2896 IrInstruction *child_type;
2897 uint32_t bit_offset_start;
2898 uint32_t bit_offset_end;
2899 bool is_const;
2900 bool is_volatile;
2901};
2902
2903struct IrInstructionAlignCast {2912struct IrInstructionAlignCast {
2904 IrInstruction base;2913 IrInstruction base;
29052914
src/analyze.cpp+41-21
...@@ -25,6 +25,7 @@ static void resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type);...@@ -25,6 +25,7 @@ static void resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type);
25static void resolve_struct_zero_bits(CodeGen *g, TypeTableEntry *struct_type);25static void resolve_struct_zero_bits(CodeGen *g, TypeTableEntry *struct_type);
26static void resolve_enum_zero_bits(CodeGen *g, TypeTableEntry *enum_type);26static void resolve_enum_zero_bits(CodeGen *g, TypeTableEntry *enum_type);
27static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type);27static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type);
28static void analyze_fn_body(CodeGen *g, FnTableEntry *fn_table_entry);
2829
29ErrorMsg *add_node_error(CodeGen *g, AstNode *node, Buf *msg) {30ErrorMsg *add_node_error(CodeGen *g, AstNode *node, Buf *msg) {
30 if (node->owner->c_import_node != nullptr) {31 if (node->owner->c_import_node != nullptr) {
...@@ -380,14 +381,14 @@ TypeTableEntry *get_promise_type(CodeGen *g, TypeTableEntry *result_type) {...@@ -380,14 +381,14 @@ TypeTableEntry *get_promise_type(CodeGen *g, TypeTableEntry *result_type) {
380}381}
381382
382TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type, bool is_const,383TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type, bool is_const,
383 bool is_volatile, uint32_t byte_alignment, uint32_t bit_offset, uint32_t unaligned_bit_count)384 bool is_volatile, PtrLen ptr_len, uint32_t byte_alignment, uint32_t bit_offset, uint32_t unaligned_bit_count)
384{385{
385 assert(!type_is_invalid(child_type));386 assert(!type_is_invalid(child_type));
386387
387 TypeId type_id = {};388 TypeId type_id = {};
388 TypeTableEntry **parent_pointer = nullptr;389 TypeTableEntry **parent_pointer = nullptr;
389 uint32_t abi_alignment = get_abi_alignment(g, child_type);390 uint32_t abi_alignment = get_abi_alignment(g, child_type);
390 if (unaligned_bit_count != 0 || is_volatile || byte_alignment != abi_alignment) {391 if (unaligned_bit_count != 0 || is_volatile || byte_alignment != abi_alignment || ptr_len != PtrLenSingle) {
391 type_id.id = TypeTableEntryIdPointer;392 type_id.id = TypeTableEntryIdPointer;
392 type_id.data.pointer.child_type = child_type;393 type_id.data.pointer.child_type = child_type;
393 type_id.data.pointer.is_const = is_const;394 type_id.data.pointer.is_const = is_const;
...@@ -395,6 +396,7 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type...@@ -395,6 +396,7 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type
395 type_id.data.pointer.alignment = byte_alignment;396 type_id.data.pointer.alignment = byte_alignment;
396 type_id.data.pointer.bit_offset = bit_offset;397 type_id.data.pointer.bit_offset = bit_offset;
397 type_id.data.pointer.unaligned_bit_count = unaligned_bit_count;398 type_id.data.pointer.unaligned_bit_count = unaligned_bit_count;
399 type_id.data.pointer.ptr_len = ptr_len;
398400
399 auto existing_entry = g->type_table.maybe_get(type_id);401 auto existing_entry = g->type_table.maybe_get(type_id);
400 if (existing_entry)402 if (existing_entry)
...@@ -413,16 +415,17 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type...@@ -413,16 +415,17 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type
413 TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdPointer);415 TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdPointer);
414 entry->is_copyable = true;416 entry->is_copyable = true;
415417
418 const char *star_str = ptr_len == PtrLenSingle ? "*" : "[*]";
416 const char *const_str = is_const ? "const " : "";419 const char *const_str = is_const ? "const " : "";
417 const char *volatile_str = is_volatile ? "volatile " : "";420 const char *volatile_str = is_volatile ? "volatile " : "";
418 buf_resize(&entry->name, 0);421 buf_resize(&entry->name, 0);
419 if (unaligned_bit_count == 0 && byte_alignment == abi_alignment) {422 if (unaligned_bit_count == 0 && byte_alignment == abi_alignment) {
420 buf_appendf(&entry->name, "&%s%s%s", const_str, volatile_str, buf_ptr(&child_type->name));423 buf_appendf(&entry->name, "%s%s%s%s", star_str, const_str, volatile_str, buf_ptr(&child_type->name));
421 } else if (unaligned_bit_count == 0) {424 } else if (unaligned_bit_count == 0) {
422 buf_appendf(&entry->name, "&align(%" PRIu32 ") %s%s%s", byte_alignment,425 buf_appendf(&entry->name, "%salign(%" PRIu32 ") %s%s%s", star_str, byte_alignment,
423 const_str, volatile_str, buf_ptr(&child_type->name));426 const_str, volatile_str, buf_ptr(&child_type->name));
424 } else {427 } else {
425 buf_appendf(&entry->name, "&align(%" PRIu32 ":%" PRIu32 ":%" PRIu32 ") %s%s%s", byte_alignment,428 buf_appendf(&entry->name, "%salign(%" PRIu32 ":%" PRIu32 ":%" PRIu32 ") %s%s%s", star_str, byte_alignment,
426 bit_offset, bit_offset + unaligned_bit_count, const_str, volatile_str, buf_ptr(&child_type->name));429 bit_offset, bit_offset + unaligned_bit_count, const_str, volatile_str, buf_ptr(&child_type->name));
427 }430 }
428431
...@@ -432,7 +435,9 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type...@@ -432,7 +435,9 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type
432435
433 if (!entry->zero_bits) {436 if (!entry->zero_bits) {
434 assert(byte_alignment > 0);437 assert(byte_alignment > 0);
435 if (is_const || is_volatile || unaligned_bit_count != 0 || byte_alignment != abi_alignment) {438 if (is_const || is_volatile || unaligned_bit_count != 0 || byte_alignment != abi_alignment ||
439 ptr_len != PtrLenSingle)
440 {
436 TypeTableEntry *peer_type = get_pointer_to_type(g, child_type, false);441 TypeTableEntry *peer_type = get_pointer_to_type(g, child_type, false);
437 entry->type_ref = peer_type->type_ref;442 entry->type_ref = peer_type->type_ref;
438 entry->di_type = peer_type->di_type;443 entry->di_type = peer_type->di_type;
...@@ -450,6 +455,7 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type...@@ -450,6 +455,7 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type
450 entry->di_type = g->builtin_types.entry_void->di_type;455 entry->di_type = g->builtin_types.entry_void->di_type;
451 }456 }
452457
458 entry->data.pointer.ptr_len = ptr_len;
453 entry->data.pointer.child_type = child_type;459 entry->data.pointer.child_type = child_type;
454 entry->data.pointer.is_const = is_const;460 entry->data.pointer.is_const = is_const;
455 entry->data.pointer.is_volatile = is_volatile;461 entry->data.pointer.is_volatile = is_volatile;
...@@ -466,7 +472,8 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type...@@ -466,7 +472,8 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type
466}472}
467473
468TypeTableEntry *get_pointer_to_type(CodeGen *g, TypeTableEntry *child_type, bool is_const) {474TypeTableEntry *get_pointer_to_type(CodeGen *g, TypeTableEntry *child_type, bool is_const) {
469 return get_pointer_to_type_extra(g, child_type, is_const, false, get_abi_alignment(g, child_type), 0, 0);475 return get_pointer_to_type_extra(g, child_type, is_const, false, PtrLenSingle,
476 get_abi_alignment(g, child_type), 0, 0);
470}477}
471478
472TypeTableEntry *get_promise_frame_type(CodeGen *g, TypeTableEntry *return_type) {479TypeTableEntry *get_promise_frame_type(CodeGen *g, TypeTableEntry *return_type) {
...@@ -756,6 +763,7 @@ static void slice_type_common_init(CodeGen *g, TypeTableEntry *pointer_type, Typ...@@ -756,6 +763,7 @@ static void slice_type_common_init(CodeGen *g, TypeTableEntry *pointer_type, Typ
756763
757TypeTableEntry *get_slice_type(CodeGen *g, TypeTableEntry *ptr_type) {764TypeTableEntry *get_slice_type(CodeGen *g, TypeTableEntry *ptr_type) {
758 assert(ptr_type->id == TypeTableEntryIdPointer);765 assert(ptr_type->id == TypeTableEntryIdPointer);
766 assert(ptr_type->data.pointer.ptr_len == PtrLenUnknown);
759767
760 TypeTableEntry **parent_pointer = &ptr_type->data.pointer.slice_parent;768 TypeTableEntry **parent_pointer = &ptr_type->data.pointer.slice_parent;
761 if (*parent_pointer) {769 if (*parent_pointer) {
...@@ -767,14 +775,16 @@ TypeTableEntry *get_slice_type(CodeGen *g, TypeTableEntry *ptr_type) {...@@ -767,14 +775,16 @@ TypeTableEntry *get_slice_type(CodeGen *g, TypeTableEntry *ptr_type) {
767775
768 // replace the & with [] to go from a ptr type name to a slice type name776 // replace the & with [] to go from a ptr type name to a slice type name
769 buf_resize(&entry->name, 0);777 buf_resize(&entry->name, 0);
770 buf_appendf(&entry->name, "[]%s", buf_ptr(&ptr_type->name) + 1);778 size_t name_offset = (ptr_type->data.pointer.ptr_len == PtrLenSingle) ? 1 : 3;
779 buf_appendf(&entry->name, "[]%s", buf_ptr(&ptr_type->name) + name_offset);
771780
772 TypeTableEntry *child_type = ptr_type->data.pointer.child_type;781 TypeTableEntry *child_type = ptr_type->data.pointer.child_type;
773 uint32_t abi_alignment;782 uint32_t abi_alignment = get_abi_alignment(g, child_type);
774 if (ptr_type->data.pointer.is_const || ptr_type->data.pointer.is_volatile ||783 if (ptr_type->data.pointer.is_const || ptr_type->data.pointer.is_volatile ||
775 ptr_type->data.pointer.alignment != (abi_alignment = get_abi_alignment(g, child_type)))784 ptr_type->data.pointer.alignment != abi_alignment)
776 {785 {
777 TypeTableEntry *peer_ptr_type = get_pointer_to_type(g, child_type, false);786 TypeTableEntry *peer_ptr_type = get_pointer_to_type_extra(g, child_type, false, false,
787 PtrLenUnknown, abi_alignment, 0, 0);
778 TypeTableEntry *peer_slice_type = get_slice_type(g, peer_ptr_type);788 TypeTableEntry *peer_slice_type = get_slice_type(g, peer_ptr_type);
779789
780 slice_type_common_init(g, ptr_type, entry);790 slice_type_common_init(g, ptr_type, entry);
...@@ -798,9 +808,11 @@ TypeTableEntry *get_slice_type(CodeGen *g, TypeTableEntry *ptr_type) {...@@ -798,9 +808,11 @@ TypeTableEntry *get_slice_type(CodeGen *g, TypeTableEntry *ptr_type) {
798 if (child_ptr_type->data.pointer.is_const || child_ptr_type->data.pointer.is_volatile ||808 if (child_ptr_type->data.pointer.is_const || child_ptr_type->data.pointer.is_volatile ||
799 child_ptr_type->data.pointer.alignment != get_abi_alignment(g, grand_child_type))809 child_ptr_type->data.pointer.alignment != get_abi_alignment(g, grand_child_type))
800 {810 {
801 TypeTableEntry *bland_child_ptr_type = get_pointer_to_type(g, grand_child_type, false);811 TypeTableEntry *bland_child_ptr_type = get_pointer_to_type_extra(g, grand_child_type, false, false,
812 PtrLenUnknown, get_abi_alignment(g, grand_child_type), 0, 0);
802 TypeTableEntry *bland_child_slice = get_slice_type(g, bland_child_ptr_type);813 TypeTableEntry *bland_child_slice = get_slice_type(g, bland_child_ptr_type);
803 TypeTableEntry *peer_ptr_type = get_pointer_to_type(g, bland_child_slice, false);814 TypeTableEntry *peer_ptr_type = get_pointer_to_type_extra(g, bland_child_slice, false, false,
815 PtrLenUnknown, get_abi_alignment(g, bland_child_slice), 0, 0);
804 TypeTableEntry *peer_slice_type = get_slice_type(g, peer_ptr_type);816 TypeTableEntry *peer_slice_type = get_slice_type(g, peer_ptr_type);
805817
806 entry->type_ref = peer_slice_type->type_ref;818 entry->type_ref = peer_slice_type->type_ref;
...@@ -1283,7 +1295,8 @@ static bool analyze_const_align(CodeGen *g, Scope *scope, AstNode *node, uint32_...@@ -1283,7 +1295,8 @@ static bool analyze_const_align(CodeGen *g, Scope *scope, AstNode *node, uint32_
1283}1295}
12841296
1285static bool analyze_const_string(CodeGen *g, Scope *scope, AstNode *node, Buf **out_buffer) {1297static bool analyze_const_string(CodeGen *g, Scope *scope, AstNode *node, Buf **out_buffer) {
1286 TypeTableEntry *ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);1298 TypeTableEntry *ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
1299 PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0);
1287 TypeTableEntry *str_type = get_slice_type(g, ptr_type);1300 TypeTableEntry *str_type = get_slice_type(g, ptr_type);
1288 IrInstruction *instr = analyze_const_value(g, scope, node, str_type, nullptr);1301 IrInstruction *instr = analyze_const_value(g, scope, node, str_type, nullptr);
1289 if (type_is_invalid(instr->value.type))1302 if (type_is_invalid(instr->value.type))
...@@ -2953,7 +2966,8 @@ static void typecheck_panic_fn(CodeGen *g, FnTableEntry *panic_fn) {...@@ -2953,7 +2966,8 @@ static void typecheck_panic_fn(CodeGen *g, FnTableEntry *panic_fn) {
2953 if (fn_type_id->param_count != 2) {2966 if (fn_type_id->param_count != 2) {
2954 return wrong_panic_prototype(g, proto_node, fn_type);2967 return wrong_panic_prototype(g, proto_node, fn_type);
2955 }2968 }
2956 TypeTableEntry *const_u8_ptr = get_pointer_to_type(g, g->builtin_types.entry_u8, true);2969 TypeTableEntry *const_u8_ptr = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
2970 PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0);
2957 TypeTableEntry *const_u8_slice = get_slice_type(g, const_u8_ptr);2971 TypeTableEntry *const_u8_slice = get_slice_type(g, const_u8_ptr);
2958 if (fn_type_id->param_info[0].type != const_u8_slice) {2972 if (fn_type_id->param_info[0].type != const_u8_slice) {
2959 return wrong_panic_prototype(g, proto_node, fn_type);2973 return wrong_panic_prototype(g, proto_node, fn_type);
...@@ -3269,7 +3283,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) {...@@ -3269,7 +3283,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) {
3269 case NodeTypeThisLiteral:3283 case NodeTypeThisLiteral:
3270 case NodeTypeSymbol:3284 case NodeTypeSymbol:
3271 case NodeTypePrefixOpExpr:3285 case NodeTypePrefixOpExpr:
3272 case NodeTypeAddrOfExpr:3286 case NodeTypePointerType:
3273 case NodeTypeIfBoolExpr:3287 case NodeTypeIfBoolExpr:
3274 case NodeTypeWhileExpr:3288 case NodeTypeWhileExpr:
3275 case NodeTypeForExpr:3289 case NodeTypeForExpr:
...@@ -3880,7 +3894,7 @@ static void define_local_param_variables(CodeGen *g, FnTableEntry *fn_table_entr...@@ -3880,7 +3894,7 @@ static void define_local_param_variables(CodeGen *g, FnTableEntry *fn_table_entr
3880 }3894 }
3881}3895}
38823896
3883static bool analyze_resolve_inferred_error_set(CodeGen *g, TypeTableEntry *err_set_type, AstNode *source_node) {3897bool resolve_inferred_error_set(CodeGen *g, TypeTableEntry *err_set_type, AstNode *source_node) {
3884 FnTableEntry *infer_fn = err_set_type->data.error_set.infer_fn;3898 FnTableEntry *infer_fn = err_set_type->data.error_set.infer_fn;
3885 if (infer_fn != nullptr) {3899 if (infer_fn != nullptr) {
3886 if (infer_fn->anal_state == FnAnalStateInvalid) {3900 if (infer_fn->anal_state == FnAnalStateInvalid) {
...@@ -3932,7 +3946,7 @@ void analyze_fn_ir(CodeGen *g, FnTableEntry *fn_table_entry, AstNode *return_typ...@@ -3932,7 +3946,7 @@ void analyze_fn_ir(CodeGen *g, FnTableEntry *fn_table_entry, AstNode *return_typ
3932 }3946 }
39333947
3934 if (inferred_err_set_type->data.error_set.infer_fn != nullptr) {3948 if (inferred_err_set_type->data.error_set.infer_fn != nullptr) {
3935 if (!analyze_resolve_inferred_error_set(g, inferred_err_set_type, return_type_node)) {3949 if (!resolve_inferred_error_set(g, inferred_err_set_type, return_type_node)) {
3936 fn_table_entry->anal_state = FnAnalStateInvalid;3950 fn_table_entry->anal_state = FnAnalStateInvalid;
3937 return;3951 return;
3938 }3952 }
...@@ -3962,7 +3976,7 @@ void analyze_fn_ir(CodeGen *g, FnTableEntry *fn_table_entry, AstNode *return_typ...@@ -3962,7 +3976,7 @@ void analyze_fn_ir(CodeGen *g, FnTableEntry *fn_table_entry, AstNode *return_typ
3962 fn_table_entry->anal_state = FnAnalStateComplete;3976 fn_table_entry->anal_state = FnAnalStateComplete;
3963}3977}
39643978
3965void analyze_fn_body(CodeGen *g, FnTableEntry *fn_table_entry) {3979static void analyze_fn_body(CodeGen *g, FnTableEntry *fn_table_entry) {
3966 assert(fn_table_entry->anal_state != FnAnalStateProbing);3980 assert(fn_table_entry->anal_state != FnAnalStateProbing);
3967 if (fn_table_entry->anal_state != FnAnalStateReady)3981 if (fn_table_entry->anal_state != FnAnalStateReady)
3968 return;3982 return;
...@@ -4993,7 +5007,9 @@ void init_const_c_str_lit(CodeGen *g, ConstExprValue *const_val, Buf *str) {...@@ -4993,7 +5007,9 @@ void init_const_c_str_lit(CodeGen *g, ConstExprValue *const_val, Buf *str) {
49935007
4994 // then make the pointer point to it5008 // then make the pointer point to it
4995 const_val->special = ConstValSpecialStatic;5009 const_val->special = ConstValSpecialStatic;
4996 const_val->type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);5010 // TODO make this `[*]null u8` instead of `[*]u8`
5011 const_val->type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
5012 PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0);
4997 const_val->data.x_ptr.special = ConstPtrSpecialBaseArray;5013 const_val->data.x_ptr.special = ConstPtrSpecialBaseArray;
4998 const_val->data.x_ptr.data.base_array.array_val = array_val;5014 const_val->data.x_ptr.data.base_array.array_val = array_val;
4999 const_val->data.x_ptr.data.base_array.elem_index = 0;5015 const_val->data.x_ptr.data.base_array.elem_index = 0;
...@@ -5134,7 +5150,9 @@ void init_const_slice(CodeGen *g, ConstExprValue *const_val, ConstExprValue *arr...@@ -5134,7 +5150,9 @@ void init_const_slice(CodeGen *g, ConstExprValue *const_val, ConstExprValue *arr
5134{5150{
5135 assert(array_val->type->id == TypeTableEntryIdArray);5151 assert(array_val->type->id == TypeTableEntryIdArray);
51365152
5137 TypeTableEntry *ptr_type = get_pointer_to_type(g, array_val->type->data.array.child_type, is_const);5153 TypeTableEntry *ptr_type = get_pointer_to_type_extra(g, array_val->type->data.array.child_type,
5154 is_const, false, PtrLenUnknown, get_abi_alignment(g, array_val->type->data.array.child_type),
5155 0, 0);
51385156
5139 const_val->special = ConstValSpecialStatic;5157 const_val->special = ConstValSpecialStatic;
5140 const_val->type = get_slice_type(g, ptr_type);5158 const_val->type = get_slice_type(g, ptr_type);
...@@ -5758,6 +5776,7 @@ uint32_t type_id_hash(TypeId x) {...@@ -5758,6 +5776,7 @@ uint32_t type_id_hash(TypeId x) {
5758 return hash_ptr(x.data.error_union.err_set_type) ^ hash_ptr(x.data.error_union.payload_type);5776 return hash_ptr(x.data.error_union.err_set_type) ^ hash_ptr(x.data.error_union.payload_type);
5759 case TypeTableEntryIdPointer:5777 case TypeTableEntryIdPointer:
5760 return hash_ptr(x.data.pointer.child_type) +5778 return hash_ptr(x.data.pointer.child_type) +
5779 ((x.data.pointer.ptr_len == PtrLenSingle) ? (uint32_t)1120226602 : (uint32_t)3200913342) +
5761 (x.data.pointer.is_const ? (uint32_t)2749109194 : (uint32_t)4047371087) +5780 (x.data.pointer.is_const ? (uint32_t)2749109194 : (uint32_t)4047371087) +
5762 (x.data.pointer.is_volatile ? (uint32_t)536730450 : (uint32_t)1685612214) +5781 (x.data.pointer.is_volatile ? (uint32_t)536730450 : (uint32_t)1685612214) +
5763 (((uint32_t)x.data.pointer.alignment) ^ (uint32_t)0x777fbe0e) +5782 (((uint32_t)x.data.pointer.alignment) ^ (uint32_t)0x777fbe0e) +
...@@ -5806,6 +5825,7 @@ bool type_id_eql(TypeId a, TypeId b) {...@@ -5806,6 +5825,7 @@ bool type_id_eql(TypeId a, TypeId b) {
58065825
5807 case TypeTableEntryIdPointer:5826 case TypeTableEntryIdPointer:
5808 return a.data.pointer.child_type == b.data.pointer.child_type &&5827 return a.data.pointer.child_type == b.data.pointer.child_type &&
5828 a.data.pointer.ptr_len == b.data.pointer.ptr_len &&
5809 a.data.pointer.is_const == b.data.pointer.is_const &&5829 a.data.pointer.is_const == b.data.pointer.is_const &&
5810 a.data.pointer.is_volatile == b.data.pointer.is_volatile &&5830 a.data.pointer.is_volatile == b.data.pointer.is_volatile &&
5811 a.data.pointer.alignment == b.data.pointer.alignment &&5831 a.data.pointer.alignment == b.data.pointer.alignment &&
src/analyze.hpp+2-2
...@@ -16,7 +16,7 @@ ErrorMsg *add_error_note(CodeGen *g, ErrorMsg *parent_msg, AstNode *node, Buf *m...@@ -16,7 +16,7 @@ ErrorMsg *add_error_note(CodeGen *g, ErrorMsg *parent_msg, AstNode *node, Buf *m
16TypeTableEntry *new_type_table_entry(TypeTableEntryId id);16TypeTableEntry *new_type_table_entry(TypeTableEntryId id);
17TypeTableEntry *get_pointer_to_type(CodeGen *g, TypeTableEntry *child_type, bool is_const);17TypeTableEntry *get_pointer_to_type(CodeGen *g, TypeTableEntry *child_type, bool is_const);
18TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type, bool is_const,18TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type, bool is_const,
19 bool is_volatile, uint32_t byte_alignment, uint32_t bit_offset, uint32_t unaligned_bit_count);19 bool is_volatile, PtrLen ptr_len, uint32_t byte_alignment, uint32_t bit_offset, uint32_t unaligned_bit_count);
20uint64_t type_size(CodeGen *g, TypeTableEntry *type_entry);20uint64_t type_size(CodeGen *g, TypeTableEntry *type_entry);
21uint64_t type_size_bits(CodeGen *g, TypeTableEntry *type_entry);21uint64_t type_size_bits(CodeGen *g, TypeTableEntry *type_entry);
22TypeTableEntry **get_int_type_ptr(CodeGen *g, bool is_signed, uint32_t size_in_bits);22TypeTableEntry **get_int_type_ptr(CodeGen *g, bool is_signed, uint32_t size_in_bits);
...@@ -191,7 +191,7 @@ void add_fn_export(CodeGen *g, FnTableEntry *fn_table_entry, Buf *symbol_name, G...@@ -191,7 +191,7 @@ void add_fn_export(CodeGen *g, FnTableEntry *fn_table_entry, Buf *symbol_name, G
191191
192ConstExprValue *get_builtin_value(CodeGen *codegen, const char *name);192ConstExprValue *get_builtin_value(CodeGen *codegen, const char *name);
193TypeTableEntry *get_ptr_to_stack_trace_type(CodeGen *g);193TypeTableEntry *get_ptr_to_stack_trace_type(CodeGen *g);
194void analyze_fn_body(CodeGen *g, FnTableEntry *fn_table_entry);194bool resolve_inferred_error_set(CodeGen *g, TypeTableEntry *err_set_type, AstNode *source_node);
195195
196TypeTableEntry *get_auto_err_set_type(CodeGen *g, FnTableEntry *fn_entry);196TypeTableEntry *get_auto_err_set_type(CodeGen *g, FnTableEntry *fn_entry);
197197
src/ast_render.cpp+22-15
...@@ -68,6 +68,7 @@ static const char *prefix_op_str(PrefixOp prefix_op) {...@@ -68,6 +68,7 @@ static const char *prefix_op_str(PrefixOp prefix_op) {
68 case PrefixOpBinNot: return "~";68 case PrefixOpBinNot: return "~";
69 case PrefixOpMaybe: return "?";69 case PrefixOpMaybe: return "?";
70 case PrefixOpUnwrapMaybe: return "??";70 case PrefixOpUnwrapMaybe: return "??";
71 case PrefixOpAddrOf: return "&";
71 }72 }
72 zig_unreachable();73 zig_unreachable();
73}74}
...@@ -185,8 +186,6 @@ static const char *node_type_str(NodeType node_type) {...@@ -185,8 +186,6 @@ static const char *node_type_str(NodeType node_type) {
185 return "Symbol";186 return "Symbol";
186 case NodeTypePrefixOpExpr:187 case NodeTypePrefixOpExpr:
187 return "PrefixOpExpr";188 return "PrefixOpExpr";
188 case NodeTypeAddrOfExpr:
189 return "AddrOfExpr";
190 case NodeTypeUse:189 case NodeTypeUse:
191 return "Use";190 return "Use";
192 case NodeTypeBoolLiteral:191 case NodeTypeBoolLiteral:
...@@ -251,6 +250,8 @@ static const char *node_type_str(NodeType node_type) {...@@ -251,6 +250,8 @@ static const char *node_type_str(NodeType node_type) {
251 return "Suspend";250 return "Suspend";
252 case NodeTypePromiseType:251 case NodeTypePromiseType:
253 return "PromiseType";252 return "PromiseType";
253 case NodeTypePointerType:
254 return "PointerType";
254 }255 }
255 zig_unreachable();256 zig_unreachable();
256}257}
...@@ -616,41 +617,47 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {...@@ -616,41 +617,47 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
616 fprintf(ar->f, "%s", prefix_op_str(op));617 fprintf(ar->f, "%s", prefix_op_str(op));
617618
618 AstNode *child_node = node->data.prefix_op_expr.primary_expr;619 AstNode *child_node = node->data.prefix_op_expr.primary_expr;
619 bool new_grouped = child_node->type == NodeTypePrefixOpExpr || child_node->type == NodeTypeAddrOfExpr;620 bool new_grouped = child_node->type == NodeTypePrefixOpExpr || child_node->type == NodeTypePointerType;
620 render_node_extra(ar, child_node, new_grouped);621 render_node_extra(ar, child_node, new_grouped);
621 if (!grouped) fprintf(ar->f, ")");622 if (!grouped) fprintf(ar->f, ")");
622 break;623 break;
623 }624 }
624 case NodeTypeAddrOfExpr:625 case NodeTypePointerType:
625 {626 {
626 if (!grouped) fprintf(ar->f, "(");627 if (!grouped) fprintf(ar->f, "(");
627 fprintf(ar->f, "&");628 const char *star = "[*]";
628 if (node->data.addr_of_expr.align_expr != nullptr) {629 if (node->data.pointer_type.star_token != nullptr &&
630 (node->data.pointer_type.star_token->id == TokenIdStar || node->data.pointer_type.star_token->id == TokenIdStarStar))
631 {
632 star = "*";
633 }
634 fprintf(ar->f, "%s", star);
635 if (node->data.pointer_type.align_expr != nullptr) {
629 fprintf(ar->f, "align(");636 fprintf(ar->f, "align(");
630 render_node_grouped(ar, node->data.addr_of_expr.align_expr);637 render_node_grouped(ar, node->data.pointer_type.align_expr);
631 if (node->data.addr_of_expr.bit_offset_start != nullptr) {638 if (node->data.pointer_type.bit_offset_start != nullptr) {
632 assert(node->data.addr_of_expr.bit_offset_end != nullptr);639 assert(node->data.pointer_type.bit_offset_end != nullptr);
633640
634 Buf offset_start_buf = BUF_INIT;641 Buf offset_start_buf = BUF_INIT;
635 buf_resize(&offset_start_buf, 0);642 buf_resize(&offset_start_buf, 0);
636 bigint_append_buf(&offset_start_buf, node->data.addr_of_expr.bit_offset_start, 10);643 bigint_append_buf(&offset_start_buf, node->data.pointer_type.bit_offset_start, 10);
637644
638 Buf offset_end_buf = BUF_INIT;645 Buf offset_end_buf = BUF_INIT;
639 buf_resize(&offset_end_buf, 0);646 buf_resize(&offset_end_buf, 0);
640 bigint_append_buf(&offset_end_buf, node->data.addr_of_expr.bit_offset_end, 10);647 bigint_append_buf(&offset_end_buf, node->data.pointer_type.bit_offset_end, 10);
641648
642 fprintf(ar->f, ":%s:%s ", buf_ptr(&offset_start_buf), buf_ptr(&offset_end_buf));649 fprintf(ar->f, ":%s:%s ", buf_ptr(&offset_start_buf), buf_ptr(&offset_end_buf));
643 }650 }
644 fprintf(ar->f, ") ");651 fprintf(ar->f, ") ");
645 }652 }
646 if (node->data.addr_of_expr.is_const) {653 if (node->data.pointer_type.is_const) {
647 fprintf(ar->f, "const ");654 fprintf(ar->f, "const ");
648 }655 }
649 if (node->data.addr_of_expr.is_volatile) {656 if (node->data.pointer_type.is_volatile) {
650 fprintf(ar->f, "volatile ");657 fprintf(ar->f, "volatile ");
651 }658 }
652659
653 render_node_ungrouped(ar, node->data.addr_of_expr.op_expr);660 render_node_ungrouped(ar, node->data.pointer_type.op_expr);
654 if (!grouped) fprintf(ar->f, ")");661 if (!grouped) fprintf(ar->f, ")");
655 break;662 break;
656 }663 }
...@@ -669,7 +676,7 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {...@@ -669,7 +676,7 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
669 fprintf(ar->f, " ");676 fprintf(ar->f, " ");
670 }677 }
671 AstNode *fn_ref_node = node->data.fn_call_expr.fn_ref_expr;678 AstNode *fn_ref_node = node->data.fn_call_expr.fn_ref_expr;
672 bool grouped = (fn_ref_node->type != NodeTypePrefixOpExpr && fn_ref_node->type != NodeTypeAddrOfExpr);679 bool grouped = (fn_ref_node->type != NodeTypePrefixOpExpr && fn_ref_node->type != NodeTypePointerType);
673 render_node_extra(ar, fn_ref_node, grouped);680 render_node_extra(ar, fn_ref_node, grouped);
674 fprintf(ar->f, "(");681 fprintf(ar->f, "(");
675 for (size_t i = 0; i < node->data.fn_call_expr.params.length; i += 1) {682 for (size_t i = 0; i < node->data.fn_call_expr.params.length; i += 1) {
src/codegen.cpp+36-15
...@@ -897,7 +897,8 @@ static LLVMValueRef get_panic_msg_ptr_val(CodeGen *g, PanicMsgId msg_id) {...@@ -897,7 +897,8 @@ static LLVMValueRef get_panic_msg_ptr_val(CodeGen *g, PanicMsgId msg_id) {
897 assert(val->global_refs->llvm_global);897 assert(val->global_refs->llvm_global);
898 }898 }
899899
900 TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);900 TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
901 PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0);
901 TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type);902 TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type);
902 return LLVMConstBitCast(val->global_refs->llvm_global, LLVMPointerType(str_type->type_ref, 0));903 return LLVMConstBitCast(val->global_refs->llvm_global, LLVMPointerType(str_type->type_ref, 0));
903}904}
...@@ -1446,7 +1447,8 @@ static LLVMValueRef get_safety_crash_err_fn(CodeGen *g) {...@@ -1446,7 +1447,8 @@ static LLVMValueRef get_safety_crash_err_fn(CodeGen *g) {
1446 LLVMValueRef full_buf_ptr = LLVMConstInBoundsGEP(global_array, full_buf_ptr_indices, 2);1447 LLVMValueRef full_buf_ptr = LLVMConstInBoundsGEP(global_array, full_buf_ptr_indices, 2);
14471448
14481449
1449 TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);1450 TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
1451 PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0);
1450 TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type);1452 TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type);
1451 LLVMValueRef global_slice_fields[] = {1453 LLVMValueRef global_slice_fields[] = {
1452 full_buf_ptr,1454 full_buf_ptr,
...@@ -2179,9 +2181,13 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable,...@@ -2179,9 +2181,13 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable,
2179 IrInstruction *op2 = bin_op_instruction->op2;2181 IrInstruction *op2 = bin_op_instruction->op2;
21802182
2181 assert(op1->value.type == op2->value.type || op_id == IrBinOpBitShiftLeftLossy ||2183 assert(op1->value.type == op2->value.type || op_id == IrBinOpBitShiftLeftLossy ||
2182 op_id == IrBinOpBitShiftLeftExact || op_id == IrBinOpBitShiftRightLossy ||2184 op_id == IrBinOpBitShiftLeftExact || op_id == IrBinOpBitShiftRightLossy ||
2183 op_id == IrBinOpBitShiftRightExact ||2185 op_id == IrBinOpBitShiftRightExact ||
2184 (op1->value.type->id == TypeTableEntryIdErrorSet && op2->value.type->id == TypeTableEntryIdErrorSet));2186 (op1->value.type->id == TypeTableEntryIdErrorSet && op2->value.type->id == TypeTableEntryIdErrorSet) ||
2187 (op1->value.type->id == TypeTableEntryIdPointer &&
2188 (op_id == IrBinOpAdd || op_id == IrBinOpSub) &&
2189 op1->value.type->data.pointer.ptr_len == PtrLenUnknown)
2190 );
2185 TypeTableEntry *type_entry = op1->value.type;2191 TypeTableEntry *type_entry = op1->value.type;
21862192
2187 bool want_runtime_safety = bin_op_instruction->safety_check_on &&2193 bool want_runtime_safety = bin_op_instruction->safety_check_on &&
...@@ -2189,6 +2195,8 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable,...@@ -2189,6 +2195,8 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable,
21892195
2190 LLVMValueRef op1_value = ir_llvm_value(g, op1);2196 LLVMValueRef op1_value = ir_llvm_value(g, op1);
2191 LLVMValueRef op2_value = ir_llvm_value(g, op2);2197 LLVMValueRef op2_value = ir_llvm_value(g, op2);
2198
2199
2192 switch (op_id) {2200 switch (op_id) {
2193 case IrBinOpInvalid:2201 case IrBinOpInvalid:
2194 case IrBinOpArrayCat:2202 case IrBinOpArrayCat:
...@@ -2227,7 +2235,11 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable,...@@ -2227,7 +2235,11 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable,
2227 }2235 }
2228 case IrBinOpAdd:2236 case IrBinOpAdd:
2229 case IrBinOpAddWrap:2237 case IrBinOpAddWrap:
2230 if (type_entry->id == TypeTableEntryIdFloat) {2238 if (type_entry->id == TypeTableEntryIdPointer) {
2239 assert(type_entry->data.pointer.ptr_len == PtrLenUnknown);
2240 // TODO runtime safety
2241 return LLVMBuildInBoundsGEP(g->builder, op1_value, &op2_value, 1, "");
2242 } else if (type_entry->id == TypeTableEntryIdFloat) {
2231 ZigLLVMSetFastMath(g->builder, ir_want_fast_math(g, &bin_op_instruction->base));2243 ZigLLVMSetFastMath(g->builder, ir_want_fast_math(g, &bin_op_instruction->base));
2232 return LLVMBuildFAdd(g->builder, op1_value, op2_value, "");2244 return LLVMBuildFAdd(g->builder, op1_value, op2_value, "");
2233 } else if (type_entry->id == TypeTableEntryIdInt) {2245 } else if (type_entry->id == TypeTableEntryIdInt) {
...@@ -2290,7 +2302,12 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable,...@@ -2290,7 +2302,12 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable,
2290 }2302 }
2291 case IrBinOpSub:2303 case IrBinOpSub:
2292 case IrBinOpSubWrap:2304 case IrBinOpSubWrap:
2293 if (type_entry->id == TypeTableEntryIdFloat) {2305 if (type_entry->id == TypeTableEntryIdPointer) {
2306 assert(type_entry->data.pointer.ptr_len == PtrLenUnknown);
2307 // TODO runtime safety
2308 LLVMValueRef subscript_value = LLVMBuildNeg(g->builder, op2_value, "");
2309 return LLVMBuildInBoundsGEP(g->builder, op1_value, &subscript_value, 1, "");
2310 } else if (type_entry->id == TypeTableEntryIdFloat) {
2294 ZigLLVMSetFastMath(g->builder, ir_want_fast_math(g, &bin_op_instruction->base));2311 ZigLLVMSetFastMath(g->builder, ir_want_fast_math(g, &bin_op_instruction->base));
2295 return LLVMBuildFSub(g->builder, op1_value, op2_value, "");2312 return LLVMBuildFSub(g->builder, op1_value, op2_value, "");
2296 } else if (type_entry->id == TypeTableEntryIdInt) {2313 } else if (type_entry->id == TypeTableEntryIdInt) {
...@@ -2718,7 +2735,7 @@ static LLVMValueRef ir_render_decl_var(CodeGen *g, IrExecutable *executable,...@@ -2718,7 +2735,7 @@ static LLVMValueRef ir_render_decl_var(CodeGen *g, IrExecutable *executable,
2718 if (have_init_expr) {2735 if (have_init_expr) {
2719 assert(var->value->type == init_value->value.type);2736 assert(var->value->type == init_value->value.type);
2720 TypeTableEntry *var_ptr_type = get_pointer_to_type_extra(g, var->value->type, false, false,2737 TypeTableEntry *var_ptr_type = get_pointer_to_type_extra(g, var->value->type, false, false,
2721 var->align_bytes, 0, 0);2738 PtrLenSingle, var->align_bytes, 0, 0);
2722 gen_assign_raw(g, var->value_ref, var_ptr_type, ir_llvm_value(g, init_value));2739 gen_assign_raw(g, var->value_ref, var_ptr_type, ir_llvm_value(g, init_value));
2723 } else {2740 } else {
2724 bool want_safe = ir_want_runtime_safety(g, &decl_var_instruction->base);2741 bool want_safe = ir_want_runtime_safety(g, &decl_var_instruction->base);
...@@ -4087,7 +4104,7 @@ static LLVMValueRef ir_render_struct_init(CodeGen *g, IrExecutable *executable,...@@ -4087,7 +4104,7 @@ static LLVMValueRef ir_render_struct_init(CodeGen *g, IrExecutable *executable,
4087 uint32_t field_align_bytes = get_abi_alignment(g, type_struct_field->type_entry);4104 uint32_t field_align_bytes = get_abi_alignment(g, type_struct_field->type_entry);
40884105
4089 TypeTableEntry *ptr_type = get_pointer_to_type_extra(g, type_struct_field->type_entry,4106 TypeTableEntry *ptr_type = get_pointer_to_type_extra(g, type_struct_field->type_entry,
4090 false, false, field_align_bytes,4107 false, false, PtrLenSingle, field_align_bytes,
4091 (uint32_t)type_struct_field->packed_bits_offset, (uint32_t)type_struct_field->unaligned_bit_count);4108 (uint32_t)type_struct_field->packed_bits_offset, (uint32_t)type_struct_field->unaligned_bit_count);
40924109
4093 gen_assign_raw(g, field_ptr, ptr_type, value);4110 gen_assign_raw(g, field_ptr, ptr_type, value);
...@@ -4103,7 +4120,7 @@ static LLVMValueRef ir_render_union_init(CodeGen *g, IrExecutable *executable, I...@@ -4103,7 +4120,7 @@ static LLVMValueRef ir_render_union_init(CodeGen *g, IrExecutable *executable, I
41034120
4104 uint32_t field_align_bytes = get_abi_alignment(g, type_union_field->type_entry);4121 uint32_t field_align_bytes = get_abi_alignment(g, type_union_field->type_entry);
4105 TypeTableEntry *ptr_type = get_pointer_to_type_extra(g, type_union_field->type_entry,4122 TypeTableEntry *ptr_type = get_pointer_to_type_extra(g, type_union_field->type_entry,
4106 false, false, field_align_bytes,4123 false, false, PtrLenSingle, field_align_bytes,
4107 0, 0);4124 0, 0);
41084125
4109 LLVMValueRef uncasted_union_ptr;4126 LLVMValueRef uncasted_union_ptr;
...@@ -4350,7 +4367,8 @@ static LLVMValueRef get_coro_alloc_helper_fn_val(CodeGen *g, LLVMTypeRef alloc_f...@@ -4350,7 +4367,8 @@ static LLVMValueRef get_coro_alloc_helper_fn_val(CodeGen *g, LLVMTypeRef alloc_f
43504367
4351 LLVMPositionBuilderAtEnd(g->builder, ok_block);4368 LLVMPositionBuilderAtEnd(g->builder, ok_block);
4352 LLVMValueRef payload_ptr = LLVMBuildStructGEP(g->builder, sret_ptr, err_union_payload_index, "");4369 LLVMValueRef payload_ptr = LLVMBuildStructGEP(g->builder, sret_ptr, err_union_payload_index, "");
4353 TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, false);4370 TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, false, false,
4371 PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0);
4354 TypeTableEntry *slice_type = get_slice_type(g, u8_ptr_type);4372 TypeTableEntry *slice_type = get_slice_type(g, u8_ptr_type);
4355 size_t ptr_field_index = slice_type->data.structure.fields[slice_ptr_index].gen_index;4373 size_t ptr_field_index = slice_type->data.structure.fields[slice_ptr_index].gen_index;
4356 LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, payload_ptr, ptr_field_index, "");4374 LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, payload_ptr, ptr_field_index, "");
...@@ -4515,7 +4533,7 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable,...@@ -4515,7 +4533,7 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable,
4515 case IrInstructionIdTypeInfo:4533 case IrInstructionIdTypeInfo:
4516 case IrInstructionIdTypeId:4534 case IrInstructionIdTypeId:
4517 case IrInstructionIdSetEvalBranchQuota:4535 case IrInstructionIdSetEvalBranchQuota:
4518 case IrInstructionIdPtrTypeOf:4536 case IrInstructionIdPtrType:
4519 case IrInstructionIdOpaqueType:4537 case IrInstructionIdOpaqueType:
4520 case IrInstructionIdSetAlignStack:4538 case IrInstructionIdSetAlignStack:
4521 case IrInstructionIdArgType:4539 case IrInstructionIdArgType:
...@@ -5292,7 +5310,8 @@ static void generate_error_name_table(CodeGen *g) {...@@ -5292,7 +5310,8 @@ static void generate_error_name_table(CodeGen *g) {
52925310
5293 assert(g->errors_by_index.length > 0);5311 assert(g->errors_by_index.length > 0);
52945312
5295 TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);5313 TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
5314 PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0);
5296 TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type);5315 TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type);
52975316
5298 LLVMValueRef *values = allocate<LLVMValueRef>(g->errors_by_index.length);5317 LLVMValueRef *values = allocate<LLVMValueRef>(g->errors_by_index.length);
...@@ -5330,7 +5349,8 @@ static void generate_error_name_table(CodeGen *g) {...@@ -5330,7 +5349,8 @@ static void generate_error_name_table(CodeGen *g) {
5330}5349}
53315350
5332static void generate_enum_name_tables(CodeGen *g) {5351static void generate_enum_name_tables(CodeGen *g) {
5333 TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);5352 TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
5353 PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0);
5334 TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type);5354 TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type);
53355355
5336 TypeTableEntry *usize = g->builtin_types.entry_usize;5356 TypeTableEntry *usize = g->builtin_types.entry_usize;
...@@ -6784,7 +6804,8 @@ static void create_test_compile_var_and_add_test_runner(CodeGen *g) {...@@ -6784,7 +6804,8 @@ static void create_test_compile_var_and_add_test_runner(CodeGen *g) {
6784 exit(0);6804 exit(0);
6785 }6805 }
67866806
6787 TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);6807 TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
6808 PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0);
6788 TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type);6809 TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type);
6789 TypeTableEntry *fn_type = get_test_fn_type(g);6810 TypeTableEntry *fn_type = get_test_fn_type(g);
67906811
src/ir.cpp+331-265
...@@ -41,10 +41,6 @@ struct IrAnalyze {...@@ -41,10 +41,6 @@ struct IrAnalyze {
41static const LVal LVAL_NONE = { false, false, false };41static const LVal LVAL_NONE = { false, false, false };
42static const LVal LVAL_PTR = { true, false, false };42static const LVal LVAL_PTR = { true, false, false };
4343
44static LVal make_lval_addr(bool is_const, bool is_volatile) {
45 return { true, is_const, is_volatile };
46}
47
48enum ConstCastResultId {44enum ConstCastResultId {
49 ConstCastResultIdOk,45 ConstCastResultIdOk,
50 ConstCastResultIdErrSet,46 ConstCastResultIdErrSet,
...@@ -108,8 +104,7 @@ static IrInstruction *ir_get_deref(IrAnalyze *ira, IrInstruction *source_instruc...@@ -108,8 +104,7 @@ static IrInstruction *ir_get_deref(IrAnalyze *ira, IrInstruction *source_instruc
108static ErrorMsg *exec_add_error_node(CodeGen *codegen, IrExecutable *exec, AstNode *source_node, Buf *msg);104static ErrorMsg *exec_add_error_node(CodeGen *codegen, IrExecutable *exec, AstNode *source_node, Buf *msg);
109static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_name,105static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_name,
110 IrInstruction *source_instr, IrInstruction *container_ptr, TypeTableEntry *container_type);106 IrInstruction *source_instr, IrInstruction *container_ptr, TypeTableEntry *container_type);
111static IrInstruction *ir_get_var_ptr(IrAnalyze *ira, IrInstruction *instruction,107static IrInstruction *ir_get_var_ptr(IrAnalyze *ira, IrInstruction *instruction, VariableTableEntry *var);
112 VariableTableEntry *var, bool is_const_ptr, bool is_volatile_ptr);
113static TypeTableEntry *ir_resolve_atomic_operand_type(IrAnalyze *ira, IrInstruction *op);108static TypeTableEntry *ir_resolve_atomic_operand_type(IrAnalyze *ira, IrInstruction *op);
114static IrInstruction *ir_lval_wrap(IrBuilder *irb, Scope *scope, IrInstruction *value, LVal lval);109static IrInstruction *ir_lval_wrap(IrBuilder *irb, Scope *scope, IrInstruction *value, LVal lval);
115110
...@@ -629,8 +624,8 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionSetEvalBranchQuo...@@ -629,8 +624,8 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionSetEvalBranchQuo
629 return IrInstructionIdSetEvalBranchQuota;624 return IrInstructionIdSetEvalBranchQuota;
630}625}
631626
632static constexpr IrInstructionId ir_instruction_id(IrInstructionPtrTypeOf *) {627static constexpr IrInstructionId ir_instruction_id(IrInstructionPtrType *) {
633 return IrInstructionIdPtrTypeOf;628 return IrInstructionIdPtrType;
634}629}
635630
636static constexpr IrInstructionId ir_instruction_id(IrInstructionAlignCast *) {631static constexpr IrInstructionId ir_instruction_id(IrInstructionAlignCast *) {
...@@ -1004,13 +999,9 @@ static IrInstruction *ir_build_bin_op_from(IrBuilder *irb, IrInstruction *old_in...@@ -1004,13 +999,9 @@ static IrInstruction *ir_build_bin_op_from(IrBuilder *irb, IrInstruction *old_in
1004 return new_instruction;999 return new_instruction;
1005}1000}
10061001
1007static IrInstruction *ir_build_var_ptr(IrBuilder *irb, Scope *scope, AstNode *source_node,1002static IrInstruction *ir_build_var_ptr(IrBuilder *irb, Scope *scope, AstNode *source_node, VariableTableEntry *var) {
1008 VariableTableEntry *var, bool is_const, bool is_volatile)
1009{
1010 IrInstructionVarPtr *instruction = ir_build_instruction<IrInstructionVarPtr>(irb, scope, source_node);1003 IrInstructionVarPtr *instruction = ir_build_instruction<IrInstructionVarPtr>(irb, scope, source_node);
1011 instruction->var = var;1004 instruction->var = var;
1012 instruction->is_const = is_const;
1013 instruction->is_volatile = is_volatile;
10141005
1015 ir_ref_var(var);1006 ir_ref_var(var);
10161007
...@@ -1018,12 +1009,13 @@ static IrInstruction *ir_build_var_ptr(IrBuilder *irb, Scope *scope, AstNode *so...@@ -1018,12 +1009,13 @@ static IrInstruction *ir_build_var_ptr(IrBuilder *irb, Scope *scope, AstNode *so
1018}1009}
10191010
1020static IrInstruction *ir_build_elem_ptr(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *array_ptr,1011static IrInstruction *ir_build_elem_ptr(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *array_ptr,
1021 IrInstruction *elem_index, bool safety_check_on)1012 IrInstruction *elem_index, bool safety_check_on, PtrLen ptr_len)
1022{1013{
1023 IrInstructionElemPtr *instruction = ir_build_instruction<IrInstructionElemPtr>(irb, scope, source_node);1014 IrInstructionElemPtr *instruction = ir_build_instruction<IrInstructionElemPtr>(irb, scope, source_node);
1024 instruction->array_ptr = array_ptr;1015 instruction->array_ptr = array_ptr;
1025 instruction->elem_index = elem_index;1016 instruction->elem_index = elem_index;
1026 instruction->safety_check_on = safety_check_on;1017 instruction->safety_check_on = safety_check_on;
1018 instruction->ptr_len = ptr_len;
10271019
1028 ir_ref_instruction(array_ptr, irb->current_basic_block);1020 ir_ref_instruction(array_ptr, irb->current_basic_block);
1029 ir_ref_instruction(elem_index, irb->current_basic_block);1021 ir_ref_instruction(elem_index, irb->current_basic_block);
...@@ -1031,15 +1023,6 @@ static IrInstruction *ir_build_elem_ptr(IrBuilder *irb, Scope *scope, AstNode *s...@@ -1031,15 +1023,6 @@ static IrInstruction *ir_build_elem_ptr(IrBuilder *irb, Scope *scope, AstNode *s
1031 return &instruction->base;1023 return &instruction->base;
1032}1024}
10331025
1034static IrInstruction *ir_build_elem_ptr_from(IrBuilder *irb, IrInstruction *old_instruction,
1035 IrInstruction *array_ptr, IrInstruction *elem_index, bool safety_check_on)
1036{
1037 IrInstruction *new_instruction = ir_build_elem_ptr(irb, old_instruction->scope,
1038 old_instruction->source_node, array_ptr, elem_index, safety_check_on);
1039 ir_link_new_instruction(new_instruction, old_instruction);
1040 return new_instruction;
1041}
1042
1043static IrInstruction *ir_build_field_ptr_instruction(IrBuilder *irb, Scope *scope, AstNode *source_node,1026static IrInstruction *ir_build_field_ptr_instruction(IrBuilder *irb, Scope *scope, AstNode *source_node,
1044 IrInstruction *container_ptr, IrInstruction *field_name_expr)1027 IrInstruction *container_ptr, IrInstruction *field_name_expr)
1045{1028{
...@@ -1196,15 +1179,16 @@ static IrInstruction *ir_build_br_from(IrBuilder *irb, IrInstruction *old_instru...@@ -1196,15 +1179,16 @@ static IrInstruction *ir_build_br_from(IrBuilder *irb, IrInstruction *old_instru
1196 return new_instruction;1179 return new_instruction;
1197}1180}
11981181
1199static IrInstruction *ir_build_ptr_type_of(IrBuilder *irb, Scope *scope, AstNode *source_node,1182static IrInstruction *ir_build_ptr_type(IrBuilder *irb, Scope *scope, AstNode *source_node,
1200 IrInstruction *child_type, bool is_const, bool is_volatile, IrInstruction *align_value,1183 IrInstruction *child_type, bool is_const, bool is_volatile, PtrLen ptr_len,
1201 uint32_t bit_offset_start, uint32_t bit_offset_end)1184 IrInstruction *align_value, uint32_t bit_offset_start, uint32_t bit_offset_end)
1202{1185{
1203 IrInstructionPtrTypeOf *ptr_type_of_instruction = ir_build_instruction<IrInstructionPtrTypeOf>(irb, scope, source_node);1186 IrInstructionPtrType *ptr_type_of_instruction = ir_build_instruction<IrInstructionPtrType>(irb, scope, source_node);
1204 ptr_type_of_instruction->align_value = align_value;1187 ptr_type_of_instruction->align_value = align_value;
1205 ptr_type_of_instruction->child_type = child_type;1188 ptr_type_of_instruction->child_type = child_type;
1206 ptr_type_of_instruction->is_const = is_const;1189 ptr_type_of_instruction->is_const = is_const;
1207 ptr_type_of_instruction->is_volatile = is_volatile;1190 ptr_type_of_instruction->is_volatile = is_volatile;
1191 ptr_type_of_instruction->ptr_len = ptr_len;
1208 ptr_type_of_instruction->bit_offset_start = bit_offset_start;1192 ptr_type_of_instruction->bit_offset_start = bit_offset_start;
1209 ptr_type_of_instruction->bit_offset_end = bit_offset_end;1193 ptr_type_of_instruction->bit_offset_end = bit_offset_end;
12101194
...@@ -3519,8 +3503,7 @@ static IrInstruction *ir_gen_symbol(IrBuilder *irb, Scope *scope, AstNode *node,...@@ -3519,8 +3503,7 @@ static IrInstruction *ir_gen_symbol(IrBuilder *irb, Scope *scope, AstNode *node,
35193503
3520 VariableTableEntry *var = find_variable(irb->codegen, scope, variable_name);3504 VariableTableEntry *var = find_variable(irb->codegen, scope, variable_name);
3521 if (var) {3505 if (var) {
3522 IrInstruction *var_ptr = ir_build_var_ptr(irb, scope, node, var,3506 IrInstruction *var_ptr = ir_build_var_ptr(irb, scope, node, var);
3523 !lval.is_ptr || lval.is_const, lval.is_ptr && lval.is_volatile);
3524 if (lval.is_ptr)3507 if (lval.is_ptr)
3525 return var_ptr;3508 return var_ptr;
3526 else3509 else
...@@ -3557,7 +3540,7 @@ static IrInstruction *ir_gen_array_access(IrBuilder *irb, Scope *scope, AstNode...@@ -3557,7 +3540,7 @@ static IrInstruction *ir_gen_array_access(IrBuilder *irb, Scope *scope, AstNode
3557 return subscript_instruction;3540 return subscript_instruction;
35583541
3559 IrInstruction *ptr_instruction = ir_build_elem_ptr(irb, scope, node, array_ref_instruction,3542 IrInstruction *ptr_instruction = ir_build_elem_ptr(irb, scope, node, array_ref_instruction,
3560 subscript_instruction, true);3543 subscript_instruction, true, PtrLenSingle);
3561 if (lval.is_ptr)3544 if (lval.is_ptr)
3562 return ptr_instruction;3545 return ptr_instruction;
35633546
...@@ -4609,14 +4592,8 @@ static IrInstruction *ir_gen_if_bool_expr(IrBuilder *irb, Scope *scope, AstNode...@@ -4609,14 +4592,8 @@ static IrInstruction *ir_gen_if_bool_expr(IrBuilder *irb, Scope *scope, AstNode
4609}4592}
46104593
4611static IrInstruction *ir_gen_prefix_op_id_lval(IrBuilder *irb, Scope *scope, AstNode *node, IrUnOp op_id, LVal lval) {4594static IrInstruction *ir_gen_prefix_op_id_lval(IrBuilder *irb, Scope *scope, AstNode *node, IrUnOp op_id, LVal lval) {
4612 AstNode *expr_node;4595 assert(node->type == NodeTypePrefixOpExpr);
4613 if (node->type == NodeTypePrefixOpExpr) {4596 AstNode *expr_node = node->data.prefix_op_expr.primary_expr;
4614 expr_node = node->data.prefix_op_expr.primary_expr;
4615 } else if (node->type == NodeTypePtrDeref) {
4616 expr_node = node->data.ptr_deref_expr.target;
4617 } else {
4618 zig_unreachable();
4619 }
46204597
4621 IrInstruction *value = ir_gen_node_extra(irb, expr_node, scope, lval);4598 IrInstruction *value = ir_gen_node_extra(irb, expr_node, scope, lval);
4622 if (value == irb->codegen->invalid_instruction)4599 if (value == irb->codegen->invalid_instruction)
...@@ -4640,16 +4617,17 @@ static IrInstruction *ir_lval_wrap(IrBuilder *irb, Scope *scope, IrInstruction *...@@ -4640,16 +4617,17 @@ static IrInstruction *ir_lval_wrap(IrBuilder *irb, Scope *scope, IrInstruction *
4640 return ir_build_ref(irb, scope, value->source_node, value, lval.is_const, lval.is_volatile);4617 return ir_build_ref(irb, scope, value->source_node, value, lval.is_const, lval.is_volatile);
4641}4618}
46424619
4643static IrInstruction *ir_gen_address_of(IrBuilder *irb, Scope *scope, AstNode *node) {4620static IrInstruction *ir_gen_pointer_type(IrBuilder *irb, Scope *scope, AstNode *node) {
4644 assert(node->type == NodeTypeAddrOfExpr);4621 assert(node->type == NodeTypePointerType);
4645 bool is_const = node->data.addr_of_expr.is_const;4622 // The null check here is for C imports which don't set a token on the AST node. We could potentially
4646 bool is_volatile = node->data.addr_of_expr.is_volatile;4623 // update that code to create a fake token and then remove this check.
4647 AstNode *expr_node = node->data.addr_of_expr.op_expr;4624 PtrLen ptr_len = (node->data.pointer_type.star_token != nullptr &&
4648 AstNode *align_expr = node->data.addr_of_expr.align_expr;4625 (node->data.pointer_type.star_token->id == TokenIdStar ||
46494626 node->data.pointer_type.star_token->id == TokenIdStarStar)) ? PtrLenSingle : PtrLenUnknown;
4650 if (align_expr == nullptr && !is_const && !is_volatile) {4627 bool is_const = node->data.pointer_type.is_const;
4651 return ir_gen_node_extra(irb, expr_node, scope, make_lval_addr(is_const, is_volatile));4628 bool is_volatile = node->data.pointer_type.is_volatile;
4652 }4629 AstNode *expr_node = node->data.pointer_type.op_expr;
4630 AstNode *align_expr = node->data.pointer_type.align_expr;
46534631
4654 IrInstruction *align_value;4632 IrInstruction *align_value;
4655 if (align_expr != nullptr) {4633 if (align_expr != nullptr) {
...@@ -4665,27 +4643,27 @@ static IrInstruction *ir_gen_address_of(IrBuilder *irb, Scope *scope, AstNode *n...@@ -4665,27 +4643,27 @@ static IrInstruction *ir_gen_address_of(IrBuilder *irb, Scope *scope, AstNode *n
4665 return child_type;4643 return child_type;
46664644
4667 uint32_t bit_offset_start = 0;4645 uint32_t bit_offset_start = 0;
4668 if (node->data.addr_of_expr.bit_offset_start != nullptr) {4646 if (node->data.pointer_type.bit_offset_start != nullptr) {
4669 if (!bigint_fits_in_bits(node->data.addr_of_expr.bit_offset_start, 32, false)) {4647 if (!bigint_fits_in_bits(node->data.pointer_type.bit_offset_start, 32, false)) {
4670 Buf *val_buf = buf_alloc();4648 Buf *val_buf = buf_alloc();
4671 bigint_append_buf(val_buf, node->data.addr_of_expr.bit_offset_start, 10);4649 bigint_append_buf(val_buf, node->data.pointer_type.bit_offset_start, 10);
4672 exec_add_error_node(irb->codegen, irb->exec, node,4650 exec_add_error_node(irb->codegen, irb->exec, node,
4673 buf_sprintf("value %s too large for u32 bit offset", buf_ptr(val_buf)));4651 buf_sprintf("value %s too large for u32 bit offset", buf_ptr(val_buf)));
4674 return irb->codegen->invalid_instruction;4652 return irb->codegen->invalid_instruction;
4675 }4653 }
4676 bit_offset_start = bigint_as_unsigned(node->data.addr_of_expr.bit_offset_start);4654 bit_offset_start = bigint_as_unsigned(node->data.pointer_type.bit_offset_start);
4677 }4655 }
46784656
4679 uint32_t bit_offset_end = 0;4657 uint32_t bit_offset_end = 0;
4680 if (node->data.addr_of_expr.bit_offset_end != nullptr) {4658 if (node->data.pointer_type.bit_offset_end != nullptr) {
4681 if (!bigint_fits_in_bits(node->data.addr_of_expr.bit_offset_end, 32, false)) {4659 if (!bigint_fits_in_bits(node->data.pointer_type.bit_offset_end, 32, false)) {
4682 Buf *val_buf = buf_alloc();4660 Buf *val_buf = buf_alloc();
4683 bigint_append_buf(val_buf, node->data.addr_of_expr.bit_offset_end, 10);4661 bigint_append_buf(val_buf, node->data.pointer_type.bit_offset_end, 10);
4684 exec_add_error_node(irb->codegen, irb->exec, node,4662 exec_add_error_node(irb->codegen, irb->exec, node,
4685 buf_sprintf("value %s too large for u32 bit offset", buf_ptr(val_buf)));4663 buf_sprintf("value %s too large for u32 bit offset", buf_ptr(val_buf)));
4686 return irb->codegen->invalid_instruction;4664 return irb->codegen->invalid_instruction;
4687 }4665 }
4688 bit_offset_end = bigint_as_unsigned(node->data.addr_of_expr.bit_offset_end);4666 bit_offset_end = bigint_as_unsigned(node->data.pointer_type.bit_offset_end);
4689 }4667 }
46904668
4691 if ((bit_offset_start != 0 || bit_offset_end != 0) && bit_offset_start >= bit_offset_end) {4669 if ((bit_offset_start != 0 || bit_offset_end != 0) && bit_offset_start >= bit_offset_end) {
...@@ -4694,8 +4672,8 @@ static IrInstruction *ir_gen_address_of(IrBuilder *irb, Scope *scope, AstNode *n...@@ -4694,8 +4672,8 @@ static IrInstruction *ir_gen_address_of(IrBuilder *irb, Scope *scope, AstNode *n
4694 return irb->codegen->invalid_instruction;4672 return irb->codegen->invalid_instruction;
4695 }4673 }
46964674
4697 return ir_build_ptr_type_of(irb, scope, node, child_type, is_const, is_volatile,4675 return ir_build_ptr_type(irb, scope, node, child_type, is_const, is_volatile,
4698 align_value, bit_offset_start, bit_offset_end);4676 ptr_len, align_value, bit_offset_start, bit_offset_end);
4699}4677}
47004678
4701static IrInstruction *ir_gen_err_assert_ok(IrBuilder *irb, Scope *scope, AstNode *source_node, AstNode *expr_node,4679static IrInstruction *ir_gen_err_assert_ok(IrBuilder *irb, Scope *scope, AstNode *source_node, AstNode *expr_node,
...@@ -4761,6 +4739,10 @@ static IrInstruction *ir_gen_prefix_op_expr(IrBuilder *irb, Scope *scope, AstNod...@@ -4761,6 +4739,10 @@ static IrInstruction *ir_gen_prefix_op_expr(IrBuilder *irb, Scope *scope, AstNod
4761 return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpMaybe), lval);4739 return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpMaybe), lval);
4762 case PrefixOpUnwrapMaybe:4740 case PrefixOpUnwrapMaybe:
4763 return ir_gen_maybe_assert_ok(irb, scope, node, lval);4741 return ir_gen_maybe_assert_ok(irb, scope, node, lval);
4742 case PrefixOpAddrOf: {
4743 AstNode *expr_node = node->data.prefix_op_expr.primary_expr;
4744 return ir_lval_wrap(irb, scope, ir_gen_node_extra(irb, expr_node, scope, LVAL_PTR), lval);
4745 }
4764 }4746 }
4765 zig_unreachable();4747 zig_unreachable();
4766}4748}
...@@ -5150,7 +5132,7 @@ static IrInstruction *ir_gen_for_expr(IrBuilder *irb, Scope *parent_scope, AstNo...@@ -5150,7 +5132,7 @@ static IrInstruction *ir_gen_for_expr(IrBuilder *irb, Scope *parent_scope, AstNo
51505132
5151 IrInstruction *undefined_value = ir_build_const_undefined(irb, child_scope, elem_node);5133 IrInstruction *undefined_value = ir_build_const_undefined(irb, child_scope, elem_node);
5152 ir_build_var_decl(irb, child_scope, elem_node, elem_var, elem_var_type, nullptr, undefined_value);5134 ir_build_var_decl(irb, child_scope, elem_node, elem_var, elem_var_type, nullptr, undefined_value);
5153 IrInstruction *elem_var_ptr = ir_build_var_ptr(irb, child_scope, node, elem_var, false, false);5135 IrInstruction *elem_var_ptr = ir_build_var_ptr(irb, child_scope, node, elem_var);
51545136
5155 AstNode *index_var_source_node;5137 AstNode *index_var_source_node;
5156 VariableTableEntry *index_var;5138 VariableTableEntry *index_var;
...@@ -5168,7 +5150,7 @@ static IrInstruction *ir_gen_for_expr(IrBuilder *irb, Scope *parent_scope, AstNo...@@ -5168,7 +5150,7 @@ static IrInstruction *ir_gen_for_expr(IrBuilder *irb, Scope *parent_scope, AstNo
5168 IrInstruction *zero = ir_build_const_usize(irb, child_scope, node, 0);5150 IrInstruction *zero = ir_build_const_usize(irb, child_scope, node, 0);
5169 IrInstruction *one = ir_build_const_usize(irb, child_scope, node, 1);5151 IrInstruction *one = ir_build_const_usize(irb, child_scope, node, 1);
5170 ir_build_var_decl(irb, child_scope, index_var_source_node, index_var, usize, nullptr, zero);5152 ir_build_var_decl(irb, child_scope, index_var_source_node, index_var, usize, nullptr, zero);
5171 IrInstruction *index_ptr = ir_build_var_ptr(irb, child_scope, node, index_var, false, false);5153 IrInstruction *index_ptr = ir_build_var_ptr(irb, child_scope, node, index_var);
51725154
51735155
5174 IrBasicBlock *cond_block = ir_create_basic_block(irb, child_scope, "ForCond");5156 IrBasicBlock *cond_block = ir_create_basic_block(irb, child_scope, "ForCond");
...@@ -5188,7 +5170,7 @@ static IrInstruction *ir_gen_for_expr(IrBuilder *irb, Scope *parent_scope, AstNo...@@ -5188,7 +5170,7 @@ static IrInstruction *ir_gen_for_expr(IrBuilder *irb, Scope *parent_scope, AstNo
5188 ir_mark_gen(ir_build_cond_br(irb, child_scope, node, cond, body_block, else_block, is_comptime));5170 ir_mark_gen(ir_build_cond_br(irb, child_scope, node, cond, body_block, else_block, is_comptime));
51895171
5190 ir_set_cursor_at_end_and_append_block(irb, body_block);5172 ir_set_cursor_at_end_and_append_block(irb, body_block);
5191 IrInstruction *elem_ptr = ir_build_elem_ptr(irb, child_scope, node, array_val_ptr, index_val, false);5173 IrInstruction *elem_ptr = ir_build_elem_ptr(irb, child_scope, node, array_val_ptr, index_val, false, PtrLenSingle);
5192 IrInstruction *elem_val;5174 IrInstruction *elem_val;
5193 if (node->data.for_expr.elem_is_ptr) {5175 if (node->data.for_expr.elem_is_ptr) {
5194 elem_val = elem_ptr;5176 elem_val = elem_ptr;
...@@ -6397,7 +6379,7 @@ static IrInstruction *ir_gen_await_expr(IrBuilder *irb, Scope *parent_scope, Ast...@@ -6397,7 +6379,7 @@ static IrInstruction *ir_gen_await_expr(IrBuilder *irb, Scope *parent_scope, Ast
6397 IrInstruction *promise_result_type = ir_build_promise_result_type(irb, parent_scope, node, target_promise_type);6379 IrInstruction *promise_result_type = ir_build_promise_result_type(irb, parent_scope, node, target_promise_type);
6398 ir_build_await_bookkeeping(irb, parent_scope, node, promise_result_type);6380 ir_build_await_bookkeeping(irb, parent_scope, node, promise_result_type);
6399 ir_build_var_decl(irb, parent_scope, node, result_var, promise_result_type, nullptr, undefined_value);6381 ir_build_var_decl(irb, parent_scope, node, result_var, promise_result_type, nullptr, undefined_value);
6400 IrInstruction *my_result_var_ptr = ir_build_var_ptr(irb, parent_scope, node, result_var, false, false);6382 IrInstruction *my_result_var_ptr = ir_build_var_ptr(irb, parent_scope, node, result_var);
6401 ir_build_store_ptr(irb, parent_scope, node, result_ptr_field_ptr, my_result_var_ptr);6383 ir_build_store_ptr(irb, parent_scope, node, result_ptr_field_ptr, my_result_var_ptr);
6402 IrInstruction *save_token = ir_build_coro_save(irb, parent_scope, node, irb->exec->coro_handle);6384 IrInstruction *save_token = ir_build_coro_save(irb, parent_scope, node, irb->exec->coro_handle);
6403 IrInstruction *promise_type_val = ir_build_const_type(irb, parent_scope, node,6385 IrInstruction *promise_type_val = ir_build_const_type(irb, parent_scope, node,
...@@ -6568,8 +6550,6 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop...@@ -6568,8 +6550,6 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop
6568 return ir_lval_wrap(irb, scope, ir_gen_if_bool_expr(irb, scope, node), lval);6550 return ir_lval_wrap(irb, scope, ir_gen_if_bool_expr(irb, scope, node), lval);
6569 case NodeTypePrefixOpExpr:6551 case NodeTypePrefixOpExpr:
6570 return ir_gen_prefix_op_expr(irb, scope, node, lval);6552 return ir_gen_prefix_op_expr(irb, scope, node, lval);
6571 case NodeTypeAddrOfExpr:
6572 return ir_lval_wrap(irb, scope, ir_gen_address_of(irb, scope, node), lval);
6573 case NodeTypeContainerInitExpr:6553 case NodeTypeContainerInitExpr:
6574 return ir_lval_wrap(irb, scope, ir_gen_container_init_expr(irb, scope, node), lval);6554 return ir_lval_wrap(irb, scope, ir_gen_container_init_expr(irb, scope, node), lval);
6575 case NodeTypeVariableDeclaration:6555 case NodeTypeVariableDeclaration:
...@@ -6592,14 +6572,23 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop...@@ -6592,14 +6572,23 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop
65926572
6593 return ir_build_load_ptr(irb, scope, node, ptr_instruction);6573 return ir_build_load_ptr(irb, scope, node, ptr_instruction);
6594 }6574 }
6595 case NodeTypePtrDeref:6575 case NodeTypePtrDeref: {
6596 return ir_gen_prefix_op_id_lval(irb, scope, node, IrUnOpDereference, lval);6576 assert(node->type == NodeTypePtrDeref);
6577 AstNode *expr_node = node->data.ptr_deref_expr.target;
6578 IrInstruction *value = ir_gen_node_extra(irb, expr_node, scope, lval);
6579 if (value == irb->codegen->invalid_instruction)
6580 return value;
6581
6582 return ir_build_un_op(irb, scope, node, IrUnOpDereference, value);
6583 }
6597 case NodeTypeThisLiteral:6584 case NodeTypeThisLiteral:
6598 return ir_lval_wrap(irb, scope, ir_gen_this_literal(irb, scope, node), lval);6585 return ir_lval_wrap(irb, scope, ir_gen_this_literal(irb, scope, node), lval);
6599 case NodeTypeBoolLiteral:6586 case NodeTypeBoolLiteral:
6600 return ir_lval_wrap(irb, scope, ir_gen_bool_literal(irb, scope, node), lval);6587 return ir_lval_wrap(irb, scope, ir_gen_bool_literal(irb, scope, node), lval);
6601 case NodeTypeArrayType:6588 case NodeTypeArrayType:
6602 return ir_lval_wrap(irb, scope, ir_gen_array_type(irb, scope, node), lval);6589 return ir_lval_wrap(irb, scope, ir_gen_array_type(irb, scope, node), lval);
6590 case NodeTypePointerType:
6591 return ir_lval_wrap(irb, scope, ir_gen_pointer_type(irb, scope, node), lval);
6603 case NodeTypePromiseType:6592 case NodeTypePromiseType:
6604 return ir_lval_wrap(irb, scope, ir_gen_promise_type(irb, scope, node), lval);6593 return ir_lval_wrap(irb, scope, ir_gen_promise_type(irb, scope, node), lval);
6605 case NodeTypeStringLiteral:6594 case NodeTypeStringLiteral:
...@@ -6711,15 +6700,14 @@ bool ir_gen(CodeGen *codegen, AstNode *node, Scope *scope, IrExecutable *ir_exec...@@ -6711,15 +6700,14 @@ bool ir_gen(CodeGen *codegen, AstNode *node, Scope *scope, IrExecutable *ir_exec
6711 IrInstruction *coro_frame_type_value = ir_build_const_type(irb, coro_scope, node, coro_frame_type);6700 IrInstruction *coro_frame_type_value = ir_build_const_type(irb, coro_scope, node, coro_frame_type);
6712 // TODO mark this var decl as "no safety" e.g. disable initializing the undef value to 0xaa6701 // TODO mark this var decl as "no safety" e.g. disable initializing the undef value to 0xaa
6713 ir_build_var_decl(irb, coro_scope, node, promise_var, coro_frame_type_value, nullptr, undef);6702 ir_build_var_decl(irb, coro_scope, node, promise_var, coro_frame_type_value, nullptr, undef);
6714 coro_promise_ptr = ir_build_var_ptr(irb, coro_scope, node, promise_var, false, false);6703 coro_promise_ptr = ir_build_var_ptr(irb, coro_scope, node, promise_var);
67156704
6716 VariableTableEntry *await_handle_var = ir_create_var(irb, node, coro_scope, nullptr, false, false, true, const_bool_false);6705 VariableTableEntry *await_handle_var = ir_create_var(irb, node, coro_scope, nullptr, false, false, true, const_bool_false);
6717 IrInstruction *null_value = ir_build_const_null(irb, coro_scope, node);6706 IrInstruction *null_value = ir_build_const_null(irb, coro_scope, node);
6718 IrInstruction *await_handle_type_val = ir_build_const_type(irb, coro_scope, node,6707 IrInstruction *await_handle_type_val = ir_build_const_type(irb, coro_scope, node,
6719 get_maybe_type(irb->codegen, irb->codegen->builtin_types.entry_promise));6708 get_maybe_type(irb->codegen, irb->codegen->builtin_types.entry_promise));
6720 ir_build_var_decl(irb, coro_scope, node, await_handle_var, await_handle_type_val, nullptr, null_value);6709 ir_build_var_decl(irb, coro_scope, node, await_handle_var, await_handle_type_val, nullptr, null_value);
6721 irb->exec->await_handle_var_ptr = ir_build_var_ptr(irb, coro_scope, node,6710 irb->exec->await_handle_var_ptr = ir_build_var_ptr(irb, coro_scope, node, await_handle_var);
6722 await_handle_var, false, false);
67236711
6724 u8_ptr_type = ir_build_const_type(irb, coro_scope, node,6712 u8_ptr_type = ir_build_const_type(irb, coro_scope, node,
6725 get_pointer_to_type(irb->codegen, irb->codegen->builtin_types.entry_u8, false));6713 get_pointer_to_type(irb->codegen, irb->codegen->builtin_types.entry_u8, false));
...@@ -6821,9 +6809,13 @@ bool ir_gen(CodeGen *codegen, AstNode *node, Scope *scope, IrExecutable *ir_exec...@@ -6821,9 +6809,13 @@ bool ir_gen(CodeGen *codegen, AstNode *node, Scope *scope, IrExecutable *ir_exec
68216809
6822 ir_set_cursor_at_end_and_append_block(irb, irb->exec->coro_normal_final);6810 ir_set_cursor_at_end_and_append_block(irb, irb->exec->coro_normal_final);
6823 if (type_has_bits(return_type)) {6811 if (type_has_bits(return_type)) {
6812 IrInstruction *u8_ptr_type_unknown_len = ir_build_const_type(irb, scope, node,
6813 get_pointer_to_type_extra(irb->codegen, irb->codegen->builtin_types.entry_u8,
6814 false, false, PtrLenUnknown, get_abi_alignment(irb->codegen, irb->codegen->builtin_types.entry_u8),
6815 0, 0));
6824 IrInstruction *result_ptr = ir_build_load_ptr(irb, scope, node, irb->exec->coro_result_ptr_field_ptr);6816 IrInstruction *result_ptr = ir_build_load_ptr(irb, scope, node, irb->exec->coro_result_ptr_field_ptr);
6825 IrInstruction *result_ptr_as_u8_ptr = ir_build_ptr_cast(irb, scope, node, u8_ptr_type, result_ptr);6817 IrInstruction *result_ptr_as_u8_ptr = ir_build_ptr_cast(irb, scope, node, u8_ptr_type_unknown_len, result_ptr);
6826 IrInstruction *return_value_ptr_as_u8_ptr = ir_build_ptr_cast(irb, scope, node, u8_ptr_type,6818 IrInstruction *return_value_ptr_as_u8_ptr = ir_build_ptr_cast(irb, scope, node, u8_ptr_type_unknown_len,
6827 irb->exec->coro_result_field_ptr);6819 irb->exec->coro_result_field_ptr);
6828 IrInstruction *return_type_inst = ir_build_const_type(irb, scope, node,6820 IrInstruction *return_type_inst = ir_build_const_type(irb, scope, node,
6829 fn_entry->type_entry->data.fn.fn_type_id.return_type);6821 fn_entry->type_entry->data.fn.fn_type_id.return_type);
...@@ -6859,7 +6851,7 @@ bool ir_gen(CodeGen *codegen, AstNode *node, Scope *scope, IrExecutable *ir_exec...@@ -6859,7 +6851,7 @@ bool ir_gen(CodeGen *codegen, AstNode *node, Scope *scope, IrExecutable *ir_exec
6859 IrInstruction *coro_mem_ptr_maybe = ir_build_coro_free(irb, scope, node, coro_id, irb->exec->coro_handle);6851 IrInstruction *coro_mem_ptr_maybe = ir_build_coro_free(irb, scope, node, coro_id, irb->exec->coro_handle);
6860 IrInstruction *coro_mem_ptr = ir_build_ptr_cast(irb, scope, node, u8_ptr_type, coro_mem_ptr_maybe);6852 IrInstruction *coro_mem_ptr = ir_build_ptr_cast(irb, scope, node, u8_ptr_type, coro_mem_ptr_maybe);
6861 IrInstruction *coro_mem_ptr_ref = ir_build_ref(irb, scope, node, coro_mem_ptr, true, false);6853 IrInstruction *coro_mem_ptr_ref = ir_build_ref(irb, scope, node, coro_mem_ptr, true, false);
6862 IrInstruction *coro_size_ptr = ir_build_var_ptr(irb, scope, node, coro_size_var, true, false);6854 IrInstruction *coro_size_ptr = ir_build_var_ptr(irb, scope, node, coro_size_var);
6863 IrInstruction *coro_size = ir_build_load_ptr(irb, scope, node, coro_size_ptr);6855 IrInstruction *coro_size = ir_build_load_ptr(irb, scope, node, coro_size_ptr);
6864 IrInstruction *mem_slice = ir_build_slice(irb, scope, node, coro_mem_ptr_ref, zero, coro_size, false);6856 IrInstruction *mem_slice = ir_build_slice(irb, scope, node, coro_mem_ptr_ref, zero, coro_size, false);
6865 size_t arg_count = 2;6857 size_t arg_count = 2;
...@@ -7633,38 +7625,16 @@ static bool slice_is_const(TypeTableEntry *type) {...@@ -7633,38 +7625,16 @@ static bool slice_is_const(TypeTableEntry *type) {
7633 return type->data.structure.fields[slice_ptr_index].type_entry->data.pointer.is_const;7625 return type->data.structure.fields[slice_ptr_index].type_entry->data.pointer.is_const;
7634}7626}
76357627
7636static bool resolve_inferred_error_set(IrAnalyze *ira, TypeTableEntry *err_set_type, AstNode *source_node) {
7637 assert(err_set_type->id == TypeTableEntryIdErrorSet);
7638 FnTableEntry *infer_fn = err_set_type->data.error_set.infer_fn;
7639 if (infer_fn != nullptr) {
7640 if (infer_fn->anal_state == FnAnalStateInvalid) {
7641 return false;
7642 } else if (infer_fn->anal_state == FnAnalStateReady) {
7643 analyze_fn_body(ira->codegen, infer_fn);
7644 if (err_set_type->data.error_set.infer_fn != nullptr) {
7645 assert(ira->codegen->errors.length != 0);
7646 return false;
7647 }
7648 } else {
7649 ir_add_error_node(ira, source_node,
7650 buf_sprintf("cannot resolve inferred error set '%s': function '%s' not fully analyzed yet",
7651 buf_ptr(&err_set_type->name), buf_ptr(&err_set_type->data.error_set.infer_fn->symbol_name)));
7652 return false;
7653 }
7654 }
7655 return true;
7656}
7657
7658static TypeTableEntry *get_error_set_intersection(IrAnalyze *ira, TypeTableEntry *set1, TypeTableEntry *set2,7628static TypeTableEntry *get_error_set_intersection(IrAnalyze *ira, TypeTableEntry *set1, TypeTableEntry *set2,
7659 AstNode *source_node)7629 AstNode *source_node)
7660{7630{
7661 assert(set1->id == TypeTableEntryIdErrorSet);7631 assert(set1->id == TypeTableEntryIdErrorSet);
7662 assert(set2->id == TypeTableEntryIdErrorSet);7632 assert(set2->id == TypeTableEntryIdErrorSet);
76637633
7664 if (!resolve_inferred_error_set(ira, set1, source_node)) {7634 if (!resolve_inferred_error_set(ira->codegen, set1, source_node)) {
7665 return ira->codegen->builtin_types.entry_invalid;7635 return ira->codegen->builtin_types.entry_invalid;
7666 }7636 }
7667 if (!resolve_inferred_error_set(ira, set2, source_node)) {7637 if (!resolve_inferred_error_set(ira->codegen, set2, source_node)) {
7668 return ira->codegen->builtin_types.entry_invalid;7638 return ira->codegen->builtin_types.entry_invalid;
7669 }7639 }
7670 if (type_is_global_error_set(set1)) {7640 if (type_is_global_error_set(set1)) {
...@@ -7723,6 +7693,7 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, TypeTableEntry...@@ -7723,6 +7693,7 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, TypeTableEntry
7723 // pointer const7693 // pointer const
7724 if (expected_type->id == TypeTableEntryIdPointer &&7694 if (expected_type->id == TypeTableEntryIdPointer &&
7725 actual_type->id == TypeTableEntryIdPointer &&7695 actual_type->id == TypeTableEntryIdPointer &&
7696 (actual_type->data.pointer.ptr_len == expected_type->data.pointer.ptr_len) &&
7726 (!actual_type->data.pointer.is_const || expected_type->data.pointer.is_const) &&7697 (!actual_type->data.pointer.is_const || expected_type->data.pointer.is_const) &&
7727 (!actual_type->data.pointer.is_volatile || expected_type->data.pointer.is_volatile) &&7698 (!actual_type->data.pointer.is_volatile || expected_type->data.pointer.is_volatile) &&
7728 actual_type->data.pointer.bit_offset == expected_type->data.pointer.bit_offset &&7699 actual_type->data.pointer.bit_offset == expected_type->data.pointer.bit_offset &&
...@@ -7803,7 +7774,7 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, TypeTableEntry...@@ -7803,7 +7774,7 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, TypeTableEntry
7803 return result;7774 return result;
7804 }7775 }
78057776
7806 if (!resolve_inferred_error_set(ira, contained_set, source_node)) {7777 if (!resolve_inferred_error_set(ira->codegen, contained_set, source_node)) {
7807 result.id = ConstCastResultIdUnresolvedInferredErrSet;7778 result.id = ConstCastResultIdUnresolvedInferredErrSet;
7808 return result;7779 return result;
7809 }7780 }
...@@ -7966,11 +7937,20 @@ static ImplicitCastMatchResult ir_types_match_with_implicit_cast(IrAnalyze *ira,...@@ -7966,11 +7937,20 @@ static ImplicitCastMatchResult ir_types_match_with_implicit_cast(IrAnalyze *ira,
7966 return ImplicitCastMatchResultReportedError;7937 return ImplicitCastMatchResultReportedError;
7967 }7938 }
79687939
7940 // implicit conversion from ?T to ?U
7941 if (expected_type->id == TypeTableEntryIdMaybe && actual_type->id == TypeTableEntryIdMaybe) {
7942 ImplicitCastMatchResult res = ir_types_match_with_implicit_cast(ira, expected_type->data.maybe.child_type,
7943 actual_type->data.maybe.child_type, value);
7944 if (res != ImplicitCastMatchResultNo)
7945 return res;
7946 }
7947
7969 // implicit conversion from non maybe type to maybe type7948 // implicit conversion from non maybe type to maybe type
7970 if (expected_type->id == TypeTableEntryIdMaybe &&7949 if (expected_type->id == TypeTableEntryIdMaybe) {
7971 ir_types_match_with_implicit_cast(ira, expected_type->data.maybe.child_type, actual_type, value))7950 ImplicitCastMatchResult res = ir_types_match_with_implicit_cast(ira, expected_type->data.maybe.child_type,
7972 {7951 actual_type, value);
7973 return ImplicitCastMatchResultYes;7952 if (res != ImplicitCastMatchResultNo)
7953 return res;
7974 }7954 }
79757955
7976 // implicit conversion from null literal to maybe type7956 // implicit conversion from null literal to maybe type
...@@ -8192,7 +8172,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod...@@ -8192,7 +8172,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod
8192 err_set_type = ira->codegen->builtin_types.entry_global_error_set;8172 err_set_type = ira->codegen->builtin_types.entry_global_error_set;
8193 } else {8173 } else {
8194 err_set_type = prev_inst->value.type;8174 err_set_type = prev_inst->value.type;
8195 if (!resolve_inferred_error_set(ira, err_set_type, prev_inst->source_node)) {8175 if (!resolve_inferred_error_set(ira->codegen, err_set_type, prev_inst->source_node)) {
8196 return ira->codegen->builtin_types.entry_invalid;8176 return ira->codegen->builtin_types.entry_invalid;
8197 }8177 }
8198 update_errors_helper(ira->codegen, &errors, &errors_count);8178 update_errors_helper(ira->codegen, &errors, &errors_count);
...@@ -8231,7 +8211,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod...@@ -8231,7 +8211,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod
8231 if (type_is_global_error_set(err_set_type)) {8211 if (type_is_global_error_set(err_set_type)) {
8232 continue;8212 continue;
8233 }8213 }
8234 if (!resolve_inferred_error_set(ira, cur_type, cur_inst->source_node)) {8214 if (!resolve_inferred_error_set(ira->codegen, cur_type, cur_inst->source_node)) {
8235 return ira->codegen->builtin_types.entry_invalid;8215 return ira->codegen->builtin_types.entry_invalid;
8236 }8216 }
8237 if (type_is_global_error_set(cur_type)) {8217 if (type_is_global_error_set(cur_type)) {
...@@ -8297,7 +8277,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod...@@ -8297,7 +8277,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod
8297 continue;8277 continue;
8298 }8278 }
8299 TypeTableEntry *cur_err_set_type = cur_type->data.error_union.err_set_type;8279 TypeTableEntry *cur_err_set_type = cur_type->data.error_union.err_set_type;
8300 if (!resolve_inferred_error_set(ira, cur_err_set_type, cur_inst->source_node)) {8280 if (!resolve_inferred_error_set(ira->codegen, cur_err_set_type, cur_inst->source_node)) {
8301 return ira->codegen->builtin_types.entry_invalid;8281 return ira->codegen->builtin_types.entry_invalid;
8302 }8282 }
8303 if (type_is_global_error_set(cur_err_set_type)) {8283 if (type_is_global_error_set(cur_err_set_type)) {
...@@ -8360,7 +8340,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod...@@ -8360,7 +8340,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod
8360 if (err_set_type != nullptr && type_is_global_error_set(err_set_type)) {8340 if (err_set_type != nullptr && type_is_global_error_set(err_set_type)) {
8361 continue;8341 continue;
8362 }8342 }
8363 if (!resolve_inferred_error_set(ira, cur_type, cur_inst->source_node)) {8343 if (!resolve_inferred_error_set(ira->codegen, cur_type, cur_inst->source_node)) {
8364 return ira->codegen->builtin_types.entry_invalid;8344 return ira->codegen->builtin_types.entry_invalid;
8365 }8345 }
83668346
...@@ -8417,11 +8397,11 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod...@@ -8417,11 +8397,11 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod
8417 TypeTableEntry *prev_err_set_type = (err_set_type == nullptr) ? prev_type->data.error_union.err_set_type : err_set_type;8397 TypeTableEntry *prev_err_set_type = (err_set_type == nullptr) ? prev_type->data.error_union.err_set_type : err_set_type;
8418 TypeTableEntry *cur_err_set_type = cur_type->data.error_union.err_set_type;8398 TypeTableEntry *cur_err_set_type = cur_type->data.error_union.err_set_type;
84198399
8420 if (!resolve_inferred_error_set(ira, prev_err_set_type, cur_inst->source_node)) {8400 if (!resolve_inferred_error_set(ira->codegen, prev_err_set_type, cur_inst->source_node)) {
8421 return ira->codegen->builtin_types.entry_invalid;8401 return ira->codegen->builtin_types.entry_invalid;
8422 }8402 }
84238403
8424 if (!resolve_inferred_error_set(ira, cur_err_set_type, cur_inst->source_node)) {8404 if (!resolve_inferred_error_set(ira->codegen, cur_err_set_type, cur_inst->source_node)) {
8425 return ira->codegen->builtin_types.entry_invalid;8405 return ira->codegen->builtin_types.entry_invalid;
8426 }8406 }
84278407
...@@ -8531,7 +8511,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod...@@ -8531,7 +8511,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod
8531 {8511 {
8532 if (err_set_type != nullptr) {8512 if (err_set_type != nullptr) {
8533 TypeTableEntry *cur_err_set_type = cur_type->data.error_union.err_set_type;8513 TypeTableEntry *cur_err_set_type = cur_type->data.error_union.err_set_type;
8534 if (!resolve_inferred_error_set(ira, cur_err_set_type, cur_inst->source_node)) {8514 if (!resolve_inferred_error_set(ira->codegen, cur_err_set_type, cur_inst->source_node)) {
8535 return ira->codegen->builtin_types.entry_invalid;8515 return ira->codegen->builtin_types.entry_invalid;
8536 }8516 }
8537 if (type_is_global_error_set(cur_err_set_type) || type_is_global_error_set(err_set_type)) {8517 if (type_is_global_error_set(cur_err_set_type) || type_is_global_error_set(err_set_type)) {
...@@ -8667,7 +8647,11 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod...@@ -8667,7 +8647,11 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod
86678647
8668 if (convert_to_const_slice) {8648 if (convert_to_const_slice) {
8669 assert(prev_inst->value.type->id == TypeTableEntryIdArray);8649 assert(prev_inst->value.type->id == TypeTableEntryIdArray);
8670 TypeTableEntry *ptr_type = get_pointer_to_type(ira->codegen, prev_inst->value.type->data.array.child_type, true);8650 TypeTableEntry *ptr_type = get_pointer_to_type_extra(
8651 ira->codegen, prev_inst->value.type->data.array.child_type,
8652 true, false, PtrLenUnknown,
8653 get_abi_alignment(ira->codegen, prev_inst->value.type->data.array.child_type),
8654 0, 0);
8671 TypeTableEntry *slice_type = get_slice_type(ira->codegen, ptr_type);8655 TypeTableEntry *slice_type = get_slice_type(ira->codegen, ptr_type);
8672 if (err_set_type != nullptr) {8656 if (err_set_type != nullptr) {
8673 return get_error_union_type(ira->codegen, err_set_type, slice_type);8657 return get_error_union_type(ira->codegen, err_set_type, slice_type);
...@@ -8983,34 +8967,15 @@ static IrInstruction *ir_get_const_ptr(IrAnalyze *ira, IrInstruction *instructio...@@ -8983,34 +8967,15 @@ static IrInstruction *ir_get_const_ptr(IrAnalyze *ira, IrInstruction *instructio
8983 ConstExprValue *pointee, TypeTableEntry *pointee_type,8967 ConstExprValue *pointee, TypeTableEntry *pointee_type,
8984 ConstPtrMut ptr_mut, bool ptr_is_const, bool ptr_is_volatile, uint32_t ptr_align)8968 ConstPtrMut ptr_mut, bool ptr_is_const, bool ptr_is_volatile, uint32_t ptr_align)
8985{8969{
8986 if (pointee_type->id == TypeTableEntryIdMetaType) {8970 TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, pointee_type,
8987 TypeTableEntry *type_entry = pointee->data.x_type;8971 ptr_is_const, ptr_is_volatile, PtrLenSingle, ptr_align, 0, 0);
8988 if (type_entry->id == TypeTableEntryIdUnreachable) {8972 IrInstruction *const_instr = ir_get_const(ira, instruction);
8989 ir_add_error(ira, instruction, buf_sprintf("pointer to noreturn not allowed"));8973 ConstExprValue *const_val = &const_instr->value;
8990 return ira->codegen->invalid_instruction;8974 const_val->type = ptr_type;
8991 }8975 const_val->data.x_ptr.special = ConstPtrSpecialRef;
89928976 const_val->data.x_ptr.mut = ptr_mut;
8993 IrInstruction *const_instr = ir_get_const(ira, instruction);8977 const_val->data.x_ptr.data.ref.pointee = pointee;
8994 ConstExprValue *const_val = &const_instr->value;8978 return const_instr;
8995 const_val->type = pointee_type;
8996 type_ensure_zero_bits_known(ira->codegen, type_entry);
8997 if (type_is_invalid(type_entry)) {
8998 return ira->codegen->invalid_instruction;
8999 }
9000 const_val->data.x_type = get_pointer_to_type_extra(ira->codegen, type_entry,
9001 ptr_is_const, ptr_is_volatile, get_abi_alignment(ira->codegen, type_entry), 0, 0);
9002 return const_instr;
9003 } else {
9004 TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, pointee_type,
9005 ptr_is_const, ptr_is_volatile, ptr_align, 0, 0);
9006 IrInstruction *const_instr = ir_get_const(ira, instruction);
9007 ConstExprValue *const_val = &const_instr->value;
9008 const_val->type = ptr_type;
9009 const_val->data.x_ptr.special = ConstPtrSpecialRef;
9010 const_val->data.x_ptr.mut = ptr_mut;
9011 const_val->data.x_ptr.data.ref.pointee = pointee;
9012 return const_instr;
9013 }
9014}8979}
90158980
9016static TypeTableEntry *ir_analyze_const_ptr(IrAnalyze *ira, IrInstruction *instruction,8981static TypeTableEntry *ir_analyze_const_ptr(IrAnalyze *ira, IrInstruction *instruction,
...@@ -9213,7 +9178,7 @@ static IrInstruction *ir_analyze_err_set_cast(IrAnalyze *ira, IrInstruction *sou...@@ -9213,7 +9178,7 @@ static IrInstruction *ir_analyze_err_set_cast(IrAnalyze *ira, IrInstruction *sou
9213 if (!val)9178 if (!val)
9214 return ira->codegen->invalid_instruction;9179 return ira->codegen->invalid_instruction;
92159180
9216 if (!resolve_inferred_error_set(ira, wanted_type, source_instr->source_node)) {9181 if (!resolve_inferred_error_set(ira->codegen, wanted_type, source_instr->source_node)) {
9217 return ira->codegen->invalid_instruction;9182 return ira->codegen->invalid_instruction;
9218 }9183 }
9219 if (!type_is_global_error_set(wanted_type)) {9184 if (!type_is_global_error_set(wanted_type)) {
...@@ -9338,14 +9303,13 @@ static IrInstruction *ir_get_ref(IrAnalyze *ira, IrInstruction *source_instructi...@@ -9338,14 +9303,13 @@ static IrInstruction *ir_get_ref(IrAnalyze *ira, IrInstruction *source_instructi
9338 ConstExprValue *val = ir_resolve_const(ira, value, UndefOk);9303 ConstExprValue *val = ir_resolve_const(ira, value, UndefOk);
9339 if (!val)9304 if (!val)
9340 return ira->codegen->invalid_instruction;9305 return ira->codegen->invalid_instruction;
9341 bool final_is_const = (value->value.type->id == TypeTableEntryIdMetaType) ? is_const : true;
9342 return ir_get_const_ptr(ira, source_instruction, val, value->value.type,9306 return ir_get_const_ptr(ira, source_instruction, val, value->value.type,
9343 ConstPtrMutComptimeConst, final_is_const, is_volatile,9307 ConstPtrMutComptimeConst, is_const, is_volatile,
9344 get_abi_alignment(ira->codegen, value->value.type));9308 get_abi_alignment(ira->codegen, value->value.type));
9345 }9309 }
93469310
9347 TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, value->value.type,9311 TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, value->value.type,
9348 is_const, is_volatile, get_abi_alignment(ira->codegen, value->value.type), 0, 0);9312 is_const, is_volatile, PtrLenSingle, get_abi_alignment(ira->codegen, value->value.type), 0, 0);
9349 IrInstruction *new_instruction = ir_build_ref(&ira->new_irb, source_instruction->scope,9313 IrInstruction *new_instruction = ir_build_ref(&ira->new_irb, source_instruction->scope,
9350 source_instruction->source_node, value, is_const, is_volatile);9314 source_instruction->source_node, value, is_const, is_volatile);
9351 new_instruction->value.type = ptr_type;9315 new_instruction->value.type = ptr_type;
...@@ -9485,6 +9449,8 @@ static IrInstruction *ir_analyze_enum_to_union(IrAnalyze *ira, IrInstruction *so...@@ -9485,6 +9449,8 @@ static IrInstruction *ir_analyze_enum_to_union(IrAnalyze *ira, IrInstruction *so
9485 TypeUnionField *union_field = find_union_field_by_tag(wanted_type, &val->data.x_enum_tag);9449 TypeUnionField *union_field = find_union_field_by_tag(wanted_type, &val->data.x_enum_tag);
9486 assert(union_field != nullptr);9450 assert(union_field != nullptr);
9487 type_ensure_zero_bits_known(ira->codegen, union_field->type_entry);9451 type_ensure_zero_bits_known(ira->codegen, union_field->type_entry);
9452 if (type_is_invalid(union_field->type_entry))
9453 return ira->codegen->invalid_instruction;
9488 if (!union_field->type_entry->zero_bits) {9454 if (!union_field->type_entry->zero_bits) {
9489 AstNode *field_node = wanted_type->data.unionation.decl_node->data.container_decl.fields.at(9455 AstNode *field_node = wanted_type->data.unionation.decl_node->data.container_decl.fields.at(
9490 union_field->enum_field->decl_index);9456 union_field->enum_field->decl_index);
...@@ -9654,7 +9620,7 @@ static IrInstruction *ir_analyze_int_to_err(IrAnalyze *ira, IrInstruction *sourc...@@ -9654,7 +9620,7 @@ static IrInstruction *ir_analyze_int_to_err(IrAnalyze *ira, IrInstruction *sourc
9654 IrInstruction *result = ir_create_const(&ira->new_irb, source_instr->scope,9620 IrInstruction *result = ir_create_const(&ira->new_irb, source_instr->scope,
9655 source_instr->source_node, wanted_type);9621 source_instr->source_node, wanted_type);
96569622
9657 if (!resolve_inferred_error_set(ira, wanted_type, source_instr->source_node)) {9623 if (!resolve_inferred_error_set(ira->codegen, wanted_type, source_instr->source_node)) {
9658 return ira->codegen->invalid_instruction;9624 return ira->codegen->invalid_instruction;
9659 }9625 }
96609626
...@@ -9752,7 +9718,7 @@ static IrInstruction *ir_analyze_err_to_int(IrAnalyze *ira, IrInstruction *sourc...@@ -9752,7 +9718,7 @@ static IrInstruction *ir_analyze_err_to_int(IrAnalyze *ira, IrInstruction *sourc
9752 zig_unreachable();9718 zig_unreachable();
9753 }9719 }
9754 if (!type_is_global_error_set(err_set_type)) {9720 if (!type_is_global_error_set(err_set_type)) {
9755 if (!resolve_inferred_error_set(ira, err_set_type, source_instr->source_node)) {9721 if (!resolve_inferred_error_set(ira->codegen, err_set_type, source_instr->source_node)) {
9756 return ira->codegen->invalid_instruction;9722 return ira->codegen->invalid_instruction;
9757 }9723 }
9758 if (err_set_type->data.error_set.err_count == 0) {9724 if (err_set_type->data.error_set.err_count == 0) {
...@@ -10067,6 +10033,9 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst...@@ -10067,6 +10033,9 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
10067 if (actual_type->id == TypeTableEntryIdNumLitFloat ||10033 if (actual_type->id == TypeTableEntryIdNumLitFloat ||
10068 actual_type->id == TypeTableEntryIdNumLitInt)10034 actual_type->id == TypeTableEntryIdNumLitInt)
10069 {10035 {
10036 ensure_complete_type(ira->codegen, wanted_type);
10037 if (type_is_invalid(wanted_type))
10038 return ira->codegen->invalid_instruction;
10070 if (wanted_type->id == TypeTableEntryIdEnum) {10039 if (wanted_type->id == TypeTableEntryIdEnum) {
10071 IrInstruction *cast1 = ir_analyze_cast(ira, source_instr, wanted_type->data.enumeration.tag_int_type, value);10040 IrInstruction *cast1 = ir_analyze_cast(ira, source_instr, wanted_type->data.enumeration.tag_int_type, value);
10072 if (type_is_invalid(cast1->value.type))10041 if (type_is_invalid(cast1->value.type))
...@@ -10269,21 +10238,6 @@ static IrInstruction *ir_get_deref(IrAnalyze *ira, IrInstruction *source_instruc...@@ -10269,21 +10238,6 @@ static IrInstruction *ir_get_deref(IrAnalyze *ira, IrInstruction *source_instruc
10269 source_instruction->source_node, ptr);10238 source_instruction->source_node, ptr);
10270 load_ptr_instruction->value.type = child_type;10239 load_ptr_instruction->value.type = child_type;
10271 return load_ptr_instruction;10240 return load_ptr_instruction;
10272 } else if (type_entry->id == TypeTableEntryIdMetaType) {
10273 ConstExprValue *ptr_val = ir_resolve_const(ira, ptr, UndefBad);
10274 if (!ptr_val)
10275 return ira->codegen->invalid_instruction;
10276
10277 TypeTableEntry *ptr_type = ptr_val->data.x_type;
10278 if (ptr_type->id == TypeTableEntryIdPointer) {
10279 TypeTableEntry *child_type = ptr_type->data.pointer.child_type;
10280 return ir_create_const_type(&ira->new_irb, source_instruction->scope,
10281 source_instruction->source_node, child_type);
10282 } else {
10283 ir_add_error(ira, source_instruction,
10284 buf_sprintf("attempt to dereference non pointer type '%s'", buf_ptr(&ptr_type->name)));
10285 return ira->codegen->invalid_instruction;
10286 }
10287 } else {10241 } else {
10288 ir_add_error_node(ira, source_instruction->source_node,10242 ir_add_error_node(ira, source_instruction->source_node,
10289 buf_sprintf("attempt to dereference non pointer type '%s'",10243 buf_sprintf("attempt to dereference non pointer type '%s'",
...@@ -10452,7 +10406,9 @@ static Buf *ir_resolve_str(IrAnalyze *ira, IrInstruction *value) {...@@ -10452,7 +10406,9 @@ static Buf *ir_resolve_str(IrAnalyze *ira, IrInstruction *value) {
10452 if (type_is_invalid(value->value.type))10406 if (type_is_invalid(value->value.type))
10453 return nullptr;10407 return nullptr;
1045410408
10455 TypeTableEntry *ptr_type = get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, true);10409 TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, ira->codegen->builtin_types.entry_u8,
10410 true, false, PtrLenUnknown,
10411 get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8), 0, 0);
10456 TypeTableEntry *str_type = get_slice_type(ira->codegen, ptr_type);10412 TypeTableEntry *str_type = get_slice_type(ira->codegen, ptr_type);
10457 IrInstruction *casted_value = ir_implicit_cast(ira, value, str_type);10413 IrInstruction *casted_value = ir_implicit_cast(ira, value, str_type);
10458 if (type_is_invalid(casted_value->value.type))10414 if (type_is_invalid(casted_value->value.type))
...@@ -10647,7 +10603,7 @@ static TypeTableEntry *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp...@@ -10647,7 +10603,7 @@ static TypeTableEntry *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp
10647 return ira->codegen->builtin_types.entry_invalid;10603 return ira->codegen->builtin_types.entry_invalid;
10648 }10604 }
1064910605
10650 if (!resolve_inferred_error_set(ira, intersect_type, source_node)) {10606 if (!resolve_inferred_error_set(ira->codegen, intersect_type, source_node)) {
10651 return ira->codegen->builtin_types.entry_invalid;10607 return ira->codegen->builtin_types.entry_invalid;
10652 }10608 }
1065310609
...@@ -11107,11 +11063,27 @@ static TypeTableEntry *ir_analyze_bit_shift(IrAnalyze *ira, IrInstructionBinOp *...@@ -11107,11 +11063,27 @@ static TypeTableEntry *ir_analyze_bit_shift(IrAnalyze *ira, IrInstructionBinOp *
11107static TypeTableEntry *ir_analyze_bin_op_math(IrAnalyze *ira, IrInstructionBinOp *bin_op_instruction) {11063static TypeTableEntry *ir_analyze_bin_op_math(IrAnalyze *ira, IrInstructionBinOp *bin_op_instruction) {
11108 IrInstruction *op1 = bin_op_instruction->op1->other;11064 IrInstruction *op1 = bin_op_instruction->op1->other;
11109 IrInstruction *op2 = bin_op_instruction->op2->other;11065 IrInstruction *op2 = bin_op_instruction->op2->other;
11066 IrBinOp op_id = bin_op_instruction->op_id;
11067
11068 // look for pointer math
11069 if (op1->value.type->id == TypeTableEntryIdPointer && op1->value.type->data.pointer.ptr_len == PtrLenUnknown &&
11070 (op_id == IrBinOpAdd || op_id == IrBinOpSub))
11071 {
11072 IrInstruction *casted_op2 = ir_implicit_cast(ira, op2, ira->codegen->builtin_types.entry_usize);
11073 if (casted_op2 == ira->codegen->invalid_instruction)
11074 return ira->codegen->builtin_types.entry_invalid;
11075
11076 IrInstruction *result = ir_build_bin_op(&ira->new_irb, bin_op_instruction->base.scope,
11077 bin_op_instruction->base.source_node, op_id, op1, casted_op2, true);
11078 result->value.type = op1->value.type;
11079 ir_link_new_instruction(result, &bin_op_instruction->base);
11080 return result->value.type;
11081 }
11082
11110 IrInstruction *instructions[] = {op1, op2};11083 IrInstruction *instructions[] = {op1, op2};
11111 TypeTableEntry *resolved_type = ir_resolve_peer_types(ira, bin_op_instruction->base.source_node, nullptr, instructions, 2);11084 TypeTableEntry *resolved_type = ir_resolve_peer_types(ira, bin_op_instruction->base.source_node, nullptr, instructions, 2);
11112 if (type_is_invalid(resolved_type))11085 if (type_is_invalid(resolved_type))
11113 return resolved_type;11086 return resolved_type;
11114 IrBinOp op_id = bin_op_instruction->op_id;
1111511087
11116 bool is_int = resolved_type->id == TypeTableEntryIdInt || resolved_type->id == TypeTableEntryIdNumLitInt;11088 bool is_int = resolved_type->id == TypeTableEntryIdInt || resolved_type->id == TypeTableEntryIdNumLitInt;
11117 bool is_float = resolved_type->id == TypeTableEntryIdFloat || resolved_type->id == TypeTableEntryIdNumLitFloat;11089 bool is_float = resolved_type->id == TypeTableEntryIdFloat || resolved_type->id == TypeTableEntryIdNumLitFloat;
...@@ -11384,7 +11356,8 @@ static TypeTableEntry *ir_analyze_array_cat(IrAnalyze *ira, IrInstructionBinOp *...@@ -11384,7 +11356,8 @@ static TypeTableEntry *ir_analyze_array_cat(IrAnalyze *ira, IrInstructionBinOp *
1138411356
11385 out_array_val = out_val;11357 out_array_val = out_val;
11386 } else if (is_slice(op1_type) || is_slice(op2_type)) {11358 } else if (is_slice(op1_type) || is_slice(op2_type)) {
11387 TypeTableEntry *ptr_type = get_pointer_to_type(ira->codegen, child_type, true);11359 TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, child_type,
11360 true, false, PtrLenUnknown, get_abi_alignment(ira->codegen, child_type), 0, 0);
11388 result_type = get_slice_type(ira->codegen, ptr_type);11361 result_type = get_slice_type(ira->codegen, ptr_type);
11389 out_array_val = create_const_vals(1);11362 out_array_val = create_const_vals(1);
11390 out_array_val->special = ConstValSpecialStatic;11363 out_array_val->special = ConstValSpecialStatic;
...@@ -11404,7 +11377,9 @@ static TypeTableEntry *ir_analyze_array_cat(IrAnalyze *ira, IrInstructionBinOp *...@@ -11404,7 +11377,9 @@ static TypeTableEntry *ir_analyze_array_cat(IrAnalyze *ira, IrInstructionBinOp *
11404 } else {11377 } else {
11405 new_len += 1; // null byte11378 new_len += 1; // null byte
1140611379
11407 result_type = get_pointer_to_type(ira->codegen, child_type, true);11380 // TODO make this `[*]null T` instead of `[*]T`
11381 result_type = get_pointer_to_type_extra(ira->codegen, child_type, true, false,
11382 PtrLenUnknown, get_abi_alignment(ira->codegen, child_type), 0, 0);
1140811383
11409 out_array_val = create_const_vals(1);11384 out_array_val = create_const_vals(1);
11410 out_array_val->special = ConstValSpecialStatic;11385 out_array_val->special = ConstValSpecialStatic;
...@@ -11503,11 +11478,11 @@ static TypeTableEntry *ir_analyze_merge_error_sets(IrAnalyze *ira, IrInstruction...@@ -11503,11 +11478,11 @@ static TypeTableEntry *ir_analyze_merge_error_sets(IrAnalyze *ira, IrInstruction
11503 return ira->codegen->builtin_types.entry_type;11478 return ira->codegen->builtin_types.entry_type;
11504 }11479 }
1150511480
11506 if (!resolve_inferred_error_set(ira, op1_type, instruction->op1->other->source_node)) {11481 if (!resolve_inferred_error_set(ira->codegen, op1_type, instruction->op1->other->source_node)) {
11507 return ira->codegen->builtin_types.entry_invalid;11482 return ira->codegen->builtin_types.entry_invalid;
11508 }11483 }
1150911484
11510 if (!resolve_inferred_error_set(ira, op2_type, instruction->op2->other->source_node)) {11485 if (!resolve_inferred_error_set(ira->codegen, op2_type, instruction->op2->other->source_node)) {
11511 return ira->codegen->builtin_types.entry_invalid;11486 return ira->codegen->builtin_types.entry_invalid;
11512 }11487 }
1151311488
...@@ -11990,7 +11965,7 @@ IrInstruction *ir_get_implicit_allocator(IrAnalyze *ira, IrInstruction *source_i...@@ -11990,7 +11965,7 @@ IrInstruction *ir_get_implicit_allocator(IrAnalyze *ira, IrInstruction *source_i
11990 {11965 {
11991 VariableTableEntry *coro_allocator_var = ira->old_irb.exec->coro_allocator_var;11966 VariableTableEntry *coro_allocator_var = ira->old_irb.exec->coro_allocator_var;
11992 assert(coro_allocator_var != nullptr);11967 assert(coro_allocator_var != nullptr);
11993 IrInstruction *var_ptr_inst = ir_get_var_ptr(ira, source_instr, coro_allocator_var, true, false);11968 IrInstruction *var_ptr_inst = ir_get_var_ptr(ira, source_instr, coro_allocator_var);
11994 IrInstruction *result = ir_get_deref(ira, source_instr, var_ptr_inst);11969 IrInstruction *result = ir_get_deref(ira, source_instr, var_ptr_inst);
11995 assert(result->value.type != nullptr);11970 assert(result->value.type != nullptr);
11996 return result;11971 return result;
...@@ -12171,7 +12146,7 @@ static VariableTableEntry *get_fn_var_by_index(FnTableEntry *fn_entry, size_t in...@@ -12171,7 +12146,7 @@ static VariableTableEntry *get_fn_var_by_index(FnTableEntry *fn_entry, size_t in
12171}12146}
1217212147
12173static IrInstruction *ir_get_var_ptr(IrAnalyze *ira, IrInstruction *instruction,12148static IrInstruction *ir_get_var_ptr(IrAnalyze *ira, IrInstruction *instruction,
12174 VariableTableEntry *var, bool is_const_ptr, bool is_volatile_ptr)12149 VariableTableEntry *var)
12175{12150{
12176 if (var->mem_slot_index != SIZE_MAX && var->owner_exec->analysis == nullptr) {12151 if (var->mem_slot_index != SIZE_MAX && var->owner_exec->analysis == nullptr) {
12177 assert(ira->codegen->errors.length != 0);12152 assert(ira->codegen->errors.length != 0);
...@@ -12197,8 +12172,8 @@ static IrInstruction *ir_get_var_ptr(IrAnalyze *ira, IrInstruction *instruction,...@@ -12197,8 +12172,8 @@ static IrInstruction *ir_get_var_ptr(IrAnalyze *ira, IrInstruction *instruction,
12197 }12172 }
12198 }12173 }
1219912174
12200 bool is_const = (var->value->type->id == TypeTableEntryIdMetaType) ? is_const_ptr : var->src_is_const;12175 bool is_const = var->src_is_const;
12201 bool is_volatile = (var->value->type->id == TypeTableEntryIdMetaType) ? is_volatile_ptr : false;12176 bool is_volatile = false;
12202 if (mem_slot != nullptr) {12177 if (mem_slot != nullptr) {
12203 switch (mem_slot->special) {12178 switch (mem_slot->special) {
12204 case ConstValSpecialRuntime:12179 case ConstValSpecialRuntime:
...@@ -12224,9 +12199,9 @@ static IrInstruction *ir_get_var_ptr(IrAnalyze *ira, IrInstruction *instruction,...@@ -12224,9 +12199,9 @@ static IrInstruction *ir_get_var_ptr(IrAnalyze *ira, IrInstruction *instruction,
12224no_mem_slot:12199no_mem_slot:
1222512200
12226 IrInstruction *var_ptr_instruction = ir_build_var_ptr(&ira->new_irb,12201 IrInstruction *var_ptr_instruction = ir_build_var_ptr(&ira->new_irb,
12227 instruction->scope, instruction->source_node, var, is_const, is_volatile);12202 instruction->scope, instruction->source_node, var);
12228 var_ptr_instruction->value.type = get_pointer_to_type_extra(ira->codegen, var->value->type,12203 var_ptr_instruction->value.type = get_pointer_to_type_extra(ira->codegen, var->value->type,
12229 var->src_is_const, is_volatile, var->align_bytes, 0, 0);12204 var->src_is_const, is_volatile, PtrLenSingle, var->align_bytes, 0, 0);
12230 type_ensure_zero_bits_known(ira->codegen, var->value->type);12205 type_ensure_zero_bits_known(ira->codegen, var->value->type);
1223112206
12232 bool in_fn_scope = (scope_fn_entry(var->parent_scope) != nullptr);12207 bool in_fn_scope = (scope_fn_entry(var->parent_scope) != nullptr);
...@@ -12405,7 +12380,9 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal...@@ -12405,7 +12380,9 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal
1240512380
12406 IrInstruction *casted_new_stack = nullptr;12381 IrInstruction *casted_new_stack = nullptr;
12407 if (call_instruction->new_stack != nullptr) {12382 if (call_instruction->new_stack != nullptr) {
12408 TypeTableEntry *u8_ptr = get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, false);12383 TypeTableEntry *u8_ptr = get_pointer_to_type_extra(ira->codegen, ira->codegen->builtin_types.entry_u8,
12384 false, false, PtrLenUnknown,
12385 get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8), 0, 0);
12409 TypeTableEntry *u8_slice = get_slice_type(ira->codegen, u8_ptr);12386 TypeTableEntry *u8_slice = get_slice_type(ira->codegen, u8_ptr);
12410 IrInstruction *new_stack = call_instruction->new_stack->other;12387 IrInstruction *new_stack = call_instruction->new_stack->other;
12411 if (type_is_invalid(new_stack->value.type))12388 if (type_is_invalid(new_stack->value.type))
...@@ -12510,7 +12487,7 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal...@@ -12510,7 +12487,7 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal
12510 buf_sprintf("compiler bug: var args can't handle void. https://github.com/ziglang/zig/issues/557"));12487 buf_sprintf("compiler bug: var args can't handle void. https://github.com/ziglang/zig/issues/557"));
12511 return ira->codegen->builtin_types.entry_invalid;12488 return ira->codegen->builtin_types.entry_invalid;
12512 }12489 }
12513 IrInstruction *arg_var_ptr_inst = ir_get_var_ptr(ira, arg, arg_var, true, false);12490 IrInstruction *arg_var_ptr_inst = ir_get_var_ptr(ira, arg, arg_var);
12514 if (type_is_invalid(arg_var_ptr_inst->value.type))12491 if (type_is_invalid(arg_var_ptr_inst->value.type))
12515 return ira->codegen->builtin_types.entry_invalid;12492 return ira->codegen->builtin_types.entry_invalid;
1251612493
...@@ -12833,6 +12810,10 @@ static TypeTableEntry *ir_analyze_maybe(IrAnalyze *ira, IrInstructionUnOp *un_op...@@ -12833,6 +12810,10 @@ static TypeTableEntry *ir_analyze_maybe(IrAnalyze *ira, IrInstructionUnOp *un_op
12833 TypeTableEntry *type_entry = ir_resolve_type(ira, value);12810 TypeTableEntry *type_entry = ir_resolve_type(ira, value);
12834 if (type_is_invalid(type_entry))12811 if (type_is_invalid(type_entry))
12835 return ira->codegen->builtin_types.entry_invalid;12812 return ira->codegen->builtin_types.entry_invalid;
12813 ensure_complete_type(ira->codegen, type_entry);
12814 if (type_is_invalid(type_entry))
12815 return ira->codegen->builtin_types.entry_invalid;
12816
12836 switch (type_entry->id) {12817 switch (type_entry->id) {
12837 case TypeTableEntryIdInvalid:12818 case TypeTableEntryIdInvalid:
12838 zig_unreachable();12819 zig_unreachable();
...@@ -13144,17 +13125,16 @@ static TypeTableEntry *ir_analyze_instruction_phi(IrAnalyze *ira, IrInstructionP...@@ -13144,17 +13125,16 @@ static TypeTableEntry *ir_analyze_instruction_phi(IrAnalyze *ira, IrInstructionP
13144}13125}
1314513126
13146static TypeTableEntry *ir_analyze_var_ptr(IrAnalyze *ira, IrInstruction *instruction,13127static TypeTableEntry *ir_analyze_var_ptr(IrAnalyze *ira, IrInstruction *instruction,
13147 VariableTableEntry *var, bool is_const_ptr, bool is_volatile_ptr)13128 VariableTableEntry *var)
13148{13129{
13149 IrInstruction *result = ir_get_var_ptr(ira, instruction, var, is_const_ptr, is_volatile_ptr);13130 IrInstruction *result = ir_get_var_ptr(ira, instruction, var);
13150 ir_link_new_instruction(result, instruction);13131 ir_link_new_instruction(result, instruction);
13151 return result->value.type;13132 return result->value.type;
13152}13133}
1315313134
13154static TypeTableEntry *ir_analyze_instruction_var_ptr(IrAnalyze *ira, IrInstructionVarPtr *var_ptr_instruction) {13135static TypeTableEntry *ir_analyze_instruction_var_ptr(IrAnalyze *ira, IrInstructionVarPtr *var_ptr_instruction) {
13155 VariableTableEntry *var = var_ptr_instruction->var;13136 VariableTableEntry *var = var_ptr_instruction->var;
13156 return ir_analyze_var_ptr(ira, &var_ptr_instruction->base, var, var_ptr_instruction->is_const,13137 return ir_analyze_var_ptr(ira, &var_ptr_instruction->base, var);
13157 var_ptr_instruction->is_volatile);
13158}13138}
1315913139
13160static TypeTableEntry *adjust_ptr_align(CodeGen *g, TypeTableEntry *ptr_type, uint32_t new_align) {13140static TypeTableEntry *adjust_ptr_align(CodeGen *g, TypeTableEntry *ptr_type, uint32_t new_align) {
...@@ -13162,10 +13142,21 @@ static TypeTableEntry *adjust_ptr_align(CodeGen *g, TypeTableEntry *ptr_type, ui...@@ -13162,10 +13142,21 @@ static TypeTableEntry *adjust_ptr_align(CodeGen *g, TypeTableEntry *ptr_type, ui
13162 return get_pointer_to_type_extra(g,13142 return get_pointer_to_type_extra(g,
13163 ptr_type->data.pointer.child_type,13143 ptr_type->data.pointer.child_type,
13164 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,13144 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,
13145 ptr_type->data.pointer.ptr_len,
13165 new_align,13146 new_align,
13166 ptr_type->data.pointer.bit_offset, ptr_type->data.pointer.unaligned_bit_count);13147 ptr_type->data.pointer.bit_offset, ptr_type->data.pointer.unaligned_bit_count);
13167}13148}
1316813149
13150static TypeTableEntry *adjust_ptr_len(CodeGen *g, TypeTableEntry *ptr_type, PtrLen ptr_len) {
13151 assert(ptr_type->id == TypeTableEntryIdPointer);
13152 return get_pointer_to_type_extra(g,
13153 ptr_type->data.pointer.child_type,
13154 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,
13155 ptr_len,
13156 ptr_type->data.pointer.alignment,
13157 ptr_type->data.pointer.bit_offset, ptr_type->data.pointer.unaligned_bit_count);
13158}
13159
13169static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstructionElemPtr *elem_ptr_instruction) {13160static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstructionElemPtr *elem_ptr_instruction) {
13170 IrInstruction *array_ptr = elem_ptr_instruction->array_ptr->other;13161 IrInstruction *array_ptr = elem_ptr_instruction->array_ptr->other;
13171 if (type_is_invalid(array_ptr->value.type))13162 if (type_is_invalid(array_ptr->value.type))
...@@ -13176,11 +13167,6 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc...@@ -13176,11 +13167,6 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc
13176 return ira->codegen->builtin_types.entry_invalid;13167 return ira->codegen->builtin_types.entry_invalid;
1317713168
13178 TypeTableEntry *ptr_type = array_ptr->value.type;13169 TypeTableEntry *ptr_type = array_ptr->value.type;
13179 if (ptr_type->id == TypeTableEntryIdMetaType) {
13180 ir_add_error(ira, &elem_ptr_instruction->base,
13181 buf_sprintf("array access of non-array type '%s'", buf_ptr(&ptr_type->name)));
13182 return ira->codegen->builtin_types.entry_invalid;
13183 }
13184 assert(ptr_type->id == TypeTableEntryIdPointer);13170 assert(ptr_type->id == TypeTableEntryIdPointer);
1318513171
13186 TypeTableEntry *array_type = ptr_type->data.pointer.child_type;13172 TypeTableEntry *array_type = ptr_type->data.pointer.child_type;
...@@ -13201,6 +13187,7 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc...@@ -13201,6 +13187,7 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc
13201 if (ptr_type->data.pointer.unaligned_bit_count == 0) {13187 if (ptr_type->data.pointer.unaligned_bit_count == 0) {
13202 return_type = get_pointer_to_type_extra(ira->codegen, child_type,13188 return_type = get_pointer_to_type_extra(ira->codegen, child_type,
13203 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,13189 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,
13190 elem_ptr_instruction->ptr_len,
13204 ptr_type->data.pointer.alignment, 0, 0);13191 ptr_type->data.pointer.alignment, 0, 0);
13205 } else {13192 } else {
13206 uint64_t elem_val_scalar;13193 uint64_t elem_val_scalar;
...@@ -13212,12 +13199,19 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc...@@ -13212,12 +13199,19 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc
1321213199
13213 return_type = get_pointer_to_type_extra(ira->codegen, child_type,13200 return_type = get_pointer_to_type_extra(ira->codegen, child_type,
13214 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,13201 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,
13202 elem_ptr_instruction->ptr_len,
13215 1, (uint32_t)bit_offset, (uint32_t)bit_width);13203 1, (uint32_t)bit_offset, (uint32_t)bit_width);
13216 }13204 }
13217 } else if (array_type->id == TypeTableEntryIdPointer) {13205 } else if (array_type->id == TypeTableEntryIdPointer) {
13218 return_type = array_type;13206 if (array_type->data.pointer.ptr_len == PtrLenSingle) {
13207 ir_add_error_node(ira, elem_ptr_instruction->base.source_node,
13208 buf_sprintf("indexing not allowed on pointer to single item"));
13209 return ira->codegen->builtin_types.entry_invalid;
13210 }
13211 return_type = adjust_ptr_len(ira->codegen, array_type, elem_ptr_instruction->ptr_len);
13219 } else if (is_slice(array_type)) {13212 } else if (is_slice(array_type)) {
13220 return_type = array_type->data.structure.fields[slice_ptr_index].type_entry;13213 return_type = adjust_ptr_len(ira->codegen, array_type->data.structure.fields[slice_ptr_index].type_entry,
13214 elem_ptr_instruction->ptr_len);
13221 } else if (array_type->id == TypeTableEntryIdArgTuple) {13215 } else if (array_type->id == TypeTableEntryIdArgTuple) {
13222 ConstExprValue *ptr_val = ir_resolve_const(ira, array_ptr, UndefBad);13216 ConstExprValue *ptr_val = ir_resolve_const(ira, array_ptr, UndefBad);
13223 if (!ptr_val)13217 if (!ptr_val)
...@@ -13242,8 +13236,7 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc...@@ -13242,8 +13236,7 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc
13242 bool is_const = true;13236 bool is_const = true;
13243 bool is_volatile = false;13237 bool is_volatile = false;
13244 if (var) {13238 if (var) {
13245 return ir_analyze_var_ptr(ira, &elem_ptr_instruction->base, var,13239 return ir_analyze_var_ptr(ira, &elem_ptr_instruction->base, var);
13246 is_const, is_volatile);
13247 } else {13240 } else {
13248 return ir_analyze_const_ptr(ira, &elem_ptr_instruction->base, &ira->codegen->const_void_val,13241 return ir_analyze_const_ptr(ira, &elem_ptr_instruction->base, &ira->codegen->const_void_val,
13249 ira->codegen->builtin_types.entry_void, ConstPtrMutComptimeConst, is_const, is_volatile);13242 ira->codegen->builtin_types.entry_void, ConstPtrMutComptimeConst, is_const, is_volatile);
...@@ -13261,6 +13254,9 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc...@@ -13261,6 +13254,9 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc
1326113254
13262 bool safety_check_on = elem_ptr_instruction->safety_check_on;13255 bool safety_check_on = elem_ptr_instruction->safety_check_on;
13263 ensure_complete_type(ira->codegen, return_type->data.pointer.child_type);13256 ensure_complete_type(ira->codegen, return_type->data.pointer.child_type);
13257 if (type_is_invalid(return_type->data.pointer.child_type))
13258 return ira->codegen->builtin_types.entry_invalid;
13259
13264 uint64_t elem_size = type_size(ira->codegen, return_type->data.pointer.child_type);13260 uint64_t elem_size = type_size(ira->codegen, return_type->data.pointer.child_type);
13265 uint64_t abi_align = get_abi_alignment(ira->codegen, return_type->data.pointer.child_type);13261 uint64_t abi_align = get_abi_alignment(ira->codegen, return_type->data.pointer.child_type);
13266 uint64_t ptr_align = return_type->data.pointer.alignment;13262 uint64_t ptr_align = return_type->data.pointer.alignment;
...@@ -13357,8 +13353,10 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc...@@ -13357,8 +13353,10 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc
13357 } else if (is_slice(array_type)) {13353 } else if (is_slice(array_type)) {
13358 ConstExprValue *ptr_field = &array_ptr_val->data.x_struct.fields[slice_ptr_index];13354 ConstExprValue *ptr_field = &array_ptr_val->data.x_struct.fields[slice_ptr_index];
13359 if (ptr_field->data.x_ptr.special == ConstPtrSpecialHardCodedAddr) {13355 if (ptr_field->data.x_ptr.special == ConstPtrSpecialHardCodedAddr) {
13360 ir_build_elem_ptr_from(&ira->new_irb, &elem_ptr_instruction->base, array_ptr,13356 IrInstruction *result = ir_build_elem_ptr(&ira->new_irb, elem_ptr_instruction->base.scope, elem_ptr_instruction->base.source_node,
13361 casted_elem_index, false);13357 array_ptr, casted_elem_index, false, elem_ptr_instruction->ptr_len);
13358 result->value.type = return_type;
13359 ir_link_new_instruction(result, &elem_ptr_instruction->base);
13362 return return_type;13360 return return_type;
13363 }13361 }
13364 ConstExprValue *len_field = &array_ptr_val->data.x_struct.fields[slice_len_index];13362 ConstExprValue *len_field = &array_ptr_val->data.x_struct.fields[slice_len_index];
...@@ -13426,8 +13424,10 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc...@@ -13426,8 +13424,10 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc
13426 }13424 }
13427 }13425 }
1342813426
13429 ir_build_elem_ptr_from(&ira->new_irb, &elem_ptr_instruction->base, array_ptr,13427 IrInstruction *result = ir_build_elem_ptr(&ira->new_irb, elem_ptr_instruction->base.scope, elem_ptr_instruction->base.source_node,
13430 casted_elem_index, safety_check_on);13428 array_ptr, casted_elem_index, safety_check_on, elem_ptr_instruction->ptr_len);
13429 result->value.type = return_type;
13430 ir_link_new_instruction(result, &elem_ptr_instruction->base);
13431 return return_type;13431 return return_type;
13432}13432}
1343313433
...@@ -13502,7 +13502,7 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_...@@ -13502,7 +13502,7 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_
13502 return ira->codegen->invalid_instruction;13502 return ira->codegen->invalid_instruction;
13503 ConstExprValue *field_val = &struct_val->data.x_struct.fields[field->src_index];13503 ConstExprValue *field_val = &struct_val->data.x_struct.fields[field->src_index];
13504 TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, field_val->type,13504 TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, field_val->type,
13505 is_const, is_volatile, align_bytes,13505 is_const, is_volatile, PtrLenSingle, align_bytes,
13506 (uint32_t)(ptr_bit_offset + field->packed_bits_offset),13506 (uint32_t)(ptr_bit_offset + field->packed_bits_offset),
13507 (uint32_t)unaligned_bit_count_for_result_type);13507 (uint32_t)unaligned_bit_count_for_result_type);
13508 IrInstruction *result = ir_get_const(ira, source_instr);13508 IrInstruction *result = ir_get_const(ira, source_instr);
...@@ -13518,6 +13518,7 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_...@@ -13518,6 +13518,7 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_
13518 IrInstruction *result = ir_build_struct_field_ptr(&ira->new_irb, source_instr->scope, source_instr->source_node,13518 IrInstruction *result = ir_build_struct_field_ptr(&ira->new_irb, source_instr->scope, source_instr->source_node,
13519 container_ptr, field);13519 container_ptr, field);
13520 result->value.type = get_pointer_to_type_extra(ira->codegen, field->type_entry, is_const, is_volatile,13520 result->value.type = get_pointer_to_type_extra(ira->codegen, field->type_entry, is_const, is_volatile,
13521 PtrLenSingle,
13521 align_bytes,13522 align_bytes,
13522 (uint32_t)(ptr_bit_offset + field->packed_bits_offset),13523 (uint32_t)(ptr_bit_offset + field->packed_bits_offset),
13523 (uint32_t)unaligned_bit_count_for_result_type);13524 (uint32_t)unaligned_bit_count_for_result_type);
...@@ -13564,7 +13565,9 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_...@@ -13564,7 +13565,9 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_
13564 payload_val->type = field_type;13565 payload_val->type = field_type;
13565 }13566 }
1356613567
13567 TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, field_type, is_const, is_volatile,13568 TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, field_type,
13569 is_const, is_volatile,
13570 PtrLenSingle,
13568 get_abi_alignment(ira->codegen, field_type), 0, 0);13571 get_abi_alignment(ira->codegen, field_type), 0, 0);
1356913572
13570 IrInstruction *result = ir_get_const(ira, source_instr);13573 IrInstruction *result = ir_get_const(ira, source_instr);
...@@ -13579,7 +13582,7 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_...@@ -13579,7 +13582,7 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_
1357913582
13580 IrInstruction *result = ir_build_union_field_ptr(&ira->new_irb, source_instr->scope, source_instr->source_node, container_ptr, field);13583 IrInstruction *result = ir_build_union_field_ptr(&ira->new_irb, source_instr->scope, source_instr->source_node, container_ptr, field);
13581 result->value.type = get_pointer_to_type_extra(ira->codegen, field->type_entry, is_const, is_volatile,13584 result->value.type = get_pointer_to_type_extra(ira->codegen, field->type_entry, is_const, is_volatile,
13582 get_abi_alignment(ira->codegen, field->type_entry), 0, 0);13585 PtrLenSingle, get_abi_alignment(ira->codegen, field->type_entry), 0, 0);
13583 return result;13586 return result;
13584 } else {13587 } else {
13585 return ir_analyze_container_member_access_inner(ira, bare_type, field_name,13588 return ir_analyze_container_member_access_inner(ira, bare_type, field_name,
...@@ -13627,7 +13630,7 @@ static TypeTableEntry *ir_analyze_decl_ref(IrAnalyze *ira, IrInstruction *source...@@ -13627,7 +13630,7 @@ static TypeTableEntry *ir_analyze_decl_ref(IrAnalyze *ira, IrInstruction *source
13627 add_link_lib_symbol(ira, tld_var->extern_lib_name, &var->name, source_instruction->source_node);13630 add_link_lib_symbol(ira, tld_var->extern_lib_name, &var->name, source_instruction->source_node);
13628 }13631 }
1362913632
13630 return ir_analyze_var_ptr(ira, source_instruction, var, false, false);13633 return ir_analyze_var_ptr(ira, source_instruction, var);
13631 }13634 }
13632 case TldIdFn:13635 case TldIdFn:
13633 {13636 {
...@@ -13676,14 +13679,8 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru...@@ -13676,14 +13679,8 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru
13676 if (type_is_invalid(container_ptr->value.type))13679 if (type_is_invalid(container_ptr->value.type))
13677 return ira->codegen->builtin_types.entry_invalid;13680 return ira->codegen->builtin_types.entry_invalid;
1367813681
13679 TypeTableEntry *container_type;13682 TypeTableEntry *container_type = container_ptr->value.type->data.pointer.child_type;
13680 if (container_ptr->value.type->id == TypeTableEntryIdPointer) {13683 assert(container_ptr->value.type->id == TypeTableEntryIdPointer);
13681 container_type = container_ptr->value.type->data.pointer.child_type;
13682 } else if (container_ptr->value.type->id == TypeTableEntryIdMetaType) {
13683 container_type = container_ptr->value.type;
13684 } else {
13685 zig_unreachable();
13686 }
1368713684
13688 Buf *field_name = field_ptr_instruction->field_name_buffer;13685 Buf *field_name = field_ptr_instruction->field_name_buffer;
13689 if (!field_name) {13686 if (!field_name) {
...@@ -13756,17 +13753,9 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru...@@ -13756,17 +13753,9 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru
13756 if (!container_ptr_val)13753 if (!container_ptr_val)
13757 return ira->codegen->builtin_types.entry_invalid;13754 return ira->codegen->builtin_types.entry_invalid;
1375813755
13759 TypeTableEntry *child_type;13756 assert(container_ptr->value.type->id == TypeTableEntryIdPointer);
13760 if (container_ptr->value.type->id == TypeTableEntryIdMetaType) {13757 ConstExprValue *child_val = const_ptr_pointee(ira->codegen, container_ptr_val);
13761 TypeTableEntry *ptr_type = container_ptr_val->data.x_type;13758 TypeTableEntry *child_type = child_val->data.x_type;
13762 assert(ptr_type->id == TypeTableEntryIdPointer);
13763 child_type = ptr_type->data.pointer.child_type;
13764 } else if (container_ptr->value.type->id == TypeTableEntryIdPointer) {
13765 ConstExprValue *child_val = const_ptr_pointee(ira->codegen, container_ptr_val);
13766 child_type = child_val->data.x_type;
13767 } else {
13768 zig_unreachable();
13769 }
1377013759
13771 if (type_is_invalid(child_type)) {13760 if (type_is_invalid(child_type)) {
13772 return ira->codegen->builtin_types.entry_invalid;13761 return ira->codegen->builtin_types.entry_invalid;
...@@ -13784,7 +13773,7 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru...@@ -13784,7 +13773,7 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru
13784 }13773 }
13785 if (child_type->id == TypeTableEntryIdEnum) {13774 if (child_type->id == TypeTableEntryIdEnum) {
13786 ensure_complete_type(ira->codegen, child_type);13775 ensure_complete_type(ira->codegen, child_type);
13787 if (child_type->data.enumeration.is_invalid)13776 if (type_is_invalid(child_type))
13788 return ira->codegen->builtin_types.entry_invalid;13777 return ira->codegen->builtin_types.entry_invalid;
1378913778
13790 TypeEnumField *field = find_enum_type_field(child_type, field_name);13779 TypeEnumField *field = find_enum_type_field(child_type, field_name);
...@@ -13851,7 +13840,7 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru...@@ -13851,7 +13840,7 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru
13851 }13840 }
13852 err_set_type = err_entry->set_with_only_this_in_it;13841 err_set_type = err_entry->set_with_only_this_in_it;
13853 } else {13842 } else {
13854 if (!resolve_inferred_error_set(ira, child_type, field_ptr_instruction->base.source_node)) {13843 if (!resolve_inferred_error_set(ira->codegen, child_type, field_ptr_instruction->base.source_node)) {
13855 return ira->codegen->builtin_types.entry_invalid;13844 return ira->codegen->builtin_types.entry_invalid;
13856 }13845 }
13857 err_entry = find_err_table_entry(child_type, field_name);13846 err_entry = find_err_table_entry(child_type, field_name);
...@@ -14186,7 +14175,7 @@ static TypeTableEntry *ir_analyze_instruction_to_ptr_type(IrAnalyze *ira,...@@ -14186,7 +14175,7 @@ static TypeTableEntry *ir_analyze_instruction_to_ptr_type(IrAnalyze *ira,
14186 if (type_entry->id == TypeTableEntryIdArray) {14175 if (type_entry->id == TypeTableEntryIdArray) {
14187 ptr_type = get_pointer_to_type(ira->codegen, type_entry->data.array.child_type, false);14176 ptr_type = get_pointer_to_type(ira->codegen, type_entry->data.array.child_type, false);
14188 } else if (is_slice(type_entry)) {14177 } else if (is_slice(type_entry)) {
14189 ptr_type = type_entry->data.structure.fields[0].type_entry;14178 ptr_type = adjust_ptr_len(ira->codegen, type_entry->data.structure.fields[0].type_entry, PtrLenSingle);
14190 } else if (type_entry->id == TypeTableEntryIdArgTuple) {14179 } else if (type_entry->id == TypeTableEntryIdArgTuple) {
14191 ConstExprValue *arg_tuple_val = ir_resolve_const(ira, value, UndefBad);14180 ConstExprValue *arg_tuple_val = ir_resolve_const(ira, value, UndefBad);
14192 if (!arg_tuple_val)14181 if (!arg_tuple_val)
...@@ -14434,7 +14423,7 @@ static TypeTableEntry *ir_analyze_instruction_slice_type(IrAnalyze *ira,...@@ -14434,7 +14423,7 @@ static TypeTableEntry *ir_analyze_instruction_slice_type(IrAnalyze *ira,
14434 {14423 {
14435 type_ensure_zero_bits_known(ira->codegen, child_type);14424 type_ensure_zero_bits_known(ira->codegen, child_type);
14436 TypeTableEntry *slice_ptr_type = get_pointer_to_type_extra(ira->codegen, child_type,14425 TypeTableEntry *slice_ptr_type = get_pointer_to_type_extra(ira->codegen, child_type,
14437 is_const, is_volatile, align_bytes, 0, 0);14426 is_const, is_volatile, PtrLenUnknown, align_bytes, 0, 0);
14438 TypeTableEntry *result_type = get_slice_type(ira->codegen, slice_ptr_type);14427 TypeTableEntry *result_type = get_slice_type(ira->codegen, slice_ptr_type);
14439 ConstExprValue *out_val = ir_build_const_from(ira, &slice_type_instruction->base);14428 ConstExprValue *out_val = ir_build_const_from(ira, &slice_type_instruction->base);
14440 out_val->data.x_type = result_type;14429 out_val->data.x_type = result_type;
...@@ -14657,27 +14646,27 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_maybe(IrAnalyze *ira,...@@ -14657,27 +14646,27 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_maybe(IrAnalyze *ira,
14657 return ira->codegen->builtin_types.entry_invalid;14646 return ira->codegen->builtin_types.entry_invalid;
1465814647
14659 TypeTableEntry *ptr_type = value->value.type;14648 TypeTableEntry *ptr_type = value->value.type;
14660 if (ptr_type->id == TypeTableEntryIdMetaType) {14649 assert(ptr_type->id == TypeTableEntryIdPointer);
14650
14651 TypeTableEntry *type_entry = ptr_type->data.pointer.child_type;
14652 if (type_is_invalid(type_entry)) {
14653 return ira->codegen->builtin_types.entry_invalid;
14654 } else if (type_entry->id == TypeTableEntryIdMetaType) {
14661 // surprise! actually this is just ??T not an unwrap maybe instruction14655 // surprise! actually this is just ??T not an unwrap maybe instruction
14662 TypeTableEntry *ptr_type_ptr = ir_resolve_type(ira, value);14656 ConstExprValue *ptr_val = const_ptr_pointee(ira->codegen, &value->value);
14663 assert(ptr_type_ptr->id == TypeTableEntryIdPointer);14657 assert(ptr_val->type->id == TypeTableEntryIdMetaType);
14664 TypeTableEntry *child_type = ptr_type_ptr->data.pointer.child_type;14658 TypeTableEntry *child_type = ptr_val->data.x_type;
14659
14665 type_ensure_zero_bits_known(ira->codegen, child_type);14660 type_ensure_zero_bits_known(ira->codegen, child_type);
14666 TypeTableEntry *layer1 = get_maybe_type(ira->codegen, child_type);14661 TypeTableEntry *layer1 = get_maybe_type(ira->codegen, child_type);
14667 TypeTableEntry *layer2 = get_maybe_type(ira->codegen, layer1);14662 TypeTableEntry *layer2 = get_maybe_type(ira->codegen, layer1);
14668 TypeTableEntry *result_type = get_pointer_to_type(ira->codegen, layer2, true);
1466914663
14670 IrInstruction *const_instr = ir_build_const_type(&ira->new_irb, unwrap_maybe_instruction->base.scope,14664 IrInstruction *const_instr = ir_build_const_type(&ira->new_irb, unwrap_maybe_instruction->base.scope,
14671 unwrap_maybe_instruction->base.source_node, result_type);14665 unwrap_maybe_instruction->base.source_node, layer2);
14672 ir_link_new_instruction(const_instr, &unwrap_maybe_instruction->base);14666 IrInstruction *result_instr = ir_get_ref(ira, &unwrap_maybe_instruction->base, const_instr,
14673 return const_instr->value.type;14667 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile);
14674 }14668 ir_link_new_instruction(result_instr, &unwrap_maybe_instruction->base);
1467514669 return result_instr->value.type;
14676 assert(ptr_type->id == TypeTableEntryIdPointer);
14677
14678 TypeTableEntry *type_entry = ptr_type->data.pointer.child_type;
14679 if (type_is_invalid(type_entry)) {
14680 return ira->codegen->builtin_types.entry_invalid;
14681 } else if (type_entry->id != TypeTableEntryIdMaybe) {14670 } else if (type_entry->id != TypeTableEntryIdMaybe) {
14682 ir_add_error_node(ira, unwrap_maybe_instruction->value->source_node,14671 ir_add_error_node(ira, unwrap_maybe_instruction->value->source_node,
14683 buf_sprintf("expected nullable type, found '%s'", buf_ptr(&type_entry->name)));14672 buf_sprintf("expected nullable type, found '%s'", buf_ptr(&type_entry->name)));
...@@ -14686,6 +14675,7 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_maybe(IrAnalyze *ira,...@@ -14686,6 +14675,7 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_maybe(IrAnalyze *ira,
14686 TypeTableEntry *child_type = type_entry->data.maybe.child_type;14675 TypeTableEntry *child_type = type_entry->data.maybe.child_type;
14687 TypeTableEntry *result_type = get_pointer_to_type_extra(ira->codegen, child_type,14676 TypeTableEntry *result_type = get_pointer_to_type_extra(ira->codegen, child_type,
14688 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,14677 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,
14678 PtrLenSingle,
14689 get_abi_alignment(ira->codegen, child_type), 0, 0);14679 get_abi_alignment(ira->codegen, child_type), 0, 0);
1469014680
14691 if (instr_is_comptime(value)) {14681 if (instr_is_comptime(value)) {
...@@ -15203,6 +15193,8 @@ static TypeTableEntry *ir_analyze_container_init_fields_union(IrAnalyze *ira, Ir...@@ -15203,6 +15193,8 @@ static TypeTableEntry *ir_analyze_container_init_fields_union(IrAnalyze *ira, Ir
15203 assert(container_type->id == TypeTableEntryIdUnion);15193 assert(container_type->id == TypeTableEntryIdUnion);
1520415194
15205 ensure_complete_type(ira->codegen, container_type);15195 ensure_complete_type(ira->codegen, container_type);
15196 if (type_is_invalid(container_type))
15197 return ira->codegen->builtin_types.entry_invalid;
1520615198
15207 if (instr_field_count != 1) {15199 if (instr_field_count != 1) {
15208 ir_add_error(ira, instruction,15200 ir_add_error(ira, instruction,
...@@ -15270,6 +15262,8 @@ static TypeTableEntry *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstru...@@ -15270,6 +15262,8 @@ static TypeTableEntry *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstru
15270 }15262 }
1527115263
15272 ensure_complete_type(ira->codegen, container_type);15264 ensure_complete_type(ira->codegen, container_type);
15265 if (type_is_invalid(container_type))
15266 return ira->codegen->builtin_types.entry_invalid;
1527315267
15274 size_t actual_field_count = container_type->data.structure.src_field_count;15268 size_t actual_field_count = container_type->data.structure.src_field_count;
1527515269
...@@ -15629,7 +15623,8 @@ static TypeTableEntry *ir_analyze_instruction_err_name(IrAnalyze *ira, IrInstruc...@@ -15629,7 +15623,8 @@ static TypeTableEntry *ir_analyze_instruction_err_name(IrAnalyze *ira, IrInstruc
15629 if (type_is_invalid(casted_value->value.type))15623 if (type_is_invalid(casted_value->value.type))
15630 return ira->codegen->builtin_types.entry_invalid;15624 return ira->codegen->builtin_types.entry_invalid;
1563115625
15632 TypeTableEntry *u8_ptr_type = get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, true);15626 TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(ira->codegen, ira->codegen->builtin_types.entry_u8,
15627 true, false, PtrLenUnknown, get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8), 0, 0);
15633 TypeTableEntry *str_type = get_slice_type(ira->codegen, u8_ptr_type);15628 TypeTableEntry *str_type = get_slice_type(ira->codegen, u8_ptr_type);
15634 if (casted_value->value.special == ConstValSpecialStatic) {15629 if (casted_value->value.special == ConstValSpecialStatic) {
15635 ErrorTableEntry *err = casted_value->value.data.x_err_set;15630 ErrorTableEntry *err = casted_value->value.data.x_err_set;
...@@ -15670,7 +15665,11 @@ static TypeTableEntry *ir_analyze_instruction_enum_tag_name(IrAnalyze *ira, IrIn...@@ -15670,7 +15665,11 @@ static TypeTableEntry *ir_analyze_instruction_enum_tag_name(IrAnalyze *ira, IrIn
15670 IrInstruction *result = ir_build_tag_name(&ira->new_irb, instruction->base.scope,15665 IrInstruction *result = ir_build_tag_name(&ira->new_irb, instruction->base.scope,
15671 instruction->base.source_node, target);15666 instruction->base.source_node, target);
15672 ir_link_new_instruction(result, &instruction->base);15667 ir_link_new_instruction(result, &instruction->base);
15673 TypeTableEntry *u8_ptr_type = get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, true);15668 TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(
15669 ira->codegen, ira->codegen->builtin_types.entry_u8,
15670 true, false, PtrLenUnknown,
15671 get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8),
15672 0, 0);
15674 result->value.type = get_slice_type(ira->codegen, u8_ptr_type);15673 result->value.type = get_slice_type(ira->codegen, u8_ptr_type);
15675 return result->value.type;15674 return result->value.type;
15676}15675}
...@@ -15723,6 +15722,7 @@ static TypeTableEntry *ir_analyze_instruction_field_parent_ptr(IrAnalyze *ira,...@@ -15723,6 +15722,7 @@ static TypeTableEntry *ir_analyze_instruction_field_parent_ptr(IrAnalyze *ira,
15723 TypeTableEntry *field_ptr_type = get_pointer_to_type_extra(ira->codegen, field->type_entry,15722 TypeTableEntry *field_ptr_type = get_pointer_to_type_extra(ira->codegen, field->type_entry,
15724 field_ptr->value.type->data.pointer.is_const,15723 field_ptr->value.type->data.pointer.is_const,
15725 field_ptr->value.type->data.pointer.is_volatile,15724 field_ptr->value.type->data.pointer.is_volatile,
15725 PtrLenSingle,
15726 field_ptr_align, 0, 0);15726 field_ptr_align, 0, 0);
15727 IrInstruction *casted_field_ptr = ir_implicit_cast(ira, field_ptr, field_ptr_type);15727 IrInstruction *casted_field_ptr = ir_implicit_cast(ira, field_ptr, field_ptr_type);
15728 if (type_is_invalid(casted_field_ptr->value.type))15728 if (type_is_invalid(casted_field_ptr->value.type))
...@@ -15731,6 +15731,7 @@ static TypeTableEntry *ir_analyze_instruction_field_parent_ptr(IrAnalyze *ira,...@@ -15731,6 +15731,7 @@ static TypeTableEntry *ir_analyze_instruction_field_parent_ptr(IrAnalyze *ira,
15731 TypeTableEntry *result_type = get_pointer_to_type_extra(ira->codegen, container_type,15731 TypeTableEntry *result_type = get_pointer_to_type_extra(ira->codegen, container_type,
15732 casted_field_ptr->value.type->data.pointer.is_const,15732 casted_field_ptr->value.type->data.pointer.is_const,
15733 casted_field_ptr->value.type->data.pointer.is_volatile,15733 casted_field_ptr->value.type->data.pointer.is_volatile,
15734 PtrLenSingle,
15734 parent_ptr_align, 0, 0);15735 parent_ptr_align, 0, 0);
1573515736
15736 if (instr_is_comptime(casted_field_ptr)) {15737 if (instr_is_comptime(casted_field_ptr)) {
...@@ -15775,6 +15776,8 @@ static TypeTableEntry *ir_analyze_instruction_offset_of(IrAnalyze *ira,...@@ -15775,6 +15776,8 @@ static TypeTableEntry *ir_analyze_instruction_offset_of(IrAnalyze *ira,
15775 return ira->codegen->builtin_types.entry_invalid;15776 return ira->codegen->builtin_types.entry_invalid;
1577615777
15777 ensure_complete_type(ira->codegen, container_type);15778 ensure_complete_type(ira->codegen, container_type);
15779 if (type_is_invalid(container_type))
15780 return ira->codegen->builtin_types.entry_invalid;
1577815781
15779 IrInstruction *field_name_value = instruction->field_name->other;15782 IrInstruction *field_name_value = instruction->field_name->other;
15780 Buf *field_name = ir_resolve_str(ira, field_name_value);15783 Buf *field_name = ir_resolve_str(ira, field_name_value);
...@@ -15828,6 +15831,9 @@ static TypeTableEntry *ir_type_info_get_type(IrAnalyze *ira, const char *type_na...@@ -15828,6 +15831,9 @@ static TypeTableEntry *ir_type_info_get_type(IrAnalyze *ira, const char *type_na
15828 assert(type_info_var->type->id == TypeTableEntryIdMetaType);15831 assert(type_info_var->type->id == TypeTableEntryIdMetaType);
1582915832
15830 ensure_complete_type(ira->codegen, type_info_var->data.x_type);15833 ensure_complete_type(ira->codegen, type_info_var->data.x_type);
15834 if (type_is_invalid(type_info_var->data.x_type))
15835 return ira->codegen->builtin_types.entry_invalid;
15836
15831 type_info_type = type_info_var->data.x_type;15837 type_info_type = type_info_var->data.x_type;
15832 assert(type_info_type->id == TypeTableEntryIdUnion);15838 assert(type_info_type->id == TypeTableEntryIdUnion);
15833 }15839 }
...@@ -15853,26 +15859,37 @@ static TypeTableEntry *ir_type_info_get_type(IrAnalyze *ira, const char *type_na...@@ -15853,26 +15859,37 @@ static TypeTableEntry *ir_type_info_get_type(IrAnalyze *ira, const char *type_na
15853 VariableTableEntry *var = tld->var;15859 VariableTableEntry *var = tld->var;
1585415860
15855 ensure_complete_type(ira->codegen, var->value->type);15861 ensure_complete_type(ira->codegen, var->value->type);
15862 if (type_is_invalid(var->value->type))
15863 return ira->codegen->builtin_types.entry_invalid;
15856 assert(var->value->type->id == TypeTableEntryIdMetaType);15864 assert(var->value->type->id == TypeTableEntryIdMetaType);
15857 return var->value->data.x_type;15865 return var->value->data.x_type;
15858}15866}
1585915867
15860static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, ScopeDecls *decls_scope)15868static bool ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, ScopeDecls *decls_scope)
15861{15869{
15862 TypeTableEntry *type_info_definition_type = ir_type_info_get_type(ira, "Definition");15870 TypeTableEntry *type_info_definition_type = ir_type_info_get_type(ira, "Definition");
15863 ensure_complete_type(ira->codegen, type_info_definition_type);15871 ensure_complete_type(ira->codegen, type_info_definition_type);
15872 if (type_is_invalid(type_info_definition_type))
15873 return false;
15874
15864 ensure_field_index(type_info_definition_type, "name", 0);15875 ensure_field_index(type_info_definition_type, "name", 0);
15865 ensure_field_index(type_info_definition_type, "is_pub", 1);15876 ensure_field_index(type_info_definition_type, "is_pub", 1);
15866 ensure_field_index(type_info_definition_type, "data", 2);15877 ensure_field_index(type_info_definition_type, "data", 2);
1586715878
15868 TypeTableEntry *type_info_definition_data_type = ir_type_info_get_type(ira, "Data", type_info_definition_type);15879 TypeTableEntry *type_info_definition_data_type = ir_type_info_get_type(ira, "Data", type_info_definition_type);
15869 ensure_complete_type(ira->codegen, type_info_definition_data_type);15880 ensure_complete_type(ira->codegen, type_info_definition_data_type);
15881 if (type_is_invalid(type_info_definition_data_type))
15882 return false;
1587015883
15871 TypeTableEntry *type_info_fn_def_type = ir_type_info_get_type(ira, "FnDef", type_info_definition_data_type);15884 TypeTableEntry *type_info_fn_def_type = ir_type_info_get_type(ira, "FnDef", type_info_definition_data_type);
15872 ensure_complete_type(ira->codegen, type_info_fn_def_type);15885 ensure_complete_type(ira->codegen, type_info_fn_def_type);
15886 if (type_is_invalid(type_info_fn_def_type))
15887 return false;
1587315888
15874 TypeTableEntry *type_info_fn_def_inline_type = ir_type_info_get_type(ira, "Inline", type_info_fn_def_type);15889 TypeTableEntry *type_info_fn_def_inline_type = ir_type_info_get_type(ira, "Inline", type_info_fn_def_type);
15875 ensure_complete_type(ira->codegen, type_info_fn_def_inline_type);15890 ensure_complete_type(ira->codegen, type_info_fn_def_inline_type);
15891 if (type_is_invalid(type_info_fn_def_inline_type))
15892 return false;
1587615893
15877 // Loop through our definitions once to figure out how many definitions we will generate info for.15894 // Loop through our definitions once to figure out how many definitions we will generate info for.
15878 auto decl_it = decls_scope->decl_table.entry_iterator();15895 auto decl_it = decls_scope->decl_table.entry_iterator();
...@@ -15887,7 +15904,7 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop...@@ -15887,7 +15904,7 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
15887 resolve_top_level_decl(ira->codegen, curr_entry->value, false, curr_entry->value->source_node);15904 resolve_top_level_decl(ira->codegen, curr_entry->value, false, curr_entry->value->source_node);
15888 if (curr_entry->value->resolution != TldResolutionOk)15905 if (curr_entry->value->resolution != TldResolutionOk)
15889 {15906 {
15890 return;15907 return false;
15891 }15908 }
15892 }15909 }
1589315910
...@@ -15952,6 +15969,9 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop...@@ -15952,6 +15969,9 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
15952 {15969 {
15953 VariableTableEntry *var = ((TldVar *)curr_entry->value)->var;15970 VariableTableEntry *var = ((TldVar *)curr_entry->value)->var;
15954 ensure_complete_type(ira->codegen, var->value->type);15971 ensure_complete_type(ira->codegen, var->value->type);
15972 if (type_is_invalid(var->value->type))
15973 return false;
15974
15955 if (var->value->type->id == TypeTableEntryIdMetaType)15975 if (var->value->type->id == TypeTableEntryIdMetaType)
15956 {15976 {
15957 // We have a variable of type 'type', so it's actually a type definition.15977 // We have a variable of type 'type', so it's actually a type definition.
...@@ -15982,10 +16002,6 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop...@@ -15982,10 +16002,6 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
15982 FnTableEntry *fn_entry = ((TldFn *)curr_entry->value)->fn_entry;16002 FnTableEntry *fn_entry = ((TldFn *)curr_entry->value)->fn_entry;
15983 assert(!fn_entry->is_test);16003 assert(!fn_entry->is_test);
1598416004
15985 analyze_fn_body(ira->codegen, fn_entry);
15986 if (fn_entry->anal_state == FnAnalStateInvalid)
15987 return;
15988
15989 AstNodeFnProto *fn_node = (AstNodeFnProto *)(fn_entry->proto_node);16005 AstNodeFnProto *fn_node = (AstNodeFnProto *)(fn_entry->proto_node);
1599016006
15991 ConstExprValue *fn_def_val = create_const_vals(1);16007 ConstExprValue *fn_def_val = create_const_vals(1);
...@@ -16031,11 +16047,13 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop...@@ -16031,11 +16047,13 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
16031 // lib_name: ?[]const u816047 // lib_name: ?[]const u8
16032 ensure_field_index(fn_def_val->type, "lib_name", 6);16048 ensure_field_index(fn_def_val->type, "lib_name", 6);
16033 fn_def_fields[6].special = ConstValSpecialStatic;16049 fn_def_fields[6].special = ConstValSpecialStatic;
16034 fn_def_fields[6].type = get_maybe_type(ira->codegen,16050 TypeTableEntry *u8_ptr = get_pointer_to_type_extra(
16035 get_slice_type(ira->codegen, get_pointer_to_type(ira->codegen,16051 ira->codegen, ira->codegen->builtin_types.entry_u8,
16036 ira->codegen->builtin_types.entry_u8, true)));16052 true, false, PtrLenUnknown,
16037 if (fn_node->is_extern && buf_len(fn_node->lib_name) > 0)16053 get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8),
16038 {16054 0, 0);
16055 fn_def_fields[6].type = get_maybe_type(ira->codegen, get_slice_type(ira->codegen, u8_ptr));
16056 if (fn_node->is_extern && buf_len(fn_node->lib_name) > 0) {
16039 fn_def_fields[6].data.x_maybe = create_const_vals(1);16057 fn_def_fields[6].data.x_maybe = create_const_vals(1);
16040 ConstExprValue *lib_name = create_const_str_lit(ira->codegen, fn_node->lib_name);16058 ConstExprValue *lib_name = create_const_str_lit(ira->codegen, fn_node->lib_name);
16041 init_const_slice(ira->codegen, fn_def_fields[6].data.x_maybe, lib_name, 0, buf_len(fn_node->lib_name), true);16059 init_const_slice(ira->codegen, fn_def_fields[6].data.x_maybe, lib_name, 0, buf_len(fn_node->lib_name), true);
...@@ -16057,8 +16075,8 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop...@@ -16057,8 +16075,8 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
16057 size_t fn_arg_count = fn_entry->variable_list.length;16075 size_t fn_arg_count = fn_entry->variable_list.length;
16058 ConstExprValue *fn_arg_name_array = create_const_vals(1);16076 ConstExprValue *fn_arg_name_array = create_const_vals(1);
16059 fn_arg_name_array->special = ConstValSpecialStatic;16077 fn_arg_name_array->special = ConstValSpecialStatic;
16060 fn_arg_name_array->type = get_array_type(ira->codegen, get_slice_type(ira->codegen,16078 fn_arg_name_array->type = get_array_type(ira->codegen,
16061 get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, true)), fn_arg_count);16079 get_slice_type(ira->codegen, u8_ptr), fn_arg_count);
16062 fn_arg_name_array->data.x_array.special = ConstArraySpecialNone;16080 fn_arg_name_array->data.x_array.special = ConstArraySpecialNone;
16063 fn_arg_name_array->data.x_array.s_none.parent.id = ConstParentIdNone;16081 fn_arg_name_array->data.x_array.s_none.parent.id = ConstParentIdNone;
16064 fn_arg_name_array->data.x_array.s_none.elements = create_const_vals(fn_arg_count);16082 fn_arg_name_array->data.x_array.s_none.elements = create_const_vals(fn_arg_count);
...@@ -16083,6 +16101,9 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop...@@ -16083,6 +16101,9 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
16083 {16101 {
16084 TypeTableEntry *type_entry = ((TldContainer *)curr_entry->value)->type_entry;16102 TypeTableEntry *type_entry = ((TldContainer *)curr_entry->value)->type_entry;
16085 ensure_complete_type(ira->codegen, type_entry);16103 ensure_complete_type(ira->codegen, type_entry);
16104 if (type_is_invalid(type_entry))
16105 return false;
16106
16086 // This is a type.16107 // This is a type.
16087 bigint_init_unsigned(&inner_fields[2].data.x_union.tag, 0);16108 bigint_init_unsigned(&inner_fields[2].data.x_union.tag, 0);
1608816109
...@@ -16103,6 +16124,7 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop...@@ -16103,6 +16124,7 @@ static void ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
16103 }16124 }
1610416125
16105 assert(definition_index == definition_count);16126 assert(definition_index == definition_count);
16127 return true;
16106}16128}
1610716129
16108static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *type_entry)16130static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *type_entry)
...@@ -16111,6 +16133,8 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t...@@ -16111,6 +16133,8 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
16111 assert(!type_is_invalid(type_entry));16133 assert(!type_is_invalid(type_entry));
1611216134
16113 ensure_complete_type(ira->codegen, type_entry);16135 ensure_complete_type(ira->codegen, type_entry);
16136 if (type_is_invalid(type_entry))
16137 return nullptr;
1611416138
16115 const auto make_enum_field_val = [ira](ConstExprValue *enum_field_val, TypeEnumField *enum_field,16139 const auto make_enum_field_val = [ira](ConstExprValue *enum_field_val, TypeEnumField *enum_field,
16116 TypeTableEntry *type_info_enum_field_type) {16140 TypeTableEntry *type_info_enum_field_type) {
...@@ -16338,7 +16362,8 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t...@@ -16338,7 +16362,8 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
16338 }16362 }
16339 // defs: []TypeInfo.Definition16363 // defs: []TypeInfo.Definition
16340 ensure_field_index(result->type, "defs", 3);16364 ensure_field_index(result->type, "defs", 3);
16341 ir_make_type_info_defs(ira, &fields[3], type_entry->data.enumeration.decls_scope);16365 if (!ir_make_type_info_defs(ira, &fields[3], type_entry->data.enumeration.decls_scope))
16366 return nullptr;
1634216367
16343 break;16368 break;
16344 }16369 }
...@@ -16493,7 +16518,8 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t...@@ -16493,7 +16518,8 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
16493 }16518 }
16494 // defs: []TypeInfo.Definition16519 // defs: []TypeInfo.Definition
16495 ensure_field_index(result->type, "defs", 3);16520 ensure_field_index(result->type, "defs", 3);
16496 ir_make_type_info_defs(ira, &fields[3], type_entry->data.unionation.decls_scope);16521 if (!ir_make_type_info_defs(ira, &fields[3], type_entry->data.unionation.decls_scope))
16522 return nullptr;
1649716523
16498 break;16524 break;
16499 }16525 }
...@@ -16504,6 +16530,8 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t...@@ -16504,6 +16530,8 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
16504 buf_init_from_str(&ptr_field_name, "ptr");16530 buf_init_from_str(&ptr_field_name, "ptr");
16505 TypeTableEntry *ptr_type = type_entry->data.structure.fields_by_name.get(&ptr_field_name)->type_entry;16531 TypeTableEntry *ptr_type = type_entry->data.structure.fields_by_name.get(&ptr_field_name)->type_entry;
16506 ensure_complete_type(ira->codegen, ptr_type);16532 ensure_complete_type(ira->codegen, ptr_type);
16533 if (type_is_invalid(ptr_type))
16534 return nullptr;
16507 buf_deinit(&ptr_field_name);16535 buf_deinit(&ptr_field_name);
1650816536
16509 result = create_ptr_like_type_info("Slice", ptr_type);16537 result = create_ptr_like_type_info("Slice", ptr_type);
...@@ -16574,7 +16602,8 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t...@@ -16574,7 +16602,8 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
16574 }16602 }
16575 // defs: []TypeInfo.Definition16603 // defs: []TypeInfo.Definition
16576 ensure_field_index(result->type, "defs", 2);16604 ensure_field_index(result->type, "defs", 2);
16577 ir_make_type_info_defs(ira, &fields[2], type_entry->data.structure.decls_scope);16605 if (!ir_make_type_info_defs(ira, &fields[2], type_entry->data.structure.decls_scope))
16606 return nullptr;
1657816607
16579 break;16608 break;
16580 }16609 }
...@@ -17125,7 +17154,8 @@ static TypeTableEntry *ir_analyze_instruction_memset(IrAnalyze *ira, IrInstructi...@@ -17125,7 +17154,8 @@ static TypeTableEntry *ir_analyze_instruction_memset(IrAnalyze *ira, IrInstructi
17125 TypeTableEntry *u8 = ira->codegen->builtin_types.entry_u8;17154 TypeTableEntry *u8 = ira->codegen->builtin_types.entry_u8;
17126 uint32_t dest_align = (dest_uncasted_type->id == TypeTableEntryIdPointer) ?17155 uint32_t dest_align = (dest_uncasted_type->id == TypeTableEntryIdPointer) ?
17127 dest_uncasted_type->data.pointer.alignment : get_abi_alignment(ira->codegen, u8);17156 dest_uncasted_type->data.pointer.alignment : get_abi_alignment(ira->codegen, u8);
17128 TypeTableEntry *u8_ptr = get_pointer_to_type_extra(ira->codegen, u8, false, dest_is_volatile, dest_align, 0, 0);17157 TypeTableEntry *u8_ptr = get_pointer_to_type_extra(ira->codegen, u8, false, dest_is_volatile,
17158 PtrLenUnknown, dest_align, 0, 0);
1712917159
17130 IrInstruction *casted_dest_ptr = ir_implicit_cast(ira, dest_ptr, u8_ptr);17160 IrInstruction *casted_dest_ptr = ir_implicit_cast(ira, dest_ptr, u8_ptr);
17131 if (type_is_invalid(casted_dest_ptr->value.type))17161 if (type_is_invalid(casted_dest_ptr->value.type))
...@@ -17221,8 +17251,10 @@ static TypeTableEntry *ir_analyze_instruction_memcpy(IrAnalyze *ira, IrInstructi...@@ -17221,8 +17251,10 @@ static TypeTableEntry *ir_analyze_instruction_memcpy(IrAnalyze *ira, IrInstructi
17221 src_uncasted_type->data.pointer.alignment : get_abi_alignment(ira->codegen, u8);17251 src_uncasted_type->data.pointer.alignment : get_abi_alignment(ira->codegen, u8);
1722217252
17223 TypeTableEntry *usize = ira->codegen->builtin_types.entry_usize;17253 TypeTableEntry *usize = ira->codegen->builtin_types.entry_usize;
17224 TypeTableEntry *u8_ptr_mut = get_pointer_to_type_extra(ira->codegen, u8, false, dest_is_volatile, dest_align, 0, 0);17254 TypeTableEntry *u8_ptr_mut = get_pointer_to_type_extra(ira->codegen, u8, false, dest_is_volatile,
17225 TypeTableEntry *u8_ptr_const = get_pointer_to_type_extra(ira->codegen, u8, true, src_is_volatile, src_align, 0, 0);17255 PtrLenUnknown, dest_align, 0, 0);
17256 TypeTableEntry *u8_ptr_const = get_pointer_to_type_extra(ira->codegen, u8, true, src_is_volatile,
17257 PtrLenUnknown, src_align, 0, 0);
1722617258
17227 IrInstruction *casted_dest_ptr = ir_implicit_cast(ira, dest_ptr, u8_ptr_mut);17259 IrInstruction *casted_dest_ptr = ir_implicit_cast(ira, dest_ptr, u8_ptr_mut);
17228 if (type_is_invalid(casted_dest_ptr->value.type))17260 if (type_is_invalid(casted_dest_ptr->value.type))
...@@ -17365,13 +17397,18 @@ static TypeTableEntry *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstructio...@@ -17365,13 +17397,18 @@ static TypeTableEntry *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstructio
17365 if (array_type->data.array.len == 0 && byte_alignment == 0) {17397 if (array_type->data.array.len == 0 && byte_alignment == 0) {
17366 byte_alignment = get_abi_alignment(ira->codegen, array_type->data.array.child_type);17398 byte_alignment = get_abi_alignment(ira->codegen, array_type->data.array.child_type);
17367 }17399 }
17400 bool is_comptime_const = ptr_ptr->value.special == ConstValSpecialStatic &&
17401 ptr_ptr->value.data.x_ptr.mut == ConstPtrMutComptimeConst;
17368 TypeTableEntry *slice_ptr_type = get_pointer_to_type_extra(ira->codegen, array_type->data.array.child_type,17402 TypeTableEntry *slice_ptr_type = get_pointer_to_type_extra(ira->codegen, array_type->data.array.child_type,
17369 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,17403 ptr_type->data.pointer.is_const || is_comptime_const,
17404 ptr_type->data.pointer.is_volatile,
17405 PtrLenUnknown,
17370 byte_alignment, 0, 0);17406 byte_alignment, 0, 0);
17371 return_type = get_slice_type(ira->codegen, slice_ptr_type);17407 return_type = get_slice_type(ira->codegen, slice_ptr_type);
17372 } else if (array_type->id == TypeTableEntryIdPointer) {17408 } else if (array_type->id == TypeTableEntryIdPointer) {
17373 TypeTableEntry *slice_ptr_type = get_pointer_to_type_extra(ira->codegen, array_type->data.pointer.child_type,17409 TypeTableEntry *slice_ptr_type = get_pointer_to_type_extra(ira->codegen, array_type->data.pointer.child_type,
17374 array_type->data.pointer.is_const, array_type->data.pointer.is_volatile,17410 array_type->data.pointer.is_const, array_type->data.pointer.is_volatile,
17411 PtrLenUnknown,
17375 array_type->data.pointer.alignment, 0, 0);17412 array_type->data.pointer.alignment, 0, 0);
17376 return_type = get_slice_type(ira->codegen, slice_ptr_type);17413 return_type = get_slice_type(ira->codegen, slice_ptr_type);
17377 if (!end) {17414 if (!end) {
...@@ -17553,6 +17590,10 @@ static TypeTableEntry *ir_analyze_instruction_member_count(IrAnalyze *ira, IrIns...@@ -17553,6 +17590,10 @@ static TypeTableEntry *ir_analyze_instruction_member_count(IrAnalyze *ira, IrIns
17553 return ira->codegen->builtin_types.entry_invalid;17590 return ira->codegen->builtin_types.entry_invalid;
17554 TypeTableEntry *container_type = ir_resolve_type(ira, container);17591 TypeTableEntry *container_type = ir_resolve_type(ira, container);
1755517592
17593 ensure_complete_type(ira->codegen, container_type);
17594 if (type_is_invalid(container_type))
17595 return ira->codegen->builtin_types.entry_invalid;
17596
17556 uint64_t result;17597 uint64_t result;
17557 if (type_is_invalid(container_type)) {17598 if (type_is_invalid(container_type)) {
17558 return ira->codegen->builtin_types.entry_invalid;17599 return ira->codegen->builtin_types.entry_invalid;
...@@ -17563,7 +17604,7 @@ static TypeTableEntry *ir_analyze_instruction_member_count(IrAnalyze *ira, IrIns...@@ -17563,7 +17604,7 @@ static TypeTableEntry *ir_analyze_instruction_member_count(IrAnalyze *ira, IrIns
17563 } else if (container_type->id == TypeTableEntryIdUnion) {17604 } else if (container_type->id == TypeTableEntryIdUnion) {
17564 result = container_type->data.unionation.src_field_count;17605 result = container_type->data.unionation.src_field_count;
17565 } else if (container_type->id == TypeTableEntryIdErrorSet) {17606 } else if (container_type->id == TypeTableEntryIdErrorSet) {
17566 if (!resolve_inferred_error_set(ira, container_type, instruction->base.source_node)) {17607 if (!resolve_inferred_error_set(ira->codegen, container_type, instruction->base.source_node)) {
17567 return ira->codegen->builtin_types.entry_invalid;17608 return ira->codegen->builtin_types.entry_invalid;
17568 }17609 }
17569 if (type_is_global_error_set(container_type)) {17610 if (type_is_global_error_set(container_type)) {
...@@ -17587,6 +17628,11 @@ static TypeTableEntry *ir_analyze_instruction_member_type(IrAnalyze *ira, IrInst...@@ -17587,6 +17628,11 @@ static TypeTableEntry *ir_analyze_instruction_member_type(IrAnalyze *ira, IrInst
17587 if (type_is_invalid(container_type))17628 if (type_is_invalid(container_type))
17588 return ira->codegen->builtin_types.entry_invalid;17629 return ira->codegen->builtin_types.entry_invalid;
1758917630
17631 ensure_complete_type(ira->codegen, container_type);
17632 if (type_is_invalid(container_type))
17633 return ira->codegen->builtin_types.entry_invalid;
17634
17635
17590 uint64_t member_index;17636 uint64_t member_index;
17591 IrInstruction *index_value = instruction->member_index->other;17637 IrInstruction *index_value = instruction->member_index->other;
17592 if (!ir_resolve_usize(ira, index_value, &member_index))17638 if (!ir_resolve_usize(ira, index_value, &member_index))
...@@ -17629,6 +17675,10 @@ static TypeTableEntry *ir_analyze_instruction_member_name(IrAnalyze *ira, IrInst...@@ -17629,6 +17675,10 @@ static TypeTableEntry *ir_analyze_instruction_member_name(IrAnalyze *ira, IrInst
17629 if (type_is_invalid(container_type))17675 if (type_is_invalid(container_type))
17630 return ira->codegen->builtin_types.entry_invalid;17676 return ira->codegen->builtin_types.entry_invalid;
1763117677
17678 ensure_complete_type(ira->codegen, container_type);
17679 if (type_is_invalid(container_type))
17680 return ira->codegen->builtin_types.entry_invalid;
17681
17632 uint64_t member_index;17682 uint64_t member_index;
17633 IrInstruction *index_value = instruction->member_index->other;17683 IrInstruction *index_value = instruction->member_index->other;
17634 if (!ir_resolve_usize(ira, index_value, &member_index))17684 if (!ir_resolve_usize(ira, index_value, &member_index))
...@@ -17795,6 +17845,7 @@ static TypeTableEntry *ir_analyze_instruction_overflow_op(IrAnalyze *ira, IrInst...@@ -17795,6 +17845,7 @@ static TypeTableEntry *ir_analyze_instruction_overflow_op(IrAnalyze *ira, IrInst
17795 if (result_ptr->value.type->id == TypeTableEntryIdPointer) {17845 if (result_ptr->value.type->id == TypeTableEntryIdPointer) {
17796 expected_ptr_type = get_pointer_to_type_extra(ira->codegen, dest_type,17846 expected_ptr_type = get_pointer_to_type_extra(ira->codegen, dest_type,
17797 false, result_ptr->value.type->data.pointer.is_volatile,17847 false, result_ptr->value.type->data.pointer.is_volatile,
17848 PtrLenSingle,
17798 result_ptr->value.type->data.pointer.alignment, 0, 0);17849 result_ptr->value.type->data.pointer.alignment, 0, 0);
17799 } else {17850 } else {
17800 expected_ptr_type = get_pointer_to_type(ira->codegen, dest_type, false);17851 expected_ptr_type = get_pointer_to_type(ira->codegen, dest_type, false);
...@@ -17867,7 +17918,7 @@ static TypeTableEntry *ir_analyze_instruction_test_err(IrAnalyze *ira, IrInstruc...@@ -17867,7 +17918,7 @@ static TypeTableEntry *ir_analyze_instruction_test_err(IrAnalyze *ira, IrInstruc
17867 }17918 }
1786817919
17869 TypeTableEntry *err_set_type = type_entry->data.error_union.err_set_type;17920 TypeTableEntry *err_set_type = type_entry->data.error_union.err_set_type;
17870 if (!resolve_inferred_error_set(ira, err_set_type, instruction->base.source_node)) {17921 if (!resolve_inferred_error_set(ira->codegen, err_set_type, instruction->base.source_node)) {
17871 return ira->codegen->builtin_types.entry_invalid;17922 return ira->codegen->builtin_types.entry_invalid;
17872 }17923 }
17873 if (!type_is_global_error_set(err_set_type) &&17924 if (!type_is_global_error_set(err_set_type) &&
...@@ -17950,6 +18001,7 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_err_payload(IrAnalyze *ira,...@@ -17950,6 +18001,7 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_err_payload(IrAnalyze *ira,
17950 TypeTableEntry *payload_type = type_entry->data.error_union.payload_type;18001 TypeTableEntry *payload_type = type_entry->data.error_union.payload_type;
17951 TypeTableEntry *result_type = get_pointer_to_type_extra(ira->codegen, payload_type,18002 TypeTableEntry *result_type = get_pointer_to_type_extra(ira->codegen, payload_type,
17952 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,18003 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,
18004 PtrLenSingle,
17953 get_abi_alignment(ira->codegen, payload_type), 0, 0);18005 get_abi_alignment(ira->codegen, payload_type), 0, 0);
17954 if (instr_is_comptime(value)) {18006 if (instr_is_comptime(value)) {
17955 ConstExprValue *ptr_val = ir_resolve_const(ira, value, UndefBad);18007 ConstExprValue *ptr_val = ir_resolve_const(ira, value, UndefBad);
...@@ -18135,7 +18187,7 @@ static TypeTableEntry *ir_analyze_instruction_check_switch_prongs(IrAnalyze *ira...@@ -18135,7 +18187,7 @@ static TypeTableEntry *ir_analyze_instruction_check_switch_prongs(IrAnalyze *ira
18135 }18187 }
18136 }18188 }
18137 } else if (switch_type->id == TypeTableEntryIdErrorSet) {18189 } else if (switch_type->id == TypeTableEntryIdErrorSet) {
18138 if (!resolve_inferred_error_set(ira, switch_type, target_value->source_node)) {18190 if (!resolve_inferred_error_set(ira->codegen, switch_type, target_value->source_node)) {
18139 return ira->codegen->builtin_types.entry_invalid;18191 return ira->codegen->builtin_types.entry_invalid;
18140 }18192 }
1814118193
...@@ -18291,7 +18343,8 @@ static TypeTableEntry *ir_analyze_instruction_panic(IrAnalyze *ira, IrInstructio...@@ -18291,7 +18343,8 @@ static TypeTableEntry *ir_analyze_instruction_panic(IrAnalyze *ira, IrInstructio
18291 return ir_unreach_error(ira);18343 return ir_unreach_error(ira);
18292 }18344 }
1829318345
18294 TypeTableEntry *u8_ptr_type = get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, true);18346 TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(ira->codegen, ira->codegen->builtin_types.entry_u8,
18347 true, false, PtrLenUnknown, get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8), 0, 0);
18295 TypeTableEntry *str_type = get_slice_type(ira->codegen, u8_ptr_type);18348 TypeTableEntry *str_type = get_slice_type(ira->codegen, u8_ptr_type);
18296 IrInstruction *casted_msg = ir_implicit_cast(ira, msg, str_type);18349 IrInstruction *casted_msg = ir_implicit_cast(ira, msg, str_type);
18297 if (type_is_invalid(casted_msg->value.type))18350 if (type_is_invalid(casted_msg->value.type))
...@@ -18570,7 +18623,12 @@ static TypeTableEntry *ir_analyze_instruction_bit_cast(IrAnalyze *ira, IrInstruc...@@ -18570,7 +18623,12 @@ static TypeTableEntry *ir_analyze_instruction_bit_cast(IrAnalyze *ira, IrInstruc
18570 return ira->codegen->builtin_types.entry_invalid;18623 return ira->codegen->builtin_types.entry_invalid;
1857118624
18572 ensure_complete_type(ira->codegen, dest_type);18625 ensure_complete_type(ira->codegen, dest_type);
18626 if (type_is_invalid(dest_type))
18627 return ira->codegen->builtin_types.entry_invalid;
18628
18573 ensure_complete_type(ira->codegen, src_type);18629 ensure_complete_type(ira->codegen, src_type);
18630 if (type_is_invalid(src_type))
18631 return ira->codegen->builtin_types.entry_invalid;
1857418632
18575 if (get_codegen_ptr_type(src_type) != nullptr) {18633 if (get_codegen_ptr_type(src_type) != nullptr) {
18576 ir_add_error(ira, value,18634 ir_add_error(ira, value,
...@@ -18716,8 +18774,7 @@ static TypeTableEntry *ir_analyze_instruction_decl_ref(IrAnalyze *ira,...@@ -18716,8 +18774,7 @@ static TypeTableEntry *ir_analyze_instruction_decl_ref(IrAnalyze *ira,
18716 TldVar *tld_var = (TldVar *)tld;18774 TldVar *tld_var = (TldVar *)tld;
18717 VariableTableEntry *var = tld_var->var;18775 VariableTableEntry *var = tld_var->var;
1871818776
18719 IrInstruction *var_ptr = ir_get_var_ptr(ira, &instruction->base, var,18777 IrInstruction *var_ptr = ir_get_var_ptr(ira, &instruction->base, var);
18720 !lval.is_ptr || lval.is_const, lval.is_ptr && lval.is_volatile);
18721 if (type_is_invalid(var_ptr->value.type))18778 if (type_is_invalid(var_ptr->value.type))
18722 return ira->codegen->builtin_types.entry_invalid;18779 return ira->codegen->builtin_types.entry_invalid;
1872318780
...@@ -18795,22 +18852,31 @@ static TypeTableEntry *ir_analyze_instruction_ptr_to_int(IrAnalyze *ira, IrInstr...@@ -18795,22 +18852,31 @@ static TypeTableEntry *ir_analyze_instruction_ptr_to_int(IrAnalyze *ira, IrInstr
18795 return usize;18852 return usize;
18796}18853}
1879718854
18798static TypeTableEntry *ir_analyze_instruction_ptr_type_of(IrAnalyze *ira, IrInstructionPtrTypeOf *instruction) {18855static TypeTableEntry *ir_analyze_instruction_ptr_type(IrAnalyze *ira, IrInstructionPtrType *instruction) {
18799 TypeTableEntry *child_type = ir_resolve_type(ira, instruction->child_type->other);18856 TypeTableEntry *child_type = ir_resolve_type(ira, instruction->child_type->other);
18800 if (type_is_invalid(child_type))18857 if (type_is_invalid(child_type))
18801 return ira->codegen->builtin_types.entry_invalid;18858 return ira->codegen->builtin_types.entry_invalid;
1880218859
18860 if (child_type->id == TypeTableEntryIdUnreachable) {
18861 ir_add_error(ira, &instruction->base, buf_sprintf("pointer to noreturn not allowed"));
18862 return ira->codegen->builtin_types.entry_invalid;
18863 }
18864
18803 uint32_t align_bytes;18865 uint32_t align_bytes;
18804 if (instruction->align_value != nullptr) {18866 if (instruction->align_value != nullptr) {
18805 if (!ir_resolve_align(ira, instruction->align_value->other, &align_bytes))18867 if (!ir_resolve_align(ira, instruction->align_value->other, &align_bytes))
18806 return ira->codegen->builtin_types.entry_invalid;18868 return ira->codegen->builtin_types.entry_invalid;
18807 } else {18869 } else {
18870 type_ensure_zero_bits_known(ira->codegen, child_type);
18871 if (type_is_invalid(child_type))
18872 return ira->codegen->builtin_types.entry_invalid;
18808 align_bytes = get_abi_alignment(ira->codegen, child_type);18873 align_bytes = get_abi_alignment(ira->codegen, child_type);
18809 }18874 }
1881018875
18811 ConstExprValue *out_val = ir_build_const_from(ira, &instruction->base);18876 ConstExprValue *out_val = ir_build_const_from(ira, &instruction->base);
18812 out_val->data.x_type = get_pointer_to_type_extra(ira->codegen, child_type,18877 out_val->data.x_type = get_pointer_to_type_extra(ira->codegen, child_type,
18813 instruction->is_const, instruction->is_volatile, align_bytes,18878 instruction->is_const, instruction->is_volatile,
18879 instruction->ptr_len, align_bytes,
18814 instruction->bit_offset_start, instruction->bit_offset_end - instruction->bit_offset_start);18880 instruction->bit_offset_start, instruction->bit_offset_end - instruction->bit_offset_start);
1881518881
18816 return ira->codegen->builtin_types.entry_type;18882 return ira->codegen->builtin_types.entry_type;
...@@ -19623,8 +19689,8 @@ static TypeTableEntry *ir_analyze_instruction_nocast(IrAnalyze *ira, IrInstructi...@@ -19623,8 +19689,8 @@ static TypeTableEntry *ir_analyze_instruction_nocast(IrAnalyze *ira, IrInstructi
19623 return ir_analyze_instruction_type_id(ira, (IrInstructionTypeId *)instruction);19689 return ir_analyze_instruction_type_id(ira, (IrInstructionTypeId *)instruction);
19624 case IrInstructionIdSetEvalBranchQuota:19690 case IrInstructionIdSetEvalBranchQuota:
19625 return ir_analyze_instruction_set_eval_branch_quota(ira, (IrInstructionSetEvalBranchQuota *)instruction);19691 return ir_analyze_instruction_set_eval_branch_quota(ira, (IrInstructionSetEvalBranchQuota *)instruction);
19626 case IrInstructionIdPtrTypeOf:19692 case IrInstructionIdPtrType:
19627 return ir_analyze_instruction_ptr_type_of(ira, (IrInstructionPtrTypeOf *)instruction);19693 return ir_analyze_instruction_ptr_type(ira, (IrInstructionPtrType *)instruction);
19628 case IrInstructionIdAlignCast:19694 case IrInstructionIdAlignCast:
19629 return ir_analyze_instruction_align_cast(ira, (IrInstructionAlignCast *)instruction);19695 return ir_analyze_instruction_align_cast(ira, (IrInstructionAlignCast *)instruction);
19630 case IrInstructionIdOpaqueType:19696 case IrInstructionIdOpaqueType:
...@@ -19800,7 +19866,7 @@ bool ir_has_side_effects(IrInstruction *instruction) {...@@ -19800,7 +19866,7 @@ bool ir_has_side_effects(IrInstruction *instruction) {
19800 case IrInstructionIdCheckStatementIsVoid:19866 case IrInstructionIdCheckStatementIsVoid:
19801 case IrInstructionIdPanic:19867 case IrInstructionIdPanic:
19802 case IrInstructionIdSetEvalBranchQuota:19868 case IrInstructionIdSetEvalBranchQuota:
19803 case IrInstructionIdPtrTypeOf:19869 case IrInstructionIdPtrType:
19804 case IrInstructionIdSetAlignStack:19870 case IrInstructionIdSetAlignStack:
19805 case IrInstructionIdExport:19871 case IrInstructionIdExport:
19806 case IrInstructionIdCancel:19872 case IrInstructionIdCancel:
src/ir_print.cpp+3-3
...@@ -921,7 +921,7 @@ static void ir_print_can_implicit_cast(IrPrint *irp, IrInstructionCanImplicitCas...@@ -921,7 +921,7 @@ static void ir_print_can_implicit_cast(IrPrint *irp, IrInstructionCanImplicitCas
921 fprintf(irp->f, ")");921 fprintf(irp->f, ")");
922}922}
923923
924static void ir_print_ptr_type_of(IrPrint *irp, IrInstructionPtrTypeOf *instruction) {924static void ir_print_ptr_type(IrPrint *irp, IrInstructionPtrType *instruction) {
925 fprintf(irp->f, "&");925 fprintf(irp->f, "&");
926 if (instruction->align_value != nullptr) {926 if (instruction->align_value != nullptr) {
927 fprintf(irp->f, "align(");927 fprintf(irp->f, "align(");
...@@ -1527,8 +1527,8 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) {...@@ -1527,8 +1527,8 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) {
1527 case IrInstructionIdCanImplicitCast:1527 case IrInstructionIdCanImplicitCast:
1528 ir_print_can_implicit_cast(irp, (IrInstructionCanImplicitCast *)instruction);1528 ir_print_can_implicit_cast(irp, (IrInstructionCanImplicitCast *)instruction);
1529 break;1529 break;
1530 case IrInstructionIdPtrTypeOf:1530 case IrInstructionIdPtrType:
1531 ir_print_ptr_type_of(irp, (IrInstructionPtrTypeOf *)instruction);1531 ir_print_ptr_type(irp, (IrInstructionPtrType *)instruction);
1532 break;1532 break;
1533 case IrInstructionIdDeclRef:1533 case IrInstructionIdDeclRef:
1534 ir_print_decl_ref(irp, (IrInstructionDeclRef *)instruction);1534 ir_print_decl_ref(irp, (IrInstructionDeclRef *)instruction);
src/parser.cpp+27-18
...@@ -1167,20 +1167,20 @@ static PrefixOp tok_to_prefix_op(Token *token) {...@@ -1167,20 +1167,20 @@ static PrefixOp tok_to_prefix_op(Token *token) {
1167 case TokenIdTilde: return PrefixOpBinNot;1167 case TokenIdTilde: return PrefixOpBinNot;
1168 case TokenIdMaybe: return PrefixOpMaybe;1168 case TokenIdMaybe: return PrefixOpMaybe;
1169 case TokenIdDoubleQuestion: return PrefixOpUnwrapMaybe;1169 case TokenIdDoubleQuestion: return PrefixOpUnwrapMaybe;
1170 case TokenIdAmpersand: return PrefixOpAddrOf;
1170 default: return PrefixOpInvalid;1171 default: return PrefixOpInvalid;
1171 }1172 }
1172}1173}
11731174
1174static AstNode *ast_parse_addr_of(ParseContext *pc, size_t *token_index) {1175static AstNode *ast_parse_pointer_type(ParseContext *pc, size_t *token_index, Token *star_tok) {
1175 Token *ampersand_tok = ast_eat_token(pc, token_index, TokenIdAmpersand);1176 AstNode *node = ast_create_node(pc, NodeTypePointerType, star_tok);
11761177 node->data.pointer_type.star_token = star_tok;
1177 AstNode *node = ast_create_node(pc, NodeTypeAddrOfExpr, ampersand_tok);
11781178
1179 Token *token = &pc->tokens->at(*token_index);1179 Token *token = &pc->tokens->at(*token_index);
1180 if (token->id == TokenIdKeywordAlign) {1180 if (token->id == TokenIdKeywordAlign) {
1181 *token_index += 1;1181 *token_index += 1;
1182 ast_eat_token(pc, token_index, TokenIdLParen);1182 ast_eat_token(pc, token_index, TokenIdLParen);
1183 node->data.addr_of_expr.align_expr = ast_parse_expression(pc, token_index, true);1183 node->data.pointer_type.align_expr = ast_parse_expression(pc, token_index, true);
11841184
1185 token = &pc->tokens->at(*token_index);1185 token = &pc->tokens->at(*token_index);
1186 if (token->id == TokenIdColon) {1186 if (token->id == TokenIdColon) {
...@@ -1189,35 +1189,45 @@ static AstNode *ast_parse_addr_of(ParseContext *pc, size_t *token_index) {...@@ -1189,35 +1189,45 @@ static AstNode *ast_parse_addr_of(ParseContext *pc, size_t *token_index) {
1189 ast_eat_token(pc, token_index, TokenIdColon);1189 ast_eat_token(pc, token_index, TokenIdColon);
1190 Token *bit_offset_end_tok = ast_eat_token(pc, token_index, TokenIdIntLiteral);1190 Token *bit_offset_end_tok = ast_eat_token(pc, token_index, TokenIdIntLiteral);
11911191
1192 node->data.addr_of_expr.bit_offset_start = token_bigint(bit_offset_start_tok);1192 node->data.pointer_type.bit_offset_start = token_bigint(bit_offset_start_tok);
1193 node->data.addr_of_expr.bit_offset_end = token_bigint(bit_offset_end_tok);1193 node->data.pointer_type.bit_offset_end = token_bigint(bit_offset_end_tok);
1194 }1194 }
1195 ast_eat_token(pc, token_index, TokenIdRParen);1195 ast_eat_token(pc, token_index, TokenIdRParen);
1196 token = &pc->tokens->at(*token_index);1196 token = &pc->tokens->at(*token_index);
1197 }1197 }
1198 if (token->id == TokenIdKeywordConst) {1198 if (token->id == TokenIdKeywordConst) {
1199 *token_index += 1;1199 *token_index += 1;
1200 node->data.addr_of_expr.is_const = true;1200 node->data.pointer_type.is_const = true;
12011201
1202 token = &pc->tokens->at(*token_index);1202 token = &pc->tokens->at(*token_index);
1203 }1203 }
1204 if (token->id == TokenIdKeywordVolatile) {1204 if (token->id == TokenIdKeywordVolatile) {
1205 *token_index += 1;1205 *token_index += 1;
1206 node->data.addr_of_expr.is_volatile = true;1206 node->data.pointer_type.is_volatile = true;
1207 }1207 }
12081208
1209 node->data.addr_of_expr.op_expr = ast_parse_prefix_op_expr(pc, token_index, true);1209 node->data.pointer_type.op_expr = ast_parse_prefix_op_expr(pc, token_index, true);
1210 return node;1210 return node;
1211}1211}
12121212
1213/*1213/*
1214PrefixOpExpression = PrefixOp ErrorSetExpr | SuffixOpExpression1214PrefixOpExpression = PrefixOp ErrorSetExpr | SuffixOpExpression
1215PrefixOp = "!" | "-" | "~" | ("*" option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "??" | "-%" | "try" | "await"1215PrefixOp = "!" | "-" | "~" | (("*" | "[*]") option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "??" | "-%" | "try" | "await"
1216*/1216*/
1217static AstNode *ast_parse_prefix_op_expr(ParseContext *pc, size_t *token_index, bool mandatory) {1217static AstNode *ast_parse_prefix_op_expr(ParseContext *pc, size_t *token_index, bool mandatory) {
1218 Token *token = &pc->tokens->at(*token_index);1218 Token *token = &pc->tokens->at(*token_index);
1219 if (token->id == TokenIdAmpersand) {1219 if (token->id == TokenIdStar || token->id == TokenIdBracketStarBracket) {
1220 return ast_parse_addr_of(pc, token_index);1220 *token_index += 1;
1221 return ast_parse_pointer_type(pc, token_index, token);
1222 }
1223 if (token->id == TokenIdStarStar) {
1224 *token_index += 1;
1225 AstNode *child_node = ast_parse_pointer_type(pc, token_index, token);
1226 child_node->column += 1;
1227 AstNode *parent_node = ast_create_node(pc, NodeTypePointerType, token);
1228 parent_node->data.pointer_type.star_token = token;
1229 parent_node->data.pointer_type.op_expr = child_node;
1230 return parent_node;
1221 }1231 }
1222 if (token->id == TokenIdKeywordTry) {1232 if (token->id == TokenIdKeywordTry) {
1223 return ast_parse_try_expr(pc, token_index);1233 return ast_parse_try_expr(pc, token_index);
...@@ -1234,13 +1244,12 @@ static AstNode *ast_parse_prefix_op_expr(ParseContext *pc, size_t *token_index,...@@ -1234,13 +1244,12 @@ static AstNode *ast_parse_prefix_op_expr(ParseContext *pc, size_t *token_index,
12341244
12351245
1236 AstNode *node = ast_create_node(pc, NodeTypePrefixOpExpr, token);1246 AstNode *node = ast_create_node(pc, NodeTypePrefixOpExpr, token);
1237 AstNode *parent_node = node;
12381247
1239 AstNode *prefix_op_expr = ast_parse_error_set_expr(pc, token_index, true);1248 AstNode *prefix_op_expr = ast_parse_error_set_expr(pc, token_index, true);
1240 node->data.prefix_op_expr.primary_expr = prefix_op_expr;1249 node->data.prefix_op_expr.primary_expr = prefix_op_expr;
1241 node->data.prefix_op_expr.prefix_op = prefix_op;1250 node->data.prefix_op_expr.prefix_op = prefix_op;
12421251
1243 return parent_node;1252 return node;
1244}1253}
12451254
12461255
...@@ -3121,9 +3130,9 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont...@@ -3121,9 +3130,9 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont
3121 case NodeTypeErrorType:3130 case NodeTypeErrorType:
3122 // none3131 // none
3123 break;3132 break;
3124 case NodeTypeAddrOfExpr:3133 case NodeTypePointerType:
3125 visit_field(&node->data.addr_of_expr.align_expr, visit, context);3134 visit_field(&node->data.pointer_type.align_expr, visit, context);
3126 visit_field(&node->data.addr_of_expr.op_expr, visit, context);3135 visit_field(&node->data.pointer_type.op_expr, visit, context);
3127 break;3136 break;
3128 case NodeTypeErrorSetDecl:3137 case NodeTypeErrorSetDecl:
3129 visit_node_list(&node->data.err_set_decl.decls, visit, context);3138 visit_node_list(&node->data.err_set_decl.decls, visit, context);
src/tokenizer.cpp+30-1
...@@ -219,6 +219,8 @@ enum TokenizeState {...@@ -219,6 +219,8 @@ enum TokenizeState {
219 TokenizeStateSawAtSign,219 TokenizeStateSawAtSign,
220 TokenizeStateCharCode,220 TokenizeStateCharCode,
221 TokenizeStateError,221 TokenizeStateError,
222 TokenizeStateLBracket,
223 TokenizeStateLBracketStar,
222};224};
223225
224226
...@@ -539,8 +541,8 @@ void tokenize(Buf *buf, Tokenization *out) {...@@ -539,8 +541,8 @@ void tokenize(Buf *buf, Tokenization *out) {
539 end_token(&t);541 end_token(&t);
540 break;542 break;
541 case '[':543 case '[':
544 t.state = TokenizeStateLBracket;
542 begin_token(&t, TokenIdLBracket);545 begin_token(&t, TokenIdLBracket);
543 end_token(&t);
544 break;546 break;
545 case ']':547 case ']':
546 begin_token(&t, TokenIdRBracket);548 begin_token(&t, TokenIdRBracket);
...@@ -852,6 +854,30 @@ void tokenize(Buf *buf, Tokenization *out) {...@@ -852,6 +854,30 @@ void tokenize(Buf *buf, Tokenization *out) {
852 continue;854 continue;
853 }855 }
854 break;856 break;
857 case TokenizeStateLBracket:
858 switch (c) {
859 case '*':
860 t.state = TokenizeStateLBracketStar;
861 set_token_id(&t, t.cur_tok, TokenIdBracketStarBracket);
862 break;
863 default:
864 // reinterpret as just an lbracket
865 t.pos -= 1;
866 end_token(&t);
867 t.state = TokenizeStateStart;
868 continue;
869 }
870 break;
871 case TokenizeStateLBracketStar:
872 switch (c) {
873 case ']':
874 end_token(&t);
875 t.state = TokenizeStateStart;
876 break;
877 default:
878 invalid_char_error(&t, c);
879 }
880 break;
855 case TokenizeStateSawPlusPercent:881 case TokenizeStateSawPlusPercent:
856 switch (c) {882 switch (c) {
857 case '=':883 case '=':
...@@ -1467,12 +1493,14 @@ void tokenize(Buf *buf, Tokenization *out) {...@@ -1467,12 +1493,14 @@ void tokenize(Buf *buf, Tokenization *out) {
1467 case TokenizeStateLineString:1493 case TokenizeStateLineString:
1468 case TokenizeStateLineStringEnd:1494 case TokenizeStateLineStringEnd:
1469 case TokenizeStateSawBarBar:1495 case TokenizeStateSawBarBar:
1496 case TokenizeStateLBracket:
1470 end_token(&t);1497 end_token(&t);
1471 break;1498 break;
1472 case TokenizeStateSawDotDot:1499 case TokenizeStateSawDotDot:
1473 case TokenizeStateSawBackslash:1500 case TokenizeStateSawBackslash:
1474 case TokenizeStateLineStringContinue:1501 case TokenizeStateLineStringContinue:
1475 case TokenizeStateLineStringContinueC:1502 case TokenizeStateLineStringContinueC:
1503 case TokenizeStateLBracketStar:
1476 tokenize_error(&t, "unexpected EOF");1504 tokenize_error(&t, "unexpected EOF");
1477 break;1505 break;
1478 case TokenizeStateLineComment:1506 case TokenizeStateLineComment:
...@@ -1509,6 +1537,7 @@ const char * token_name(TokenId id) {...@@ -1509,6 +1537,7 @@ const char * token_name(TokenId id) {
1509 case TokenIdBitShiftRight: return ">>";1537 case TokenIdBitShiftRight: return ">>";
1510 case TokenIdBitShiftRightEq: return ">>=";1538 case TokenIdBitShiftRightEq: return ">>=";
1511 case TokenIdBitXorEq: return "^=";1539 case TokenIdBitXorEq: return "^=";
1540 case TokenIdBracketStarBracket: return "[*]";
1512 case TokenIdCharLiteral: return "CharLiteral";1541 case TokenIdCharLiteral: return "CharLiteral";
1513 case TokenIdCmpEq: return "==";1542 case TokenIdCmpEq: return "==";
1514 case TokenIdCmpGreaterOrEq: return ">=";1543 case TokenIdCmpGreaterOrEq: return ">=";
src/tokenizer.hpp+1
...@@ -28,6 +28,7 @@ enum TokenId {...@@ -28,6 +28,7 @@ enum TokenId {
28 TokenIdBitShiftRight,28 TokenIdBitShiftRight,
29 TokenIdBitShiftRightEq,29 TokenIdBitShiftRightEq,
30 TokenIdBitXorEq,30 TokenIdBitXorEq,
31 TokenIdBracketStarBracket,
31 TokenIdCharLiteral,32 TokenIdCharLiteral,
32 TokenIdCmpEq,33 TokenIdCmpEq,
33 TokenIdCmpGreaterOrEq,34 TokenIdCmpGreaterOrEq,
src/translate_c.cpp+20-13
...@@ -276,11 +276,18 @@ static AstNode *maybe_suppress_result(Context *c, ResultUsed result_used, AstNod...@@ -276,11 +276,18 @@ static AstNode *maybe_suppress_result(Context *c, ResultUsed result_used, AstNod
276 node);276 node);
277}277}
278278
279static AstNode *trans_create_node_addr_of(Context *c, bool is_const, bool is_volatile, AstNode *child_node) {279static AstNode *trans_create_node_ptr_type(Context *c, bool is_const, bool is_volatile, AstNode *child_node) {
280 AstNode *node = trans_create_node(c, NodeTypeAddrOfExpr);280 AstNode *node = trans_create_node(c, NodeTypePointerType);
281 node->data.addr_of_expr.is_const = is_const;281 node->data.pointer_type.is_const = is_const;
282 node->data.addr_of_expr.is_volatile = is_volatile;282 node->data.pointer_type.is_volatile = is_volatile;
283 node->data.addr_of_expr.op_expr = child_node;283 node->data.pointer_type.op_expr = child_node;
284 return node;
285}
286
287static AstNode *trans_create_node_addr_of(Context *c, AstNode *child_node) {
288 AstNode *node = trans_create_node(c, NodeTypePrefixOpExpr);
289 node->data.prefix_op_expr.prefix_op = PrefixOpAddrOf;
290 node->data.prefix_op_expr.primary_expr = child_node;
284 return node;291 return node;
285}292}
286293
...@@ -849,7 +856,7 @@ static AstNode *trans_type(Context *c, const Type *ty, const SourceLocation &sou...@@ -849,7 +856,7 @@ static AstNode *trans_type(Context *c, const Type *ty, const SourceLocation &sou
849 return trans_create_node_prefix_op(c, PrefixOpMaybe, child_node);856 return trans_create_node_prefix_op(c, PrefixOpMaybe, child_node);
850 }857 }
851858
852 AstNode *pointer_node = trans_create_node_addr_of(c, child_qt.isConstQualified(),859 AstNode *pointer_node = trans_create_node_ptr_type(c, child_qt.isConstQualified(),
853 child_qt.isVolatileQualified(), child_node);860 child_qt.isVolatileQualified(), child_node);
854 return trans_create_node_prefix_op(c, PrefixOpMaybe, pointer_node);861 return trans_create_node_prefix_op(c, PrefixOpMaybe, pointer_node);
855 }862 }
...@@ -1034,7 +1041,7 @@ static AstNode *trans_type(Context *c, const Type *ty, const SourceLocation &sou...@@ -1034,7 +1041,7 @@ static AstNode *trans_type(Context *c, const Type *ty, const SourceLocation &sou
1034 emit_warning(c, source_loc, "unresolved array element type");1041 emit_warning(c, source_loc, "unresolved array element type");
1035 return nullptr;1042 return nullptr;
1036 }1043 }
1037 AstNode *pointer_node = trans_create_node_addr_of(c, child_qt.isConstQualified(),1044 AstNode *pointer_node = trans_create_node_ptr_type(c, child_qt.isConstQualified(),
1038 child_qt.isVolatileQualified(), child_type_node);1045 child_qt.isVolatileQualified(), child_type_node);
1039 return pointer_node;1046 return pointer_node;
1040 }1047 }
...@@ -1403,7 +1410,7 @@ static AstNode *trans_create_compound_assign_shift(Context *c, ResultUsed result...@@ -1403,7 +1410,7 @@ static AstNode *trans_create_compound_assign_shift(Context *c, ResultUsed result
1403 // const _ref = &lhs;1410 // const _ref = &lhs;
1404 AstNode *lhs = trans_expr(c, ResultUsedYes, &child_scope->base, stmt->getLHS(), TransLValue);1411 AstNode *lhs = trans_expr(c, ResultUsedYes, &child_scope->base, stmt->getLHS(), TransLValue);
1405 if (lhs == nullptr) return nullptr;1412 if (lhs == nullptr) return nullptr;
1406 AstNode *addr_of_lhs = trans_create_node_addr_of(c, false, false, lhs);1413 AstNode *addr_of_lhs = trans_create_node_addr_of(c, lhs);
1407 // TODO: avoid name collisions with generated variable names1414 // TODO: avoid name collisions with generated variable names
1408 Buf* tmp_var_name = buf_create_from_str("_ref");1415 Buf* tmp_var_name = buf_create_from_str("_ref");
1409 AstNode *tmp_var_decl = trans_create_node_var_decl_local(c, true, tmp_var_name, nullptr, addr_of_lhs);1416 AstNode *tmp_var_decl = trans_create_node_var_decl_local(c, true, tmp_var_name, nullptr, addr_of_lhs);
...@@ -1477,7 +1484,7 @@ static AstNode *trans_create_compound_assign(Context *c, ResultUsed result_used,...@@ -1477,7 +1484,7 @@ static AstNode *trans_create_compound_assign(Context *c, ResultUsed result_used,
1477 // const _ref = &lhs;1484 // const _ref = &lhs;
1478 AstNode *lhs = trans_expr(c, ResultUsedYes, &child_scope->base, stmt->getLHS(), TransLValue);1485 AstNode *lhs = trans_expr(c, ResultUsedYes, &child_scope->base, stmt->getLHS(), TransLValue);
1479 if (lhs == nullptr) return nullptr;1486 if (lhs == nullptr) return nullptr;
1480 AstNode *addr_of_lhs = trans_create_node_addr_of(c, false, false, lhs);1487 AstNode *addr_of_lhs = trans_create_node_addr_of(c, lhs);
1481 // TODO: avoid name collisions with generated variable names1488 // TODO: avoid name collisions with generated variable names
1482 Buf* tmp_var_name = buf_create_from_str("_ref");1489 Buf* tmp_var_name = buf_create_from_str("_ref");
1483 AstNode *tmp_var_decl = trans_create_node_var_decl_local(c, true, tmp_var_name, nullptr, addr_of_lhs);1490 AstNode *tmp_var_decl = trans_create_node_var_decl_local(c, true, tmp_var_name, nullptr, addr_of_lhs);
...@@ -1814,7 +1821,7 @@ static AstNode *trans_create_post_crement(Context *c, ResultUsed result_used, Tr...@@ -1814,7 +1821,7 @@ static AstNode *trans_create_post_crement(Context *c, ResultUsed result_used, Tr
1814 // const _ref = &expr;1821 // const _ref = &expr;
1815 AstNode *expr = trans_expr(c, ResultUsedYes, &child_scope->base, op_expr, TransLValue);1822 AstNode *expr = trans_expr(c, ResultUsedYes, &child_scope->base, op_expr, TransLValue);
1816 if (expr == nullptr) return nullptr;1823 if (expr == nullptr) return nullptr;
1817 AstNode *addr_of_expr = trans_create_node_addr_of(c, false, false, expr);1824 AstNode *addr_of_expr = trans_create_node_addr_of(c, expr);
1818 // TODO: avoid name collisions with generated variable names1825 // TODO: avoid name collisions with generated variable names
1819 Buf* ref_var_name = buf_create_from_str("_ref");1826 Buf* ref_var_name = buf_create_from_str("_ref");
1820 AstNode *ref_var_decl = trans_create_node_var_decl_local(c, true, ref_var_name, nullptr, addr_of_expr);1827 AstNode *ref_var_decl = trans_create_node_var_decl_local(c, true, ref_var_name, nullptr, addr_of_expr);
...@@ -1869,7 +1876,7 @@ static AstNode *trans_create_pre_crement(Context *c, ResultUsed result_used, Tra...@@ -1869,7 +1876,7 @@ static AstNode *trans_create_pre_crement(Context *c, ResultUsed result_used, Tra
1869 // const _ref = &expr;1876 // const _ref = &expr;
1870 AstNode *expr = trans_expr(c, ResultUsedYes, &child_scope->base, op_expr, TransLValue);1877 AstNode *expr = trans_expr(c, ResultUsedYes, &child_scope->base, op_expr, TransLValue);
1871 if (expr == nullptr) return nullptr;1878 if (expr == nullptr) return nullptr;
1872 AstNode *addr_of_expr = trans_create_node_addr_of(c, false, false, expr);1879 AstNode *addr_of_expr = trans_create_node_addr_of(c, expr);
1873 // TODO: avoid name collisions with generated variable names1880 // TODO: avoid name collisions with generated variable names
1874 Buf* ref_var_name = buf_create_from_str("_ref");1881 Buf* ref_var_name = buf_create_from_str("_ref");
1875 AstNode *ref_var_decl = trans_create_node_var_decl_local(c, true, ref_var_name, nullptr, addr_of_expr);1882 AstNode *ref_var_decl = trans_create_node_var_decl_local(c, true, ref_var_name, nullptr, addr_of_expr);
...@@ -1918,7 +1925,7 @@ static AstNode *trans_unary_operator(Context *c, ResultUsed result_used, TransSc...@@ -1918,7 +1925,7 @@ static AstNode *trans_unary_operator(Context *c, ResultUsed result_used, TransSc
1918 AstNode *value_node = trans_expr(c, result_used, scope, stmt->getSubExpr(), TransLValue);1925 AstNode *value_node = trans_expr(c, result_used, scope, stmt->getSubExpr(), TransLValue);
1919 if (value_node == nullptr)1926 if (value_node == nullptr)
1920 return value_node;1927 return value_node;
1921 return trans_create_node_addr_of(c, false, false, value_node);1928 return trans_create_node_addr_of(c, value_node);
1922 }1929 }
1923 case UO_Deref:1930 case UO_Deref:
1924 {1931 {
...@@ -4443,7 +4450,7 @@ static AstNode *parse_ctok_suffix_op_expr(Context *c, CTokenize *ctok, size_t *t...@@ -4443,7 +4450,7 @@ static AstNode *parse_ctok_suffix_op_expr(Context *c, CTokenize *ctok, size_t *t
4443 } else if (first_tok->id == CTokIdAsterisk) {4450 } else if (first_tok->id == CTokIdAsterisk) {
4444 *tok_i += 1;4451 *tok_i += 1;
44454452
4446 node = trans_create_node_addr_of(c, false, false, node);4453 node = trans_create_node_ptr_type(c, false, false, node);
4447 } else {4454 } else {
4448 return node;4455 return node;
4449 }4456 }
src/util.hpp+5-5
...@@ -38,11 +38,11 @@ ATTRIBUTE_NORETURN...@@ -38,11 +38,11 @@ ATTRIBUTE_NORETURN
38ATTRIBUTE_PRINTF(1, 2)38ATTRIBUTE_PRINTF(1, 2)
39void zig_panic(const char *format, ...);39void zig_panic(const char *format, ...);
4040
41ATTRIBUTE_COLD41#ifdef WIN32
42ATTRIBUTE_NORETURN42#define __func__ __FUNCTION__
43static inline void zig_unreachable(void) {43#endif
44 zig_panic("unreachable");44
45}45#define zig_unreachable() zig_panic("unreachable: %s:%s:%d", __FILE__, __func__, __LINE__)
4646
47#if defined(_MSC_VER)47#if defined(_MSC_VER)
48static inline int clzll(unsigned long long mask) {48static inline int clzll(unsigned long long mask) {
std/array_list.zig+26-26
...@@ -17,10 +17,10 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {...@@ -17,10 +17,10 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
17 /// you uninitialized memory.17 /// you uninitialized memory.
18 items: []align(A) T,18 items: []align(A) T,
19 len: usize,19 len: usize,
20 allocator: &Allocator,20 allocator: *Allocator,
2121
22 /// Deinitialize with `deinit` or use `toOwnedSlice`.22 /// Deinitialize with `deinit` or use `toOwnedSlice`.
23 pub fn init(allocator: &Allocator) Self {23 pub fn init(allocator: *Allocator) Self {
24 return Self{24 return Self{
25 .items = []align(A) T{},25 .items = []align(A) T{},
26 .len = 0,26 .len = 0,
...@@ -28,30 +28,30 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {...@@ -28,30 +28,30 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
28 };28 };
29 }29 }
3030
31 pub fn deinit(l: &const Self) void {31 pub fn deinit(l: *const Self) void {
32 l.allocator.free(l.items);32 l.allocator.free(l.items);
33 }33 }
3434
35 pub fn toSlice(l: &const Self) []align(A) T {35 pub fn toSlice(l: *const Self) []align(A) T {
36 return l.items[0..l.len];36 return l.items[0..l.len];
37 }37 }
3838
39 pub fn toSliceConst(l: &const Self) []align(A) const T {39 pub fn toSliceConst(l: *const Self) []align(A) const T {
40 return l.items[0..l.len];40 return l.items[0..l.len];
41 }41 }
4242
43 pub fn at(l: &const Self, n: usize) T {43 pub fn at(l: *const Self, n: usize) T {
44 return l.toSliceConst()[n];44 return l.toSliceConst()[n];
45 }45 }
4646
47 pub fn count(self: &const Self) usize {47 pub fn count(self: *const Self) usize {
48 return self.len;48 return self.len;
49 }49 }
5050
51 /// ArrayList takes ownership of the passed in slice. The slice must have been51 /// ArrayList takes ownership of the passed in slice. The slice must have been
52 /// allocated with `allocator`.52 /// allocated with `allocator`.
53 /// Deinitialize with `deinit` or use `toOwnedSlice`.53 /// Deinitialize with `deinit` or use `toOwnedSlice`.
54 pub fn fromOwnedSlice(allocator: &Allocator, slice: []align(A) T) Self {54 pub fn fromOwnedSlice(allocator: *Allocator, slice: []align(A) T) Self {
55 return Self{55 return Self{
56 .items = slice,56 .items = slice,
57 .len = slice.len,57 .len = slice.len,
...@@ -60,51 +60,51 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {...@@ -60,51 +60,51 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
60 }60 }
6161
62 /// The caller owns the returned memory. ArrayList becomes empty.62 /// The caller owns the returned memory. ArrayList becomes empty.
63 pub fn toOwnedSlice(self: &Self) []align(A) T {63 pub fn toOwnedSlice(self: *Self) []align(A) T {
64 const allocator = self.allocator;64 const allocator = self.allocator;
65 const result = allocator.alignedShrink(T, A, self.items, self.len);65 const result = allocator.alignedShrink(T, A, self.items, self.len);
66 self.* = init(allocator);66 self.* = init(allocator);
67 return result;67 return result;
68 }68 }
6969
70 pub fn insert(l: &Self, n: usize, item: &const T) !void {70 pub fn insert(l: *Self, n: usize, item: *const T) !void {
71 try l.ensureCapacity(l.len + 1);71 try l.ensureCapacity(l.len + 1);
72 l.len += 1;72 l.len += 1;
7373
74 mem.copy(T, l.items[n + 1..l.len], l.items[n..l.len - 1]);74 mem.copy(T, l.items[n + 1 .. l.len], l.items[n .. l.len - 1]);
75 l.items[n] = item.*;75 l.items[n] = item.*;
76 }76 }
7777
78 pub fn insertSlice(l: &Self, n: usize, items: []align(A) const T) !void {78 pub fn insertSlice(l: *Self, n: usize, items: []align(A) const T) !void {
79 try l.ensureCapacity(l.len + items.len);79 try l.ensureCapacity(l.len + items.len);
80 l.len += items.len;80 l.len += items.len;
8181
82 mem.copy(T, l.items[n + items.len..l.len], l.items[n..l.len - items.len]);82 mem.copy(T, l.items[n + items.len .. l.len], l.items[n .. l.len - items.len]);
83 mem.copy(T, l.items[n..n + items.len], items);83 mem.copy(T, l.items[n .. n + items.len], items);
84 }84 }
8585
86 pub fn append(l: &Self, item: &const T) !void {86 pub fn append(l: *Self, item: *const T) !void {
87 const new_item_ptr = try l.addOne();87 const new_item_ptr = try l.addOne();
88 new_item_ptr.* = item.*;88 new_item_ptr.* = item.*;
89 }89 }
9090
91 pub fn appendSlice(l: &Self, items: []align(A) const T) !void {91 pub fn appendSlice(l: *Self, items: []align(A) const T) !void {
92 try l.ensureCapacity(l.len + items.len);92 try l.ensureCapacity(l.len + items.len);
93 mem.copy(T, l.items[l.len..], items);93 mem.copy(T, l.items[l.len..], items);
94 l.len += items.len;94 l.len += items.len;
95 }95 }
9696
97 pub fn resize(l: &Self, new_len: usize) !void {97 pub fn resize(l: *Self, new_len: usize) !void {
98 try l.ensureCapacity(new_len);98 try l.ensureCapacity(new_len);
99 l.len = new_len;99 l.len = new_len;
100 }100 }
101101
102 pub fn shrink(l: &Self, new_len: usize) void {102 pub fn shrink(l: *Self, new_len: usize) void {
103 assert(new_len <= l.len);103 assert(new_len <= l.len);
104 l.len = new_len;104 l.len = new_len;
105 }105 }
106106
107 pub fn ensureCapacity(l: &Self, new_capacity: usize) !void {107 pub fn ensureCapacity(l: *Self, new_capacity: usize) !void {
108 var better_capacity = l.items.len;108 var better_capacity = l.items.len;
109 if (better_capacity >= new_capacity) return;109 if (better_capacity >= new_capacity) return;
110 while (true) {110 while (true) {
...@@ -114,7 +114,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {...@@ -114,7 +114,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
114 l.items = try l.allocator.alignedRealloc(T, A, l.items, better_capacity);114 l.items = try l.allocator.alignedRealloc(T, A, l.items, better_capacity);
115 }115 }
116116
117 pub fn addOne(l: &Self) !&T {117 pub fn addOne(l: *Self) !*T {
118 const new_length = l.len + 1;118 const new_length = l.len + 1;
119 try l.ensureCapacity(new_length);119 try l.ensureCapacity(new_length);
120 const result = &l.items[l.len];120 const result = &l.items[l.len];
...@@ -122,34 +122,34 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {...@@ -122,34 +122,34 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
122 return result;122 return result;
123 }123 }
124124
125 pub fn pop(self: &Self) T {125 pub fn pop(self: *Self) T {
126 self.len -= 1;126 self.len -= 1;
127 return self.items[self.len];127 return self.items[self.len];
128 }128 }
129129
130 pub fn popOrNull(self: &Self) ?T {130 pub fn popOrNull(self: *Self) ?T {
131 if (self.len == 0) return null;131 if (self.len == 0) return null;
132 return self.pop();132 return self.pop();
133 }133 }
134134
135 pub const Iterator = struct {135 pub const Iterator = struct {
136 list: &const Self,136 list: *const Self,
137 // how many items have we returned137 // how many items have we returned
138 count: usize,138 count: usize,
139139
140 pub fn next(it: &Iterator) ?T {140 pub fn next(it: *Iterator) ?T {
141 if (it.count >= it.list.len) return null;141 if (it.count >= it.list.len) return null;
142 const val = it.list.at(it.count);142 const val = it.list.at(it.count);
143 it.count += 1;143 it.count += 1;
144 return val;144 return val;
145 }145 }
146146
147 pub fn reset(it: &Iterator) void {147 pub fn reset(it: *Iterator) void {
148 it.count = 0;148 it.count = 0;
149 }149 }
150 };150 };
151151
152 pub fn iterator(self: &const Self) Iterator {152 pub fn iterator(self: *const Self) Iterator {
153 return Iterator{153 return Iterator{
154 .list = self,154 .list = self,
155 .count = 0,155 .count = 0,
std/atomic/queue.zig+16-16
...@@ -5,36 +5,36 @@ const AtomicRmwOp = builtin.AtomicRmwOp;...@@ -5,36 +5,36 @@ const AtomicRmwOp = builtin.AtomicRmwOp;
5/// Many reader, many writer, non-allocating, thread-safe, lock-free5/// Many reader, many writer, non-allocating, thread-safe, lock-free
6pub fn Queue(comptime T: type) type {6pub fn Queue(comptime T: type) type {
7 return struct {7 return struct {
8 head: &Node,8 head: *Node,
9 tail: &Node,9 tail: *Node,
10 root: Node,10 root: Node,
1111
12 pub const Self = this;12 pub const Self = this;
1313
14 pub const Node = struct {14 pub const Node = struct {
15 next: ?&Node,15 next: ?*Node,
16 data: T,16 data: T,
17 };17 };
1818
19 // TODO: well defined copy elision: https://github.com/ziglang/zig/issues/28719 // TODO: well defined copy elision: https://github.com/ziglang/zig/issues/287
20 pub fn init(self: &Self) void {20 pub fn init(self: *Self) void {
21 self.root.next = null;21 self.root.next = null;
22 self.head = &self.root;22 self.head = &self.root;
23 self.tail = &self.root;23 self.tail = &self.root;
24 }24 }
2525
26 pub fn put(self: &Self, node: &Node) void {26 pub fn put(self: *Self, node: *Node) void {
27 node.next = null;27 node.next = null;
2828
29 const tail = @atomicRmw(&Node, &self.tail, AtomicRmwOp.Xchg, node, AtomicOrder.SeqCst);29 const tail = @atomicRmw(*Node, &self.tail, AtomicRmwOp.Xchg, node, AtomicOrder.SeqCst);
30 _ = @atomicRmw(?&Node, &tail.next, AtomicRmwOp.Xchg, node, AtomicOrder.SeqCst);30 _ = @atomicRmw(?*Node, &tail.next, AtomicRmwOp.Xchg, node, AtomicOrder.SeqCst);
31 }31 }
3232
33 pub fn get(self: &Self) ?&Node {33 pub fn get(self: *Self) ?*Node {
34 var head = @atomicLoad(&Node, &self.head, AtomicOrder.SeqCst);34 var head = @atomicLoad(*Node, &self.head, AtomicOrder.SeqCst);
35 while (true) {35 while (true) {
36 const node = head.next ?? return null;36 const node = head.next ?? return null;
37 head = @cmpxchgWeak(&Node, &self.head, head, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return node;37 head = @cmpxchgWeak(*Node, &self.head, head, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return node;
38 }38 }
39 }39 }
40 };40 };
...@@ -42,8 +42,8 @@ pub fn Queue(comptime T: type) type {...@@ -42,8 +42,8 @@ pub fn Queue(comptime T: type) type {
4242
43const std = @import("std");43const std = @import("std");
44const Context = struct {44const Context = struct {
45 allocator: &std.mem.Allocator,45 allocator: *std.mem.Allocator,
46 queue: &Queue(i32),46 queue: *Queue(i32),
47 put_sum: isize,47 put_sum: isize,
48 get_sum: isize,48 get_sum: isize,
49 get_count: usize,49 get_count: usize,
...@@ -79,11 +79,11 @@ test "std.atomic.queue" {...@@ -79,11 +79,11 @@ test "std.atomic.queue" {
79 .get_count = 0,79 .get_count = 0,
80 };80 };
8181
82 var putters: [put_thread_count]&std.os.Thread = undefined;82 var putters: [put_thread_count]*std.os.Thread = undefined;
83 for (putters) |*t| {83 for (putters) |*t| {
84 t.* = try std.os.spawnThread(&context, startPuts);84 t.* = try std.os.spawnThread(&context, startPuts);
85 }85 }
86 var getters: [put_thread_count]&std.os.Thread = undefined;86 var getters: [put_thread_count]*std.os.Thread = undefined;
87 for (getters) |*t| {87 for (getters) |*t| {
88 t.* = try std.os.spawnThread(&context, startGets);88 t.* = try std.os.spawnThread(&context, startGets);
89 }89 }
...@@ -98,7 +98,7 @@ test "std.atomic.queue" {...@@ -98,7 +98,7 @@ test "std.atomic.queue" {
98 std.debug.assert(context.get_count == puts_per_thread * put_thread_count);98 std.debug.assert(context.get_count == puts_per_thread * put_thread_count);
99}99}
100100
101fn startPuts(ctx: &Context) u8 {101fn startPuts(ctx: *Context) u8 {
102 var put_count: usize = puts_per_thread;102 var put_count: usize = puts_per_thread;
103 var r = std.rand.DefaultPrng.init(0xdeadbeef);103 var r = std.rand.DefaultPrng.init(0xdeadbeef);
104 while (put_count != 0) : (put_count -= 1) {104 while (put_count != 0) : (put_count -= 1) {
...@@ -112,7 +112,7 @@ fn startPuts(ctx: &Context) u8 {...@@ -112,7 +112,7 @@ fn startPuts(ctx: &Context) u8 {
112 return 0;112 return 0;
113}113}
114114
115fn startGets(ctx: &Context) u8 {115fn startGets(ctx: *Context) u8 {
116 while (true) {116 while (true) {
117 while (ctx.queue.get()) |node| {117 while (ctx.queue.get()) |node| {
118 std.os.time.sleep(0, 1); // let the os scheduler be our fuzz118 std.os.time.sleep(0, 1); // let the os scheduler be our fuzz
std/atomic/stack.zig+18-18
...@@ -4,12 +4,12 @@ const AtomicOrder = builtin.AtomicOrder;...@@ -4,12 +4,12 @@ const AtomicOrder = builtin.AtomicOrder;
4/// Many reader, many writer, non-allocating, thread-safe, lock-free4/// Many reader, many writer, non-allocating, thread-safe, lock-free
5pub fn Stack(comptime T: type) type {5pub fn Stack(comptime T: type) type {
6 return struct {6 return struct {
7 root: ?&Node,7 root: ?*Node,
88
9 pub const Self = this;9 pub const Self = this;
1010
11 pub const Node = struct {11 pub const Node = struct {
12 next: ?&Node,12 next: ?*Node,
13 data: T,13 data: T,
14 };14 };
1515
...@@ -19,36 +19,36 @@ pub fn Stack(comptime T: type) type {...@@ -19,36 +19,36 @@ pub fn Stack(comptime T: type) type {
1919
20 /// push operation, but only if you are the first item in the stack. if you did not succeed in20 /// push operation, but only if you are the first item in the stack. if you did not succeed in
21 /// being the first item in the stack, returns the other item that was there.21 /// being the first item in the stack, returns the other item that was there.
22 pub fn pushFirst(self: &Self, node: &Node) ?&Node {22 pub fn pushFirst(self: *Self, node: *Node) ?*Node {
23 node.next = null;23 node.next = null;
24 return @cmpxchgStrong(?&Node, &self.root, null, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst);24 return @cmpxchgStrong(?*Node, &self.root, null, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst);
25 }25 }
2626
27 pub fn push(self: &Self, node: &Node) void {27 pub fn push(self: *Self, node: *Node) void {
28 var root = @atomicLoad(?&Node, &self.root, AtomicOrder.SeqCst);28 var root = @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst);
29 while (true) {29 while (true) {
30 node.next = root;30 node.next = root;
31 root = @cmpxchgWeak(?&Node, &self.root, root, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? break;31 root = @cmpxchgWeak(?*Node, &self.root, root, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? break;
32 }32 }
33 }33 }
3434
35 pub fn pop(self: &Self) ?&Node {35 pub fn pop(self: *Self) ?*Node {
36 var root = @atomicLoad(?&Node, &self.root, AtomicOrder.SeqCst);36 var root = @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst);
37 while (true) {37 while (true) {
38 root = @cmpxchgWeak(?&Node, &self.root, root, (root ?? return null).next, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return root;38 root = @cmpxchgWeak(?*Node, &self.root, root, (root ?? return null).next, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return root;
39 }39 }
40 }40 }
4141
42 pub fn isEmpty(self: &Self) bool {42 pub fn isEmpty(self: *Self) bool {
43 return @atomicLoad(?&Node, &self.root, AtomicOrder.SeqCst) == null;43 return @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst) == null;
44 }44 }
45 };45 };
46}46}
4747
48const std = @import("std");48const std = @import("std");
49const Context = struct {49const Context = struct {
50 allocator: &std.mem.Allocator,50 allocator: *std.mem.Allocator,
51 stack: &Stack(i32),51 stack: *Stack(i32),
52 put_sum: isize,52 put_sum: isize,
53 get_sum: isize,53 get_sum: isize,
54 get_count: usize,54 get_count: usize,
...@@ -82,11 +82,11 @@ test "std.atomic.stack" {...@@ -82,11 +82,11 @@ test "std.atomic.stack" {
82 .get_count = 0,82 .get_count = 0,
83 };83 };
8484
85 var putters: [put_thread_count]&std.os.Thread = undefined;85 var putters: [put_thread_count]*std.os.Thread = undefined;
86 for (putters) |*t| {86 for (putters) |*t| {
87 t.* = try std.os.spawnThread(&context, startPuts);87 t.* = try std.os.spawnThread(&context, startPuts);
88 }88 }
89 var getters: [put_thread_count]&std.os.Thread = undefined;89 var getters: [put_thread_count]*std.os.Thread = undefined;
90 for (getters) |*t| {90 for (getters) |*t| {
91 t.* = try std.os.spawnThread(&context, startGets);91 t.* = try std.os.spawnThread(&context, startGets);
92 }92 }
...@@ -101,7 +101,7 @@ test "std.atomic.stack" {...@@ -101,7 +101,7 @@ test "std.atomic.stack" {
101 std.debug.assert(context.get_count == puts_per_thread * put_thread_count);101 std.debug.assert(context.get_count == puts_per_thread * put_thread_count);
102}102}
103103
104fn startPuts(ctx: &Context) u8 {104fn startPuts(ctx: *Context) u8 {
105 var put_count: usize = puts_per_thread;105 var put_count: usize = puts_per_thread;
106 var r = std.rand.DefaultPrng.init(0xdeadbeef);106 var r = std.rand.DefaultPrng.init(0xdeadbeef);
107 while (put_count != 0) : (put_count -= 1) {107 while (put_count != 0) : (put_count -= 1) {
...@@ -115,7 +115,7 @@ fn startPuts(ctx: &Context) u8 {...@@ -115,7 +115,7 @@ fn startPuts(ctx: &Context) u8 {
115 return 0;115 return 0;
116}116}
117117
118fn startGets(ctx: &Context) u8 {118fn startGets(ctx: *Context) u8 {
119 while (true) {119 while (true) {
120 while (ctx.stack.pop()) |node| {120 while (ctx.stack.pop()) |node| {
121 std.os.time.sleep(0, 1); // let the os scheduler be our fuzz121 std.os.time.sleep(0, 1); // let the os scheduler be our fuzz
std/base64.zig+8-7
...@@ -32,7 +32,7 @@ pub const Base64Encoder = struct {...@@ -32,7 +32,7 @@ pub const Base64Encoder = struct {
32 }32 }
3333
34 /// dest.len must be what you get from ::calcSize.34 /// dest.len must be what you get from ::calcSize.
35 pub fn encode(encoder: &const Base64Encoder, dest: []u8, source: []const u8) void {35 pub fn encode(encoder: *const Base64Encoder, dest: []u8, source: []const u8) void {
36 assert(dest.len == Base64Encoder.calcSize(source.len));36 assert(dest.len == Base64Encoder.calcSize(source.len));
3737
38 var i: usize = 0;38 var i: usize = 0;
...@@ -81,6 +81,7 @@ pub const Base64Decoder = struct {...@@ -81,6 +81,7 @@ pub const Base64Decoder = struct {
81 /// e.g. 'A' => 0.81 /// e.g. 'A' => 0.
82 /// undefined for any value not in the 64 alphabet chars.82 /// undefined for any value not in the 64 alphabet chars.
83 char_to_index: [256]u8,83 char_to_index: [256]u8,
84
84 /// true only for the 64 chars in the alphabet, not the pad char.85 /// true only for the 64 chars in the alphabet, not the pad char.
85 char_in_alphabet: [256]bool,86 char_in_alphabet: [256]bool,
86 pad_char: u8,87 pad_char: u8,
...@@ -106,7 +107,7 @@ pub const Base64Decoder = struct {...@@ -106,7 +107,7 @@ pub const Base64Decoder = struct {
106 }107 }
107108
108 /// If the encoded buffer is detected to be invalid, returns error.InvalidPadding.109 /// If the encoded buffer is detected to be invalid, returns error.InvalidPadding.
109 pub fn calcSize(decoder: &const Base64Decoder, source: []const u8) !usize {110 pub fn calcSize(decoder: *const Base64Decoder, source: []const u8) !usize {
110 if (source.len % 4 != 0) return error.InvalidPadding;111 if (source.len % 4 != 0) return error.InvalidPadding;
111 return calcDecodedSizeExactUnsafe(source, decoder.pad_char);112 return calcDecodedSizeExactUnsafe(source, decoder.pad_char);
112 }113 }
...@@ -114,7 +115,7 @@ pub const Base64Decoder = struct {...@@ -114,7 +115,7 @@ pub const Base64Decoder = struct {
114 /// dest.len must be what you get from ::calcSize.115 /// dest.len must be what you get from ::calcSize.
115 /// invalid characters result in error.InvalidCharacter.116 /// invalid characters result in error.InvalidCharacter.
116 /// invalid padding results in error.InvalidPadding.117 /// invalid padding results in error.InvalidPadding.
117 pub fn decode(decoder: &const Base64Decoder, dest: []u8, source: []const u8) !void {118 pub fn decode(decoder: *const Base64Decoder, dest: []u8, source: []const u8) !void {
118 assert(dest.len == (decoder.calcSize(source) catch unreachable));119 assert(dest.len == (decoder.calcSize(source) catch unreachable));
119 assert(source.len % 4 == 0);120 assert(source.len % 4 == 0);
120121
...@@ -180,7 +181,7 @@ pub const Base64DecoderWithIgnore = struct {...@@ -180,7 +181,7 @@ pub const Base64DecoderWithIgnore = struct {
180 /// Invalid padding results in error.InvalidPadding.181 /// Invalid padding results in error.InvalidPadding.
181 /// Decoding more data than can fit in dest results in error.OutputTooSmall. See also ::calcSizeUpperBound.182 /// Decoding more data than can fit in dest results in error.OutputTooSmall. See also ::calcSizeUpperBound.
182 /// Returns the number of bytes writen to dest.183 /// Returns the number of bytes writen to dest.
183 pub fn decode(decoder_with_ignore: &const Base64DecoderWithIgnore, dest: []u8, source: []const u8) !usize {184 pub fn decode(decoder_with_ignore: *const Base64DecoderWithIgnore, dest: []u8, source: []const u8) !usize {
184 const decoder = &decoder_with_ignore.decoder;185 const decoder = &decoder_with_ignore.decoder;
185186
186 var src_cursor: usize = 0;187 var src_cursor: usize = 0;
...@@ -289,13 +290,13 @@ pub const Base64DecoderUnsafe = struct {...@@ -289,13 +290,13 @@ pub const Base64DecoderUnsafe = struct {
289 }290 }
290291
291 /// The source buffer must be valid.292 /// The source buffer must be valid.
292 pub fn calcSize(decoder: &const Base64DecoderUnsafe, source: []const u8) usize {293 pub fn calcSize(decoder: *const Base64DecoderUnsafe, source: []const u8) usize {
293 return calcDecodedSizeExactUnsafe(source, decoder.pad_char);294 return calcDecodedSizeExactUnsafe(source, decoder.pad_char);
294 }295 }
295296
296 /// dest.len must be what you get from ::calcDecodedSizeExactUnsafe.297 /// dest.len must be what you get from ::calcDecodedSizeExactUnsafe.
297 /// invalid characters or padding will result in undefined values.298 /// invalid characters or padding will result in undefined values.
298 pub fn decode(decoder: &const Base64DecoderUnsafe, dest: []u8, source: []const u8) void {299 pub fn decode(decoder: *const Base64DecoderUnsafe, dest: []u8, source: []const u8) void {
299 assert(dest.len == decoder.calcSize(source));300 assert(dest.len == decoder.calcSize(source));
300301
301 var src_index: usize = 0;302 var src_index: usize = 0;
...@@ -449,7 +450,7 @@ fn testError(encoded: []const u8, expected_err: error) !void {...@@ -449,7 +450,7 @@ fn testError(encoded: []const u8, expected_err: error) !void {
449fn testOutputTooSmallError(encoded: []const u8) !void {450fn testOutputTooSmallError(encoded: []const u8) !void {
450 const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " ");451 const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " ");
451 var buffer: [0x100]u8 = undefined;452 var buffer: [0x100]u8 = undefined;
452 var decoded = buffer[0..calcDecodedSizeExactUnsafe(encoded, standard_pad_char) - 1];453 var decoded = buffer[0 .. calcDecodedSizeExactUnsafe(encoded, standard_pad_char) - 1];
453 if (standard_decoder_ignore_space.decode(decoded, encoded)) |_| {454 if (standard_decoder_ignore_space.decode(decoded, encoded)) |_| {
454 return error.ExpectedError;455 return error.ExpectedError;
455 } else |err| if (err != error.OutputTooSmall) return err;456 } else |err| if (err != error.OutputTooSmall) return err;
std/buf_map.zig+9-9
...@@ -11,12 +11,12 @@ pub const BufMap = struct {...@@ -11,12 +11,12 @@ pub const BufMap = struct {
1111
12 const BufMapHashMap = HashMap([]const u8, []const u8, mem.hash_slice_u8, mem.eql_slice_u8);12 const BufMapHashMap = HashMap([]const u8, []const u8, mem.hash_slice_u8, mem.eql_slice_u8);
1313
14 pub fn init(allocator: &Allocator) BufMap {14 pub fn init(allocator: *Allocator) BufMap {
15 var self = BufMap{ .hash_map = BufMapHashMap.init(allocator) };15 var self = BufMap{ .hash_map = BufMapHashMap.init(allocator) };
16 return self;16 return self;
17 }17 }
1818
19 pub fn deinit(self: &const BufMap) void {19 pub fn deinit(self: *const BufMap) void {
20 var it = self.hash_map.iterator();20 var it = self.hash_map.iterator();
21 while (true) {21 while (true) {
22 const entry = it.next() ?? break;22 const entry = it.next() ?? break;
...@@ -27,7 +27,7 @@ pub const BufMap = struct {...@@ -27,7 +27,7 @@ pub const BufMap = struct {
27 self.hash_map.deinit();27 self.hash_map.deinit();
28 }28 }
2929
30 pub fn set(self: &BufMap, key: []const u8, value: []const u8) !void {30 pub fn set(self: *BufMap, key: []const u8, value: []const u8) !void {
31 self.delete(key);31 self.delete(key);
32 const key_copy = try self.copy(key);32 const key_copy = try self.copy(key);
33 errdefer self.free(key_copy);33 errdefer self.free(key_copy);
...@@ -36,30 +36,30 @@ pub const BufMap = struct {...@@ -36,30 +36,30 @@ pub const BufMap = struct {
36 _ = try self.hash_map.put(key_copy, value_copy);36 _ = try self.hash_map.put(key_copy, value_copy);
37 }37 }
3838
39 pub fn get(self: &const BufMap, key: []const u8) ?[]const u8 {39 pub fn get(self: *const BufMap, key: []const u8) ?[]const u8 {
40 const entry = self.hash_map.get(key) ?? return null;40 const entry = self.hash_map.get(key) ?? return null;
41 return entry.value;41 return entry.value;
42 }42 }
4343
44 pub fn delete(self: &BufMap, key: []const u8) void {44 pub fn delete(self: *BufMap, key: []const u8) void {
45 const entry = self.hash_map.remove(key) ?? return;45 const entry = self.hash_map.remove(key) ?? return;
46 self.free(entry.key);46 self.free(entry.key);
47 self.free(entry.value);47 self.free(entry.value);
48 }48 }
4949
50 pub fn count(self: &const BufMap) usize {50 pub fn count(self: *const BufMap) usize {
51 return self.hash_map.count();51 return self.hash_map.count();
52 }52 }
5353
54 pub fn iterator(self: &const BufMap) BufMapHashMap.Iterator {54 pub fn iterator(self: *const BufMap) BufMapHashMap.Iterator {
55 return self.hash_map.iterator();55 return self.hash_map.iterator();
56 }56 }
5757
58 fn free(self: &const BufMap, value: []const u8) void {58 fn free(self: *const BufMap, value: []const u8) void {
59 self.hash_map.allocator.free(value);59 self.hash_map.allocator.free(value);
60 }60 }
6161
62 fn copy(self: &const BufMap, value: []const u8) ![]const u8 {62 fn copy(self: *const BufMap, value: []const u8) ![]const u8 {
63 return mem.dupe(self.hash_map.allocator, u8, value);63 return mem.dupe(self.hash_map.allocator, u8, value);
64 }64 }
65};65};
std/buf_set.zig+9-9
...@@ -9,12 +9,12 @@ pub const BufSet = struct {...@@ -9,12 +9,12 @@ pub const BufSet = struct {
99
10 const BufSetHashMap = HashMap([]const u8, void, mem.hash_slice_u8, mem.eql_slice_u8);10 const BufSetHashMap = HashMap([]const u8, void, mem.hash_slice_u8, mem.eql_slice_u8);
1111
12 pub fn init(a: &Allocator) BufSet {12 pub fn init(a: *Allocator) BufSet {
13 var self = BufSet{ .hash_map = BufSetHashMap.init(a) };13 var self = BufSet{ .hash_map = BufSetHashMap.init(a) };
14 return self;14 return self;
15 }15 }
1616
17 pub fn deinit(self: &const BufSet) void {17 pub fn deinit(self: *const BufSet) void {
18 var it = self.hash_map.iterator();18 var it = self.hash_map.iterator();
19 while (true) {19 while (true) {
20 const entry = it.next() ?? break;20 const entry = it.next() ?? break;
...@@ -24,7 +24,7 @@ pub const BufSet = struct {...@@ -24,7 +24,7 @@ pub const BufSet = struct {
24 self.hash_map.deinit();24 self.hash_map.deinit();
25 }25 }
2626
27 pub fn put(self: &BufSet, key: []const u8) !void {27 pub fn put(self: *BufSet, key: []const u8) !void {
28 if (self.hash_map.get(key) == null) {28 if (self.hash_map.get(key) == null) {
29 const key_copy = try self.copy(key);29 const key_copy = try self.copy(key);
30 errdefer self.free(key_copy);30 errdefer self.free(key_copy);
...@@ -32,28 +32,28 @@ pub const BufSet = struct {...@@ -32,28 +32,28 @@ pub const BufSet = struct {
32 }32 }
33 }33 }
3434
35 pub fn delete(self: &BufSet, key: []const u8) void {35 pub fn delete(self: *BufSet, key: []const u8) void {
36 const entry = self.hash_map.remove(key) ?? return;36 const entry = self.hash_map.remove(key) ?? return;
37 self.free(entry.key);37 self.free(entry.key);
38 }38 }
3939
40 pub fn count(self: &const BufSet) usize {40 pub fn count(self: *const BufSet) usize {
41 return self.hash_map.count();41 return self.hash_map.count();
42 }42 }
4343
44 pub fn iterator(self: &const BufSet) BufSetHashMap.Iterator {44 pub fn iterator(self: *const BufSet) BufSetHashMap.Iterator {
45 return self.hash_map.iterator();45 return self.hash_map.iterator();
46 }46 }
4747
48 pub fn allocator(self: &const BufSet) &Allocator {48 pub fn allocator(self: *const BufSet) *Allocator {
49 return self.hash_map.allocator;49 return self.hash_map.allocator;
50 }50 }
5151
52 fn free(self: &const BufSet, value: []const u8) void {52 fn free(self: *const BufSet, value: []const u8) void {
53 self.hash_map.allocator.free(value);53 self.hash_map.allocator.free(value);
54 }54 }
5555
56 fn copy(self: &const BufSet, value: []const u8) ![]const u8 {56 fn copy(self: *const BufSet, value: []const u8) ![]const u8 {
57 const result = try self.hash_map.allocator.alloc(u8, value.len);57 const result = try self.hash_map.allocator.alloc(u8, value.len);
58 mem.copy(u8, result, value);58 mem.copy(u8, result, value);
59 return result;59 return result;
std/buffer.zig+20-20
...@@ -12,14 +12,14 @@ pub const Buffer = struct {...@@ -12,14 +12,14 @@ pub const Buffer = struct {
12 list: ArrayList(u8),12 list: ArrayList(u8),
1313
14 /// Must deinitialize with deinit.14 /// Must deinitialize with deinit.
15 pub fn init(allocator: &Allocator, m: []const u8) !Buffer {15 pub fn init(allocator: *Allocator, m: []const u8) !Buffer {
16 var self = try initSize(allocator, m.len);16 var self = try initSize(allocator, m.len);
17 mem.copy(u8, self.list.items, m);17 mem.copy(u8, self.list.items, m);
18 return self;18 return self;
19 }19 }
2020
21 /// Must deinitialize with deinit.21 /// Must deinitialize with deinit.
22 pub fn initSize(allocator: &Allocator, size: usize) !Buffer {22 pub fn initSize(allocator: *Allocator, size: usize) !Buffer {
23 var self = initNull(allocator);23 var self = initNull(allocator);
24 try self.resize(size);24 try self.resize(size);
25 return self;25 return self;
...@@ -30,19 +30,19 @@ pub const Buffer = struct {...@@ -30,19 +30,19 @@ pub const Buffer = struct {
30 /// * ::replaceContents30 /// * ::replaceContents
31 /// * ::replaceContentsBuffer31 /// * ::replaceContentsBuffer
32 /// * ::resize32 /// * ::resize
33 pub fn initNull(allocator: &Allocator) Buffer {33 pub fn initNull(allocator: *Allocator) Buffer {
34 return Buffer{ .list = ArrayList(u8).init(allocator) };34 return Buffer{ .list = ArrayList(u8).init(allocator) };
35 }35 }
3636
37 /// Must deinitialize with deinit.37 /// Must deinitialize with deinit.
38 pub fn initFromBuffer(buffer: &const Buffer) !Buffer {38 pub fn initFromBuffer(buffer: *const Buffer) !Buffer {
39 return Buffer.init(buffer.list.allocator, buffer.toSliceConst());39 return Buffer.init(buffer.list.allocator, buffer.toSliceConst());
40 }40 }
4141
42 /// Buffer takes ownership of the passed in slice. The slice must have been42 /// Buffer takes ownership of the passed in slice. The slice must have been
43 /// allocated with `allocator`.43 /// allocated with `allocator`.
44 /// Must deinitialize with deinit.44 /// Must deinitialize with deinit.
45 pub fn fromOwnedSlice(allocator: &Allocator, slice: []u8) Buffer {45 pub fn fromOwnedSlice(allocator: *Allocator, slice: []u8) Buffer {
46 var self = Buffer{ .list = ArrayList(u8).fromOwnedSlice(allocator, slice) };46 var self = Buffer{ .list = ArrayList(u8).fromOwnedSlice(allocator, slice) };
47 self.list.append(0);47 self.list.append(0);
48 return self;48 return self;
...@@ -50,79 +50,79 @@ pub const Buffer = struct {...@@ -50,79 +50,79 @@ pub const Buffer = struct {
5050
51 /// The caller owns the returned memory. The Buffer becomes null and51 /// The caller owns the returned memory. The Buffer becomes null and
52 /// is safe to `deinit`.52 /// is safe to `deinit`.
53 pub fn toOwnedSlice(self: &Buffer) []u8 {53 pub fn toOwnedSlice(self: *Buffer) []u8 {
54 const allocator = self.list.allocator;54 const allocator = self.list.allocator;
55 const result = allocator.shrink(u8, self.list.items, self.len());55 const result = allocator.shrink(u8, self.list.items, self.len());
56 self.* = initNull(allocator);56 self.* = initNull(allocator);
57 return result;57 return result;
58 }58 }
5959
60 pub fn deinit(self: &Buffer) void {60 pub fn deinit(self: *Buffer) void {
61 self.list.deinit();61 self.list.deinit();
62 }62 }
6363
64 pub fn toSlice(self: &const Buffer) []u8 {64 pub fn toSlice(self: *const Buffer) []u8 {
65 return self.list.toSlice()[0..self.len()];65 return self.list.toSlice()[0..self.len()];
66 }66 }
6767
68 pub fn toSliceConst(self: &const Buffer) []const u8 {68 pub fn toSliceConst(self: *const Buffer) []const u8 {
69 return self.list.toSliceConst()[0..self.len()];69 return self.list.toSliceConst()[0..self.len()];
70 }70 }
7171
72 pub fn shrink(self: &Buffer, new_len: usize) void {72 pub fn shrink(self: *Buffer, new_len: usize) void {
73 assert(new_len <= self.len());73 assert(new_len <= self.len());
74 self.list.shrink(new_len + 1);74 self.list.shrink(new_len + 1);
75 self.list.items[self.len()] = 0;75 self.list.items[self.len()] = 0;
76 }76 }
7777
78 pub fn resize(self: &Buffer, new_len: usize) !void {78 pub fn resize(self: *Buffer, new_len: usize) !void {
79 try self.list.resize(new_len + 1);79 try self.list.resize(new_len + 1);
80 self.list.items[self.len()] = 0;80 self.list.items[self.len()] = 0;
81 }81 }
8282
83 pub fn isNull(self: &const Buffer) bool {83 pub fn isNull(self: *const Buffer) bool {
84 return self.list.len == 0;84 return self.list.len == 0;
85 }85 }
8686
87 pub fn len(self: &const Buffer) usize {87 pub fn len(self: *const Buffer) usize {
88 return self.list.len - 1;88 return self.list.len - 1;
89 }89 }
9090
91 pub fn append(self: &Buffer, m: []const u8) !void {91 pub fn append(self: *Buffer, m: []const u8) !void {
92 const old_len = self.len();92 const old_len = self.len();
93 try self.resize(old_len + m.len);93 try self.resize(old_len + m.len);
94 mem.copy(u8, self.list.toSlice()[old_len..], m);94 mem.copy(u8, self.list.toSlice()[old_len..], m);
95 }95 }
9696
97 pub fn appendByte(self: &Buffer, byte: u8) !void {97 pub fn appendByte(self: *Buffer, byte: u8) !void {
98 const old_len = self.len();98 const old_len = self.len();
99 try self.resize(old_len + 1);99 try self.resize(old_len + 1);
100 self.list.toSlice()[old_len] = byte;100 self.list.toSlice()[old_len] = byte;
101 }101 }
102102
103 pub fn eql(self: &const Buffer, m: []const u8) bool {103 pub fn eql(self: *const Buffer, m: []const u8) bool {
104 return mem.eql(u8, self.toSliceConst(), m);104 return mem.eql(u8, self.toSliceConst(), m);
105 }105 }
106106
107 pub fn startsWith(self: &const Buffer, m: []const u8) bool {107 pub fn startsWith(self: *const Buffer, m: []const u8) bool {
108 if (self.len() < m.len) return false;108 if (self.len() < m.len) return false;
109 return mem.eql(u8, self.list.items[0..m.len], m);109 return mem.eql(u8, self.list.items[0..m.len], m);
110 }110 }
111111
112 pub fn endsWith(self: &const Buffer, m: []const u8) bool {112 pub fn endsWith(self: *const Buffer, m: []const u8) bool {
113 const l = self.len();113 const l = self.len();
114 if (l < m.len) return false;114 if (l < m.len) return false;
115 const start = l - m.len;115 const start = l - m.len;
116 return mem.eql(u8, self.list.items[start..l], m);116 return mem.eql(u8, self.list.items[start..l], m);
117 }117 }
118118
119 pub fn replaceContents(self: &const Buffer, m: []const u8) !void {119 pub fn replaceContents(self: *const Buffer, m: []const u8) !void {
120 try self.resize(m.len);120 try self.resize(m.len);
121 mem.copy(u8, self.list.toSlice(), m);121 mem.copy(u8, self.list.toSlice(), m);
122 }122 }
123123
124 /// For passing to C functions.124 /// For passing to C functions.
125 pub fn ptr(self: &const Buffer) &u8 {125 pub fn ptr(self: *const Buffer) [*]u8 {
126 return self.list.items.ptr;126 return self.list.items.ptr;
127 }127 }
128};128};
std/build.zig+139-139
...@@ -20,7 +20,7 @@ pub const Builder = struct {...@@ -20,7 +20,7 @@ pub const Builder = struct {
20 install_tls: TopLevelStep,20 install_tls: TopLevelStep,
21 have_uninstall_step: bool,21 have_uninstall_step: bool,
22 have_install_step: bool,22 have_install_step: bool,
23 allocator: &Allocator,23 allocator: *Allocator,
24 lib_paths: ArrayList([]const u8),24 lib_paths: ArrayList([]const u8),
25 include_paths: ArrayList([]const u8),25 include_paths: ArrayList([]const u8),
26 rpaths: ArrayList([]const u8),26 rpaths: ArrayList([]const u8),
...@@ -36,9 +36,9 @@ pub const Builder = struct {...@@ -36,9 +36,9 @@ pub const Builder = struct {
36 verbose_cimport: bool,36 verbose_cimport: bool,
37 invalid_user_input: bool,37 invalid_user_input: bool,
38 zig_exe: []const u8,38 zig_exe: []const u8,
39 default_step: &Step,39 default_step: *Step,
40 env_map: BufMap,40 env_map: BufMap,
41 top_level_steps: ArrayList(&TopLevelStep),41 top_level_steps: ArrayList(*TopLevelStep),
42 prefix: []const u8,42 prefix: []const u8,
43 search_prefixes: ArrayList([]const u8),43 search_prefixes: ArrayList([]const u8),
44 lib_dir: []const u8,44 lib_dir: []const u8,
...@@ -82,7 +82,7 @@ pub const Builder = struct {...@@ -82,7 +82,7 @@ pub const Builder = struct {
82 description: []const u8,82 description: []const u8,
83 };83 };
8484
85 pub fn init(allocator: &Allocator, zig_exe: []const u8, build_root: []const u8, cache_root: []const u8) Builder {85 pub fn init(allocator: *Allocator, zig_exe: []const u8, build_root: []const u8, cache_root: []const u8) Builder {
86 var self = Builder{86 var self = Builder{
87 .zig_exe = zig_exe,87 .zig_exe = zig_exe,
88 .build_root = build_root,88 .build_root = build_root,
...@@ -102,7 +102,7 @@ pub const Builder = struct {...@@ -102,7 +102,7 @@ pub const Builder = struct {
102 .user_input_options = UserInputOptionsMap.init(allocator),102 .user_input_options = UserInputOptionsMap.init(allocator),
103 .available_options_map = AvailableOptionsMap.init(allocator),103 .available_options_map = AvailableOptionsMap.init(allocator),
104 .available_options_list = ArrayList(AvailableOption).init(allocator),104 .available_options_list = ArrayList(AvailableOption).init(allocator),
105 .top_level_steps = ArrayList(&TopLevelStep).init(allocator),105 .top_level_steps = ArrayList(*TopLevelStep).init(allocator),
106 .default_step = undefined,106 .default_step = undefined,
107 .env_map = os.getEnvMap(allocator) catch unreachable,107 .env_map = os.getEnvMap(allocator) catch unreachable,
108 .prefix = undefined,108 .prefix = undefined,
...@@ -127,7 +127,7 @@ pub const Builder = struct {...@@ -127,7 +127,7 @@ pub const Builder = struct {
127 return self;127 return self;
128 }128 }
129129
130 pub fn deinit(self: &Builder) void {130 pub fn deinit(self: *Builder) void {
131 self.lib_paths.deinit();131 self.lib_paths.deinit();
132 self.include_paths.deinit();132 self.include_paths.deinit();
133 self.rpaths.deinit();133 self.rpaths.deinit();
...@@ -135,81 +135,81 @@ pub const Builder = struct {...@@ -135,81 +135,81 @@ pub const Builder = struct {
135 self.top_level_steps.deinit();135 self.top_level_steps.deinit();
136 }136 }
137137
138 pub fn setInstallPrefix(self: &Builder, maybe_prefix: ?[]const u8) void {138 pub fn setInstallPrefix(self: *Builder, maybe_prefix: ?[]const u8) void {
139 self.prefix = maybe_prefix ?? "/usr/local"; // TODO better default139 self.prefix = maybe_prefix ?? "/usr/local"; // TODO better default
140 self.lib_dir = os.path.join(self.allocator, self.prefix, "lib") catch unreachable;140 self.lib_dir = os.path.join(self.allocator, self.prefix, "lib") catch unreachable;
141 self.exe_dir = os.path.join(self.allocator, self.prefix, "bin") catch unreachable;141 self.exe_dir = os.path.join(self.allocator, self.prefix, "bin") catch unreachable;
142 }142 }
143143
144 pub fn addExecutable(self: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep {144 pub fn addExecutable(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep {
145 return LibExeObjStep.createExecutable(self, name, root_src);145 return LibExeObjStep.createExecutable(self, name, root_src);
146 }146 }
147147
148 pub fn addObject(self: &Builder, name: []const u8, root_src: []const u8) &LibExeObjStep {148 pub fn addObject(self: *Builder, name: []const u8, root_src: []const u8) *LibExeObjStep {
149 return LibExeObjStep.createObject(self, name, root_src);149 return LibExeObjStep.createObject(self, name, root_src);
150 }150 }
151151
152 pub fn addSharedLibrary(self: &Builder, name: []const u8, root_src: ?[]const u8, ver: &const Version) &LibExeObjStep {152 pub fn addSharedLibrary(self: *Builder, name: []const u8, root_src: ?[]const u8, ver: *const Version) *LibExeObjStep {
153 return LibExeObjStep.createSharedLibrary(self, name, root_src, ver);153 return LibExeObjStep.createSharedLibrary(self, name, root_src, ver);
154 }154 }
155155
156 pub fn addStaticLibrary(self: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep {156 pub fn addStaticLibrary(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep {
157 return LibExeObjStep.createStaticLibrary(self, name, root_src);157 return LibExeObjStep.createStaticLibrary(self, name, root_src);
158 }158 }
159159
160 pub fn addTest(self: &Builder, root_src: []const u8) &TestStep {160 pub fn addTest(self: *Builder, root_src: []const u8) *TestStep {
161 const test_step = self.allocator.create(TestStep) catch unreachable;161 const test_step = self.allocator.create(TestStep) catch unreachable;
162 test_step.* = TestStep.init(self, root_src);162 test_step.* = TestStep.init(self, root_src);
163 return test_step;163 return test_step;
164 }164 }
165165
166 pub fn addAssemble(self: &Builder, name: []const u8, src: []const u8) &LibExeObjStep {166 pub fn addAssemble(self: *Builder, name: []const u8, src: []const u8) *LibExeObjStep {
167 const obj_step = LibExeObjStep.createObject(self, name, null);167 const obj_step = LibExeObjStep.createObject(self, name, null);
168 obj_step.addAssemblyFile(src);168 obj_step.addAssemblyFile(src);
169 return obj_step;169 return obj_step;
170 }170 }
171171
172 pub fn addCStaticLibrary(self: &Builder, name: []const u8) &LibExeObjStep {172 pub fn addCStaticLibrary(self: *Builder, name: []const u8) *LibExeObjStep {
173 return LibExeObjStep.createCStaticLibrary(self, name);173 return LibExeObjStep.createCStaticLibrary(self, name);
174 }174 }
175175
176 pub fn addCSharedLibrary(self: &Builder, name: []const u8, ver: &const Version) &LibExeObjStep {176 pub fn addCSharedLibrary(self: *Builder, name: []const u8, ver: *const Version) *LibExeObjStep {
177 return LibExeObjStep.createCSharedLibrary(self, name, ver);177 return LibExeObjStep.createCSharedLibrary(self, name, ver);
178 }178 }
179179
180 pub fn addCExecutable(self: &Builder, name: []const u8) &LibExeObjStep {180 pub fn addCExecutable(self: *Builder, name: []const u8) *LibExeObjStep {
181 return LibExeObjStep.createCExecutable(self, name);181 return LibExeObjStep.createCExecutable(self, name);
182 }182 }
183183
184 pub fn addCObject(self: &Builder, name: []const u8, src: []const u8) &LibExeObjStep {184 pub fn addCObject(self: *Builder, name: []const u8, src: []const u8) *LibExeObjStep {
185 return LibExeObjStep.createCObject(self, name, src);185 return LibExeObjStep.createCObject(self, name, src);
186 }186 }
187187
188 /// ::argv is copied.188 /// ::argv is copied.
189 pub fn addCommand(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) &CommandStep {189 pub fn addCommand(self: *Builder, cwd: ?[]const u8, env_map: *const BufMap, argv: []const []const u8) *CommandStep {
190 return CommandStep.create(self, cwd, env_map, argv);190 return CommandStep.create(self, cwd, env_map, argv);
191 }191 }
192192
193 pub fn addWriteFile(self: &Builder, file_path: []const u8, data: []const u8) &WriteFileStep {193 pub fn addWriteFile(self: *Builder, file_path: []const u8, data: []const u8) *WriteFileStep {
194 const write_file_step = self.allocator.create(WriteFileStep) catch unreachable;194 const write_file_step = self.allocator.create(WriteFileStep) catch unreachable;
195 write_file_step.* = WriteFileStep.init(self, file_path, data);195 write_file_step.* = WriteFileStep.init(self, file_path, data);
196 return write_file_step;196 return write_file_step;
197 }197 }
198198
199 pub fn addLog(self: &Builder, comptime format: []const u8, args: ...) &LogStep {199 pub fn addLog(self: *Builder, comptime format: []const u8, args: ...) *LogStep {
200 const data = self.fmt(format, args);200 const data = self.fmt(format, args);
201 const log_step = self.allocator.create(LogStep) catch unreachable;201 const log_step = self.allocator.create(LogStep) catch unreachable;
202 log_step.* = LogStep.init(self, data);202 log_step.* = LogStep.init(self, data);
203 return log_step;203 return log_step;
204 }204 }
205205
206 pub fn addRemoveDirTree(self: &Builder, dir_path: []const u8) &RemoveDirStep {206 pub fn addRemoveDirTree(self: *Builder, dir_path: []const u8) *RemoveDirStep {
207 const remove_dir_step = self.allocator.create(RemoveDirStep) catch unreachable;207 const remove_dir_step = self.allocator.create(RemoveDirStep) catch unreachable;
208 remove_dir_step.* = RemoveDirStep.init(self, dir_path);208 remove_dir_step.* = RemoveDirStep.init(self, dir_path);
209 return remove_dir_step;209 return remove_dir_step;
210 }210 }
211211
212 pub fn version(self: &const Builder, major: u32, minor: u32, patch: u32) Version {212 pub fn version(self: *const Builder, major: u32, minor: u32, patch: u32) Version {
213 return Version{213 return Version{
214 .major = major,214 .major = major,
215 .minor = minor,215 .minor = minor,
...@@ -217,20 +217,20 @@ pub const Builder = struct {...@@ -217,20 +217,20 @@ pub const Builder = struct {
217 };217 };
218 }218 }
219219
220 pub fn addCIncludePath(self: &Builder, path: []const u8) void {220 pub fn addCIncludePath(self: *Builder, path: []const u8) void {
221 self.include_paths.append(path) catch unreachable;221 self.include_paths.append(path) catch unreachable;
222 }222 }
223223
224 pub fn addRPath(self: &Builder, path: []const u8) void {224 pub fn addRPath(self: *Builder, path: []const u8) void {
225 self.rpaths.append(path) catch unreachable;225 self.rpaths.append(path) catch unreachable;
226 }226 }
227227
228 pub fn addLibPath(self: &Builder, path: []const u8) void {228 pub fn addLibPath(self: *Builder, path: []const u8) void {
229 self.lib_paths.append(path) catch unreachable;229 self.lib_paths.append(path) catch unreachable;
230 }230 }
231231
232 pub fn make(self: &Builder, step_names: []const []const u8) !void {232 pub fn make(self: *Builder, step_names: []const []const u8) !void {
233 var wanted_steps = ArrayList(&Step).init(self.allocator);233 var wanted_steps = ArrayList(*Step).init(self.allocator);
234 defer wanted_steps.deinit();234 defer wanted_steps.deinit();
235235
236 if (step_names.len == 0) {236 if (step_names.len == 0) {
...@@ -247,7 +247,7 @@ pub const Builder = struct {...@@ -247,7 +247,7 @@ pub const Builder = struct {
247 }247 }
248 }248 }
249249
250 pub fn getInstallStep(self: &Builder) &Step {250 pub fn getInstallStep(self: *Builder) *Step {
251 if (self.have_install_step) return &self.install_tls.step;251 if (self.have_install_step) return &self.install_tls.step;
252252
253 self.top_level_steps.append(&self.install_tls) catch unreachable;253 self.top_level_steps.append(&self.install_tls) catch unreachable;
...@@ -255,7 +255,7 @@ pub const Builder = struct {...@@ -255,7 +255,7 @@ pub const Builder = struct {
255 return &self.install_tls.step;255 return &self.install_tls.step;
256 }256 }
257257
258 pub fn getUninstallStep(self: &Builder) &Step {258 pub fn getUninstallStep(self: *Builder) *Step {
259 if (self.have_uninstall_step) return &self.uninstall_tls.step;259 if (self.have_uninstall_step) return &self.uninstall_tls.step;
260260
261 self.top_level_steps.append(&self.uninstall_tls) catch unreachable;261 self.top_level_steps.append(&self.uninstall_tls) catch unreachable;
...@@ -263,7 +263,7 @@ pub const Builder = struct {...@@ -263,7 +263,7 @@ pub const Builder = struct {
263 return &self.uninstall_tls.step;263 return &self.uninstall_tls.step;
264 }264 }
265265
266 fn makeUninstall(uninstall_step: &Step) error!void {266 fn makeUninstall(uninstall_step: *Step) error!void {
267 const uninstall_tls = @fieldParentPtr(TopLevelStep, "step", uninstall_step);267 const uninstall_tls = @fieldParentPtr(TopLevelStep, "step", uninstall_step);
268 const self = @fieldParentPtr(Builder, "uninstall_tls", uninstall_tls);268 const self = @fieldParentPtr(Builder, "uninstall_tls", uninstall_tls);
269269
...@@ -277,7 +277,7 @@ pub const Builder = struct {...@@ -277,7 +277,7 @@ pub const Builder = struct {
277 // TODO remove empty directories277 // TODO remove empty directories
278 }278 }
279279
280 fn makeOneStep(self: &Builder, s: &Step) error!void {280 fn makeOneStep(self: *Builder, s: *Step) error!void {
281 if (s.loop_flag) {281 if (s.loop_flag) {
282 warn("Dependency loop detected:\n {}\n", s.name);282 warn("Dependency loop detected:\n {}\n", s.name);
283 return error.DependencyLoopDetected;283 return error.DependencyLoopDetected;
...@@ -298,7 +298,7 @@ pub const Builder = struct {...@@ -298,7 +298,7 @@ pub const Builder = struct {
298 try s.make();298 try s.make();
299 }299 }
300300
301 fn getTopLevelStepByName(self: &Builder, name: []const u8) !&Step {301 fn getTopLevelStepByName(self: *Builder, name: []const u8) !*Step {
302 for (self.top_level_steps.toSliceConst()) |top_level_step| {302 for (self.top_level_steps.toSliceConst()) |top_level_step| {
303 if (mem.eql(u8, top_level_step.step.name, name)) {303 if (mem.eql(u8, top_level_step.step.name, name)) {
304 return &top_level_step.step;304 return &top_level_step.step;
...@@ -308,7 +308,7 @@ pub const Builder = struct {...@@ -308,7 +308,7 @@ pub const Builder = struct {
308 return error.InvalidStepName;308 return error.InvalidStepName;
309 }309 }
310310
311 fn processNixOSEnvVars(self: &Builder) void {311 fn processNixOSEnvVars(self: *Builder) void {
312 if (os.getEnvVarOwned(self.allocator, "NIX_CFLAGS_COMPILE")) |nix_cflags_compile| {312 if (os.getEnvVarOwned(self.allocator, "NIX_CFLAGS_COMPILE")) |nix_cflags_compile| {
313 var it = mem.split(nix_cflags_compile, " ");313 var it = mem.split(nix_cflags_compile, " ");
314 while (true) {314 while (true) {
...@@ -350,7 +350,7 @@ pub const Builder = struct {...@@ -350,7 +350,7 @@ pub const Builder = struct {
350 }350 }
351 }351 }
352352
353 pub fn option(self: &Builder, comptime T: type, name: []const u8, description: []const u8) ?T {353 pub fn option(self: *Builder, comptime T: type, name: []const u8, description: []const u8) ?T {
354 const type_id = comptime typeToEnum(T);354 const type_id = comptime typeToEnum(T);
355 const available_option = AvailableOption{355 const available_option = AvailableOption{
356 .name = name,356 .name = name,
...@@ -403,7 +403,7 @@ pub const Builder = struct {...@@ -403,7 +403,7 @@ pub const Builder = struct {
403 }403 }
404 }404 }
405405
406 pub fn step(self: &Builder, name: []const u8, description: []const u8) &Step {406 pub fn step(self: *Builder, name: []const u8, description: []const u8) *Step {
407 const step_info = self.allocator.create(TopLevelStep) catch unreachable;407 const step_info = self.allocator.create(TopLevelStep) catch unreachable;
408 step_info.* = TopLevelStep{408 step_info.* = TopLevelStep{
409 .step = Step.initNoOp(name, self.allocator),409 .step = Step.initNoOp(name, self.allocator),
...@@ -413,7 +413,7 @@ pub const Builder = struct {...@@ -413,7 +413,7 @@ pub const Builder = struct {
413 return &step_info.step;413 return &step_info.step;
414 }414 }
415415
416 pub fn standardReleaseOptions(self: &Builder) builtin.Mode {416 pub fn standardReleaseOptions(self: *Builder) builtin.Mode {
417 if (self.release_mode) |mode| return mode;417 if (self.release_mode) |mode| return mode;
418418
419 const release_safe = self.option(bool, "release-safe", "optimizations on and safety on") ?? false;419 const release_safe = self.option(bool, "release-safe", "optimizations on and safety on") ?? false;
...@@ -429,7 +429,7 @@ pub const Builder = struct {...@@ -429,7 +429,7 @@ pub const Builder = struct {
429 return mode;429 return mode;
430 }430 }
431431
432 pub fn addUserInputOption(self: &Builder, name: []const u8, value: []const u8) bool {432 pub fn addUserInputOption(self: *Builder, name: []const u8, value: []const u8) bool {
433 if (self.user_input_options.put(name, UserInputOption{433 if (self.user_input_options.put(name, UserInputOption{
434 .name = name,434 .name = name,
435 .value = UserValue{ .Scalar = value },435 .value = UserValue{ .Scalar = value },
...@@ -466,7 +466,7 @@ pub const Builder = struct {...@@ -466,7 +466,7 @@ pub const Builder = struct {
466 return false;466 return false;
467 }467 }
468468
469 pub fn addUserInputFlag(self: &Builder, name: []const u8) bool {469 pub fn addUserInputFlag(self: *Builder, name: []const u8) bool {
470 if (self.user_input_options.put(name, UserInputOption{470 if (self.user_input_options.put(name, UserInputOption{
471 .name = name,471 .name = name,
472 .value = UserValue{ .Flag = {} },472 .value = UserValue{ .Flag = {} },
...@@ -500,7 +500,7 @@ pub const Builder = struct {...@@ -500,7 +500,7 @@ pub const Builder = struct {
500 };500 };
501 }501 }
502502
503 fn markInvalidUserInput(self: &Builder) void {503 fn markInvalidUserInput(self: *Builder) void {
504 self.invalid_user_input = true;504 self.invalid_user_input = true;
505 }505 }
506506
...@@ -514,7 +514,7 @@ pub const Builder = struct {...@@ -514,7 +514,7 @@ pub const Builder = struct {
514 };514 };
515 }515 }
516516
517 pub fn validateUserInputDidItFail(self: &Builder) bool {517 pub fn validateUserInputDidItFail(self: *Builder) bool {
518 // make sure all args are used518 // make sure all args are used
519 var it = self.user_input_options.iterator();519 var it = self.user_input_options.iterator();
520 while (true) {520 while (true) {
...@@ -528,7 +528,7 @@ pub const Builder = struct {...@@ -528,7 +528,7 @@ pub const Builder = struct {
528 return self.invalid_user_input;528 return self.invalid_user_input;
529 }529 }
530530
531 fn spawnChild(self: &Builder, argv: []const []const u8) !void {531 fn spawnChild(self: *Builder, argv: []const []const u8) !void {
532 return self.spawnChildEnvMap(null, &self.env_map, argv);532 return self.spawnChildEnvMap(null, &self.env_map, argv);
533 }533 }
534534
...@@ -540,7 +540,7 @@ pub const Builder = struct {...@@ -540,7 +540,7 @@ pub const Builder = struct {
540 warn("\n");540 warn("\n");
541 }541 }
542542
543 fn spawnChildEnvMap(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) !void {543 fn spawnChildEnvMap(self: *Builder, cwd: ?[]const u8, env_map: *const BufMap, argv: []const []const u8) !void {
544 if (self.verbose) {544 if (self.verbose) {
545 printCmd(cwd, argv);545 printCmd(cwd, argv);
546 }546 }
...@@ -573,28 +573,28 @@ pub const Builder = struct {...@@ -573,28 +573,28 @@ pub const Builder = struct {
573 }573 }
574 }574 }
575575
576 pub fn makePath(self: &Builder, path: []const u8) !void {576 pub fn makePath(self: *Builder, path: []const u8) !void {
577 os.makePath(self.allocator, self.pathFromRoot(path)) catch |err| {577 os.makePath(self.allocator, self.pathFromRoot(path)) catch |err| {
578 warn("Unable to create path {}: {}\n", path, @errorName(err));578 warn("Unable to create path {}: {}\n", path, @errorName(err));
579 return err;579 return err;
580 };580 };
581 }581 }
582582
583 pub fn installArtifact(self: &Builder, artifact: &LibExeObjStep) void {583 pub fn installArtifact(self: *Builder, artifact: *LibExeObjStep) void {
584 self.getInstallStep().dependOn(&self.addInstallArtifact(artifact).step);584 self.getInstallStep().dependOn(&self.addInstallArtifact(artifact).step);
585 }585 }
586586
587 pub fn addInstallArtifact(self: &Builder, artifact: &LibExeObjStep) &InstallArtifactStep {587 pub fn addInstallArtifact(self: *Builder, artifact: *LibExeObjStep) *InstallArtifactStep {
588 return InstallArtifactStep.create(self, artifact);588 return InstallArtifactStep.create(self, artifact);
589 }589 }
590590
591 ///::dest_rel_path is relative to prefix path or it can be an absolute path591 ///::dest_rel_path is relative to prefix path or it can be an absolute path
592 pub fn installFile(self: &Builder, src_path: []const u8, dest_rel_path: []const u8) void {592 pub fn installFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) void {
593 self.getInstallStep().dependOn(&self.addInstallFile(src_path, dest_rel_path).step);593 self.getInstallStep().dependOn(&self.addInstallFile(src_path, dest_rel_path).step);
594 }594 }
595595
596 ///::dest_rel_path is relative to prefix path or it can be an absolute path596 ///::dest_rel_path is relative to prefix path or it can be an absolute path
597 pub fn addInstallFile(self: &Builder, src_path: []const u8, dest_rel_path: []const u8) &InstallFileStep {597 pub fn addInstallFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) *InstallFileStep {
598 const full_dest_path = os.path.resolve(self.allocator, self.prefix, dest_rel_path) catch unreachable;598 const full_dest_path = os.path.resolve(self.allocator, self.prefix, dest_rel_path) catch unreachable;
599 self.pushInstalledFile(full_dest_path);599 self.pushInstalledFile(full_dest_path);
600600
...@@ -603,16 +603,16 @@ pub const Builder = struct {...@@ -603,16 +603,16 @@ pub const Builder = struct {
603 return install_step;603 return install_step;
604 }604 }
605605
606 pub fn pushInstalledFile(self: &Builder, full_path: []const u8) void {606 pub fn pushInstalledFile(self: *Builder, full_path: []const u8) void {
607 _ = self.getUninstallStep();607 _ = self.getUninstallStep();
608 self.installed_files.append(full_path) catch unreachable;608 self.installed_files.append(full_path) catch unreachable;
609 }609 }
610610
611 fn copyFile(self: &Builder, source_path: []const u8, dest_path: []const u8) !void {611 fn copyFile(self: *Builder, source_path: []const u8, dest_path: []const u8) !void {
612 return self.copyFileMode(source_path, dest_path, os.default_file_mode);612 return self.copyFileMode(source_path, dest_path, os.default_file_mode);
613 }613 }
614614
615 fn copyFileMode(self: &Builder, source_path: []const u8, dest_path: []const u8, mode: os.FileMode) !void {615 fn copyFileMode(self: *Builder, source_path: []const u8, dest_path: []const u8, mode: os.FileMode) !void {
616 if (self.verbose) {616 if (self.verbose) {
617 warn("cp {} {}\n", source_path, dest_path);617 warn("cp {} {}\n", source_path, dest_path);
618 }618 }
...@@ -629,15 +629,15 @@ pub const Builder = struct {...@@ -629,15 +629,15 @@ pub const Builder = struct {
629 };629 };
630 }630 }
631631
632 fn pathFromRoot(self: &Builder, rel_path: []const u8) []u8 {632 fn pathFromRoot(self: *Builder, rel_path: []const u8) []u8 {
633 return os.path.resolve(self.allocator, self.build_root, rel_path) catch unreachable;633 return os.path.resolve(self.allocator, self.build_root, rel_path) catch unreachable;
634 }634 }
635635
636 pub fn fmt(self: &Builder, comptime format: []const u8, args: ...) []u8 {636 pub fn fmt(self: *Builder, comptime format: []const u8, args: ...) []u8 {
637 return fmt_lib.allocPrint(self.allocator, format, args) catch unreachable;637 return fmt_lib.allocPrint(self.allocator, format, args) catch unreachable;
638 }638 }
639639
640 fn getCCExe(self: &Builder) []const u8 {640 fn getCCExe(self: *Builder) []const u8 {
641 if (builtin.environ == builtin.Environ.msvc) {641 if (builtin.environ == builtin.Environ.msvc) {
642 return "cl.exe";642 return "cl.exe";
643 } else {643 } else {
...@@ -645,7 +645,7 @@ pub const Builder = struct {...@@ -645,7 +645,7 @@ pub const Builder = struct {
645 }645 }
646 }646 }
647647
648 pub fn findProgram(self: &Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 {648 pub fn findProgram(self: *Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 {
649 // TODO report error for ambiguous situations649 // TODO report error for ambiguous situations
650 const exe_extension = (Target{ .Native = {} }).exeFileExt();650 const exe_extension = (Target{ .Native = {} }).exeFileExt();
651 for (self.search_prefixes.toSliceConst()) |search_prefix| {651 for (self.search_prefixes.toSliceConst()) |search_prefix| {
...@@ -693,7 +693,7 @@ pub const Builder = struct {...@@ -693,7 +693,7 @@ pub const Builder = struct {
693 return error.FileNotFound;693 return error.FileNotFound;
694 }694 }
695695
696 pub fn exec(self: &Builder, argv: []const []const u8) ![]u8 {696 pub fn exec(self: *Builder, argv: []const []const u8) ![]u8 {
697 const max_output_size = 100 * 1024;697 const max_output_size = 100 * 1024;
698 const result = try os.ChildProcess.exec(self.allocator, argv, null, null, max_output_size);698 const result = try os.ChildProcess.exec(self.allocator, argv, null, null, max_output_size);
699 switch (result.term) {699 switch (result.term) {
...@@ -715,7 +715,7 @@ pub const Builder = struct {...@@ -715,7 +715,7 @@ pub const Builder = struct {
715 }715 }
716 }716 }
717717
718 pub fn addSearchPrefix(self: &Builder, search_prefix: []const u8) void {718 pub fn addSearchPrefix(self: *Builder, search_prefix: []const u8) void {
719 self.search_prefixes.append(search_prefix) catch unreachable;719 self.search_prefixes.append(search_prefix) catch unreachable;
720 }720 }
721};721};
...@@ -736,7 +736,7 @@ pub const Target = union(enum) {...@@ -736,7 +736,7 @@ pub const Target = union(enum) {
736 Native: void,736 Native: void,
737 Cross: CrossTarget,737 Cross: CrossTarget,
738738
739 pub fn oFileExt(self: &const Target) []const u8 {739 pub fn oFileExt(self: *const Target) []const u8 {
740 const environ = switch (self.*) {740 const environ = switch (self.*) {
741 Target.Native => builtin.environ,741 Target.Native => builtin.environ,
742 Target.Cross => |t| t.environ,742 Target.Cross => |t| t.environ,
...@@ -747,49 +747,49 @@ pub const Target = union(enum) {...@@ -747,49 +747,49 @@ pub const Target = union(enum) {
747 };747 };
748 }748 }
749749
750 pub fn exeFileExt(self: &const Target) []const u8 {750 pub fn exeFileExt(self: *const Target) []const u8 {
751 return switch (self.getOs()) {751 return switch (self.getOs()) {
752 builtin.Os.windows => ".exe",752 builtin.Os.windows => ".exe",
753 else => "",753 else => "",
754 };754 };
755 }755 }
756756
757 pub fn libFileExt(self: &const Target) []const u8 {757 pub fn libFileExt(self: *const Target) []const u8 {
758 return switch (self.getOs()) {758 return switch (self.getOs()) {
759 builtin.Os.windows => ".lib",759 builtin.Os.windows => ".lib",
760 else => ".a",760 else => ".a",
761 };761 };
762 }762 }
763763
764 pub fn getOs(self: &const Target) builtin.Os {764 pub fn getOs(self: *const Target) builtin.Os {
765 return switch (self.*) {765 return switch (self.*) {
766 Target.Native => builtin.os,766 Target.Native => builtin.os,
767 Target.Cross => |t| t.os,767 Target.Cross => |t| t.os,
768 };768 };
769 }769 }
770770
771 pub fn isDarwin(self: &const Target) bool {771 pub fn isDarwin(self: *const Target) bool {
772 return switch (self.getOs()) {772 return switch (self.getOs()) {
773 builtin.Os.ios, builtin.Os.macosx => true,773 builtin.Os.ios, builtin.Os.macosx => true,
774 else => false,774 else => false,
775 };775 };
776 }776 }
777777
778 pub fn isWindows(self: &const Target) bool {778 pub fn isWindows(self: *const Target) bool {
779 return switch (self.getOs()) {779 return switch (self.getOs()) {
780 builtin.Os.windows => true,780 builtin.Os.windows => true,
781 else => false,781 else => false,
782 };782 };
783 }783 }
784784
785 pub fn wantSharedLibSymLinks(self: &const Target) bool {785 pub fn wantSharedLibSymLinks(self: *const Target) bool {
786 return !self.isWindows();786 return !self.isWindows();
787 }787 }
788};788};
789789
790pub const LibExeObjStep = struct {790pub const LibExeObjStep = struct {
791 step: Step,791 step: Step,
792 builder: &Builder,792 builder: *Builder,
793 name: []const u8,793 name: []const u8,
794 target: Target,794 target: Target,
795 link_libs: BufSet,795 link_libs: BufSet,
...@@ -836,56 +836,56 @@ pub const LibExeObjStep = struct {...@@ -836,56 +836,56 @@ pub const LibExeObjStep = struct {
836 Obj,836 Obj,
837 };837 };
838838
839 pub fn createSharedLibrary(builder: &Builder, name: []const u8, root_src: ?[]const u8, ver: &const Version) &LibExeObjStep {839 pub fn createSharedLibrary(builder: *Builder, name: []const u8, root_src: ?[]const u8, ver: *const Version) *LibExeObjStep {
840 const self = builder.allocator.create(LibExeObjStep) catch unreachable;840 const self = builder.allocator.create(LibExeObjStep) catch unreachable;
841 self.* = initExtraArgs(builder, name, root_src, Kind.Lib, false, ver);841 self.* = initExtraArgs(builder, name, root_src, Kind.Lib, false, ver);
842 return self;842 return self;
843 }843 }
844844
845 pub fn createCSharedLibrary(builder: &Builder, name: []const u8, version: &const Version) &LibExeObjStep {845 pub fn createCSharedLibrary(builder: *Builder, name: []const u8, version: *const Version) *LibExeObjStep {
846 const self = builder.allocator.create(LibExeObjStep) catch unreachable;846 const self = builder.allocator.create(LibExeObjStep) catch unreachable;
847 self.* = initC(builder, name, Kind.Lib, version, false);847 self.* = initC(builder, name, Kind.Lib, version, false);
848 return self;848 return self;
849 }849 }
850850
851 pub fn createStaticLibrary(builder: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep {851 pub fn createStaticLibrary(builder: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep {
852 const self = builder.allocator.create(LibExeObjStep) catch unreachable;852 const self = builder.allocator.create(LibExeObjStep) catch unreachable;
853 self.* = initExtraArgs(builder, name, root_src, Kind.Lib, true, builder.version(0, 0, 0));853 self.* = initExtraArgs(builder, name, root_src, Kind.Lib, true, builder.version(0, 0, 0));
854 return self;854 return self;
855 }855 }
856856
857 pub fn createCStaticLibrary(builder: &Builder, name: []const u8) &LibExeObjStep {857 pub fn createCStaticLibrary(builder: *Builder, name: []const u8) *LibExeObjStep {
858 const self = builder.allocator.create(LibExeObjStep) catch unreachable;858 const self = builder.allocator.create(LibExeObjStep) catch unreachable;
859 self.* = initC(builder, name, Kind.Lib, builder.version(0, 0, 0), true);859 self.* = initC(builder, name, Kind.Lib, builder.version(0, 0, 0), true);
860 return self;860 return self;
861 }861 }
862862
863 pub fn createObject(builder: &Builder, name: []const u8, root_src: []const u8) &LibExeObjStep {863 pub fn createObject(builder: *Builder, name: []const u8, root_src: []const u8) *LibExeObjStep {
864 const self = builder.allocator.create(LibExeObjStep) catch unreachable;864 const self = builder.allocator.create(LibExeObjStep) catch unreachable;
865 self.* = initExtraArgs(builder, name, root_src, Kind.Obj, false, builder.version(0, 0, 0));865 self.* = initExtraArgs(builder, name, root_src, Kind.Obj, false, builder.version(0, 0, 0));
866 return self;866 return self;
867 }867 }
868868
869 pub fn createCObject(builder: &Builder, name: []const u8, src: []const u8) &LibExeObjStep {869 pub fn createCObject(builder: *Builder, name: []const u8, src: []const u8) *LibExeObjStep {
870 const self = builder.allocator.create(LibExeObjStep) catch unreachable;870 const self = builder.allocator.create(LibExeObjStep) catch unreachable;
871 self.* = initC(builder, name, Kind.Obj, builder.version(0, 0, 0), false);871 self.* = initC(builder, name, Kind.Obj, builder.version(0, 0, 0), false);
872 self.object_src = src;872 self.object_src = src;
873 return self;873 return self;
874 }874 }
875875
876 pub fn createExecutable(builder: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep {876 pub fn createExecutable(builder: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep {
877 const self = builder.allocator.create(LibExeObjStep) catch unreachable;877 const self = builder.allocator.create(LibExeObjStep) catch unreachable;
878 self.* = initExtraArgs(builder, name, root_src, Kind.Exe, false, builder.version(0, 0, 0));878 self.* = initExtraArgs(builder, name, root_src, Kind.Exe, false, builder.version(0, 0, 0));
879 return self;879 return self;
880 }880 }
881881
882 pub fn createCExecutable(builder: &Builder, name: []const u8) &LibExeObjStep {882 pub fn createCExecutable(builder: *Builder, name: []const u8) *LibExeObjStep {
883 const self = builder.allocator.create(LibExeObjStep) catch unreachable;883 const self = builder.allocator.create(LibExeObjStep) catch unreachable;
884 self.* = initC(builder, name, Kind.Exe, builder.version(0, 0, 0), false);884 self.* = initC(builder, name, Kind.Exe, builder.version(0, 0, 0), false);
885 return self;885 return self;
886 }886 }
887887
888 fn initExtraArgs(builder: &Builder, name: []const u8, root_src: ?[]const u8, kind: Kind, static: bool, ver: &const Version) LibExeObjStep {888 fn initExtraArgs(builder: *Builder, name: []const u8, root_src: ?[]const u8, kind: Kind, static: bool, ver: *const Version) LibExeObjStep {
889 var self = LibExeObjStep{889 var self = LibExeObjStep{
890 .strip = false,890 .strip = false,
891 .builder = builder,891 .builder = builder,
...@@ -924,7 +924,7 @@ pub const LibExeObjStep = struct {...@@ -924,7 +924,7 @@ pub const LibExeObjStep = struct {
924 return self;924 return self;
925 }925 }
926926
927 fn initC(builder: &Builder, name: []const u8, kind: Kind, version: &const Version, static: bool) LibExeObjStep {927 fn initC(builder: *Builder, name: []const u8, kind: Kind, version: *const Version, static: bool) LibExeObjStep {
928 var self = LibExeObjStep{928 var self = LibExeObjStep{
929 .builder = builder,929 .builder = builder,
930 .name = name,930 .name = name,
...@@ -964,7 +964,7 @@ pub const LibExeObjStep = struct {...@@ -964,7 +964,7 @@ pub const LibExeObjStep = struct {
964 return self;964 return self;
965 }965 }
966966
967 fn computeOutFileNames(self: &LibExeObjStep) void {967 fn computeOutFileNames(self: *LibExeObjStep) void {
968 switch (self.kind) {968 switch (self.kind) {
969 Kind.Obj => {969 Kind.Obj => {
970 self.out_filename = self.builder.fmt("{}{}", self.name, self.target.oFileExt());970 self.out_filename = self.builder.fmt("{}{}", self.name, self.target.oFileExt());
...@@ -996,7 +996,7 @@ pub const LibExeObjStep = struct {...@@ -996,7 +996,7 @@ pub const LibExeObjStep = struct {
996 }996 }
997 }997 }
998998
999 pub fn setTarget(self: &LibExeObjStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void {999 pub fn setTarget(self: *LibExeObjStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void {
1000 self.target = Target{1000 self.target = Target{
1001 .Cross = CrossTarget{1001 .Cross = CrossTarget{
1002 .arch = target_arch,1002 .arch = target_arch,
...@@ -1008,16 +1008,16 @@ pub const LibExeObjStep = struct {...@@ -1008,16 +1008,16 @@ pub const LibExeObjStep = struct {
1008 }1008 }
10091009
1010 // TODO respect this in the C args1010 // TODO respect this in the C args
1011 pub fn setLinkerScriptPath(self: &LibExeObjStep, path: []const u8) void {1011 pub fn setLinkerScriptPath(self: *LibExeObjStep, path: []const u8) void {
1012 self.linker_script = path;1012 self.linker_script = path;
1013 }1013 }
10141014
1015 pub fn linkFramework(self: &LibExeObjStep, framework_name: []const u8) void {1015 pub fn linkFramework(self: *LibExeObjStep, framework_name: []const u8) void {
1016 assert(self.target.isDarwin());1016 assert(self.target.isDarwin());
1017 self.frameworks.put(framework_name) catch unreachable;1017 self.frameworks.put(framework_name) catch unreachable;
1018 }1018 }
10191019
1020 pub fn linkLibrary(self: &LibExeObjStep, lib: &LibExeObjStep) void {1020 pub fn linkLibrary(self: *LibExeObjStep, lib: *LibExeObjStep) void {
1021 assert(self.kind != Kind.Obj);1021 assert(self.kind != Kind.Obj);
1022 assert(lib.kind == Kind.Lib);1022 assert(lib.kind == Kind.Lib);
10231023
...@@ -1038,26 +1038,26 @@ pub const LibExeObjStep = struct {...@@ -1038,26 +1038,26 @@ pub const LibExeObjStep = struct {
1038 }1038 }
1039 }1039 }
10401040
1041 pub fn linkSystemLibrary(self: &LibExeObjStep, name: []const u8) void {1041 pub fn linkSystemLibrary(self: *LibExeObjStep, name: []const u8) void {
1042 assert(self.kind != Kind.Obj);1042 assert(self.kind != Kind.Obj);
1043 self.link_libs.put(name) catch unreachable;1043 self.link_libs.put(name) catch unreachable;
1044 }1044 }
10451045
1046 pub fn addSourceFile(self: &LibExeObjStep, file: []const u8) void {1046 pub fn addSourceFile(self: *LibExeObjStep, file: []const u8) void {
1047 assert(self.kind != Kind.Obj);1047 assert(self.kind != Kind.Obj);
1048 assert(!self.is_zig);1048 assert(!self.is_zig);
1049 self.source_files.append(file) catch unreachable;1049 self.source_files.append(file) catch unreachable;
1050 }1050 }
10511051
1052 pub fn setVerboseLink(self: &LibExeObjStep, value: bool) void {1052 pub fn setVerboseLink(self: *LibExeObjStep, value: bool) void {
1053 self.verbose_link = value;1053 self.verbose_link = value;
1054 }1054 }
10551055
1056 pub fn setBuildMode(self: &LibExeObjStep, mode: builtin.Mode) void {1056 pub fn setBuildMode(self: *LibExeObjStep, mode: builtin.Mode) void {
1057 self.build_mode = mode;1057 self.build_mode = mode;
1058 }1058 }
10591059
1060 pub fn setOutputPath(self: &LibExeObjStep, file_path: []const u8) void {1060 pub fn setOutputPath(self: *LibExeObjStep, file_path: []const u8) void {
1061 self.output_path = file_path;1061 self.output_path = file_path;
10621062
1063 // catch a common mistake1063 // catch a common mistake
...@@ -1066,11 +1066,11 @@ pub const LibExeObjStep = struct {...@@ -1066,11 +1066,11 @@ pub const LibExeObjStep = struct {
1066 }1066 }
1067 }1067 }
10681068
1069 pub fn getOutputPath(self: &LibExeObjStep) []const u8 {1069 pub fn getOutputPath(self: *LibExeObjStep) []const u8 {
1070 return if (self.output_path) |output_path| output_path else os.path.join(self.builder.allocator, self.builder.cache_root, self.out_filename) catch unreachable;1070 return if (self.output_path) |output_path| output_path else os.path.join(self.builder.allocator, self.builder.cache_root, self.out_filename) catch unreachable;
1071 }1071 }
10721072
1073 pub fn setOutputHPath(self: &LibExeObjStep, file_path: []const u8) void {1073 pub fn setOutputHPath(self: *LibExeObjStep, file_path: []const u8) void {
1074 self.output_h_path = file_path;1074 self.output_h_path = file_path;
10751075
1076 // catch a common mistake1076 // catch a common mistake
...@@ -1079,21 +1079,21 @@ pub const LibExeObjStep = struct {...@@ -1079,21 +1079,21 @@ pub const LibExeObjStep = struct {
1079 }1079 }
1080 }1080 }
10811081
1082 pub fn getOutputHPath(self: &LibExeObjStep) []const u8 {1082 pub fn getOutputHPath(self: *LibExeObjStep) []const u8 {
1083 return if (self.output_h_path) |output_h_path| output_h_path else os.path.join(self.builder.allocator, self.builder.cache_root, self.out_h_filename) catch unreachable;1083 return if (self.output_h_path) |output_h_path| output_h_path else os.path.join(self.builder.allocator, self.builder.cache_root, self.out_h_filename) catch unreachable;
1084 }1084 }
10851085
1086 pub fn addAssemblyFile(self: &LibExeObjStep, path: []const u8) void {1086 pub fn addAssemblyFile(self: *LibExeObjStep, path: []const u8) void {
1087 self.assembly_files.append(path) catch unreachable;1087 self.assembly_files.append(path) catch unreachable;
1088 }1088 }
10891089
1090 pub fn addObjectFile(self: &LibExeObjStep, path: []const u8) void {1090 pub fn addObjectFile(self: *LibExeObjStep, path: []const u8) void {
1091 assert(self.kind != Kind.Obj);1091 assert(self.kind != Kind.Obj);
10921092
1093 self.object_files.append(path) catch unreachable;1093 self.object_files.append(path) catch unreachable;
1094 }1094 }
10951095
1096 pub fn addObject(self: &LibExeObjStep, obj: &LibExeObjStep) void {1096 pub fn addObject(self: *LibExeObjStep, obj: *LibExeObjStep) void {
1097 assert(obj.kind == Kind.Obj);1097 assert(obj.kind == Kind.Obj);
1098 assert(self.kind != Kind.Obj);1098 assert(self.kind != Kind.Obj);
10991099
...@@ -1110,15 +1110,15 @@ pub const LibExeObjStep = struct {...@@ -1110,15 +1110,15 @@ pub const LibExeObjStep = struct {
1110 self.include_dirs.append(self.builder.cache_root) catch unreachable;1110 self.include_dirs.append(self.builder.cache_root) catch unreachable;
1111 }1111 }
11121112
1113 pub fn addIncludeDir(self: &LibExeObjStep, path: []const u8) void {1113 pub fn addIncludeDir(self: *LibExeObjStep, path: []const u8) void {
1114 self.include_dirs.append(path) catch unreachable;1114 self.include_dirs.append(path) catch unreachable;
1115 }1115 }
11161116
1117 pub fn addLibPath(self: &LibExeObjStep, path: []const u8) void {1117 pub fn addLibPath(self: *LibExeObjStep, path: []const u8) void {
1118 self.lib_paths.append(path) catch unreachable;1118 self.lib_paths.append(path) catch unreachable;
1119 }1119 }
11201120
1121 pub fn addPackagePath(self: &LibExeObjStep, name: []const u8, pkg_index_path: []const u8) void {1121 pub fn addPackagePath(self: *LibExeObjStep, name: []const u8, pkg_index_path: []const u8) void {
1122 assert(self.is_zig);1122 assert(self.is_zig);
11231123
1124 self.packages.append(Pkg{1124 self.packages.append(Pkg{
...@@ -1127,23 +1127,23 @@ pub const LibExeObjStep = struct {...@@ -1127,23 +1127,23 @@ pub const LibExeObjStep = struct {
1127 }) catch unreachable;1127 }) catch unreachable;
1128 }1128 }
11291129
1130 pub fn addCompileFlags(self: &LibExeObjStep, flags: []const []const u8) void {1130 pub fn addCompileFlags(self: *LibExeObjStep, flags: []const []const u8) void {
1131 for (flags) |flag| {1131 for (flags) |flag| {
1132 self.cflags.append(flag) catch unreachable;1132 self.cflags.append(flag) catch unreachable;
1133 }1133 }
1134 }1134 }
11351135
1136 pub fn setNoStdLib(self: &LibExeObjStep, disable: bool) void {1136 pub fn setNoStdLib(self: *LibExeObjStep, disable: bool) void {
1137 assert(!self.is_zig);1137 assert(!self.is_zig);
1138 self.disable_libc = disable;1138 self.disable_libc = disable;
1139 }1139 }
11401140
1141 fn make(step: &Step) !void {1141 fn make(step: *Step) !void {
1142 const self = @fieldParentPtr(LibExeObjStep, "step", step);1142 const self = @fieldParentPtr(LibExeObjStep, "step", step);
1143 return if (self.is_zig) self.makeZig() else self.makeC();1143 return if (self.is_zig) self.makeZig() else self.makeC();
1144 }1144 }
11451145
1146 fn makeZig(self: &LibExeObjStep) !void {1146 fn makeZig(self: *LibExeObjStep) !void {
1147 const builder = self.builder;1147 const builder = self.builder;
11481148
1149 assert(self.is_zig);1149 assert(self.is_zig);
...@@ -1309,7 +1309,7 @@ pub const LibExeObjStep = struct {...@@ -1309,7 +1309,7 @@ pub const LibExeObjStep = struct {
1309 }1309 }
1310 }1310 }
13111311
1312 fn appendCompileFlags(self: &LibExeObjStep, args: &ArrayList([]const u8)) void {1312 fn appendCompileFlags(self: *LibExeObjStep, args: *ArrayList([]const u8)) void {
1313 if (!self.strip) {1313 if (!self.strip) {
1314 args.append("-g") catch unreachable;1314 args.append("-g") catch unreachable;
1315 }1315 }
...@@ -1354,7 +1354,7 @@ pub const LibExeObjStep = struct {...@@ -1354,7 +1354,7 @@ pub const LibExeObjStep = struct {
1354 }1354 }
1355 }1355 }
13561356
1357 fn makeC(self: &LibExeObjStep) !void {1357 fn makeC(self: *LibExeObjStep) !void {
1358 const builder = self.builder;1358 const builder = self.builder;
13591359
1360 const cc = builder.getCCExe();1360 const cc = builder.getCCExe();
...@@ -1580,7 +1580,7 @@ pub const LibExeObjStep = struct {...@@ -1580,7 +1580,7 @@ pub const LibExeObjStep = struct {
15801580
1581pub const TestStep = struct {1581pub const TestStep = struct {
1582 step: Step,1582 step: Step,
1583 builder: &Builder,1583 builder: *Builder,
1584 root_src: []const u8,1584 root_src: []const u8,
1585 build_mode: builtin.Mode,1585 build_mode: builtin.Mode,
1586 verbose: bool,1586 verbose: bool,
...@@ -1591,7 +1591,7 @@ pub const TestStep = struct {...@@ -1591,7 +1591,7 @@ pub const TestStep = struct {
1591 exec_cmd_args: ?[]const ?[]const u8,1591 exec_cmd_args: ?[]const ?[]const u8,
1592 include_dirs: ArrayList([]const u8),1592 include_dirs: ArrayList([]const u8),
15931593
1594 pub fn init(builder: &Builder, root_src: []const u8) TestStep {1594 pub fn init(builder: *Builder, root_src: []const u8) TestStep {
1595 const step_name = builder.fmt("test {}", root_src);1595 const step_name = builder.fmt("test {}", root_src);
1596 return TestStep{1596 return TestStep{
1597 .step = Step.init(step_name, builder.allocator, make),1597 .step = Step.init(step_name, builder.allocator, make),
...@@ -1608,31 +1608,31 @@ pub const TestStep = struct {...@@ -1608,31 +1608,31 @@ pub const TestStep = struct {
1608 };1608 };
1609 }1609 }
16101610
1611 pub fn setVerbose(self: &TestStep, value: bool) void {1611 pub fn setVerbose(self: *TestStep, value: bool) void {
1612 self.verbose = value;1612 self.verbose = value;
1613 }1613 }
16141614
1615 pub fn addIncludeDir(self: &TestStep, path: []const u8) void {1615 pub fn addIncludeDir(self: *TestStep, path: []const u8) void {
1616 self.include_dirs.append(path) catch unreachable;1616 self.include_dirs.append(path) catch unreachable;
1617 }1617 }
16181618
1619 pub fn setBuildMode(self: &TestStep, mode: builtin.Mode) void {1619 pub fn setBuildMode(self: *TestStep, mode: builtin.Mode) void {
1620 self.build_mode = mode;1620 self.build_mode = mode;
1621 }1621 }
16221622
1623 pub fn linkSystemLibrary(self: &TestStep, name: []const u8) void {1623 pub fn linkSystemLibrary(self: *TestStep, name: []const u8) void {
1624 self.link_libs.put(name) catch unreachable;1624 self.link_libs.put(name) catch unreachable;
1625 }1625 }
16261626
1627 pub fn setNamePrefix(self: &TestStep, text: []const u8) void {1627 pub fn setNamePrefix(self: *TestStep, text: []const u8) void {
1628 self.name_prefix = text;1628 self.name_prefix = text;
1629 }1629 }
16301630
1631 pub fn setFilter(self: &TestStep, text: ?[]const u8) void {1631 pub fn setFilter(self: *TestStep, text: ?[]const u8) void {
1632 self.filter = text;1632 self.filter = text;
1633 }1633 }
16341634
1635 pub fn setTarget(self: &TestStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void {1635 pub fn setTarget(self: *TestStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void {
1636 self.target = Target{1636 self.target = Target{
1637 .Cross = CrossTarget{1637 .Cross = CrossTarget{
1638 .arch = target_arch,1638 .arch = target_arch,
...@@ -1642,11 +1642,11 @@ pub const TestStep = struct {...@@ -1642,11 +1642,11 @@ pub const TestStep = struct {
1642 };1642 };
1643 }1643 }
16441644
1645 pub fn setExecCmd(self: &TestStep, args: []const ?[]const u8) void {1645 pub fn setExecCmd(self: *TestStep, args: []const ?[]const u8) void {
1646 self.exec_cmd_args = args;1646 self.exec_cmd_args = args;
1647 }1647 }
16481648
1649 fn make(step: &Step) !void {1649 fn make(step: *Step) !void {
1650 const self = @fieldParentPtr(TestStep, "step", step);1650 const self = @fieldParentPtr(TestStep, "step", step);
1651 const builder = self.builder;1651 const builder = self.builder;
16521652
...@@ -1739,13 +1739,13 @@ pub const TestStep = struct {...@@ -1739,13 +1739,13 @@ pub const TestStep = struct {
17391739
1740pub const CommandStep = struct {1740pub const CommandStep = struct {
1741 step: Step,1741 step: Step,
1742 builder: &Builder,1742 builder: *Builder,
1743 argv: [][]const u8,1743 argv: [][]const u8,
1744 cwd: ?[]const u8,1744 cwd: ?[]const u8,
1745 env_map: &const BufMap,1745 env_map: *const BufMap,
17461746
1747 /// ::argv is copied.1747 /// ::argv is copied.
1748 pub fn create(builder: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) &CommandStep {1748 pub fn create(builder: *Builder, cwd: ?[]const u8, env_map: *const BufMap, argv: []const []const u8) *CommandStep {
1749 const self = builder.allocator.create(CommandStep) catch unreachable;1749 const self = builder.allocator.create(CommandStep) catch unreachable;
1750 self.* = CommandStep{1750 self.* = CommandStep{
1751 .builder = builder,1751 .builder = builder,
...@@ -1759,7 +1759,7 @@ pub const CommandStep = struct {...@@ -1759,7 +1759,7 @@ pub const CommandStep = struct {
1759 return self;1759 return self;
1760 }1760 }
17611761
1762 fn make(step: &Step) !void {1762 fn make(step: *Step) !void {
1763 const self = @fieldParentPtr(CommandStep, "step", step);1763 const self = @fieldParentPtr(CommandStep, "step", step);
17641764
1765 const cwd = if (self.cwd) |cwd| self.builder.pathFromRoot(cwd) else self.builder.build_root;1765 const cwd = if (self.cwd) |cwd| self.builder.pathFromRoot(cwd) else self.builder.build_root;
...@@ -1769,13 +1769,13 @@ pub const CommandStep = struct {...@@ -1769,13 +1769,13 @@ pub const CommandStep = struct {
17691769
1770const InstallArtifactStep = struct {1770const InstallArtifactStep = struct {
1771 step: Step,1771 step: Step,
1772 builder: &Builder,1772 builder: *Builder,
1773 artifact: &LibExeObjStep,1773 artifact: *LibExeObjStep,
1774 dest_file: []const u8,1774 dest_file: []const u8,
17751775
1776 const Self = this;1776 const Self = this;
17771777
1778 pub fn create(builder: &Builder, artifact: &LibExeObjStep) &Self {1778 pub fn create(builder: *Builder, artifact: *LibExeObjStep) *Self {
1779 const self = builder.allocator.create(Self) catch unreachable;1779 const self = builder.allocator.create(Self) catch unreachable;
1780 const dest_dir = switch (artifact.kind) {1780 const dest_dir = switch (artifact.kind) {
1781 LibExeObjStep.Kind.Obj => unreachable,1781 LibExeObjStep.Kind.Obj => unreachable,
...@@ -1797,7 +1797,7 @@ const InstallArtifactStep = struct {...@@ -1797,7 +1797,7 @@ const InstallArtifactStep = struct {
1797 return self;1797 return self;
1798 }1798 }
17991799
1800 fn make(step: &Step) !void {1800 fn make(step: *Step) !void {
1801 const self = @fieldParentPtr(Self, "step", step);1801 const self = @fieldParentPtr(Self, "step", step);
1802 const builder = self.builder;1802 const builder = self.builder;
18031803
...@@ -1818,11 +1818,11 @@ const InstallArtifactStep = struct {...@@ -1818,11 +1818,11 @@ const InstallArtifactStep = struct {
18181818
1819pub const InstallFileStep = struct {1819pub const InstallFileStep = struct {
1820 step: Step,1820 step: Step,
1821 builder: &Builder,1821 builder: *Builder,
1822 src_path: []const u8,1822 src_path: []const u8,
1823 dest_path: []const u8,1823 dest_path: []const u8,
18241824
1825 pub fn init(builder: &Builder, src_path: []const u8, dest_path: []const u8) InstallFileStep {1825 pub fn init(builder: *Builder, src_path: []const u8, dest_path: []const u8) InstallFileStep {
1826 return InstallFileStep{1826 return InstallFileStep{
1827 .builder = builder,1827 .builder = builder,
1828 .step = Step.init(builder.fmt("install {}", src_path), builder.allocator, make),1828 .step = Step.init(builder.fmt("install {}", src_path), builder.allocator, make),
...@@ -1831,7 +1831,7 @@ pub const InstallFileStep = struct {...@@ -1831,7 +1831,7 @@ pub const InstallFileStep = struct {
1831 };1831 };
1832 }1832 }
18331833
1834 fn make(step: &Step) !void {1834 fn make(step: *Step) !void {
1835 const self = @fieldParentPtr(InstallFileStep, "step", step);1835 const self = @fieldParentPtr(InstallFileStep, "step", step);
1836 try self.builder.copyFile(self.src_path, self.dest_path);1836 try self.builder.copyFile(self.src_path, self.dest_path);
1837 }1837 }
...@@ -1839,11 +1839,11 @@ pub const InstallFileStep = struct {...@@ -1839,11 +1839,11 @@ pub const InstallFileStep = struct {
18391839
1840pub const WriteFileStep = struct {1840pub const WriteFileStep = struct {
1841 step: Step,1841 step: Step,
1842 builder: &Builder,1842 builder: *Builder,
1843 file_path: []const u8,1843 file_path: []const u8,
1844 data: []const u8,1844 data: []const u8,
18451845
1846 pub fn init(builder: &Builder, file_path: []const u8, data: []const u8) WriteFileStep {1846 pub fn init(builder: *Builder, file_path: []const u8, data: []const u8) WriteFileStep {
1847 return WriteFileStep{1847 return WriteFileStep{
1848 .builder = builder,1848 .builder = builder,
1849 .step = Step.init(builder.fmt("writefile {}", file_path), builder.allocator, make),1849 .step = Step.init(builder.fmt("writefile {}", file_path), builder.allocator, make),
...@@ -1852,7 +1852,7 @@ pub const WriteFileStep = struct {...@@ -1852,7 +1852,7 @@ pub const WriteFileStep = struct {
1852 };1852 };
1853 }1853 }
18541854
1855 fn make(step: &Step) !void {1855 fn make(step: *Step) !void {
1856 const self = @fieldParentPtr(WriteFileStep, "step", step);1856 const self = @fieldParentPtr(WriteFileStep, "step", step);
1857 const full_path = self.builder.pathFromRoot(self.file_path);1857 const full_path = self.builder.pathFromRoot(self.file_path);
1858 const full_path_dir = os.path.dirname(full_path);1858 const full_path_dir = os.path.dirname(full_path);
...@@ -1869,10 +1869,10 @@ pub const WriteFileStep = struct {...@@ -1869,10 +1869,10 @@ pub const WriteFileStep = struct {
18691869
1870pub const LogStep = struct {1870pub const LogStep = struct {
1871 step: Step,1871 step: Step,
1872 builder: &Builder,1872 builder: *Builder,
1873 data: []const u8,1873 data: []const u8,
18741874
1875 pub fn init(builder: &Builder, data: []const u8) LogStep {1875 pub fn init(builder: *Builder, data: []const u8) LogStep {
1876 return LogStep{1876 return LogStep{
1877 .builder = builder,1877 .builder = builder,
1878 .step = Step.init(builder.fmt("log {}", data), builder.allocator, make),1878 .step = Step.init(builder.fmt("log {}", data), builder.allocator, make),
...@@ -1880,7 +1880,7 @@ pub const LogStep = struct {...@@ -1880,7 +1880,7 @@ pub const LogStep = struct {
1880 };1880 };
1881 }1881 }
18821882
1883 fn make(step: &Step) error!void {1883 fn make(step: *Step) error!void {
1884 const self = @fieldParentPtr(LogStep, "step", step);1884 const self = @fieldParentPtr(LogStep, "step", step);
1885 warn("{}", self.data);1885 warn("{}", self.data);
1886 }1886 }
...@@ -1888,10 +1888,10 @@ pub const LogStep = struct {...@@ -1888,10 +1888,10 @@ pub const LogStep = struct {
18881888
1889pub const RemoveDirStep = struct {1889pub const RemoveDirStep = struct {
1890 step: Step,1890 step: Step,
1891 builder: &Builder,1891 builder: *Builder,
1892 dir_path: []const u8,1892 dir_path: []const u8,
18931893
1894 pub fn init(builder: &Builder, dir_path: []const u8) RemoveDirStep {1894 pub fn init(builder: *Builder, dir_path: []const u8) RemoveDirStep {
1895 return RemoveDirStep{1895 return RemoveDirStep{
1896 .builder = builder,1896 .builder = builder,
1897 .step = Step.init(builder.fmt("RemoveDir {}", dir_path), builder.allocator, make),1897 .step = Step.init(builder.fmt("RemoveDir {}", dir_path), builder.allocator, make),
...@@ -1899,7 +1899,7 @@ pub const RemoveDirStep = struct {...@@ -1899,7 +1899,7 @@ pub const RemoveDirStep = struct {
1899 };1899 };
1900 }1900 }
19011901
1902 fn make(step: &Step) !void {1902 fn make(step: *Step) !void {
1903 const self = @fieldParentPtr(RemoveDirStep, "step", step);1903 const self = @fieldParentPtr(RemoveDirStep, "step", step);
19041904
1905 const full_path = self.builder.pathFromRoot(self.dir_path);1905 const full_path = self.builder.pathFromRoot(self.dir_path);
...@@ -1912,39 +1912,39 @@ pub const RemoveDirStep = struct {...@@ -1912,39 +1912,39 @@ pub const RemoveDirStep = struct {
19121912
1913pub const Step = struct {1913pub const Step = struct {
1914 name: []const u8,1914 name: []const u8,
1915 makeFn: fn(self: &Step) error!void,1915 makeFn: fn (self: *Step) error!void,
1916 dependencies: ArrayList(&Step),1916 dependencies: ArrayList(*Step),
1917 loop_flag: bool,1917 loop_flag: bool,
1918 done_flag: bool,1918 done_flag: bool,
19191919
1920 pub fn init(name: []const u8, allocator: &Allocator, makeFn: fn(&Step) error!void) Step {1920 pub fn init(name: []const u8, allocator: *Allocator, makeFn: fn (*Step) error!void) Step {
1921 return Step{1921 return Step{
1922 .name = name,1922 .name = name,
1923 .makeFn = makeFn,1923 .makeFn = makeFn,
1924 .dependencies = ArrayList(&Step).init(allocator),1924 .dependencies = ArrayList(*Step).init(allocator),
1925 .loop_flag = false,1925 .loop_flag = false,
1926 .done_flag = false,1926 .done_flag = false,
1927 };1927 };
1928 }1928 }
1929 pub fn initNoOp(name: []const u8, allocator: &Allocator) Step {1929 pub fn initNoOp(name: []const u8, allocator: *Allocator) Step {
1930 return init(name, allocator, makeNoOp);1930 return init(name, allocator, makeNoOp);
1931 }1931 }
19321932
1933 pub fn make(self: &Step) !void {1933 pub fn make(self: *Step) !void {
1934 if (self.done_flag) return;1934 if (self.done_flag) return;
19351935
1936 try self.makeFn(self);1936 try self.makeFn(self);
1937 self.done_flag = true;1937 self.done_flag = true;
1938 }1938 }
19391939
1940 pub fn dependOn(self: &Step, other: &Step) void {1940 pub fn dependOn(self: *Step, other: *Step) void {
1941 self.dependencies.append(other) catch unreachable;1941 self.dependencies.append(other) catch unreachable;
1942 }1942 }
19431943
1944 fn makeNoOp(self: &Step) error!void {}1944 fn makeNoOp(self: *Step) error!void {}
1945};1945};
19461946
1947fn doAtomicSymLinks(allocator: &Allocator, output_path: []const u8, filename_major_only: []const u8, filename_name_only: []const u8) !void {1947fn doAtomicSymLinks(allocator: *Allocator, output_path: []const u8, filename_major_only: []const u8, filename_name_only: []const u8) !void {
1948 const out_dir = os.path.dirname(output_path);1948 const out_dir = os.path.dirname(output_path);
1949 const out_basename = os.path.basename(output_path);1949 const out_basename = os.path.basename(output_path);
1950 // sym link for libfoo.so.1 to libfoo.so.1.2.31950 // sym link for libfoo.so.1 to libfoo.so.1.2.3
std/c/darwin.zig+5-5
...@@ -1,10 +1,10 @@...@@ -1,10 +1,10 @@
1extern "c" fn __error() &c_int;1extern "c" fn __error() *c_int;
2pub extern "c" fn _NSGetExecutablePath(buf: &u8, bufsize: &u32) c_int;2pub extern "c" fn _NSGetExecutablePath(buf: [*]u8, bufsize: *u32) c_int;
33
4pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: &u8, buf_len: usize, basep: &i64) usize;4pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: [*]u8, buf_len: usize, basep: *i64) usize;
55
6pub extern "c" fn mach_absolute_time() u64;6pub extern "c" fn mach_absolute_time() u64;
7pub extern "c" fn mach_timebase_info(tinfo: ?&mach_timebase_info_data) void;7pub extern "c" fn mach_timebase_info(tinfo: ?*mach_timebase_info_data) void;
88
9pub use @import("../os/darwin_errno.zig");9pub use @import("../os/darwin_errno.zig");
1010
...@@ -60,7 +60,7 @@ pub const sigset_t = u32;...@@ -60,7 +60,7 @@ pub const sigset_t = u32;
6060
61/// Renamed from `sigaction` to `Sigaction` to avoid conflict with function name.61/// Renamed from `sigaction` to `Sigaction` to avoid conflict with function name.
62pub const Sigaction = extern struct {62pub const Sigaction = extern struct {
63 handler: extern fn(c_int) void,63 handler: extern fn (c_int) void,
64 sa_mask: sigset_t,64 sa_mask: sigset_t,
65 sa_flags: c_int,65 sa_flags: c_int,
66};66};
std/c/index.zig+38-36
...@@ -9,53 +9,55 @@ pub use switch (builtin.os) {...@@ -9,53 +9,55 @@ pub use switch (builtin.os) {
9};9};
10const empty_import = @import("../empty.zig");10const empty_import = @import("../empty.zig");
1111
12// TODO https://github.com/ziglang/zig/issues/265 on this whole file
13
12pub extern "c" fn abort() noreturn;14pub extern "c" fn abort() noreturn;
13pub extern "c" fn exit(code: c_int) noreturn;15pub extern "c" fn exit(code: c_int) noreturn;
14pub extern "c" fn isatty(fd: c_int) c_int;16pub extern "c" fn isatty(fd: c_int) c_int;
15pub extern "c" fn close(fd: c_int) c_int;17pub extern "c" fn close(fd: c_int) c_int;
16pub extern "c" fn fstat(fd: c_int, buf: &Stat) c_int;18pub extern "c" fn fstat(fd: c_int, buf: *Stat) c_int;
17pub extern "c" fn @"fstat$INODE64"(fd: c_int, buf: &Stat) c_int;19pub extern "c" fn @"fstat$INODE64"(fd: c_int, buf: *Stat) c_int;
18pub extern "c" fn lseek(fd: c_int, offset: isize, whence: c_int) isize;20pub extern "c" fn lseek(fd: c_int, offset: isize, whence: c_int) isize;
19pub extern "c" fn open(path: &const u8, oflag: c_int, ...) c_int;21pub extern "c" fn open(path: [*]const u8, oflag: c_int, ...) c_int;
20pub extern "c" fn raise(sig: c_int) c_int;22pub extern "c" fn raise(sig: c_int) c_int;
21pub extern "c" fn read(fd: c_int, buf: &c_void, nbyte: usize) isize;23pub extern "c" fn read(fd: c_int, buf: [*]c_void, nbyte: usize) isize;
22pub extern "c" fn stat(noalias path: &const u8, noalias buf: &Stat) c_int;24pub extern "c" fn stat(noalias path: [*]const u8, noalias buf: *Stat) c_int;
23pub extern "c" fn write(fd: c_int, buf: &const c_void, nbyte: usize) isize;25pub extern "c" fn write(fd: c_int, buf: [*]const c_void, nbyte: usize) isize;
24pub extern "c" fn mmap(addr: ?&c_void, len: usize, prot: c_int, flags: c_int, fd: c_int, offset: isize) ?&c_void;26pub extern "c" fn mmap(addr: ?[*]c_void, len: usize, prot: c_int, flags: c_int, fd: c_int, offset: isize) ?[*]c_void;
25pub extern "c" fn munmap(addr: &c_void, len: usize) c_int;27pub extern "c" fn munmap(addr: [*]c_void, len: usize) c_int;
26pub extern "c" fn unlink(path: &const u8) c_int;28pub extern "c" fn unlink(path: [*]const u8) c_int;
27pub extern "c" fn getcwd(buf: &u8, size: usize) ?&u8;29pub extern "c" fn getcwd(buf: [*]u8, size: usize) ?[*]u8;
28pub extern "c" fn waitpid(pid: c_int, stat_loc: &c_int, options: c_int) c_int;30pub extern "c" fn waitpid(pid: c_int, stat_loc: *c_int, options: c_int) c_int;
29pub extern "c" fn fork() c_int;31pub extern "c" fn fork() c_int;
30pub extern "c" fn access(path: &const u8, mode: c_uint) c_int;32pub extern "c" fn access(path: [*]const u8, mode: c_uint) c_int;
31pub extern "c" fn pipe(fds: &c_int) c_int;33pub extern "c" fn pipe(fds: *[2]c_int) c_int;
32pub extern "c" fn mkdir(path: &const u8, mode: c_uint) c_int;34pub extern "c" fn mkdir(path: [*]const u8, mode: c_uint) c_int;
33pub extern "c" fn symlink(existing: &const u8, new: &const u8) c_int;35pub extern "c" fn symlink(existing: [*]const u8, new: [*]const u8) c_int;
34pub extern "c" fn rename(old: &const u8, new: &const u8) c_int;36pub extern "c" fn rename(old: [*]const u8, new: [*]const u8) c_int;
35pub extern "c" fn chdir(path: &const u8) c_int;37pub extern "c" fn chdir(path: [*]const u8) c_int;
36pub extern "c" fn execve(path: &const u8, argv: &const ?&const u8, envp: &const ?&const u8) c_int;38pub extern "c" fn execve(path: [*]const u8, argv: [*]const ?[*]const u8, envp: [*]const ?[*]const u8) c_int;
37pub extern "c" fn dup(fd: c_int) c_int;39pub extern "c" fn dup(fd: c_int) c_int;
38pub extern "c" fn dup2(old_fd: c_int, new_fd: c_int) c_int;40pub extern "c" fn dup2(old_fd: c_int, new_fd: c_int) c_int;
39pub extern "c" fn readlink(noalias path: &const u8, noalias buf: &u8, bufsize: usize) isize;41pub extern "c" fn readlink(noalias path: [*]const u8, noalias buf: [*]u8, bufsize: usize) isize;
40pub extern "c" fn realpath(noalias file_name: &const u8, noalias resolved_name: &u8) ?&u8;42pub extern "c" fn realpath(noalias file_name: [*]const u8, noalias resolved_name: [*]u8) ?[*]u8;
41pub extern "c" fn sigprocmask(how: c_int, noalias set: &const sigset_t, noalias oset: ?&sigset_t) c_int;43pub extern "c" fn sigprocmask(how: c_int, noalias set: *const sigset_t, noalias oset: ?*sigset_t) c_int;
42pub extern "c" fn gettimeofday(tv: ?&timeval, tz: ?&timezone) c_int;44pub extern "c" fn gettimeofday(tv: ?*timeval, tz: ?*timezone) c_int;
43pub extern "c" fn sigaction(sig: c_int, noalias act: &const Sigaction, noalias oact: ?&Sigaction) c_int;45pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int;
44pub extern "c" fn nanosleep(rqtp: &const timespec, rmtp: ?&timespec) c_int;46pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int;
45pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int;47pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int;
46pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) c_int;48pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) c_int;
47pub extern "c" fn rmdir(path: &const u8) c_int;49pub extern "c" fn rmdir(path: [*]const u8) c_int;
4850
49pub extern "c" fn aligned_alloc(alignment: usize, size: usize) ?&c_void;51pub extern "c" fn aligned_alloc(alignment: usize, size: usize) ?[*]c_void;
50pub extern "c" fn malloc(usize) ?&c_void;52pub extern "c" fn malloc(usize) ?[*]c_void;
51pub extern "c" fn realloc(&c_void, usize) ?&c_void;53pub extern "c" fn realloc([*]c_void, usize) ?[*]c_void;
52pub extern "c" fn free(&c_void) void;54pub extern "c" fn free([*]c_void) void;
53pub extern "c" fn posix_memalign(memptr: &&c_void, alignment: usize, size: usize) c_int;55pub extern "c" fn posix_memalign(memptr: *[*]c_void, alignment: usize, size: usize) c_int;
5456
55pub extern "pthread" fn pthread_create(noalias newthread: &pthread_t, noalias attr: ?&const pthread_attr_t, start_routine: extern fn(?&c_void) ?&c_void, noalias arg: ?&c_void) c_int;57pub extern "pthread" fn pthread_create(noalias newthread: *pthread_t, noalias attr: ?*const pthread_attr_t, start_routine: extern fn (?*c_void) ?*c_void, noalias arg: ?*c_void) c_int;
56pub extern "pthread" fn pthread_attr_init(attr: &pthread_attr_t) c_int;58pub extern "pthread" fn pthread_attr_init(attr: *pthread_attr_t) c_int;
57pub extern "pthread" fn pthread_attr_setstack(attr: &pthread_attr_t, stackaddr: &c_void, stacksize: usize) c_int;59pub extern "pthread" fn pthread_attr_setstack(attr: *pthread_attr_t, stackaddr: [*]c_void, stacksize: usize) c_int;
58pub extern "pthread" fn pthread_attr_destroy(attr: &pthread_attr_t) c_int;60pub extern "pthread" fn pthread_attr_destroy(attr: *pthread_attr_t) c_int;
59pub extern "pthread" fn pthread_join(thread: pthread_t, arg_return: ?&?&c_void) c_int;61pub extern "pthread" fn pthread_join(thread: pthread_t, arg_return: ?*?*c_void) c_int;
6062
61pub const pthread_t = &@OpaqueType();63pub const pthread_t = *@OpaqueType();
std/c/linux.zig+2-2
...@@ -1,7 +1,7 @@...@@ -1,7 +1,7 @@
1pub use @import("../os/linux/errno.zig");1pub use @import("../os/linux/errno.zig");
22
3pub extern "c" fn getrandom(buf_ptr: &u8, buf_len: usize, flags: c_uint) c_int;3pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) c_int;
4extern "c" fn __errno_location() &c_int;4extern "c" fn __errno_location() *c_int;
5pub const _errno = __errno_location;5pub const _errno = __errno_location;
66
7pub const pthread_attr_t = extern struct {7pub const pthread_attr_t = extern struct {
std/c/windows.zig+1-1
...@@ -1 +1 @@...@@ -1 +1 @@
1pub extern "c" fn _errno() &c_int;1pub extern "c" fn _errno() *c_int;
std/crypto/blake2.zig+38-242
...@@ -49,16 +49,16 @@ fn Blake2s(comptime out_len: usize) type {...@@ -49,16 +49,16 @@ fn Blake2s(comptime out_len: usize) type {
49 };49 };
5050
51 const sigma = [10][16]u8{51 const sigma = [10][16]u8{
52 []const u8 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },52 []const u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
53 []const u8 { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },53 []const u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
54 []const u8 { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },54 []const u8{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
55 []const u8 { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },55 []const u8{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
56 []const u8 { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },56 []const u8{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
57 []const u8 { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },57 []const u8{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
58 []const u8 { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },58 []const u8{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
59 []const u8 { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },59 []const u8{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
60 []const u8 { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },60 []const u8{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
61 []const u8 { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 },61 []const u8{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 },
62 };62 };
6363
64 h: [8]u32,64 h: [8]u32,
...@@ -75,7 +75,7 @@ fn Blake2s(comptime out_len: usize) type {...@@ -75,7 +75,7 @@ fn Blake2s(comptime out_len: usize) type {
75 return s;75 return s;
76 }76 }
7777
78 pub fn reset(d: &Self) void {78 pub fn reset(d: *Self) void {
79 mem.copy(u32, d.h[0..], iv[0..]);79 mem.copy(u32, d.h[0..], iv[0..]);
8080
81 // No key plus default parameters81 // No key plus default parameters
...@@ -90,7 +90,7 @@ fn Blake2s(comptime out_len: usize) type {...@@ -90,7 +90,7 @@ fn Blake2s(comptime out_len: usize) type {
90 d.final(out);90 d.final(out);
91 }91 }
9292
93 pub fn update(d: &Self, b: []const u8) void {93 pub fn update(d: *Self, b: []const u8) void {
94 var off: usize = 0;94 var off: usize = 0;
9595
96 // Partial buffer exists from previous update. Copy into buffer then hash.96 // Partial buffer exists from previous update. Copy into buffer then hash.
...@@ -105,7 +105,7 @@ fn Blake2s(comptime out_len: usize) type {...@@ -105,7 +105,7 @@ fn Blake2s(comptime out_len: usize) type {
105 // Full middle blocks.105 // Full middle blocks.
106 while (off + 64 <= b.len) : (off += 64) {106 while (off + 64 <= b.len) : (off += 64) {
107 d.t += 64;107 d.t += 64;
108 d.round(b[off..off + 64], false);108 d.round(b[off .. off + 64], false);
109 }109 }
110110
111 // Copy any remainder for next pass.111 // Copy any remainder for next pass.
...@@ -113,28 +113,28 @@ fn Blake2s(comptime out_len: usize) type {...@@ -113,28 +113,28 @@ fn Blake2s(comptime out_len: usize) type {
113 d.buf_len += u8(b[off..].len);113 d.buf_len += u8(b[off..].len);
114 }114 }
115115
116 pub fn final(d: &Self, out: []u8) void {116 pub fn final(d: *Self, out: []u8) void {
117 debug.assert(out.len >= out_len / 8);117 debug.assert(out.len >= out_len / 8);
118118
119 mem.set(u8, d.buf[d.buf_len..], 0);119 mem.set(u8, d.buf[d.buf_len..], 0);
120 d.t += d.buf_len;120 d.t += d.buf_len;
121 d.round(d.buf[0..], true);121 d.round(d.buf[0..], true);
122122
123 const rr = d.h[0..out_len / 32];123 const rr = d.h[0 .. out_len / 32];
124124
125 for (rr) |s, j| {125 for (rr) |s, j| {
126 mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Little);126 mem.writeInt(out[4 * j .. 4 * j + 4], s, builtin.Endian.Little);
127 }127 }
128 }128 }
129129
130 fn round(d: &Self, b: []const u8, last: bool) void {130 fn round(d: *Self, b: []const u8, last: bool) void {
131 debug.assert(b.len == 64);131 debug.assert(b.len == 64);
132132
133 var m: [16]u32 = undefined;133 var m: [16]u32 = undefined;
134 var v: [16]u32 = undefined;134 var v: [16]u32 = undefined;
135135
136 for (m) |*r, i| {136 for (m) |*r, i| {
137 r.* = mem.readIntLE(u32, b[4 * i..4 * i + 4]);137 r.* = mem.readIntLE(u32, b[4 * i .. 4 * i + 4]);
138 }138 }
139139
140 var k: usize = 0;140 var k: usize = 0;
...@@ -282,222 +282,18 @@ fn Blake2b(comptime out_len: usize) type {...@@ -282,222 +282,18 @@ fn Blake2b(comptime out_len: usize) type {
282 };282 };
283283
284 const sigma = [12][16]u8{284 const sigma = [12][16]u8{
285 []const u8{285 []const u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
286 0,286 []const u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
287 1,287 []const u8{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
288 2,288 []const u8{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
289 3,289 []const u8{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
290 4,290 []const u8{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
291 5,291 []const u8{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
292 6,292 []const u8{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
293 7,293 []const u8{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
294 8,294 []const u8{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 },
295 9,295 []const u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
296 10,296 []const u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
297 11,
298 12,
299 13,
300 14,
301 15,
302 },
303 []const u8{
304 14,
305 10,
306 4,
307 8,
308 9,
309 15,
310 13,
311 6,
312 1,
313 12,
314 0,
315 2,
316 11,
317 7,
318 5,
319 3,
320 },
321 []const u8{
322 11,
323 8,
324 12,
325 0,
326 5,
327 2,
328 15,
329 13,
330 10,
331 14,
332 3,
333 6,
334 7,
335 1,
336 9,
337 4,
338 },
339 []const u8{
340 7,
341 9,
342 3,
343 1,
344 13,
345 12,
346 11,
347 14,
348 2,
349 6,
350 5,
351 10,
352 4,
353 0,
354 15,
355 8,
356 },
357 []const u8{
358 9,
359 0,
360 5,
361 7,
362 2,
363 4,
364 10,
365 15,
366 14,
367 1,
368 11,
369 12,
370 6,
371 8,
372 3,
373 13,
374 },
375 []const u8{
376 2,
377 12,
378 6,
379 10,
380 0,
381 11,
382 8,
383 3,
384 4,
385 13,
386 7,
387 5,
388 15,
389 14,
390 1,
391 9,
392 },
393 []const u8{
394 12,
395 5,
396 1,
397 15,
398 14,
399 13,
400 4,
401 10,
402 0,
403 7,
404 6,
405 3,
406 9,
407 2,
408 8,
409 11,
410 },
411 []const u8{
412 13,
413 11,
414 7,
415 14,
416 12,
417 1,
418 3,
419 9,
420 5,
421 0,
422 15,
423 4,
424 8,
425 6,
426 2,
427 10,
428 },
429 []const u8{
430 6,
431 15,
432 14,
433 9,
434 11,
435 3,
436 0,
437 8,
438 12,
439 2,
440 13,
441 7,
442 1,
443 4,
444 10,
445 5,
446 },
447 []const u8{
448 10,
449 2,
450 8,
451 4,
452 7,
453 6,
454 1,
455 5,
456 15,
457 11,
458 9,
459 14,
460 3,
461 12,
462 13,
463 0,
464 },
465 []const u8{
466 0,
467 1,
468 2,
469 3,
470 4,
471 5,
472 6,
473 7,
474 8,
475 9,
476 10,
477 11,
478 12,
479 13,
480 14,
481 15,
482 },
483 []const u8{
484 14,
485 10,
486 4,
487 8,
488 9,
489 15,
490 13,
491 6,
492 1,
493 12,
494 0,
495 2,
496 11,
497 7,
498 5,
499 3,
500 },
501 };297 };
502298
503 h: [8]u64,299 h: [8]u64,
...@@ -514,7 +310,7 @@ fn Blake2b(comptime out_len: usize) type {...@@ -514,7 +310,7 @@ fn Blake2b(comptime out_len: usize) type {
514 return s;310 return s;
515 }311 }
516312
517 pub fn reset(d: &Self) void {313 pub fn reset(d: *Self) void {
518 mem.copy(u64, d.h[0..], iv[0..]);314 mem.copy(u64, d.h[0..], iv[0..]);
519315
520 // No key plus default parameters316 // No key plus default parameters
...@@ -529,7 +325,7 @@ fn Blake2b(comptime out_len: usize) type {...@@ -529,7 +325,7 @@ fn Blake2b(comptime out_len: usize) type {
529 d.final(out);325 d.final(out);
530 }326 }
531327
532 pub fn update(d: &Self, b: []const u8) void {328 pub fn update(d: *Self, b: []const u8) void {
533 var off: usize = 0;329 var off: usize = 0;
534330
535 // Partial buffer exists from previous update. Copy into buffer then hash.331 // Partial buffer exists from previous update. Copy into buffer then hash.
...@@ -544,7 +340,7 @@ fn Blake2b(comptime out_len: usize) type {...@@ -544,7 +340,7 @@ fn Blake2b(comptime out_len: usize) type {
544 // Full middle blocks.340 // Full middle blocks.
545 while (off + 128 <= b.len) : (off += 128) {341 while (off + 128 <= b.len) : (off += 128) {
546 d.t += 128;342 d.t += 128;
547 d.round(b[off..off + 128], false);343 d.round(b[off .. off + 128], false);
548 }344 }
549345
550 // Copy any remainder for next pass.346 // Copy any remainder for next pass.
...@@ -552,26 +348,26 @@ fn Blake2b(comptime out_len: usize) type {...@@ -552,26 +348,26 @@ fn Blake2b(comptime out_len: usize) type {
552 d.buf_len += u8(b[off..].len);348 d.buf_len += u8(b[off..].len);
553 }349 }
554350
555 pub fn final(d: &Self, out: []u8) void {351 pub fn final(d: *Self, out: []u8) void {
556 mem.set(u8, d.buf[d.buf_len..], 0);352 mem.set(u8, d.buf[d.buf_len..], 0);
557 d.t += d.buf_len;353 d.t += d.buf_len;
558 d.round(d.buf[0..], true);354 d.round(d.buf[0..], true);
559355
560 const rr = d.h[0..out_len / 64];356 const rr = d.h[0 .. out_len / 64];
561357
562 for (rr) |s, j| {358 for (rr) |s, j| {
563 mem.writeInt(out[8 * j..8 * j + 8], s, builtin.Endian.Little);359 mem.writeInt(out[8 * j .. 8 * j + 8], s, builtin.Endian.Little);
564 }360 }
565 }361 }
566362
567 fn round(d: &Self, b: []const u8, last: bool) void {363 fn round(d: *Self, b: []const u8, last: bool) void {
568 debug.assert(b.len == 128);364 debug.assert(b.len == 128);
569365
570 var m: [16]u64 = undefined;366 var m: [16]u64 = undefined;
571 var v: [16]u64 = undefined;367 var v: [16]u64 = undefined;
572368
573 for (m) |*r, i| {369 for (m) |*r, i| {
574 r.* = mem.readIntLE(u64, b[8 * i..8 * i + 8]);370 r.* = mem.readIntLE(u64, b[8 * i .. 8 * i + 8]);
575 }371 }
576372
577 var k: usize = 0;373 var k: usize = 0;
std/crypto/md5.zig+6-6
...@@ -44,7 +44,7 @@ pub const Md5 = struct {...@@ -44,7 +44,7 @@ pub const Md5 = struct {
44 return d;44 return d;
45 }45 }
4646
47 pub fn reset(d: &Self) void {47 pub fn reset(d: *Self) void {
48 d.s[0] = 0x67452301;48 d.s[0] = 0x67452301;
49 d.s[1] = 0xEFCDAB89;49 d.s[1] = 0xEFCDAB89;
50 d.s[2] = 0x98BADCFE;50 d.s[2] = 0x98BADCFE;
...@@ -59,7 +59,7 @@ pub const Md5 = struct {...@@ -59,7 +59,7 @@ pub const Md5 = struct {
59 d.final(out);59 d.final(out);
60 }60 }
6161
62 pub fn update(d: &Self, b: []const u8) void {62 pub fn update(d: *Self, b: []const u8) void {
63 var off: usize = 0;63 var off: usize = 0;
6464
65 // Partial buffer exists from previous update. Copy into buffer then hash.65 // Partial buffer exists from previous update. Copy into buffer then hash.
...@@ -73,7 +73,7 @@ pub const Md5 = struct {...@@ -73,7 +73,7 @@ pub const Md5 = struct {
7373
74 // Full middle blocks.74 // Full middle blocks.
75 while (off + 64 <= b.len) : (off += 64) {75 while (off + 64 <= b.len) : (off += 64) {
76 d.round(b[off..off + 64]);76 d.round(b[off .. off + 64]);
77 }77 }
7878
79 // Copy any remainder for next pass.79 // Copy any remainder for next pass.
...@@ -84,7 +84,7 @@ pub const Md5 = struct {...@@ -84,7 +84,7 @@ pub const Md5 = struct {
84 d.total_len +%= b.len;84 d.total_len +%= b.len;
85 }85 }
8686
87 pub fn final(d: &Self, out: []u8) void {87 pub fn final(d: *Self, out: []u8) void {
88 debug.assert(out.len >= 16);88 debug.assert(out.len >= 16);
8989
90 // The buffer here will never be completely full.90 // The buffer here will never be completely full.
...@@ -112,11 +112,11 @@ pub const Md5 = struct {...@@ -112,11 +112,11 @@ pub const Md5 = struct {
112 d.round(d.buf[0..]);112 d.round(d.buf[0..]);
113113
114 for (d.s) |s, j| {114 for (d.s) |s, j| {
115 mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Little);115 mem.writeInt(out[4 * j .. 4 * j + 4], s, builtin.Endian.Little);
116 }116 }
117 }117 }
118118
119 fn round(d: &Self, b: []const u8) void {119 fn round(d: *Self, b: []const u8) void {
120 debug.assert(b.len == 64);120 debug.assert(b.len == 64);
121121
122 var s: [16]u32 = undefined;122 var s: [16]u32 = undefined;
std/crypto/sha1.zig+6-6
...@@ -43,7 +43,7 @@ pub const Sha1 = struct {...@@ -43,7 +43,7 @@ pub const Sha1 = struct {
43 return d;43 return d;
44 }44 }
4545
46 pub fn reset(d: &Self) void {46 pub fn reset(d: *Self) void {
47 d.s[0] = 0x67452301;47 d.s[0] = 0x67452301;
48 d.s[1] = 0xEFCDAB89;48 d.s[1] = 0xEFCDAB89;
49 d.s[2] = 0x98BADCFE;49 d.s[2] = 0x98BADCFE;
...@@ -59,7 +59,7 @@ pub const Sha1 = struct {...@@ -59,7 +59,7 @@ pub const Sha1 = struct {
59 d.final(out);59 d.final(out);
60 }60 }
6161
62 pub fn update(d: &Self, b: []const u8) void {62 pub fn update(d: *Self, b: []const u8) void {
63 var off: usize = 0;63 var off: usize = 0;
6464
65 // Partial buffer exists from previous update. Copy into buffer then hash.65 // Partial buffer exists from previous update. Copy into buffer then hash.
...@@ -73,7 +73,7 @@ pub const Sha1 = struct {...@@ -73,7 +73,7 @@ pub const Sha1 = struct {
7373
74 // Full middle blocks.74 // Full middle blocks.
75 while (off + 64 <= b.len) : (off += 64) {75 while (off + 64 <= b.len) : (off += 64) {
76 d.round(b[off..off + 64]);76 d.round(b[off .. off + 64]);
77 }77 }
7878
79 // Copy any remainder for next pass.79 // Copy any remainder for next pass.
...@@ -83,7 +83,7 @@ pub const Sha1 = struct {...@@ -83,7 +83,7 @@ pub const Sha1 = struct {
83 d.total_len += b.len;83 d.total_len += b.len;
84 }84 }
8585
86 pub fn final(d: &Self, out: []u8) void {86 pub fn final(d: *Self, out: []u8) void {
87 debug.assert(out.len >= 20);87 debug.assert(out.len >= 20);
8888
89 // The buffer here will never be completely full.89 // The buffer here will never be completely full.
...@@ -111,11 +111,11 @@ pub const Sha1 = struct {...@@ -111,11 +111,11 @@ pub const Sha1 = struct {
111 d.round(d.buf[0..]);111 d.round(d.buf[0..]);
112112
113 for (d.s) |s, j| {113 for (d.s) |s, j| {
114 mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Big);114 mem.writeInt(out[4 * j .. 4 * j + 4], s, builtin.Endian.Big);
115 }115 }
116 }116 }
117117
118 fn round(d: &Self, b: []const u8) void {118 fn round(d: *Self, b: []const u8) void {
119 debug.assert(b.len == 64);119 debug.assert(b.len == 64);
120120
121 var s: [16]u32 = undefined;121 var s: [16]u32 = undefined;
std/crypto/sha2.zig+14-14
...@@ -93,7 +93,7 @@ fn Sha2_32(comptime params: Sha2Params32) type {...@@ -93,7 +93,7 @@ fn Sha2_32(comptime params: Sha2Params32) type {
93 return d;93 return d;
94 }94 }
9595
96 pub fn reset(d: &Self) void {96 pub fn reset(d: *Self) void {
97 d.s[0] = params.iv0;97 d.s[0] = params.iv0;
98 d.s[1] = params.iv1;98 d.s[1] = params.iv1;
99 d.s[2] = params.iv2;99 d.s[2] = params.iv2;
...@@ -112,7 +112,7 @@ fn Sha2_32(comptime params: Sha2Params32) type {...@@ -112,7 +112,7 @@ fn Sha2_32(comptime params: Sha2Params32) type {
112 d.final(out);112 d.final(out);
113 }113 }
114114
115 pub fn update(d: &Self, b: []const u8) void {115 pub fn update(d: *Self, b: []const u8) void {
116 var off: usize = 0;116 var off: usize = 0;
117117
118 // Partial buffer exists from previous update. Copy into buffer then hash.118 // Partial buffer exists from previous update. Copy into buffer then hash.
...@@ -126,7 +126,7 @@ fn Sha2_32(comptime params: Sha2Params32) type {...@@ -126,7 +126,7 @@ fn Sha2_32(comptime params: Sha2Params32) type {
126126
127 // Full middle blocks.127 // Full middle blocks.
128 while (off + 64 <= b.len) : (off += 64) {128 while (off + 64 <= b.len) : (off += 64) {
129 d.round(b[off..off + 64]);129 d.round(b[off .. off + 64]);
130 }130 }
131131
132 // Copy any remainder for next pass.132 // Copy any remainder for next pass.
...@@ -136,7 +136,7 @@ fn Sha2_32(comptime params: Sha2Params32) type {...@@ -136,7 +136,7 @@ fn Sha2_32(comptime params: Sha2Params32) type {
136 d.total_len += b.len;136 d.total_len += b.len;
137 }137 }
138138
139 pub fn final(d: &Self, out: []u8) void {139 pub fn final(d: *Self, out: []u8) void {
140 debug.assert(out.len >= params.out_len / 8);140 debug.assert(out.len >= params.out_len / 8);
141141
142 // The buffer here will never be completely full.142 // The buffer here will never be completely full.
...@@ -164,14 +164,14 @@ fn Sha2_32(comptime params: Sha2Params32) type {...@@ -164,14 +164,14 @@ fn Sha2_32(comptime params: Sha2Params32) type {
164 d.round(d.buf[0..]);164 d.round(d.buf[0..]);
165165
166 // May truncate for possible 224 output166 // May truncate for possible 224 output
167 const rr = d.s[0..params.out_len / 32];167 const rr = d.s[0 .. params.out_len / 32];
168168
169 for (rr) |s, j| {169 for (rr) |s, j| {
170 mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Big);170 mem.writeInt(out[4 * j .. 4 * j + 4], s, builtin.Endian.Big);
171 }171 }
172 }172 }
173173
174 fn round(d: &Self, b: []const u8) void {174 fn round(d: *Self, b: []const u8) void {
175 debug.assert(b.len == 64);175 debug.assert(b.len == 64);
176176
177 var s: [64]u32 = undefined;177 var s: [64]u32 = undefined;
...@@ -434,7 +434,7 @@ fn Sha2_64(comptime params: Sha2Params64) type {...@@ -434,7 +434,7 @@ fn Sha2_64(comptime params: Sha2Params64) type {
434 return d;434 return d;
435 }435 }
436436
437 pub fn reset(d: &Self) void {437 pub fn reset(d: *Self) void {
438 d.s[0] = params.iv0;438 d.s[0] = params.iv0;
439 d.s[1] = params.iv1;439 d.s[1] = params.iv1;
440 d.s[2] = params.iv2;440 d.s[2] = params.iv2;
...@@ -453,7 +453,7 @@ fn Sha2_64(comptime params: Sha2Params64) type {...@@ -453,7 +453,7 @@ fn Sha2_64(comptime params: Sha2Params64) type {
453 d.final(out);453 d.final(out);
454 }454 }
455455
456 pub fn update(d: &Self, b: []const u8) void {456 pub fn update(d: *Self, b: []const u8) void {
457 var off: usize = 0;457 var off: usize = 0;
458458
459 // Partial buffer exists from previous update. Copy into buffer then hash.459 // Partial buffer exists from previous update. Copy into buffer then hash.
...@@ -467,7 +467,7 @@ fn Sha2_64(comptime params: Sha2Params64) type {...@@ -467,7 +467,7 @@ fn Sha2_64(comptime params: Sha2Params64) type {
467467
468 // Full middle blocks.468 // Full middle blocks.
469 while (off + 128 <= b.len) : (off += 128) {469 while (off + 128 <= b.len) : (off += 128) {
470 d.round(b[off..off + 128]);470 d.round(b[off .. off + 128]);
471 }471 }
472472
473 // Copy any remainder for next pass.473 // Copy any remainder for next pass.
...@@ -477,7 +477,7 @@ fn Sha2_64(comptime params: Sha2Params64) type {...@@ -477,7 +477,7 @@ fn Sha2_64(comptime params: Sha2Params64) type {
477 d.total_len += b.len;477 d.total_len += b.len;
478 }478 }
479479
480 pub fn final(d: &Self, out: []u8) void {480 pub fn final(d: *Self, out: []u8) void {
481 debug.assert(out.len >= params.out_len / 8);481 debug.assert(out.len >= params.out_len / 8);
482482
483 // The buffer here will never be completely full.483 // The buffer here will never be completely full.
...@@ -505,14 +505,14 @@ fn Sha2_64(comptime params: Sha2Params64) type {...@@ -505,14 +505,14 @@ fn Sha2_64(comptime params: Sha2Params64) type {
505 d.round(d.buf[0..]);505 d.round(d.buf[0..]);
506506
507 // May truncate for possible 384 output507 // May truncate for possible 384 output
508 const rr = d.s[0..params.out_len / 64];508 const rr = d.s[0 .. params.out_len / 64];
509509
510 for (rr) |s, j| {510 for (rr) |s, j| {
511 mem.writeInt(out[8 * j..8 * j + 8], s, builtin.Endian.Big);511 mem.writeInt(out[8 * j .. 8 * j + 8], s, builtin.Endian.Big);
512 }512 }
513 }513 }
514514
515 fn round(d: &Self, b: []const u8) void {515 fn round(d: *Self, b: []const u8) void {
516 debug.assert(b.len == 128);516 debug.assert(b.len == 128);
517517
518 var s: [80]u64 = undefined;518 var s: [80]u64 = undefined;
std/crypto/sha3.zig+7-7
...@@ -26,7 +26,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type {...@@ -26,7 +26,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type {
26 return d;26 return d;
27 }27 }
2828
29 pub fn reset(d: &Self) void {29 pub fn reset(d: *Self) void {
30 mem.set(u8, d.s[0..], 0);30 mem.set(u8, d.s[0..], 0);
31 d.offset = 0;31 d.offset = 0;
32 d.rate = 200 - (bits / 4);32 d.rate = 200 - (bits / 4);
...@@ -38,7 +38,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type {...@@ -38,7 +38,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type {
38 d.final(out);38 d.final(out);
39 }39 }
4040
41 pub fn update(d: &Self, b: []const u8) void {41 pub fn update(d: *Self, b: []const u8) void {
42 var ip: usize = 0;42 var ip: usize = 0;
43 var len = b.len;43 var len = b.len;
44 var rate = d.rate - d.offset;44 var rate = d.rate - d.offset;
...@@ -46,7 +46,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type {...@@ -46,7 +46,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type {
4646
47 // absorb47 // absorb
48 while (len >= rate) {48 while (len >= rate) {
49 for (d.s[offset..offset + rate]) |*r, i|49 for (d.s[offset .. offset + rate]) |*r, i|
50 r.* ^= b[ip..][i];50 r.* ^= b[ip..][i];
5151
52 keccak_f(1600, d.s[0..]);52 keccak_f(1600, d.s[0..]);
...@@ -57,13 +57,13 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type {...@@ -57,13 +57,13 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type {
57 offset = 0;57 offset = 0;
58 }58 }
5959
60 for (d.s[offset..offset + len]) |*r, i|60 for (d.s[offset .. offset + len]) |*r, i|
61 r.* ^= b[ip..][i];61 r.* ^= b[ip..][i];
6262
63 d.offset = offset + len;63 d.offset = offset + len;
64 }64 }
6565
66 pub fn final(d: &Self, out: []u8) void {66 pub fn final(d: *Self, out: []u8) void {
67 // padding67 // padding
68 d.s[d.offset] ^= delim;68 d.s[d.offset] ^= delim;
69 d.s[d.rate - 1] ^= 0x80;69 d.s[d.rate - 1] ^= 0x80;
...@@ -193,7 +193,7 @@ fn keccak_f(comptime F: usize, d: []u8) void {...@@ -193,7 +193,7 @@ fn keccak_f(comptime F: usize, d: []u8) void {
193 var c = []const u64{0} ** 5;193 var c = []const u64{0} ** 5;
194194
195 for (s) |*r, i| {195 for (s) |*r, i| {
196 r.* = mem.readIntLE(u64, d[8 * i..8 * i + 8]);196 r.* = mem.readIntLE(u64, d[8 * i .. 8 * i + 8]);
197 }197 }
198198
199 comptime var x: usize = 0;199 comptime var x: usize = 0;
...@@ -240,7 +240,7 @@ fn keccak_f(comptime F: usize, d: []u8) void {...@@ -240,7 +240,7 @@ fn keccak_f(comptime F: usize, d: []u8) void {
240 }240 }
241241
242 for (s) |r, i| {242 for (s) |r, i| {
243 mem.writeInt(d[8 * i..8 * i + 8], r, builtin.Endian.Little);243 mem.writeInt(d[8 * i .. 8 * i + 8], r, builtin.Endian.Little);
244 }244 }
245}245}
246246
std/crypto/test.zig+1-1
...@@ -14,7 +14,7 @@ pub fn assertEqualHash(comptime Hasher: var, comptime expected: []const u8, inpu...@@ -14,7 +14,7 @@ pub fn assertEqualHash(comptime Hasher: var, comptime expected: []const u8, inpu
14pub fn assertEqual(comptime expected: []const u8, input: []const u8) void {14pub fn assertEqual(comptime expected: []const u8, input: []const u8) void {
15 var expected_bytes: [expected.len / 2]u8 = undefined;15 var expected_bytes: [expected.len / 2]u8 = undefined;
16 for (expected_bytes) |*r, i| {16 for (expected_bytes) |*r, i| {
17 r.* = fmt.parseInt(u8, expected[2 * i..2 * i + 2], 16) catch unreachable;17 r.* = fmt.parseInt(u8, expected[2 * i .. 2 * i + 2], 16) catch unreachable;
18 }18 }
1919
20 debug.assert(mem.eql(u8, expected_bytes, input));20 debug.assert(mem.eql(u8, expected_bytes, input));
std/crypto/throughput_test.zig+2-2
...@@ -15,8 +15,8 @@ const BytesToHash = 1024 * MiB;...@@ -15,8 +15,8 @@ const BytesToHash = 1024 * MiB;
1515
16pub fn main() !void {16pub fn main() !void {
17 var stdout_file = try std.io.getStdOut();17 var stdout_file = try std.io.getStdOut();
18 var stdout_out_stream = std.io.FileOutStream.init(&stdout_file);18 var stdout_out_stream = std.io.FileOutStream.init(*stdout_file);
19 const stdout = &stdout_out_stream.stream;19 const stdout = *stdout_out_stream.stream;
2020
21 var block: [HashFunction.block_size]u8 = undefined;21 var block: [HashFunction.block_size]u8 = undefined;
22 std.mem.set(u8, block[0..], 0);22 std.mem.set(u8, block[0..], 0);
std/cstr.zig+14-14
...@@ -9,13 +9,13 @@ pub const line_sep = switch (builtin.os) {...@@ -9,13 +9,13 @@ pub const line_sep = switch (builtin.os) {
9 else => "\n",9 else => "\n",
10};10};
1111
12pub fn len(ptr: &const u8) usize {12pub fn len(ptr: [*]const u8) usize {
13 var count: usize = 0;13 var count: usize = 0;
14 while (ptr[count] != 0) : (count += 1) {}14 while (ptr[count] != 0) : (count += 1) {}
15 return count;15 return count;
16}16}
1717
18pub fn cmp(a: &const u8, b: &const u8) i8 {18pub fn cmp(a: [*]const u8, b: [*]const u8) i8 {
19 var index: usize = 0;19 var index: usize = 0;
20 while (a[index] == b[index] and a[index] != 0) : (index += 1) {}20 while (a[index] == b[index] and a[index] != 0) : (index += 1) {}
21 if (a[index] > b[index]) {21 if (a[index] > b[index]) {
...@@ -27,11 +27,11 @@ pub fn cmp(a: &const u8, b: &const u8) i8 {...@@ -27,11 +27,11 @@ pub fn cmp(a: &const u8, b: &const u8) i8 {
27 }27 }
28}28}
2929
30pub fn toSliceConst(str: &const u8) []const u8 {30pub fn toSliceConst(str: [*]const u8) []const u8 {
31 return str[0..len(str)];31 return str[0..len(str)];
32}32}
3333
34pub fn toSlice(str: &u8) []u8 {34pub fn toSlice(str: [*]u8) []u8 {
35 return str[0..len(str)];35 return str[0..len(str)];
36}36}
3737
...@@ -47,7 +47,7 @@ fn testCStrFnsImpl() void {...@@ -47,7 +47,7 @@ fn testCStrFnsImpl() void {
4747
48/// Returns a mutable slice with 1 more byte of length which is a null byte.48/// Returns a mutable slice with 1 more byte of length which is a null byte.
49/// Caller owns the returned memory.49/// Caller owns the returned memory.
50pub fn addNullByte(allocator: &mem.Allocator, slice: []const u8) ![]u8 {50pub fn addNullByte(allocator: *mem.Allocator, slice: []const u8) ![]u8 {
51 const result = try allocator.alloc(u8, slice.len + 1);51 const result = try allocator.alloc(u8, slice.len + 1);
52 mem.copy(u8, result, slice);52 mem.copy(u8, result, slice);
53 result[slice.len] = 0;53 result[slice.len] = 0;
...@@ -55,13 +55,13 @@ pub fn addNullByte(allocator: &mem.Allocator, slice: []const u8) ![]u8 {...@@ -55,13 +55,13 @@ pub fn addNullByte(allocator: &mem.Allocator, slice: []const u8) ![]u8 {
55}55}
5656
57pub const NullTerminated2DArray = struct {57pub const NullTerminated2DArray = struct {
58 allocator: &mem.Allocator,58 allocator: *mem.Allocator,
59 byte_count: usize,59 byte_count: usize,
60 ptr: ?&?&u8,60 ptr: ?[*]?[*]u8,
6161
62 /// Takes N lists of strings, concatenates the lists together, and adds a null terminator62 /// Takes N lists of strings, concatenates the lists together, and adds a null terminator
63 /// Caller must deinit result63 /// Caller must deinit result
64 pub fn fromSlices(allocator: &mem.Allocator, slices: []const []const []const u8) !NullTerminated2DArray {64 pub fn fromSlices(allocator: *mem.Allocator, slices: []const []const []const u8) !NullTerminated2DArray {
65 var new_len: usize = 1; // 1 for the list null65 var new_len: usize = 1; // 1 for the list null
66 var byte_count: usize = 0;66 var byte_count: usize = 0;
67 for (slices) |slice| {67 for (slices) |slice| {
...@@ -75,16 +75,16 @@ pub const NullTerminated2DArray = struct {...@@ -75,16 +75,16 @@ pub const NullTerminated2DArray = struct {
75 const index_size = @sizeOf(usize) * new_len; // size of the ptrs75 const index_size = @sizeOf(usize) * new_len; // size of the ptrs
76 byte_count += index_size;76 byte_count += index_size;
7777
78 const buf = try allocator.alignedAlloc(u8, @alignOf(?&u8), byte_count);78 const buf = try allocator.alignedAlloc(u8, @alignOf(?*u8), byte_count);
79 errdefer allocator.free(buf);79 errdefer allocator.free(buf);
8080
81 var write_index = index_size;81 var write_index = index_size;
82 const index_buf = ([]?&u8)(buf);82 const index_buf = ([]?[*]u8)(buf);
8383
84 var i: usize = 0;84 var i: usize = 0;
85 for (slices) |slice| {85 for (slices) |slice| {
86 for (slice) |inner| {86 for (slice) |inner| {
87 index_buf[i] = &buf[write_index];87 index_buf[i] = buf.ptr + write_index;
88 i += 1;88 i += 1;
89 mem.copy(u8, buf[write_index..], inner);89 mem.copy(u8, buf[write_index..], inner);
90 write_index += inner.len;90 write_index += inner.len;
...@@ -97,12 +97,12 @@ pub const NullTerminated2DArray = struct {...@@ -97,12 +97,12 @@ pub const NullTerminated2DArray = struct {
97 return NullTerminated2DArray{97 return NullTerminated2DArray{
98 .allocator = allocator,98 .allocator = allocator,
99 .byte_count = byte_count,99 .byte_count = byte_count,
100 .ptr = @ptrCast(?&?&u8, buf.ptr),100 .ptr = @ptrCast(?[*]?[*]u8, buf.ptr),
101 };101 };
102 }102 }
103103
104 pub fn deinit(self: &NullTerminated2DArray) void {104 pub fn deinit(self: *NullTerminated2DArray) void {
105 const buf = @ptrCast(&u8, self.ptr);105 const buf = @ptrCast([*]u8, self.ptr);
106 self.allocator.free(buf[0..self.byte_count]);106 self.allocator.free(buf[0..self.byte_count]);
107 }107 }
108};108};
std/debug/failing_allocator.zig+5-5
...@@ -7,12 +7,12 @@ pub const FailingAllocator = struct {...@@ -7,12 +7,12 @@ pub const FailingAllocator = struct {
7 allocator: mem.Allocator,7 allocator: mem.Allocator,
8 index: usize,8 index: usize,
9 fail_index: usize,9 fail_index: usize,
10 internal_allocator: &mem.Allocator,10 internal_allocator: *mem.Allocator,
11 allocated_bytes: usize,11 allocated_bytes: usize,
12 freed_bytes: usize,12 freed_bytes: usize,
13 deallocations: usize,13 deallocations: usize,
1414
15 pub fn init(allocator: &mem.Allocator, fail_index: usize) FailingAllocator {15 pub fn init(allocator: *mem.Allocator, fail_index: usize) FailingAllocator {
16 return FailingAllocator{16 return FailingAllocator{
17 .internal_allocator = allocator,17 .internal_allocator = allocator,
18 .fail_index = fail_index,18 .fail_index = fail_index,
...@@ -28,7 +28,7 @@ pub const FailingAllocator = struct {...@@ -28,7 +28,7 @@ pub const FailingAllocator = struct {
28 };28 };
29 }29 }
3030
31 fn alloc(allocator: &mem.Allocator, n: usize, alignment: u29) ![]u8 {31 fn alloc(allocator: *mem.Allocator, n: usize, alignment: u29) ![]u8 {
32 const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);32 const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);
33 if (self.index == self.fail_index) {33 if (self.index == self.fail_index) {
34 return error.OutOfMemory;34 return error.OutOfMemory;
...@@ -39,7 +39,7 @@ pub const FailingAllocator = struct {...@@ -39,7 +39,7 @@ pub const FailingAllocator = struct {
39 return result;39 return result;
40 }40 }
4141
42 fn realloc(allocator: &mem.Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {42 fn realloc(allocator: *mem.Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {
43 const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);43 const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);
44 if (new_size <= old_mem.len) {44 if (new_size <= old_mem.len) {
45 self.freed_bytes += old_mem.len - new_size;45 self.freed_bytes += old_mem.len - new_size;
...@@ -55,7 +55,7 @@ pub const FailingAllocator = struct {...@@ -55,7 +55,7 @@ pub const FailingAllocator = struct {
55 return result;55 return result;
56 }56 }
5757
58 fn free(allocator: &mem.Allocator, bytes: []u8) void {58 fn free(allocator: *mem.Allocator, bytes: []u8) void {
59 const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);59 const self = @fieldParentPtr(FailingAllocator, "allocator", allocator);
60 self.freed_bytes += bytes.len;60 self.freed_bytes += bytes.len;
61 self.deallocations += 1;61 self.deallocations += 1;
std/debug/index.zig+53-53
...@@ -16,12 +16,12 @@ pub const FailingAllocator = @import("failing_allocator.zig").FailingAllocator;...@@ -16,12 +16,12 @@ pub const FailingAllocator = @import("failing_allocator.zig").FailingAllocator;
16/// TODO atomic/multithread support16/// TODO atomic/multithread support
17var stderr_file: os.File = undefined;17var stderr_file: os.File = undefined;
18var stderr_file_out_stream: io.FileOutStream = undefined;18var stderr_file_out_stream: io.FileOutStream = undefined;
19var stderr_stream: ?&io.OutStream(io.FileOutStream.Error) = null;19var stderr_stream: ?*io.OutStream(io.FileOutStream.Error) = null;
20pub fn warn(comptime fmt: []const u8, args: ...) void {20pub fn warn(comptime fmt: []const u8, args: ...) void {
21 const stderr = getStderrStream() catch return;21 const stderr = getStderrStream() catch return;
22 stderr.print(fmt, args) catch return;22 stderr.print(fmt, args) catch return;
23}23}
24fn getStderrStream() !&io.OutStream(io.FileOutStream.Error) {24fn getStderrStream() !*io.OutStream(io.FileOutStream.Error) {
25 if (stderr_stream) |st| {25 if (stderr_stream) |st| {
26 return st;26 return st;
27 } else {27 } else {
...@@ -33,8 +33,8 @@ fn getStderrStream() !&io.OutStream(io.FileOutStream.Error) {...@@ -33,8 +33,8 @@ fn getStderrStream() !&io.OutStream(io.FileOutStream.Error) {
33 }33 }
34}34}
3535
36var self_debug_info: ?&ElfStackTrace = null;36var self_debug_info: ?*ElfStackTrace = null;
37pub fn getSelfDebugInfo() !&ElfStackTrace {37pub fn getSelfDebugInfo() !*ElfStackTrace {
38 if (self_debug_info) |info| {38 if (self_debug_info) |info| {
39 return info;39 return info;
40 } else {40 } else {
...@@ -58,7 +58,7 @@ pub fn dumpCurrentStackTrace(start_addr: ?usize) void {...@@ -58,7 +58,7 @@ pub fn dumpCurrentStackTrace(start_addr: ?usize) void {
58}58}
5959
60/// Tries to print a stack trace to stderr, unbuffered, and ignores any error returned.60/// Tries to print a stack trace to stderr, unbuffered, and ignores any error returned.
61pub fn dumpStackTrace(stack_trace: &const builtin.StackTrace) void {61pub fn dumpStackTrace(stack_trace: *const builtin.StackTrace) void {
62 const stderr = getStderrStream() catch return;62 const stderr = getStderrStream() catch return;
63 const debug_info = getSelfDebugInfo() catch |err| {63 const debug_info = getSelfDebugInfo() catch |err| {
64 stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", @errorName(err)) catch return;64 stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", @errorName(err)) catch return;
...@@ -104,7 +104,7 @@ pub fn panic(comptime format: []const u8, args: ...) noreturn {...@@ -104,7 +104,7 @@ pub fn panic(comptime format: []const u8, args: ...) noreturn {
104104
105var panicking: u8 = 0; // TODO make this a bool105var panicking: u8 = 0; // TODO make this a bool
106106
107pub fn panicExtra(trace: ?&const builtin.StackTrace, first_trace_addr: ?usize, comptime format: []const u8, args: ...) noreturn {107pub fn panicExtra(trace: ?*const builtin.StackTrace, first_trace_addr: ?usize, comptime format: []const u8, args: ...) noreturn {
108 @setCold(true);108 @setCold(true);
109109
110 if (@atomicRmw(u8, &panicking, builtin.AtomicRmwOp.Xchg, 1, builtin.AtomicOrder.SeqCst) == 1) {110 if (@atomicRmw(u8, &panicking, builtin.AtomicRmwOp.Xchg, 1, builtin.AtomicOrder.SeqCst) == 1) {
...@@ -130,7 +130,7 @@ const WHITE = "\x1b[37;1m";...@@ -130,7 +130,7 @@ const WHITE = "\x1b[37;1m";
130const DIM = "\x1b[2m";130const DIM = "\x1b[2m";
131const RESET = "\x1b[0m";131const RESET = "\x1b[0m";
132132
133pub fn writeStackTrace(stack_trace: &const builtin.StackTrace, out_stream: var, allocator: &mem.Allocator, debug_info: &ElfStackTrace, tty_color: bool) !void {133pub fn writeStackTrace(stack_trace: *const builtin.StackTrace, out_stream: var, allocator: *mem.Allocator, debug_info: *ElfStackTrace, tty_color: bool) !void {
134 var frame_index: usize = undefined;134 var frame_index: usize = undefined;
135 var frames_left: usize = undefined;135 var frames_left: usize = undefined;
136 if (stack_trace.index < stack_trace.instruction_addresses.len) {136 if (stack_trace.index < stack_trace.instruction_addresses.len) {
...@@ -150,7 +150,7 @@ pub fn writeStackTrace(stack_trace: &const builtin.StackTrace, out_stream: var,...@@ -150,7 +150,7 @@ pub fn writeStackTrace(stack_trace: &const builtin.StackTrace, out_stream: var,
150 }150 }
151}151}
152152
153pub fn writeCurrentStackTrace(out_stream: var, allocator: &mem.Allocator, debug_info: &ElfStackTrace, tty_color: bool, start_addr: ?usize) !void {153pub fn writeCurrentStackTrace(out_stream: var, allocator: *mem.Allocator, debug_info: *ElfStackTrace, tty_color: bool, start_addr: ?usize) !void {
154 const AddressState = union(enum) {154 const AddressState = union(enum) {
155 NotLookingForStartAddress,155 NotLookingForStartAddress,
156 LookingForStartAddress: usize,156 LookingForStartAddress: usize,
...@@ -166,8 +166,8 @@ pub fn writeCurrentStackTrace(out_stream: var, allocator: &mem.Allocator, debug_...@@ -166,8 +166,8 @@ pub fn writeCurrentStackTrace(out_stream: var, allocator: &mem.Allocator, debug_
166 }166 }
167167
168 var fp = @ptrToInt(@frameAddress());168 var fp = @ptrToInt(@frameAddress());
169 while (fp != 0) : (fp = @intToPtr(&const usize, fp).*) {169 while (fp != 0) : (fp = @intToPtr(*const usize, fp).*) {
170 const return_address = @intToPtr(&const usize, fp + @sizeOf(usize)).*;170 const return_address = @intToPtr(*const usize, fp + @sizeOf(usize)).*;
171171
172 switch (addr_state) {172 switch (addr_state) {
173 AddressState.NotLookingForStartAddress => {},173 AddressState.NotLookingForStartAddress => {},
...@@ -183,7 +183,7 @@ pub fn writeCurrentStackTrace(out_stream: var, allocator: &mem.Allocator, debug_...@@ -183,7 +183,7 @@ pub fn writeCurrentStackTrace(out_stream: var, allocator: &mem.Allocator, debug_
183 }183 }
184}184}
185185
186fn printSourceAtAddress(debug_info: &ElfStackTrace, out_stream: var, address: usize) !void {186fn printSourceAtAddress(debug_info: *ElfStackTrace, out_stream: var, address: usize) !void {
187 const ptr_hex = "0x{x}";187 const ptr_hex = "0x{x}";
188188
189 switch (builtin.os) {189 switch (builtin.os) {
...@@ -236,7 +236,7 @@ fn printSourceAtAddress(debug_info: &ElfStackTrace, out_stream: var, address: us...@@ -236,7 +236,7 @@ fn printSourceAtAddress(debug_info: &ElfStackTrace, out_stream: var, address: us
236 }236 }
237}237}
238238
239pub fn openSelfDebugInfo(allocator: &mem.Allocator) !&ElfStackTrace {239pub fn openSelfDebugInfo(allocator: *mem.Allocator) !*ElfStackTrace {
240 switch (builtin.object_format) {240 switch (builtin.object_format) {
241 builtin.ObjectFormat.elf => {241 builtin.ObjectFormat.elf => {
242 const st = try allocator.create(ElfStackTrace);242 const st = try allocator.create(ElfStackTrace);
...@@ -289,7 +289,7 @@ pub fn openSelfDebugInfo(allocator: &mem.Allocator) !&ElfStackTrace {...@@ -289,7 +289,7 @@ pub fn openSelfDebugInfo(allocator: &mem.Allocator) !&ElfStackTrace {
289 }289 }
290}290}
291291
292fn printLineFromFile(allocator: &mem.Allocator, out_stream: var, line_info: &const LineInfo) !void {292fn printLineFromFile(allocator: *mem.Allocator, out_stream: var, line_info: *const LineInfo) !void {
293 var f = try os.File.openRead(allocator, line_info.file_name);293 var f = try os.File.openRead(allocator, line_info.file_name);
294 defer f.close();294 defer f.close();
295 // TODO fstat and make sure that the file has the correct size295 // TODO fstat and make sure that the file has the correct size
...@@ -325,32 +325,32 @@ pub const ElfStackTrace = switch (builtin.os) {...@@ -325,32 +325,32 @@ pub const ElfStackTrace = switch (builtin.os) {
325 builtin.Os.macosx => struct {325 builtin.Os.macosx => struct {
326 symbol_table: macho.SymbolTable,326 symbol_table: macho.SymbolTable,
327327
328 pub fn close(self: &ElfStackTrace) void {328 pub fn close(self: *ElfStackTrace) void {
329 self.symbol_table.deinit();329 self.symbol_table.deinit();
330 }330 }
331 },331 },
332 else => struct {332 else => struct {
333 self_exe_file: os.File,333 self_exe_file: os.File,
334 elf: elf.Elf,334 elf: elf.Elf,
335 debug_info: &elf.SectionHeader,335 debug_info: *elf.SectionHeader,
336 debug_abbrev: &elf.SectionHeader,336 debug_abbrev: *elf.SectionHeader,
337 debug_str: &elf.SectionHeader,337 debug_str: *elf.SectionHeader,
338 debug_line: &elf.SectionHeader,338 debug_line: *elf.SectionHeader,
339 debug_ranges: ?&elf.SectionHeader,339 debug_ranges: ?*elf.SectionHeader,
340 abbrev_table_list: ArrayList(AbbrevTableHeader),340 abbrev_table_list: ArrayList(AbbrevTableHeader),
341 compile_unit_list: ArrayList(CompileUnit),341 compile_unit_list: ArrayList(CompileUnit),
342342
343 pub fn allocator(self: &const ElfStackTrace) &mem.Allocator {343 pub fn allocator(self: *const ElfStackTrace) *mem.Allocator {
344 return self.abbrev_table_list.allocator;344 return self.abbrev_table_list.allocator;
345 }345 }
346346
347 pub fn readString(self: &ElfStackTrace) ![]u8 {347 pub fn readString(self: *ElfStackTrace) ![]u8 {
348 var in_file_stream = io.FileInStream.init(&self.self_exe_file);348 var in_file_stream = io.FileInStream.init(&self.self_exe_file);
349 const in_stream = &in_file_stream.stream;349 const in_stream = &in_file_stream.stream;
350 return readStringRaw(self.allocator(), in_stream);350 return readStringRaw(self.allocator(), in_stream);
351 }351 }
352352
353 pub fn close(self: &ElfStackTrace) void {353 pub fn close(self: *ElfStackTrace) void {
354 self.self_exe_file.close();354 self.self_exe_file.close();
355 self.elf.close();355 self.elf.close();
356 }356 }
...@@ -365,7 +365,7 @@ const PcRange = struct {...@@ -365,7 +365,7 @@ const PcRange = struct {
365const CompileUnit = struct {365const CompileUnit = struct {
366 version: u16,366 version: u16,
367 is_64: bool,367 is_64: bool,
368 die: &Die,368 die: *Die,
369 index: usize,369 index: usize,
370 pc_range: ?PcRange,370 pc_range: ?PcRange,
371};371};
...@@ -408,7 +408,7 @@ const Constant = struct {...@@ -408,7 +408,7 @@ const Constant = struct {
408 payload: []u8,408 payload: []u8,
409 signed: bool,409 signed: bool,
410410
411 fn asUnsignedLe(self: &const Constant) !u64 {411 fn asUnsignedLe(self: *const Constant) !u64 {
412 if (self.payload.len > @sizeOf(u64)) return error.InvalidDebugInfo;412 if (self.payload.len > @sizeOf(u64)) return error.InvalidDebugInfo;
413 if (self.signed) return error.InvalidDebugInfo;413 if (self.signed) return error.InvalidDebugInfo;
414 return mem.readInt(self.payload, u64, builtin.Endian.Little);414 return mem.readInt(self.payload, u64, builtin.Endian.Little);
...@@ -425,14 +425,14 @@ const Die = struct {...@@ -425,14 +425,14 @@ const Die = struct {
425 value: FormValue,425 value: FormValue,
426 };426 };
427427
428 fn getAttr(self: &const Die, id: u64) ?&const FormValue {428 fn getAttr(self: *const Die, id: u64) ?*const FormValue {
429 for (self.attrs.toSliceConst()) |*attr| {429 for (self.attrs.toSliceConst()) |*attr| {
430 if (attr.id == id) return &attr.value;430 if (attr.id == id) return &attr.value;
431 }431 }
432 return null;432 return null;
433 }433 }
434434
435 fn getAttrAddr(self: &const Die, id: u64) !u64 {435 fn getAttrAddr(self: *const Die, id: u64) !u64 {
436 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;436 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;
437 return switch (form_value.*) {437 return switch (form_value.*) {
438 FormValue.Address => |value| value,438 FormValue.Address => |value| value,
...@@ -440,7 +440,7 @@ const Die = struct {...@@ -440,7 +440,7 @@ const Die = struct {
440 };440 };
441 }441 }
442442
443 fn getAttrSecOffset(self: &const Die, id: u64) !u64 {443 fn getAttrSecOffset(self: *const Die, id: u64) !u64 {
444 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;444 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;
445 return switch (form_value.*) {445 return switch (form_value.*) {
446 FormValue.Const => |value| value.asUnsignedLe(),446 FormValue.Const => |value| value.asUnsignedLe(),
...@@ -449,7 +449,7 @@ const Die = struct {...@@ -449,7 +449,7 @@ const Die = struct {
449 };449 };
450 }450 }
451451
452 fn getAttrUnsignedLe(self: &const Die, id: u64) !u64 {452 fn getAttrUnsignedLe(self: *const Die, id: u64) !u64 {
453 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;453 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;
454 return switch (form_value.*) {454 return switch (form_value.*) {
455 FormValue.Const => |value| value.asUnsignedLe(),455 FormValue.Const => |value| value.asUnsignedLe(),
...@@ -457,7 +457,7 @@ const Die = struct {...@@ -457,7 +457,7 @@ const Die = struct {
457 };457 };
458 }458 }
459459
460 fn getAttrString(self: &const Die, st: &ElfStackTrace, id: u64) ![]u8 {460 fn getAttrString(self: *const Die, st: *ElfStackTrace, id: u64) ![]u8 {
461 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;461 const form_value = self.getAttr(id) ?? return error.MissingDebugInfo;
462 return switch (form_value.*) {462 return switch (form_value.*) {
463 FormValue.String => |value| value,463 FormValue.String => |value| value,
...@@ -478,9 +478,9 @@ const LineInfo = struct {...@@ -478,9 +478,9 @@ const LineInfo = struct {
478 line: usize,478 line: usize,
479 column: usize,479 column: usize,
480 file_name: []u8,480 file_name: []u8,
481 allocator: &mem.Allocator,481 allocator: *mem.Allocator,
482482
483 fn deinit(self: &const LineInfo) void {483 fn deinit(self: *const LineInfo) void {
484 self.allocator.free(self.file_name);484 self.allocator.free(self.file_name);
485 }485 }
486};486};
...@@ -496,7 +496,7 @@ const LineNumberProgram = struct {...@@ -496,7 +496,7 @@ const LineNumberProgram = struct {
496496
497 target_address: usize,497 target_address: usize,
498 include_dirs: []const []const u8,498 include_dirs: []const []const u8,
499 file_entries: &ArrayList(FileEntry),499 file_entries: *ArrayList(FileEntry),
500500
501 prev_address: usize,501 prev_address: usize,
502 prev_file: usize,502 prev_file: usize,
...@@ -506,7 +506,7 @@ const LineNumberProgram = struct {...@@ -506,7 +506,7 @@ const LineNumberProgram = struct {
506 prev_basic_block: bool,506 prev_basic_block: bool,
507 prev_end_sequence: bool,507 prev_end_sequence: bool,
508508
509 pub fn init(is_stmt: bool, include_dirs: []const []const u8, file_entries: &ArrayList(FileEntry), target_address: usize) LineNumberProgram {509 pub fn init(is_stmt: bool, include_dirs: []const []const u8, file_entries: *ArrayList(FileEntry), target_address: usize) LineNumberProgram {
510 return LineNumberProgram{510 return LineNumberProgram{
511 .address = 0,511 .address = 0,
512 .file = 1,512 .file = 1,
...@@ -528,7 +528,7 @@ const LineNumberProgram = struct {...@@ -528,7 +528,7 @@ const LineNumberProgram = struct {
528 };528 };
529 }529 }
530530
531 pub fn checkLineMatch(self: &LineNumberProgram) !?LineInfo {531 pub fn checkLineMatch(self: *LineNumberProgram) !?LineInfo {
532 if (self.target_address >= self.prev_address and self.target_address < self.address) {532 if (self.target_address >= self.prev_address and self.target_address < self.address) {
533 const file_entry = if (self.prev_file == 0) {533 const file_entry = if (self.prev_file == 0) {
534 return error.MissingDebugInfo;534 return error.MissingDebugInfo;
...@@ -562,7 +562,7 @@ const LineNumberProgram = struct {...@@ -562,7 +562,7 @@ const LineNumberProgram = struct {
562 }562 }
563};563};
564564
565fn readStringRaw(allocator: &mem.Allocator, in_stream: var) ![]u8 {565fn readStringRaw(allocator: *mem.Allocator, in_stream: var) ![]u8 {
566 var buf = ArrayList(u8).init(allocator);566 var buf = ArrayList(u8).init(allocator);
567 while (true) {567 while (true) {
568 const byte = try in_stream.readByte();568 const byte = try in_stream.readByte();
...@@ -572,30 +572,30 @@ fn readStringRaw(allocator: &mem.Allocator, in_stream: var) ![]u8 {...@@ -572,30 +572,30 @@ fn readStringRaw(allocator: &mem.Allocator, in_stream: var) ![]u8 {
572 return buf.toSlice();572 return buf.toSlice();
573}573}
574574
575fn getString(st: &ElfStackTrace, offset: u64) ![]u8 {575fn getString(st: *ElfStackTrace, offset: u64) ![]u8 {
576 const pos = st.debug_str.offset + offset;576 const pos = st.debug_str.offset + offset;
577 try st.self_exe_file.seekTo(pos);577 try st.self_exe_file.seekTo(pos);
578 return st.readString();578 return st.readString();
579}579}
580580
581fn readAllocBytes(allocator: &mem.Allocator, in_stream: var, size: usize) ![]u8 {581fn readAllocBytes(allocator: *mem.Allocator, in_stream: var, size: usize) ![]u8 {
582 const buf = try allocator.alloc(u8, size);582 const buf = try allocator.alloc(u8, size);
583 errdefer allocator.free(buf);583 errdefer allocator.free(buf);
584 if ((try in_stream.read(buf)) < size) return error.EndOfFile;584 if ((try in_stream.read(buf)) < size) return error.EndOfFile;
585 return buf;585 return buf;
586}586}
587587
588fn parseFormValueBlockLen(allocator: &mem.Allocator, in_stream: var, size: usize) !FormValue {588fn parseFormValueBlockLen(allocator: *mem.Allocator, in_stream: var, size: usize) !FormValue {
589 const buf = try readAllocBytes(allocator, in_stream, size);589 const buf = try readAllocBytes(allocator, in_stream, size);
590 return FormValue{ .Block = buf };590 return FormValue{ .Block = buf };
591}591}
592592
593fn parseFormValueBlock(allocator: &mem.Allocator, in_stream: var, size: usize) !FormValue {593fn parseFormValueBlock(allocator: *mem.Allocator, in_stream: var, size: usize) !FormValue {
594 const block_len = try in_stream.readVarInt(builtin.Endian.Little, usize, size);594 const block_len = try in_stream.readVarInt(builtin.Endian.Little, usize, size);
595 return parseFormValueBlockLen(allocator, in_stream, block_len);595 return parseFormValueBlockLen(allocator, in_stream, block_len);
596}596}
597597
598fn parseFormValueConstant(allocator: &mem.Allocator, in_stream: var, signed: bool, size: usize) !FormValue {598fn parseFormValueConstant(allocator: *mem.Allocator, in_stream: var, signed: bool, size: usize) !FormValue {
599 return FormValue{599 return FormValue{
600 .Const = Constant{600 .Const = Constant{
601 .signed = signed,601 .signed = signed,
...@@ -612,12 +612,12 @@ fn parseFormValueTargetAddrSize(in_stream: var) !u64 {...@@ -612,12 +612,12 @@ fn parseFormValueTargetAddrSize(in_stream: var) !u64 {
612 return if (@sizeOf(usize) == 4) u64(try in_stream.readIntLe(u32)) else if (@sizeOf(usize) == 8) try in_stream.readIntLe(u64) else unreachable;612 return if (@sizeOf(usize) == 4) u64(try in_stream.readIntLe(u32)) else if (@sizeOf(usize) == 8) try in_stream.readIntLe(u64) else unreachable;
613}613}
614614
615fn parseFormValueRefLen(allocator: &mem.Allocator, in_stream: var, size: usize) !FormValue {615fn parseFormValueRefLen(allocator: *mem.Allocator, in_stream: var, size: usize) !FormValue {
616 const buf = try readAllocBytes(allocator, in_stream, size);616 const buf = try readAllocBytes(allocator, in_stream, size);
617 return FormValue{ .Ref = buf };617 return FormValue{ .Ref = buf };
618}618}
619619
620fn parseFormValueRef(allocator: &mem.Allocator, in_stream: var, comptime T: type) !FormValue {620fn parseFormValueRef(allocator: *mem.Allocator, in_stream: var, comptime T: type) !FormValue {
621 const block_len = try in_stream.readIntLe(T);621 const block_len = try in_stream.readIntLe(T);
622 return parseFormValueRefLen(allocator, in_stream, block_len);622 return parseFormValueRefLen(allocator, in_stream, block_len);
623}623}
...@@ -632,7 +632,7 @@ const ParseFormValueError = error{...@@ -632,7 +632,7 @@ const ParseFormValueError = error{
632 OutOfMemory,632 OutOfMemory,
633};633};
634634
635fn parseFormValue(allocator: &mem.Allocator, in_stream: var, form_id: u64, is_64: bool) ParseFormValueError!FormValue {635fn parseFormValue(allocator: *mem.Allocator, in_stream: var, form_id: u64, is_64: bool) ParseFormValueError!FormValue {
636 return switch (form_id) {636 return switch (form_id) {
637 DW.FORM_addr => FormValue{ .Address = try parseFormValueTargetAddrSize(in_stream) },637 DW.FORM_addr => FormValue{ .Address = try parseFormValueTargetAddrSize(in_stream) },
638 DW.FORM_block1 => parseFormValueBlock(allocator, in_stream, 1),638 DW.FORM_block1 => parseFormValueBlock(allocator, in_stream, 1),
...@@ -682,7 +682,7 @@ fn parseFormValue(allocator: &mem.Allocator, in_stream: var, form_id: u64, is_64...@@ -682,7 +682,7 @@ fn parseFormValue(allocator: &mem.Allocator, in_stream: var, form_id: u64, is_64
682 };682 };
683}683}
684684
685fn parseAbbrevTable(st: &ElfStackTrace) !AbbrevTable {685fn parseAbbrevTable(st: *ElfStackTrace) !AbbrevTable {
686 const in_file = &st.self_exe_file;686 const in_file = &st.self_exe_file;
687 var in_file_stream = io.FileInStream.init(in_file);687 var in_file_stream = io.FileInStream.init(in_file);
688 const in_stream = &in_file_stream.stream;688 const in_stream = &in_file_stream.stream;
...@@ -712,7 +712,7 @@ fn parseAbbrevTable(st: &ElfStackTrace) !AbbrevTable {...@@ -712,7 +712,7 @@ fn parseAbbrevTable(st: &ElfStackTrace) !AbbrevTable {
712712
713/// Gets an already existing AbbrevTable given the abbrev_offset, or if not found,713/// Gets an already existing AbbrevTable given the abbrev_offset, or if not found,
714/// seeks in the stream and parses it.714/// seeks in the stream and parses it.
715fn getAbbrevTable(st: &ElfStackTrace, abbrev_offset: u64) !&const AbbrevTable {715fn getAbbrevTable(st: *ElfStackTrace, abbrev_offset: u64) !*const AbbrevTable {
716 for (st.abbrev_table_list.toSlice()) |*header| {716 for (st.abbrev_table_list.toSlice()) |*header| {
717 if (header.offset == abbrev_offset) {717 if (header.offset == abbrev_offset) {
718 return &header.table;718 return &header.table;
...@@ -726,14 +726,14 @@ fn getAbbrevTable(st: &ElfStackTrace, abbrev_offset: u64) !&const AbbrevTable {...@@ -726,14 +726,14 @@ fn getAbbrevTable(st: &ElfStackTrace, abbrev_offset: u64) !&const AbbrevTable {
726 return &st.abbrev_table_list.items[st.abbrev_table_list.len - 1].table;726 return &st.abbrev_table_list.items[st.abbrev_table_list.len - 1].table;
727}727}
728728
729fn getAbbrevTableEntry(abbrev_table: &const AbbrevTable, abbrev_code: u64) ?&const AbbrevTableEntry {729fn getAbbrevTableEntry(abbrev_table: *const AbbrevTable, abbrev_code: u64) ?*const AbbrevTableEntry {
730 for (abbrev_table.toSliceConst()) |*table_entry| {730 for (abbrev_table.toSliceConst()) |*table_entry| {
731 if (table_entry.abbrev_code == abbrev_code) return table_entry;731 if (table_entry.abbrev_code == abbrev_code) return table_entry;
732 }732 }
733 return null;733 return null;
734}734}
735735
736fn parseDie(st: &ElfStackTrace, abbrev_table: &const AbbrevTable, is_64: bool) !Die {736fn parseDie(st: *ElfStackTrace, abbrev_table: *const AbbrevTable, is_64: bool) !Die {
737 const in_file = &st.self_exe_file;737 const in_file = &st.self_exe_file;
738 var in_file_stream = io.FileInStream.init(in_file);738 var in_file_stream = io.FileInStream.init(in_file);
739 const in_stream = &in_file_stream.stream;739 const in_stream = &in_file_stream.stream;
...@@ -755,7 +755,7 @@ fn parseDie(st: &ElfStackTrace, abbrev_table: &const AbbrevTable, is_64: bool) !...@@ -755,7 +755,7 @@ fn parseDie(st: &ElfStackTrace, abbrev_table: &const AbbrevTable, is_64: bool) !
755 return result;755 return result;
756}756}
757757
758fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, target_address: usize) !LineInfo {758fn getLineNumberInfo(st: *ElfStackTrace, compile_unit: *const CompileUnit, target_address: usize) !LineInfo {
759 const compile_unit_cwd = try compile_unit.die.getAttrString(st, DW.AT_comp_dir);759 const compile_unit_cwd = try compile_unit.die.getAttrString(st, DW.AT_comp_dir);
760760
761 const in_file = &st.self_exe_file;761 const in_file = &st.self_exe_file;
...@@ -934,7 +934,7 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe...@@ -934,7 +934,7 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe
934 return error.MissingDebugInfo;934 return error.MissingDebugInfo;
935}935}
936936
937fn scanAllCompileUnits(st: &ElfStackTrace) !void {937fn scanAllCompileUnits(st: *ElfStackTrace) !void {
938 const debug_info_end = st.debug_info.offset + st.debug_info.size;938 const debug_info_end = st.debug_info.offset + st.debug_info.size;
939 var this_unit_offset = st.debug_info.offset;939 var this_unit_offset = st.debug_info.offset;
940 var cu_index: usize = 0;940 var cu_index: usize = 0;
...@@ -1005,7 +1005,7 @@ fn scanAllCompileUnits(st: &ElfStackTrace) !void {...@@ -1005,7 +1005,7 @@ fn scanAllCompileUnits(st: &ElfStackTrace) !void {
1005 }1005 }
1006}1006}
10071007
1008fn findCompileUnit(st: &ElfStackTrace, target_address: u64) !&const CompileUnit {1008fn findCompileUnit(st: *ElfStackTrace, target_address: u64) !*const CompileUnit {
1009 var in_file_stream = io.FileInStream.init(&st.self_exe_file);1009 var in_file_stream = io.FileInStream.init(&st.self_exe_file);
1010 const in_stream = &in_file_stream.stream;1010 const in_stream = &in_file_stream.stream;
1011 for (st.compile_unit_list.toSlice()) |*compile_unit| {1011 for (st.compile_unit_list.toSlice()) |*compile_unit| {
...@@ -1039,7 +1039,7 @@ fn findCompileUnit(st: &ElfStackTrace, target_address: u64) !&const CompileUnit...@@ -1039,7 +1039,7 @@ fn findCompileUnit(st: &ElfStackTrace, target_address: u64) !&const CompileUnit
1039 return error.MissingDebugInfo;1039 return error.MissingDebugInfo;
1040}1040}
10411041
1042fn readInitialLength(comptime E: type, in_stream: &io.InStream(E), is_64: &bool) !u64 {1042fn readInitialLength(comptime E: type, in_stream: *io.InStream(E), is_64: *bool) !u64 {
1043 const first_32_bits = try in_stream.readIntLe(u32);1043 const first_32_bits = try in_stream.readIntLe(u32);
1044 is_64.* = (first_32_bits == 0xffffffff);1044 is_64.* = (first_32_bits == 0xffffffff);
1045 if (is_64.*) {1045 if (is_64.*) {
...@@ -1096,10 +1096,10 @@ var global_fixed_allocator = std.heap.FixedBufferAllocator.init(global_allocator...@@ -1096,10 +1096,10 @@ var global_fixed_allocator = std.heap.FixedBufferAllocator.init(global_allocator
1096var global_allocator_mem: [100 * 1024]u8 = undefined;1096var global_allocator_mem: [100 * 1024]u8 = undefined;
10971097
1098// TODO make thread safe1098// TODO make thread safe
1099var debug_info_allocator: ?&mem.Allocator = null;1099var debug_info_allocator: ?*mem.Allocator = null;
1100var debug_info_direct_allocator: std.heap.DirectAllocator = undefined;1100var debug_info_direct_allocator: std.heap.DirectAllocator = undefined;
1101var debug_info_arena_allocator: std.heap.ArenaAllocator = undefined;1101var debug_info_arena_allocator: std.heap.ArenaAllocator = undefined;
1102fn getDebugInfoAllocator() &mem.Allocator {1102fn getDebugInfoAllocator() *mem.Allocator {
1103 if (debug_info_allocator) |a| return a;1103 if (debug_info_allocator) |a| return a;
11041104
1105 debug_info_direct_allocator = std.heap.DirectAllocator.init();1105 debug_info_direct_allocator = std.heap.DirectAllocator.init();
std/elf.zig+9-9
...@@ -338,7 +338,7 @@ pub const SectionHeader = struct {...@@ -338,7 +338,7 @@ pub const SectionHeader = struct {
338};338};
339339
340pub const Elf = struct {340pub const Elf = struct {
341 in_file: &os.File,341 in_file: *os.File,
342 auto_close_stream: bool,342 auto_close_stream: bool,
343 is_64: bool,343 is_64: bool,
344 endian: builtin.Endian,344 endian: builtin.Endian,
...@@ -348,20 +348,20 @@ pub const Elf = struct {...@@ -348,20 +348,20 @@ pub const Elf = struct {
348 program_header_offset: u64,348 program_header_offset: u64,
349 section_header_offset: u64,349 section_header_offset: u64,
350 string_section_index: u64,350 string_section_index: u64,
351 string_section: &SectionHeader,351 string_section: *SectionHeader,
352 section_headers: []SectionHeader,352 section_headers: []SectionHeader,
353 allocator: &mem.Allocator,353 allocator: *mem.Allocator,
354 prealloc_file: os.File,354 prealloc_file: os.File,
355355
356 /// Call close when done.356 /// Call close when done.
357 pub fn openPath(elf: &Elf, allocator: &mem.Allocator, path: []const u8) !void {357 pub fn openPath(elf: *Elf, allocator: *mem.Allocator, path: []const u8) !void {
358 try elf.prealloc_file.open(path);358 try elf.prealloc_file.open(path);
359 try elf.openFile(allocator, &elf.prealloc_file);359 try elf.openFile(allocator, *elf.prealloc_file);
360 elf.auto_close_stream = true;360 elf.auto_close_stream = true;
361 }361 }
362362
363 /// Call close when done.363 /// Call close when done.
364 pub fn openFile(elf: &Elf, allocator: &mem.Allocator, file: &os.File) !void {364 pub fn openFile(elf: *Elf, allocator: *mem.Allocator, file: *os.File) !void {
365 elf.allocator = allocator;365 elf.allocator = allocator;
366 elf.in_file = file;366 elf.in_file = file;
367 elf.auto_close_stream = false;367 elf.auto_close_stream = false;
...@@ -503,13 +503,13 @@ pub const Elf = struct {...@@ -503,13 +503,13 @@ pub const Elf = struct {
503 }503 }
504 }504 }
505505
506 pub fn close(elf: &Elf) void {506 pub fn close(elf: *Elf) void {
507 elf.allocator.free(elf.section_headers);507 elf.allocator.free(elf.section_headers);
508508
509 if (elf.auto_close_stream) elf.in_file.close();509 if (elf.auto_close_stream) elf.in_file.close();
510 }510 }
511511
512 pub fn findSection(elf: &Elf, name: []const u8) !?&SectionHeader {512 pub fn findSection(elf: *Elf, name: []const u8) !?*SectionHeader {
513 var file_stream = io.FileInStream.init(elf.in_file);513 var file_stream = io.FileInStream.init(elf.in_file);
514 const in = &file_stream.stream;514 const in = &file_stream.stream;
515515
...@@ -533,7 +533,7 @@ pub const Elf = struct {...@@ -533,7 +533,7 @@ pub const Elf = struct {
533 return null;533 return null;
534 }534 }
535535
536 pub fn seekToSection(elf: &Elf, elf_section: &SectionHeader) !void {536 pub fn seekToSection(elf: *Elf, elf_section: *SectionHeader) !void {
537 try elf.in_file.seekTo(elf_section.offset);537 try elf.in_file.seekTo(elf_section.offset);
538 }538 }
539};539};
std/event.zig+17-17
...@@ -6,9 +6,9 @@ const mem = std.mem;...@@ -6,9 +6,9 @@ const mem = std.mem;
6const posix = std.os.posix;6const posix = std.os.posix;
77
8pub const TcpServer = struct {8pub const TcpServer = struct {
9 handleRequestFn: async<&mem.Allocator> fn(&TcpServer, &const std.net.Address, &const std.os.File) void,9 handleRequestFn: async<*mem.Allocator> fn (*TcpServer, *const std.net.Address, *const std.os.File) void,
1010
11 loop: &Loop,11 loop: *Loop,
12 sockfd: i32,12 sockfd: i32,
13 accept_coro: ?promise,13 accept_coro: ?promise,
14 listen_address: std.net.Address,14 listen_address: std.net.Address,
...@@ -17,7 +17,7 @@ pub const TcpServer = struct {...@@ -17,7 +17,7 @@ pub const TcpServer = struct {
1717
18 const PromiseNode = std.LinkedList(promise).Node;18 const PromiseNode = std.LinkedList(promise).Node;
1919
20 pub fn init(loop: &Loop) !TcpServer {20 pub fn init(loop: *Loop) !TcpServer {
21 const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp);21 const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp);
22 errdefer std.os.close(sockfd);22 errdefer std.os.close(sockfd);
2323
...@@ -32,7 +32,7 @@ pub const TcpServer = struct {...@@ -32,7 +32,7 @@ pub const TcpServer = struct {
32 };32 };
33 }33 }
3434
35 pub fn listen(self: &TcpServer, address: &const std.net.Address, handleRequestFn: async<&mem.Allocator> fn(&TcpServer, &const std.net.Address, &const std.os.File) void) !void {35 pub fn listen(self: *TcpServer, address: *const std.net.Address, handleRequestFn: async<*mem.Allocator> fn (*TcpServer, *const std.net.Address, *const std.os.File) void) !void {
36 self.handleRequestFn = handleRequestFn;36 self.handleRequestFn = handleRequestFn;
3737
38 try std.os.posixBind(self.sockfd, &address.os_addr);38 try std.os.posixBind(self.sockfd, &address.os_addr);
...@@ -46,13 +46,13 @@ pub const TcpServer = struct {...@@ -46,13 +46,13 @@ pub const TcpServer = struct {
46 errdefer self.loop.removeFd(self.sockfd);46 errdefer self.loop.removeFd(self.sockfd);
47 }47 }
4848
49 pub fn deinit(self: &TcpServer) void {49 pub fn deinit(self: *TcpServer) void {
50 self.loop.removeFd(self.sockfd);50 self.loop.removeFd(self.sockfd);
51 if (self.accept_coro) |accept_coro| cancel accept_coro;51 if (self.accept_coro) |accept_coro| cancel accept_coro;
52 std.os.close(self.sockfd);52 std.os.close(self.sockfd);
53 }53 }
5454
55 pub async fn handler(self: &TcpServer) void {55 pub async fn handler(self: *TcpServer) void {
56 while (true) {56 while (true) {
57 var accepted_addr: std.net.Address = undefined;57 var accepted_addr: std.net.Address = undefined;
58 if (std.os.posixAccept(self.sockfd, &accepted_addr.os_addr, posix.SOCK_NONBLOCK | posix.SOCK_CLOEXEC)) |accepted_fd| {58 if (std.os.posixAccept(self.sockfd, &accepted_addr.os_addr, posix.SOCK_NONBLOCK | posix.SOCK_CLOEXEC)) |accepted_fd| {
...@@ -92,11 +92,11 @@ pub const TcpServer = struct {...@@ -92,11 +92,11 @@ pub const TcpServer = struct {
92};92};
9393
94pub const Loop = struct {94pub const Loop = struct {
95 allocator: &mem.Allocator,95 allocator: *mem.Allocator,
96 epollfd: i32,96 epollfd: i32,
97 keep_running: bool,97 keep_running: bool,
9898
99 fn init(allocator: &mem.Allocator) !Loop {99 fn init(allocator: *mem.Allocator) !Loop {
100 const epollfd = try std.os.linuxEpollCreate(std.os.linux.EPOLL_CLOEXEC);100 const epollfd = try std.os.linuxEpollCreate(std.os.linux.EPOLL_CLOEXEC);
101 return Loop{101 return Loop{
102 .keep_running = true,102 .keep_running = true,
...@@ -105,7 +105,7 @@ pub const Loop = struct {...@@ -105,7 +105,7 @@ pub const Loop = struct {
105 };105 };
106 }106 }
107107
108 pub fn addFd(self: &Loop, fd: i32, prom: promise) !void {108 pub fn addFd(self: *Loop, fd: i32, prom: promise) !void {
109 var ev = std.os.linux.epoll_event{109 var ev = std.os.linux.epoll_event{
110 .events = std.os.linux.EPOLLIN | std.os.linux.EPOLLOUT | std.os.linux.EPOLLET,110 .events = std.os.linux.EPOLLIN | std.os.linux.EPOLLOUT | std.os.linux.EPOLLET,
111 .data = std.os.linux.epoll_data{ .ptr = @ptrToInt(prom) },111 .data = std.os.linux.epoll_data{ .ptr = @ptrToInt(prom) },
...@@ -113,23 +113,23 @@ pub const Loop = struct {...@@ -113,23 +113,23 @@ pub const Loop = struct {
113 try std.os.linuxEpollCtl(self.epollfd, std.os.linux.EPOLL_CTL_ADD, fd, &ev);113 try std.os.linuxEpollCtl(self.epollfd, std.os.linux.EPOLL_CTL_ADD, fd, &ev);
114 }114 }
115115
116 pub fn removeFd(self: &Loop, fd: i32) void {116 pub fn removeFd(self: *Loop, fd: i32) void {
117 std.os.linuxEpollCtl(self.epollfd, std.os.linux.EPOLL_CTL_DEL, fd, undefined) catch {};117 std.os.linuxEpollCtl(self.epollfd, std.os.linux.EPOLL_CTL_DEL, fd, undefined) catch {};
118 }118 }
119 async fn waitFd(self: &Loop, fd: i32) !void {119 async fn waitFd(self: *Loop, fd: i32) !void {
120 defer self.removeFd(fd);120 defer self.removeFd(fd);
121 suspend |p| {121 suspend |p| {
122 try self.addFd(fd, p);122 try self.addFd(fd, p);
123 }123 }
124 }124 }
125125
126 pub fn stop(self: &Loop) void {126 pub fn stop(self: *Loop) void {
127 // TODO make atomic127 // TODO make atomic
128 self.keep_running = false;128 self.keep_running = false;
129 // TODO activate an fd in the epoll set129 // TODO activate an fd in the epoll set
130 }130 }
131131
132 pub fn run(self: &Loop) void {132 pub fn run(self: *Loop) void {
133 while (self.keep_running) {133 while (self.keep_running) {
134 var events: [16]std.os.linux.epoll_event = undefined;134 var events: [16]std.os.linux.epoll_event = undefined;
135 const count = std.os.linuxEpollWait(self.epollfd, events[0..], -1);135 const count = std.os.linuxEpollWait(self.epollfd, events[0..], -1);
...@@ -141,7 +141,7 @@ pub const Loop = struct {...@@ -141,7 +141,7 @@ pub const Loop = struct {
141 }141 }
142};142};
143143
144pub async fn connect(loop: &Loop, _address: &const std.net.Address) !std.os.File {144pub async fn connect(loop: *Loop, _address: *const std.net.Address) !std.os.File {
145 var address = _address.*; // TODO https://github.com/ziglang/zig/issues/733145 var address = _address.*; // TODO https://github.com/ziglang/zig/issues/733
146146
147 const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp);147 const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp);
...@@ -163,7 +163,7 @@ test "listen on a port, send bytes, receive bytes" {...@@ -163,7 +163,7 @@ test "listen on a port, send bytes, receive bytes" {
163 tcp_server: TcpServer,163 tcp_server: TcpServer,
164164
165 const Self = this;165 const Self = this;
166 async<&mem.Allocator> fn handler(tcp_server: &TcpServer, _addr: &const std.net.Address, _socket: &const std.os.File) void {166 async<*mem.Allocator> fn handler(tcp_server: *TcpServer, _addr: *const std.net.Address, _socket: *const std.os.File) void {
167 const self = @fieldParentPtr(Self, "tcp_server", tcp_server);167 const self = @fieldParentPtr(Self, "tcp_server", tcp_server);
168 var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733168 var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733
169 defer socket.close();169 defer socket.close();
...@@ -177,7 +177,7 @@ test "listen on a port, send bytes, receive bytes" {...@@ -177,7 +177,7 @@ test "listen on a port, send bytes, receive bytes" {
177 cancel p;177 cancel p;
178 }178 }
179 }179 }
180 async fn errorableHandler(self: &Self, _addr: &const std.net.Address, _socket: &const std.os.File) !void {180 async fn errorableHandler(self: *Self, _addr: *const std.net.Address, _socket: *const std.os.File) !void {
181 const addr = _addr.*; // TODO https://github.com/ziglang/zig/issues/733181 const addr = _addr.*; // TODO https://github.com/ziglang/zig/issues/733
182 var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733182 var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733
183183
...@@ -199,7 +199,7 @@ test "listen on a port, send bytes, receive bytes" {...@@ -199,7 +199,7 @@ test "listen on a port, send bytes, receive bytes" {
199 defer cancel p;199 defer cancel p;
200 loop.run();200 loop.run();
201}201}
202async fn doAsyncTest(loop: &Loop, address: &const std.net.Address) void {202async fn doAsyncTest(loop: *Loop, address: *const std.net.Address) void {
203 errdefer @panic("test failure");203 errdefer @panic("test failure");
204204
205 var socket_file = try await try async event.connect(loop, address);205 var socket_file = try await try async event.connect(loop, address);
std/fmt/errol/index.zig+10-11
...@@ -21,7 +21,7 @@ pub const RoundMode = enum {...@@ -21,7 +21,7 @@ pub const RoundMode = enum {
2121
22/// Round a FloatDecimal as returned by errol3 to the specified fractional precision.22/// Round a FloatDecimal as returned by errol3 to the specified fractional precision.
23/// All digits after the specified precision should be considered invalid.23/// All digits after the specified precision should be considered invalid.
24pub fn roundToPrecision(float_decimal: &FloatDecimal, precision: usize, mode: RoundMode) void {24pub fn roundToPrecision(float_decimal: *FloatDecimal, precision: usize, mode: RoundMode) void {
25 // The round digit refers to the index which we should look at to determine25 // The round digit refers to the index which we should look at to determine
26 // whether we need to round to match the specified precision.26 // whether we need to round to match the specified precision.
27 var round_digit: usize = 0;27 var round_digit: usize = 0;
...@@ -59,8 +59,8 @@ pub fn roundToPrecision(float_decimal: &FloatDecimal, precision: usize, mode: Ro...@@ -59,8 +59,8 @@ pub fn roundToPrecision(float_decimal: &FloatDecimal, precision: usize, mode: Ro
59 float_decimal.exp += 1;59 float_decimal.exp += 1;
6060
61 // Re-size the buffer to use the reserved leading byte.61 // Re-size the buffer to use the reserved leading byte.
62 const one_before = @intToPtr(&u8, @ptrToInt(&float_decimal.digits[0]) - 1);62 const one_before = @intToPtr(*u8, @ptrToInt(&float_decimal.digits[0]) - 1);
63 float_decimal.digits = one_before[0..float_decimal.digits.len + 1];63 float_decimal.digits = one_before[0 .. float_decimal.digits.len + 1];
64 float_decimal.digits[0] = '1';64 float_decimal.digits[0] = '1';
65 return;65 return;
66 }66 }
...@@ -84,7 +84,7 @@ pub fn errol3(value: f64, buffer: []u8) FloatDecimal {...@@ -84,7 +84,7 @@ pub fn errol3(value: f64, buffer: []u8) FloatDecimal {
84 const i = tableLowerBound(bits);84 const i = tableLowerBound(bits);
85 if (i < enum3.len and enum3[i] == bits) {85 if (i < enum3.len and enum3[i] == bits) {
86 const data = enum3_data[i];86 const data = enum3_data[i];
87 const digits = buffer[1..data.str.len + 1];87 const digits = buffer[1 .. data.str.len + 1];
88 mem.copy(u8, digits, data.str);88 mem.copy(u8, digits, data.str);
89 return FloatDecimal{89 return FloatDecimal{
90 .digits = digits,90 .digits = digits,
...@@ -98,7 +98,6 @@ pub fn errol3(value: f64, buffer: []u8) FloatDecimal {...@@ -98,7 +98,6 @@ pub fn errol3(value: f64, buffer: []u8) FloatDecimal {
98/// Uncorrected Errol3 double to ASCII conversion.98/// Uncorrected Errol3 double to ASCII conversion.
99fn errol3u(val: f64, buffer: []u8) FloatDecimal {99fn errol3u(val: f64, buffer: []u8) FloatDecimal {
100 // check if in integer or fixed range100 // check if in integer or fixed range
101
102 if (val > 9.007199254740992e15 and val < 3.40282366920938e+38) {101 if (val > 9.007199254740992e15 and val < 3.40282366920938e+38) {
103 return errolInt(val, buffer);102 return errolInt(val, buffer);
104 } else if (val >= 16.0 and val < 9.007199254740992e15) {103 } else if (val >= 16.0 and val < 9.007199254740992e15) {
...@@ -218,7 +217,7 @@ fn tableLowerBound(k: u64) usize {...@@ -218,7 +217,7 @@ fn tableLowerBound(k: u64) usize {
218/// @in: The HP number.217/// @in: The HP number.
219/// @val: The double.218/// @val: The double.
220/// &returns: The HP number.219/// &returns: The HP number.
221fn hpProd(in: &const HP, val: f64) HP {220fn hpProd(in: *const HP, val: f64) HP {
222 var hi: f64 = undefined;221 var hi: f64 = undefined;
223 var lo: f64 = undefined;222 var lo: f64 = undefined;
224 split(in.val, &hi, &lo);223 split(in.val, &hi, &lo);
...@@ -240,7 +239,7 @@ fn hpProd(in: &const HP, val: f64) HP {...@@ -240,7 +239,7 @@ fn hpProd(in: &const HP, val: f64) HP {
240/// @val: The double.239/// @val: The double.
241/// @hi: The high bits.240/// @hi: The high bits.
242/// @lo: The low bits.241/// @lo: The low bits.
243fn split(val: f64, hi: &f64, lo: &f64) void {242fn split(val: f64, hi: *f64, lo: *f64) void {
244 hi.* = gethi(val);243 hi.* = gethi(val);
245 lo.* = val - hi.*;244 lo.* = val - hi.*;
246}245}
...@@ -253,7 +252,7 @@ fn gethi(in: f64) f64 {...@@ -253,7 +252,7 @@ fn gethi(in: f64) f64 {
253252
254/// Normalize the number by factoring in the error.253/// Normalize the number by factoring in the error.
255/// @hp: The float pair.254/// @hp: The float pair.
256fn hpNormalize(hp: &HP) void {255fn hpNormalize(hp: *HP) void {
257 // Required to avoid segfaults causing buffer overrun during errol3 digit output termination.256 // Required to avoid segfaults causing buffer overrun during errol3 digit output termination.
258 @setFloatMode(this, @import("builtin").FloatMode.Strict);257 @setFloatMode(this, @import("builtin").FloatMode.Strict);
259258
...@@ -265,7 +264,7 @@ fn hpNormalize(hp: &HP) void {...@@ -265,7 +264,7 @@ fn hpNormalize(hp: &HP) void {
265264
266/// Divide the high-precision number by ten.265/// Divide the high-precision number by ten.
267/// @hp: The high-precision number266/// @hp: The high-precision number
268fn hpDiv10(hp: &HP) void {267fn hpDiv10(hp: *HP) void {
269 var val = hp.val;268 var val = hp.val;
270269
271 hp.val /= 10.0;270 hp.val /= 10.0;
...@@ -281,7 +280,7 @@ fn hpDiv10(hp: &HP) void {...@@ -281,7 +280,7 @@ fn hpDiv10(hp: &HP) void {
281280
282/// Multiply the high-precision number by ten.281/// Multiply the high-precision number by ten.
283/// @hp: The high-precision number282/// @hp: The high-precision number
284fn hpMul10(hp: &HP) void {283fn hpMul10(hp: *HP) void {
285 const val = hp.val;284 const val = hp.val;
286285
287 hp.val *= 10.0;286 hp.val *= 10.0;
...@@ -420,7 +419,7 @@ fn fpprev(val: f64) f64 {...@@ -420,7 +419,7 @@ fn fpprev(val: f64) f64 {
420 return @bitCast(f64, @bitCast(u64, val) -% 1);419 return @bitCast(f64, @bitCast(u64, val) -% 1);
421}420}
422421
423pub const c_digits_lut = []u8 {422pub const c_digits_lut = []u8{
424 '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6',423 '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6',
425 '0', '7', '0', '8', '0', '9', '1', '0', '1', '1', '1', '2', '1', '3',424 '0', '7', '0', '8', '0', '9', '1', '0', '1', '1', '1', '2', '1', '3',
426 '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '2', '0',425 '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '2', '0',
std/fmt/errol/lookup.zig+600-600
...@@ -3,604 +3,604 @@ pub const HP = struct {...@@ -3,604 +3,604 @@ pub const HP = struct {
3 off: f64,3 off: f64,
4};4};
5pub const lookup_table = []HP{5pub const lookup_table = []HP{
6 HP{.val=1.000000e+308, .off= -1.097906362944045488e+291 },6 HP{ .val = 1.000000e+308, .off = -1.097906362944045488e+291 },
7 HP{.val=1.000000e+307, .off= 1.396894023974354241e+290 },7 HP{ .val = 1.000000e+307, .off = 1.396894023974354241e+290 },
8 HP{.val=1.000000e+306, .off= -1.721606459673645508e+289 },8 HP{ .val = 1.000000e+306, .off = -1.721606459673645508e+289 },
9 HP{.val=1.000000e+305, .off= 6.074644749446353973e+288 },9 HP{ .val = 1.000000e+305, .off = 6.074644749446353973e+288 },
10 HP{.val=1.000000e+304, .off= 6.074644749446353567e+287 },10 HP{ .val = 1.000000e+304, .off = 6.074644749446353567e+287 },
11 HP{.val=1.000000e+303, .off= -1.617650767864564452e+284 },11 HP{ .val = 1.000000e+303, .off = -1.617650767864564452e+284 },
12 HP{.val=1.000000e+302, .off= -7.629703079084895055e+285 },12 HP{ .val = 1.000000e+302, .off = -7.629703079084895055e+285 },
13 HP{.val=1.000000e+301, .off= -5.250476025520442286e+284 },13 HP{ .val = 1.000000e+301, .off = -5.250476025520442286e+284 },
14 HP{.val=1.000000e+300, .off= -5.250476025520441956e+283 },14 HP{ .val = 1.000000e+300, .off = -5.250476025520441956e+283 },
15 HP{.val=1.000000e+299, .off= -5.250476025520441750e+282 },15 HP{ .val = 1.000000e+299, .off = -5.250476025520441750e+282 },
16 HP{.val=1.000000e+298, .off= 4.043379652465702264e+281 },16 HP{ .val = 1.000000e+298, .off = 4.043379652465702264e+281 },
17 HP{.val=1.000000e+297, .off= -1.765280146275637946e+280 },17 HP{ .val = 1.000000e+297, .off = -1.765280146275637946e+280 },
18 HP{.val=1.000000e+296, .off= 1.865132227937699609e+279 },18 HP{ .val = 1.000000e+296, .off = 1.865132227937699609e+279 },
19 HP{.val=1.000000e+295, .off= 1.865132227937699609e+278 },19 HP{ .val = 1.000000e+295, .off = 1.865132227937699609e+278 },
20 HP{.val=1.000000e+294, .off= -6.643646774124810287e+277 },20 HP{ .val = 1.000000e+294, .off = -6.643646774124810287e+277 },
21 HP{.val=1.000000e+293, .off= 7.537651562646039934e+276 },21 HP{ .val = 1.000000e+293, .off = 7.537651562646039934e+276 },
22 HP{.val=1.000000e+292, .off= -1.325659897835741608e+275 },22 HP{ .val = 1.000000e+292, .off = -1.325659897835741608e+275 },
23 HP{.val=1.000000e+291, .off= 4.213909764965371606e+274 },23 HP{ .val = 1.000000e+291, .off = 4.213909764965371606e+274 },
24 HP{.val=1.000000e+290, .off= -6.172783352786715670e+273 },24 HP{ .val = 1.000000e+290, .off = -6.172783352786715670e+273 },
25 HP{.val=1.000000e+289, .off= -6.172783352786715670e+272 },25 HP{ .val = 1.000000e+289, .off = -6.172783352786715670e+272 },
26 HP{.val=1.000000e+288, .off= -7.630473539575035471e+270 },26 HP{ .val = 1.000000e+288, .off = -7.630473539575035471e+270 },
27 HP{.val=1.000000e+287, .off= -7.525217352494018700e+270 },27 HP{ .val = 1.000000e+287, .off = -7.525217352494018700e+270 },
28 HP{.val=1.000000e+286, .off= -3.298861103408696612e+269 },28 HP{ .val = 1.000000e+286, .off = -3.298861103408696612e+269 },
29 HP{.val=1.000000e+285, .off= 1.984084207947955778e+268 },29 HP{ .val = 1.000000e+285, .off = 1.984084207947955778e+268 },
30 HP{.val=1.000000e+284, .off= -7.921438250845767591e+267 },30 HP{ .val = 1.000000e+284, .off = -7.921438250845767591e+267 },
31 HP{.val=1.000000e+283, .off= 4.460464822646386735e+266 },31 HP{ .val = 1.000000e+283, .off = 4.460464822646386735e+266 },
32 HP{.val=1.000000e+282, .off= -3.278224598286209647e+265 },32 HP{ .val = 1.000000e+282, .off = -3.278224598286209647e+265 },
33 HP{.val=1.000000e+281, .off= -3.278224598286209737e+264 },33 HP{ .val = 1.000000e+281, .off = -3.278224598286209737e+264 },
34 HP{.val=1.000000e+280, .off= -3.278224598286209961e+263 },34 HP{ .val = 1.000000e+280, .off = -3.278224598286209961e+263 },
35 HP{.val=1.000000e+279, .off= -5.797329227496039232e+262 },35 HP{ .val = 1.000000e+279, .off = -5.797329227496039232e+262 },
36 HP{.val=1.000000e+278, .off= 3.649313132040821498e+261 },36 HP{ .val = 1.000000e+278, .off = 3.649313132040821498e+261 },
37 HP{.val=1.000000e+277, .off= -2.867878510995372374e+259 },37 HP{ .val = 1.000000e+277, .off = -2.867878510995372374e+259 },
38 HP{.val=1.000000e+276, .off= -5.206914080024985409e+259 },38 HP{ .val = 1.000000e+276, .off = -5.206914080024985409e+259 },
39 HP{.val=1.000000e+275, .off= 4.018322599210230404e+258 },39 HP{ .val = 1.000000e+275, .off = 4.018322599210230404e+258 },
40 HP{.val=1.000000e+274, .off= 7.862171215558236495e+257 },40 HP{ .val = 1.000000e+274, .off = 7.862171215558236495e+257 },
41 HP{.val=1.000000e+273, .off= 5.459765830340732821e+256 },41 HP{ .val = 1.000000e+273, .off = 5.459765830340732821e+256 },
42 HP{.val=1.000000e+272, .off= -6.552261095746788047e+255 },42 HP{ .val = 1.000000e+272, .off = -6.552261095746788047e+255 },
43 HP{.val=1.000000e+271, .off= 4.709014147460262298e+254 },43 HP{ .val = 1.000000e+271, .off = 4.709014147460262298e+254 },
44 HP{.val=1.000000e+270, .off= -4.675381888545612729e+253 },44 HP{ .val = 1.000000e+270, .off = -4.675381888545612729e+253 },
45 HP{.val=1.000000e+269, .off= -4.675381888545612892e+252 },45 HP{ .val = 1.000000e+269, .off = -4.675381888545612892e+252 },
46 HP{.val=1.000000e+268, .off= 2.656177514583977380e+251 },46 HP{ .val = 1.000000e+268, .off = 2.656177514583977380e+251 },
47 HP{.val=1.000000e+267, .off= 2.656177514583977190e+250 },47 HP{ .val = 1.000000e+267, .off = 2.656177514583977190e+250 },
48 HP{.val=1.000000e+266, .off= -3.071603269111014892e+249 },48 HP{ .val = 1.000000e+266, .off = -3.071603269111014892e+249 },
49 HP{.val=1.000000e+265, .off= -6.651466258920385440e+248 },49 HP{ .val = 1.000000e+265, .off = -6.651466258920385440e+248 },
50 HP{.val=1.000000e+264, .off= -4.414051890289528972e+247 },50 HP{ .val = 1.000000e+264, .off = -4.414051890289528972e+247 },
51 HP{.val=1.000000e+263, .off= -1.617283929500958387e+246 },51 HP{ .val = 1.000000e+263, .off = -1.617283929500958387e+246 },
52 HP{.val=1.000000e+262, .off= -1.617283929500958241e+245 },52 HP{ .val = 1.000000e+262, .off = -1.617283929500958241e+245 },
53 HP{.val=1.000000e+261, .off= 7.122615947963323868e+244 },53 HP{ .val = 1.000000e+261, .off = 7.122615947963323868e+244 },
54 HP{.val=1.000000e+260, .off= -6.533477610574617382e+243 },54 HP{ .val = 1.000000e+260, .off = -6.533477610574617382e+243 },
55 HP{.val=1.000000e+259, .off= 7.122615947963323982e+242 },55 HP{ .val = 1.000000e+259, .off = 7.122615947963323982e+242 },
56 HP{.val=1.000000e+258, .off= -5.679971763165996225e+241 },56 HP{ .val = 1.000000e+258, .off = -5.679971763165996225e+241 },
57 HP{.val=1.000000e+257, .off= -3.012765990014054219e+240 },57 HP{ .val = 1.000000e+257, .off = -3.012765990014054219e+240 },
58 HP{.val=1.000000e+256, .off= -3.012765990014054219e+239 },58 HP{ .val = 1.000000e+256, .off = -3.012765990014054219e+239 },
59 HP{.val=1.000000e+255, .off= 1.154743030535854616e+238 },59 HP{ .val = 1.000000e+255, .off = 1.154743030535854616e+238 },
60 HP{.val=1.000000e+254, .off= 6.364129306223240767e+237 },60 HP{ .val = 1.000000e+254, .off = 6.364129306223240767e+237 },
61 HP{.val=1.000000e+253, .off= 6.364129306223241129e+236 },61 HP{ .val = 1.000000e+253, .off = 6.364129306223241129e+236 },
62 HP{.val=1.000000e+252, .off= -9.915202805299840595e+235 },62 HP{ .val = 1.000000e+252, .off = -9.915202805299840595e+235 },
63 HP{.val=1.000000e+251, .off= -4.827911520448877980e+234 },63 HP{ .val = 1.000000e+251, .off = -4.827911520448877980e+234 },
64 HP{.val=1.000000e+250, .off= 7.890316691678530146e+233 },64 HP{ .val = 1.000000e+250, .off = 7.890316691678530146e+233 },
65 HP{.val=1.000000e+249, .off= 7.890316691678529484e+232 },65 HP{ .val = 1.000000e+249, .off = 7.890316691678529484e+232 },
66 HP{.val=1.000000e+248, .off= -4.529828046727141859e+231 },66 HP{ .val = 1.000000e+248, .off = -4.529828046727141859e+231 },
67 HP{.val=1.000000e+247, .off= 4.785280507077111924e+230 },67 HP{ .val = 1.000000e+247, .off = 4.785280507077111924e+230 },
68 HP{.val=1.000000e+246, .off= -6.858605185178205305e+229 },68 HP{ .val = 1.000000e+246, .off = -6.858605185178205305e+229 },
69 HP{.val=1.000000e+245, .off= -4.432795665958347728e+228 },69 HP{ .val = 1.000000e+245, .off = -4.432795665958347728e+228 },
70 HP{.val=1.000000e+244, .off= -7.465057564983169531e+227 },70 HP{ .val = 1.000000e+244, .off = -7.465057564983169531e+227 },
71 HP{.val=1.000000e+243, .off= -7.465057564983169741e+226 },71 HP{ .val = 1.000000e+243, .off = -7.465057564983169741e+226 },
72 HP{.val=1.000000e+242, .off= -5.096102956370027445e+225 },72 HP{ .val = 1.000000e+242, .off = -5.096102956370027445e+225 },
73 HP{.val=1.000000e+241, .off= -5.096102956370026952e+224 },73 HP{ .val = 1.000000e+241, .off = -5.096102956370026952e+224 },
74 HP{.val=1.000000e+240, .off= -1.394611380411992474e+223 },74 HP{ .val = 1.000000e+240, .off = -1.394611380411992474e+223 },
75 HP{.val=1.000000e+239, .off= 9.188208545617793960e+221 },75 HP{ .val = 1.000000e+239, .off = 9.188208545617793960e+221 },
76 HP{.val=1.000000e+238, .off= -4.864759732872650359e+221 },76 HP{ .val = 1.000000e+238, .off = -4.864759732872650359e+221 },
77 HP{.val=1.000000e+237, .off= 5.979453868566904629e+220 },77 HP{ .val = 1.000000e+237, .off = 5.979453868566904629e+220 },
78 HP{.val=1.000000e+236, .off= -5.316601966265964857e+219 },78 HP{ .val = 1.000000e+236, .off = -5.316601966265964857e+219 },
79 HP{.val=1.000000e+235, .off= -5.316601966265964701e+218 },79 HP{ .val = 1.000000e+235, .off = -5.316601966265964701e+218 },
80 HP{.val=1.000000e+234, .off= -1.786584517880693123e+217 },80 HP{ .val = 1.000000e+234, .off = -1.786584517880693123e+217 },
81 HP{.val=1.000000e+233, .off= 2.625937292600896716e+216 },81 HP{ .val = 1.000000e+233, .off = 2.625937292600896716e+216 },
82 HP{.val=1.000000e+232, .off= -5.647541102052084079e+215 },82 HP{ .val = 1.000000e+232, .off = -5.647541102052084079e+215 },
83 HP{.val=1.000000e+231, .off= -5.647541102052083888e+214 },83 HP{ .val = 1.000000e+231, .off = -5.647541102052083888e+214 },
84 HP{.val=1.000000e+230, .off= -9.956644432600511943e+213 },84 HP{ .val = 1.000000e+230, .off = -9.956644432600511943e+213 },
85 HP{.val=1.000000e+229, .off= 8.161138937705571862e+211 },85 HP{ .val = 1.000000e+229, .off = 8.161138937705571862e+211 },
86 HP{.val=1.000000e+228, .off= 7.549087847752475275e+211 },86 HP{ .val = 1.000000e+228, .off = 7.549087847752475275e+211 },
87 HP{.val=1.000000e+227, .off= -9.283347037202319948e+210 },87 HP{ .val = 1.000000e+227, .off = -9.283347037202319948e+210 },
88 HP{.val=1.000000e+226, .off= 3.866992716668613820e+209 },88 HP{ .val = 1.000000e+226, .off = 3.866992716668613820e+209 },
89 HP{.val=1.000000e+225, .off= 7.154577655136347262e+208 },89 HP{ .val = 1.000000e+225, .off = 7.154577655136347262e+208 },
90 HP{.val=1.000000e+224, .off= 3.045096482051680688e+207 },90 HP{ .val = 1.000000e+224, .off = 3.045096482051680688e+207 },
91 HP{.val=1.000000e+223, .off= -4.660180717482069567e+206 },91 HP{ .val = 1.000000e+223, .off = -4.660180717482069567e+206 },
92 HP{.val=1.000000e+222, .off= -4.660180717482070101e+205 },92 HP{ .val = 1.000000e+222, .off = -4.660180717482070101e+205 },
93 HP{.val=1.000000e+221, .off= -4.660180717482069544e+204 },93 HP{ .val = 1.000000e+221, .off = -4.660180717482069544e+204 },
94 HP{.val=1.000000e+220, .off= 3.562757926310489022e+202 },94 HP{ .val = 1.000000e+220, .off = 3.562757926310489022e+202 },
95 HP{.val=1.000000e+219, .off= 3.491561111451748149e+202 },95 HP{ .val = 1.000000e+219, .off = 3.491561111451748149e+202 },
96 HP{.val=1.000000e+218, .off= -8.265758834125874135e+201 },96 HP{ .val = 1.000000e+218, .off = -8.265758834125874135e+201 },
97 HP{.val=1.000000e+217, .off= 3.981449442517482365e+200 },97 HP{ .val = 1.000000e+217, .off = 3.981449442517482365e+200 },
98 HP{.val=1.000000e+216, .off= -2.142154695804195936e+199 },98 HP{ .val = 1.000000e+216, .off = -2.142154695804195936e+199 },
99 HP{.val=1.000000e+215, .off= 9.339603063548950188e+198 },99 HP{ .val = 1.000000e+215, .off = 9.339603063548950188e+198 },
100 HP{.val=1.000000e+214, .off= 4.555537330485139746e+197 },100 HP{ .val = 1.000000e+214, .off = 4.555537330485139746e+197 },
101 HP{.val=1.000000e+213, .off= 1.565496247320257804e+196 },101 HP{ .val = 1.000000e+213, .off = 1.565496247320257804e+196 },
102 HP{.val=1.000000e+212, .off= 9.040598955232462036e+195 },102 HP{ .val = 1.000000e+212, .off = 9.040598955232462036e+195 },
103 HP{.val=1.000000e+211, .off= 4.368659762787334780e+194 },103 HP{ .val = 1.000000e+211, .off = 4.368659762787334780e+194 },
104 HP{.val=1.000000e+210, .off= 7.288621758065539072e+193 },104 HP{ .val = 1.000000e+210, .off = 7.288621758065539072e+193 },
105 HP{.val=1.000000e+209, .off= -7.311188218325485628e+192 },105 HP{ .val = 1.000000e+209, .off = -7.311188218325485628e+192 },
106 HP{.val=1.000000e+208, .off= 1.813693016918905189e+191 },106 HP{ .val = 1.000000e+208, .off = 1.813693016918905189e+191 },
107 HP{.val=1.000000e+207, .off= -3.889357755108838992e+190 },107 HP{ .val = 1.000000e+207, .off = -3.889357755108838992e+190 },
108 HP{.val=1.000000e+206, .off= -3.889357755108838992e+189 },108 HP{ .val = 1.000000e+206, .off = -3.889357755108838992e+189 },
109 HP{.val=1.000000e+205, .off= -1.661603547285501360e+188 },109 HP{ .val = 1.000000e+205, .off = -1.661603547285501360e+188 },
110 HP{.val=1.000000e+204, .off= 1.123089212493670643e+187 },110 HP{ .val = 1.000000e+204, .off = 1.123089212493670643e+187 },
111 HP{.val=1.000000e+203, .off= 1.123089212493670643e+186 },111 HP{ .val = 1.000000e+203, .off = 1.123089212493670643e+186 },
112 HP{.val=1.000000e+202, .off= 9.825254086803583029e+185 },112 HP{ .val = 1.000000e+202, .off = 9.825254086803583029e+185 },
113 HP{.val=1.000000e+201, .off= -3.771878529305654999e+184 },113 HP{ .val = 1.000000e+201, .off = -3.771878529305654999e+184 },
114 HP{.val=1.000000e+200, .off= 3.026687778748963675e+183 },114 HP{ .val = 1.000000e+200, .off = 3.026687778748963675e+183 },
115 HP{.val=1.000000e+199, .off= -9.720624048853446693e+182 },115 HP{ .val = 1.000000e+199, .off = -9.720624048853446693e+182 },
116 HP{.val=1.000000e+198, .off= -1.753554156601940139e+181 },116 HP{ .val = 1.000000e+198, .off = -1.753554156601940139e+181 },
117 HP{.val=1.000000e+197, .off= 4.885670753607648963e+180 },117 HP{ .val = 1.000000e+197, .off = 4.885670753607648963e+180 },
118 HP{.val=1.000000e+196, .off= 4.885670753607648963e+179 },118 HP{ .val = 1.000000e+196, .off = 4.885670753607648963e+179 },
119 HP{.val=1.000000e+195, .off= 2.292223523057028076e+178 },119 HP{ .val = 1.000000e+195, .off = 2.292223523057028076e+178 },
120 HP{.val=1.000000e+194, .off= 5.534032561245303825e+177 },120 HP{ .val = 1.000000e+194, .off = 5.534032561245303825e+177 },
121 HP{.val=1.000000e+193, .off= -6.622751331960730683e+176 },121 HP{ .val = 1.000000e+193, .off = -6.622751331960730683e+176 },
122 HP{.val=1.000000e+192, .off= -4.090088020876139692e+175 },122 HP{ .val = 1.000000e+192, .off = -4.090088020876139692e+175 },
123 HP{.val=1.000000e+191, .off= -7.255917159731877552e+174 },123 HP{ .val = 1.000000e+191, .off = -7.255917159731877552e+174 },
124 HP{.val=1.000000e+190, .off= -7.255917159731877992e+173 },124 HP{ .val = 1.000000e+190, .off = -7.255917159731877992e+173 },
125 HP{.val=1.000000e+189, .off= -2.309309130269787104e+172 },125 HP{ .val = 1.000000e+189, .off = -2.309309130269787104e+172 },
126 HP{.val=1.000000e+188, .off= -2.309309130269787019e+171 },126 HP{ .val = 1.000000e+188, .off = -2.309309130269787019e+171 },
127 HP{.val=1.000000e+187, .off= 9.284303438781988230e+170 },127 HP{ .val = 1.000000e+187, .off = 9.284303438781988230e+170 },
128 HP{.val=1.000000e+186, .off= 2.038295583124628364e+169 },128 HP{ .val = 1.000000e+186, .off = 2.038295583124628364e+169 },
129 HP{.val=1.000000e+185, .off= 2.038295583124628532e+168 },129 HP{ .val = 1.000000e+185, .off = 2.038295583124628532e+168 },
130 HP{.val=1.000000e+184, .off= -1.735666841696912925e+167 },130 HP{ .val = 1.000000e+184, .off = -1.735666841696912925e+167 },
131 HP{.val=1.000000e+183, .off= 5.340512704843477241e+166 },131 HP{ .val = 1.000000e+183, .off = 5.340512704843477241e+166 },
132 HP{.val=1.000000e+182, .off= -6.453119872723839321e+165 },132 HP{ .val = 1.000000e+182, .off = -6.453119872723839321e+165 },
133 HP{.val=1.000000e+181, .off= 8.288920849235306587e+164 },133 HP{ .val = 1.000000e+181, .off = 8.288920849235306587e+164 },
134 HP{.val=1.000000e+180, .off= -9.248546019891598293e+162 },134 HP{ .val = 1.000000e+180, .off = -9.248546019891598293e+162 },
135 HP{.val=1.000000e+179, .off= 1.954450226518486016e+162 },135 HP{ .val = 1.000000e+179, .off = 1.954450226518486016e+162 },
136 HP{.val=1.000000e+178, .off= -5.243811844750628197e+161 },136 HP{ .val = 1.000000e+178, .off = -5.243811844750628197e+161 },
137 HP{.val=1.000000e+177, .off= -7.448980502074320639e+159 },137 HP{ .val = 1.000000e+177, .off = -7.448980502074320639e+159 },
138 HP{.val=1.000000e+176, .off= -7.448980502074319858e+158 },138 HP{ .val = 1.000000e+176, .off = -7.448980502074319858e+158 },
139 HP{.val=1.000000e+175, .off= 6.284654753766312753e+158 },139 HP{ .val = 1.000000e+175, .off = 6.284654753766312753e+158 },
140 HP{.val=1.000000e+174, .off= -6.895756753684458388e+157 },140 HP{ .val = 1.000000e+174, .off = -6.895756753684458388e+157 },
141 HP{.val=1.000000e+173, .off= -1.403918625579970616e+156 },141 HP{ .val = 1.000000e+173, .off = -1.403918625579970616e+156 },
142 HP{.val=1.000000e+172, .off= -8.268716285710580522e+155 },142 HP{ .val = 1.000000e+172, .off = -8.268716285710580522e+155 },
143 HP{.val=1.000000e+171, .off= 4.602779327034313170e+154 },143 HP{ .val = 1.000000e+171, .off = 4.602779327034313170e+154 },
144 HP{.val=1.000000e+170, .off= -3.441905430931244940e+153 },144 HP{ .val = 1.000000e+170, .off = -3.441905430931244940e+153 },
145 HP{.val=1.000000e+169, .off= 6.613950516525702884e+152 },145 HP{ .val = 1.000000e+169, .off = 6.613950516525702884e+152 },
146 HP{.val=1.000000e+168, .off= 6.613950516525702652e+151 },146 HP{ .val = 1.000000e+168, .off = 6.613950516525702652e+151 },
147 HP{.val=1.000000e+167, .off= -3.860899428741951187e+150 },147 HP{ .val = 1.000000e+167, .off = -3.860899428741951187e+150 },
148 HP{.val=1.000000e+166, .off= 5.959272394946474605e+149 },148 HP{ .val = 1.000000e+166, .off = 5.959272394946474605e+149 },
149 HP{.val=1.000000e+165, .off= 1.005101065481665103e+149 },149 HP{ .val = 1.000000e+165, .off = 1.005101065481665103e+149 },
150 HP{.val=1.000000e+164, .off= -1.783349948587918355e+146 },150 HP{ .val = 1.000000e+164, .off = -1.783349948587918355e+146 },
151 HP{.val=1.000000e+163, .off= 6.215006036188360099e+146 },151 HP{ .val = 1.000000e+163, .off = 6.215006036188360099e+146 },
152 HP{.val=1.000000e+162, .off= 6.215006036188360099e+145 },152 HP{ .val = 1.000000e+162, .off = 6.215006036188360099e+145 },
153 HP{.val=1.000000e+161, .off= -3.774589324822814903e+144 },153 HP{ .val = 1.000000e+161, .off = -3.774589324822814903e+144 },
154 HP{.val=1.000000e+160, .off= -6.528407745068226929e+142 },154 HP{ .val = 1.000000e+160, .off = -6.528407745068226929e+142 },
155 HP{.val=1.000000e+159, .off= 7.151530601283157561e+142 },155 HP{ .val = 1.000000e+159, .off = 7.151530601283157561e+142 },
156 HP{.val=1.000000e+158, .off= 4.712664546348788765e+141 },156 HP{ .val = 1.000000e+158, .off = 4.712664546348788765e+141 },
157 HP{.val=1.000000e+157, .off= 1.664081977680827856e+140 },157 HP{ .val = 1.000000e+157, .off = 1.664081977680827856e+140 },
158 HP{.val=1.000000e+156, .off= 1.664081977680827750e+139 },158 HP{ .val = 1.000000e+156, .off = 1.664081977680827750e+139 },
159 HP{.val=1.000000e+155, .off= -7.176231540910168265e+137 },159 HP{ .val = 1.000000e+155, .off = -7.176231540910168265e+137 },
160 HP{.val=1.000000e+154, .off= -3.694754568805822650e+137 },160 HP{ .val = 1.000000e+154, .off = -3.694754568805822650e+137 },
161 HP{.val=1.000000e+153, .off= 2.665969958768462622e+134 },161 HP{ .val = 1.000000e+153, .off = 2.665969958768462622e+134 },
162 HP{.val=1.000000e+152, .off= -4.625108135904199522e+135 },162 HP{ .val = 1.000000e+152, .off = -4.625108135904199522e+135 },
163 HP{.val=1.000000e+151, .off= -1.717753238721771919e+134 },163 HP{ .val = 1.000000e+151, .off = -1.717753238721771919e+134 },
164 HP{.val=1.000000e+150, .off= 1.916440382756262433e+133 },164 HP{ .val = 1.000000e+150, .off = 1.916440382756262433e+133 },
165 HP{.val=1.000000e+149, .off= -4.897672657515052040e+132 },165 HP{ .val = 1.000000e+149, .off = -4.897672657515052040e+132 },
166 HP{.val=1.000000e+148, .off= -4.897672657515052198e+131 },166 HP{ .val = 1.000000e+148, .off = -4.897672657515052198e+131 },
167 HP{.val=1.000000e+147, .off= 2.200361759434233991e+130 },167 HP{ .val = 1.000000e+147, .off = 2.200361759434233991e+130 },
168 HP{.val=1.000000e+146, .off= 6.636633270027537273e+129 },168 HP{ .val = 1.000000e+146, .off = 6.636633270027537273e+129 },
169 HP{.val=1.000000e+145, .off= 1.091293881785907977e+128 },169 HP{ .val = 1.000000e+145, .off = 1.091293881785907977e+128 },
170 HP{.val=1.000000e+144, .off= -2.374543235865110597e+127 },170 HP{ .val = 1.000000e+144, .off = -2.374543235865110597e+127 },
171 HP{.val=1.000000e+143, .off= -2.374543235865110537e+126 },171 HP{ .val = 1.000000e+143, .off = -2.374543235865110537e+126 },
172 HP{.val=1.000000e+142, .off= -5.082228484029969099e+125 },172 HP{ .val = 1.000000e+142, .off = -5.082228484029969099e+125 },
173 HP{.val=1.000000e+141, .off= -1.697621923823895943e+124 },173 HP{ .val = 1.000000e+141, .off = -1.697621923823895943e+124 },
174 HP{.val=1.000000e+140, .off= -5.928380124081487212e+123 },174 HP{ .val = 1.000000e+140, .off = -5.928380124081487212e+123 },
175 HP{.val=1.000000e+139, .off= -3.284156248920492522e+122 },175 HP{ .val = 1.000000e+139, .off = -3.284156248920492522e+122 },
176 HP{.val=1.000000e+138, .off= -3.284156248920492706e+121 },176 HP{ .val = 1.000000e+138, .off = -3.284156248920492706e+121 },
177 HP{.val=1.000000e+137, .off= -3.284156248920492476e+120 },177 HP{ .val = 1.000000e+137, .off = -3.284156248920492476e+120 },
178 HP{.val=1.000000e+136, .off= -5.866406127007401066e+119 },178 HP{ .val = 1.000000e+136, .off = -5.866406127007401066e+119 },
179 HP{.val=1.000000e+135, .off= 3.817030915818506056e+118 },179 HP{ .val = 1.000000e+135, .off = 3.817030915818506056e+118 },
180 HP{.val=1.000000e+134, .off= 7.851796350329300951e+117 },180 HP{ .val = 1.000000e+134, .off = 7.851796350329300951e+117 },
181 HP{.val=1.000000e+133, .off= -2.235117235947686077e+116 },181 HP{ .val = 1.000000e+133, .off = -2.235117235947686077e+116 },
182 HP{.val=1.000000e+132, .off= 9.170432597638723691e+114 },182 HP{ .val = 1.000000e+132, .off = 9.170432597638723691e+114 },
183 HP{.val=1.000000e+131, .off= 8.797444499042767883e+114 },183 HP{ .val = 1.000000e+131, .off = 8.797444499042767883e+114 },
184 HP{.val=1.000000e+130, .off= -5.978307824605161274e+113 },184 HP{ .val = 1.000000e+130, .off = -5.978307824605161274e+113 },
185 HP{.val=1.000000e+129, .off= 1.782556435814758516e+111 },185 HP{ .val = 1.000000e+129, .off = 1.782556435814758516e+111 },
186 HP{.val=1.000000e+128, .off= -7.517448691651820362e+111 },186 HP{ .val = 1.000000e+128, .off = -7.517448691651820362e+111 },
187 HP{.val=1.000000e+127, .off= 4.507089332150205498e+110 },187 HP{ .val = 1.000000e+127, .off = 4.507089332150205498e+110 },
188 HP{.val=1.000000e+126, .off= 7.513223838100711695e+109 },188 HP{ .val = 1.000000e+126, .off = 7.513223838100711695e+109 },
189 HP{.val=1.000000e+125, .off= 7.513223838100712113e+108 },189 HP{ .val = 1.000000e+125, .off = 7.513223838100712113e+108 },
190 HP{.val=1.000000e+124, .off= 5.164681255326878494e+107 },190 HP{ .val = 1.000000e+124, .off = 5.164681255326878494e+107 },
191 HP{.val=1.000000e+123, .off= 2.229003026859587122e+106 },191 HP{ .val = 1.000000e+123, .off = 2.229003026859587122e+106 },
192 HP{.val=1.000000e+122, .off= -1.440594758724527399e+105 },192 HP{ .val = 1.000000e+122, .off = -1.440594758724527399e+105 },
193 HP{.val=1.000000e+121, .off= -3.734093374714598783e+104 },193 HP{ .val = 1.000000e+121, .off = -3.734093374714598783e+104 },
194 HP{.val=1.000000e+120, .off= 1.999653165260579757e+103 },194 HP{ .val = 1.000000e+120, .off = 1.999653165260579757e+103 },
195 HP{.val=1.000000e+119, .off= 5.583244752745066693e+102 },195 HP{ .val = 1.000000e+119, .off = 5.583244752745066693e+102 },
196 HP{.val=1.000000e+118, .off= 3.343500010567262234e+101 },196 HP{ .val = 1.000000e+118, .off = 3.343500010567262234e+101 },
197 HP{.val=1.000000e+117, .off= -5.055542772599503556e+100 },197 HP{ .val = 1.000000e+117, .off = -5.055542772599503556e+100 },
198 HP{.val=1.000000e+116, .off= -1.555941612946684331e+99 },198 HP{ .val = 1.000000e+116, .off = -1.555941612946684331e+99 },
199 HP{.val=1.000000e+115, .off= -1.555941612946684331e+98 },199 HP{ .val = 1.000000e+115, .off = -1.555941612946684331e+98 },
200 HP{.val=1.000000e+114, .off= -1.555941612946684293e+97 },200 HP{ .val = 1.000000e+114, .off = -1.555941612946684293e+97 },
201 HP{.val=1.000000e+113, .off= -1.555941612946684246e+96 },201 HP{ .val = 1.000000e+113, .off = -1.555941612946684246e+96 },
202 HP{.val=1.000000e+112, .off= 6.988006530736955847e+95 },202 HP{ .val = 1.000000e+112, .off = 6.988006530736955847e+95 },
203 HP{.val=1.000000e+111, .off= 4.318022735835818244e+94 },203 HP{ .val = 1.000000e+111, .off = 4.318022735835818244e+94 },
204 HP{.val=1.000000e+110, .off= -2.356936751417025578e+93 },204 HP{ .val = 1.000000e+110, .off = -2.356936751417025578e+93 },
205 HP{.val=1.000000e+109, .off= 1.814912928116001926e+92 },205 HP{ .val = 1.000000e+109, .off = 1.814912928116001926e+92 },
206 HP{.val=1.000000e+108, .off= -3.399899171300282744e+91 },206 HP{ .val = 1.000000e+108, .off = -3.399899171300282744e+91 },
207 HP{.val=1.000000e+107, .off= 3.118615952970072913e+90 },207 HP{ .val = 1.000000e+107, .off = 3.118615952970072913e+90 },
208 HP{.val=1.000000e+106, .off= -9.103599905036843605e+89 },208 HP{ .val = 1.000000e+106, .off = -9.103599905036843605e+89 },
209 HP{.val=1.000000e+105, .off= 6.174169917471802325e+88 },209 HP{ .val = 1.000000e+105, .off = 6.174169917471802325e+88 },
210 HP{.val=1.000000e+104, .off= -1.915675085734668657e+86 },210 HP{ .val = 1.000000e+104, .off = -1.915675085734668657e+86 },
211 HP{.val=1.000000e+103, .off= -1.915675085734668864e+85 },211 HP{ .val = 1.000000e+103, .off = -1.915675085734668864e+85 },
212 HP{.val=1.000000e+102, .off= 2.295048673475466221e+85 },212 HP{ .val = 1.000000e+102, .off = 2.295048673475466221e+85 },
213 HP{.val=1.000000e+101, .off= 2.295048673475466135e+84 },213 HP{ .val = 1.000000e+101, .off = 2.295048673475466135e+84 },
214 HP{.val=1.000000e+100, .off= -1.590289110975991792e+83 },214 HP{ .val = 1.000000e+100, .off = -1.590289110975991792e+83 },
215 HP{.val=1.000000e+99, .off= 3.266383119588331155e+82 },215 HP{ .val = 1.000000e+99, .off = 3.266383119588331155e+82 },
216 HP{.val=1.000000e+98, .off= 2.309629754856292029e+80 },216 HP{ .val = 1.000000e+98, .off = 2.309629754856292029e+80 },
217 HP{.val=1.000000e+97, .off= -7.357587384771124533e+80 },217 HP{ .val = 1.000000e+97, .off = -7.357587384771124533e+80 },
218 HP{.val=1.000000e+96, .off= -4.986165397190889509e+79 },218 HP{ .val = 1.000000e+96, .off = -4.986165397190889509e+79 },
219 HP{.val=1.000000e+95, .off= -2.021887912715594741e+78 },219 HP{ .val = 1.000000e+95, .off = -2.021887912715594741e+78 },
220 HP{.val=1.000000e+94, .off= -2.021887912715594638e+77 },220 HP{ .val = 1.000000e+94, .off = -2.021887912715594638e+77 },
221 HP{.val=1.000000e+93, .off= -4.337729697461918675e+76 },221 HP{ .val = 1.000000e+93, .off = -4.337729697461918675e+76 },
222 HP{.val=1.000000e+92, .off= -4.337729697461918997e+75 },222 HP{ .val = 1.000000e+92, .off = -4.337729697461918997e+75 },
223 HP{.val=1.000000e+91, .off= -7.956232486128049702e+74 },223 HP{ .val = 1.000000e+91, .off = -7.956232486128049702e+74 },
224 HP{.val=1.000000e+90, .off= 3.351588728453609882e+73 },224 HP{ .val = 1.000000e+90, .off = 3.351588728453609882e+73 },
225 HP{.val=1.000000e+89, .off= 5.246334248081951113e+71 },225 HP{ .val = 1.000000e+89, .off = 5.246334248081951113e+71 },
226 HP{.val=1.000000e+88, .off= 4.058327554364963672e+71 },226 HP{ .val = 1.000000e+88, .off = 4.058327554364963672e+71 },
227 HP{.val=1.000000e+87, .off= 4.058327554364963918e+70 },227 HP{ .val = 1.000000e+87, .off = 4.058327554364963918e+70 },
228 HP{.val=1.000000e+86, .off= -1.463069523067487266e+69 },228 HP{ .val = 1.000000e+86, .off = -1.463069523067487266e+69 },
229 HP{.val=1.000000e+85, .off= -1.463069523067487314e+68 },229 HP{ .val = 1.000000e+85, .off = -1.463069523067487314e+68 },
230 HP{.val=1.000000e+84, .off= -5.776660989811589441e+67 },230 HP{ .val = 1.000000e+84, .off = -5.776660989811589441e+67 },
231 HP{.val=1.000000e+83, .off= -3.080666323096525761e+66 },231 HP{ .val = 1.000000e+83, .off = -3.080666323096525761e+66 },
232 HP{.val=1.000000e+82, .off= 3.659320343691134468e+65 },232 HP{ .val = 1.000000e+82, .off = 3.659320343691134468e+65 },
233 HP{.val=1.000000e+81, .off= 7.871812010433421235e+64 },233 HP{ .val = 1.000000e+81, .off = 7.871812010433421235e+64 },
234 HP{.val=1.000000e+80, .off= -2.660986470836727449e+61 },234 HP{ .val = 1.000000e+80, .off = -2.660986470836727449e+61 },
235 HP{.val=1.000000e+79, .off= 3.264399249934044627e+62 },235 HP{ .val = 1.000000e+79, .off = 3.264399249934044627e+62 },
236 HP{.val=1.000000e+78, .off= -8.493621433689703070e+60 },236 HP{ .val = 1.000000e+78, .off = -8.493621433689703070e+60 },
237 HP{.val=1.000000e+77, .off= 1.721738727445414063e+60 },237 HP{ .val = 1.000000e+77, .off = 1.721738727445414063e+60 },
238 HP{.val=1.000000e+76, .off= -4.706013449590547218e+59 },238 HP{ .val = 1.000000e+76, .off = -4.706013449590547218e+59 },
239 HP{.val=1.000000e+75, .off= 7.346021882351880518e+58 },239 HP{ .val = 1.000000e+75, .off = 7.346021882351880518e+58 },
240 HP{.val=1.000000e+74, .off= 4.835181188197207515e+57 },240 HP{ .val = 1.000000e+74, .off = 4.835181188197207515e+57 },
241 HP{.val=1.000000e+73, .off= 1.696630320503867482e+56 },241 HP{ .val = 1.000000e+73, .off = 1.696630320503867482e+56 },
242 HP{.val=1.000000e+72, .off= 5.619818905120542959e+55 },242 HP{ .val = 1.000000e+72, .off = 5.619818905120542959e+55 },
243 HP{.val=1.000000e+71, .off= -4.188152556421145598e+54 },243 HP{ .val = 1.000000e+71, .off = -4.188152556421145598e+54 },
244 HP{.val=1.000000e+70, .off= -7.253143638152923145e+53 },244 HP{ .val = 1.000000e+70, .off = -7.253143638152923145e+53 },
245 HP{.val=1.000000e+69, .off= -7.253143638152923145e+52 },245 HP{ .val = 1.000000e+69, .off = -7.253143638152923145e+52 },
246 HP{.val=1.000000e+68, .off= 4.719477774861832896e+51 },246 HP{ .val = 1.000000e+68, .off = 4.719477774861832896e+51 },
247 HP{.val=1.000000e+67, .off= 1.726322421608144052e+50 },247 HP{ .val = 1.000000e+67, .off = 1.726322421608144052e+50 },
248 HP{.val=1.000000e+66, .off= 5.467766613175255107e+49 },248 HP{ .val = 1.000000e+66, .off = 5.467766613175255107e+49 },
249 HP{.val=1.000000e+65, .off= 7.909613737163661911e+47 },249 HP{ .val = 1.000000e+65, .off = 7.909613737163661911e+47 },
250 HP{.val=1.000000e+64, .off= -2.132041900945439564e+47 },250 HP{ .val = 1.000000e+64, .off = -2.132041900945439564e+47 },
251 HP{.val=1.000000e+63, .off= -5.785795994272697265e+46 },251 HP{ .val = 1.000000e+63, .off = -5.785795994272697265e+46 },
252 HP{.val=1.000000e+62, .off= -3.502199685943161329e+45 },252 HP{ .val = 1.000000e+62, .off = -3.502199685943161329e+45 },
253 HP{.val=1.000000e+61, .off= 5.061286470292598274e+44 },253 HP{ .val = 1.000000e+61, .off = 5.061286470292598274e+44 },
254 HP{.val=1.000000e+60, .off= 5.061286470292598472e+43 },254 HP{ .val = 1.000000e+60, .off = 5.061286470292598472e+43 },
255 HP{.val=1.000000e+59, .off= 2.831211950439536034e+42 },255 HP{ .val = 1.000000e+59, .off = 2.831211950439536034e+42 },
256 HP{.val=1.000000e+58, .off= 5.618805100255863927e+41 },256 HP{ .val = 1.000000e+58, .off = 5.618805100255863927e+41 },
257 HP{.val=1.000000e+57, .off= -4.834669211555366251e+40 },257 HP{ .val = 1.000000e+57, .off = -4.834669211555366251e+40 },
258 HP{.val=1.000000e+56, .off= -9.190283508143378583e+39 },258 HP{ .val = 1.000000e+56, .off = -9.190283508143378583e+39 },
259 HP{.val=1.000000e+55, .off= -1.023506702040855158e+38 },259 HP{ .val = 1.000000e+55, .off = -1.023506702040855158e+38 },
260 HP{.val=1.000000e+54, .off= -7.829154040459624616e+37 },260 HP{ .val = 1.000000e+54, .off = -7.829154040459624616e+37 },
261 HP{.val=1.000000e+53, .off= 6.779051325638372659e+35 },261 HP{ .val = 1.000000e+53, .off = 6.779051325638372659e+35 },
262 HP{.val=1.000000e+52, .off= 6.779051325638372290e+34 },262 HP{ .val = 1.000000e+52, .off = 6.779051325638372290e+34 },
263 HP{.val=1.000000e+51, .off= 6.779051325638371598e+33 },263 HP{ .val = 1.000000e+51, .off = 6.779051325638371598e+33 },
264 HP{.val=1.000000e+50, .off= -7.629769841091887392e+33 },264 HP{ .val = 1.000000e+50, .off = -7.629769841091887392e+33 },
265 HP{.val=1.000000e+49, .off= 5.350972305245182400e+32 },265 HP{ .val = 1.000000e+49, .off = 5.350972305245182400e+32 },
266 HP{.val=1.000000e+48, .off= -4.384584304507619764e+31 },266 HP{ .val = 1.000000e+48, .off = -4.384584304507619764e+31 },
267 HP{.val=1.000000e+47, .off= -4.384584304507619876e+30 },267 HP{ .val = 1.000000e+47, .off = -4.384584304507619876e+30 },
268 HP{.val=1.000000e+46, .off= 6.860180964052978705e+28 },268 HP{ .val = 1.000000e+46, .off = 6.860180964052978705e+28 },
269 HP{.val=1.000000e+45, .off= 7.024271097546444878e+28 },269 HP{ .val = 1.000000e+45, .off = 7.024271097546444878e+28 },
270 HP{.val=1.000000e+44, .off= -8.821361405306422641e+27 },270 HP{ .val = 1.000000e+44, .off = -8.821361405306422641e+27 },
271 HP{.val=1.000000e+43, .off= -1.393721169594140991e+26 },271 HP{ .val = 1.000000e+43, .off = -1.393721169594140991e+26 },
272 HP{.val=1.000000e+42, .off= -4.488571267807591679e+25 },272 HP{ .val = 1.000000e+42, .off = -4.488571267807591679e+25 },
273 HP{.val=1.000000e+41, .off= -6.200086450407783195e+23 },273 HP{ .val = 1.000000e+41, .off = -6.200086450407783195e+23 },
274 HP{.val=1.000000e+40, .off= -3.037860284270036669e+23 },274 HP{ .val = 1.000000e+40, .off = -3.037860284270036669e+23 },
275 HP{.val=1.000000e+39, .off= 6.029083362839682141e+22 },275 HP{ .val = 1.000000e+39, .off = 6.029083362839682141e+22 },
276 HP{.val=1.000000e+38, .off= 2.251190176543965970e+21 },276 HP{ .val = 1.000000e+38, .off = 2.251190176543965970e+21 },
277 HP{.val=1.000000e+37, .off= 4.612373417978788577e+20 },277 HP{ .val = 1.000000e+37, .off = 4.612373417978788577e+20 },
278 HP{.val=1.000000e+36, .off= -4.242063737401796198e+19 },278 HP{ .val = 1.000000e+36, .off = -4.242063737401796198e+19 },
279 HP{.val=1.000000e+35, .off= 3.136633892082024448e+18 },279 HP{ .val = 1.000000e+35, .off = 3.136633892082024448e+18 },
280 HP{.val=1.000000e+34, .off= 5.442476901295718400e+17 },280 HP{ .val = 1.000000e+34, .off = 5.442476901295718400e+17 },
281 HP{.val=1.000000e+33, .off= 5.442476901295718400e+16 },281 HP{ .val = 1.000000e+33, .off = 5.442476901295718400e+16 },
282 HP{.val=1.000000e+32, .off= -5.366162204393472000e+15 },282 HP{ .val = 1.000000e+32, .off = -5.366162204393472000e+15 },
283 HP{.val=1.000000e+31, .off= 3.641037050347520000e+14 },283 HP{ .val = 1.000000e+31, .off = 3.641037050347520000e+14 },
284 HP{.val=1.000000e+30, .off= -1.988462483865600000e+13 },284 HP{ .val = 1.000000e+30, .off = -1.988462483865600000e+13 },
285 HP{.val=1.000000e+29, .off= 8.566849142784000000e+12 },285 HP{ .val = 1.000000e+29, .off = 8.566849142784000000e+12 },
286 HP{.val=1.000000e+28, .off= 4.168802631680000000e+11 },286 HP{ .val = 1.000000e+28, .off = 4.168802631680000000e+11 },
287 HP{.val=1.000000e+27, .off= -1.328755507200000000e+10 },287 HP{ .val = 1.000000e+27, .off = -1.328755507200000000e+10 },
288 HP{.val=1.000000e+26, .off= -4.764729344000000000e+09 },288 HP{ .val = 1.000000e+26, .off = -4.764729344000000000e+09 },
289 HP{.val=1.000000e+25, .off= -9.059696640000000000e+08 },289 HP{ .val = 1.000000e+25, .off = -9.059696640000000000e+08 },
290 HP{.val=1.000000e+24, .off= 1.677721600000000000e+07 },290 HP{ .val = 1.000000e+24, .off = 1.677721600000000000e+07 },
291 HP{.val=1.000000e+23, .off= 8.388608000000000000e+06 },291 HP{ .val = 1.000000e+23, .off = 8.388608000000000000e+06 },
292 HP{.val=1.000000e+22, .off= 0.000000000000000000e+00 },292 HP{ .val = 1.000000e+22, .off = 0.000000000000000000e+00 },
293 HP{.val=1.000000e+21, .off= 0.000000000000000000e+00 },293 HP{ .val = 1.000000e+21, .off = 0.000000000000000000e+00 },
294 HP{.val=1.000000e+20, .off= 0.000000000000000000e+00 },294 HP{ .val = 1.000000e+20, .off = 0.000000000000000000e+00 },
295 HP{.val=1.000000e+19, .off= 0.000000000000000000e+00 },295 HP{ .val = 1.000000e+19, .off = 0.000000000000000000e+00 },
296 HP{.val=1.000000e+18, .off= 0.000000000000000000e+00 },296 HP{ .val = 1.000000e+18, .off = 0.000000000000000000e+00 },
297 HP{.val=1.000000e+17, .off= 0.000000000000000000e+00 },297 HP{ .val = 1.000000e+17, .off = 0.000000000000000000e+00 },
298 HP{.val=1.000000e+16, .off= 0.000000000000000000e+00 },298 HP{ .val = 1.000000e+16, .off = 0.000000000000000000e+00 },
299 HP{.val=1.000000e+15, .off= 0.000000000000000000e+00 },299 HP{ .val = 1.000000e+15, .off = 0.000000000000000000e+00 },
300 HP{.val=1.000000e+14, .off= 0.000000000000000000e+00 },300 HP{ .val = 1.000000e+14, .off = 0.000000000000000000e+00 },
301 HP{.val=1.000000e+13, .off= 0.000000000000000000e+00 },301 HP{ .val = 1.000000e+13, .off = 0.000000000000000000e+00 },
302 HP{.val=1.000000e+12, .off= 0.000000000000000000e+00 },302 HP{ .val = 1.000000e+12, .off = 0.000000000000000000e+00 },
303 HP{.val=1.000000e+11, .off= 0.000000000000000000e+00 },303 HP{ .val = 1.000000e+11, .off = 0.000000000000000000e+00 },
304 HP{.val=1.000000e+10, .off= 0.000000000000000000e+00 },304 HP{ .val = 1.000000e+10, .off = 0.000000000000000000e+00 },
305 HP{.val=1.000000e+09, .off= 0.000000000000000000e+00 },305 HP{ .val = 1.000000e+09, .off = 0.000000000000000000e+00 },
306 HP{.val=1.000000e+08, .off= 0.000000000000000000e+00 },306 HP{ .val = 1.000000e+08, .off = 0.000000000000000000e+00 },
307 HP{.val=1.000000e+07, .off= 0.000000000000000000e+00 },307 HP{ .val = 1.000000e+07, .off = 0.000000000000000000e+00 },
308 HP{.val=1.000000e+06, .off= 0.000000000000000000e+00 },308 HP{ .val = 1.000000e+06, .off = 0.000000000000000000e+00 },
309 HP{.val=1.000000e+05, .off= 0.000000000000000000e+00 },309 HP{ .val = 1.000000e+05, .off = 0.000000000000000000e+00 },
310 HP{.val=1.000000e+04, .off= 0.000000000000000000e+00 },310 HP{ .val = 1.000000e+04, .off = 0.000000000000000000e+00 },
311 HP{.val=1.000000e+03, .off= 0.000000000000000000e+00 },311 HP{ .val = 1.000000e+03, .off = 0.000000000000000000e+00 },
312 HP{.val=1.000000e+02, .off= 0.000000000000000000e+00 },312 HP{ .val = 1.000000e+02, .off = 0.000000000000000000e+00 },
313 HP{.val=1.000000e+01, .off= 0.000000000000000000e+00 },313 HP{ .val = 1.000000e+01, .off = 0.000000000000000000e+00 },
314 HP{.val=1.000000e+00, .off= 0.000000000000000000e+00 },314 HP{ .val = 1.000000e+00, .off = 0.000000000000000000e+00 },
315 HP{.val=1.000000e-01, .off= -5.551115123125783010e-18 },315 HP{ .val = 1.000000e-01, .off = -5.551115123125783010e-18 },
316 HP{.val=1.000000e-02, .off= -2.081668171172168436e-19 },316 HP{ .val = 1.000000e-02, .off = -2.081668171172168436e-19 },
317 HP{.val=1.000000e-03, .off= -2.081668171172168557e-20 },317 HP{ .val = 1.000000e-03, .off = -2.081668171172168557e-20 },
318 HP{.val=1.000000e-04, .off= -4.792173602385929943e-21 },318 HP{ .val = 1.000000e-04, .off = -4.792173602385929943e-21 },
319 HP{.val=1.000000e-05, .off= -8.180305391403130547e-22 },319 HP{ .val = 1.000000e-05, .off = -8.180305391403130547e-22 },
320 HP{.val=1.000000e-06, .off= 4.525188817411374069e-23 },320 HP{ .val = 1.000000e-06, .off = 4.525188817411374069e-23 },
321 HP{.val=1.000000e-07, .off= 4.525188817411373922e-24 },321 HP{ .val = 1.000000e-07, .off = 4.525188817411373922e-24 },
322 HP{.val=1.000000e-08, .off= -2.092256083012847109e-25 },322 HP{ .val = 1.000000e-08, .off = -2.092256083012847109e-25 },
323 HP{.val=1.000000e-09, .off= -6.228159145777985254e-26 },323 HP{ .val = 1.000000e-09, .off = -6.228159145777985254e-26 },
324 HP{.val=1.000000e-10, .off= -3.643219731549774344e-27 },324 HP{ .val = 1.000000e-10, .off = -3.643219731549774344e-27 },
325 HP{.val=1.000000e-11, .off= 6.050303071806019080e-28 },325 HP{ .val = 1.000000e-11, .off = 6.050303071806019080e-28 },
326 HP{.val=1.000000e-12, .off= 2.011335237074438524e-29 },326 HP{ .val = 1.000000e-12, .off = 2.011335237074438524e-29 },
327 HP{.val=1.000000e-13, .off= -3.037374556340037101e-30 },327 HP{ .val = 1.000000e-13, .off = -3.037374556340037101e-30 },
328 HP{.val=1.000000e-14, .off= 1.180690645440101289e-32 },328 HP{ .val = 1.000000e-14, .off = 1.180690645440101289e-32 },
329 HP{.val=1.000000e-15, .off= -7.770539987666107583e-32 },329 HP{ .val = 1.000000e-15, .off = -7.770539987666107583e-32 },
330 HP{.val=1.000000e-16, .off= 2.090221327596539779e-33 },330 HP{ .val = 1.000000e-16, .off = 2.090221327596539779e-33 },
331 HP{.val=1.000000e-17, .off= -7.154242405462192144e-34 },331 HP{ .val = 1.000000e-17, .off = -7.154242405462192144e-34 },
332 HP{.val=1.000000e-18, .off= -7.154242405462192572e-35 },332 HP{ .val = 1.000000e-18, .off = -7.154242405462192572e-35 },
333 HP{.val=1.000000e-19, .off= 2.475407316473986894e-36 },333 HP{ .val = 1.000000e-19, .off = 2.475407316473986894e-36 },
334 HP{.val=1.000000e-20, .off= 5.484672854579042914e-37 },334 HP{ .val = 1.000000e-20, .off = 5.484672854579042914e-37 },
335 HP{.val=1.000000e-21, .off= 9.246254777210362522e-38 },335 HP{ .val = 1.000000e-21, .off = 9.246254777210362522e-38 },
336 HP{.val=1.000000e-22, .off= -4.859677432657087182e-39 },336 HP{ .val = 1.000000e-22, .off = -4.859677432657087182e-39 },
337 HP{.val=1.000000e-23, .off= 3.956530198510069291e-40 },337 HP{ .val = 1.000000e-23, .off = 3.956530198510069291e-40 },
338 HP{.val=1.000000e-24, .off= 7.629950044829717753e-41 },338 HP{ .val = 1.000000e-24, .off = 7.629950044829717753e-41 },
339 HP{.val=1.000000e-25, .off= -3.849486974919183692e-42 },339 HP{ .val = 1.000000e-25, .off = -3.849486974919183692e-42 },
340 HP{.val=1.000000e-26, .off= -3.849486974919184170e-43 },340 HP{ .val = 1.000000e-26, .off = -3.849486974919184170e-43 },
341 HP{.val=1.000000e-27, .off= -3.849486974919184070e-44 },341 HP{ .val = 1.000000e-27, .off = -3.849486974919184070e-44 },
342 HP{.val=1.000000e-28, .off= 2.876745653839937870e-45 },342 HP{ .val = 1.000000e-28, .off = 2.876745653839937870e-45 },
343 HP{.val=1.000000e-29, .off= 5.679342582489572168e-46 },343 HP{ .val = 1.000000e-29, .off = 5.679342582489572168e-46 },
344 HP{.val=1.000000e-30, .off= -8.333642060758598930e-47 },344 HP{ .val = 1.000000e-30, .off = -8.333642060758598930e-47 },
345 HP{.val=1.000000e-31, .off= -8.333642060758597958e-48 },345 HP{ .val = 1.000000e-31, .off = -8.333642060758597958e-48 },
346 HP{.val=1.000000e-32, .off= -5.596730997624190224e-49 },346 HP{ .val = 1.000000e-32, .off = -5.596730997624190224e-49 },
347 HP{.val=1.000000e-33, .off= -5.596730997624190604e-50 },347 HP{ .val = 1.000000e-33, .off = -5.596730997624190604e-50 },
348 HP{.val=1.000000e-34, .off= 7.232539610818348498e-51 },348 HP{ .val = 1.000000e-34, .off = 7.232539610818348498e-51 },
349 HP{.val=1.000000e-35, .off= -7.857545194582380514e-53 },349 HP{ .val = 1.000000e-35, .off = -7.857545194582380514e-53 },
350 HP{.val=1.000000e-36, .off= 5.896157255772251528e-53 },350 HP{ .val = 1.000000e-36, .off = 5.896157255772251528e-53 },
351 HP{.val=1.000000e-37, .off= -6.632427322784915796e-54 },351 HP{ .val = 1.000000e-37, .off = -6.632427322784915796e-54 },
352 HP{.val=1.000000e-38, .off= 3.808059826012723592e-55 },352 HP{ .val = 1.000000e-38, .off = 3.808059826012723592e-55 },
353 HP{.val=1.000000e-39, .off= 7.070712060011985131e-56 },353 HP{ .val = 1.000000e-39, .off = 7.070712060011985131e-56 },
354 HP{.val=1.000000e-40, .off= 7.070712060011985584e-57 },354 HP{ .val = 1.000000e-40, .off = 7.070712060011985584e-57 },
355 HP{.val=1.000000e-41, .off= -5.761291134237854167e-59 },355 HP{ .val = 1.000000e-41, .off = -5.761291134237854167e-59 },
356 HP{.val=1.000000e-42, .off= -3.762312935688689794e-59 },356 HP{ .val = 1.000000e-42, .off = -3.762312935688689794e-59 },
357 HP{.val=1.000000e-43, .off= -7.745042713519821150e-60 },357 HP{ .val = 1.000000e-43, .off = -7.745042713519821150e-60 },
358 HP{.val=1.000000e-44, .off= 4.700987842202462817e-61 },358 HP{ .val = 1.000000e-44, .off = 4.700987842202462817e-61 },
359 HP{.val=1.000000e-45, .off= 1.589480203271891964e-62 },359 HP{ .val = 1.000000e-45, .off = 1.589480203271891964e-62 },
360 HP{.val=1.000000e-46, .off= -2.299904345391321765e-63 },360 HP{ .val = 1.000000e-46, .off = -2.299904345391321765e-63 },
361 HP{.val=1.000000e-47, .off= 2.561826340437695261e-64 },361 HP{ .val = 1.000000e-47, .off = 2.561826340437695261e-64 },
362 HP{.val=1.000000e-48, .off= 2.561826340437695345e-65 },362 HP{ .val = 1.000000e-48, .off = 2.561826340437695345e-65 },
363 HP{.val=1.000000e-49, .off= 6.360053438741614633e-66 },363 HP{ .val = 1.000000e-49, .off = 6.360053438741614633e-66 },
364 HP{.val=1.000000e-50, .off= -7.616223705782342295e-68 },364 HP{ .val = 1.000000e-50, .off = -7.616223705782342295e-68 },
365 HP{.val=1.000000e-51, .off= -7.616223705782343324e-69 },365 HP{ .val = 1.000000e-51, .off = -7.616223705782343324e-69 },
366 HP{.val=1.000000e-52, .off= -7.616223705782342295e-70 },366 HP{ .val = 1.000000e-52, .off = -7.616223705782342295e-70 },
367 HP{.val=1.000000e-53, .off= -3.079876214757872338e-70 },367 HP{ .val = 1.000000e-53, .off = -3.079876214757872338e-70 },
368 HP{.val=1.000000e-54, .off= -3.079876214757872821e-71 },368 HP{ .val = 1.000000e-54, .off = -3.079876214757872821e-71 },
369 HP{.val=1.000000e-55, .off= 5.423954167728123147e-73 },369 HP{ .val = 1.000000e-55, .off = 5.423954167728123147e-73 },
370 HP{.val=1.000000e-56, .off= -3.985444122640543680e-73 },370 HP{ .val = 1.000000e-56, .off = -3.985444122640543680e-73 },
371 HP{.val=1.000000e-57, .off= 4.504255013759498850e-74 },371 HP{ .val = 1.000000e-57, .off = 4.504255013759498850e-74 },
372 HP{.val=1.000000e-58, .off= -2.570494266573869991e-75 },372 HP{ .val = 1.000000e-58, .off = -2.570494266573869991e-75 },
373 HP{.val=1.000000e-59, .off= -2.570494266573869930e-76 },373 HP{ .val = 1.000000e-59, .off = -2.570494266573869930e-76 },
374 HP{.val=1.000000e-60, .off= 2.956653608686574324e-77 },374 HP{ .val = 1.000000e-60, .off = 2.956653608686574324e-77 },
375 HP{.val=1.000000e-61, .off= -3.952281235388981376e-78 },375 HP{ .val = 1.000000e-61, .off = -3.952281235388981376e-78 },
376 HP{.val=1.000000e-62, .off= -3.952281235388981376e-79 },376 HP{ .val = 1.000000e-62, .off = -3.952281235388981376e-79 },
377 HP{.val=1.000000e-63, .off= -6.651083908855995172e-80 },377 HP{ .val = 1.000000e-63, .off = -6.651083908855995172e-80 },
378 HP{.val=1.000000e-64, .off= 3.469426116645307030e-81 },378 HP{ .val = 1.000000e-64, .off = 3.469426116645307030e-81 },
379 HP{.val=1.000000e-65, .off= 7.686305293937516319e-82 },379 HP{ .val = 1.000000e-65, .off = 7.686305293937516319e-82 },
380 HP{.val=1.000000e-66, .off= 2.415206322322254927e-83 },380 HP{ .val = 1.000000e-66, .off = 2.415206322322254927e-83 },
381 HP{.val=1.000000e-67, .off= 5.709643179581793251e-84 },381 HP{ .val = 1.000000e-67, .off = 5.709643179581793251e-84 },
382 HP{.val=1.000000e-68, .off= -6.644495035141475923e-85 },382 HP{ .val = 1.000000e-68, .off = -6.644495035141475923e-85 },
383 HP{.val=1.000000e-69, .off= 3.650620143794581913e-86 },383 HP{ .val = 1.000000e-69, .off = 3.650620143794581913e-86 },
384 HP{.val=1.000000e-70, .off= 4.333966503770636492e-88 },384 HP{ .val = 1.000000e-70, .off = 4.333966503770636492e-88 },
385 HP{.val=1.000000e-71, .off= 8.476455383920859113e-88 },385 HP{ .val = 1.000000e-71, .off = 8.476455383920859113e-88 },
386 HP{.val=1.000000e-72, .off= 3.449543675455986564e-89 },386 HP{ .val = 1.000000e-72, .off = 3.449543675455986564e-89 },
387 HP{.val=1.000000e-73, .off= 3.077238576654418974e-91 },387 HP{ .val = 1.000000e-73, .off = 3.077238576654418974e-91 },
388 HP{.val=1.000000e-74, .off= 4.234998629903623140e-91 },388 HP{ .val = 1.000000e-74, .off = 4.234998629903623140e-91 },
389 HP{.val=1.000000e-75, .off= 4.234998629903623412e-92 },389 HP{ .val = 1.000000e-75, .off = 4.234998629903623412e-92 },
390 HP{.val=1.000000e-76, .off= 7.303182045714702338e-93 },390 HP{ .val = 1.000000e-76, .off = 7.303182045714702338e-93 },
391 HP{.val=1.000000e-77, .off= 7.303182045714701699e-94 },391 HP{ .val = 1.000000e-77, .off = 7.303182045714701699e-94 },
392 HP{.val=1.000000e-78, .off= 1.121271649074855759e-96 },392 HP{ .val = 1.000000e-78, .off = 1.121271649074855759e-96 },
393 HP{.val=1.000000e-79, .off= 1.121271649074855863e-97 },393 HP{ .val = 1.000000e-79, .off = 1.121271649074855863e-97 },
394 HP{.val=1.000000e-80, .off= 3.857468248661243988e-97 },394 HP{ .val = 1.000000e-80, .off = 3.857468248661243988e-97 },
395 HP{.val=1.000000e-81, .off= 3.857468248661244248e-98 },395 HP{ .val = 1.000000e-81, .off = 3.857468248661244248e-98 },
396 HP{.val=1.000000e-82, .off= 3.857468248661244410e-99 },396 HP{ .val = 1.000000e-82, .off = 3.857468248661244410e-99 },
397 HP{.val=1.000000e-83, .off= -3.457651055545315679e-100 },397 HP{ .val = 1.000000e-83, .off = -3.457651055545315679e-100 },
398 HP{.val=1.000000e-84, .off= -3.457651055545315933e-101 },398 HP{ .val = 1.000000e-84, .off = -3.457651055545315933e-101 },
399 HP{.val=1.000000e-85, .off= 2.257285900866059216e-102 },399 HP{ .val = 1.000000e-85, .off = 2.257285900866059216e-102 },
400 HP{.val=1.000000e-86, .off= -8.458220892405268345e-103 },400 HP{ .val = 1.000000e-86, .off = -8.458220892405268345e-103 },
401 HP{.val=1.000000e-87, .off= -1.761029146610688867e-104 },401 HP{ .val = 1.000000e-87, .off = -1.761029146610688867e-104 },
402 HP{.val=1.000000e-88, .off= 6.610460535632536565e-105 },402 HP{ .val = 1.000000e-88, .off = 6.610460535632536565e-105 },
403 HP{.val=1.000000e-89, .off= -3.853901567171494935e-106 },403 HP{ .val = 1.000000e-89, .off = -3.853901567171494935e-106 },
404 HP{.val=1.000000e-90, .off= 5.062493089968513723e-108 },404 HP{ .val = 1.000000e-90, .off = 5.062493089968513723e-108 },
405 HP{.val=1.000000e-91, .off= -2.218844988608365240e-108 },405 HP{ .val = 1.000000e-91, .off = -2.218844988608365240e-108 },
406 HP{.val=1.000000e-92, .off= 1.187522883398155383e-109 },406 HP{ .val = 1.000000e-92, .off = 1.187522883398155383e-109 },
407 HP{.val=1.000000e-93, .off= 9.703442563414457296e-110 },407 HP{ .val = 1.000000e-93, .off = 9.703442563414457296e-110 },
408 HP{.val=1.000000e-94, .off= 4.380992763404268896e-111 },408 HP{ .val = 1.000000e-94, .off = 4.380992763404268896e-111 },
409 HP{.val=1.000000e-95, .off= 1.054461638397900823e-112 },409 HP{ .val = 1.000000e-95, .off = 1.054461638397900823e-112 },
410 HP{.val=1.000000e-96, .off= 9.370789450913819736e-113 },410 HP{ .val = 1.000000e-96, .off = 9.370789450913819736e-113 },
411 HP{.val=1.000000e-97, .off= -3.623472756142303998e-114 },411 HP{ .val = 1.000000e-97, .off = -3.623472756142303998e-114 },
412 HP{.val=1.000000e-98, .off= 6.122223899149788839e-115 },412 HP{ .val = 1.000000e-98, .off = 6.122223899149788839e-115 },
413 HP{.val=1.000000e-99, .off= -1.999189980260288281e-116 },413 HP{ .val = 1.000000e-99, .off = -1.999189980260288281e-116 },
414 HP{.val=1.000000e-100, .off= -1.999189980260288281e-117 },414 HP{ .val = 1.000000e-100, .off = -1.999189980260288281e-117 },
415 HP{.val=1.000000e-101, .off= -5.171617276904849634e-118 },415 HP{ .val = 1.000000e-101, .off = -5.171617276904849634e-118 },
416 HP{.val=1.000000e-102, .off= 6.724985085512256320e-119 },416 HP{ .val = 1.000000e-102, .off = 6.724985085512256320e-119 },
417 HP{.val=1.000000e-103, .off= 4.246526260008692213e-120 },417 HP{ .val = 1.000000e-103, .off = 4.246526260008692213e-120 },
418 HP{.val=1.000000e-104, .off= 7.344599791888147003e-121 },418 HP{ .val = 1.000000e-104, .off = 7.344599791888147003e-121 },
419 HP{.val=1.000000e-105, .off= 3.472007877038828407e-122 },419 HP{ .val = 1.000000e-105, .off = 3.472007877038828407e-122 },
420 HP{.val=1.000000e-106, .off= 5.892377823819652194e-123 },420 HP{ .val = 1.000000e-106, .off = 5.892377823819652194e-123 },
421 HP{.val=1.000000e-107, .off= -1.585470431324073925e-125 },421 HP{ .val = 1.000000e-107, .off = -1.585470431324073925e-125 },
422 HP{.val=1.000000e-108, .off= -3.940375084977444795e-125 },422 HP{ .val = 1.000000e-108, .off = -3.940375084977444795e-125 },
423 HP{.val=1.000000e-109, .off= 7.869099673288519908e-127 },423 HP{ .val = 1.000000e-109, .off = 7.869099673288519908e-127 },
424 HP{.val=1.000000e-110, .off= -5.122196348054018581e-127 },424 HP{ .val = 1.000000e-110, .off = -5.122196348054018581e-127 },
425 HP{.val=1.000000e-111, .off= -8.815387795168313713e-128 },425 HP{ .val = 1.000000e-111, .off = -8.815387795168313713e-128 },
426 HP{.val=1.000000e-112, .off= 5.034080131510290214e-129 },426 HP{ .val = 1.000000e-112, .off = 5.034080131510290214e-129 },
427 HP{.val=1.000000e-113, .off= 2.148774313452247863e-130 },427 HP{ .val = 1.000000e-113, .off = 2.148774313452247863e-130 },
428 HP{.val=1.000000e-114, .off= -5.064490231692858416e-131 },428 HP{ .val = 1.000000e-114, .off = -5.064490231692858416e-131 },
429 HP{.val=1.000000e-115, .off= -5.064490231692858166e-132 },429 HP{ .val = 1.000000e-115, .off = -5.064490231692858166e-132 },
430 HP{.val=1.000000e-116, .off= 5.708726942017560559e-134 },430 HP{ .val = 1.000000e-116, .off = 5.708726942017560559e-134 },
431 HP{.val=1.000000e-117, .off= -2.951229134482377772e-134 },431 HP{ .val = 1.000000e-117, .off = -2.951229134482377772e-134 },
432 HP{.val=1.000000e-118, .off= 1.451398151372789513e-135 },432 HP{ .val = 1.000000e-118, .off = 1.451398151372789513e-135 },
433 HP{.val=1.000000e-119, .off= -1.300243902286690040e-136 },433 HP{ .val = 1.000000e-119, .off = -1.300243902286690040e-136 },
434 HP{.val=1.000000e-120, .off= 2.139308664787659449e-137 },434 HP{ .val = 1.000000e-120, .off = 2.139308664787659449e-137 },
435 HP{.val=1.000000e-121, .off= 2.139308664787659329e-138 },435 HP{ .val = 1.000000e-121, .off = 2.139308664787659329e-138 },
436 HP{.val=1.000000e-122, .off= -5.922142664292847471e-139 },436 HP{ .val = 1.000000e-122, .off = -5.922142664292847471e-139 },
437 HP{.val=1.000000e-123, .off= -5.922142664292846912e-140 },437 HP{ .val = 1.000000e-123, .off = -5.922142664292846912e-140 },
438 HP{.val=1.000000e-124, .off= 6.673875037395443799e-141 },438 HP{ .val = 1.000000e-124, .off = 6.673875037395443799e-141 },
439 HP{.val=1.000000e-125, .off= -1.198636026159737932e-142 },439 HP{ .val = 1.000000e-125, .off = -1.198636026159737932e-142 },
440 HP{.val=1.000000e-126, .off= 5.361789860136246995e-143 },440 HP{ .val = 1.000000e-126, .off = 5.361789860136246995e-143 },
441 HP{.val=1.000000e-127, .off= -2.838742497733733936e-144 },441 HP{ .val = 1.000000e-127, .off = -2.838742497733733936e-144 },
442 HP{.val=1.000000e-128, .off= -5.401408859568103261e-145 },442 HP{ .val = 1.000000e-128, .off = -5.401408859568103261e-145 },
443 HP{.val=1.000000e-129, .off= 7.411922949603743011e-146 },443 HP{ .val = 1.000000e-129, .off = 7.411922949603743011e-146 },
444 HP{.val=1.000000e-130, .off= -8.604741811861064385e-147 },444 HP{ .val = 1.000000e-130, .off = -8.604741811861064385e-147 },
445 HP{.val=1.000000e-131, .off= 1.405673664054439890e-148 },445 HP{ .val = 1.000000e-131, .off = 1.405673664054439890e-148 },
446 HP{.val=1.000000e-132, .off= 1.405673664054439933e-149 },446 HP{ .val = 1.000000e-132, .off = 1.405673664054439933e-149 },
447 HP{.val=1.000000e-133, .off= -6.414963426504548053e-150 },447 HP{ .val = 1.000000e-133, .off = -6.414963426504548053e-150 },
448 HP{.val=1.000000e-134, .off= -3.971014335704864578e-151 },448 HP{ .val = 1.000000e-134, .off = -3.971014335704864578e-151 },
449 HP{.val=1.000000e-135, .off= -3.971014335704864748e-152 },449 HP{ .val = 1.000000e-135, .off = -3.971014335704864748e-152 },
450 HP{.val=1.000000e-136, .off= -1.523438813303585576e-154 },450 HP{ .val = 1.000000e-136, .off = -1.523438813303585576e-154 },
451 HP{.val=1.000000e-137, .off= 2.234325152653707766e-154 },451 HP{ .val = 1.000000e-137, .off = 2.234325152653707766e-154 },
452 HP{.val=1.000000e-138, .off= -6.715683724786540160e-155 },452 HP{ .val = 1.000000e-138, .off = -6.715683724786540160e-155 },
453 HP{.val=1.000000e-139, .off= -2.986513359186437306e-156 },453 HP{ .val = 1.000000e-139, .off = -2.986513359186437306e-156 },
454 HP{.val=1.000000e-140, .off= 1.674949597813692102e-157 },454 HP{ .val = 1.000000e-140, .off = 1.674949597813692102e-157 },
455 HP{.val=1.000000e-141, .off= -4.151879098436469092e-158 },455 HP{ .val = 1.000000e-141, .off = -4.151879098436469092e-158 },
456 HP{.val=1.000000e-142, .off= -4.151879098436469295e-159 },456 HP{ .val = 1.000000e-142, .off = -4.151879098436469295e-159 },
457 HP{.val=1.000000e-143, .off= 4.952540739454407825e-160 },457 HP{ .val = 1.000000e-143, .off = 4.952540739454407825e-160 },
458 HP{.val=1.000000e-144, .off= 4.952540739454407667e-161 },458 HP{ .val = 1.000000e-144, .off = 4.952540739454407667e-161 },
459 HP{.val=1.000000e-145, .off= 8.508954738630531443e-162 },459 HP{ .val = 1.000000e-145, .off = 8.508954738630531443e-162 },
460 HP{.val=1.000000e-146, .off= -2.604839008794855481e-163 },460 HP{ .val = 1.000000e-146, .off = -2.604839008794855481e-163 },
461 HP{.val=1.000000e-147, .off= 2.952057864917838382e-164 },461 HP{ .val = 1.000000e-147, .off = 2.952057864917838382e-164 },
462 HP{.val=1.000000e-148, .off= 6.425118410988271757e-165 },462 HP{ .val = 1.000000e-148, .off = 6.425118410988271757e-165 },
463 HP{.val=1.000000e-149, .off= 2.083792728400229858e-166 },463 HP{ .val = 1.000000e-149, .off = 2.083792728400229858e-166 },
464 HP{.val=1.000000e-150, .off= -6.295358232172964237e-168 },464 HP{ .val = 1.000000e-150, .off = -6.295358232172964237e-168 },
465 HP{.val=1.000000e-151, .off= 6.153785555826519421e-168 },465 HP{ .val = 1.000000e-151, .off = 6.153785555826519421e-168 },
466 HP{.val=1.000000e-152, .off= -6.564942029880634994e-169 },466 HP{ .val = 1.000000e-152, .off = -6.564942029880634994e-169 },
467 HP{.val=1.000000e-153, .off= -3.915207116191644540e-170 },467 HP{ .val = 1.000000e-153, .off = -3.915207116191644540e-170 },
468 HP{.val=1.000000e-154, .off= 2.709130168030831503e-171 },468 HP{ .val = 1.000000e-154, .off = 2.709130168030831503e-171 },
469 HP{.val=1.000000e-155, .off= -1.431080634608215966e-172 },469 HP{ .val = 1.000000e-155, .off = -1.431080634608215966e-172 },
470 HP{.val=1.000000e-156, .off= -4.018712386257620994e-173 },470 HP{ .val = 1.000000e-156, .off = -4.018712386257620994e-173 },
471 HP{.val=1.000000e-157, .off= 5.684906682427646782e-174 },471 HP{ .val = 1.000000e-157, .off = 5.684906682427646782e-174 },
472 HP{.val=1.000000e-158, .off= -6.444617153428937489e-175 },472 HP{ .val = 1.000000e-158, .off = -6.444617153428937489e-175 },
473 HP{.val=1.000000e-159, .off= 1.136335243981427681e-176 },473 HP{ .val = 1.000000e-159, .off = 1.136335243981427681e-176 },
474 HP{.val=1.000000e-160, .off= 1.136335243981427725e-177 },474 HP{ .val = 1.000000e-160, .off = 1.136335243981427725e-177 },
475 HP{.val=1.000000e-161, .off= -2.812077463003137395e-178 },475 HP{ .val = 1.000000e-161, .off = -2.812077463003137395e-178 },
476 HP{.val=1.000000e-162, .off= 4.591196362592922204e-179 },476 HP{ .val = 1.000000e-162, .off = 4.591196362592922204e-179 },
477 HP{.val=1.000000e-163, .off= 7.675893789924613703e-180 },477 HP{ .val = 1.000000e-163, .off = 7.675893789924613703e-180 },
478 HP{.val=1.000000e-164, .off= 3.820022005759999543e-181 },478 HP{ .val = 1.000000e-164, .off = 3.820022005759999543e-181 },
479 HP{.val=1.000000e-165, .off= -9.998177244457686588e-183 },479 HP{ .val = 1.000000e-165, .off = -9.998177244457686588e-183 },
480 HP{.val=1.000000e-166, .off= -4.012217555824373639e-183 },480 HP{ .val = 1.000000e-166, .off = -4.012217555824373639e-183 },
481 HP{.val=1.000000e-167, .off= -2.467177666011174334e-185 },481 HP{ .val = 1.000000e-167, .off = -2.467177666011174334e-185 },
482 HP{.val=1.000000e-168, .off= -4.953592503130188139e-185 },482 HP{ .val = 1.000000e-168, .off = -4.953592503130188139e-185 },
483 HP{.val=1.000000e-169, .off= -2.011795792799518887e-186 },483 HP{ .val = 1.000000e-169, .off = -2.011795792799518887e-186 },
484 HP{.val=1.000000e-170, .off= 1.665450095113817423e-187 },484 HP{ .val = 1.000000e-170, .off = 1.665450095113817423e-187 },
485 HP{.val=1.000000e-171, .off= 1.665450095113817487e-188 },485 HP{ .val = 1.000000e-171, .off = 1.665450095113817487e-188 },
486 HP{.val=1.000000e-172, .off= -4.080246604750770577e-189 },486 HP{ .val = 1.000000e-172, .off = -4.080246604750770577e-189 },
487 HP{.val=1.000000e-173, .off= -4.080246604750770677e-190 },487 HP{ .val = 1.000000e-173, .off = -4.080246604750770677e-190 },
488 HP{.val=1.000000e-174, .off= 4.085789420184387951e-192 },488 HP{ .val = 1.000000e-174, .off = 4.085789420184387951e-192 },
489 HP{.val=1.000000e-175, .off= 4.085789420184388146e-193 },489 HP{ .val = 1.000000e-175, .off = 4.085789420184388146e-193 },
490 HP{.val=1.000000e-176, .off= 4.085789420184388146e-194 },490 HP{ .val = 1.000000e-176, .off = 4.085789420184388146e-194 },
491 HP{.val=1.000000e-177, .off= 4.792197640035244894e-194 },491 HP{ .val = 1.000000e-177, .off = 4.792197640035244894e-194 },
492 HP{.val=1.000000e-178, .off= 4.792197640035244742e-195 },492 HP{ .val = 1.000000e-178, .off = 4.792197640035244742e-195 },
493 HP{.val=1.000000e-179, .off= -2.057206575616014662e-196 },493 HP{ .val = 1.000000e-179, .off = -2.057206575616014662e-196 },
494 HP{.val=1.000000e-180, .off= -2.057206575616014662e-197 },494 HP{ .val = 1.000000e-180, .off = -2.057206575616014662e-197 },
495 HP{.val=1.000000e-181, .off= -4.732755097354788053e-198 },495 HP{ .val = 1.000000e-181, .off = -4.732755097354788053e-198 },
496 HP{.val=1.000000e-182, .off= -4.732755097354787867e-199 },496 HP{ .val = 1.000000e-182, .off = -4.732755097354787867e-199 },
497 HP{.val=1.000000e-183, .off= -5.522105321379546765e-201 },497 HP{ .val = 1.000000e-183, .off = -5.522105321379546765e-201 },
498 HP{.val=1.000000e-184, .off= -5.777891238658996019e-201 },498 HP{ .val = 1.000000e-184, .off = -5.777891238658996019e-201 },
499 HP{.val=1.000000e-185, .off= 7.542096444923057046e-203 },499 HP{ .val = 1.000000e-185, .off = 7.542096444923057046e-203 },
500 HP{.val=1.000000e-186, .off= 8.919335748431433483e-203 },500 HP{ .val = 1.000000e-186, .off = 8.919335748431433483e-203 },
501 HP{.val=1.000000e-187, .off= -1.287071881492476028e-204 },501 HP{ .val = 1.000000e-187, .off = -1.287071881492476028e-204 },
502 HP{.val=1.000000e-188, .off= 5.091932887209967018e-205 },502 HP{ .val = 1.000000e-188, .off = 5.091932887209967018e-205 },
503 HP{.val=1.000000e-189, .off= -6.868701054107114024e-206 },503 HP{ .val = 1.000000e-189, .off = -6.868701054107114024e-206 },
504 HP{.val=1.000000e-190, .off= -1.885103578558330118e-207 },504 HP{ .val = 1.000000e-190, .off = -1.885103578558330118e-207 },
505 HP{.val=1.000000e-191, .off= -1.885103578558330205e-208 },505 HP{ .val = 1.000000e-191, .off = -1.885103578558330205e-208 },
506 HP{.val=1.000000e-192, .off= -9.671974634103305058e-209 },506 HP{ .val = 1.000000e-192, .off = -9.671974634103305058e-209 },
507 HP{.val=1.000000e-193, .off= -4.805180224387695640e-210 },507 HP{ .val = 1.000000e-193, .off = -4.805180224387695640e-210 },
508 HP{.val=1.000000e-194, .off= -1.763433718315439838e-211 },508 HP{ .val = 1.000000e-194, .off = -1.763433718315439838e-211 },
509 HP{.val=1.000000e-195, .off= -9.367799983496079132e-212 },509 HP{ .val = 1.000000e-195, .off = -9.367799983496079132e-212 },
510 HP{.val=1.000000e-196, .off= -4.615071067758179837e-213 },510 HP{ .val = 1.000000e-196, .off = -4.615071067758179837e-213 },
511 HP{.val=1.000000e-197, .off= 1.325840076914194777e-214 },511 HP{ .val = 1.000000e-197, .off = 1.325840076914194777e-214 },
512 HP{.val=1.000000e-198, .off= 8.751979007754662425e-215 },512 HP{ .val = 1.000000e-198, .off = 8.751979007754662425e-215 },
513 HP{.val=1.000000e-199, .off= 1.789973760091724198e-216 },513 HP{ .val = 1.000000e-199, .off = 1.789973760091724198e-216 },
514 HP{.val=1.000000e-200, .off= 1.789973760091724077e-217 },514 HP{ .val = 1.000000e-200, .off = 1.789973760091724077e-217 },
515 HP{.val=1.000000e-201, .off= 5.416018159916171171e-218 },515 HP{ .val = 1.000000e-201, .off = 5.416018159916171171e-218 },
516 HP{.val=1.000000e-202, .off= -3.649092839644947067e-219 },516 HP{ .val = 1.000000e-202, .off = -3.649092839644947067e-219 },
517 HP{.val=1.000000e-203, .off= -3.649092839644947067e-220 },517 HP{ .val = 1.000000e-203, .off = -3.649092839644947067e-220 },
518 HP{.val=1.000000e-204, .off= -1.080338554413850956e-222 },518 HP{ .val = 1.000000e-204, .off = -1.080338554413850956e-222 },
519 HP{.val=1.000000e-205, .off= -1.080338554413850841e-223 },519 HP{ .val = 1.000000e-205, .off = -1.080338554413850841e-223 },
520 HP{.val=1.000000e-206, .off= -2.874486186850417807e-223 },520 HP{ .val = 1.000000e-206, .off = -2.874486186850417807e-223 },
521 HP{.val=1.000000e-207, .off= 7.499710055933455072e-224 },521 HP{ .val = 1.000000e-207, .off = 7.499710055933455072e-224 },
522 HP{.val=1.000000e-208, .off= -9.790617015372999087e-225 },522 HP{ .val = 1.000000e-208, .off = -9.790617015372999087e-225 },
523 HP{.val=1.000000e-209, .off= -4.387389805589732612e-226 },523 HP{ .val = 1.000000e-209, .off = -4.387389805589732612e-226 },
524 HP{.val=1.000000e-210, .off= -4.387389805589732612e-227 },524 HP{ .val = 1.000000e-210, .off = -4.387389805589732612e-227 },
525 HP{.val=1.000000e-211, .off= -8.608661063232909897e-228 },525 HP{ .val = 1.000000e-211, .off = -8.608661063232909897e-228 },
526 HP{.val=1.000000e-212, .off= 4.582811616902018972e-229 },526 HP{ .val = 1.000000e-212, .off = 4.582811616902018972e-229 },
527 HP{.val=1.000000e-213, .off= 4.582811616902019155e-230 },527 HP{ .val = 1.000000e-213, .off = 4.582811616902019155e-230 },
528 HP{.val=1.000000e-214, .off= 8.705146829444184930e-231 },528 HP{ .val = 1.000000e-214, .off = 8.705146829444184930e-231 },
529 HP{.val=1.000000e-215, .off= -4.177150709750081830e-232 },529 HP{ .val = 1.000000e-215, .off = -4.177150709750081830e-232 },
530 HP{.val=1.000000e-216, .off= -4.177150709750082366e-233 },530 HP{ .val = 1.000000e-216, .off = -4.177150709750082366e-233 },
531 HP{.val=1.000000e-217, .off= -8.202868690748290237e-234 },531 HP{ .val = 1.000000e-217, .off = -8.202868690748290237e-234 },
532 HP{.val=1.000000e-218, .off= -3.170721214500530119e-235 },532 HP{ .val = 1.000000e-218, .off = -3.170721214500530119e-235 },
533 HP{.val=1.000000e-219, .off= -3.170721214500529857e-236 },533 HP{ .val = 1.000000e-219, .off = -3.170721214500529857e-236 },
534 HP{.val=1.000000e-220, .off= 7.606440013180328441e-238 },534 HP{ .val = 1.000000e-220, .off = 7.606440013180328441e-238 },
535 HP{.val=1.000000e-221, .off= -1.696459258568569049e-238 },535 HP{ .val = 1.000000e-221, .off = -1.696459258568569049e-238 },
536 HP{.val=1.000000e-222, .off= -4.767838333426821244e-239 },536 HP{ .val = 1.000000e-222, .off = -4.767838333426821244e-239 },
537 HP{.val=1.000000e-223, .off= 2.910609353718809138e-240 },537 HP{ .val = 1.000000e-223, .off = 2.910609353718809138e-240 },
538 HP{.val=1.000000e-224, .off= -1.888420450747209784e-241 },538 HP{ .val = 1.000000e-224, .off = -1.888420450747209784e-241 },
539 HP{.val=1.000000e-225, .off= 4.110366804835314035e-242 },539 HP{ .val = 1.000000e-225, .off = 4.110366804835314035e-242 },
540 HP{.val=1.000000e-226, .off= 7.859608839574391006e-243 },540 HP{ .val = 1.000000e-226, .off = 7.859608839574391006e-243 },
541 HP{.val=1.000000e-227, .off= 5.516332567862468419e-244 },541 HP{ .val = 1.000000e-227, .off = 5.516332567862468419e-244 },
542 HP{.val=1.000000e-228, .off= -3.270953451057244613e-245 },542 HP{ .val = 1.000000e-228, .off = -3.270953451057244613e-245 },
543 HP{.val=1.000000e-229, .off= -6.932322625607124670e-246 },543 HP{ .val = 1.000000e-229, .off = -6.932322625607124670e-246 },
544 HP{.val=1.000000e-230, .off= -4.643966891513449762e-247 },544 HP{ .val = 1.000000e-230, .off = -4.643966891513449762e-247 },
545 HP{.val=1.000000e-231, .off= 1.076922443720738305e-248 },545 HP{ .val = 1.000000e-231, .off = 1.076922443720738305e-248 },
546 HP{.val=1.000000e-232, .off= -2.498633390800628939e-249 },546 HP{ .val = 1.000000e-232, .off = -2.498633390800628939e-249 },
547 HP{.val=1.000000e-233, .off= 4.205533798926934891e-250 },547 HP{ .val = 1.000000e-233, .off = 4.205533798926934891e-250 },
548 HP{.val=1.000000e-234, .off= 4.205533798926934891e-251 },548 HP{ .val = 1.000000e-234, .off = 4.205533798926934891e-251 },
549 HP{.val=1.000000e-235, .off= 4.205533798926934697e-252 },549 HP{ .val = 1.000000e-235, .off = 4.205533798926934697e-252 },
550 HP{.val=1.000000e-236, .off= -4.523850562697497656e-253 },550 HP{ .val = 1.000000e-236, .off = -4.523850562697497656e-253 },
551 HP{.val=1.000000e-237, .off= 9.320146633177728298e-255 },551 HP{ .val = 1.000000e-237, .off = 9.320146633177728298e-255 },
552 HP{.val=1.000000e-238, .off= 9.320146633177728062e-256 },552 HP{ .val = 1.000000e-238, .off = 9.320146633177728062e-256 },
553 HP{.val=1.000000e-239, .off= -7.592774752331086440e-256 },553 HP{ .val = 1.000000e-239, .off = -7.592774752331086440e-256 },
554 HP{.val=1.000000e-240, .off= 3.063212017229987840e-257 },554 HP{ .val = 1.000000e-240, .off = 3.063212017229987840e-257 },
555 HP{.val=1.000000e-241, .off= 3.063212017229987562e-258 },555 HP{ .val = 1.000000e-241, .off = 3.063212017229987562e-258 },
556 HP{.val=1.000000e-242, .off= 3.063212017229987562e-259 },556 HP{ .val = 1.000000e-242, .off = 3.063212017229987562e-259 },
557 HP{.val=1.000000e-243, .off= 4.616527473176159842e-261 },557 HP{ .val = 1.000000e-243, .off = 4.616527473176159842e-261 },
558 HP{.val=1.000000e-244, .off= 6.965550922098544975e-261 },558 HP{ .val = 1.000000e-244, .off = 6.965550922098544975e-261 },
559 HP{.val=1.000000e-245, .off= 6.965550922098544749e-262 },559 HP{ .val = 1.000000e-245, .off = 6.965550922098544749e-262 },
560 HP{.val=1.000000e-246, .off= 4.424965697574744679e-263 },560 HP{ .val = 1.000000e-246, .off = 4.424965697574744679e-263 },
561 HP{.val=1.000000e-247, .off= -1.926497363734756420e-264 },561 HP{ .val = 1.000000e-247, .off = -1.926497363734756420e-264 },
562 HP{.val=1.000000e-248, .off= 2.043167049583681740e-265 },562 HP{ .val = 1.000000e-248, .off = 2.043167049583681740e-265 },
563 HP{.val=1.000000e-249, .off= -5.399953725388390154e-266 },563 HP{ .val = 1.000000e-249, .off = -5.399953725388390154e-266 },
564 HP{.val=1.000000e-250, .off= -5.399953725388389982e-267 },564 HP{ .val = 1.000000e-250, .off = -5.399953725388389982e-267 },
565 HP{.val=1.000000e-251, .off= -1.523328321757102663e-268 },565 HP{ .val = 1.000000e-251, .off = -1.523328321757102663e-268 },
566 HP{.val=1.000000e-252, .off= 5.745344310051561161e-269 },566 HP{ .val = 1.000000e-252, .off = 5.745344310051561161e-269 },
567 HP{.val=1.000000e-253, .off= -6.369110076296211879e-270 },567 HP{ .val = 1.000000e-253, .off = -6.369110076296211879e-270 },
568 HP{.val=1.000000e-254, .off= 8.773957906638504842e-271 },568 HP{ .val = 1.000000e-254, .off = 8.773957906638504842e-271 },
569 HP{.val=1.000000e-255, .off= -6.904595826956931908e-273 },569 HP{ .val = 1.000000e-255, .off = -6.904595826956931908e-273 },
570 HP{.val=1.000000e-256, .off= 2.267170882721243669e-273 },570 HP{ .val = 1.000000e-256, .off = 2.267170882721243669e-273 },
571 HP{.val=1.000000e-257, .off= 2.267170882721243669e-274 },571 HP{ .val = 1.000000e-257, .off = 2.267170882721243669e-274 },
572 HP{.val=1.000000e-258, .off= 4.577819683828225398e-275 },572 HP{ .val = 1.000000e-258, .off = 4.577819683828225398e-275 },
573 HP{.val=1.000000e-259, .off= -6.975424321706684210e-276 },573 HP{ .val = 1.000000e-259, .off = -6.975424321706684210e-276 },
574 HP{.val=1.000000e-260, .off= 3.855741933482293648e-277 },574 HP{ .val = 1.000000e-260, .off = 3.855741933482293648e-277 },
575 HP{.val=1.000000e-261, .off= 1.599248963651256552e-278 },575 HP{ .val = 1.000000e-261, .off = 1.599248963651256552e-278 },
576 HP{.val=1.000000e-262, .off= -1.221367248637539543e-279 },576 HP{ .val = 1.000000e-262, .off = -1.221367248637539543e-279 },
577 HP{.val=1.000000e-263, .off= -1.221367248637539494e-280 },577 HP{ .val = 1.000000e-263, .off = -1.221367248637539494e-280 },
578 HP{.val=1.000000e-264, .off= -1.221367248637539647e-281 },578 HP{ .val = 1.000000e-264, .off = -1.221367248637539647e-281 },
579 HP{.val=1.000000e-265, .off= 1.533140771175737943e-282 },579 HP{ .val = 1.000000e-265, .off = 1.533140771175737943e-282 },
580 HP{.val=1.000000e-266, .off= 1.533140771175737895e-283 },580 HP{ .val = 1.000000e-266, .off = 1.533140771175737895e-283 },
581 HP{.val=1.000000e-267, .off= 1.533140771175738074e-284 },581 HP{ .val = 1.000000e-267, .off = 1.533140771175738074e-284 },
582 HP{.val=1.000000e-268, .off= 4.223090009274641634e-285 },582 HP{ .val = 1.000000e-268, .off = 4.223090009274641634e-285 },
583 HP{.val=1.000000e-269, .off= 4.223090009274641634e-286 },583 HP{ .val = 1.000000e-269, .off = 4.223090009274641634e-286 },
584 HP{.val=1.000000e-270, .off= -4.183001359784432924e-287 },584 HP{ .val = 1.000000e-270, .off = -4.183001359784432924e-287 },
585 HP{.val=1.000000e-271, .off= 3.697709298708449474e-288 },585 HP{ .val = 1.000000e-271, .off = 3.697709298708449474e-288 },
586 HP{.val=1.000000e-272, .off= 6.981338739747150474e-289 },586 HP{ .val = 1.000000e-272, .off = 6.981338739747150474e-289 },
587 HP{.val=1.000000e-273, .off= -9.436808465446354751e-290 },587 HP{ .val = 1.000000e-273, .off = -9.436808465446354751e-290 },
588 HP{.val=1.000000e-274, .off= 3.389869038611071740e-291 },588 HP{ .val = 1.000000e-274, .off = 3.389869038611071740e-291 },
589 HP{.val=1.000000e-275, .off= 6.596538414625427829e-292 },589 HP{ .val = 1.000000e-275, .off = 6.596538414625427829e-292 },
590 HP{.val=1.000000e-276, .off= -9.436808465446354618e-293 },590 HP{ .val = 1.000000e-276, .off = -9.436808465446354618e-293 },
591 HP{.val=1.000000e-277, .off= 3.089243784609725523e-294 },591 HP{ .val = 1.000000e-277, .off = 3.089243784609725523e-294 },
592 HP{.val=1.000000e-278, .off= 6.220756847123745836e-295 },592 HP{ .val = 1.000000e-278, .off = 6.220756847123745836e-295 },
593 HP{.val=1.000000e-279, .off= -5.522417137303829470e-296 },593 HP{ .val = 1.000000e-279, .off = -5.522417137303829470e-296 },
594 HP{.val=1.000000e-280, .off= 4.263561183052483059e-297 },594 HP{ .val = 1.000000e-280, .off = 4.263561183052483059e-297 },
595 HP{.val=1.000000e-281, .off= -1.852675267170212272e-298 },595 HP{ .val = 1.000000e-281, .off = -1.852675267170212272e-298 },
596 HP{.val=1.000000e-282, .off= -1.852675267170212378e-299 },596 HP{ .val = 1.000000e-282, .off = -1.852675267170212378e-299 },
597 HP{.val=1.000000e-283, .off= 5.314789322934508480e-300 },597 HP{ .val = 1.000000e-283, .off = 5.314789322934508480e-300 },
598 HP{.val=1.000000e-284, .off= -3.644541414696392675e-301 },598 HP{ .val = 1.000000e-284, .off = -3.644541414696392675e-301 },
599 HP{.val=1.000000e-285, .off= -7.377595888709267777e-302 },599 HP{ .val = 1.000000e-285, .off = -7.377595888709267777e-302 },
600 HP{.val=1.000000e-286, .off= -5.044436842451220838e-303 },600 HP{ .val = 1.000000e-286, .off = -5.044436842451220838e-303 },
601 HP{.val=1.000000e-287, .off= -2.127988034628661760e-304 },601 HP{ .val = 1.000000e-287, .off = -2.127988034628661760e-304 },
602 HP{.val=1.000000e-288, .off= -5.773549044406860911e-305 },602 HP{ .val = 1.000000e-288, .off = -5.773549044406860911e-305 },
603 HP{.val=1.000000e-289, .off= -1.216597782184112068e-306 },603 HP{ .val = 1.000000e-289, .off = -1.216597782184112068e-306 },
604 HP{.val=1.000000e-290, .off= -6.912786859962547924e-307 },604 HP{ .val = 1.000000e-290, .off = -6.912786859962547924e-307 },
605 HP{.val=1.000000e-291, .off= 3.767567660872018813e-308 },605 HP{ .val = 1.000000e-291, .off = 3.767567660872018813e-308 },
606};606};
std/fmt/index.zig+53-47
...@@ -11,7 +11,7 @@ const max_int_digits = 65;...@@ -11,7 +11,7 @@ const max_int_digits = 65;
11/// Renders fmt string with args, calling output with slices of bytes.11/// Renders fmt string with args, calling output with slices of bytes.
12/// If `output` returns an error, the error is returned from `format` and12/// If `output` returns an error, the error is returned from `format` and
13/// `output` is not called again.13/// `output` is not called again.
14pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void, comptime fmt: []const u8, args: ...) Errors!void {14pub fn format(context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void, comptime fmt: []const u8, args: ...) Errors!void {
15 const State = enum {15 const State = enum {
16 Start,16 Start,
17 OpenBrace,17 OpenBrace,
...@@ -107,7 +107,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -107,7 +107,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
107 '}' => {107 '}' => {
108 return output(context, args[next_arg]);108 return output(context, args[next_arg]);
109 },109 },
110 '0' ... '9' => {110 '0'...'9' => {
111 width_start = i;111 width_start = i;
112 state = State.BufWidth;112 state = State.BufWidth;
113 },113 },
...@@ -127,7 +127,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -127,7 +127,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
127 state = State.Start;127 state = State.Start;
128 start_index = i + 1;128 start_index = i + 1;
129 },129 },
130 '0' ... '9' => {130 '0'...'9' => {
131 width_start = i;131 width_start = i;
132 state = State.IntegerWidth;132 state = State.IntegerWidth;
133 },133 },
...@@ -141,7 +141,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -141,7 +141,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
141 state = State.Start;141 state = State.Start;
142 start_index = i + 1;142 start_index = i + 1;
143 },143 },
144 '0' ... '9' => {},144 '0'...'9' => {},
145 else => @compileError("Unexpected character in format string: " ++ []u8{c}),145 else => @compileError("Unexpected character in format string: " ++ []u8{c}),
146 },146 },
147 State.FloatScientific => switch (c) {147 State.FloatScientific => switch (c) {
...@@ -151,7 +151,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -151,7 +151,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
151 state = State.Start;151 state = State.Start;
152 start_index = i + 1;152 start_index = i + 1;
153 },153 },
154 '0' ... '9' => {154 '0'...'9' => {
155 width_start = i;155 width_start = i;
156 state = State.FloatScientificWidth;156 state = State.FloatScientificWidth;
157 },157 },
...@@ -165,7 +165,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -165,7 +165,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
165 state = State.Start;165 state = State.Start;
166 start_index = i + 1;166 start_index = i + 1;
167 },167 },
168 '0' ... '9' => {},168 '0'...'9' => {},
169 else => @compileError("Unexpected character in format string: " ++ []u8{c}),169 else => @compileError("Unexpected character in format string: " ++ []u8{c}),
170 },170 },
171 State.Float => switch (c) {171 State.Float => switch (c) {
...@@ -175,7 +175,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -175,7 +175,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
175 state = State.Start;175 state = State.Start;
176 start_index = i + 1;176 start_index = i + 1;
177 },177 },
178 '0' ... '9' => {178 '0'...'9' => {
179 width_start = i;179 width_start = i;
180 state = State.FloatWidth;180 state = State.FloatWidth;
181 },181 },
...@@ -189,7 +189,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -189,7 +189,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
189 state = State.Start;189 state = State.Start;
190 start_index = i + 1;190 start_index = i + 1;
191 },191 },
192 '0' ... '9' => {},192 '0'...'9' => {},
193 else => @compileError("Unexpected character in format string: " ++ []u8{c}),193 else => @compileError("Unexpected character in format string: " ++ []u8{c}),
194 },194 },
195 State.BufWidth => switch (c) {195 State.BufWidth => switch (c) {
...@@ -200,7 +200,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -200,7 +200,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
200 state = State.Start;200 state = State.Start;
201 start_index = i + 1;201 start_index = i + 1;
202 },202 },
203 '0' ... '9' => {},203 '0'...'9' => {},
204 else => @compileError("Unexpected character in format string: " ++ []u8{c}),204 else => @compileError("Unexpected character in format string: " ++ []u8{c}),
205 },205 },
206 State.Character => switch (c) {206 State.Character => switch (c) {
...@@ -223,7 +223,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -223,7 +223,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
223 radix = 1024;223 radix = 1024;
224 state = State.BytesBase;224 state = State.BytesBase;
225 },225 },
226 '0' ... '9' => {226 '0'...'9' => {
227 width_start = i;227 width_start = i;
228 state = State.BytesWidth;228 state = State.BytesWidth;
229 },229 },
...@@ -236,7 +236,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -236,7 +236,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
236 state = State.Start;236 state = State.Start;
237 start_index = i + 1;237 start_index = i + 1;
238 },238 },
239 '0' ... '9' => {239 '0'...'9' => {
240 width_start = i;240 width_start = i;
241 state = State.BytesWidth;241 state = State.BytesWidth;
242 },242 },
...@@ -250,7 +250,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -250,7 +250,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
250 state = State.Start;250 state = State.Start;
251 start_index = i + 1;251 start_index = i + 1;
252 },252 },
253 '0' ... '9' => {},253 '0'...'9' => {},
254 else => @compileError("Unexpected character in format string: " ++ []u8{c}),254 else => @compileError("Unexpected character in format string: " ++ []u8{c}),
255 },255 },
256 }256 }
...@@ -268,7 +268,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),...@@ -268,7 +268,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context),
268 }268 }
269}269}
270270
271pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void {271pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void {
272 const T = @typeOf(value);272 const T = @typeOf(value);
273 switch (@typeId(T)) {273 switch (@typeId(T)) {
274 builtin.TypeId.Int => {274 builtin.TypeId.Int => {
...@@ -317,11 +317,11 @@ pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@...@@ -317,11 +317,11 @@ pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@
317 }317 }
318}318}
319319
320pub fn formatAsciiChar(c: u8, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void {320pub fn formatAsciiChar(c: u8, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void {
321 return output(context, (&c)[0..1]);321 return output(context, (&c)[0..1]);
322}322}
323323
324pub fn formatBuf(buf: []const u8, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void {324pub fn formatBuf(buf: []const u8, width: usize, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void {
325 try output(context, buf);325 try output(context, buf);
326326
327 var leftover_padding = if (width > buf.len) (width - buf.len) else return;327 var leftover_padding = if (width > buf.len) (width - buf.len) else return;
...@@ -334,7 +334,7 @@ pub fn formatBuf(buf: []const u8, width: usize, context: var, comptime Errors: t...@@ -334,7 +334,7 @@ pub fn formatBuf(buf: []const u8, width: usize, context: var, comptime Errors: t
334// Print a float in scientific notation to the specified precision. Null uses full precision.334// Print a float in scientific notation to the specified precision. Null uses full precision.
335// It should be the case that every full precision, printed value can be re-parsed back to the335// It should be the case that every full precision, printed value can be re-parsed back to the
336// same type unambiguously.336// same type unambiguously.
337pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void {337pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void {
338 var x = f64(value);338 var x = f64(value);
339339
340 // Errol doesn't handle these special cases.340 // Errol doesn't handle these special cases.
...@@ -423,7 +423,7 @@ pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var,...@@ -423,7 +423,7 @@ pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var,
423423
424// Print a float of the format x.yyyyy where the number of y is specified by the precision argument.424// Print a float of the format x.yyyyy where the number of y is specified by the precision argument.
425// By default floats are printed at full precision (no rounding).425// By default floats are printed at full precision (no rounding).
426pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void {426pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void {
427 var x = f64(value);427 var x = f64(value);
428428
429 // Errol doesn't handle these special cases.429 // Errol doesn't handle these special cases.
...@@ -512,7 +512,7 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com...@@ -512,7 +512,7 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com
512 // Remaining fractional portion, zero-padding if insufficient.512 // Remaining fractional portion, zero-padding if insufficient.
513 debug.assert(precision >= printed);513 debug.assert(precision >= printed);
514 if (num_digits_whole_no_pad + precision - printed < float_decimal.digits.len) {514 if (num_digits_whole_no_pad + precision - printed < float_decimal.digits.len) {
515 try output(context, float_decimal.digits[num_digits_whole_no_pad..num_digits_whole_no_pad + precision - printed]);515 try output(context, float_decimal.digits[num_digits_whole_no_pad .. num_digits_whole_no_pad + precision - printed]);
516 return;516 return;
517 } else {517 } else {
518 try output(context, float_decimal.digits[num_digits_whole_no_pad..]);518 try output(context, float_decimal.digits[num_digits_whole_no_pad..]);
...@@ -562,9 +562,14 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com...@@ -562,9 +562,14 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com
562 }562 }
563}563}
564564
565pub fn formatBytes(value: var, width: ?usize, comptime radix: usize,565pub fn formatBytes(
566 context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void566 value: var,
567{567 width: ?usize,
568 comptime radix: usize,
569 context: var,
570 comptime Errors: type,
571 output: fn (@typeOf(context), []const u8) Errors!void,
572) Errors!void {
568 if (value == 0) {573 if (value == 0) {
569 return output(context, "0B");574 return output(context, "0B");
570 }575 }
...@@ -585,16 +590,22 @@ pub fn formatBytes(value: var, width: ?usize, comptime radix: usize,...@@ -585,16 +590,22 @@ pub fn formatBytes(value: var, width: ?usize, comptime radix: usize,
585 }590 }
586591
587 const buf = switch (radix) {592 const buf = switch (radix) {
588 1000 => []u8 { suffix, 'B' },593 1000 => []u8{ suffix, 'B' },
589 1024 => []u8 { suffix, 'i', 'B' },594 1024 => []u8{ suffix, 'i', 'B' },
590 else => unreachable,595 else => unreachable,
591 };596 };
592 return output(context, buf);597 return output(context, buf);
593}598}
594599
595pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize,600pub fn formatInt(
596 context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void601 value: var,
597{602 base: u8,
603 uppercase: bool,
604 width: usize,
605 context: var,
606 comptime Errors: type,
607 output: fn (@typeOf(context), []const u8) Errors!void,
608) Errors!void {
598 if (@typeOf(value).is_signed) {609 if (@typeOf(value).is_signed) {
599 return formatIntSigned(value, base, uppercase, width, context, Errors, output);610 return formatIntSigned(value, base, uppercase, width, context, Errors, output);
600 } else {611 } else {
...@@ -602,7 +613,7 @@ pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize,...@@ -602,7 +613,7 @@ pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize,
602 }613 }
603}614}
604615
605fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void {616fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void {
606 const uint = @IntType(false, @typeOf(value).bit_count);617 const uint = @IntType(false, @typeOf(value).bit_count);
607 if (value < 0) {618 if (value < 0) {
608 const minus_sign: u8 = '-';619 const minus_sign: u8 = '-';
...@@ -621,7 +632,7 @@ fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, context:...@@ -621,7 +632,7 @@ fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, context:
621 }632 }
622}633}
623634
624fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void {635fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void {
625 // max_int_digits accounts for the minus sign. when printing an unsigned636 // max_int_digits accounts for the minus sign. when printing an unsigned
626 // number we don't need to do that.637 // number we don't need to do that.
627 var buf: [max_int_digits - 1]u8 = undefined;638 var buf: [max_int_digits - 1]u8 = undefined;
...@@ -650,7 +661,7 @@ fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, contex...@@ -650,7 +661,7 @@ fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, contex
650 mem.set(u8, buf[0..index], '0');661 mem.set(u8, buf[0..index], '0');
651 return output(context, buf);662 return output(context, buf);
652 } else {663 } else {
653 const padded_buf = buf[index - padding..];664 const padded_buf = buf[index - padding ..];
654 mem.set(u8, padded_buf[0..padding], '0');665 mem.set(u8, padded_buf[0..padding], '0');
655 return output(context, padded_buf);666 return output(context, padded_buf);
656 }667 }
...@@ -668,7 +679,7 @@ const FormatIntBuf = struct {...@@ -668,7 +679,7 @@ const FormatIntBuf = struct {
668 out_buf: []u8,679 out_buf: []u8,
669 index: usize,680 index: usize,
670};681};
671fn formatIntCallback(context: &FormatIntBuf, bytes: []const u8) (error{}!void) {682fn formatIntCallback(context: *FormatIntBuf, bytes: []const u8) (error{}!void) {
672 mem.copy(u8, context.out_buf[context.index..], bytes);683 mem.copy(u8, context.out_buf[context.index..], bytes);
673 context.index += bytes.len;684 context.index += bytes.len;
674}685}
...@@ -717,9 +728,9 @@ pub fn parseUnsigned(comptime T: type, buf: []const u8, radix: u8) ParseUnsigned...@@ -717,9 +728,9 @@ pub fn parseUnsigned(comptime T: type, buf: []const u8, radix: u8) ParseUnsigned
717728
718pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) {729pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) {
719 const value = switch (c) {730 const value = switch (c) {
720 '0' ... '9' => c - '0',731 '0'...'9' => c - '0',
721 'A' ... 'Z' => c - 'A' + 10,732 'A'...'Z' => c - 'A' + 10,
722 'a' ... 'z' => c - 'a' + 10,733 'a'...'z' => c - 'a' + 10,
723 else => return error.InvalidCharacter,734 else => return error.InvalidCharacter,
724 };735 };
725736
...@@ -730,8 +741,8 @@ pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) {...@@ -730,8 +741,8 @@ pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) {
730741
731fn digitToChar(digit: u8, uppercase: bool) u8 {742fn digitToChar(digit: u8, uppercase: bool) u8 {
732 return switch (digit) {743 return switch (digit) {
733 0 ... 9 => digit + '0',744 0...9 => digit + '0',
734 10 ... 35 => digit + ((if (uppercase) u8('A') else u8('a')) - 10),745 10...35 => digit + ((if (uppercase) u8('A') else u8('a')) - 10),
735 else => unreachable,746 else => unreachable,
736 };747 };
737}748}
...@@ -740,7 +751,7 @@ const BufPrintContext = struct {...@@ -740,7 +751,7 @@ const BufPrintContext = struct {
740 remaining: []u8,751 remaining: []u8,
741};752};
742753
743fn bufPrintWrite(context: &BufPrintContext, bytes: []const u8) !void {754fn bufPrintWrite(context: *BufPrintContext, bytes: []const u8) !void {
744 if (context.remaining.len < bytes.len) return error.BufferTooSmall;755 if (context.remaining.len < bytes.len) return error.BufferTooSmall;
745 mem.copy(u8, context.remaining, bytes);756 mem.copy(u8, context.remaining, bytes);
746 context.remaining = context.remaining[bytes.len..];757 context.remaining = context.remaining[bytes.len..];
...@@ -749,18 +760,17 @@ fn bufPrintWrite(context: &BufPrintContext, bytes: []const u8) !void {...@@ -749,18 +760,17 @@ fn bufPrintWrite(context: &BufPrintContext, bytes: []const u8) !void {
749pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: ...) ![]u8 {760pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: ...) ![]u8 {
750 var context = BufPrintContext{ .remaining = buf };761 var context = BufPrintContext{ .remaining = buf };
751 try format(&context, error{BufferTooSmall}, bufPrintWrite, fmt, args);762 try format(&context, error{BufferTooSmall}, bufPrintWrite, fmt, args);
752 return buf[0..buf.len - context.remaining.len];763 return buf[0 .. buf.len - context.remaining.len];
753}764}
754765
755pub fn allocPrint(allocator: &mem.Allocator, comptime fmt: []const u8, args: ...) ![]u8 {766pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: ...) ![]u8 {
756 var size: usize = 0;767 var size: usize = 0;
757 format(&size, error{}, countSize, fmt, args) catch |err| switch (err) {768 format(&size, error{}, countSize, fmt, args) catch |err| switch (err) {};
758 };
759 const buf = try allocator.alloc(u8, size);769 const buf = try allocator.alloc(u8, size);
760 return bufPrint(buf, fmt, args);770 return bufPrint(buf, fmt, args);
761}771}
762772
763fn countSize(size: &usize, bytes: []const u8) (error{}!void) {773fn countSize(size: *usize, bytes: []const u8) (error{}!void) {
764 size.* += bytes.len;774 size.* += bytes.len;
765}775}
766776
...@@ -1043,8 +1053,7 @@ test "fmt.format" {...@@ -1043,8 +1053,7 @@ test "fmt.format" {
1043fn testFmt(expected: []const u8, comptime template: []const u8, args: ...) !void {1053fn testFmt(expected: []const u8, comptime template: []const u8, args: ...) !void {
1044 var buf: [100]u8 = undefined;1054 var buf: [100]u8 = undefined;
1045 const result = try bufPrint(buf[0..], template, args);1055 const result = try bufPrint(buf[0..], template, args);
1046 if (mem.eql(u8, result, expected))1056 if (mem.eql(u8, result, expected)) return;
1047 return;
10481057
1049 std.debug.warn("\n====== expected this output: =========\n");1058 std.debug.warn("\n====== expected this output: =========\n");
1050 std.debug.warn("{}", expected);1059 std.debug.warn("{}", expected);
...@@ -1082,10 +1091,7 @@ test "fmt.trim" {...@@ -1082,10 +1091,7 @@ test "fmt.trim" {
10821091
1083pub fn isWhiteSpace(byte: u8) bool {1092pub fn isWhiteSpace(byte: u8) bool {
1084 return switch (byte) {1093 return switch (byte) {
1085 ' ',1094 ' ', '\t', '\n', '\r' => true,
1086 '\t',
1087 '\n',
1088 '\r' => true,
1089 else => false,1095 else => false,
1090 };1096 };
1091}1097}
std/hash/adler.zig+8-13
...@@ -13,14 +13,12 @@ pub const Adler32 = struct {...@@ -13,14 +13,12 @@ pub const Adler32 = struct {
13 adler: u32,13 adler: u32,
1414
15 pub fn init() Adler32 {15 pub fn init() Adler32 {
16 return Adler32 {16 return Adler32{ .adler = 1 };
17 .adler = 1,
18 };
19 }17 }
2018
21 // This fast variant is taken from zlib. It reduces the required modulos and unrolls longer19 // This fast variant is taken from zlib. It reduces the required modulos and unrolls longer
22 // buffer inputs and should be much quicker.20 // buffer inputs and should be much quicker.
23 pub fn update(self: &Adler32, input: []const u8) void {21 pub fn update(self: *Adler32, input: []const u8) void {
24 var s1 = self.adler & 0xffff;22 var s1 = self.adler & 0xffff;
25 var s2 = (self.adler >> 16) & 0xffff;23 var s2 = (self.adler >> 16) & 0xffff;
2624
...@@ -33,8 +31,7 @@ pub const Adler32 = struct {...@@ -33,8 +31,7 @@ pub const Adler32 = struct {
33 if (s2 >= base) {31 if (s2 >= base) {
34 s2 -= base;32 s2 -= base;
35 }33 }
36 }34 } else if (input.len < 16) {
37 else if (input.len < 16) {
38 for (input) |b| {35 for (input) |b| {
39 s1 +%= b;36 s1 +%= b;
40 s2 +%= s1;37 s2 +%= s1;
...@@ -44,8 +41,7 @@ pub const Adler32 = struct {...@@ -44,8 +41,7 @@ pub const Adler32 = struct {
44 }41 }
4542
46 s2 %= base;43 s2 %= base;
47 }44 } else {
48 else {
49 var i: usize = 0;45 var i: usize = 0;
50 while (i + nmax <= input.len) : (i += nmax) {46 while (i + nmax <= input.len) : (i += nmax) {
51 const n = nmax / 16; // note: 16 | nmax47 const n = nmax / 16; // note: 16 | nmax
...@@ -81,7 +77,7 @@ pub const Adler32 = struct {...@@ -81,7 +77,7 @@ pub const Adler32 = struct {
81 self.adler = s1 | (s2 << 16);77 self.adler = s1 | (s2 << 16);
82 }78 }
8379
84 pub fn final(self: &Adler32) u32 {80 pub fn final(self: *Adler32) u32 {
85 return self.adler;81 return self.adler;
86 }82 }
8783
...@@ -98,15 +94,14 @@ test "adler32 sanity" {...@@ -98,15 +94,14 @@ test "adler32 sanity" {
98}94}
9995
100test "adler32 long" {96test "adler32 long" {
101 const long1 = []u8 {1} ** 1024;97 const long1 = []u8{1} ** 1024;
102 debug.assert(Adler32.hash(long1[0..]) == 0x06780401);98 debug.assert(Adler32.hash(long1[0..]) == 0x06780401);
10399
104 const long2 = []u8 {1} ** 1025;100 const long2 = []u8{1} ** 1025;
105 debug.assert(Adler32.hash(long2[0..]) == 0x0a7a0402);101 debug.assert(Adler32.hash(long2[0..]) == 0x0a7a0402);
106}102}
107103
108test "adler32 very long" {104test "adler32 very long" {
109 const long = []u8 {1} ** 5553;105 const long = []u8{1} ** 5553;
110 debug.assert(Adler32.hash(long[0..]) == 0x707f15b2);106 debug.assert(Adler32.hash(long[0..]) == 0x707f15b2);
111}107}
112
std/hash/crc.zig+7-8
...@@ -58,10 +58,10 @@ pub fn Crc32WithPoly(comptime poly: u32) type {...@@ -58,10 +58,10 @@ pub fn Crc32WithPoly(comptime poly: u32) type {
58 return Self{ .crc = 0xffffffff };58 return Self{ .crc = 0xffffffff };
59 }59 }
6060
61 pub fn update(self: &Self, input: []const u8) void {61 pub fn update(self: *Self, input: []const u8) void {
62 var i: usize = 0;62 var i: usize = 0;
63 while (i + 8 <= input.len) : (i += 8) {63 while (i + 8 <= input.len) : (i += 8) {
64 const p = input[i..i + 8];64 const p = input[i .. i + 8];
6565
66 // Unrolling this way gives ~50Mb/s increase66 // Unrolling this way gives ~50Mb/s increase
67 self.crc ^= (u32(p[0]) << 0);67 self.crc ^= (u32(p[0]) << 0);
...@@ -69,7 +69,6 @@ pub fn Crc32WithPoly(comptime poly: u32) type {...@@ -69,7 +69,6 @@ pub fn Crc32WithPoly(comptime poly: u32) type {
69 self.crc ^= (u32(p[2]) << 16);69 self.crc ^= (u32(p[2]) << 16);
70 self.crc ^= (u32(p[3]) << 24);70 self.crc ^= (u32(p[3]) << 24);
7171
72
73 self.crc =72 self.crc =
74 lookup_tables[0][p[7]] ^73 lookup_tables[0][p[7]] ^
75 lookup_tables[1][p[6]] ^74 lookup_tables[1][p[6]] ^
...@@ -77,8 +76,8 @@ pub fn Crc32WithPoly(comptime poly: u32) type {...@@ -77,8 +76,8 @@ pub fn Crc32WithPoly(comptime poly: u32) type {
77 lookup_tables[3][p[4]] ^76 lookup_tables[3][p[4]] ^
78 lookup_tables[4][@truncate(u8, self.crc >> 24)] ^77 lookup_tables[4][@truncate(u8, self.crc >> 24)] ^
79 lookup_tables[5][@truncate(u8, self.crc >> 16)] ^78 lookup_tables[5][@truncate(u8, self.crc >> 16)] ^
80 lookup_tables[6][@truncate(u8, self.crc >> 8)] ^79 lookup_tables[6][@truncate(u8, self.crc >> 8)] ^
81 lookup_tables[7][@truncate(u8, self.crc >> 0)];80 lookup_tables[7][@truncate(u8, self.crc >> 0)];
82 }81 }
8382
84 while (i < input.len) : (i += 1) {83 while (i < input.len) : (i += 1) {
...@@ -87,7 +86,7 @@ pub fn Crc32WithPoly(comptime poly: u32) type {...@@ -87,7 +86,7 @@ pub fn Crc32WithPoly(comptime poly: u32) type {
87 }86 }
88 }87 }
8988
90 pub fn final(self: &Self) u32 {89 pub fn final(self: *Self) u32 {
91 return ~self.crc;90 return ~self.crc;
92 }91 }
9392
...@@ -144,14 +143,14 @@ pub fn Crc32SmallWithPoly(comptime poly: u32) type {...@@ -144,14 +143,14 @@ pub fn Crc32SmallWithPoly(comptime poly: u32) type {
144 return Self{ .crc = 0xffffffff };143 return Self{ .crc = 0xffffffff };
145 }144 }
146145
147 pub fn update(self: &Self, input: []const u8) void {146 pub fn update(self: *Self, input: []const u8) void {
148 for (input) |b| {147 for (input) |b| {
149 self.crc = lookup_table[@truncate(u4, self.crc ^ (b >> 0))] ^ (self.crc >> 4);148 self.crc = lookup_table[@truncate(u4, self.crc ^ (b >> 0))] ^ (self.crc >> 4);
150 self.crc = lookup_table[@truncate(u4, self.crc ^ (b >> 4))] ^ (self.crc >> 4);149 self.crc = lookup_table[@truncate(u4, self.crc ^ (b >> 4))] ^ (self.crc >> 4);
151 }150 }
152 }151 }
153152
154 pub fn final(self: &Self) u32 {153 pub fn final(self: *Self) u32 {
155 return ~self.crc;154 return ~self.crc;
156 }155 }
157156
std/hash/fnv.zig+4-6
...@@ -7,7 +7,7 @@...@@ -7,7 +7,7 @@
7const std = @import("../index.zig");7const std = @import("../index.zig");
8const debug = std.debug;8const debug = std.debug;
99
10pub const Fnv1a_32 = Fnv1a(u32, 0x01000193 , 0x811c9dc5);10pub const Fnv1a_32 = Fnv1a(u32, 0x01000193, 0x811c9dc5);
11pub const Fnv1a_64 = Fnv1a(u64, 0x100000001b3, 0xcbf29ce484222325);11pub const Fnv1a_64 = Fnv1a(u64, 0x100000001b3, 0xcbf29ce484222325);
12pub const Fnv1a_128 = Fnv1a(u128, 0x1000000000000000000013b, 0x6c62272e07bb014262b821756295c58d);12pub const Fnv1a_128 = Fnv1a(u128, 0x1000000000000000000013b, 0x6c62272e07bb014262b821756295c58d);
1313
...@@ -18,19 +18,17 @@ fn Fnv1a(comptime T: type, comptime prime: T, comptime offset: T) type {...@@ -18,19 +18,17 @@ fn Fnv1a(comptime T: type, comptime prime: T, comptime offset: T) type {
18 value: T,18 value: T,
1919
20 pub fn init() Self {20 pub fn init() Self {
21 return Self {21 return Self{ .value = offset };
22 .value = offset,
23 };
24 }22 }
2523
26 pub fn update(self: &Self, input: []const u8) void {24 pub fn update(self: *Self, input: []const u8) void {
27 for (input) |b| {25 for (input) |b| {
28 self.value ^= b;26 self.value ^= b;
29 self.value *%= prime;27 self.value *%= prime;
30 }28 }
31 }29 }
3230
33 pub fn final(self: &Self) T {31 pub fn final(self: *Self) T {
34 return self.value;32 return self.value;
35 }33 }
3634
std/hash/siphash.zig+8-8
...@@ -45,7 +45,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)...@@ -45,7 +45,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)
45 const k0 = mem.readInt(key[0..8], u64, Endian.Little);45 const k0 = mem.readInt(key[0..8], u64, Endian.Little);
46 const k1 = mem.readInt(key[8..16], u64, Endian.Little);46 const k1 = mem.readInt(key[8..16], u64, Endian.Little);
4747
48 var d = Self {48 var d = Self{
49 .v0 = k0 ^ 0x736f6d6570736575,49 .v0 = k0 ^ 0x736f6d6570736575,
50 .v1 = k1 ^ 0x646f72616e646f6d,50 .v1 = k1 ^ 0x646f72616e646f6d,
51 .v2 = k0 ^ 0x6c7967656e657261,51 .v2 = k0 ^ 0x6c7967656e657261,
...@@ -63,7 +63,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)...@@ -63,7 +63,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)
63 return d;63 return d;
64 }64 }
6565
66 pub fn update(d: &Self, b: []const u8) void {66 pub fn update(d: *Self, b: []const u8) void {
67 var off: usize = 0;67 var off: usize = 0;
6868
69 // Partial from previous.69 // Partial from previous.
...@@ -76,7 +76,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)...@@ -76,7 +76,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)
7676
77 // Full middle blocks.77 // Full middle blocks.
78 while (off + 8 <= b.len) : (off += 8) {78 while (off + 8 <= b.len) : (off += 8) {
79 d.round(b[off..off + 8]);79 d.round(b[off .. off + 8]);
80 }80 }
8181
82 // Remainder for next pass.82 // Remainder for next pass.
...@@ -85,7 +85,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)...@@ -85,7 +85,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)
85 d.msg_len +%= @truncate(u8, b.len);85 d.msg_len +%= @truncate(u8, b.len);
86 }86 }
8787
88 pub fn final(d: &Self) T {88 pub fn final(d: *Self) T {
89 // Padding89 // Padding
90 mem.set(u8, d.buf[d.buf_len..], 0);90 mem.set(u8, d.buf[d.buf_len..], 0);
91 d.buf[7] = d.msg_len;91 d.buf[7] = d.msg_len;
...@@ -118,7 +118,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)...@@ -118,7 +118,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)
118 return (u128(b2) << 64) | b1;118 return (u128(b2) << 64) | b1;
119 }119 }
120120
121 fn round(d: &Self, b: []const u8) void {121 fn round(d: *Self, b: []const u8) void {
122 debug.assert(b.len == 8);122 debug.assert(b.len == 8);
123123
124 const m = mem.readInt(b[0..], u64, Endian.Little);124 const m = mem.readInt(b[0..], u64, Endian.Little);
...@@ -132,7 +132,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)...@@ -132,7 +132,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)
132 d.v0 ^= m;132 d.v0 ^= m;
133 }133 }
134134
135 fn sipRound(d: &Self) void {135 fn sipRound(d: *Self) void {
136 d.v0 +%= d.v1;136 d.v0 +%= d.v1;
137 d.v1 = math.rotl(u64, d.v1, u64(13));137 d.v1 = math.rotl(u64, d.v1, u64(13));
138 d.v1 ^= d.v0;138 d.v1 ^= d.v0;
...@@ -162,7 +162,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)...@@ -162,7 +162,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)
162const test_key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f";162const test_key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f";
163163
164test "siphash64-2-4 sanity" {164test "siphash64-2-4 sanity" {
165 const vectors = [][]const u8 {165 const vectors = [][]const u8{
166 "\x31\x0e\x0e\xdd\x47\xdb\x6f\x72", // ""166 "\x31\x0e\x0e\xdd\x47\xdb\x6f\x72", // ""
167 "\xfd\x67\xdc\x93\xc5\x39\xf8\x74", // "\x00"167 "\xfd\x67\xdc\x93\xc5\x39\xf8\x74", // "\x00"
168 "\x5a\x4f\xa9\xd9\x09\x80\x6c\x0d", // "\x00\x01" ... etc168 "\x5a\x4f\xa9\xd9\x09\x80\x6c\x0d", // "\x00\x01" ... etc
...@@ -241,7 +241,7 @@ test "siphash64-2-4 sanity" {...@@ -241,7 +241,7 @@ test "siphash64-2-4 sanity" {
241}241}
242242
243test "siphash128-2-4 sanity" {243test "siphash128-2-4 sanity" {
244 const vectors = [][]const u8 {244 const vectors = [][]const u8{
245 "\xa3\x81\x7f\x04\xba\x25\xa8\xe6\x6d\xf6\x72\x14\xc7\x55\x02\x93",245 "\xa3\x81\x7f\x04\xba\x25\xa8\xe6\x6d\xf6\x72\x14\xc7\x55\x02\x93",
246 "\xda\x87\xc1\xd8\x6b\x99\xaf\x44\x34\x76\x59\x11\x9b\x22\xfc\x45",246 "\xda\x87\xc1\xd8\x6b\x99\xaf\x44\x34\x76\x59\x11\x9b\x22\xfc\x45",
247 "\x81\x77\x22\x8d\xa4\xa4\x5d\xc7\xfc\xa3\x8b\xde\xf6\x0a\xff\xe4",247 "\x81\x77\x22\x8d\xa4\xa4\x5d\xc7\xfc\xa3\x8b\xde\xf6\x0a\xff\xe4",
std/hash_map.zig+19-19
...@@ -9,12 +9,12 @@ const builtin = @import("builtin");...@@ -9,12 +9,12 @@ const builtin = @import("builtin");
9const want_modification_safety = builtin.mode != builtin.Mode.ReleaseFast;9const want_modification_safety = builtin.mode != builtin.Mode.ReleaseFast;
10const debug_u32 = if (want_modification_safety) u32 else void;10const debug_u32 = if (want_modification_safety) u32 else void;
1111
12pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32, comptime eql: fn(a: K, b: K) bool) type {12pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u32, comptime eql: fn (a: K, b: K) bool) type {
13 return struct {13 return struct {
14 entries: []Entry,14 entries: []Entry,
15 size: usize,15 size: usize,
16 max_distance_from_start_index: usize,16 max_distance_from_start_index: usize,
17 allocator: &Allocator,17 allocator: *Allocator,
18 // this is used to detect bugs where a hashtable is edited while an iterator is running.18 // this is used to detect bugs where a hashtable is edited while an iterator is running.
19 modification_count: debug_u32,19 modification_count: debug_u32,
2020
...@@ -28,7 +28,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -28,7 +28,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
28 };28 };
2929
30 pub const Iterator = struct {30 pub const Iterator = struct {
31 hm: &const Self,31 hm: *const Self,
32 // how many items have we returned32 // how many items have we returned
33 count: usize,33 count: usize,
34 // iterator through the entry array34 // iterator through the entry array
...@@ -36,7 +36,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -36,7 +36,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
36 // used to detect concurrent modification36 // used to detect concurrent modification
37 initial_modification_count: debug_u32,37 initial_modification_count: debug_u32,
3838
39 pub fn next(it: &Iterator) ?&Entry {39 pub fn next(it: *Iterator) ?*Entry {
40 if (want_modification_safety) {40 if (want_modification_safety) {
41 assert(it.initial_modification_count == it.hm.modification_count); // concurrent modification41 assert(it.initial_modification_count == it.hm.modification_count); // concurrent modification
42 }42 }
...@@ -53,7 +53,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -53,7 +53,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
53 }53 }
5454
55 // Reset the iterator to the initial index55 // Reset the iterator to the initial index
56 pub fn reset(it: &Iterator) void {56 pub fn reset(it: *Iterator) void {
57 it.count = 0;57 it.count = 0;
58 it.index = 0;58 it.index = 0;
59 // Resetting the modification count too59 // Resetting the modification count too
...@@ -61,7 +61,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -61,7 +61,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
61 }61 }
62 };62 };
6363
64 pub fn init(allocator: &Allocator) Self {64 pub fn init(allocator: *Allocator) Self {
65 return Self{65 return Self{
66 .entries = []Entry{},66 .entries = []Entry{},
67 .allocator = allocator,67 .allocator = allocator,
...@@ -71,11 +71,11 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -71,11 +71,11 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
71 };71 };
72 }72 }
7373
74 pub fn deinit(hm: &const Self) void {74 pub fn deinit(hm: *const Self) void {
75 hm.allocator.free(hm.entries);75 hm.allocator.free(hm.entries);
76 }76 }
7777
78 pub fn clear(hm: &Self) void {78 pub fn clear(hm: *Self) void {
79 for (hm.entries) |*entry| {79 for (hm.entries) |*entry| {
80 entry.used = false;80 entry.used = false;
81 }81 }
...@@ -84,12 +84,12 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -84,12 +84,12 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
84 hm.incrementModificationCount();84 hm.incrementModificationCount();
85 }85 }
8686
87 pub fn count(hm: &const Self) usize {87 pub fn count(hm: *const Self) usize {
88 return hm.size;88 return hm.size;
89 }89 }
9090
91 /// Returns the value that was already there.91 /// Returns the value that was already there.
92 pub fn put(hm: &Self, key: K, value: &const V) !?V {92 pub fn put(hm: *Self, key: K, value: *const V) !?V {
93 if (hm.entries.len == 0) {93 if (hm.entries.len == 0) {
94 try hm.initCapacity(16);94 try hm.initCapacity(16);
95 }95 }
...@@ -111,18 +111,18 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -111,18 +111,18 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
111 return hm.internalPut(key, value);111 return hm.internalPut(key, value);
112 }112 }
113113
114 pub fn get(hm: &const Self, key: K) ?&Entry {114 pub fn get(hm: *const Self, key: K) ?*Entry {
115 if (hm.entries.len == 0) {115 if (hm.entries.len == 0) {
116 return null;116 return null;
117 }117 }
118 return hm.internalGet(key);118 return hm.internalGet(key);
119 }119 }
120120
121 pub fn contains(hm: &const Self, key: K) bool {121 pub fn contains(hm: *const Self, key: K) bool {
122 return hm.get(key) != null;122 return hm.get(key) != null;
123 }123 }
124124
125 pub fn remove(hm: &Self, key: K) ?&Entry {125 pub fn remove(hm: *Self, key: K) ?*Entry {
126 if (hm.entries.len == 0) return null;126 if (hm.entries.len == 0) return null;
127 hm.incrementModificationCount();127 hm.incrementModificationCount();
128 const start_index = hm.keyToIndex(key);128 const start_index = hm.keyToIndex(key);
...@@ -154,7 +154,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -154,7 +154,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
154 return null;154 return null;
155 }155 }
156156
157 pub fn iterator(hm: &const Self) Iterator {157 pub fn iterator(hm: *const Self) Iterator {
158 return Iterator{158 return Iterator{
159 .hm = hm,159 .hm = hm,
160 .count = 0,160 .count = 0,
...@@ -163,7 +163,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -163,7 +163,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
163 };163 };
164 }164 }
165165
166 fn initCapacity(hm: &Self, capacity: usize) !void {166 fn initCapacity(hm: *Self, capacity: usize) !void {
167 hm.entries = try hm.allocator.alloc(Entry, capacity);167 hm.entries = try hm.allocator.alloc(Entry, capacity);
168 hm.size = 0;168 hm.size = 0;
169 hm.max_distance_from_start_index = 0;169 hm.max_distance_from_start_index = 0;
...@@ -172,14 +172,14 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -172,14 +172,14 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
172 }172 }
173 }173 }
174174
175 fn incrementModificationCount(hm: &Self) void {175 fn incrementModificationCount(hm: *Self) void {
176 if (want_modification_safety) {176 if (want_modification_safety) {
177 hm.modification_count +%= 1;177 hm.modification_count +%= 1;
178 }178 }
179 }179 }
180180
181 /// Returns the value that was already there.181 /// Returns the value that was already there.
182 fn internalPut(hm: &Self, orig_key: K, orig_value: &const V) ?V {182 fn internalPut(hm: *Self, orig_key: K, orig_value: *const V) ?V {
183 var key = orig_key;183 var key = orig_key;
184 var value = orig_value.*;184 var value = orig_value.*;
185 const start_index = hm.keyToIndex(key);185 const start_index = hm.keyToIndex(key);
...@@ -231,7 +231,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -231,7 +231,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
231 unreachable; // put into a full map231 unreachable; // put into a full map
232 }232 }
233233
234 fn internalGet(hm: &const Self, key: K) ?&Entry {234 fn internalGet(hm: *const Self, key: K) ?*Entry {
235 const start_index = hm.keyToIndex(key);235 const start_index = hm.keyToIndex(key);
236 {236 {
237 var roll_over: usize = 0;237 var roll_over: usize = 0;
...@@ -246,7 +246,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32...@@ -246,7 +246,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32
246 return null;246 return null;
247 }247 }
248248
249 fn keyToIndex(hm: &const Self, key: K) usize {249 fn keyToIndex(hm: *const Self, key: K) usize {
250 return usize(hash(key)) % hm.entries.len;250 return usize(hash(key)) % hm.entries.len;
251 }251 }
252 };252 };
std/heap.zig+46-52
...@@ -16,15 +16,15 @@ var c_allocator_state = Allocator{...@@ -16,15 +16,15 @@ var c_allocator_state = Allocator{
16 .freeFn = cFree,16 .freeFn = cFree,
17};17};
1818
19fn cAlloc(self: &Allocator, n: usize, alignment: u29) ![]u8 {19fn cAlloc(self: *Allocator, n: usize, alignment: u29) ![]u8 {
20 assert(alignment <= @alignOf(c_longdouble));20 assert(alignment <= @alignOf(c_longdouble));
21 return if (c.malloc(n)) |buf| @ptrCast(&u8, buf)[0..n] else error.OutOfMemory;21 return if (c.malloc(n)) |buf| @ptrCast([*]u8, buf)[0..n] else error.OutOfMemory;
22}22}
2323
24fn cRealloc(self: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {24fn cRealloc(self: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {
25 const old_ptr = @ptrCast(&c_void, old_mem.ptr);25 const old_ptr = @ptrCast([*]c_void, old_mem.ptr);
26 if (c.realloc(old_ptr, new_size)) |buf| {26 if (c.realloc(old_ptr, new_size)) |buf| {
27 return @ptrCast(&u8, buf)[0..new_size];27 return @ptrCast(*u8, buf)[0..new_size];
28 } else if (new_size <= old_mem.len) {28 } else if (new_size <= old_mem.len) {
29 return old_mem[0..new_size];29 return old_mem[0..new_size];
30 } else {30 } else {
...@@ -32,8 +32,8 @@ fn cRealloc(self: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![...@@ -32,8 +32,8 @@ fn cRealloc(self: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![
32 }32 }
33}33}
3434
35fn cFree(self: &Allocator, old_mem: []u8) void {35fn cFree(self: *Allocator, old_mem: []u8) void {
36 const old_ptr = @ptrCast(&c_void, old_mem.ptr);36 const old_ptr = @ptrCast([*]c_void, old_mem.ptr);
37 c.free(old_ptr);37 c.free(old_ptr);
38}38}
3939
...@@ -55,7 +55,7 @@ pub const DirectAllocator = struct {...@@ -55,7 +55,7 @@ pub const DirectAllocator = struct {
55 };55 };
56 }56 }
5757
58 pub fn deinit(self: &DirectAllocator) void {58 pub fn deinit(self: *DirectAllocator) void {
59 switch (builtin.os) {59 switch (builtin.os) {
60 Os.windows => if (self.heap_handle) |heap_handle| {60 Os.windows => if (self.heap_handle) |heap_handle| {
61 _ = os.windows.HeapDestroy(heap_handle);61 _ = os.windows.HeapDestroy(heap_handle);
...@@ -64,19 +64,17 @@ pub const DirectAllocator = struct {...@@ -64,19 +64,17 @@ pub const DirectAllocator = struct {
64 }64 }
65 }65 }
6666
67 fn alloc(allocator: &Allocator, n: usize, alignment: u29) ![]u8 {67 fn alloc(allocator: *Allocator, n: usize, alignment: u29) ![]u8 {
68 const self = @fieldParentPtr(DirectAllocator, "allocator", allocator);68 const self = @fieldParentPtr(DirectAllocator, "allocator", allocator);
6969
70 switch (builtin.os) {70 switch (builtin.os) {
71 Os.linux,71 Os.linux, Os.macosx, Os.ios => {
72 Os.macosx,
73 Os.ios => {
74 const p = os.posix;72 const p = os.posix;
75 const alloc_size = if (alignment <= os.page_size) n else n + alignment;73 const alloc_size = if (alignment <= os.page_size) n else n + alignment;
76 const addr = p.mmap(null, alloc_size, p.PROT_READ | p.PROT_WRITE, p.MAP_PRIVATE | p.MAP_ANONYMOUS, -1, 0);74 const addr = p.mmap(null, alloc_size, p.PROT_READ | p.PROT_WRITE, p.MAP_PRIVATE | p.MAP_ANONYMOUS, -1, 0);
77 if (addr == p.MAP_FAILED) return error.OutOfMemory;75 if (addr == p.MAP_FAILED) return error.OutOfMemory;
7876
79 if (alloc_size == n) return @intToPtr(&u8, addr)[0..n];77 if (alloc_size == n) return @intToPtr([*]u8, addr)[0..n];
8078
81 var aligned_addr = addr & ~usize(alignment - 1);79 var aligned_addr = addr & ~usize(alignment - 1);
82 aligned_addr += alignment;80 aligned_addr += alignment;
...@@ -95,7 +93,7 @@ pub const DirectAllocator = struct {...@@ -95,7 +93,7 @@ pub const DirectAllocator = struct {
95 //It is impossible that there is an unoccupied page at the top of our93 //It is impossible that there is an unoccupied page at the top of our
96 // mmap.94 // mmap.
9795
98 return @intToPtr(&u8, aligned_addr)[0..n];96 return @intToPtr([*]u8, aligned_addr)[0..n];
99 },97 },
100 Os.windows => {98 Os.windows => {
101 const amt = n + alignment + @sizeOf(usize);99 const amt = n + alignment + @sizeOf(usize);
...@@ -110,20 +108,18 @@ pub const DirectAllocator = struct {...@@ -110,20 +108,18 @@ pub const DirectAllocator = struct {
110 const march_forward_bytes = if (rem == 0) 0 else (alignment - rem);108 const march_forward_bytes = if (rem == 0) 0 else (alignment - rem);
111 const adjusted_addr = root_addr + march_forward_bytes;109 const adjusted_addr = root_addr + march_forward_bytes;
112 const record_addr = adjusted_addr + n;110 const record_addr = adjusted_addr + n;
113 @intToPtr(&align(1) usize, record_addr).* = root_addr;111 @intToPtr(*align(1) usize, record_addr).* = root_addr;
114 return @intToPtr(&u8, adjusted_addr)[0..n];112 return @intToPtr([*]u8, adjusted_addr)[0..n];
115 },113 },
116 else => @compileError("Unsupported OS"),114 else => @compileError("Unsupported OS"),
117 }115 }
118 }116 }
119117
120 fn realloc(allocator: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {118 fn realloc(allocator: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {
121 const self = @fieldParentPtr(DirectAllocator, "allocator", allocator);119 const self = @fieldParentPtr(DirectAllocator, "allocator", allocator);
122120
123 switch (builtin.os) {121 switch (builtin.os) {
124 Os.linux,122 Os.linux, Os.macosx, Os.ios => {
125 Os.macosx,
126 Os.ios => {
127 if (new_size <= old_mem.len) {123 if (new_size <= old_mem.len) {
128 const base_addr = @ptrToInt(old_mem.ptr);124 const base_addr = @ptrToInt(old_mem.ptr);
129 const old_addr_end = base_addr + old_mem.len;125 const old_addr_end = base_addr + old_mem.len;
...@@ -143,13 +139,13 @@ pub const DirectAllocator = struct {...@@ -143,13 +139,13 @@ pub const DirectAllocator = struct {
143 Os.windows => {139 Os.windows => {
144 const old_adjusted_addr = @ptrToInt(old_mem.ptr);140 const old_adjusted_addr = @ptrToInt(old_mem.ptr);
145 const old_record_addr = old_adjusted_addr + old_mem.len;141 const old_record_addr = old_adjusted_addr + old_mem.len;
146 const root_addr = @intToPtr(&align(1) usize, old_record_addr).*;142 const root_addr = @intToPtr(*align(1) usize, old_record_addr).*;
147 const old_ptr = @intToPtr(os.windows.LPVOID, root_addr);143 const old_ptr = @intToPtr([*]c_void, root_addr);
148 const amt = new_size + alignment + @sizeOf(usize);144 const amt = new_size + alignment + @sizeOf(usize);
149 const new_ptr = os.windows.HeapReAlloc(??self.heap_handle, 0, old_ptr, amt) ?? blk: {145 const new_ptr = os.windows.HeapReAlloc(??self.heap_handle, 0, old_ptr, amt) ?? blk: {
150 if (new_size > old_mem.len) return error.OutOfMemory;146 if (new_size > old_mem.len) return error.OutOfMemory;
151 const new_record_addr = old_record_addr - new_size + old_mem.len;147 const new_record_addr = old_record_addr - new_size + old_mem.len;
152 @intToPtr(&align(1) usize, new_record_addr).* = root_addr;148 @intToPtr(*align(1) usize, new_record_addr).* = root_addr;
153 return old_mem[0..new_size];149 return old_mem[0..new_size];
154 };150 };
155 const offset = old_adjusted_addr - root_addr;151 const offset = old_adjusted_addr - root_addr;
...@@ -157,26 +153,24 @@ pub const DirectAllocator = struct {...@@ -157,26 +153,24 @@ pub const DirectAllocator = struct {
157 const new_adjusted_addr = new_root_addr + offset;153 const new_adjusted_addr = new_root_addr + offset;
158 assert(new_adjusted_addr % alignment == 0);154 assert(new_adjusted_addr % alignment == 0);
159 const new_record_addr = new_adjusted_addr + new_size;155 const new_record_addr = new_adjusted_addr + new_size;
160 @intToPtr(&align(1) usize, new_record_addr).* = new_root_addr;156 @intToPtr(*align(1) usize, new_record_addr).* = new_root_addr;
161 return @intToPtr(&u8, new_adjusted_addr)[0..new_size];157 return @intToPtr([*]u8, new_adjusted_addr)[0..new_size];
162 },158 },
163 else => @compileError("Unsupported OS"),159 else => @compileError("Unsupported OS"),
164 }160 }
165 }161 }
166162
167 fn free(allocator: &Allocator, bytes: []u8) void {163 fn free(allocator: *Allocator, bytes: []u8) void {
168 const self = @fieldParentPtr(DirectAllocator, "allocator", allocator);164 const self = @fieldParentPtr(DirectAllocator, "allocator", allocator);
169165
170 switch (builtin.os) {166 switch (builtin.os) {
171 Os.linux,167 Os.linux, Os.macosx, Os.ios => {
172 Os.macosx,
173 Os.ios => {
174 _ = os.posix.munmap(@ptrToInt(bytes.ptr), bytes.len);168 _ = os.posix.munmap(@ptrToInt(bytes.ptr), bytes.len);
175 },169 },
176 Os.windows => {170 Os.windows => {
177 const record_addr = @ptrToInt(bytes.ptr) + bytes.len;171 const record_addr = @ptrToInt(bytes.ptr) + bytes.len;
178 const root_addr = @intToPtr(&align(1) usize, record_addr).*;172 const root_addr = @intToPtr(*align(1) usize, record_addr).*;
179 const ptr = @intToPtr(os.windows.LPVOID, root_addr);173 const ptr = @intToPtr([*]c_void, root_addr);
180 _ = os.windows.HeapFree(??self.heap_handle, 0, ptr);174 _ = os.windows.HeapFree(??self.heap_handle, 0, ptr);
181 },175 },
182 else => @compileError("Unsupported OS"),176 else => @compileError("Unsupported OS"),
...@@ -189,13 +183,13 @@ pub const DirectAllocator = struct {...@@ -189,13 +183,13 @@ pub const DirectAllocator = struct {
189pub const ArenaAllocator = struct {183pub const ArenaAllocator = struct {
190 pub allocator: Allocator,184 pub allocator: Allocator,
191185
192 child_allocator: &Allocator,186 child_allocator: *Allocator,
193 buffer_list: std.LinkedList([]u8),187 buffer_list: std.LinkedList([]u8),
194 end_index: usize,188 end_index: usize,
195189
196 const BufNode = std.LinkedList([]u8).Node;190 const BufNode = std.LinkedList([]u8).Node;
197191
198 pub fn init(child_allocator: &Allocator) ArenaAllocator {192 pub fn init(child_allocator: *Allocator) ArenaAllocator {
199 return ArenaAllocator{193 return ArenaAllocator{
200 .allocator = Allocator{194 .allocator = Allocator{
201 .allocFn = alloc,195 .allocFn = alloc,
...@@ -208,7 +202,7 @@ pub const ArenaAllocator = struct {...@@ -208,7 +202,7 @@ pub const ArenaAllocator = struct {
208 };202 };
209 }203 }
210204
211 pub fn deinit(self: &ArenaAllocator) void {205 pub fn deinit(self: *ArenaAllocator) void {
212 var it = self.buffer_list.first;206 var it = self.buffer_list.first;
213 while (it) |node| {207 while (it) |node| {
214 // this has to occur before the free because the free frees node208 // this has to occur before the free because the free frees node
...@@ -218,7 +212,7 @@ pub const ArenaAllocator = struct {...@@ -218,7 +212,7 @@ pub const ArenaAllocator = struct {
218 }212 }
219 }213 }
220214
221 fn createNode(self: &ArenaAllocator, prev_len: usize, minimum_size: usize) !&BufNode {215 fn createNode(self: *ArenaAllocator, prev_len: usize, minimum_size: usize) !*BufNode {
222 const actual_min_size = minimum_size + @sizeOf(BufNode);216 const actual_min_size = minimum_size + @sizeOf(BufNode);
223 var len = prev_len;217 var len = prev_len;
224 while (true) {218 while (true) {
...@@ -239,7 +233,7 @@ pub const ArenaAllocator = struct {...@@ -239,7 +233,7 @@ pub const ArenaAllocator = struct {
239 return buf_node;233 return buf_node;
240 }234 }
241235
242 fn alloc(allocator: &Allocator, n: usize, alignment: u29) ![]u8 {236 fn alloc(allocator: *Allocator, n: usize, alignment: u29) ![]u8 {
243 const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator);237 const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator);
244238
245 var cur_node = if (self.buffer_list.last) |last_node| last_node else try self.createNode(0, n + alignment);239 var cur_node = if (self.buffer_list.last) |last_node| last_node else try self.createNode(0, n + alignment);
...@@ -260,7 +254,7 @@ pub const ArenaAllocator = struct {...@@ -260,7 +254,7 @@ pub const ArenaAllocator = struct {
260 }254 }
261 }255 }
262256
263 fn realloc(allocator: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {257 fn realloc(allocator: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {
264 if (new_size <= old_mem.len) {258 if (new_size <= old_mem.len) {
265 return old_mem[0..new_size];259 return old_mem[0..new_size];
266 } else {260 } else {
...@@ -270,7 +264,7 @@ pub const ArenaAllocator = struct {...@@ -270,7 +264,7 @@ pub const ArenaAllocator = struct {
270 }264 }
271 }265 }
272266
273 fn free(allocator: &Allocator, bytes: []u8) void {}267 fn free(allocator: *Allocator, bytes: []u8) void {}
274};268};
275269
276pub const FixedBufferAllocator = struct {270pub const FixedBufferAllocator = struct {
...@@ -290,7 +284,7 @@ pub const FixedBufferAllocator = struct {...@@ -290,7 +284,7 @@ pub const FixedBufferAllocator = struct {
290 };284 };
291 }285 }
292286
293 fn alloc(allocator: &Allocator, n: usize, alignment: u29) ![]u8 {287 fn alloc(allocator: *Allocator, n: usize, alignment: u29) ![]u8 {
294 const self = @fieldParentPtr(FixedBufferAllocator, "allocator", allocator);288 const self = @fieldParentPtr(FixedBufferAllocator, "allocator", allocator);
295 const addr = @ptrToInt(self.buffer.ptr) + self.end_index;289 const addr = @ptrToInt(self.buffer.ptr) + self.end_index;
296 const rem = @rem(addr, alignment);290 const rem = @rem(addr, alignment);
...@@ -306,7 +300,7 @@ pub const FixedBufferAllocator = struct {...@@ -306,7 +300,7 @@ pub const FixedBufferAllocator = struct {
306 return result;300 return result;
307 }301 }
308302
309 fn realloc(allocator: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {303 fn realloc(allocator: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {
310 if (new_size <= old_mem.len) {304 if (new_size <= old_mem.len) {
311 return old_mem[0..new_size];305 return old_mem[0..new_size];
312 } else {306 } else {
...@@ -316,7 +310,7 @@ pub const FixedBufferAllocator = struct {...@@ -316,7 +310,7 @@ pub const FixedBufferAllocator = struct {
316 }310 }
317 }311 }
318312
319 fn free(allocator: &Allocator, bytes: []u8) void {}313 fn free(allocator: *Allocator, bytes: []u8) void {}
320};314};
321315
322/// lock free316/// lock free
...@@ -337,7 +331,7 @@ pub const ThreadSafeFixedBufferAllocator = struct {...@@ -337,7 +331,7 @@ pub const ThreadSafeFixedBufferAllocator = struct {
337 };331 };
338 }332 }
339333
340 fn alloc(allocator: &Allocator, n: usize, alignment: u29) ![]u8 {334 fn alloc(allocator: *Allocator, n: usize, alignment: u29) ![]u8 {
341 const self = @fieldParentPtr(ThreadSafeFixedBufferAllocator, "allocator", allocator);335 const self = @fieldParentPtr(ThreadSafeFixedBufferAllocator, "allocator", allocator);
342 var end_index = @atomicLoad(usize, &self.end_index, builtin.AtomicOrder.SeqCst);336 var end_index = @atomicLoad(usize, &self.end_index, builtin.AtomicOrder.SeqCst);
343 while (true) {337 while (true) {
...@@ -353,7 +347,7 @@ pub const ThreadSafeFixedBufferAllocator = struct {...@@ -353,7 +347,7 @@ pub const ThreadSafeFixedBufferAllocator = struct {
353 }347 }
354 }348 }
355349
356 fn realloc(allocator: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {350 fn realloc(allocator: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 {
357 if (new_size <= old_mem.len) {351 if (new_size <= old_mem.len) {
358 return old_mem[0..new_size];352 return old_mem[0..new_size];
359 } else {353 } else {
...@@ -363,7 +357,7 @@ pub const ThreadSafeFixedBufferAllocator = struct {...@@ -363,7 +357,7 @@ pub const ThreadSafeFixedBufferAllocator = struct {
363 }357 }
364 }358 }
365359
366 fn free(allocator: &Allocator, bytes: []u8) void {}360 fn free(allocator: *Allocator, bytes: []u8) void {}
367};361};
368362
369test "c_allocator" {363test "c_allocator" {
...@@ -409,8 +403,8 @@ test "ThreadSafeFixedBufferAllocator" {...@@ -409,8 +403,8 @@ test "ThreadSafeFixedBufferAllocator" {
409 try testAllocatorLargeAlignment(&fixed_buffer_allocator.allocator);403 try testAllocatorLargeAlignment(&fixed_buffer_allocator.allocator);
410}404}
411405
412fn testAllocator(allocator: &mem.Allocator) !void {406fn testAllocator(allocator: *mem.Allocator) !void {
413 var slice = try allocator.alloc(&i32, 100);407 var slice = try allocator.alloc(*i32, 100);
414408
415 for (slice) |*item, i| {409 for (slice) |*item, i| {
416 item.* = try allocator.create(i32);410 item.* = try allocator.create(i32);
...@@ -421,16 +415,16 @@ fn testAllocator(allocator: &mem.Allocator) !void {...@@ -421,16 +415,16 @@ fn testAllocator(allocator: &mem.Allocator) !void {
421 allocator.destroy(item);415 allocator.destroy(item);
422 }416 }
423417
424 slice = try allocator.realloc(&i32, slice, 20000);418 slice = try allocator.realloc(*i32, slice, 20000);
425 slice = try allocator.realloc(&i32, slice, 50);419 slice = try allocator.realloc(*i32, slice, 50);
426 slice = try allocator.realloc(&i32, slice, 25);420 slice = try allocator.realloc(*i32, slice, 25);
427 slice = try allocator.realloc(&i32, slice, 10);421 slice = try allocator.realloc(*i32, slice, 10);
428422
429 allocator.free(slice);423 allocator.free(slice);
430}424}
431425
432fn testAllocatorLargeAlignment(allocator: &mem.Allocator) mem.Allocator.Error!void {426fn testAllocatorLargeAlignment(allocator: *mem.Allocator) mem.Allocator.Error!void {
433 //Maybe a platform's page_size is actually the same as or 427 //Maybe a platform's page_size is actually the same as or
434 // very near usize?428 // very near usize?
435 if (os.page_size << 2 > @maxValue(usize)) return;429 if (os.page_size << 2 > @maxValue(usize)) return;
436430
std/io.zig+41-41
...@@ -34,20 +34,20 @@ pub fn getStdIn() GetStdIoErrs!File {...@@ -34,20 +34,20 @@ pub fn getStdIn() GetStdIoErrs!File {
3434
35/// Implementation of InStream trait for File35/// Implementation of InStream trait for File
36pub const FileInStream = struct {36pub const FileInStream = struct {
37 file: &File,37 file: *File,
38 stream: Stream,38 stream: Stream,
3939
40 pub const Error = @typeOf(File.read).ReturnType.ErrorSet;40 pub const Error = @typeOf(File.read).ReturnType.ErrorSet;
41 pub const Stream = InStream(Error);41 pub const Stream = InStream(Error);
4242
43 pub fn init(file: &File) FileInStream {43 pub fn init(file: *File) FileInStream {
44 return FileInStream{44 return FileInStream{
45 .file = file,45 .file = file,
46 .stream = Stream{ .readFn = readFn },46 .stream = Stream{ .readFn = readFn },
47 };47 };
48 }48 }
4949
50 fn readFn(in_stream: &Stream, buffer: []u8) Error!usize {50 fn readFn(in_stream: *Stream, buffer: []u8) Error!usize {
51 const self = @fieldParentPtr(FileInStream, "stream", in_stream);51 const self = @fieldParentPtr(FileInStream, "stream", in_stream);
52 return self.file.read(buffer);52 return self.file.read(buffer);
53 }53 }
...@@ -55,20 +55,20 @@ pub const FileInStream = struct {...@@ -55,20 +55,20 @@ pub const FileInStream = struct {
5555
56/// Implementation of OutStream trait for File56/// Implementation of OutStream trait for File
57pub const FileOutStream = struct {57pub const FileOutStream = struct {
58 file: &File,58 file: *File,
59 stream: Stream,59 stream: Stream,
6060
61 pub const Error = File.WriteError;61 pub const Error = File.WriteError;
62 pub const Stream = OutStream(Error);62 pub const Stream = OutStream(Error);
6363
64 pub fn init(file: &File) FileOutStream {64 pub fn init(file: *File) FileOutStream {
65 return FileOutStream{65 return FileOutStream{
66 .file = file,66 .file = file,
67 .stream = Stream{ .writeFn = writeFn },67 .stream = Stream{ .writeFn = writeFn },
68 };68 };
69 }69 }
7070
71 fn writeFn(out_stream: &Stream, bytes: []const u8) !void {71 fn writeFn(out_stream: *Stream, bytes: []const u8) !void {
72 const self = @fieldParentPtr(FileOutStream, "stream", out_stream);72 const self = @fieldParentPtr(FileOutStream, "stream", out_stream);
73 return self.file.write(bytes);73 return self.file.write(bytes);
74 }74 }
...@@ -82,12 +82,12 @@ pub fn InStream(comptime ReadError: type) type {...@@ -82,12 +82,12 @@ pub fn InStream(comptime ReadError: type) type {
82 /// Return the number of bytes read. If the number read is smaller than buf.len, it82 /// Return the number of bytes read. If the number read is smaller than buf.len, it
83 /// means the stream reached the end. Reaching the end of a stream is not an error83 /// means the stream reached the end. Reaching the end of a stream is not an error
84 /// condition.84 /// condition.
85 readFn: fn(self: &Self, buffer: []u8) Error!usize,85 readFn: fn (self: *Self, buffer: []u8) Error!usize,
8686
87 /// Replaces `buffer` contents by reading from the stream until it is finished.87 /// Replaces `buffer` contents by reading from the stream until it is finished.
88 /// If `buffer.len()` would exceed `max_size`, `error.StreamTooLong` is returned and88 /// If `buffer.len()` would exceed `max_size`, `error.StreamTooLong` is returned and
89 /// the contents read from the stream are lost.89 /// the contents read from the stream are lost.
90 pub fn readAllBuffer(self: &Self, buffer: &Buffer, max_size: usize) !void {90 pub fn readAllBuffer(self: *Self, buffer: *Buffer, max_size: usize) !void {
91 try buffer.resize(0);91 try buffer.resize(0);
9292
93 var actual_buf_len: usize = 0;93 var actual_buf_len: usize = 0;
...@@ -111,7 +111,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -111,7 +111,7 @@ pub fn InStream(comptime ReadError: type) type {
111 /// memory would be greater than `max_size`, returns `error.StreamTooLong`.111 /// memory would be greater than `max_size`, returns `error.StreamTooLong`.
112 /// Caller owns returned memory.112 /// Caller owns returned memory.
113 /// If this function returns an error, the contents from the stream read so far are lost.113 /// If this function returns an error, the contents from the stream read so far are lost.
114 pub fn readAllAlloc(self: &Self, allocator: &mem.Allocator, max_size: usize) ![]u8 {114 pub fn readAllAlloc(self: *Self, allocator: *mem.Allocator, max_size: usize) ![]u8 {
115 var buf = Buffer.initNull(allocator);115 var buf = Buffer.initNull(allocator);
116 defer buf.deinit();116 defer buf.deinit();
117117
...@@ -123,7 +123,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -123,7 +123,7 @@ pub fn InStream(comptime ReadError: type) type {
123 /// Does not include the delimiter in the result.123 /// Does not include the delimiter in the result.
124 /// If `buffer.len()` would exceed `max_size`, `error.StreamTooLong` is returned and the contents124 /// If `buffer.len()` would exceed `max_size`, `error.StreamTooLong` is returned and the contents
125 /// read from the stream so far are lost.125 /// read from the stream so far are lost.
126 pub fn readUntilDelimiterBuffer(self: &Self, buffer: &Buffer, delimiter: u8, max_size: usize) !void {126 pub fn readUntilDelimiterBuffer(self: *Self, buffer: *Buffer, delimiter: u8, max_size: usize) !void {
127 try buffer.resize(0);127 try buffer.resize(0);
128128
129 while (true) {129 while (true) {
...@@ -145,7 +145,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -145,7 +145,7 @@ pub fn InStream(comptime ReadError: type) type {
145 /// memory would be greater than `max_size`, returns `error.StreamTooLong`.145 /// memory would be greater than `max_size`, returns `error.StreamTooLong`.
146 /// Caller owns returned memory.146 /// Caller owns returned memory.
147 /// If this function returns an error, the contents from the stream read so far are lost.147 /// If this function returns an error, the contents from the stream read so far are lost.
148 pub fn readUntilDelimiterAlloc(self: &Self, allocator: &mem.Allocator, delimiter: u8, max_size: usize) ![]u8 {148 pub fn readUntilDelimiterAlloc(self: *Self, allocator: *mem.Allocator, delimiter: u8, max_size: usize) ![]u8 {
149 var buf = Buffer.initNull(allocator);149 var buf = Buffer.initNull(allocator);
150 defer buf.deinit();150 defer buf.deinit();
151151
...@@ -156,43 +156,43 @@ pub fn InStream(comptime ReadError: type) type {...@@ -156,43 +156,43 @@ pub fn InStream(comptime ReadError: type) type {
156 /// Returns the number of bytes read. If the number read is smaller than buf.len, it156 /// Returns the number of bytes read. If the number read is smaller than buf.len, it
157 /// means the stream reached the end. Reaching the end of a stream is not an error157 /// means the stream reached the end. Reaching the end of a stream is not an error
158 /// condition.158 /// condition.
159 pub fn read(self: &Self, buffer: []u8) !usize {159 pub fn read(self: *Self, buffer: []u8) !usize {
160 return self.readFn(self, buffer);160 return self.readFn(self, buffer);
161 }161 }
162162
163 /// Same as `read` but end of stream returns `error.EndOfStream`.163 /// Same as `read` but end of stream returns `error.EndOfStream`.
164 pub fn readNoEof(self: &Self, buf: []u8) !void {164 pub fn readNoEof(self: *Self, buf: []u8) !void {
165 const amt_read = try self.read(buf);165 const amt_read = try self.read(buf);
166 if (amt_read < buf.len) return error.EndOfStream;166 if (amt_read < buf.len) return error.EndOfStream;
167 }167 }
168168
169 /// Reads 1 byte from the stream or returns `error.EndOfStream`.169 /// Reads 1 byte from the stream or returns `error.EndOfStream`.
170 pub fn readByte(self: &Self) !u8 {170 pub fn readByte(self: *Self) !u8 {
171 var result: [1]u8 = undefined;171 var result: [1]u8 = undefined;
172 try self.readNoEof(result[0..]);172 try self.readNoEof(result[0..]);
173 return result[0];173 return result[0];
174 }174 }
175175
176 /// Same as `readByte` except the returned byte is signed.176 /// Same as `readByte` except the returned byte is signed.
177 pub fn readByteSigned(self: &Self) !i8 {177 pub fn readByteSigned(self: *Self) !i8 {
178 return @bitCast(i8, try self.readByte());178 return @bitCast(i8, try self.readByte());
179 }179 }
180180
181 pub fn readIntLe(self: &Self, comptime T: type) !T {181 pub fn readIntLe(self: *Self, comptime T: type) !T {
182 return self.readInt(builtin.Endian.Little, T);182 return self.readInt(builtin.Endian.Little, T);
183 }183 }
184184
185 pub fn readIntBe(self: &Self, comptime T: type) !T {185 pub fn readIntBe(self: *Self, comptime T: type) !T {
186 return self.readInt(builtin.Endian.Big, T);186 return self.readInt(builtin.Endian.Big, T);
187 }187 }
188188
189 pub fn readInt(self: &Self, endian: builtin.Endian, comptime T: type) !T {189 pub fn readInt(self: *Self, endian: builtin.Endian, comptime T: type) !T {
190 var bytes: [@sizeOf(T)]u8 = undefined;190 var bytes: [@sizeOf(T)]u8 = undefined;
191 try self.readNoEof(bytes[0..]);191 try self.readNoEof(bytes[0..]);
192 return mem.readInt(bytes, T, endian);192 return mem.readInt(bytes, T, endian);
193 }193 }
194194
195 pub fn readVarInt(self: &Self, endian: builtin.Endian, comptime T: type, size: usize) !T {195 pub fn readVarInt(self: *Self, endian: builtin.Endian, comptime T: type, size: usize) !T {
196 assert(size <= @sizeOf(T));196 assert(size <= @sizeOf(T));
197 assert(size <= 8);197 assert(size <= 8);
198 var input_buf: [8]u8 = undefined;198 var input_buf: [8]u8 = undefined;
...@@ -208,22 +208,22 @@ pub fn OutStream(comptime WriteError: type) type {...@@ -208,22 +208,22 @@ pub fn OutStream(comptime WriteError: type) type {
208 const Self = this;208 const Self = this;
209 pub const Error = WriteError;209 pub const Error = WriteError;
210210
211 writeFn: fn(self: &Self, bytes: []const u8) Error!void,211 writeFn: fn (self: *Self, bytes: []const u8) Error!void,
212212
213 pub fn print(self: &Self, comptime format: []const u8, args: ...) !void {213 pub fn print(self: *Self, comptime format: []const u8, args: ...) !void {
214 return std.fmt.format(self, Error, self.writeFn, format, args);214 return std.fmt.format(self, Error, self.writeFn, format, args);
215 }215 }
216216
217 pub fn write(self: &Self, bytes: []const u8) !void {217 pub fn write(self: *Self, bytes: []const u8) !void {
218 return self.writeFn(self, bytes);218 return self.writeFn(self, bytes);
219 }219 }
220220
221 pub fn writeByte(self: &Self, byte: u8) !void {221 pub fn writeByte(self: *Self, byte: u8) !void {
222 const slice = (&byte)[0..1];222 const slice = (&byte)[0..1];
223 return self.writeFn(self, slice);223 return self.writeFn(self, slice);
224 }224 }
225225
226 pub fn writeByteNTimes(self: &Self, byte: u8, n: usize) !void {226 pub fn writeByteNTimes(self: *Self, byte: u8, n: usize) !void {
227 const slice = (&byte)[0..1];227 const slice = (&byte)[0..1];
228 var i: usize = 0;228 var i: usize = 0;
229 while (i < n) : (i += 1) {229 while (i < n) : (i += 1) {
...@@ -234,14 +234,14 @@ pub fn OutStream(comptime WriteError: type) type {...@@ -234,14 +234,14 @@ pub fn OutStream(comptime WriteError: type) type {
234}234}
235235
236/// `path` needs to be copied in memory to add a null terminating byte, hence the allocator.236/// `path` needs to be copied in memory to add a null terminating byte, hence the allocator.
237pub fn writeFile(allocator: &mem.Allocator, path: []const u8, data: []const u8) !void {237pub fn writeFile(allocator: *mem.Allocator, path: []const u8, data: []const u8) !void {
238 var file = try File.openWrite(allocator, path);238 var file = try File.openWrite(allocator, path);
239 defer file.close();239 defer file.close();
240 try file.write(data);240 try file.write(data);
241}241}
242242
243/// On success, caller owns returned buffer.243/// On success, caller owns returned buffer.
244pub fn readFileAlloc(allocator: &mem.Allocator, path: []const u8) ![]u8 {244pub fn readFileAlloc(allocator: *mem.Allocator, path: []const u8) ![]u8 {
245 var file = try File.openRead(allocator, path);245 var file = try File.openRead(allocator, path);
246 defer file.close();246 defer file.close();
247247
...@@ -265,13 +265,13 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type)...@@ -265,13 +265,13 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type)
265265
266 pub stream: Stream,266 pub stream: Stream,
267267
268 unbuffered_in_stream: &Stream,268 unbuffered_in_stream: *Stream,
269269
270 buffer: [buffer_size]u8,270 buffer: [buffer_size]u8,
271 start_index: usize,271 start_index: usize,
272 end_index: usize,272 end_index: usize,
273273
274 pub fn init(unbuffered_in_stream: &Stream) Self {274 pub fn init(unbuffered_in_stream: *Stream) Self {
275 return Self{275 return Self{
276 .unbuffered_in_stream = unbuffered_in_stream,276 .unbuffered_in_stream = unbuffered_in_stream,
277 .buffer = undefined,277 .buffer = undefined,
...@@ -287,7 +287,7 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type)...@@ -287,7 +287,7 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type)
287 };287 };
288 }288 }
289289
290 fn readFn(in_stream: &Stream, dest: []u8) !usize {290 fn readFn(in_stream: *Stream, dest: []u8) !usize {
291 const self = @fieldParentPtr(Self, "stream", in_stream);291 const self = @fieldParentPtr(Self, "stream", in_stream);
292292
293 var dest_index: usize = 0;293 var dest_index: usize = 0;
...@@ -338,12 +338,12 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr...@@ -338,12 +338,12 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr
338338
339 pub stream: Stream,339 pub stream: Stream,
340340
341 unbuffered_out_stream: &Stream,341 unbuffered_out_stream: *Stream,
342342
343 buffer: [buffer_size]u8,343 buffer: [buffer_size]u8,
344 index: usize,344 index: usize,
345345
346 pub fn init(unbuffered_out_stream: &Stream) Self {346 pub fn init(unbuffered_out_stream: *Stream) Self {
347 return Self{347 return Self{
348 .unbuffered_out_stream = unbuffered_out_stream,348 .unbuffered_out_stream = unbuffered_out_stream,
349 .buffer = undefined,349 .buffer = undefined,
...@@ -352,12 +352,12 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr...@@ -352,12 +352,12 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr
352 };352 };
353 }353 }
354354
355 pub fn flush(self: &Self) !void {355 pub fn flush(self: *Self) !void {
356 try self.unbuffered_out_stream.write(self.buffer[0..self.index]);356 try self.unbuffered_out_stream.write(self.buffer[0..self.index]);
357 self.index = 0;357 self.index = 0;
358 }358 }
359359
360 fn writeFn(out_stream: &Stream, bytes: []const u8) !void {360 fn writeFn(out_stream: *Stream, bytes: []const u8) !void {
361 const self = @fieldParentPtr(Self, "stream", out_stream);361 const self = @fieldParentPtr(Self, "stream", out_stream);
362362
363 if (bytes.len >= self.buffer.len) {363 if (bytes.len >= self.buffer.len) {
...@@ -369,7 +369,7 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr...@@ -369,7 +369,7 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr
369 while (src_index < bytes.len) {369 while (src_index < bytes.len) {
370 const dest_space_left = self.buffer.len - self.index;370 const dest_space_left = self.buffer.len - self.index;
371 const copy_amt = math.min(dest_space_left, bytes.len - src_index);371 const copy_amt = math.min(dest_space_left, bytes.len - src_index);
372 mem.copy(u8, self.buffer[self.index..], bytes[src_index..src_index + copy_amt]);372 mem.copy(u8, self.buffer[self.index..], bytes[src_index .. src_index + copy_amt]);
373 self.index += copy_amt;373 self.index += copy_amt;
374 assert(self.index <= self.buffer.len);374 assert(self.index <= self.buffer.len);
375 if (self.index == self.buffer.len) {375 if (self.index == self.buffer.len) {
...@@ -383,20 +383,20 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr...@@ -383,20 +383,20 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr
383383
384/// Implementation of OutStream trait for Buffer384/// Implementation of OutStream trait for Buffer
385pub const BufferOutStream = struct {385pub const BufferOutStream = struct {
386 buffer: &Buffer,386 buffer: *Buffer,
387 stream: Stream,387 stream: Stream,
388388
389 pub const Error = error{OutOfMemory};389 pub const Error = error{OutOfMemory};
390 pub const Stream = OutStream(Error);390 pub const Stream = OutStream(Error);
391391
392 pub fn init(buffer: &Buffer) BufferOutStream {392 pub fn init(buffer: *Buffer) BufferOutStream {
393 return BufferOutStream{393 return BufferOutStream{
394 .buffer = buffer,394 .buffer = buffer,
395 .stream = Stream{ .writeFn = writeFn },395 .stream = Stream{ .writeFn = writeFn },
396 };396 };
397 }397 }
398398
399 fn writeFn(out_stream: &Stream, bytes: []const u8) !void {399 fn writeFn(out_stream: *Stream, bytes: []const u8) !void {
400 const self = @fieldParentPtr(BufferOutStream, "stream", out_stream);400 const self = @fieldParentPtr(BufferOutStream, "stream", out_stream);
401 return self.buffer.append(bytes);401 return self.buffer.append(bytes);
402 }402 }
...@@ -407,7 +407,7 @@ pub const BufferedAtomicFile = struct {...@@ -407,7 +407,7 @@ pub const BufferedAtomicFile = struct {
407 file_stream: FileOutStream,407 file_stream: FileOutStream,
408 buffered_stream: BufferedOutStream(FileOutStream.Error),408 buffered_stream: BufferedOutStream(FileOutStream.Error),
409409
410 pub fn create(allocator: &mem.Allocator, dest_path: []const u8) !&BufferedAtomicFile {410 pub fn create(allocator: *mem.Allocator, dest_path: []const u8) !*BufferedAtomicFile {
411 // TODO with well defined copy elision we don't need this allocation411 // TODO with well defined copy elision we don't need this allocation
412 var self = try allocator.create(BufferedAtomicFile);412 var self = try allocator.create(BufferedAtomicFile);
413 errdefer allocator.destroy(self);413 errdefer allocator.destroy(self);
...@@ -427,18 +427,18 @@ pub const BufferedAtomicFile = struct {...@@ -427,18 +427,18 @@ pub const BufferedAtomicFile = struct {
427 }427 }
428428
429 /// always call destroy, even after successful finish()429 /// always call destroy, even after successful finish()
430 pub fn destroy(self: &BufferedAtomicFile) void {430 pub fn destroy(self: *BufferedAtomicFile) void {
431 const allocator = self.atomic_file.allocator;431 const allocator = self.atomic_file.allocator;
432 self.atomic_file.deinit();432 self.atomic_file.deinit();
433 allocator.destroy(self);433 allocator.destroy(self);
434 }434 }
435435
436 pub fn finish(self: &BufferedAtomicFile) !void {436 pub fn finish(self: *BufferedAtomicFile) !void {
437 try self.buffered_stream.flush();437 try self.buffered_stream.flush();
438 try self.atomic_file.finish();438 try self.atomic_file.finish();
439 }439 }
440440
441 pub fn stream(self: &BufferedAtomicFile) &OutStream(FileOutStream.Error) {441 pub fn stream(self: *BufferedAtomicFile) *OutStream(FileOutStream.Error) {
442 return &self.buffered_stream.stream;442 return &self.buffered_stream.stream;
443 }443 }
444};444};
std/io_test.zig+1-1
...@@ -41,7 +41,7 @@ test "write a file, read it, then delete it" {...@@ -41,7 +41,7 @@ test "write a file, read it, then delete it" {
41 defer allocator.free(contents);41 defer allocator.free(contents);
4242
43 assert(mem.eql(u8, contents[0.."begin".len], "begin"));43 assert(mem.eql(u8, contents[0.."begin".len], "begin"));
44 assert(mem.eql(u8, contents["begin".len..contents.len - "end".len], data));44 assert(mem.eql(u8, contents["begin".len .. contents.len - "end".len], data));
45 assert(mem.eql(u8, contents[contents.len - "end".len ..], "end"));45 assert(mem.eql(u8, contents[contents.len - "end".len ..], "end"));
46 }46 }
47 try os.deleteFile(allocator, tmp_file_name);47 try os.deleteFile(allocator, tmp_file_name);
std/json.zig+52-94
...@@ -10,7 +10,7 @@ const u256 = @IntType(false, 256);...@@ -10,7 +10,7 @@ const u256 = @IntType(false, 256);
1010
11// A single token slice into the parent string.11// A single token slice into the parent string.
12//12//
13// Use `token.slice()` on the inptu at the current position to get the current slice.13// Use `token.slice()` on the input at the current position to get the current slice.
14pub const Token = struct {14pub const Token = struct {
15 id: Id,15 id: Id,
16 // How many bytes do we skip before counting16 // How many bytes do we skip before counting
...@@ -76,8 +76,8 @@ pub const Token = struct {...@@ -76,8 +76,8 @@ pub const Token = struct {
76 }76 }
7777
78 // Slice into the underlying input string.78 // Slice into the underlying input string.
79 pub fn slice(self: &const Token, input: []const u8, i: usize) []const u8 {79 pub fn slice(self: *const Token, input: []const u8, i: usize) []const u8 {
80 return input[i + self.offset - self.count..i + self.offset];80 return input[i + self.offset - self.count .. i + self.offset];
81 }81 }
82};82};
8383
...@@ -115,7 +115,7 @@ pub const StreamingJsonParser = struct {...@@ -115,7 +115,7 @@ pub const StreamingJsonParser = struct {
115 return p;115 return p;
116 }116 }
117117
118 pub fn reset(p: &StreamingJsonParser) void {118 pub fn reset(p: *StreamingJsonParser) void {
119 p.state = State.TopLevelBegin;119 p.state = State.TopLevelBegin;
120 p.count = 0;120 p.count = 0;
121 // Set before ever read in main transition function121 // Set before ever read in main transition function
...@@ -205,7 +205,7 @@ pub const StreamingJsonParser = struct {...@@ -205,7 +205,7 @@ pub const StreamingJsonParser = struct {
205 // tokens. token2 is always null if token1 is null.205 // tokens. token2 is always null if token1 is null.
206 //206 //
207 // There is currently no error recovery on a bad stream.207 // There is currently no error recovery on a bad stream.
208 pub fn feed(p: &StreamingJsonParser, c: u8, token1: &?Token, token2: &?Token) Error!void {208 pub fn feed(p: *StreamingJsonParser, c: u8, token1: *?Token, token2: *?Token) Error!void {
209 token1.* = null;209 token1.* = null;
210 token2.* = null;210 token2.* = null;
211 p.count += 1;211 p.count += 1;
...@@ -217,7 +217,7 @@ pub const StreamingJsonParser = struct {...@@ -217,7 +217,7 @@ pub const StreamingJsonParser = struct {
217 }217 }
218218
219 // Perform a single transition on the state machine and return any possible token.219 // Perform a single transition on the state machine and return any possible token.
220 fn transition(p: &StreamingJsonParser, c: u8, token: &?Token) Error!bool {220 fn transition(p: *StreamingJsonParser, c: u8, token: *?Token) Error!bool {
221 switch (p.state) {221 switch (p.state) {
222 State.TopLevelBegin => switch (c) {222 State.TopLevelBegin => switch (c) {
223 '{' => {223 '{' => {
...@@ -252,7 +252,7 @@ pub const StreamingJsonParser = struct {...@@ -252,7 +252,7 @@ pub const StreamingJsonParser = struct {
252 p.after_value_state = State.TopLevelEnd;252 p.after_value_state = State.TopLevelEnd;
253 p.count = 0;253 p.count = 0;
254 },254 },
255 '1' ... '9' => {255 '1'...'9' => {
256 p.number_is_integer = true;256 p.number_is_integer = true;
257 p.state = State.NumberMaybeDigitOrDotOrExponent;257 p.state = State.NumberMaybeDigitOrDotOrExponent;
258 p.after_value_state = State.TopLevelEnd;258 p.after_value_state = State.TopLevelEnd;
...@@ -281,10 +281,7 @@ pub const StreamingJsonParser = struct {...@@ -281,10 +281,7 @@ pub const StreamingJsonParser = struct {
281 p.after_value_state = State.TopLevelEnd;281 p.after_value_state = State.TopLevelEnd;
282 p.count = 0;282 p.count = 0;
283 },283 },
284 0x09,284 0x09, 0x0A, 0x0D, 0x20 => {
285 0x0A,
286 0x0D,
287 0x20 => {
288 // whitespace285 // whitespace
289 },286 },
290 else => {287 else => {
...@@ -293,10 +290,7 @@ pub const StreamingJsonParser = struct {...@@ -293,10 +290,7 @@ pub const StreamingJsonParser = struct {
293 },290 },
294291
295 State.TopLevelEnd => switch (c) {292 State.TopLevelEnd => switch (c) {
296 0x09,293 0x09, 0x0A, 0x0D, 0x20 => {
297 0x0A,
298 0x0D,
299 0x20 => {
300 // whitespace294 // whitespace
301 },295 },
302 else => {296 else => {
...@@ -392,7 +386,7 @@ pub const StreamingJsonParser = struct {...@@ -392,7 +386,7 @@ pub const StreamingJsonParser = struct {
392 p.state = State.NumberMaybeDotOrExponent;386 p.state = State.NumberMaybeDotOrExponent;
393 p.count = 0;387 p.count = 0;
394 },388 },
395 '1' ... '9' => {389 '1'...'9' => {
396 p.state = State.NumberMaybeDigitOrDotOrExponent;390 p.state = State.NumberMaybeDigitOrDotOrExponent;
397 p.count = 0;391 p.count = 0;
398 },392 },
...@@ -412,10 +406,7 @@ pub const StreamingJsonParser = struct {...@@ -412,10 +406,7 @@ pub const StreamingJsonParser = struct {
412 p.state = State.NullLiteral1;406 p.state = State.NullLiteral1;
413 p.count = 0;407 p.count = 0;
414 },408 },
415 0x09,409 0x09, 0x0A, 0x0D, 0x20 => {
416 0x0A,
417 0x0D,
418 0x20 => {
419 // whitespace410 // whitespace
420 },411 },
421 else => {412 else => {
...@@ -461,7 +452,7 @@ pub const StreamingJsonParser = struct {...@@ -461,7 +452,7 @@ pub const StreamingJsonParser = struct {
461 p.state = State.NumberMaybeDotOrExponent;452 p.state = State.NumberMaybeDotOrExponent;
462 p.count = 0;453 p.count = 0;
463 },454 },
464 '1' ... '9' => {455 '1'...'9' => {
465 p.state = State.NumberMaybeDigitOrDotOrExponent;456 p.state = State.NumberMaybeDigitOrDotOrExponent;
466 p.count = 0;457 p.count = 0;
467 },458 },
...@@ -481,10 +472,7 @@ pub const StreamingJsonParser = struct {...@@ -481,10 +472,7 @@ pub const StreamingJsonParser = struct {
481 p.state = State.NullLiteral1;472 p.state = State.NullLiteral1;
482 p.count = 0;473 p.count = 0;
483 },474 },
484 0x09,475 0x09, 0x0A, 0x0D, 0x20 => {
485 0x0A,
486 0x0D,
487 0x20 => {
488 // whitespace476 // whitespace
489 },477 },
490 else => {478 else => {
...@@ -533,10 +521,7 @@ pub const StreamingJsonParser = struct {...@@ -533,10 +521,7 @@ pub const StreamingJsonParser = struct {
533521
534 token.* = Token.initMarker(Token.Id.ObjectEnd);522 token.* = Token.initMarker(Token.Id.ObjectEnd);
535 },523 },
536 0x09,524 0x09, 0x0A, 0x0D, 0x20 => {
537 0x0A,
538 0x0D,
539 0x20 => {
540 // whitespace525 // whitespace
541 },526 },
542 else => {527 else => {
...@@ -549,10 +534,7 @@ pub const StreamingJsonParser = struct {...@@ -549,10 +534,7 @@ pub const StreamingJsonParser = struct {
549 p.state = State.ValueBegin;534 p.state = State.ValueBegin;
550 p.after_string_state = State.ValueEnd;535 p.after_string_state = State.ValueEnd;
551 },536 },
552 0x09,537 0x09, 0x0A, 0x0D, 0x20 => {
553 0x0A,
554 0x0D,
555 0x20 => {
556 // whitespace538 // whitespace
557 },539 },
558 else => {540 else => {
...@@ -561,7 +543,7 @@ pub const StreamingJsonParser = struct {...@@ -561,7 +543,7 @@ pub const StreamingJsonParser = struct {
561 },543 },
562544
563 State.String => switch (c) {545 State.String => switch (c) {
564 0x00 ... 0x1F => {546 0x00...0x1F => {
565 return error.InvalidControlCharacter;547 return error.InvalidControlCharacter;
566 },548 },
567 '"' => {549 '"' => {
...@@ -576,19 +558,16 @@ pub const StreamingJsonParser = struct {...@@ -576,19 +558,16 @@ pub const StreamingJsonParser = struct {
576 '\\' => {558 '\\' => {
577 p.state = State.StringEscapeCharacter;559 p.state = State.StringEscapeCharacter;
578 },560 },
579 0x20,561 0x20, 0x21, 0x23...0x5B, 0x5D...0x7F => {
580 0x21,
581 0x23 ... 0x5B,
582 0x5D ... 0x7F => {
583 // non-control ascii562 // non-control ascii
584 },563 },
585 0xC0 ... 0xDF => {564 0xC0...0xDF => {
586 p.state = State.StringUtf8Byte1;565 p.state = State.StringUtf8Byte1;
587 },566 },
588 0xE0 ... 0xEF => {567 0xE0...0xEF => {
589 p.state = State.StringUtf8Byte2;568 p.state = State.StringUtf8Byte2;
590 },569 },
591 0xF0 ... 0xFF => {570 0xF0...0xFF => {
592 p.state = State.StringUtf8Byte3;571 p.state = State.StringUtf8Byte3;
593 },572 },
594 else => {573 else => {
...@@ -620,14 +599,7 @@ pub const StreamingJsonParser = struct {...@@ -620,14 +599,7 @@ pub const StreamingJsonParser = struct {
620 // The current JSONTestSuite tests rely on both of this behaviour being present599 // The current JSONTestSuite tests rely on both of this behaviour being present
621 // however, so we default to the status quo where both are accepted until this600 // however, so we default to the status quo where both are accepted until this
622 // is further clarified.601 // is further clarified.
623 '"',602 '"', '\\', '/', 'b', 'f', 'n', 'r', 't' => {
624 '\\',
625 '/',
626 'b',
627 'f',
628 'n',
629 'r',
630 't' => {
631 p.string_has_escape = true;603 p.string_has_escape = true;
632 p.state = State.String;604 p.state = State.String;
633 },605 },
...@@ -641,36 +613,28 @@ pub const StreamingJsonParser = struct {...@@ -641,36 +613,28 @@ pub const StreamingJsonParser = struct {
641 },613 },
642614
643 State.StringEscapeHexUnicode4 => switch (c) {615 State.StringEscapeHexUnicode4 => switch (c) {
644 '0' ... '9',616 '0'...'9', 'A'...'F', 'a'...'f' => {
645 'A' ... 'F',
646 'a' ... 'f' => {
647 p.state = State.StringEscapeHexUnicode3;617 p.state = State.StringEscapeHexUnicode3;
648 },618 },
649 else => return error.InvalidUnicodeHexSymbol,619 else => return error.InvalidUnicodeHexSymbol,
650 },620 },
651621
652 State.StringEscapeHexUnicode3 => switch (c) {622 State.StringEscapeHexUnicode3 => switch (c) {
653 '0' ... '9',623 '0'...'9', 'A'...'F', 'a'...'f' => {
654 'A' ... 'F',
655 'a' ... 'f' => {
656 p.state = State.StringEscapeHexUnicode2;624 p.state = State.StringEscapeHexUnicode2;
657 },625 },
658 else => return error.InvalidUnicodeHexSymbol,626 else => return error.InvalidUnicodeHexSymbol,
659 },627 },
660628
661 State.StringEscapeHexUnicode2 => switch (c) {629 State.StringEscapeHexUnicode2 => switch (c) {
662 '0' ... '9',630 '0'...'9', 'A'...'F', 'a'...'f' => {
663 'A' ... 'F',
664 'a' ... 'f' => {
665 p.state = State.StringEscapeHexUnicode1;631 p.state = State.StringEscapeHexUnicode1;
666 },632 },
667 else => return error.InvalidUnicodeHexSymbol,633 else => return error.InvalidUnicodeHexSymbol,
668 },634 },
669635
670 State.StringEscapeHexUnicode1 => switch (c) {636 State.StringEscapeHexUnicode1 => switch (c) {
671 '0' ... '9',637 '0'...'9', 'A'...'F', 'a'...'f' => {
672 'A' ... 'F',
673 'a' ... 'f' => {
674 p.state = State.String;638 p.state = State.String;
675 },639 },
676 else => return error.InvalidUnicodeHexSymbol,640 else => return error.InvalidUnicodeHexSymbol,
...@@ -682,7 +646,7 @@ pub const StreamingJsonParser = struct {...@@ -682,7 +646,7 @@ pub const StreamingJsonParser = struct {
682 '0' => {646 '0' => {
683 p.state = State.NumberMaybeDotOrExponent;647 p.state = State.NumberMaybeDotOrExponent;
684 },648 },
685 '1' ... '9' => {649 '1'...'9' => {
686 p.state = State.NumberMaybeDigitOrDotOrExponent;650 p.state = State.NumberMaybeDigitOrDotOrExponent;
687 },651 },
688 else => {652 else => {
...@@ -698,8 +662,7 @@ pub const StreamingJsonParser = struct {...@@ -698,8 +662,7 @@ pub const StreamingJsonParser = struct {
698 p.number_is_integer = false;662 p.number_is_integer = false;
699 p.state = State.NumberFractionalRequired;663 p.state = State.NumberFractionalRequired;
700 },664 },
701 'e',665 'e', 'E' => {
702 'E' => {
703 p.number_is_integer = false;666 p.number_is_integer = false;
704 p.state = State.NumberExponent;667 p.state = State.NumberExponent;
705 },668 },
...@@ -718,12 +681,11 @@ pub const StreamingJsonParser = struct {...@@ -718,12 +681,11 @@ pub const StreamingJsonParser = struct {
718 p.number_is_integer = false;681 p.number_is_integer = false;
719 p.state = State.NumberFractionalRequired;682 p.state = State.NumberFractionalRequired;
720 },683 },
721 'e',684 'e', 'E' => {
722 'E' => {
723 p.number_is_integer = false;685 p.number_is_integer = false;
724 p.state = State.NumberExponent;686 p.state = State.NumberExponent;
725 },687 },
726 '0' ... '9' => {688 '0'...'9' => {
727 // another digit689 // another digit
728 },690 },
729 else => {691 else => {
...@@ -737,7 +699,7 @@ pub const StreamingJsonParser = struct {...@@ -737,7 +699,7 @@ pub const StreamingJsonParser = struct {
737 State.NumberFractionalRequired => {699 State.NumberFractionalRequired => {
738 p.complete = p.after_value_state == State.TopLevelEnd;700 p.complete = p.after_value_state == State.TopLevelEnd;
739 switch (c) {701 switch (c) {
740 '0' ... '9' => {702 '0'...'9' => {
741 p.state = State.NumberFractional;703 p.state = State.NumberFractional;
742 },704 },
743 else => {705 else => {
...@@ -749,11 +711,10 @@ pub const StreamingJsonParser = struct {...@@ -749,11 +711,10 @@ pub const StreamingJsonParser = struct {
749 State.NumberFractional => {711 State.NumberFractional => {
750 p.complete = p.after_value_state == State.TopLevelEnd;712 p.complete = p.after_value_state == State.TopLevelEnd;
751 switch (c) {713 switch (c) {
752 '0' ... '9' => {714 '0'...'9' => {
753 // another digit715 // another digit
754 },716 },
755 'e',717 'e', 'E' => {
756 'E' => {
757 p.number_is_integer = false;718 p.number_is_integer = false;
758 p.state = State.NumberExponent;719 p.state = State.NumberExponent;
759 },720 },
...@@ -768,8 +729,7 @@ pub const StreamingJsonParser = struct {...@@ -768,8 +729,7 @@ pub const StreamingJsonParser = struct {
768 State.NumberMaybeExponent => {729 State.NumberMaybeExponent => {
769 p.complete = p.after_value_state == State.TopLevelEnd;730 p.complete = p.after_value_state == State.TopLevelEnd;
770 switch (c) {731 switch (c) {
771 'e',732 'e', 'E' => {
772 'E' => {
773 p.number_is_integer = false;733 p.number_is_integer = false;
774 p.state = State.NumberExponent;734 p.state = State.NumberExponent;
775 },735 },
...@@ -782,12 +742,11 @@ pub const StreamingJsonParser = struct {...@@ -782,12 +742,11 @@ pub const StreamingJsonParser = struct {
782 },742 },
783743
784 State.NumberExponent => switch (c) {744 State.NumberExponent => switch (c) {
785 '-',745 '-', '+' => {
786 '+' => {
787 p.complete = false;746 p.complete = false;
788 p.state = State.NumberExponentDigitsRequired;747 p.state = State.NumberExponentDigitsRequired;
789 },748 },
790 '0' ... '9' => {749 '0'...'9' => {
791 p.complete = p.after_value_state == State.TopLevelEnd;750 p.complete = p.after_value_state == State.TopLevelEnd;
792 p.state = State.NumberExponentDigits;751 p.state = State.NumberExponentDigits;
793 },752 },
...@@ -797,7 +756,7 @@ pub const StreamingJsonParser = struct {...@@ -797,7 +756,7 @@ pub const StreamingJsonParser = struct {
797 },756 },
798757
799 State.NumberExponentDigitsRequired => switch (c) {758 State.NumberExponentDigitsRequired => switch (c) {
800 '0' ... '9' => {759 '0'...'9' => {
801 p.complete = p.after_value_state == State.TopLevelEnd;760 p.complete = p.after_value_state == State.TopLevelEnd;
802 p.state = State.NumberExponentDigits;761 p.state = State.NumberExponentDigits;
803 },762 },
...@@ -809,7 +768,7 @@ pub const StreamingJsonParser = struct {...@@ -809,7 +768,7 @@ pub const StreamingJsonParser = struct {
809 State.NumberExponentDigits => {768 State.NumberExponentDigits => {
810 p.complete = p.after_value_state == State.TopLevelEnd;769 p.complete = p.after_value_state == State.TopLevelEnd;
811 switch (c) {770 switch (c) {
812 '0' ... '9' => {771 '0'...'9' => {
813 // another digit772 // another digit
814 },773 },
815 else => {774 else => {
...@@ -902,7 +861,7 @@ pub fn validate(s: []const u8) bool {...@@ -902,7 +861,7 @@ pub fn validate(s: []const u8) bool {
902 var token1: ?Token = undefined;861 var token1: ?Token = undefined;
903 var token2: ?Token = undefined;862 var token2: ?Token = undefined;
904863
905 p.feed(c, &token1, &token2) catch |err| {864 p.feed(c, *token1, *token2) catch |err| {
906 return false;865 return false;
907 };866 };
908 }867 }
...@@ -919,7 +878,7 @@ pub const ValueTree = struct {...@@ -919,7 +878,7 @@ pub const ValueTree = struct {
919 arena: ArenaAllocator,878 arena: ArenaAllocator,
920 root: Value,879 root: Value,
921880
922 pub fn deinit(self: &ValueTree) void {881 pub fn deinit(self: *ValueTree) void {
923 self.arena.deinit();882 self.arena.deinit();
924 }883 }
925};884};
...@@ -935,7 +894,7 @@ pub const Value = union(enum) {...@@ -935,7 +894,7 @@ pub const Value = union(enum) {
935 Array: ArrayList(Value),894 Array: ArrayList(Value),
936 Object: ObjectMap,895 Object: ObjectMap,
937896
938 pub fn dump(self: &const Value) void {897 pub fn dump(self: *const Value) void {
939 switch (self.*) {898 switch (self.*) {
940 Value.Null => {899 Value.Null => {
941 std.debug.warn("null");900 std.debug.warn("null");
...@@ -982,7 +941,7 @@ pub const Value = union(enum) {...@@ -982,7 +941,7 @@ pub const Value = union(enum) {
982 }941 }
983 }942 }
984943
985 pub fn dumpIndent(self: &const Value, indent: usize) void {944 pub fn dumpIndent(self: *const Value, indent: usize) void {
986 if (indent == 0) {945 if (indent == 0) {
987 self.dump();946 self.dump();
988 } else {947 } else {
...@@ -990,7 +949,7 @@ pub const Value = union(enum) {...@@ -990,7 +949,7 @@ pub const Value = union(enum) {
990 }949 }
991 }950 }
992951
993 fn dumpIndentLevel(self: &const Value, indent: usize, level: usize) void {952 fn dumpIndentLevel(self: *const Value, indent: usize, level: usize) void {
994 switch (self.*) {953 switch (self.*) {
995 Value.Null => {954 Value.Null => {
996 std.debug.warn("null");955 std.debug.warn("null");
...@@ -1054,7 +1013,7 @@ pub const Value = union(enum) {...@@ -1054,7 +1013,7 @@ pub const Value = union(enum) {
10541013
1055// A non-stream JSON parser which constructs a tree of Value's.1014// A non-stream JSON parser which constructs a tree of Value's.
1056pub const JsonParser = struct {1015pub const JsonParser = struct {
1057 allocator: &Allocator,1016 allocator: *Allocator,
1058 state: State,1017 state: State,
1059 copy_strings: bool,1018 copy_strings: bool,
1060 // Stores parent nodes and un-combined Values.1019 // Stores parent nodes and un-combined Values.
...@@ -1067,7 +1026,7 @@ pub const JsonParser = struct {...@@ -1067,7 +1026,7 @@ pub const JsonParser = struct {
1067 Simple,1026 Simple,
1068 };1027 };
10691028
1070 pub fn init(allocator: &Allocator, copy_strings: bool) JsonParser {1029 pub fn init(allocator: *Allocator, copy_strings: bool) JsonParser {
1071 return JsonParser{1030 return JsonParser{
1072 .allocator = allocator,1031 .allocator = allocator,
1073 .state = State.Simple,1032 .state = State.Simple,
...@@ -1076,16 +1035,16 @@ pub const JsonParser = struct {...@@ -1076,16 +1035,16 @@ pub const JsonParser = struct {
1076 };1035 };
1077 }1036 }
10781037
1079 pub fn deinit(p: &JsonParser) void {1038 pub fn deinit(p: *JsonParser) void {
1080 p.stack.deinit();1039 p.stack.deinit();
1081 }1040 }
10821041
1083 pub fn reset(p: &JsonParser) void {1042 pub fn reset(p: *JsonParser) void {
1084 p.state = State.Simple;1043 p.state = State.Simple;
1085 p.stack.shrink(0);1044 p.stack.shrink(0);
1086 }1045 }
10871046
1088 pub fn parse(p: &JsonParser, input: []const u8) !ValueTree {1047 pub fn parse(p: *JsonParser, input: []const u8) !ValueTree {
1089 var mp = StreamingJsonParser.init();1048 var mp = StreamingJsonParser.init();
10901049
1091 var arena = ArenaAllocator.init(p.allocator);1050 var arena = ArenaAllocator.init(p.allocator);
...@@ -1131,7 +1090,7 @@ pub const JsonParser = struct {...@@ -1131,7 +1090,7 @@ pub const JsonParser = struct {
11311090
1132 // Even though p.allocator exists, we take an explicit allocator so that allocation state1091 // Even though p.allocator exists, we take an explicit allocator so that allocation state
1133 // can be cleaned up on error correctly during a `parse` on call.1092 // can be cleaned up on error correctly during a `parse` on call.
1134 fn transition(p: &JsonParser, allocator: &Allocator, input: []const u8, i: usize, token: &const Token) !void {1093 fn transition(p: *JsonParser, allocator: *Allocator, input: []const u8, i: usize, token: *const Token) !void {
1135 switch (p.state) {1094 switch (p.state) {
1136 State.ObjectKey => switch (token.id) {1095 State.ObjectKey => switch (token.id) {
1137 Token.Id.ObjectEnd => {1096 Token.Id.ObjectEnd => {
...@@ -1257,15 +1216,14 @@ pub const JsonParser = struct {...@@ -1257,15 +1216,14 @@ pub const JsonParser = struct {
1257 Token.Id.Null => {1216 Token.Id.Null => {
1258 try p.stack.append(Value.Null);1217 try p.stack.append(Value.Null);
1259 },1218 },
1260 Token.Id.ObjectEnd,1219 Token.Id.ObjectEnd, Token.Id.ArrayEnd => {
1261 Token.Id.ArrayEnd => {
1262 unreachable;1220 unreachable;
1263 },1221 },
1264 },1222 },
1265 }1223 }
1266 }1224 }
12671225
1268 fn pushToParent(p: &JsonParser, value: &const Value) !void {1226 fn pushToParent(p: *JsonParser, value: *const Value) !void {
1269 switch (p.stack.at(p.stack.len - 1)) {1227 switch (p.stack.at(p.stack.len - 1)) {
1270 // Object Parent -> [ ..., object, <key>, value ]1228 // Object Parent -> [ ..., object, <key>, value ]
1271 Value.String => |key| {1229 Value.String => |key| {
...@@ -1286,14 +1244,14 @@ pub const JsonParser = struct {...@@ -1286,14 +1244,14 @@ pub const JsonParser = struct {
1286 }1244 }
1287 }1245 }
12881246
1289 fn parseString(p: &JsonParser, allocator: &Allocator, token: &const Token, input: []const u8, i: usize) !Value {1247 fn parseString(p: *JsonParser, allocator: *Allocator, token: *const Token, input: []const u8, i: usize) !Value {
1290 // TODO: We don't strictly have to copy values which do not contain any escape1248 // TODO: We don't strictly have to copy values which do not contain any escape
1291 // characters if flagged with the option.1249 // characters if flagged with the option.
1292 const slice = token.slice(input, i);1250 const slice = token.slice(input, i);
1293 return Value{ .String = try mem.dupe(p.allocator, u8, slice) };1251 return Value{ .String = try mem.dupe(p.allocator, u8, slice) };
1294 }1252 }
12951253
1296 fn parseNumber(p: &JsonParser, token: &const Token, input: []const u8, i: usize) !Value {1254 fn parseNumber(p: *JsonParser, token: *const Token, input: []const u8, i: usize) !Value {
1297 return if (token.number_is_integer)1255 return if (token.number_is_integer)
1298 Value{ .Integer = try std.fmt.parseInt(i64, token.slice(input, i), 10) }1256 Value{ .Integer = try std.fmt.parseInt(i64, token.slice(input, i), 10) }
1299 else1257 else
std/json_test.zig+9-27
...@@ -81,9 +81,7 @@ test "y_array_with_several_null" {...@@ -81,9 +81,7 @@ test "y_array_with_several_null" {
81}81}
8282
83test "y_array_with_trailing_space" {83test "y_array_with_trailing_space" {
84 ok(84 ok("[2] ");
85 "[2] "
86 );
87}85}
8886
89test "y_number_0e+1" {87test "y_number_0e+1" {
...@@ -579,9 +577,7 @@ test "y_structure_true_in_array" {...@@ -579,9 +577,7 @@ test "y_structure_true_in_array" {
579}577}
580578
581test "y_structure_whitespace_array" {579test "y_structure_whitespace_array" {
582 ok(580 ok(" [] ");
583 " [] "
584 );
585}581}
586582
587////////////////////////////////////////////////////////////////////////////////////////////////////583////////////////////////////////////////////////////////////////////////////////////////////////////
...@@ -696,7 +692,6 @@ test "n_array_newlines_unclosed" {...@@ -696,7 +692,6 @@ test "n_array_newlines_unclosed" {
696 );692 );
697}693}
698694
699
700test "n_array_number_and_comma" {695test "n_array_number_and_comma" {
701 err(696 err(
702 \\[1,]697 \\[1,]
...@@ -971,7 +966,6 @@ test "n_number_invalid-utf-8-in-int" {...@@ -971,7 +966,6 @@ test "n_number_invalid-utf-8-in-int" {
971 );966 );
972}967}
973968
974
975test "n_number_++" {969test "n_number_++" {
976 err(970 err(
977 \\[++1234]971 \\[++1234]
...@@ -1228,7 +1222,7 @@ test "n_object_unterminated-value" {...@@ -1228,7 +1222,7 @@ test "n_object_unterminated-value" {
1228 err(1222 err(
1229 \\{"a":"a1223 \\{"a":"a
1230 );1224 );
1231 }1225}
12321226
1233test "n_object_with_single_string" {1227test "n_object_with_single_string" {
1234 err(1228 err(
...@@ -1243,9 +1237,7 @@ test "n_object_with_trailing_garbage" {...@@ -1243,9 +1237,7 @@ test "n_object_with_trailing_garbage" {
1243}1237}
12441238
1245test "n_single_space" {1239test "n_single_space" {
1246 err(1240 err(" ");
1247 " "
1248 );
1249}1241}
12501242
1251test "n_string_1_surrogate_then_escape" {1243test "n_string_1_surrogate_then_escape" {
...@@ -1279,9 +1271,7 @@ test "n_string_accentuated_char_no_quotes" {...@@ -1279,9 +1271,7 @@ test "n_string_accentuated_char_no_quotes" {
1279}1271}
12801272
1281test "n_string_backslash_00" {1273test "n_string_backslash_00" {
1282 err(1274 err("[\"\x00\"]");
1283 \\["\"]
1284 );
1285}1275}
12861276
1287test "n_string_escaped_backslash_bad" {1277test "n_string_escaped_backslash_bad" {
...@@ -1291,9 +1281,7 @@ test "n_string_escaped_backslash_bad" {...@@ -1291,9 +1281,7 @@ test "n_string_escaped_backslash_bad" {
1291}1281}
12921282
1293test "n_string_escaped_ctrl_char_tab" {1283test "n_string_escaped_ctrl_char_tab" {
1294 err(1284 err("\x5b\x22\x5c\x09\x22\x5d");
1295 \\["\ "]
1296 );
1297}1285}
12981286
1299test "n_string_escaped_emoji" {1287test "n_string_escaped_emoji" {
...@@ -1416,9 +1404,7 @@ test "n_string_with_trailing_garbage" {...@@ -1416,9 +1404,7 @@ test "n_string_with_trailing_garbage" {
1416}1404}
14171405
1418test "n_structure_100000_opening_arrays" {1406test "n_structure_100000_opening_arrays" {
1419 err(1407 err("[" ** 100000);
1420 "[" ** 100000
1421 );
1422}1408}
14231409
1424test "n_structure_angle_bracket_." {1410test "n_structure_angle_bracket_." {
...@@ -1558,9 +1544,7 @@ test "n_structure_open_array_comma" {...@@ -1558,9 +1544,7 @@ test "n_structure_open_array_comma" {
1558}1544}
15591545
1560test "n_structure_open_array_object" {1546test "n_structure_open_array_object" {
1561 err(1547 err("[{\"\":" ** 50000);
1562 "[{\"\":" ** 50000
1563 );
1564}1548}
15651549
1566test "n_structure_open_array_open_object" {1550test "n_structure_open_array_open_object" {
...@@ -1900,9 +1884,7 @@ test "i_string_UTF8_surrogate_U+D800" {...@@ -1900,9 +1884,7 @@ test "i_string_UTF8_surrogate_U+D800" {
1900}1884}
19011885
1902test "i_structure_500_nested_arrays" {1886test "i_structure_500_nested_arrays" {
1903 any(1887 any(("[" ** 500) ++ ("]" ** 500));
1904 ("[" ** 500) ++ ("]" ** 500)
1905 );
1906}1888}
19071889
1908test "i_structure_UTF-8_BOM_empty_object" {1890test "i_structure_UTF-8_BOM_empty_object" {
std/linked_list.zig+16-16
...@@ -21,11 +21,11 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -21,11 +21,11 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
2121
22 /// Node inside the linked list wrapping the actual data.22 /// Node inside the linked list wrapping the actual data.
23 pub const Node = struct {23 pub const Node = struct {
24 prev: ?&Node,24 prev: ?*Node,
25 next: ?&Node,25 next: ?*Node,
26 data: T,26 data: T,
2727
28 pub fn init(value: &const T) Node {28 pub fn init(value: *const T) Node {
29 return Node{29 return Node{
30 .prev = null,30 .prev = null,
31 .next = null,31 .next = null,
...@@ -38,14 +38,14 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -38,14 +38,14 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
38 return Node.init({});38 return Node.init({});
39 }39 }
4040
41 pub fn toData(node: &Node) &ParentType {41 pub fn toData(node: *Node) *ParentType {
42 comptime assert(isIntrusive());42 comptime assert(isIntrusive());
43 return @fieldParentPtr(ParentType, field_name, node);43 return @fieldParentPtr(ParentType, field_name, node);
44 }44 }
45 };45 };
4646
47 first: ?&Node,47 first: ?*Node,
48 last: ?&Node,48 last: ?*Node,
49 len: usize,49 len: usize,
5050
51 /// Initialize a linked list.51 /// Initialize a linked list.
...@@ -69,7 +69,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -69,7 +69,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
69 /// Arguments:69 /// Arguments:
70 /// node: Pointer to a node in the list.70 /// node: Pointer to a node in the list.
71 /// new_node: Pointer to the new node to insert.71 /// new_node: Pointer to the new node to insert.
72 pub fn insertAfter(list: &Self, node: &Node, new_node: &Node) void {72 pub fn insertAfter(list: *Self, node: *Node, new_node: *Node) void {
73 new_node.prev = node;73 new_node.prev = node;
74 if (node.next) |next_node| {74 if (node.next) |next_node| {
75 // Intermediate node.75 // Intermediate node.
...@@ -90,7 +90,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -90,7 +90,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
90 /// Arguments:90 /// Arguments:
91 /// node: Pointer to a node in the list.91 /// node: Pointer to a node in the list.
92 /// new_node: Pointer to the new node to insert.92 /// new_node: Pointer to the new node to insert.
93 pub fn insertBefore(list: &Self, node: &Node, new_node: &Node) void {93 pub fn insertBefore(list: *Self, node: *Node, new_node: *Node) void {
94 new_node.next = node;94 new_node.next = node;
95 if (node.prev) |prev_node| {95 if (node.prev) |prev_node| {
96 // Intermediate node.96 // Intermediate node.
...@@ -110,7 +110,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -110,7 +110,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
110 ///110 ///
111 /// Arguments:111 /// Arguments:
112 /// new_node: Pointer to the new node to insert.112 /// new_node: Pointer to the new node to insert.
113 pub fn append(list: &Self, new_node: &Node) void {113 pub fn append(list: *Self, new_node: *Node) void {
114 if (list.last) |last| {114 if (list.last) |last| {
115 // Insert after last.115 // Insert after last.
116 list.insertAfter(last, new_node);116 list.insertAfter(last, new_node);
...@@ -124,7 +124,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -124,7 +124,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
124 ///124 ///
125 /// Arguments:125 /// Arguments:
126 /// new_node: Pointer to the new node to insert.126 /// new_node: Pointer to the new node to insert.
127 pub fn prepend(list: &Self, new_node: &Node) void {127 pub fn prepend(list: *Self, new_node: *Node) void {
128 if (list.first) |first| {128 if (list.first) |first| {
129 // Insert before first.129 // Insert before first.
130 list.insertBefore(first, new_node);130 list.insertBefore(first, new_node);
...@@ -143,7 +143,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -143,7 +143,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
143 ///143 ///
144 /// Arguments:144 /// Arguments:
145 /// node: Pointer to the node to be removed.145 /// node: Pointer to the node to be removed.
146 pub fn remove(list: &Self, node: &Node) void {146 pub fn remove(list: *Self, node: *Node) void {
147 if (node.prev) |prev_node| {147 if (node.prev) |prev_node| {
148 // Intermediate node.148 // Intermediate node.
149 prev_node.next = node.next;149 prev_node.next = node.next;
...@@ -168,7 +168,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -168,7 +168,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
168 ///168 ///
169 /// Returns:169 /// Returns:
170 /// A pointer to the last node in the list.170 /// A pointer to the last node in the list.
171 pub fn pop(list: &Self) ?&Node {171 pub fn pop(list: *Self) ?*Node {
172 const last = list.last ?? return null;172 const last = list.last ?? return null;
173 list.remove(last);173 list.remove(last);
174 return last;174 return last;
...@@ -178,7 +178,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -178,7 +178,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
178 ///178 ///
179 /// Returns:179 /// Returns:
180 /// A pointer to the first node in the list.180 /// A pointer to the first node in the list.
181 pub fn popFirst(list: &Self) ?&Node {181 pub fn popFirst(list: *Self) ?*Node {
182 const first = list.first ?? return null;182 const first = list.first ?? return null;
183 list.remove(first);183 list.remove(first);
184 return first;184 return first;
...@@ -191,7 +191,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -191,7 +191,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
191 ///191 ///
192 /// Returns:192 /// Returns:
193 /// A pointer to the new node.193 /// A pointer to the new node.
194 pub fn allocateNode(list: &Self, allocator: &Allocator) !&Node {194 pub fn allocateNode(list: *Self, allocator: *Allocator) !*Node {
195 comptime assert(!isIntrusive());195 comptime assert(!isIntrusive());
196 return allocator.create(Node);196 return allocator.create(Node);
197 }197 }
...@@ -201,7 +201,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -201,7 +201,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
201 /// Arguments:201 /// Arguments:
202 /// node: Pointer to the node to deallocate.202 /// node: Pointer to the node to deallocate.
203 /// allocator: Dynamic memory allocator.203 /// allocator: Dynamic memory allocator.
204 pub fn destroyNode(list: &Self, node: &Node, allocator: &Allocator) void {204 pub fn destroyNode(list: *Self, node: *Node, allocator: *Allocator) void {
205 comptime assert(!isIntrusive());205 comptime assert(!isIntrusive());
206 allocator.destroy(node);206 allocator.destroy(node);
207 }207 }
...@@ -214,7 +214,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na...@@ -214,7 +214,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na
214 ///214 ///
215 /// Returns:215 /// Returns:
216 /// A pointer to the new node.216 /// A pointer to the new node.
217 pub fn createNode(list: &Self, data: &const T, allocator: &Allocator) !&Node {217 pub fn createNode(list: *Self, data: *const T, allocator: *Allocator) !*Node {
218 comptime assert(!isIntrusive());218 comptime assert(!isIntrusive());
219 var node = try list.allocateNode(allocator);219 var node = try list.allocateNode(allocator);
220 node.* = Node.init(data);220 node.* = Node.init(data);
std/macho.zig+19-17
...@@ -42,13 +42,13 @@ pub const Symbol = struct {...@@ -42,13 +42,13 @@ pub const Symbol = struct {
42 name: []const u8,42 name: []const u8,
43 address: u64,43 address: u64,
4444
45 fn addressLessThan(lhs: &const Symbol, rhs: &const Symbol) bool {45 fn addressLessThan(lhs: *const Symbol, rhs: *const Symbol) bool {
46 return lhs.address < rhs.address;46 return lhs.address < rhs.address;
47 }47 }
48};48};
4949
50pub const SymbolTable = struct {50pub const SymbolTable = struct {
51 allocator: &mem.Allocator,51 allocator: *mem.Allocator,
52 symbols: []const Symbol,52 symbols: []const Symbol,
53 strings: []const u8,53 strings: []const u8,
5454
...@@ -56,17 +56,17 @@ pub const SymbolTable = struct {...@@ -56,17 +56,17 @@ pub const SymbolTable = struct {
56 // Ideally we'd use _mh_execute_header because it's always at 0x10000000056 // Ideally we'd use _mh_execute_header because it's always at 0x100000000
57 // in the image but as it's located in a different section than executable57 // in the image but as it's located in a different section than executable
58 // code, its displacement is different.58 // code, its displacement is different.
59 pub fn deinit(self: &SymbolTable) void {59 pub fn deinit(self: *SymbolTable) void {
60 self.allocator.free(self.symbols);60 self.allocator.free(self.symbols);
61 self.symbols = []const Symbol {};61 self.symbols = []const Symbol{};
6262
63 self.allocator.free(self.strings);63 self.allocator.free(self.strings);
64 self.strings = []const u8 {};64 self.strings = []const u8{};
65 }65 }
6666
67 pub fn search(self: &const SymbolTable, address: usize) ?&const Symbol {67 pub fn search(self: *const SymbolTable, address: usize) ?*const Symbol {
68 var min: usize = 0;68 var min: usize = 0;
69 var max: usize = self.symbols.len - 1; // Exclude sentinel.69 var max: usize = self.symbols.len - 1; // Exclude sentinel.
70 while (min < max) {70 while (min < max) {
71 const mid = min + (max - min) / 2;71 const mid = min + (max - min) / 2;
72 const curr = &self.symbols[mid];72 const curr = &self.symbols[mid];
...@@ -83,7 +83,7 @@ pub const SymbolTable = struct {...@@ -83,7 +83,7 @@ pub const SymbolTable = struct {
83 }83 }
84};84};
8585
86pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable {86pub fn loadSymbols(allocator: *mem.Allocator, in: *io.FileInStream) !SymbolTable {
87 var file = in.file;87 var file = in.file;
88 try file.seekTo(0);88 try file.seekTo(0);
8989
...@@ -118,10 +118,11 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable...@@ -118,10 +118,11 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable
118 try in.stream.readNoEof(strings);118 try in.stream.readNoEof(strings);
119119
120 var nsyms: usize = 0;120 var nsyms: usize = 0;
121 for (syms) |sym| if (isSymbol(sym)) nsyms += 1;121 for (syms) |sym|
122 if (isSymbol(sym)) nsyms += 1;
122 if (nsyms == 0) return error.MissingDebugInfo;123 if (nsyms == 0) return error.MissingDebugInfo;
123124
124 var symbols = try allocator.alloc(Symbol, nsyms + 1); // Room for sentinel.125 var symbols = try allocator.alloc(Symbol, nsyms + 1); // Room for sentinel.
125 errdefer allocator.free(symbols);126 errdefer allocator.free(symbols);
126127
127 var pie_slide: usize = 0;128 var pie_slide: usize = 0;
...@@ -132,7 +133,7 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable...@@ -132,7 +133,7 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable
132 const end = ??mem.indexOfScalarPos(u8, strings, start, 0);133 const end = ??mem.indexOfScalarPos(u8, strings, start, 0);
133 const name = strings[start..end];134 const name = strings[start..end];
134 const address = sym.n_value;135 const address = sym.n_value;
135 symbols[nsym] = Symbol { .name = name, .address = address };136 symbols[nsym] = Symbol{ .name = name, .address = address };
136 nsym += 1;137 nsym += 1;
137 if (is_pie and mem.eql(u8, name, "_SymbolTable_deinit")) {138 if (is_pie and mem.eql(u8, name, "_SymbolTable_deinit")) {
138 pie_slide = @ptrToInt(SymbolTable.deinit) - address;139 pie_slide = @ptrToInt(SymbolTable.deinit) - address;
...@@ -145,26 +146,27 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable...@@ -145,26 +146,27 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable
145 // Insert the sentinel. Since we don't know where the last function ends,146 // Insert the sentinel. Since we don't know where the last function ends,
146 // we arbitrarily limit it to the start address + 4 KB.147 // we arbitrarily limit it to the start address + 4 KB.
147 const top = symbols[nsyms - 1].address + 4096;148 const top = symbols[nsyms - 1].address + 4096;
148 symbols[nsyms] = Symbol { .name = "", .address = top };149 symbols[nsyms] = Symbol{ .name = "", .address = top };
149150
150 if (pie_slide != 0) {151 if (pie_slide != 0) {
151 for (symbols) |*symbol| symbol.address += pie_slide;152 for (symbols) |*symbol|
153 symbol.address += pie_slide;
152 }154 }
153155
154 return SymbolTable {156 return SymbolTable{
155 .allocator = allocator,157 .allocator = allocator,
156 .symbols = symbols,158 .symbols = symbols,
157 .strings = strings,159 .strings = strings,
158 };160 };
159}161}
160162
161fn readNoEof(in: &io.FileInStream, comptime T: type, result: []T) !void {163fn readNoEof(in: *io.FileInStream, comptime T: type, result: []T) !void {
162 return in.stream.readNoEof(([]u8)(result));164 return in.stream.readNoEof(([]u8)(result));
163}165}
164fn readOneNoEof(in: &io.FileInStream, comptime T: type, result: &T) !void {166fn readOneNoEof(in: *io.FileInStream, comptime T: type, result: *T) !void {
165 return readNoEof(in, T, result[0..1]);167 return readNoEof(in, T, result[0..1]);
166}168}
167169
168fn isSymbol(sym: &const Nlist64) bool {170fn isSymbol(sym: *const Nlist64) bool {
169 return sym.n_value != 0 and sym.n_desc == 0;171 return sym.n_value != 0 and sym.n_desc == 0;
170}172}
std/math/atan.zig+15-17
...@@ -17,25 +17,25 @@ pub fn atan(x: var) @typeOf(x) {...@@ -17,25 +17,25 @@ pub fn atan(x: var) @typeOf(x) {
17}17}
1818
19fn atan32(x_: f32) f32 {19fn atan32(x_: f32) f32 {
20 const atanhi = []const f32 {20 const atanhi = []const f32{
21 4.6364760399e-01, // atan(0.5)hi21 4.6364760399e-01, // atan(0.5)hi
22 7.8539812565e-01, // atan(1.0)hi22 7.8539812565e-01, // atan(1.0)hi
23 9.8279368877e-01, // atan(1.5)hi23 9.8279368877e-01, // atan(1.5)hi
24 1.5707962513e+00, // atan(inf)hi24 1.5707962513e+00, // atan(inf)hi
25 };25 };
2626
27 const atanlo = []const f32 {27 const atanlo = []const f32{
28 5.0121582440e-09, // atan(0.5)lo28 5.0121582440e-09, // atan(0.5)lo
29 3.7748947079e-08, // atan(1.0)lo29 3.7748947079e-08, // atan(1.0)lo
30 3.4473217170e-08, // atan(1.5)lo30 3.4473217170e-08, // atan(1.5)lo
31 7.5497894159e-08, // atan(inf)lo31 7.5497894159e-08, // atan(inf)lo
32 };32 };
3333
34 const aT = []const f32 {34 const aT = []const f32{
35 3.3333328366e-01,35 3.3333328366e-01,
36 -1.9999158382e-01,36 -1.9999158382e-01,
37 1.4253635705e-01,37 1.4253635705e-01,
38 -1.0648017377e-01,38 -1.0648017377e-01,
39 6.1687607318e-02,39 6.1687607318e-02,
40 };40 };
4141
...@@ -80,8 +80,7 @@ fn atan32(x_: f32) f32 {...@@ -80,8 +80,7 @@ fn atan32(x_: f32) f32 {
80 id = 1;80 id = 1;
81 x = (x - 1.0) / (x + 1.0);81 x = (x - 1.0) / (x + 1.0);
82 }82 }
83 }83 } else {
84 else {
85 // |x| < 2.437584 // |x| < 2.4375
86 if (ix < 0x401C0000) {85 if (ix < 0x401C0000) {
87 id = 2;86 id = 2;
...@@ -109,31 +108,31 @@ fn atan32(x_: f32) f32 {...@@ -109,31 +108,31 @@ fn atan32(x_: f32) f32 {
109}108}
110109
111fn atan64(x_: f64) f64 {110fn atan64(x_: f64) f64 {
112 const atanhi = []const f64 {111 const atanhi = []const f64{
113 4.63647609000806093515e-01, // atan(0.5)hi112 4.63647609000806093515e-01, // atan(0.5)hi
114 7.85398163397448278999e-01, // atan(1.0)hi113 7.85398163397448278999e-01, // atan(1.0)hi
115 9.82793723247329054082e-01, // atan(1.5)hi114 9.82793723247329054082e-01, // atan(1.5)hi
116 1.57079632679489655800e+00, // atan(inf)hi115 1.57079632679489655800e+00, // atan(inf)hi
117 };116 };
118117
119 const atanlo = []const f64 {118 const atanlo = []const f64{
120 2.26987774529616870924e-17, // atan(0.5)lo119 2.26987774529616870924e-17, // atan(0.5)lo
121 3.06161699786838301793e-17, // atan(1.0)lo120 3.06161699786838301793e-17, // atan(1.0)lo
122 1.39033110312309984516e-17, // atan(1.5)lo121 1.39033110312309984516e-17, // atan(1.5)lo
123 6.12323399573676603587e-17, // atan(inf)lo122 6.12323399573676603587e-17, // atan(inf)lo
124 };123 };
125124
126 const aT = []const f64 {125 const aT = []const f64{
127 3.33333333333329318027e-01,126 3.33333333333329318027e-01,
128 -1.99999999998764832476e-01,127 -1.99999999998764832476e-01,
129 1.42857142725034663711e-01,128 1.42857142725034663711e-01,
130 -1.11111104054623557880e-01,129 -1.11111104054623557880e-01,
131 9.09088713343650656196e-02,130 9.09088713343650656196e-02,
132 -7.69187620504482999495e-02,131 -7.69187620504482999495e-02,
133 6.66107313738753120669e-02,132 6.66107313738753120669e-02,
134 -5.83357013379057348645e-02,133 -5.83357013379057348645e-02,
135 4.97687799461593236017e-02,134 4.97687799461593236017e-02,
136 -3.65315727442169155270e-02,135 -3.65315727442169155270e-02,
137 1.62858201153657823623e-02,136 1.62858201153657823623e-02,
138 };137 };
139138
...@@ -179,8 +178,7 @@ fn atan64(x_: f64) f64 {...@@ -179,8 +178,7 @@ fn atan64(x_: f64) f64 {
179 id = 1;178 id = 1;
180 x = (x - 1.0) / (x + 1.0);179 x = (x - 1.0) / (x + 1.0);
181 }180 }
182 }181 } else {
183 else {
184 // |x| < 2.4375182 // |x| < 2.4375
185 if (ix < 0x40038000) {183 if (ix < 0x40038000) {
186 id = 2;184 id = 2;
std/math/atan2.zig+2-4
...@@ -53,8 +53,7 @@ fn atan2_32(y: f32, x: f32) f32 {...@@ -53,8 +53,7 @@ fn atan2_32(y: f32, x: f32) f32 {
5353
54 if (iy == 0) {54 if (iy == 0) {
55 switch (m) {55 switch (m) {
56 0,56 0, 1 => return y, // atan(+-0, +...)
57 1 => return y, // atan(+-0, +...)
58 2 => return pi, // atan(+0, -...)57 2 => return pi, // atan(+0, -...)
59 3 => return -pi, // atan(-0, -...)58 3 => return -pi, // atan(-0, -...)
60 else => unreachable,59 else => unreachable,
...@@ -144,8 +143,7 @@ fn atan2_64(y: f64, x: f64) f64 {...@@ -144,8 +143,7 @@ fn atan2_64(y: f64, x: f64) f64 {
144143
145 if (iy | ly == 0) {144 if (iy | ly == 0) {
146 switch (m) {145 switch (m) {
147 0,146 0, 1 => return y, // atan(+-0, +...)
148 1 => return y, // atan(+-0, +...)
149 2 => return pi, // atan(+0, -...)147 2 => return pi, // atan(+0, -...)
150 3 => return -pi, // atan(-0, -...)148 3 => return -pi, // atan(-0, -...)
151 else => unreachable,149 else => unreachable,
std/math/complex/atan.zig+2-2
...@@ -29,7 +29,7 @@ fn redupif32(x: f32) f32 {...@@ -29,7 +29,7 @@ fn redupif32(x: f32) f32 {
29 return ((x - u * DP1) - u * DP2) - t * DP3;29 return ((x - u * DP1) - u * DP2) - t * DP3;
30}30}
3131
32fn atan32(z: &const Complex(f32)) Complex(f32) {32fn atan32(z: *const Complex(f32)) Complex(f32) {
33 const maxnum = 1.0e38;33 const maxnum = 1.0e38;
3434
35 const x = z.re;35 const x = z.re;
...@@ -78,7 +78,7 @@ fn redupif64(x: f64) f64 {...@@ -78,7 +78,7 @@ fn redupif64(x: f64) f64 {
78 return ((x - u * DP1) - u * DP2) - t * DP3;78 return ((x - u * DP1) - u * DP2) - t * DP3;
79}79}
8080
81fn atan64(z: &const Complex(f64)) Complex(f64) {81fn atan64(z: *const Complex(f64)) Complex(f64) {
82 const maxnum = 1.0e308;82 const maxnum = 1.0e308;
8383
84 const x = z.re;84 const x = z.re;
std/math/complex/cosh.zig+2-2
...@@ -15,7 +15,7 @@ pub fn cosh(z: var) Complex(@typeOf(z.re)) {...@@ -15,7 +15,7 @@ pub fn cosh(z: var) Complex(@typeOf(z.re)) {
15 };15 };
16}16}
1717
18fn cosh32(z: &const Complex(f32)) Complex(f32) {18fn cosh32(z: *const Complex(f32)) Complex(f32) {
19 const x = z.re;19 const x = z.re;
20 const y = z.im;20 const y = z.im;
2121
...@@ -78,7 +78,7 @@ fn cosh32(z: &const Complex(f32)) Complex(f32) {...@@ -78,7 +78,7 @@ fn cosh32(z: &const Complex(f32)) Complex(f32) {
78 return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y));78 return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y));
79}79}
8080
81fn cosh64(z: &const Complex(f64)) Complex(f64) {81fn cosh64(z: *const Complex(f64)) Complex(f64) {
82 const x = z.re;82 const x = z.re;
83 const y = z.im;83 const y = z.im;
8484
std/math/complex/exp.zig+2-2
...@@ -16,7 +16,7 @@ pub fn exp(z: var) Complex(@typeOf(z.re)) {...@@ -16,7 +16,7 @@ pub fn exp(z: var) Complex(@typeOf(z.re)) {
16 };16 };
17}17}
1818
19fn exp32(z: &const Complex(f32)) Complex(f32) {19fn exp32(z: *const Complex(f32)) Complex(f32) {
20 @setFloatMode(this, @import("builtin").FloatMode.Strict);20 @setFloatMode(this, @import("builtin").FloatMode.Strict);
2121
22 const exp_overflow = 0x42b17218; // max_exp * ln2 ~= 88.7228395522 const exp_overflow = 0x42b17218; // max_exp * ln2 ~= 88.72283955
...@@ -63,7 +63,7 @@ fn exp32(z: &const Complex(f32)) Complex(f32) {...@@ -63,7 +63,7 @@ fn exp32(z: &const Complex(f32)) Complex(f32) {
63 }63 }
64}64}
6565
66fn exp64(z: &const Complex(f64)) Complex(f64) {66fn exp64(z: *const Complex(f64)) Complex(f64) {
67 const exp_overflow = 0x40862e42; // high bits of max_exp * ln2 ~= 71067 const exp_overflow = 0x40862e42; // high bits of max_exp * ln2 ~= 710
68 const cexp_overflow = 0x4096b8e4; // (max_exp - min_denorm_exp) * ln268 const cexp_overflow = 0x4096b8e4; // (max_exp - min_denorm_exp) * ln2
6969
std/math/complex/index.zig+18-18
...@@ -31,60 +31,60 @@ pub fn Complex(comptime T: type) type {...@@ -31,60 +31,60 @@ pub fn Complex(comptime T: type) type {
31 im: T,31 im: T,
3232
33 pub fn new(re: T, im: T) Self {33 pub fn new(re: T, im: T) Self {
34 return Self {34 return Self{
35 .re = re,35 .re = re,
36 .im = im,36 .im = im,
37 };37 };
38 }38 }
3939
40 pub fn add(self: &const Self, other: &const Self) Self {40 pub fn add(self: *const Self, other: *const Self) Self {
41 return Self {41 return Self{
42 .re = self.re + other.re,42 .re = self.re + other.re,
43 .im = self.im + other.im,43 .im = self.im + other.im,
44 };44 };
45 }45 }
4646
47 pub fn sub(self: &const Self, other: &const Self) Self {47 pub fn sub(self: *const Self, other: *const Self) Self {
48 return Self {48 return Self{
49 .re = self.re - other.re,49 .re = self.re - other.re,
50 .im = self.im - other.im,50 .im = self.im - other.im,
51 };51 };
52 }52 }
5353
54 pub fn mul(self: &const Self, other: &const Self) Self {54 pub fn mul(self: *const Self, other: *const Self) Self {
55 return Self {55 return Self{
56 .re = self.re * other.re - self.im * other.im,56 .re = self.re * other.re - self.im * other.im,
57 .im = self.im * other.re + self.re * other.im,57 .im = self.im * other.re + self.re * other.im,
58 };58 };
59 }59 }
6060
61 pub fn div(self: &const Self, other: &const Self) Self {61 pub fn div(self: *const Self, other: *const Self) Self {
62 const re_num = self.re * other.re + self.im * other.im;62 const re_num = self.re * other.re + self.im * other.im;
63 const im_num = self.im * other.re - self.re * other.im;63 const im_num = self.im * other.re - self.re * other.im;
64 const den = other.re * other.re + other.im * other.im;64 const den = other.re * other.re + other.im * other.im;
6565
66 return Self {66 return Self{
67 .re = re_num / den,67 .re = re_num / den,
68 .im = im_num / den,68 .im = im_num / den,
69 };69 };
70 }70 }
7171
72 pub fn conjugate(self: &const Self) Self {72 pub fn conjugate(self: *const Self) Self {
73 return Self {73 return Self{
74 .re = self.re,74 .re = self.re,
75 .im = -self.im,75 .im = -self.im,
76 };76 };
77 }77 }
7878
79 pub fn reciprocal(self: &const Self) Self {79 pub fn reciprocal(self: *const Self) Self {
80 const m = self.re * self.re + self.im * self.im;80 const m = self.re * self.re + self.im * self.im;
81 return Self {81 return Self{
82 .re = self.re / m,82 .re = self.re / m,
83 .im = -self.im / m,83 .im = -self.im / m,
84 };84 };
85 }85 }
8686
87 pub fn magnitude(self: &const Self) T {87 pub fn magnitude(self: *const Self) T {
88 return math.sqrt(self.re * self.re + self.im * self.im);88 return math.sqrt(self.re * self.re + self.im * self.im);
89 }89 }
90 };90 };
...@@ -121,8 +121,8 @@ test "complex.div" {...@@ -121,8 +121,8 @@ test "complex.div" {
121 const b = Complex(f32).new(2, 7);121 const b = Complex(f32).new(2, 7);
122 const c = a.div(b);122 const c = a.div(b);
123123
124 debug.assert(math.approxEq(f32, c.re, f32(31)/53, epsilon) and124 debug.assert(math.approxEq(f32, c.re, f32(31) / 53, epsilon) and
125 math.approxEq(f32, c.im, f32(-29)/53, epsilon));125 math.approxEq(f32, c.im, f32(-29) / 53, epsilon));
126}126}
127127
128test "complex.conjugate" {128test "complex.conjugate" {
...@@ -136,8 +136,8 @@ test "complex.reciprocal" {...@@ -136,8 +136,8 @@ test "complex.reciprocal" {
136 const a = Complex(f32).new(5, 3);136 const a = Complex(f32).new(5, 3);
137 const c = a.reciprocal();137 const c = a.reciprocal();
138138
139 debug.assert(math.approxEq(f32, c.re, f32(5)/34, epsilon) and139 debug.assert(math.approxEq(f32, c.re, f32(5) / 34, epsilon) and
140 math.approxEq(f32, c.im, f32(-3)/34, epsilon));140 math.approxEq(f32, c.im, f32(-3) / 34, epsilon));
141}141}
142142
143test "complex.magnitude" {143test "complex.magnitude" {
std/math/complex/ldexp.zig+4-4
...@@ -14,7 +14,7 @@ pub fn ldexp_cexp(z: var, expt: i32) Complex(@typeOf(z.re)) {...@@ -14,7 +14,7 @@ pub fn ldexp_cexp(z: var, expt: i32) Complex(@typeOf(z.re)) {
14 };14 };
15}15}
1616
17fn frexp_exp32(x: f32, expt: &i32) f32 {17fn frexp_exp32(x: f32, expt: *i32) f32 {
18 const k = 235; // reduction constant18 const k = 235; // reduction constant
19 const kln2 = 162.88958740; // k * ln219 const kln2 = 162.88958740; // k * ln2
2020
...@@ -24,7 +24,7 @@ fn frexp_exp32(x: f32, expt: &i32) f32 {...@@ -24,7 +24,7 @@ fn frexp_exp32(x: f32, expt: &i32) f32 {
24 return @bitCast(f32, (hx & 0x7fffff) | ((0x7f + 127) << 23));24 return @bitCast(f32, (hx & 0x7fffff) | ((0x7f + 127) << 23));
25}25}
2626
27fn ldexp_cexp32(z: &const Complex(f32), expt: i32) Complex(f32) {27fn ldexp_cexp32(z: *const Complex(f32), expt: i32) Complex(f32) {
28 var ex_expt: i32 = undefined;28 var ex_expt: i32 = undefined;
29 const exp_x = frexp_exp32(z.re, &ex_expt);29 const exp_x = frexp_exp32(z.re, &ex_expt);
30 const exptf = expt + ex_expt;30 const exptf = expt + ex_expt;
...@@ -38,7 +38,7 @@ fn ldexp_cexp32(z: &const Complex(f32), expt: i32) Complex(f32) {...@@ -38,7 +38,7 @@ fn ldexp_cexp32(z: &const Complex(f32), expt: i32) Complex(f32) {
38 return Complex(f32).new(math.cos(z.im) * exp_x * scale1 * scale2, math.sin(z.im) * exp_x * scale1 * scale2);38 return Complex(f32).new(math.cos(z.im) * exp_x * scale1 * scale2, math.sin(z.im) * exp_x * scale1 * scale2);
39}39}
4040
41fn frexp_exp64(x: f64, expt: &i32) f64 {41fn frexp_exp64(x: f64, expt: *i32) f64 {
42 const k = 1799; // reduction constant42 const k = 1799; // reduction constant
43 const kln2 = 1246.97177782734161156; // k * ln243 const kln2 = 1246.97177782734161156; // k * ln2
4444
...@@ -54,7 +54,7 @@ fn frexp_exp64(x: f64, expt: &i32) f64 {...@@ -54,7 +54,7 @@ fn frexp_exp64(x: f64, expt: &i32) f64 {
54 return @bitCast(f64, (u64(high_word) << 32) | lx);54 return @bitCast(f64, (u64(high_word) << 32) | lx);
55}55}
5656
57fn ldexp_cexp64(z: &const Complex(f64), expt: i32) Complex(f64) {57fn ldexp_cexp64(z: *const Complex(f64), expt: i32) Complex(f64) {
58 var ex_expt: i32 = undefined;58 var ex_expt: i32 = undefined;
59 const exp_x = frexp_exp64(z.re, &ex_expt);59 const exp_x = frexp_exp64(z.re, &ex_expt);
60 const exptf = i64(expt + ex_expt);60 const exptf = i64(expt + ex_expt);
std/math/complex/pow.zig+1-1
...@@ -4,7 +4,7 @@ const math = std.math;...@@ -4,7 +4,7 @@ const math = std.math;
4const cmath = math.complex;4const cmath = math.complex;
5const Complex = cmath.Complex;5const Complex = cmath.Complex;
66
7pub fn pow(comptime T: type, z: &const T, c: &const T) T {7pub fn pow(comptime T: type, z: *const T, c: *const T) T {
8 const p = cmath.log(z);8 const p = cmath.log(z);
9 const q = c.mul(p);9 const q = c.mul(p);
10 return cmath.exp(q);10 return cmath.exp(q);
std/math/complex/sinh.zig+2-2
...@@ -15,7 +15,7 @@ pub fn sinh(z: var) Complex(@typeOf(z.re)) {...@@ -15,7 +15,7 @@ pub fn sinh(z: var) Complex(@typeOf(z.re)) {
15 };15 };
16}16}
1717
18fn sinh32(z: &const Complex(f32)) Complex(f32) {18fn sinh32(z: *const Complex(f32)) Complex(f32) {
19 const x = z.re;19 const x = z.re;
20 const y = z.im;20 const y = z.im;
2121
...@@ -78,7 +78,7 @@ fn sinh32(z: &const Complex(f32)) Complex(f32) {...@@ -78,7 +78,7 @@ fn sinh32(z: &const Complex(f32)) Complex(f32) {
78 return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y));78 return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y));
79}79}
8080
81fn sinh64(z: &const Complex(f64)) Complex(f64) {81fn sinh64(z: *const Complex(f64)) Complex(f64) {
82 const x = z.re;82 const x = z.re;
83 const y = z.im;83 const y = z.im;
8484
std/math/complex/sqrt.zig+2-2
...@@ -15,7 +15,7 @@ pub fn sqrt(z: var) Complex(@typeOf(z.re)) {...@@ -15,7 +15,7 @@ pub fn sqrt(z: var) Complex(@typeOf(z.re)) {
15 };15 };
16}16}
1717
18fn sqrt32(z: &const Complex(f32)) Complex(f32) {18fn sqrt32(z: *const Complex(f32)) Complex(f32) {
19 const x = z.re;19 const x = z.re;
20 const y = z.im;20 const y = z.im;
2121
...@@ -57,7 +57,7 @@ fn sqrt32(z: &const Complex(f32)) Complex(f32) {...@@ -57,7 +57,7 @@ fn sqrt32(z: &const Complex(f32)) Complex(f32) {
57 }57 }
58}58}
5959
60fn sqrt64(z: &const Complex(f64)) Complex(f64) {60fn sqrt64(z: *const Complex(f64)) Complex(f64) {
61 // may encounter overflow for im,re >= DBL_MAX / (1 + sqrt(2))61 // may encounter overflow for im,re >= DBL_MAX / (1 + sqrt(2))
62 const threshold = 0x1.a827999fcef32p+1022;62 const threshold = 0x1.a827999fcef32p+1022;
6363
std/math/complex/tanh.zig+4-4
...@@ -13,7 +13,7 @@ pub fn tanh(z: var) Complex(@typeOf(z.re)) {...@@ -13,7 +13,7 @@ pub fn tanh(z: var) Complex(@typeOf(z.re)) {
13 };13 };
14}14}
1515
16fn tanh32(z: &const Complex(f32)) Complex(f32) {16fn tanh32(z: *const Complex(f32)) Complex(f32) {
17 const x = z.re;17 const x = z.re;
18 const y = z.im;18 const y = z.im;
1919
...@@ -51,7 +51,7 @@ fn tanh32(z: &const Complex(f32)) Complex(f32) {...@@ -51,7 +51,7 @@ fn tanh32(z: &const Complex(f32)) Complex(f32) {
51 return Complex(f32).new((beta * rho * s) / den, t / den);51 return Complex(f32).new((beta * rho * s) / den, t / den);
52}52}
5353
54fn tanh64(z: &const Complex(f64)) Complex(f64) {54fn tanh64(z: *const Complex(f64)) Complex(f64) {
55 const x = z.re;55 const x = z.re;
56 const y = z.im;56 const y = z.im;
5757
...@@ -98,7 +98,7 @@ test "complex.ctanh32" {...@@ -98,7 +98,7 @@ test "complex.ctanh32" {
98 const a = Complex(f32).new(5, 3);98 const a = Complex(f32).new(5, 3);
99 const c = tanh(a);99 const c = tanh(a);
100100
101 debug.assert(math.approxEq(f32, c.re, 0.999913, epsilon));101 debug.assert(math.approxEq(f32, c.re, 0.999913, epsilon));
102 debug.assert(math.approxEq(f32, c.im, -0.000025, epsilon));102 debug.assert(math.approxEq(f32, c.im, -0.000025, epsilon));
103}103}
104104
...@@ -106,6 +106,6 @@ test "complex.ctanh64" {...@@ -106,6 +106,6 @@ test "complex.ctanh64" {
106 const a = Complex(f64).new(5, 3);106 const a = Complex(f64).new(5, 3);
107 const c = tanh(a);107 const c = tanh(a);
108108
109 debug.assert(math.approxEq(f64, c.re, 0.999913, epsilon));109 debug.assert(math.approxEq(f64, c.re, 0.999913, epsilon));
110 debug.assert(math.approxEq(f64, c.im, -0.000025, epsilon));110 debug.assert(math.approxEq(f64, c.im, -0.000025, epsilon));
111}111}
std/math/exp.zig+13-17
...@@ -20,10 +20,10 @@ pub fn exp(x: var) @typeOf(x) {...@@ -20,10 +20,10 @@ pub fn exp(x: var) @typeOf(x) {
20fn exp32(x_: f32) f32 {20fn exp32(x_: f32) f32 {
21 @setFloatMode(this, builtin.FloatMode.Strict);21 @setFloatMode(this, builtin.FloatMode.Strict);
2222
23 const half = []f32 { 0.5, -0.5 };23 const half = []f32{ 0.5, -0.5 };
24 const ln2hi = 6.9314575195e-1;24 const ln2hi = 6.9314575195e-1;
25 const ln2lo = 1.4286067653e-6;25 const ln2lo = 1.4286067653e-6;
26 const invln2 = 1.4426950216e+0;26 const invln2 = 1.4426950216e+0;
27 const P1 = 1.6666625440e-1;27 const P1 = 1.6666625440e-1;
28 const P2 = -2.7667332906e-3;28 const P2 = -2.7667332906e-3;
2929
...@@ -47,7 +47,7 @@ fn exp32(x_: f32) f32 {...@@ -47,7 +47,7 @@ fn exp32(x_: f32) f32 {
47 return x * 0x1.0p127;47 return x * 0x1.0p127;
48 }48 }
49 if (sign != 0) {49 if (sign != 0) {
50 math.forceEval(-0x1.0p-149 / x); // overflow50 math.forceEval(-0x1.0p-149 / x); // overflow
51 // x <= -103.97208451 // x <= -103.972084
52 if (hx >= 0x42CFF1B5) {52 if (hx >= 0x42CFF1B5) {
53 return 0;53 return 0;
...@@ -64,8 +64,7 @@ fn exp32(x_: f32) f32 {...@@ -64,8 +64,7 @@ fn exp32(x_: f32) f32 {
64 // |x| > 1.5 * ln264 // |x| > 1.5 * ln2
65 if (hx > 0x3F851592) {65 if (hx > 0x3F851592) {
66 k = i32(invln2 * x + half[usize(sign)]);66 k = i32(invln2 * x + half[usize(sign)]);
67 }67 } else {
68 else {
69 k = 1 - sign - sign;68 k = 1 - sign - sign;
70 }69 }
7170
...@@ -79,8 +78,7 @@ fn exp32(x_: f32) f32 {...@@ -79,8 +78,7 @@ fn exp32(x_: f32) f32 {
79 k = 0;78 k = 0;
80 hi = x;79 hi = x;
81 lo = 0;80 lo = 0;
82 }81 } else {
83 else {
84 math.forceEval(0x1.0p127 + x); // inexact82 math.forceEval(0x1.0p127 + x); // inexact
85 return 1 + x;83 return 1 + x;
86 }84 }
...@@ -99,15 +97,15 @@ fn exp32(x_: f32) f32 {...@@ -99,15 +97,15 @@ fn exp32(x_: f32) f32 {
99fn exp64(x_: f64) f64 {97fn exp64(x_: f64) f64 {
100 @setFloatMode(this, builtin.FloatMode.Strict);98 @setFloatMode(this, builtin.FloatMode.Strict);
10199
102 const half = []const f64 { 0.5, -0.5 };100 const half = []const f64{ 0.5, -0.5 };
103 const ln2hi: f64 = 6.93147180369123816490e-01;101 const ln2hi: f64 = 6.93147180369123816490e-01;
104 const ln2lo: f64 = 1.90821492927058770002e-10;102 const ln2lo: f64 = 1.90821492927058770002e-10;
105 const invln2: f64 = 1.44269504088896338700e+00;103 const invln2: f64 = 1.44269504088896338700e+00;
106 const P1: f64 = 1.66666666666666019037e-01;104 const P1: f64 = 1.66666666666666019037e-01;
107 const P2: f64 = -2.77777777770155933842e-03;105 const P2: f64 = -2.77777777770155933842e-03;
108 const P3: f64 = 6.61375632143793436117e-05;106 const P3: f64 = 6.61375632143793436117e-05;
109 const P4: f64 = -1.65339022054652515390e-06;107 const P4: f64 = -1.65339022054652515390e-06;
110 const P5: f64 = 4.13813679705723846039e-08;108 const P5: f64 = 4.13813679705723846039e-08;
111109
112 var x = x_;110 var x = x_;
113 var ux = @bitCast(u64, x);111 var ux = @bitCast(u64, x);
...@@ -151,8 +149,7 @@ fn exp64(x_: f64) f64 {...@@ -151,8 +149,7 @@ fn exp64(x_: f64) f64 {
151 // |x| >= 1.5 * ln2149 // |x| >= 1.5 * ln2
152 if (hx > 0x3FF0A2B2) {150 if (hx > 0x3FF0A2B2) {
153 k = i32(invln2 * x + half[usize(sign)]);151 k = i32(invln2 * x + half[usize(sign)]);
154 }152 } else {
155 else {
156 k = 1 - sign - sign;153 k = 1 - sign - sign;
157 }154 }
158155
...@@ -166,8 +163,7 @@ fn exp64(x_: f64) f64 {...@@ -166,8 +163,7 @@ fn exp64(x_: f64) f64 {
166 k = 0;163 k = 0;
167 hi = x;164 hi = x;
168 lo = 0;165 lo = 0;
169 }166 } else {
170 else {
171 // inexact if x != 0167 // inexact if x != 0
172 // math.forceEval(0x1.0p1023 + x);168 // math.forceEval(0x1.0p1023 + x);
173 return 1 + x;169 return 1 + x;
std/math/exp2.zig+140-140
...@@ -16,7 +16,7 @@ pub fn exp2(x: var) @typeOf(x) {...@@ -16,7 +16,7 @@ pub fn exp2(x: var) @typeOf(x) {
16 };16 };
17}17}
1818
19const exp2ft = []const f64 {19const exp2ft = []const f64{
20 0x1.6a09e667f3bcdp-1,20 0x1.6a09e667f3bcdp-1,
21 0x1.7a11473eb0187p-1,21 0x1.7a11473eb0187p-1,
22 0x1.8ace5422aa0dbp-1,22 0x1.8ace5422aa0dbp-1,
...@@ -92,195 +92,195 @@ fn exp2_32(x: f32) f32 {...@@ -92,195 +92,195 @@ fn exp2_32(x: f32) f32 {
92 return f32(r * uk);92 return f32(r * uk);
93}93}
9494
95const exp2dt = []f64 {95const exp2dt = []f64{
96 // exp2(z + eps) eps96 // exp2(z + eps) eps
97 0x1.6a09e667f3d5dp-1, 0x1.9880p-44,97 0x1.6a09e667f3d5dp-1, 0x1.9880p-44,
98 0x1.6b052fa751744p-1, 0x1.8000p-50,98 0x1.6b052fa751744p-1, 0x1.8000p-50,
99 0x1.6c012750bd9fep-1, -0x1.8780p-45,99 0x1.6c012750bd9fep-1, -0x1.8780p-45,
100 0x1.6cfdcddd476bfp-1, 0x1.ec00p-46,100 0x1.6cfdcddd476bfp-1, 0x1.ec00p-46,
101 0x1.6dfb23c651a29p-1, -0x1.8000p-50,101 0x1.6dfb23c651a29p-1, -0x1.8000p-50,
102 0x1.6ef9298593ae3p-1, -0x1.c000p-52,102 0x1.6ef9298593ae3p-1, -0x1.c000p-52,
103 0x1.6ff7df9519386p-1, -0x1.fd80p-45,103 0x1.6ff7df9519386p-1, -0x1.fd80p-45,
104 0x1.70f7466f42da3p-1, -0x1.c880p-45,104 0x1.70f7466f42da3p-1, -0x1.c880p-45,
105 0x1.71f75e8ec5fc3p-1, 0x1.3c00p-46,105 0x1.71f75e8ec5fc3p-1, 0x1.3c00p-46,
106 0x1.72f8286eacf05p-1, -0x1.8300p-44,106 0x1.72f8286eacf05p-1, -0x1.8300p-44,
107 0x1.73f9a48a58152p-1, -0x1.0c00p-47,107 0x1.73f9a48a58152p-1, -0x1.0c00p-47,
108 0x1.74fbd35d7ccfcp-1, 0x1.f880p-45,108 0x1.74fbd35d7ccfcp-1, 0x1.f880p-45,
109 0x1.75feb564267f1p-1, 0x1.3e00p-47,109 0x1.75feb564267f1p-1, 0x1.3e00p-47,
110 0x1.77024b1ab6d48p-1, -0x1.7d00p-45,110 0x1.77024b1ab6d48p-1, -0x1.7d00p-45,
111 0x1.780694fde5d38p-1, -0x1.d000p-50,111 0x1.780694fde5d38p-1, -0x1.d000p-50,
112 0x1.790b938ac1d00p-1, 0x1.3000p-49,112 0x1.790b938ac1d00p-1, 0x1.3000p-49,
113 0x1.7a11473eb0178p-1, -0x1.d000p-49,113 0x1.7a11473eb0178p-1, -0x1.d000p-49,
114 0x1.7b17b0976d060p-1, 0x1.0400p-45,114 0x1.7b17b0976d060p-1, 0x1.0400p-45,
115 0x1.7c1ed0130c133p-1, 0x1.0000p-53,115 0x1.7c1ed0130c133p-1, 0x1.0000p-53,
116 0x1.7d26a62ff8636p-1, -0x1.6900p-45,116 0x1.7d26a62ff8636p-1, -0x1.6900p-45,
117 0x1.7e2f336cf4e3bp-1, -0x1.2e00p-47,117 0x1.7e2f336cf4e3bp-1, -0x1.2e00p-47,
118 0x1.7f3878491c3e8p-1, -0x1.4580p-45,118 0x1.7f3878491c3e8p-1, -0x1.4580p-45,
119 0x1.80427543e1b4ep-1, 0x1.3000p-44,119 0x1.80427543e1b4ep-1, 0x1.3000p-44,
120 0x1.814d2add1071ap-1, 0x1.f000p-47,120 0x1.814d2add1071ap-1, 0x1.f000p-47,
121 0x1.82589994ccd7ep-1, -0x1.1c00p-45,121 0x1.82589994ccd7ep-1, -0x1.1c00p-45,
122 0x1.8364c1eb942d0p-1, 0x1.9d00p-45,122 0x1.8364c1eb942d0p-1, 0x1.9d00p-45,
123 0x1.8471a4623cab5p-1, 0x1.7100p-43,123 0x1.8471a4623cab5p-1, 0x1.7100p-43,
124 0x1.857f4179f5bbcp-1, 0x1.2600p-45,124 0x1.857f4179f5bbcp-1, 0x1.2600p-45,
125 0x1.868d99b4491afp-1, -0x1.2c40p-44,125 0x1.868d99b4491afp-1, -0x1.2c40p-44,
126 0x1.879cad931a395p-1, -0x1.3000p-45,126 0x1.879cad931a395p-1, -0x1.3000p-45,
127 0x1.88ac7d98a65b8p-1, -0x1.a800p-45,127 0x1.88ac7d98a65b8p-1, -0x1.a800p-45,
128 0x1.89bd0a4785800p-1, -0x1.d000p-49,128 0x1.89bd0a4785800p-1, -0x1.d000p-49,
129 0x1.8ace5422aa223p-1, 0x1.3280p-44,129 0x1.8ace5422aa223p-1, 0x1.3280p-44,
130 0x1.8be05bad619fap-1, 0x1.2b40p-43,130 0x1.8be05bad619fap-1, 0x1.2b40p-43,
131 0x1.8cf3216b54383p-1, -0x1.ed00p-45,131 0x1.8cf3216b54383p-1, -0x1.ed00p-45,
132 0x1.8e06a5e08664cp-1, -0x1.0500p-45,132 0x1.8e06a5e08664cp-1, -0x1.0500p-45,
133 0x1.8f1ae99157807p-1, 0x1.8280p-45,133 0x1.8f1ae99157807p-1, 0x1.8280p-45,
134 0x1.902fed0282c0ep-1, -0x1.cb00p-46,134 0x1.902fed0282c0ep-1, -0x1.cb00p-46,
135 0x1.9145b0b91ff96p-1, -0x1.5e00p-47,135 0x1.9145b0b91ff96p-1, -0x1.5e00p-47,
136 0x1.925c353aa2ff9p-1, 0x1.5400p-48,136 0x1.925c353aa2ff9p-1, 0x1.5400p-48,
137 0x1.93737b0cdc64ap-1, 0x1.7200p-46,137 0x1.93737b0cdc64ap-1, 0x1.7200p-46,
138 0x1.948b82b5f98aep-1, -0x1.9000p-47,138 0x1.948b82b5f98aep-1, -0x1.9000p-47,
139 0x1.95a44cbc852cbp-1, 0x1.5680p-45,139 0x1.95a44cbc852cbp-1, 0x1.5680p-45,
140 0x1.96bdd9a766f21p-1, -0x1.6d00p-44,140 0x1.96bdd9a766f21p-1, -0x1.6d00p-44,
141 0x1.97d829fde4e2ap-1, -0x1.1000p-47,141 0x1.97d829fde4e2ap-1, -0x1.1000p-47,
142 0x1.98f33e47a23a3p-1, 0x1.d000p-45,142 0x1.98f33e47a23a3p-1, 0x1.d000p-45,
143 0x1.9a0f170ca0604p-1, -0x1.8a40p-44,143 0x1.9a0f170ca0604p-1, -0x1.8a40p-44,
144 0x1.9b2bb4d53ff89p-1, 0x1.55c0p-44,144 0x1.9b2bb4d53ff89p-1, 0x1.55c0p-44,
145 0x1.9c49182a3f15bp-1, 0x1.6b80p-45,145 0x1.9c49182a3f15bp-1, 0x1.6b80p-45,
146 0x1.9d674194bb8c5p-1, -0x1.c000p-49,146 0x1.9d674194bb8c5p-1, -0x1.c000p-49,
147 0x1.9e86319e3238ep-1, 0x1.7d00p-46,147 0x1.9e86319e3238ep-1, 0x1.7d00p-46,
148 0x1.9fa5e8d07f302p-1, 0x1.6400p-46,148 0x1.9fa5e8d07f302p-1, 0x1.6400p-46,
149 0x1.a0c667b5de54dp-1, -0x1.5000p-48,149 0x1.a0c667b5de54dp-1, -0x1.5000p-48,
150 0x1.a1e7aed8eb8f6p-1, 0x1.9e00p-47,150 0x1.a1e7aed8eb8f6p-1, 0x1.9e00p-47,
151 0x1.a309bec4a2e27p-1, 0x1.ad80p-45,151 0x1.a309bec4a2e27p-1, 0x1.ad80p-45,
152 0x1.a42c980460a5dp-1, -0x1.af00p-46,152 0x1.a42c980460a5dp-1, -0x1.af00p-46,
153 0x1.a5503b23e259bp-1, 0x1.b600p-47,153 0x1.a5503b23e259bp-1, 0x1.b600p-47,
154 0x1.a674a8af46213p-1, 0x1.8880p-44,154 0x1.a674a8af46213p-1, 0x1.8880p-44,
155 0x1.a799e1330b3a7p-1, 0x1.1200p-46,155 0x1.a799e1330b3a7p-1, 0x1.1200p-46,
156 0x1.a8bfe53c12e8dp-1, 0x1.6c00p-47,156 0x1.a8bfe53c12e8dp-1, 0x1.6c00p-47,
157 0x1.a9e6b5579fcd2p-1, -0x1.9b80p-45,157 0x1.a9e6b5579fcd2p-1, -0x1.9b80p-45,
158 0x1.ab0e521356fb8p-1, 0x1.b700p-45,158 0x1.ab0e521356fb8p-1, 0x1.b700p-45,
159 0x1.ac36bbfd3f381p-1, 0x1.9000p-50,159 0x1.ac36bbfd3f381p-1, 0x1.9000p-50,
160 0x1.ad5ff3a3c2780p-1, 0x1.4000p-49,160 0x1.ad5ff3a3c2780p-1, 0x1.4000p-49,
161 0x1.ae89f995ad2a3p-1, -0x1.c900p-45,161 0x1.ae89f995ad2a3p-1, -0x1.c900p-45,
162 0x1.afb4ce622f367p-1, 0x1.6500p-46,162 0x1.afb4ce622f367p-1, 0x1.6500p-46,
163 0x1.b0e07298db790p-1, 0x1.fd40p-45,163 0x1.b0e07298db790p-1, 0x1.fd40p-45,
164 0x1.b20ce6c9a89a9p-1, 0x1.2700p-46,164 0x1.b20ce6c9a89a9p-1, 0x1.2700p-46,
165 0x1.b33a2b84f1a4bp-1, 0x1.d470p-43,165 0x1.b33a2b84f1a4bp-1, 0x1.d470p-43,
166 0x1.b468415b747e7p-1, -0x1.8380p-44,166 0x1.b468415b747e7p-1, -0x1.8380p-44,
167 0x1.b59728de5593ap-1, 0x1.8000p-54,167 0x1.b59728de5593ap-1, 0x1.8000p-54,
168 0x1.b6c6e29f1c56ap-1, 0x1.ad00p-47,168 0x1.b6c6e29f1c56ap-1, 0x1.ad00p-47,
169 0x1.b7f76f2fb5e50p-1, 0x1.e800p-50,169 0x1.b7f76f2fb5e50p-1, 0x1.e800p-50,
170 0x1.b928cf22749b2p-1, -0x1.4c00p-47,170 0x1.b928cf22749b2p-1, -0x1.4c00p-47,
171 0x1.ba5b030a10603p-1, -0x1.d700p-47,171 0x1.ba5b030a10603p-1, -0x1.d700p-47,
172 0x1.bb8e0b79a6f66p-1, 0x1.d900p-47,172 0x1.bb8e0b79a6f66p-1, 0x1.d900p-47,
173 0x1.bcc1e904bc1ffp-1, 0x1.2a00p-47,173 0x1.bcc1e904bc1ffp-1, 0x1.2a00p-47,
174 0x1.bdf69c3f3a16fp-1, -0x1.f780p-46,174 0x1.bdf69c3f3a16fp-1, -0x1.f780p-46,
175 0x1.bf2c25bd71db8p-1, -0x1.0a00p-46,175 0x1.bf2c25bd71db8p-1, -0x1.0a00p-46,
176 0x1.c06286141b2e9p-1, -0x1.1400p-46,176 0x1.c06286141b2e9p-1, -0x1.1400p-46,
177 0x1.c199bdd8552e0p-1, 0x1.be00p-47,177 0x1.c199bdd8552e0p-1, 0x1.be00p-47,
178 0x1.c2d1cd9fa64eep-1, -0x1.9400p-47,178 0x1.c2d1cd9fa64eep-1, -0x1.9400p-47,
179 0x1.c40ab5fffd02fp-1, -0x1.ed00p-47,179 0x1.c40ab5fffd02fp-1, -0x1.ed00p-47,
180 0x1.c544778fafd15p-1, 0x1.9660p-44,180 0x1.c544778fafd15p-1, 0x1.9660p-44,
181 0x1.c67f12e57d0cbp-1, -0x1.a100p-46,181 0x1.c67f12e57d0cbp-1, -0x1.a100p-46,
182 0x1.c7ba88988c1b6p-1, -0x1.8458p-42,182 0x1.c7ba88988c1b6p-1, -0x1.8458p-42,
183 0x1.c8f6d9406e733p-1, -0x1.a480p-46,183 0x1.c8f6d9406e733p-1, -0x1.a480p-46,
184 0x1.ca3405751c4dfp-1, 0x1.b000p-51,184 0x1.ca3405751c4dfp-1, 0x1.b000p-51,
185 0x1.cb720dcef9094p-1, 0x1.1400p-47,185 0x1.cb720dcef9094p-1, 0x1.1400p-47,
186 0x1.ccb0f2e6d1689p-1, 0x1.0200p-48,186 0x1.ccb0f2e6d1689p-1, 0x1.0200p-48,
187 0x1.cdf0b555dc412p-1, 0x1.3600p-48,187 0x1.cdf0b555dc412p-1, 0x1.3600p-48,
188 0x1.cf3155b5bab3bp-1, -0x1.6900p-47,188 0x1.cf3155b5bab3bp-1, -0x1.6900p-47,
189 0x1.d072d4a0789bcp-1, 0x1.9a00p-47,189 0x1.d072d4a0789bcp-1, 0x1.9a00p-47,
190 0x1.d1b532b08c8fap-1, -0x1.5e00p-46,190 0x1.d1b532b08c8fap-1, -0x1.5e00p-46,
191 0x1.d2f87080d8a85p-1, 0x1.d280p-46,191 0x1.d2f87080d8a85p-1, 0x1.d280p-46,
192 0x1.d43c8eacaa203p-1, 0x1.1a00p-47,192 0x1.d43c8eacaa203p-1, 0x1.1a00p-47,
193 0x1.d5818dcfba491p-1, 0x1.f000p-50,193 0x1.d5818dcfba491p-1, 0x1.f000p-50,
194 0x1.d6c76e862e6a1p-1, -0x1.3a00p-47,194 0x1.d6c76e862e6a1p-1, -0x1.3a00p-47,
195 0x1.d80e316c9834ep-1, -0x1.cd80p-47,195 0x1.d80e316c9834ep-1, -0x1.cd80p-47,
196 0x1.d955d71ff6090p-1, 0x1.4c00p-48,196 0x1.d955d71ff6090p-1, 0x1.4c00p-48,
197 0x1.da9e603db32aep-1, 0x1.f900p-48,197 0x1.da9e603db32aep-1, 0x1.f900p-48,
198 0x1.dbe7cd63a8325p-1, 0x1.9800p-49,198 0x1.dbe7cd63a8325p-1, 0x1.9800p-49,
199 0x1.dd321f301b445p-1, -0x1.5200p-48,199 0x1.dd321f301b445p-1, -0x1.5200p-48,
200 0x1.de7d5641c05bfp-1, -0x1.d700p-46,200 0x1.de7d5641c05bfp-1, -0x1.d700p-46,
201 0x1.dfc97337b9aecp-1, -0x1.6140p-46,201 0x1.dfc97337b9aecp-1, -0x1.6140p-46,
202 0x1.e11676b197d5ep-1, 0x1.b480p-47,202 0x1.e11676b197d5ep-1, 0x1.b480p-47,
203 0x1.e264614f5a3e7p-1, 0x1.0ce0p-43,203 0x1.e264614f5a3e7p-1, 0x1.0ce0p-43,
204 0x1.e3b333b16ee5cp-1, 0x1.c680p-47,204 0x1.e3b333b16ee5cp-1, 0x1.c680p-47,
205 0x1.e502ee78b3fb4p-1, -0x1.9300p-47,205 0x1.e502ee78b3fb4p-1, -0x1.9300p-47,
206 0x1.e653924676d68p-1, -0x1.5000p-49,206 0x1.e653924676d68p-1, -0x1.5000p-49,
207 0x1.e7a51fbc74c44p-1, -0x1.7f80p-47,207 0x1.e7a51fbc74c44p-1, -0x1.7f80p-47,
208 0x1.e8f7977cdb726p-1, -0x1.3700p-48,208 0x1.e8f7977cdb726p-1, -0x1.3700p-48,
209 0x1.ea4afa2a490e8p-1, 0x1.5d00p-49,209 0x1.ea4afa2a490e8p-1, 0x1.5d00p-49,
210 0x1.eb9f4867ccae4p-1, 0x1.61a0p-46,210 0x1.eb9f4867ccae4p-1, 0x1.61a0p-46,
211 0x1.ecf482d8e680dp-1, 0x1.5500p-48,211 0x1.ecf482d8e680dp-1, 0x1.5500p-48,
212 0x1.ee4aaa2188514p-1, 0x1.6400p-51,212 0x1.ee4aaa2188514p-1, 0x1.6400p-51,
213 0x1.efa1bee615a13p-1, -0x1.e800p-49,213 0x1.efa1bee615a13p-1, -0x1.e800p-49,
214 0x1.f0f9c1cb64106p-1, -0x1.a880p-48,214 0x1.f0f9c1cb64106p-1, -0x1.a880p-48,
215 0x1.f252b376bb963p-1, -0x1.c900p-45,215 0x1.f252b376bb963p-1, -0x1.c900p-45,
216 0x1.f3ac948dd7275p-1, 0x1.a000p-53,216 0x1.f3ac948dd7275p-1, 0x1.a000p-53,
217 0x1.f50765b6e4524p-1, -0x1.4f00p-48,217 0x1.f50765b6e4524p-1, -0x1.4f00p-48,
218 0x1.f6632798844fdp-1, 0x1.a800p-51,218 0x1.f6632798844fdp-1, 0x1.a800p-51,
219 0x1.f7bfdad9cbe38p-1, 0x1.abc0p-48,219 0x1.f7bfdad9cbe38p-1, 0x1.abc0p-48,
220 0x1.f91d802243c82p-1, -0x1.4600p-50,220 0x1.f91d802243c82p-1, -0x1.4600p-50,
221 0x1.fa7c1819e908ep-1, -0x1.b0c0p-47,221 0x1.fa7c1819e908ep-1, -0x1.b0c0p-47,
222 0x1.fbdba3692d511p-1, -0x1.0e00p-51,222 0x1.fbdba3692d511p-1, -0x1.0e00p-51,
223 0x1.fd3c22b8f7194p-1, -0x1.0de8p-46,223 0x1.fd3c22b8f7194p-1, -0x1.0de8p-46,
224 0x1.fe9d96b2a23eep-1, 0x1.e430p-49,224 0x1.fe9d96b2a23eep-1, 0x1.e430p-49,
225 0x1.0000000000000p+0, 0x0.0000p+0,225 0x1.0000000000000p+0, 0x0.0000p+0,
226 0x1.00b1afa5abcbep+0, -0x1.3400p-52,226 0x1.00b1afa5abcbep+0, -0x1.3400p-52,
227 0x1.0163da9fb3303p+0, -0x1.2170p-46,227 0x1.0163da9fb3303p+0, -0x1.2170p-46,
228 0x1.02168143b0282p+0, 0x1.a400p-52,228 0x1.02168143b0282p+0, 0x1.a400p-52,
229 0x1.02c9a3e77806cp+0, 0x1.f980p-49,229 0x1.02c9a3e77806cp+0, 0x1.f980p-49,
230 0x1.037d42e11bbcap+0, -0x1.7400p-51,230 0x1.037d42e11bbcap+0, -0x1.7400p-51,
231 0x1.04315e86e7f89p+0, 0x1.8300p-50,231 0x1.04315e86e7f89p+0, 0x1.8300p-50,
232 0x1.04e5f72f65467p+0, -0x1.a3f0p-46,232 0x1.04e5f72f65467p+0, -0x1.a3f0p-46,
233 0x1.059b0d315855ap+0, -0x1.2840p-47,233 0x1.059b0d315855ap+0, -0x1.2840p-47,
234 0x1.0650a0e3c1f95p+0, 0x1.1600p-48,234 0x1.0650a0e3c1f95p+0, 0x1.1600p-48,
235 0x1.0706b29ddf71ap+0, 0x1.5240p-46,235 0x1.0706b29ddf71ap+0, 0x1.5240p-46,
236 0x1.07bd42b72a82dp+0, -0x1.9a00p-49,236 0x1.07bd42b72a82dp+0, -0x1.9a00p-49,
237 0x1.0874518759bd0p+0, 0x1.6400p-49,237 0x1.0874518759bd0p+0, 0x1.6400p-49,
238 0x1.092bdf66607c8p+0, -0x1.0780p-47,238 0x1.092bdf66607c8p+0, -0x1.0780p-47,
239 0x1.09e3ecac6f383p+0, -0x1.8000p-54,239 0x1.09e3ecac6f383p+0, -0x1.8000p-54,
240 0x1.0a9c79b1f3930p+0, 0x1.fa00p-48,240 0x1.0a9c79b1f3930p+0, 0x1.fa00p-48,
241 0x1.0b5586cf988fcp+0, -0x1.ac80p-48,241 0x1.0b5586cf988fcp+0, -0x1.ac80p-48,
242 0x1.0c0f145e46c8ap+0, 0x1.9c00p-50,242 0x1.0c0f145e46c8ap+0, 0x1.9c00p-50,
243 0x1.0cc922b724816p+0, 0x1.5200p-47,243 0x1.0cc922b724816p+0, 0x1.5200p-47,
244 0x1.0d83b23395dd8p+0, -0x1.ad00p-48,244 0x1.0d83b23395dd8p+0, -0x1.ad00p-48,
245 0x1.0e3ec32d3d1f3p+0, 0x1.bac0p-46,245 0x1.0e3ec32d3d1f3p+0, 0x1.bac0p-46,
246 0x1.0efa55fdfa9a6p+0, -0x1.4e80p-47,246 0x1.0efa55fdfa9a6p+0, -0x1.4e80p-47,
247 0x1.0fb66affed2f0p+0, -0x1.d300p-47,247 0x1.0fb66affed2f0p+0, -0x1.d300p-47,
248 0x1.1073028d7234bp+0, 0x1.1500p-48,248 0x1.1073028d7234bp+0, 0x1.1500p-48,
249 0x1.11301d0125b5bp+0, 0x1.c000p-49,249 0x1.11301d0125b5bp+0, 0x1.c000p-49,
250 0x1.11edbab5e2af9p+0, 0x1.6bc0p-46,250 0x1.11edbab5e2af9p+0, 0x1.6bc0p-46,
251 0x1.12abdc06c31d5p+0, 0x1.8400p-49,251 0x1.12abdc06c31d5p+0, 0x1.8400p-49,
252 0x1.136a814f2047dp+0, -0x1.ed00p-47,252 0x1.136a814f2047dp+0, -0x1.ed00p-47,
253 0x1.1429aaea92de9p+0, 0x1.8e00p-49,253 0x1.1429aaea92de9p+0, 0x1.8e00p-49,
254 0x1.14e95934f3138p+0, 0x1.b400p-49,254 0x1.14e95934f3138p+0, 0x1.b400p-49,
255 0x1.15a98c8a58e71p+0, 0x1.5300p-47,255 0x1.15a98c8a58e71p+0, 0x1.5300p-47,
256 0x1.166a45471c3dfp+0, 0x1.3380p-47,256 0x1.166a45471c3dfp+0, 0x1.3380p-47,
257 0x1.172b83c7d5211p+0, 0x1.8d40p-45,257 0x1.172b83c7d5211p+0, 0x1.8d40p-45,
258 0x1.17ed48695bb9fp+0, -0x1.5d00p-47,258 0x1.17ed48695bb9fp+0, -0x1.5d00p-47,
259 0x1.18af9388c8d93p+0, -0x1.c880p-46,259 0x1.18af9388c8d93p+0, -0x1.c880p-46,
260 0x1.1972658375d66p+0, 0x1.1f00p-46,260 0x1.1972658375d66p+0, 0x1.1f00p-46,
261 0x1.1a35beb6fcba7p+0, 0x1.0480p-46,261 0x1.1a35beb6fcba7p+0, 0x1.0480p-46,
262 0x1.1af99f81387e3p+0, -0x1.7390p-43,262 0x1.1af99f81387e3p+0, -0x1.7390p-43,
263 0x1.1bbe084045d54p+0, 0x1.4e40p-45,263 0x1.1bbe084045d54p+0, 0x1.4e40p-45,
264 0x1.1c82f95281c43p+0, -0x1.a200p-47,264 0x1.1c82f95281c43p+0, -0x1.a200p-47,
265 0x1.1d4873168b9b2p+0, 0x1.3800p-49,265 0x1.1d4873168b9b2p+0, 0x1.3800p-49,
266 0x1.1e0e75eb44031p+0, 0x1.ac00p-49,266 0x1.1e0e75eb44031p+0, 0x1.ac00p-49,
267 0x1.1ed5022fcd938p+0, 0x1.1900p-47,267 0x1.1ed5022fcd938p+0, 0x1.1900p-47,
268 0x1.1f9c18438cdf7p+0, -0x1.b780p-46,268 0x1.1f9c18438cdf7p+0, -0x1.b780p-46,
269 0x1.2063b88628d8fp+0, 0x1.d940p-45,269 0x1.2063b88628d8fp+0, 0x1.d940p-45,
270 0x1.212be3578a81ep+0, 0x1.8000p-50,270 0x1.212be3578a81ep+0, 0x1.8000p-50,
271 0x1.21f49917ddd41p+0, 0x1.b340p-45,271 0x1.21f49917ddd41p+0, 0x1.b340p-45,
272 0x1.22bdda2791323p+0, 0x1.9f80p-46,272 0x1.22bdda2791323p+0, 0x1.9f80p-46,
273 0x1.2387a6e7561e7p+0, -0x1.9c80p-46,273 0x1.2387a6e7561e7p+0, -0x1.9c80p-46,
274 0x1.2451ffb821427p+0, 0x1.2300p-47,274 0x1.2451ffb821427p+0, 0x1.2300p-47,
275 0x1.251ce4fb2a602p+0, -0x1.3480p-46,275 0x1.251ce4fb2a602p+0, -0x1.3480p-46,
276 0x1.25e85711eceb0p+0, 0x1.2700p-46,276 0x1.25e85711eceb0p+0, 0x1.2700p-46,
277 0x1.26b4565e27d16p+0, 0x1.1d00p-46,277 0x1.26b4565e27d16p+0, 0x1.1d00p-46,
278 0x1.2780e341de00fp+0, 0x1.1ee0p-44,278 0x1.2780e341de00fp+0, 0x1.1ee0p-44,
279 0x1.284dfe1f5633ep+0, -0x1.4c00p-46,279 0x1.284dfe1f5633ep+0, -0x1.4c00p-46,
280 0x1.291ba7591bb30p+0, -0x1.3d80p-46,280 0x1.291ba7591bb30p+0, -0x1.3d80p-46,
281 0x1.29e9df51fdf09p+0, 0x1.8b00p-47,281 0x1.29e9df51fdf09p+0, 0x1.8b00p-47,
282 0x1.2ab8a66d10e9bp+0, -0x1.27c0p-45,282 0x1.2ab8a66d10e9bp+0, -0x1.27c0p-45,
283 0x1.2b87fd0dada3ap+0, 0x1.a340p-45,283 0x1.2b87fd0dada3ap+0, 0x1.a340p-45,
284 0x1.2c57e39771af9p+0, -0x1.0800p-46,284 0x1.2c57e39771af9p+0, -0x1.0800p-46,
285 0x1.2d285a6e402d9p+0, -0x1.ed00p-47,285 0x1.2d285a6e402d9p+0, -0x1.ed00p-47,
286 0x1.2df961f641579p+0, -0x1.4200p-48,286 0x1.2df961f641579p+0, -0x1.4200p-48,
...@@ -290,78 +290,78 @@ const exp2dt = []f64 {...@@ -290,78 +290,78 @@ const exp2dt = []f64 {
290 0x1.31432edeea50bp+0, -0x1.0df8p-40,290 0x1.31432edeea50bp+0, -0x1.0df8p-40,
291 0x1.32170fc4cd7b8p+0, -0x1.2480p-45,291 0x1.32170fc4cd7b8p+0, -0x1.2480p-45,
292 0x1.32eb83ba8e9a2p+0, -0x1.5980p-45,292 0x1.32eb83ba8e9a2p+0, -0x1.5980p-45,
293 0x1.33c08b2641766p+0, 0x1.ed00p-46,293 0x1.33c08b2641766p+0, 0x1.ed00p-46,
294 0x1.3496266e3fa27p+0, -0x1.c000p-50,294 0x1.3496266e3fa27p+0, -0x1.c000p-50,
295 0x1.356c55f929f0fp+0, -0x1.0d80p-44,295 0x1.356c55f929f0fp+0, -0x1.0d80p-44,
296 0x1.36431a2de88b9p+0, 0x1.2c80p-45,296 0x1.36431a2de88b9p+0, 0x1.2c80p-45,
297 0x1.371a7373aaa39p+0, 0x1.0600p-45,297 0x1.371a7373aaa39p+0, 0x1.0600p-45,
298 0x1.37f26231e74fep+0, -0x1.6600p-46,298 0x1.37f26231e74fep+0, -0x1.6600p-46,
299 0x1.38cae6d05d838p+0, -0x1.ae00p-47,299 0x1.38cae6d05d838p+0, -0x1.ae00p-47,
300 0x1.39a401b713ec3p+0, -0x1.4720p-43,300 0x1.39a401b713ec3p+0, -0x1.4720p-43,
301 0x1.3a7db34e5a020p+0, 0x1.8200p-47,301 0x1.3a7db34e5a020p+0, 0x1.8200p-47,
302 0x1.3b57fbfec6e95p+0, 0x1.e800p-44,302 0x1.3b57fbfec6e95p+0, 0x1.e800p-44,
303 0x1.3c32dc313a8f2p+0, 0x1.f800p-49,303 0x1.3c32dc313a8f2p+0, 0x1.f800p-49,
304 0x1.3d0e544ede122p+0, -0x1.7a00p-46,304 0x1.3d0e544ede122p+0, -0x1.7a00p-46,
305 0x1.3dea64c1234bbp+0, 0x1.6300p-45,305 0x1.3dea64c1234bbp+0, 0x1.6300p-45,
306 0x1.3ec70df1c4eccp+0, -0x1.8a60p-43,306 0x1.3ec70df1c4eccp+0, -0x1.8a60p-43,
307 0x1.3fa4504ac7e8cp+0, -0x1.cdc0p-44,307 0x1.3fa4504ac7e8cp+0, -0x1.cdc0p-44,
308 0x1.40822c367a0bbp+0, 0x1.5b80p-45,308 0x1.40822c367a0bbp+0, 0x1.5b80p-45,
309 0x1.4160a21f72e95p+0, 0x1.ec00p-46,309 0x1.4160a21f72e95p+0, 0x1.ec00p-46,
310 0x1.423fb27094646p+0, -0x1.3600p-46,310 0x1.423fb27094646p+0, -0x1.3600p-46,
311 0x1.431f5d950a920p+0, 0x1.3980p-45,311 0x1.431f5d950a920p+0, 0x1.3980p-45,
312 0x1.43ffa3f84b9ebp+0, 0x1.a000p-48,312 0x1.43ffa3f84b9ebp+0, 0x1.a000p-48,
313 0x1.44e0860618919p+0, -0x1.6c00p-48,313 0x1.44e0860618919p+0, -0x1.6c00p-48,
314 0x1.45c2042a7d201p+0, -0x1.bc00p-47,314 0x1.45c2042a7d201p+0, -0x1.bc00p-47,
315 0x1.46a41ed1d0016p+0, -0x1.2800p-46,315 0x1.46a41ed1d0016p+0, -0x1.2800p-46,
316 0x1.4786d668b3326p+0, 0x1.0e00p-44,316 0x1.4786d668b3326p+0, 0x1.0e00p-44,
317 0x1.486a2b5c13c00p+0, -0x1.d400p-45,317 0x1.486a2b5c13c00p+0, -0x1.d400p-45,
318 0x1.494e1e192af04p+0, 0x1.c200p-47,318 0x1.494e1e192af04p+0, 0x1.c200p-47,
319 0x1.4a32af0d7d372p+0, -0x1.e500p-46,319 0x1.4a32af0d7d372p+0, -0x1.e500p-46,
320 0x1.4b17dea6db801p+0, 0x1.7800p-47,320 0x1.4b17dea6db801p+0, 0x1.7800p-47,
321 0x1.4bfdad53629e1p+0, -0x1.3800p-46,321 0x1.4bfdad53629e1p+0, -0x1.3800p-46,
322 0x1.4ce41b817c132p+0, 0x1.0800p-47,322 0x1.4ce41b817c132p+0, 0x1.0800p-47,
323 0x1.4dcb299fddddbp+0, 0x1.c700p-45,323 0x1.4dcb299fddddbp+0, 0x1.c700p-45,
324 0x1.4eb2d81d8ab96p+0, -0x1.ce00p-46,324 0x1.4eb2d81d8ab96p+0, -0x1.ce00p-46,
325 0x1.4f9b2769d2d02p+0, 0x1.9200p-46,325 0x1.4f9b2769d2d02p+0, 0x1.9200p-46,
326 0x1.508417f4531c1p+0, -0x1.8c00p-47,326 0x1.508417f4531c1p+0, -0x1.8c00p-47,
327 0x1.516daa2cf662ap+0, -0x1.a000p-48,327 0x1.516daa2cf662ap+0, -0x1.a000p-48,
328 0x1.5257de83f51eap+0, 0x1.a080p-43,328 0x1.5257de83f51eap+0, 0x1.a080p-43,
329 0x1.5342b569d4edap+0, -0x1.6d80p-45,329 0x1.5342b569d4edap+0, -0x1.6d80p-45,
330 0x1.542e2f4f6ac1ap+0, -0x1.2440p-44,330 0x1.542e2f4f6ac1ap+0, -0x1.2440p-44,
331 0x1.551a4ca5d94dbp+0, 0x1.83c0p-43,331 0x1.551a4ca5d94dbp+0, 0x1.83c0p-43,
332 0x1.56070dde9116bp+0, 0x1.4b00p-45,332 0x1.56070dde9116bp+0, 0x1.4b00p-45,
333 0x1.56f4736b529dep+0, 0x1.15a0p-43,333 0x1.56f4736b529dep+0, 0x1.15a0p-43,
334 0x1.57e27dbe2c40ep+0, -0x1.9e00p-45,334 0x1.57e27dbe2c40ep+0, -0x1.9e00p-45,
335 0x1.58d12d497c76fp+0, -0x1.3080p-45,335 0x1.58d12d497c76fp+0, -0x1.3080p-45,
336 0x1.59c0827ff0b4cp+0, 0x1.dec0p-43,336 0x1.59c0827ff0b4cp+0, 0x1.dec0p-43,
337 0x1.5ab07dd485427p+0, -0x1.4000p-51,337 0x1.5ab07dd485427p+0, -0x1.4000p-51,
338 0x1.5ba11fba87af4p+0, 0x1.0080p-44,338 0x1.5ba11fba87af4p+0, 0x1.0080p-44,
339 0x1.5c9268a59460bp+0, -0x1.6c80p-45,339 0x1.5c9268a59460bp+0, -0x1.6c80p-45,
340 0x1.5d84590998e3fp+0, 0x1.69a0p-43,340 0x1.5d84590998e3fp+0, 0x1.69a0p-43,
341 0x1.5e76f15ad20e1p+0, -0x1.b400p-46,341 0x1.5e76f15ad20e1p+0, -0x1.b400p-46,
342 0x1.5f6a320dcebcap+0, 0x1.7700p-46,342 0x1.5f6a320dcebcap+0, 0x1.7700p-46,
343 0x1.605e1b976dcb8p+0, 0x1.6f80p-45,343 0x1.605e1b976dcb8p+0, 0x1.6f80p-45,
344 0x1.6152ae6cdf715p+0, 0x1.1000p-47,344 0x1.6152ae6cdf715p+0, 0x1.1000p-47,
345 0x1.6247eb03a5531p+0, -0x1.5d00p-46,345 0x1.6247eb03a5531p+0, -0x1.5d00p-46,
346 0x1.633dd1d1929b5p+0, -0x1.2d00p-46,346 0x1.633dd1d1929b5p+0, -0x1.2d00p-46,
347 0x1.6434634ccc313p+0, -0x1.a800p-49,347 0x1.6434634ccc313p+0, -0x1.a800p-49,
348 0x1.652b9febc8efap+0, -0x1.8600p-45,348 0x1.652b9febc8efap+0, -0x1.8600p-45,
349 0x1.6623882553397p+0, 0x1.1fe0p-40,349 0x1.6623882553397p+0, 0x1.1fe0p-40,
350 0x1.671c1c708328ep+0, -0x1.7200p-44,350 0x1.671c1c708328ep+0, -0x1.7200p-44,
351 0x1.68155d44ca97ep+0, 0x1.6800p-49,351 0x1.68155d44ca97ep+0, 0x1.6800p-49,
352 0x1.690f4b19e9471p+0, -0x1.9780p-45,352 0x1.690f4b19e9471p+0, -0x1.9780p-45,
353};353};
354354
355fn exp2_64(x: f64) f64 {355fn exp2_64(x: f64) f64 {
356 @setFloatMode(this, @import("builtin").FloatMode.Strict);356 @setFloatMode(this, @import("builtin").FloatMode.Strict);
357357
358 const tblsiz = u32(exp2dt.len / 2);358 const tblsiz = u32(exp2dt.len / 2);
359 const redux: f64 = 0x1.8p52 / f64(tblsiz);359 const redux: f64 = 0x1.8p52 / f64(tblsiz);
360 const P1: f64 = 0x1.62e42fefa39efp-1;360 const P1: f64 = 0x1.62e42fefa39efp-1;
361 const P2: f64 = 0x1.ebfbdff82c575p-3;361 const P2: f64 = 0x1.ebfbdff82c575p-3;
362 const P3: f64 = 0x1.c6b08d704a0a6p-5;362 const P3: f64 = 0x1.c6b08d704a0a6p-5;
363 const P4: f64 = 0x1.3b2ab88f70400p-7;363 const P4: f64 = 0x1.3b2ab88f70400p-7;
364 const P5: f64 = 0x1.5d88003875c74p-10;364 const P5: f64 = 0x1.5d88003875c74p-10;
365365
366 const ux = @bitCast(u64, x);366 const ux = @bitCast(u64, x);
367 const ix = u32(ux >> 32) & 0x7FFFFFFF;367 const ix = u32(ux >> 32) & 0x7FFFFFFF;
std/math/expm1.zig+11-13
...@@ -21,11 +21,11 @@ pub fn expm1(x: var) @typeOf(x) {...@@ -21,11 +21,11 @@ pub fn expm1(x: var) @typeOf(x) {
21fn expm1_32(x_: f32) f32 {21fn expm1_32(x_: f32) f32 {
22 @setFloatMode(this, builtin.FloatMode.Strict);22 @setFloatMode(this, builtin.FloatMode.Strict);
23 const o_threshold: f32 = 8.8721679688e+01;23 const o_threshold: f32 = 8.8721679688e+01;
24 const ln2_hi: f32 = 6.9313812256e-01;24 const ln2_hi: f32 = 6.9313812256e-01;
25 const ln2_lo: f32 = 9.0580006145e-06;25 const ln2_lo: f32 = 9.0580006145e-06;
26 const invln2: f32 = 1.4426950216e+00;26 const invln2: f32 = 1.4426950216e+00;
27 const Q1: f32 = -3.3333212137e-2;27 const Q1: f32 = -3.3333212137e-2;
28 const Q2: f32 = 1.5807170421e-3;28 const Q2: f32 = 1.5807170421e-3;
2929
30 var x = x_;30 var x = x_;
31 const ux = @bitCast(u32, x);31 const ux = @bitCast(u32, x);
...@@ -93,8 +93,7 @@ fn expm1_32(x_: f32) f32 {...@@ -93,8 +93,7 @@ fn expm1_32(x_: f32) f32 {
93 math.forceEval(x * x);93 math.forceEval(x * x);
94 }94 }
95 return x;95 return x;
96 }96 } else {
97 else {
98 k = 0;97 k = 0;
99 }98 }
10099
...@@ -148,13 +147,13 @@ fn expm1_32(x_: f32) f32 {...@@ -148,13 +147,13 @@ fn expm1_32(x_: f32) f32 {
148fn expm1_64(x_: f64) f64 {147fn expm1_64(x_: f64) f64 {
149 @setFloatMode(this, builtin.FloatMode.Strict);148 @setFloatMode(this, builtin.FloatMode.Strict);
150 const o_threshold: f64 = 7.09782712893383973096e+02;149 const o_threshold: f64 = 7.09782712893383973096e+02;
151 const ln2_hi: f64 = 6.93147180369123816490e-01;150 const ln2_hi: f64 = 6.93147180369123816490e-01;
152 const ln2_lo: f64 = 1.90821492927058770002e-10;151 const ln2_lo: f64 = 1.90821492927058770002e-10;
153 const invln2: f64 = 1.44269504088896338700e+00;152 const invln2: f64 = 1.44269504088896338700e+00;
154 const Q1: f64 = -3.33333333333331316428e-02;153 const Q1: f64 = -3.33333333333331316428e-02;
155 const Q2: f64 = 1.58730158725481460165e-03;154 const Q2: f64 = 1.58730158725481460165e-03;
156 const Q3: f64 = -7.93650757867487942473e-05;155 const Q3: f64 = -7.93650757867487942473e-05;
157 const Q4: f64 = 4.00821782732936239552e-06;156 const Q4: f64 = 4.00821782732936239552e-06;
158 const Q5: f64 = -2.01099218183624371326e-07;157 const Q5: f64 = -2.01099218183624371326e-07;
159158
160 var x = x_;159 var x = x_;
...@@ -223,8 +222,7 @@ fn expm1_64(x_: f64) f64 {...@@ -223,8 +222,7 @@ fn expm1_64(x_: f64) f64 {
223 math.forceEval(f32(x));222 math.forceEval(f32(x));
224 }223 }
225 return x;224 return x;
226 }225 } else {
227 else {
228 k = 0;226 k = 0;
229 }227 }
230228
std/math/hypot.zig+1-1
...@@ -52,7 +52,7 @@ fn hypot32(x: f32, y: f32) f32 {...@@ -52,7 +52,7 @@ fn hypot32(x: f32, y: f32) f32 {
52 return z * math.sqrt(f32(f64(x) * x + f64(y) * y));52 return z * math.sqrt(f32(f64(x) * x + f64(y) * y));
53}53}
5454
55fn sq(hi: &f64, lo: &f64, x: f64) void {55fn sq(hi: *f64, lo: *f64, x: f64) void {
56 const split: f64 = 0x1.0p27 + 1.0;56 const split: f64 = 0x1.0p27 + 1.0;
57 const xc = x * split;57 const xc = x * split;
58 const xh = x - xc + xc;58 const xh = x - xc + xc;
std/math/index.zig+3-3
...@@ -46,12 +46,12 @@ pub fn forceEval(value: var) void {...@@ -46,12 +46,12 @@ pub fn forceEval(value: var) void {
46 switch (T) {46 switch (T) {
47 f32 => {47 f32 => {
48 var x: f32 = undefined;48 var x: f32 = undefined;
49 const p = @ptrCast(&volatile f32, &x);49 const p = @ptrCast(*volatile f32, &x);
50 p.* = x;50 p.* = x;
51 },51 },
52 f64 => {52 f64 => {
53 var x: f64 = undefined;53 var x: f64 = undefined;
54 const p = @ptrCast(&volatile f64, &x);54 const p = @ptrCast(*volatile f64, &x);
55 p.* = x;55 p.* = x;
56 },56 },
57 else => {57 else => {
...@@ -501,7 +501,7 @@ test "math.negateCast" {...@@ -501,7 +501,7 @@ test "math.negateCast" {
501 if (negateCast(u32(@maxValue(i32) + 10))) |_| unreachable else |err| assert(err == error.Overflow);501 if (negateCast(u32(@maxValue(i32) + 10))) |_| unreachable else |err| assert(err == error.Overflow);
502}502}
503503
504/// Cast an integer to a different integer type. If the value doesn't fit, 504/// Cast an integer to a different integer type. If the value doesn't fit,
505/// return an error.505/// return an error.
506pub fn cast(comptime T: type, x: var) (error{Overflow}!T) {506pub fn cast(comptime T: type, x: var) (error{Overflow}!T) {
507 comptime assert(@typeId(T) == builtin.TypeId.Int); // must pass an integer507 comptime assert(@typeId(T) == builtin.TypeId.Int); // must pass an integer
std/math/log1p.zig+1-2
...@@ -143,8 +143,7 @@ fn log1p_64(x: f64) f64 {...@@ -143,8 +143,7 @@ fn log1p_64(x: f64) f64 {
143 c = 0;143 c = 0;
144 f = x;144 f = x;
145 }145 }
146 }146 } else if (hx >= 0x7FF00000) {
147 else if (hx >= 0x7FF00000) {
148 return x;147 return x;
149 }148 }
150149
std/math/pow.zig-1
...@@ -28,7 +28,6 @@ const assert = std.debug.assert;...@@ -28,7 +28,6 @@ const assert = std.debug.assert;
2828
29// This implementation is taken from the go stlib, musl is a bit more complex.29// This implementation is taken from the go stlib, musl is a bit more complex.
30pub fn pow(comptime T: type, x: T, y: T) T {30pub fn pow(comptime T: type, x: T, y: T) T {
31
32 @setFloatMode(this, @import("builtin").FloatMode.Strict);31 @setFloatMode(this, @import("builtin").FloatMode.Strict);
3332
34 if (T != f32 and T != f64) {33 if (T != f32 and T != f64) {
std/mem.zig+27-27
...@@ -13,7 +13,7 @@ pub const Allocator = struct {...@@ -13,7 +13,7 @@ pub const Allocator = struct {
13 /// The returned newly allocated memory is undefined.13 /// The returned newly allocated memory is undefined.
14 /// `alignment` is guaranteed to be >= 114 /// `alignment` is guaranteed to be >= 1
15 /// `alignment` is guaranteed to be a power of 215 /// `alignment` is guaranteed to be a power of 2
16 allocFn: fn(self: &Allocator, byte_count: usize, alignment: u29) Error![]u8,16 allocFn: fn (self: *Allocator, byte_count: usize, alignment: u29) Error![]u8,
1717
18 /// If `new_byte_count > old_mem.len`:18 /// If `new_byte_count > old_mem.len`:
19 /// * `old_mem.len` is the same as what was returned from allocFn or reallocFn.19 /// * `old_mem.len` is the same as what was returned from allocFn or reallocFn.
...@@ -26,22 +26,22 @@ pub const Allocator = struct {...@@ -26,22 +26,22 @@ pub const Allocator = struct {
26 /// The returned newly allocated memory is undefined.26 /// The returned newly allocated memory is undefined.
27 /// `alignment` is guaranteed to be >= 127 /// `alignment` is guaranteed to be >= 1
28 /// `alignment` is guaranteed to be a power of 228 /// `alignment` is guaranteed to be a power of 2
29 reallocFn: fn(self: &Allocator, old_mem: []u8, new_byte_count: usize, alignment: u29) Error![]u8,29 reallocFn: fn (self: *Allocator, old_mem: []u8, new_byte_count: usize, alignment: u29) Error![]u8,
3030
31 /// Guaranteed: `old_mem.len` is the same as what was returned from `allocFn` or `reallocFn`31 /// Guaranteed: `old_mem.len` is the same as what was returned from `allocFn` or `reallocFn`
32 freeFn: fn(self: &Allocator, old_mem: []u8) void,32 freeFn: fn (self: *Allocator, old_mem: []u8) void,
3333
34 fn create(self: &Allocator, comptime T: type) !&T {34 fn create(self: *Allocator, comptime T: type) !*T {
35 if (@sizeOf(T) == 0) return &{};35 if (@sizeOf(T) == 0) return *{};
36 const slice = try self.alloc(T, 1);36 const slice = try self.alloc(T, 1);
37 return &slice[0];37 return &slice[0];
38 }38 }
3939
40 // TODO once #733 is solved, this will replace create40 // TODO once #733 is solved, this will replace create
41 fn construct(self: &Allocator, init: var) t: {41 fn construct(self: *Allocator, init: var) t: {
42 // TODO this is a workaround for type getting parsed as Error!&const T42 // TODO this is a workaround for type getting parsed as Error!&const T
43 const T = @typeOf(init).Child;43 const T = @typeOf(init).Child;
44 break :t Error!&T;44 break :t Error!*T;
45 } {45 } {
46 const T = @typeOf(init).Child;46 const T = @typeOf(init).Child;
47 if (@sizeOf(T) == 0) return &{};47 if (@sizeOf(T) == 0) return &{};
...@@ -51,17 +51,17 @@ pub const Allocator = struct {...@@ -51,17 +51,17 @@ pub const Allocator = struct {
51 return ptr;51 return ptr;
52 }52 }
5353
54 fn destroy(self: &Allocator, ptr: var) void {54 fn destroy(self: *Allocator, ptr: var) void {
55 self.free(ptr[0..1]);55 self.free(ptr[0..1]);
56 }56 }
5757
58 fn alloc(self: &Allocator, comptime T: type, n: usize) ![]T {58 fn alloc(self: *Allocator, comptime T: type, n: usize) ![]T {
59 return self.alignedAlloc(T, @alignOf(T), n);59 return self.alignedAlloc(T, @alignOf(T), n);
60 }60 }
6161
62 fn alignedAlloc(self: &Allocator, comptime T: type, comptime alignment: u29, n: usize) ![]align(alignment) T {62 fn alignedAlloc(self: *Allocator, comptime T: type, comptime alignment: u29, n: usize) ![]align(alignment) T {
63 if (n == 0) {63 if (n == 0) {
64 return (&align(alignment) T)(undefined)[0..0];64 return (*align(alignment) T)(undefined)[0..0];
65 }65 }
66 const byte_count = math.mul(usize, @sizeOf(T), n) catch return Error.OutOfMemory;66 const byte_count = math.mul(usize, @sizeOf(T), n) catch return Error.OutOfMemory;
67 const byte_slice = try self.allocFn(self, byte_count, alignment);67 const byte_slice = try self.allocFn(self, byte_count, alignment);
...@@ -73,17 +73,17 @@ pub const Allocator = struct {...@@ -73,17 +73,17 @@ pub const Allocator = struct {
73 return ([]align(alignment) T)(@alignCast(alignment, byte_slice));73 return ([]align(alignment) T)(@alignCast(alignment, byte_slice));
74 }74 }
7575
76 fn realloc(self: &Allocator, comptime T: type, old_mem: []T, n: usize) ![]T {76 fn realloc(self: *Allocator, comptime T: type, old_mem: []T, n: usize) ![]T {
77 return self.alignedRealloc(T, @alignOf(T), @alignCast(@alignOf(T), old_mem), n);77 return self.alignedRealloc(T, @alignOf(T), @alignCast(@alignOf(T), old_mem), n);
78 }78 }
7979
80 fn alignedRealloc(self: &Allocator, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) ![]align(alignment) T {80 fn alignedRealloc(self: *Allocator, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) ![]align(alignment) T {
81 if (old_mem.len == 0) {81 if (old_mem.len == 0) {
82 return self.alloc(T, n);82 return self.alloc(T, n);
83 }83 }
84 if (n == 0) {84 if (n == 0) {
85 self.free(old_mem);85 self.free(old_mem);
86 return (&align(alignment) T)(undefined)[0..0];86 return (*align(alignment) T)(undefined)[0..0];
87 }87 }
8888
89 const old_byte_slice = ([]u8)(old_mem);89 const old_byte_slice = ([]u8)(old_mem);
...@@ -102,11 +102,11 @@ pub const Allocator = struct {...@@ -102,11 +102,11 @@ pub const Allocator = struct {
102 /// Reallocate, but `n` must be less than or equal to `old_mem.len`.102 /// Reallocate, but `n` must be less than or equal to `old_mem.len`.
103 /// Unlike `realloc`, this function cannot fail.103 /// Unlike `realloc`, this function cannot fail.
104 /// Shrinking to 0 is the same as calling `free`.104 /// Shrinking to 0 is the same as calling `free`.
105 fn shrink(self: &Allocator, comptime T: type, old_mem: []T, n: usize) []T {105 fn shrink(self: *Allocator, comptime T: type, old_mem: []T, n: usize) []T {
106 return self.alignedShrink(T, @alignOf(T), @alignCast(@alignOf(T), old_mem), n);106 return self.alignedShrink(T, @alignOf(T), @alignCast(@alignOf(T), old_mem), n);
107 }107 }
108108
109 fn alignedShrink(self: &Allocator, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) []align(alignment) T {109 fn alignedShrink(self: *Allocator, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) []align(alignment) T {
110 if (n == 0) {110 if (n == 0) {
111 self.free(old_mem);111 self.free(old_mem);
112 return old_mem[0..0];112 return old_mem[0..0];
...@@ -123,10 +123,10 @@ pub const Allocator = struct {...@@ -123,10 +123,10 @@ pub const Allocator = struct {
123 return ([]align(alignment) T)(@alignCast(alignment, byte_slice));123 return ([]align(alignment) T)(@alignCast(alignment, byte_slice));
124 }124 }
125125
126 fn free(self: &Allocator, memory: var) void {126 fn free(self: *Allocator, memory: var) void {
127 const bytes = ([]const u8)(memory);127 const bytes = ([]const u8)(memory);
128 if (bytes.len == 0) return;128 if (bytes.len == 0) return;
129 const non_const_ptr = @intToPtr(&u8, @ptrToInt(bytes.ptr));129 const non_const_ptr = @intToPtr(*u8, @ptrToInt(bytes.ptr));
130 self.freeFn(self, non_const_ptr[0..bytes.len]);130 self.freeFn(self, non_const_ptr[0..bytes.len]);
131 }131 }
132};132};
...@@ -186,7 +186,7 @@ pub fn allEqual(comptime T: type, slice: []const T, scalar: T) bool {...@@ -186,7 +186,7 @@ pub fn allEqual(comptime T: type, slice: []const T, scalar: T) bool {
186}186}
187187
188/// Copies ::m to newly allocated memory. Caller is responsible to free it.188/// Copies ::m to newly allocated memory. Caller is responsible to free it.
189pub fn dupe(allocator: &Allocator, comptime T: type, m: []const T) ![]T {189pub fn dupe(allocator: *Allocator, comptime T: type, m: []const T) ![]T {
190 const new_buf = try allocator.alloc(T, m.len);190 const new_buf = try allocator.alloc(T, m.len);
191 copy(T, new_buf, m);191 copy(T, new_buf, m);
192 return new_buf;192 return new_buf;
...@@ -282,7 +282,7 @@ pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?us...@@ -282,7 +282,7 @@ pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?us
282282
283 var i: usize = haystack.len - needle.len;283 var i: usize = haystack.len - needle.len;
284 while (true) : (i -= 1) {284 while (true) : (i -= 1) {
285 if (mem.eql(T, haystack[i..i + needle.len], needle)) return i;285 if (mem.eql(T, haystack[i .. i + needle.len], needle)) return i;
286 if (i == 0) return null;286 if (i == 0) return null;
287 }287 }
288}288}
...@@ -294,7 +294,7 @@ pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, nee...@@ -294,7 +294,7 @@ pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, nee
294 var i: usize = start_index;294 var i: usize = start_index;
295 const end = haystack.len - needle.len;295 const end = haystack.len - needle.len;
296 while (i <= end) : (i += 1) {296 while (i <= end) : (i += 1) {
297 if (eql(T, haystack[i..i + needle.len], needle)) return i;297 if (eql(T, haystack[i .. i + needle.len], needle)) return i;
298 }298 }
299 return null;299 return null;
300}300}
...@@ -444,7 +444,7 @@ test "mem.startsWith" {...@@ -444,7 +444,7 @@ test "mem.startsWith" {
444}444}
445445
446pub fn endsWith(comptime T: type, haystack: []const T, needle: []const T) bool {446pub fn endsWith(comptime T: type, haystack: []const T, needle: []const T) bool {
447 return if (needle.len > haystack.len) false else eql(T, haystack[haystack.len - needle.len..], needle);447 return if (needle.len > haystack.len) false else eql(T, haystack[haystack.len - needle.len ..], needle);
448}448}
449449
450test "mem.endsWith" {450test "mem.endsWith" {
...@@ -457,7 +457,7 @@ pub const SplitIterator = struct {...@@ -457,7 +457,7 @@ pub const SplitIterator = struct {
457 split_bytes: []const u8,457 split_bytes: []const u8,
458 index: usize,458 index: usize,
459459
460 pub fn next(self: &SplitIterator) ?[]const u8 {460 pub fn next(self: *SplitIterator) ?[]const u8 {
461 // move to beginning of token461 // move to beginning of token
462 while (self.index < self.buffer.len and self.isSplitByte(self.buffer[self.index])) : (self.index += 1) {}462 while (self.index < self.buffer.len and self.isSplitByte(self.buffer[self.index])) : (self.index += 1) {}
463 const start = self.index;463 const start = self.index;
...@@ -473,14 +473,14 @@ pub const SplitIterator = struct {...@@ -473,14 +473,14 @@ pub const SplitIterator = struct {
473 }473 }
474474
475 /// Returns a slice of the remaining bytes. Does not affect iterator state.475 /// Returns a slice of the remaining bytes. Does not affect iterator state.
476 pub fn rest(self: &const SplitIterator) []const u8 {476 pub fn rest(self: *const SplitIterator) []const u8 {
477 // move to beginning of token477 // move to beginning of token
478 var index: usize = self.index;478 var index: usize = self.index;
479 while (index < self.buffer.len and self.isSplitByte(self.buffer[index])) : (index += 1) {}479 while (index < self.buffer.len and self.isSplitByte(self.buffer[index])) : (index += 1) {}
480 return self.buffer[index..];480 return self.buffer[index..];
481 }481 }
482482
483 fn isSplitByte(self: &const SplitIterator, byte: u8) bool {483 fn isSplitByte(self: *const SplitIterator, byte: u8) bool {
484 for (self.split_bytes) |split_byte| {484 for (self.split_bytes) |split_byte| {
485 if (byte == split_byte) {485 if (byte == split_byte) {
486 return true;486 return true;
...@@ -492,7 +492,7 @@ pub const SplitIterator = struct {...@@ -492,7 +492,7 @@ pub const SplitIterator = struct {
492492
493/// Naively combines a series of strings with a separator.493/// Naively combines a series of strings with a separator.
494/// Allocates memory for the result, which must be freed by the caller.494/// Allocates memory for the result, which must be freed by the caller.
495pub fn join(allocator: &Allocator, sep: u8, strings: ...) ![]u8 {495pub fn join(allocator: *Allocator, sep: u8, strings: ...) ![]u8 {
496 comptime assert(strings.len >= 1);496 comptime assert(strings.len >= 1);
497 var total_strings_len: usize = strings.len; // 1 sep per string497 var total_strings_len: usize = strings.len; // 1 sep per string
498 {498 {
...@@ -649,7 +649,7 @@ test "mem.max" {...@@ -649,7 +649,7 @@ test "mem.max" {
649 assert(max(u8, "abcdefg") == 'g');649 assert(max(u8, "abcdefg") == 'g');
650}650}
651651
652pub fn swap(comptime T: type, a: &T, b: &T) void {652pub fn swap(comptime T: type, a: *T, b: *T) void {
653 const tmp = a.*;653 const tmp = a.*;
654 a.* = b.*;654 a.* = b.*;
655 b.* = tmp;655 b.* = tmp;
std/net.zig+23-17
...@@ -19,36 +19,42 @@ pub const Address = struct {...@@ -19,36 +19,42 @@ pub const Address = struct {
19 os_addr: OsAddress,19 os_addr: OsAddress,
2020
21 pub fn initIp4(ip4: u32, port: u16) Address {21 pub fn initIp4(ip4: u32, port: u16) Address {
22 return Address{ .os_addr = posix.sockaddr{ .in = posix.sockaddr_in{22 return Address{
23 .family = posix.AF_INET,23 .os_addr = posix.sockaddr{
24 .port = std.mem.endianSwapIfLe(u16, port),24 .in = posix.sockaddr_in{
25 .addr = ip4,25 .family = posix.AF_INET,
26 .zero = []u8{0} ** 8,26 .port = std.mem.endianSwapIfLe(u16, port),
27 } } };27 .addr = ip4,
28 .zero = []u8{0} ** 8,
29 },
30 },
31 };
28 }32 }
2933
30 pub fn initIp6(ip6: &const Ip6Addr, port: u16) Address {34 pub fn initIp6(ip6: *const Ip6Addr, port: u16) Address {
31 return Address{35 return Address{
32 .family = posix.AF_INET6,36 .family = posix.AF_INET6,
33 .os_addr = posix.sockaddr{ .in6 = posix.sockaddr_in6{37 .os_addr = posix.sockaddr{
34 .family = posix.AF_INET6,38 .in6 = posix.sockaddr_in6{
35 .port = std.mem.endianSwapIfLe(u16, port),39 .family = posix.AF_INET6,
36 .flowinfo = 0,40 .port = std.mem.endianSwapIfLe(u16, port),
37 .addr = ip6.addr,41 .flowinfo = 0,
38 .scope_id = ip6.scope_id,42 .addr = ip6.addr,
39 } },43 .scope_id = ip6.scope_id,
44 },
45 },
40 };46 };
41 }47 }
4248
43 pub fn initPosix(addr: &const posix.sockaddr) Address {49 pub fn initPosix(addr: *const posix.sockaddr) Address {
44 return Address{ .os_addr = addr.* };50 return Address{ .os_addr = addr.* };
45 }51 }
4652
47 pub fn format(self: &const Address, out_stream: var) !void {53 pub fn format(self: *const Address, out_stream: var) !void {
48 switch (self.os_addr.in.family) {54 switch (self.os_addr.in.family) {
49 posix.AF_INET => {55 posix.AF_INET => {
50 const native_endian_port = std.mem.endianSwapIfLe(u16, self.os_addr.in.port);56 const native_endian_port = std.mem.endianSwapIfLe(u16, self.os_addr.in.port);
51 const bytes = ([]const u8)((&self.os_addr.in.addr)[0..1]);57 const bytes = ([]const u8)((*self.os_addr.in.addr)[0..1]);
52 try out_stream.print("{}.{}.{}.{}:{}", bytes[0], bytes[1], bytes[2], bytes[3], native_endian_port);58 try out_stream.print("{}.{}.{}.{}:{}", bytes[0], bytes[1], bytes[2], bytes[3], native_endian_port);
53 },59 },
54 posix.AF_INET6 => {60 posix.AF_INET6 => {
std/os/child_process.zig+33-38
...@@ -20,7 +20,7 @@ pub const ChildProcess = struct {...@@ -20,7 +20,7 @@ pub const ChildProcess = struct {
20 pub handle: if (is_windows) windows.HANDLE else void,20 pub handle: if (is_windows) windows.HANDLE else void,
21 pub thread_handle: if (is_windows) windows.HANDLE else void,21 pub thread_handle: if (is_windows) windows.HANDLE else void,
2222
23 pub allocator: &mem.Allocator,23 pub allocator: *mem.Allocator,
2424
25 pub stdin: ?os.File,25 pub stdin: ?os.File,
26 pub stdout: ?os.File,26 pub stdout: ?os.File,
...@@ -31,7 +31,7 @@ pub const ChildProcess = struct {...@@ -31,7 +31,7 @@ pub const ChildProcess = struct {
31 pub argv: []const []const u8,31 pub argv: []const []const u8,
3232
33 /// Leave as null to use the current env map using the supplied allocator.33 /// Leave as null to use the current env map using the supplied allocator.
34 pub env_map: ?&const BufMap,34 pub env_map: ?*const BufMap,
3535
36 pub stdin_behavior: StdIo,36 pub stdin_behavior: StdIo,
37 pub stdout_behavior: StdIo,37 pub stdout_behavior: StdIo,
...@@ -47,7 +47,7 @@ pub const ChildProcess = struct {...@@ -47,7 +47,7 @@ pub const ChildProcess = struct {
47 pub cwd: ?[]const u8,47 pub cwd: ?[]const u8,
4848
49 err_pipe: if (is_windows) void else [2]i32,49 err_pipe: if (is_windows) void else [2]i32,
50 llnode: if (is_windows) void else LinkedList(&ChildProcess).Node,50 llnode: if (is_windows) void else LinkedList(*ChildProcess).Node,
5151
52 pub const SpawnError = error{52 pub const SpawnError = error{
53 ProcessFdQuotaExceeded,53 ProcessFdQuotaExceeded,
...@@ -84,7 +84,7 @@ pub const ChildProcess = struct {...@@ -84,7 +84,7 @@ pub const ChildProcess = struct {
8484
85 /// First argument in argv is the executable.85 /// First argument in argv is the executable.
86 /// On success must call deinit.86 /// On success must call deinit.
87 pub fn init(argv: []const []const u8, allocator: &mem.Allocator) !&ChildProcess {87 pub fn init(argv: []const []const u8, allocator: *mem.Allocator) !*ChildProcess {
88 const child = try allocator.create(ChildProcess);88 const child = try allocator.create(ChildProcess);
89 errdefer allocator.destroy(child);89 errdefer allocator.destroy(child);
9090
...@@ -114,14 +114,14 @@ pub const ChildProcess = struct {...@@ -114,14 +114,14 @@ pub const ChildProcess = struct {
114 return child;114 return child;
115 }115 }
116116
117 pub fn setUserName(self: &ChildProcess, name: []const u8) !void {117 pub fn setUserName(self: *ChildProcess, name: []const u8) !void {
118 const user_info = try os.getUserInfo(name);118 const user_info = try os.getUserInfo(name);
119 self.uid = user_info.uid;119 self.uid = user_info.uid;
120 self.gid = user_info.gid;120 self.gid = user_info.gid;
121 }121 }
122122
123 /// On success must call `kill` or `wait`.123 /// On success must call `kill` or `wait`.
124 pub fn spawn(self: &ChildProcess) !void {124 pub fn spawn(self: *ChildProcess) !void {
125 if (is_windows) {125 if (is_windows) {
126 return self.spawnWindows();126 return self.spawnWindows();
127 } else {127 } else {
...@@ -129,13 +129,13 @@ pub const ChildProcess = struct {...@@ -129,13 +129,13 @@ pub const ChildProcess = struct {
129 }129 }
130 }130 }
131131
132 pub fn spawnAndWait(self: &ChildProcess) !Term {132 pub fn spawnAndWait(self: *ChildProcess) !Term {
133 try self.spawn();133 try self.spawn();
134 return self.wait();134 return self.wait();
135 }135 }
136136
137 /// Forcibly terminates child process and then cleans up all resources.137 /// Forcibly terminates child process and then cleans up all resources.
138 pub fn kill(self: &ChildProcess) !Term {138 pub fn kill(self: *ChildProcess) !Term {
139 if (is_windows) {139 if (is_windows) {
140 return self.killWindows(1);140 return self.killWindows(1);
141 } else {141 } else {
...@@ -143,7 +143,7 @@ pub const ChildProcess = struct {...@@ -143,7 +143,7 @@ pub const ChildProcess = struct {
143 }143 }
144 }144 }
145145
146 pub fn killWindows(self: &ChildProcess, exit_code: windows.UINT) !Term {146 pub fn killWindows(self: *ChildProcess, exit_code: windows.UINT) !Term {
147 if (self.term) |term| {147 if (self.term) |term| {
148 self.cleanupStreams();148 self.cleanupStreams();
149 return term;149 return term;
...@@ -159,7 +159,7 @@ pub const ChildProcess = struct {...@@ -159,7 +159,7 @@ pub const ChildProcess = struct {
159 return ??self.term;159 return ??self.term;
160 }160 }
161161
162 pub fn killPosix(self: &ChildProcess) !Term {162 pub fn killPosix(self: *ChildProcess) !Term {
163 if (self.term) |term| {163 if (self.term) |term| {
164 self.cleanupStreams();164 self.cleanupStreams();
165 return term;165 return term;
...@@ -179,7 +179,7 @@ pub const ChildProcess = struct {...@@ -179,7 +179,7 @@ pub const ChildProcess = struct {
179 }179 }
180180
181 /// Blocks until child process terminates and then cleans up all resources.181 /// Blocks until child process terminates and then cleans up all resources.
182 pub fn wait(self: &ChildProcess) !Term {182 pub fn wait(self: *ChildProcess) !Term {
183 if (is_windows) {183 if (is_windows) {
184 return self.waitWindows();184 return self.waitWindows();
185 } else {185 } else {
...@@ -195,7 +195,7 @@ pub const ChildProcess = struct {...@@ -195,7 +195,7 @@ pub const ChildProcess = struct {
195195
196 /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns.196 /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns.
197 /// If it succeeds, the caller owns result.stdout and result.stderr memory.197 /// If it succeeds, the caller owns result.stdout and result.stderr memory.
198 pub fn exec(allocator: &mem.Allocator, argv: []const []const u8, cwd: ?[]const u8, env_map: ?&const BufMap, max_output_size: usize) !ExecResult {198 pub fn exec(allocator: *mem.Allocator, argv: []const []const u8, cwd: ?[]const u8, env_map: ?*const BufMap, max_output_size: usize) !ExecResult {
199 const child = try ChildProcess.init(argv, allocator);199 const child = try ChildProcess.init(argv, allocator);
200 defer child.deinit();200 defer child.deinit();
201201
...@@ -225,7 +225,7 @@ pub const ChildProcess = struct {...@@ -225,7 +225,7 @@ pub const ChildProcess = struct {
225 };225 };
226 }226 }
227227
228 fn waitWindows(self: &ChildProcess) !Term {228 fn waitWindows(self: *ChildProcess) !Term {
229 if (self.term) |term| {229 if (self.term) |term| {
230 self.cleanupStreams();230 self.cleanupStreams();
231 return term;231 return term;
...@@ -235,7 +235,7 @@ pub const ChildProcess = struct {...@@ -235,7 +235,7 @@ pub const ChildProcess = struct {
235 return ??self.term;235 return ??self.term;
236 }236 }
237237
238 fn waitPosix(self: &ChildProcess) !Term {238 fn waitPosix(self: *ChildProcess) !Term {
239 if (self.term) |term| {239 if (self.term) |term| {
240 self.cleanupStreams();240 self.cleanupStreams();
241 return term;241 return term;
...@@ -245,11 +245,11 @@ pub const ChildProcess = struct {...@@ -245,11 +245,11 @@ pub const ChildProcess = struct {
245 return ??self.term;245 return ??self.term;
246 }246 }
247247
248 pub fn deinit(self: &ChildProcess) void {248 pub fn deinit(self: *ChildProcess) void {
249 self.allocator.destroy(self);249 self.allocator.destroy(self);
250 }250 }
251251
252 fn waitUnwrappedWindows(self: &ChildProcess) !void {252 fn waitUnwrappedWindows(self: *ChildProcess) !void {
253 const result = os.windowsWaitSingle(self.handle, windows.INFINITE);253 const result = os.windowsWaitSingle(self.handle, windows.INFINITE);
254254
255 self.term = (SpawnError!Term)(x: {255 self.term = (SpawnError!Term)(x: {
...@@ -267,7 +267,7 @@ pub const ChildProcess = struct {...@@ -267,7 +267,7 @@ pub const ChildProcess = struct {
267 return result;267 return result;
268 }268 }
269269
270 fn waitUnwrapped(self: &ChildProcess) void {270 fn waitUnwrapped(self: *ChildProcess) void {
271 var status: i32 = undefined;271 var status: i32 = undefined;
272 while (true) {272 while (true) {
273 const err = posix.getErrno(posix.waitpid(self.pid, &status, 0));273 const err = posix.getErrno(posix.waitpid(self.pid, &status, 0));
...@@ -283,11 +283,11 @@ pub const ChildProcess = struct {...@@ -283,11 +283,11 @@ pub const ChildProcess = struct {
283 }283 }
284 }284 }
285285
286 fn handleWaitResult(self: &ChildProcess, status: i32) void {286 fn handleWaitResult(self: *ChildProcess, status: i32) void {
287 self.term = self.cleanupAfterWait(status);287 self.term = self.cleanupAfterWait(status);
288 }288 }
289289
290 fn cleanupStreams(self: &ChildProcess) void {290 fn cleanupStreams(self: *ChildProcess) void {
291 if (self.stdin) |*stdin| {291 if (self.stdin) |*stdin| {
292 stdin.close();292 stdin.close();
293 self.stdin = null;293 self.stdin = null;
...@@ -302,7 +302,7 @@ pub const ChildProcess = struct {...@@ -302,7 +302,7 @@ pub const ChildProcess = struct {
302 }302 }
303 }303 }
304304
305 fn cleanupAfterWait(self: &ChildProcess, status: i32) !Term {305 fn cleanupAfterWait(self: *ChildProcess, status: i32) !Term {
306 defer {306 defer {
307 os.close(self.err_pipe[0]);307 os.close(self.err_pipe[0]);
308 os.close(self.err_pipe[1]);308 os.close(self.err_pipe[1]);
...@@ -335,7 +335,7 @@ pub const ChildProcess = struct {...@@ -335,7 +335,7 @@ pub const ChildProcess = struct {
335 Term{ .Unknown = status };335 Term{ .Unknown = status };
336 }336 }
337337
338 fn spawnPosix(self: &ChildProcess) !void {338 fn spawnPosix(self: *ChildProcess) !void {
339 const stdin_pipe = if (self.stdin_behavior == StdIo.Pipe) try makePipe() else undefined;339 const stdin_pipe = if (self.stdin_behavior == StdIo.Pipe) try makePipe() else undefined;
340 errdefer if (self.stdin_behavior == StdIo.Pipe) {340 errdefer if (self.stdin_behavior == StdIo.Pipe) {
341 destroyPipe(stdin_pipe);341 destroyPipe(stdin_pipe);
...@@ -387,15 +387,12 @@ pub const ChildProcess = struct {...@@ -387,15 +387,12 @@ pub const ChildProcess = struct {
387 const pid_err = posix.getErrno(pid_result);387 const pid_err = posix.getErrno(pid_result);
388 if (pid_err > 0) {388 if (pid_err > 0) {
389 return switch (pid_err) {389 return switch (pid_err) {
390 posix.EAGAIN,390 posix.EAGAIN, posix.ENOMEM, posix.ENOSYS => error.SystemResources,
391 posix.ENOMEM,
392 posix.ENOSYS => error.SystemResources,
393 else => os.unexpectedErrorPosix(pid_err),391 else => os.unexpectedErrorPosix(pid_err),
394 };392 };
395 }393 }
396 if (pid_result == 0) {394 if (pid_result == 0) {
397 // we are the child395 // we are the child
398
399 setUpChildIo(self.stdin_behavior, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err);396 setUpChildIo(self.stdin_behavior, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err);
400 setUpChildIo(self.stdout_behavior, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err);397 setUpChildIo(self.stdout_behavior, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err);
401 setUpChildIo(self.stderr_behavior, stderr_pipe[1], posix.STDERR_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err);398 setUpChildIo(self.stderr_behavior, stderr_pipe[1], posix.STDERR_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err);
...@@ -435,7 +432,7 @@ pub const ChildProcess = struct {...@@ -435,7 +432,7 @@ pub const ChildProcess = struct {
435432
436 self.pid = pid;433 self.pid = pid;
437 self.err_pipe = err_pipe;434 self.err_pipe = err_pipe;
438 self.llnode = LinkedList(&ChildProcess).Node.init(self);435 self.llnode = LinkedList(*ChildProcess).Node.init(self);
439 self.term = null;436 self.term = null;
440437
441 if (self.stdin_behavior == StdIo.Pipe) {438 if (self.stdin_behavior == StdIo.Pipe) {
...@@ -449,7 +446,7 @@ pub const ChildProcess = struct {...@@ -449,7 +446,7 @@ pub const ChildProcess = struct {
449 }446 }
450 }447 }
451448
452 fn spawnWindows(self: &ChildProcess) !void {449 fn spawnWindows(self: *ChildProcess) !void {
453 const saAttr = windows.SECURITY_ATTRIBUTES{450 const saAttr = windows.SECURITY_ATTRIBUTES{
454 .nLength = @sizeOf(windows.SECURITY_ATTRIBUTES),451 .nLength = @sizeOf(windows.SECURITY_ATTRIBUTES),
455 .bInheritHandle = windows.TRUE,452 .bInheritHandle = windows.TRUE,
...@@ -642,12 +639,11 @@ pub const ChildProcess = struct {...@@ -642,12 +639,11 @@ pub const ChildProcess = struct {
642 }639 }
643};640};
644641
645fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ?&u8, lpStartupInfo: &windows.STARTUPINFOA, lpProcessInformation: &windows.PROCESS_INFORMATION) !void {642fn windowsCreateProcess(app_name: [*]u8, cmd_line: [*]u8, envp_ptr: ?[*]u8, cwd_ptr: ?[*]u8, lpStartupInfo: *windows.STARTUPINFOA, lpProcessInformation: *windows.PROCESS_INFORMATION) !void {
646 if (windows.CreateProcessA(app_name, cmd_line, null, null, windows.TRUE, 0, @ptrCast(?&c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation) == 0) {643 if (windows.CreateProcessA(app_name, cmd_line, null, null, windows.TRUE, 0, @ptrCast(?*c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation) == 0) {
647 const err = windows.GetLastError();644 const err = windows.GetLastError();
648 return switch (err) {645 return switch (err) {
649 windows.ERROR.FILE_NOT_FOUND,646 windows.ERROR.FILE_NOT_FOUND, windows.ERROR.PATH_NOT_FOUND => error.FileNotFound,
650 windows.ERROR.PATH_NOT_FOUND => error.FileNotFound,
651 windows.ERROR.INVALID_PARAMETER => unreachable,647 windows.ERROR.INVALID_PARAMETER => unreachable,
652 windows.ERROR.INVALID_NAME => error.InvalidName,648 windows.ERROR.INVALID_NAME => error.InvalidName,
653 else => os.unexpectedErrorWindows(err),649 else => os.unexpectedErrorWindows(err),
...@@ -657,7 +653,7 @@ fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ?...@@ -657,7 +653,7 @@ fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ?
657653
658/// Caller must dealloc.654/// Caller must dealloc.
659/// Guarantees a null byte at result[result.len].655/// Guarantees a null byte at result[result.len].
660fn windowsCreateCommandLine(allocator: &mem.Allocator, argv: []const []const u8) ![]u8 {656fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![]u8 {
661 var buf = try Buffer.initSize(allocator, 0);657 var buf = try Buffer.initSize(allocator, 0);
662 defer buf.deinit();658 defer buf.deinit();
663659
...@@ -702,7 +698,7 @@ fn windowsDestroyPipe(rd: ?windows.HANDLE, wr: ?windows.HANDLE) void {...@@ -702,7 +698,7 @@ fn windowsDestroyPipe(rd: ?windows.HANDLE, wr: ?windows.HANDLE) void {
702// a namespace field lookup698// a namespace field lookup
703const SECURITY_ATTRIBUTES = windows.SECURITY_ATTRIBUTES;699const SECURITY_ATTRIBUTES = windows.SECURITY_ATTRIBUTES;
704700
705fn windowsMakePipe(rd: &windows.HANDLE, wr: &windows.HANDLE, sattr: &const SECURITY_ATTRIBUTES) !void {701fn windowsMakePipe(rd: *windows.HANDLE, wr: *windows.HANDLE, sattr: *const SECURITY_ATTRIBUTES) !void {
706 if (windows.CreatePipe(rd, wr, sattr, 0) == 0) {702 if (windows.CreatePipe(rd, wr, sattr, 0) == 0) {
707 const err = windows.GetLastError();703 const err = windows.GetLastError();
708 return switch (err) {704 return switch (err) {
...@@ -720,7 +716,7 @@ fn windowsSetHandleInfo(h: windows.HANDLE, mask: windows.DWORD, flags: windows.D...@@ -720,7 +716,7 @@ fn windowsSetHandleInfo(h: windows.HANDLE, mask: windows.DWORD, flags: windows.D
720 }716 }
721}717}
722718
723fn windowsMakePipeIn(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const SECURITY_ATTRIBUTES) !void {719fn windowsMakePipeIn(rd: *?windows.HANDLE, wr: *?windows.HANDLE, sattr: *const SECURITY_ATTRIBUTES) !void {
724 var rd_h: windows.HANDLE = undefined;720 var rd_h: windows.HANDLE = undefined;
725 var wr_h: windows.HANDLE = undefined;721 var wr_h: windows.HANDLE = undefined;
726 try windowsMakePipe(&rd_h, &wr_h, sattr);722 try windowsMakePipe(&rd_h, &wr_h, sattr);
...@@ -730,7 +726,7 @@ fn windowsMakePipeIn(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const S...@@ -730,7 +726,7 @@ fn windowsMakePipeIn(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const S
730 wr.* = wr_h;726 wr.* = wr_h;
731}727}
732728
733fn windowsMakePipeOut(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const SECURITY_ATTRIBUTES) !void {729fn windowsMakePipeOut(rd: *?windows.HANDLE, wr: *?windows.HANDLE, sattr: *const SECURITY_ATTRIBUTES) !void {
734 var rd_h: windows.HANDLE = undefined;730 var rd_h: windows.HANDLE = undefined;
735 var wr_h: windows.HANDLE = undefined;731 var wr_h: windows.HANDLE = undefined;
736 try windowsMakePipe(&rd_h, &wr_h, sattr);732 try windowsMakePipe(&rd_h, &wr_h, sattr);
...@@ -745,15 +741,14 @@ fn makePipe() ![2]i32 {...@@ -745,15 +741,14 @@ fn makePipe() ![2]i32 {
745 const err = posix.getErrno(posix.pipe(&fds));741 const err = posix.getErrno(posix.pipe(&fds));
746 if (err > 0) {742 if (err > 0) {
747 return switch (err) {743 return switch (err) {
748 posix.EMFILE,744 posix.EMFILE, posix.ENFILE => error.SystemResources,
749 posix.ENFILE => error.SystemResources,
750 else => os.unexpectedErrorPosix(err),745 else => os.unexpectedErrorPosix(err),
751 };746 };
752 }747 }
753 return fds;748 return fds;
754}749}
755750
756fn destroyPipe(pipe: &const [2]i32) void {751fn destroyPipe(pipe: *const [2]i32) void {
757 os.close((pipe.*)[0]);752 os.close((pipe.*)[0]);
758 os.close((pipe.*)[1]);753 os.close((pipe.*)[1]);
759}754}
std/os/darwin.zig+102-35
...@@ -12,52 +12,71 @@ pub const STDERR_FILENO = 2;...@@ -12,52 +12,71 @@ pub const STDERR_FILENO = 2;
1212
13/// [MC2] no permissions13/// [MC2] no permissions
14pub const PROT_NONE = 0x00;14pub const PROT_NONE = 0x00;
15
15/// [MC2] pages can be read16/// [MC2] pages can be read
16pub const PROT_READ = 0x01;17pub const PROT_READ = 0x01;
18
17/// [MC2] pages can be written19/// [MC2] pages can be written
18pub const PROT_WRITE = 0x02;20pub const PROT_WRITE = 0x02;
21
19/// [MC2] pages can be executed22/// [MC2] pages can be executed
20pub const PROT_EXEC = 0x04;23pub const PROT_EXEC = 0x04;
2124
22/// allocated from memory, swap space25/// allocated from memory, swap space
23pub const MAP_ANONYMOUS = 0x1000;26pub const MAP_ANONYMOUS = 0x1000;
27
24/// map from file (default)28/// map from file (default)
25pub const MAP_FILE = 0x0000;29pub const MAP_FILE = 0x0000;
30
26/// interpret addr exactly31/// interpret addr exactly
27pub const MAP_FIXED = 0x0010;32pub const MAP_FIXED = 0x0010;
33
28/// region may contain semaphores34/// region may contain semaphores
29pub const MAP_HASSEMAPHORE = 0x0200;35pub const MAP_HASSEMAPHORE = 0x0200;
36
30/// changes are private37/// changes are private
31pub const MAP_PRIVATE = 0x0002;38pub const MAP_PRIVATE = 0x0002;
39
32/// share changes40/// share changes
33pub const MAP_SHARED = 0x0001;41pub const MAP_SHARED = 0x0001;
42
34/// don't cache pages for this mapping43/// don't cache pages for this mapping
35pub const MAP_NOCACHE = 0x0400;44pub const MAP_NOCACHE = 0x0400;
45
36/// don't reserve needed swap area46/// don't reserve needed swap area
37pub const MAP_NORESERVE = 0x0040;47pub const MAP_NORESERVE = 0x0040;
38pub const MAP_FAILED = @maxValue(usize);48pub const MAP_FAILED = @maxValue(usize);
3949
40/// [XSI] no hang in wait/no child to reap50/// [XSI] no hang in wait/no child to reap
41pub const WNOHANG = 0x00000001;51pub const WNOHANG = 0x00000001;
52
42/// [XSI] notify on stop, untraced child53/// [XSI] notify on stop, untraced child
43pub const WUNTRACED = 0x00000002;54pub const WUNTRACED = 0x00000002;
4455
45/// take signal on signal stack56/// take signal on signal stack
46pub const SA_ONSTACK = 0x0001;57pub const SA_ONSTACK = 0x0001;
58
47/// restart system on signal return59/// restart system on signal return
48pub const SA_RESTART = 0x0002;60pub const SA_RESTART = 0x0002;
61
49/// reset to SIG_DFL when taking signal62/// reset to SIG_DFL when taking signal
50pub const SA_RESETHAND = 0x0004;63pub const SA_RESETHAND = 0x0004;
64
51/// do not generate SIGCHLD on child stop65/// do not generate SIGCHLD on child stop
52pub const SA_NOCLDSTOP = 0x0008;66pub const SA_NOCLDSTOP = 0x0008;
67
53/// don't mask the signal we're delivering68/// don't mask the signal we're delivering
54pub const SA_NODEFER = 0x0010;69pub const SA_NODEFER = 0x0010;
70
55/// don't keep zombies around71/// don't keep zombies around
56pub const SA_NOCLDWAIT = 0x0020;72pub const SA_NOCLDWAIT = 0x0020;
73
57/// signal handler with SA_SIGINFO args74/// signal handler with SA_SIGINFO args
58pub const SA_SIGINFO = 0x0040;75pub const SA_SIGINFO = 0x0040;
76
59/// do not bounce off kernel's sigtramp77/// do not bounce off kernel's sigtramp
60pub const SA_USERTRAMP = 0x0100;78pub const SA_USERTRAMP = 0x0100;
79
61/// signal handler with SA_SIGINFO args with 64bit regs information80/// signal handler with SA_SIGINFO args with 64bit regs information
62pub const SA_64REGSET = 0x0200;81pub const SA_64REGSET = 0x0200;
6382
...@@ -71,30 +90,43 @@ pub const R_OK = 4;...@@ -71,30 +90,43 @@ pub const R_OK = 4;
7190
72/// open for reading only91/// open for reading only
73pub const O_RDONLY = 0x0000;92pub const O_RDONLY = 0x0000;
93
74/// open for writing only94/// open for writing only
75pub const O_WRONLY = 0x0001;95pub const O_WRONLY = 0x0001;
96
76/// open for reading and writing97/// open for reading and writing
77pub const O_RDWR = 0x0002;98pub const O_RDWR = 0x0002;
99
78/// do not block on open or for data to become available100/// do not block on open or for data to become available
79pub const O_NONBLOCK = 0x0004;101pub const O_NONBLOCK = 0x0004;
102
80/// append on each write103/// append on each write
81pub const O_APPEND = 0x0008;104pub const O_APPEND = 0x0008;
105
82/// create file if it does not exist106/// create file if it does not exist
83pub const O_CREAT = 0x0200;107pub const O_CREAT = 0x0200;
108
84/// truncate size to 0109/// truncate size to 0
85pub const O_TRUNC = 0x0400;110pub const O_TRUNC = 0x0400;
111
86/// error if O_CREAT and the file exists112/// error if O_CREAT and the file exists
87pub const O_EXCL = 0x0800;113pub const O_EXCL = 0x0800;
114
88/// atomically obtain a shared lock115/// atomically obtain a shared lock
89pub const O_SHLOCK = 0x0010;116pub const O_SHLOCK = 0x0010;
117
90/// atomically obtain an exclusive lock118/// atomically obtain an exclusive lock
91pub const O_EXLOCK = 0x0020;119pub const O_EXLOCK = 0x0020;
120
92/// do not follow symlinks121/// do not follow symlinks
93pub const O_NOFOLLOW = 0x0100;122pub const O_NOFOLLOW = 0x0100;
123
94/// allow open of symlinks124/// allow open of symlinks
95pub const O_SYMLINK = 0x200000;125pub const O_SYMLINK = 0x200000;
126
96/// descriptor requested for event notifications only127/// descriptor requested for event notifications only
97pub const O_EVTONLY = 0x8000;128pub const O_EVTONLY = 0x8000;
129
98/// mark as close-on-exec130/// mark as close-on-exec
99pub const O_CLOEXEC = 0x1000000;131pub const O_CLOEXEC = 0x1000000;
100132
...@@ -126,75 +158,109 @@ pub const DT_WHT = 14;...@@ -126,75 +158,109 @@ pub const DT_WHT = 14;
126158
127/// block specified signal set159/// block specified signal set
128pub const SIG_BLOCK = 1;160pub const SIG_BLOCK = 1;
161
129/// unblock specified signal set162/// unblock specified signal set
130pub const SIG_UNBLOCK = 2;163pub const SIG_UNBLOCK = 2;
164
131/// set specified signal set165/// set specified signal set
132pub const SIG_SETMASK = 3;166pub const SIG_SETMASK = 3;
133167
134/// hangup168/// hangup
135pub const SIGHUP = 1;169pub const SIGHUP = 1;
170
136/// interrupt171/// interrupt
137pub const SIGINT = 2;172pub const SIGINT = 2;
173
138/// quit174/// quit
139pub const SIGQUIT = 3;175pub const SIGQUIT = 3;
176
140/// illegal instruction (not reset when caught)177/// illegal instruction (not reset when caught)
141pub const SIGILL = 4;178pub const SIGILL = 4;
179
142/// trace trap (not reset when caught)180/// trace trap (not reset when caught)
143pub const SIGTRAP = 5;181pub const SIGTRAP = 5;
182
144/// abort()183/// abort()
145pub const SIGABRT = 6;184pub const SIGABRT = 6;
185
146/// pollable event ([XSR] generated, not supported)186/// pollable event ([XSR] generated, not supported)
147pub const SIGPOLL = 7;187pub const SIGPOLL = 7;
188
148/// compatibility189/// compatibility
149pub const SIGIOT = SIGABRT;190pub const SIGIOT = SIGABRT;
191
150/// EMT instruction192/// EMT instruction
151pub const SIGEMT = 7;193pub const SIGEMT = 7;
194
152/// floating point exception195/// floating point exception
153pub const SIGFPE = 8;196pub const SIGFPE = 8;
197
154/// kill (cannot be caught or ignored)198/// kill (cannot be caught or ignored)
155pub const SIGKILL = 9;199pub const SIGKILL = 9;
200
156/// bus error201/// bus error
157pub const SIGBUS = 10;202pub const SIGBUS = 10;
203
158/// segmentation violation204/// segmentation violation
159pub const SIGSEGV = 11;205pub const SIGSEGV = 11;
206
160/// bad argument to system call207/// bad argument to system call
161pub const SIGSYS = 12;208pub const SIGSYS = 12;
209
162/// write on a pipe with no one to read it210/// write on a pipe with no one to read it
163pub const SIGPIPE = 13;211pub const SIGPIPE = 13;
212
164/// alarm clock213/// alarm clock
165pub const SIGALRM = 14;214pub const SIGALRM = 14;
215
166/// software termination signal from kill216/// software termination signal from kill
167pub const SIGTERM = 15;217pub const SIGTERM = 15;
218
168/// urgent condition on IO channel219/// urgent condition on IO channel
169pub const SIGURG = 16;220pub const SIGURG = 16;
221
170/// sendable stop signal not from tty222/// sendable stop signal not from tty
171pub const SIGSTOP = 17;223pub const SIGSTOP = 17;
224
172/// stop signal from tty225/// stop signal from tty
173pub const SIGTSTP = 18;226pub const SIGTSTP = 18;
227
174/// continue a stopped process228/// continue a stopped process
175pub const SIGCONT = 19;229pub const SIGCONT = 19;
230
176/// to parent on child stop or exit231/// to parent on child stop or exit
177pub const SIGCHLD = 20;232pub const SIGCHLD = 20;
233
178/// to readers pgrp upon background tty read234/// to readers pgrp upon background tty read
179pub const SIGTTIN = 21;235pub const SIGTTIN = 21;
236
180/// like TTIN for output if (tp->t_local&LTOSTOP)237/// like TTIN for output if (tp->t_local&LTOSTOP)
181pub const SIGTTOU = 22;238pub const SIGTTOU = 22;
239
182/// input/output possible signal240/// input/output possible signal
183pub const SIGIO = 23;241pub const SIGIO = 23;
242
184/// exceeded CPU time limit243/// exceeded CPU time limit
185pub const SIGXCPU = 24;244pub const SIGXCPU = 24;
245
186/// exceeded file size limit246/// exceeded file size limit
187pub const SIGXFSZ = 25;247pub const SIGXFSZ = 25;
248
188/// virtual time alarm249/// virtual time alarm
189pub const SIGVTALRM = 26;250pub const SIGVTALRM = 26;
251
190/// profiling time alarm252/// profiling time alarm
191pub const SIGPROF = 27;253pub const SIGPROF = 27;
254
192/// window size changes255/// window size changes
193pub const SIGWINCH = 28;256pub const SIGWINCH = 28;
257
194/// information request258/// information request
195pub const SIGINFO = 29;259pub const SIGINFO = 29;
260
196/// user defined signal 1261/// user defined signal 1
197pub const SIGUSR1 = 30;262pub const SIGUSR1 = 30;
263
198/// user defined signal 2264/// user defined signal 2
199pub const SIGUSR2 = 31;265pub const SIGUSR2 = 31;
200266
...@@ -243,7 +309,7 @@ pub fn isatty(fd: i32) bool {...@@ -243,7 +309,7 @@ pub fn isatty(fd: i32) bool {
243 return c.isatty(fd) != 0;309 return c.isatty(fd) != 0;
244}310}
245311
246pub fn fstat(fd: i32, buf: &c.Stat) usize {312pub fn fstat(fd: i32, buf: *c.Stat) usize {
247 return errnoWrap(c.@"fstat$INODE64"(fd, buf));313 return errnoWrap(c.@"fstat$INODE64"(fd, buf));
248}314}
249315
...@@ -251,7 +317,8 @@ pub fn lseek(fd: i32, offset: isize, whence: c_int) usize {...@@ -251,7 +317,8 @@ pub fn lseek(fd: i32, offset: isize, whence: c_int) usize {
251 return errnoWrap(c.lseek(fd, offset, whence));317 return errnoWrap(c.lseek(fd, offset, whence));
252}318}
253319
254pub fn open(path: &const u8, flags: u32, mode: usize) usize {320// TODO https://github.com/ziglang/zig/issues/265 on the whole file
321pub fn open(path: [*]const u8, flags: u32, mode: usize) usize {
255 return errnoWrap(c.open(path, @bitCast(c_int, flags), mode));322 return errnoWrap(c.open(path, @bitCast(c_int, flags), mode));
256}323}
257324
...@@ -259,79 +326,79 @@ pub fn raise(sig: i32) usize {...@@ -259,79 +326,79 @@ pub fn raise(sig: i32) usize {
259 return errnoWrap(c.raise(sig));326 return errnoWrap(c.raise(sig));
260}327}
261328
262pub fn read(fd: i32, buf: &u8, nbyte: usize) usize {329pub fn read(fd: i32, buf: [*]u8, nbyte: usize) usize {
263 return errnoWrap(c.read(fd, @ptrCast(&c_void, buf), nbyte));330 return errnoWrap(c.read(fd, @ptrCast([*]c_void, buf), nbyte));
264}331}
265332
266pub fn stat(noalias path: &const u8, noalias buf: &stat) usize {333pub fn stat(noalias path: [*]const u8, noalias buf: *stat) usize {
267 return errnoWrap(c.stat(path, buf));334 return errnoWrap(c.stat(path, buf));
268}335}
269336
270pub fn write(fd: i32, buf: &const u8, nbyte: usize) usize {337pub fn write(fd: i32, buf: [*]const u8, nbyte: usize) usize {
271 return errnoWrap(c.write(fd, @ptrCast(&const c_void, buf), nbyte));338 return errnoWrap(c.write(fd, @ptrCast([*]const c_void, buf), nbyte));
272}339}
273340
274pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize {341pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize {
275 const ptr_result = c.mmap(@ptrCast(&c_void, address), length, @bitCast(c_int, c_uint(prot)), @bitCast(c_int, c_uint(flags)), fd, offset);342 const ptr_result = c.mmap(@ptrCast([*]c_void, address), length, @bitCast(c_int, c_uint(prot)), @bitCast(c_int, c_uint(flags)), fd, offset);
276 const isize_result = @bitCast(isize, @ptrToInt(ptr_result));343 const isize_result = @bitCast(isize, @ptrToInt(ptr_result));
277 return errnoWrap(isize_result);344 return errnoWrap(isize_result);
278}345}
279346
280pub fn munmap(address: usize, length: usize) usize {347pub fn munmap(address: usize, length: usize) usize {
281 return errnoWrap(c.munmap(@intToPtr(&c_void, address), length));348 return errnoWrap(c.munmap(@intToPtr([*]c_void, address), length));
282}349}
283350
284pub fn unlink(path: &const u8) usize {351pub fn unlink(path: [*]const u8) usize {
285 return errnoWrap(c.unlink(path));352 return errnoWrap(c.unlink(path));
286}353}
287354
288pub fn getcwd(buf: &u8, size: usize) usize {355pub fn getcwd(buf: [*]u8, size: usize) usize {
289 return if (c.getcwd(buf, size) == null) @bitCast(usize, -isize(c._errno().*)) else 0;356 return if (c.getcwd(buf, size) == null) @bitCast(usize, -isize(c._errno().*)) else 0;
290}357}
291358
292pub fn waitpid(pid: i32, status: &i32, options: u32) usize {359pub fn waitpid(pid: i32, status: *i32, options: u32) usize {
293 comptime assert(i32.bit_count == c_int.bit_count);360 comptime assert(i32.bit_count == c_int.bit_count);
294 return errnoWrap(c.waitpid(pid, @ptrCast(&c_int, status), @bitCast(c_int, options)));361 return errnoWrap(c.waitpid(pid, @ptrCast(*c_int, status), @bitCast(c_int, options)));
295}362}
296363
297pub fn fork() usize {364pub fn fork() usize {
298 return errnoWrap(c.fork());365 return errnoWrap(c.fork());
299}366}
300367
301pub fn access(path: &const u8, mode: u32) usize {368pub fn access(path: [*]const u8, mode: u32) usize {
302 return errnoWrap(c.access(path, mode));369 return errnoWrap(c.access(path, mode));
303}370}
304371
305pub fn pipe(fds: &[2]i32) usize {372pub fn pipe(fds: *[2]i32) usize {
306 comptime assert(i32.bit_count == c_int.bit_count);373 comptime assert(i32.bit_count == c_int.bit_count);
307 return errnoWrap(c.pipe(@ptrCast(&c_int, fds)));374 return errnoWrap(c.pipe(@ptrCast(*[2]c_int, fds)));
308}375}
309376
310pub fn getdirentries64(fd: i32, buf_ptr: &u8, buf_len: usize, basep: &i64) usize {377pub fn getdirentries64(fd: i32, buf_ptr: [*]u8, buf_len: usize, basep: *i64) usize {
311 return errnoWrap(@bitCast(isize, c.__getdirentries64(fd, buf_ptr, buf_len, basep)));378 return errnoWrap(@bitCast(isize, c.__getdirentries64(fd, buf_ptr, buf_len, basep)));
312}379}
313380
314pub fn mkdir(path: &const u8, mode: u32) usize {381pub fn mkdir(path: [*]const u8, mode: u32) usize {
315 return errnoWrap(c.mkdir(path, mode));382 return errnoWrap(c.mkdir(path, mode));
316}383}
317384
318pub fn symlink(existing: &const u8, new: &const u8) usize {385pub fn symlink(existing: [*]const u8, new: [*]const u8) usize {
319 return errnoWrap(c.symlink(existing, new));386 return errnoWrap(c.symlink(existing, new));
320}387}
321388
322pub fn rename(old: &const u8, new: &const u8) usize {389pub fn rename(old: [*]const u8, new: [*]const u8) usize {
323 return errnoWrap(c.rename(old, new));390 return errnoWrap(c.rename(old, new));
324}391}
325392
326pub fn rmdir(path: &const u8) usize {393pub fn rmdir(path: [*]const u8) usize {
327 return errnoWrap(c.rmdir(path));394 return errnoWrap(c.rmdir(path));
328}395}
329396
330pub fn chdir(path: &const u8) usize {397pub fn chdir(path: [*]const u8) usize {
331 return errnoWrap(c.chdir(path));398 return errnoWrap(c.chdir(path));
332}399}
333400
334pub fn execve(path: &const u8, argv: &const ?&const u8, envp: &const ?&const u8) usize {401pub fn execve(path: [*]const u8, argv: [*]const ?[*]const u8, envp: [*]const ?[*]const u8) usize {
335 return errnoWrap(c.execve(path, argv, envp));402 return errnoWrap(c.execve(path, argv, envp));
336}403}
337404
...@@ -339,19 +406,19 @@ pub fn dup2(old: i32, new: i32) usize {...@@ -339,19 +406,19 @@ pub fn dup2(old: i32, new: i32) usize {
339 return errnoWrap(c.dup2(old, new));406 return errnoWrap(c.dup2(old, new));
340}407}
341408
342pub fn readlink(noalias path: &const u8, noalias buf_ptr: &u8, buf_len: usize) usize {409pub fn readlink(noalias path: [*]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {
343 return errnoWrap(c.readlink(path, buf_ptr, buf_len));410 return errnoWrap(c.readlink(path, buf_ptr, buf_len));
344}411}
345412
346pub fn gettimeofday(tv: ?&timeval, tz: ?&timezone) usize {413pub fn gettimeofday(tv: ?*timeval, tz: ?*timezone) usize {
347 return errnoWrap(c.gettimeofday(tv, tz));414 return errnoWrap(c.gettimeofday(tv, tz));
348}415}
349416
350pub fn nanosleep(req: &const timespec, rem: ?&timespec) usize {417pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize {
351 return errnoWrap(c.nanosleep(req, rem));418 return errnoWrap(c.nanosleep(req, rem));
352}419}
353420
354pub fn realpath(noalias filename: &const u8, noalias resolved_name: &u8) usize {421pub fn realpath(noalias filename: [*]const u8, noalias resolved_name: [*]u8) usize {
355 return if (c.realpath(filename, resolved_name) == null) @bitCast(usize, -isize(c._errno().*)) else 0;422 return if (c.realpath(filename, resolved_name) == null) @bitCast(usize, -isize(c._errno().*)) else 0;
356}423}
357424
...@@ -363,26 +430,26 @@ pub fn setregid(rgid: u32, egid: u32) usize {...@@ -363,26 +430,26 @@ pub fn setregid(rgid: u32, egid: u32) usize {
363 return errnoWrap(c.setregid(rgid, egid));430 return errnoWrap(c.setregid(rgid, egid));
364}431}
365432
366pub fn sigprocmask(flags: u32, noalias set: &const sigset_t, noalias oldset: ?&sigset_t) usize {433pub fn sigprocmask(flags: u32, noalias set: *const sigset_t, noalias oldset: ?*sigset_t) usize {
367 return errnoWrap(c.sigprocmask(@bitCast(c_int, flags), set, oldset));434 return errnoWrap(c.sigprocmask(@bitCast(c_int, flags), set, oldset));
368}435}
369436
370pub fn sigaction(sig: u5, noalias act: &const Sigaction, noalias oact: ?&Sigaction) usize {437pub fn sigaction(sig: u5, noalias act: *const Sigaction, noalias oact: ?*Sigaction) usize {
371 assert(sig != SIGKILL);438 assert(sig != SIGKILL);
372 assert(sig != SIGSTOP);439 assert(sig != SIGSTOP);
373 var cact = c.Sigaction{440 var cact = c.Sigaction{
374 .handler = @ptrCast(extern fn(c_int) void, act.handler),441 .handler = @ptrCast(extern fn (c_int) void, act.handler),
375 .sa_flags = @bitCast(c_int, act.flags),442 .sa_flags = @bitCast(c_int, act.flags),
376 .sa_mask = act.mask,443 .sa_mask = act.mask,
377 };444 };
378 var coact: c.Sigaction = undefined;445 var coact: c.Sigaction = undefined;
379 const result = errnoWrap(c.sigaction(sig, &cact, &coact));446 const result = errnoWrap(c.sigaction(sig, *cact, *coact));
380 if (result != 0) {447 if (result != 0) {
381 return result;448 return result;
382 }449 }
383 if (oact) |old| {450 if (oact) |old| {
384 old.* = Sigaction{451 old.* = Sigaction{
385 .handler = @ptrCast(extern fn(i32) void, coact.handler),452 .handler = @ptrCast(extern fn (i32) void, coact.handler),
386 .flags = @bitCast(u32, coact.sa_flags),453 .flags = @bitCast(u32, coact.sa_flags),
387 .mask = coact.sa_mask,454 .mask = coact.sa_mask,
388 };455 };
...@@ -402,12 +469,12 @@ pub const sockaddr = c.sockaddr;...@@ -402,12 +469,12 @@ pub const sockaddr = c.sockaddr;
402469
403/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.470/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
404pub const Sigaction = struct {471pub const Sigaction = struct {
405 handler: extern fn(i32) void,472 handler: extern fn (i32) void,
406 mask: sigset_t,473 mask: sigset_t,
407 flags: u32,474 flags: u32,
408};475};
409476
410pub fn sigaddset(set: &sigset_t, signo: u5) void {477pub fn sigaddset(set: *sigset_t, signo: u5) void {
411 set.* |= u32(1) << (signo - 1);478 set.* |= u32(1) << (signo - 1);
412}479}
413480
std/os/darwin_errno.zig+294-108
...@@ -1,142 +1,328 @@...@@ -1,142 +1,328 @@
1/// Operation not permitted
2pub const EPERM = 1;
13
2pub const EPERM = 1; /// Operation not permitted4/// No such file or directory
3pub const ENOENT = 2; /// No such file or directory5pub const ENOENT = 2;
4pub const ESRCH = 3; /// No such process6
5pub const EINTR = 4; /// Interrupted system call7/// No such process
6pub const EIO = 5; /// Input/output error8pub const ESRCH = 3;
7pub const ENXIO = 6; /// Device not configured9
8pub const E2BIG = 7; /// Argument list too long10/// Interrupted system call
9pub const ENOEXEC = 8; /// Exec format error11pub const EINTR = 4;
10pub const EBADF = 9; /// Bad file descriptor12
11pub const ECHILD = 10; /// No child processes13/// Input/output error
12pub const EDEADLK = 11; /// Resource deadlock avoided14pub const EIO = 5;
1315
14pub const ENOMEM = 12; /// Cannot allocate memory16/// Device not configured
15pub const EACCES = 13; /// Permission denied17pub const ENXIO = 6;
16pub const EFAULT = 14; /// Bad address18
17pub const ENOTBLK = 15; /// Block device required19/// Argument list too long
18pub const EBUSY = 16; /// Device / Resource busy20pub const E2BIG = 7;
19pub const EEXIST = 17; /// File exists21
20pub const EXDEV = 18; /// Cross-device link22/// Exec format error
21pub const ENODEV = 19; /// Operation not supported by device23pub const ENOEXEC = 8;
22pub const ENOTDIR = 20; /// Not a directory24
23pub const EISDIR = 21; /// Is a directory25/// Bad file descriptor
24pub const EINVAL = 22; /// Invalid argument26pub const EBADF = 9;
25pub const ENFILE = 23; /// Too many open files in system27
26pub const EMFILE = 24; /// Too many open files28/// No child processes
27pub const ENOTTY = 25; /// Inappropriate ioctl for device29pub const ECHILD = 10;
28pub const ETXTBSY = 26; /// Text file busy30
29pub const EFBIG = 27; /// File too large31/// Resource deadlock avoided
30pub const ENOSPC = 28; /// No space left on device32pub const EDEADLK = 11;
31pub const ESPIPE = 29; /// Illegal seek33
32pub const EROFS = 30; /// Read-only file system34/// Cannot allocate memory
33pub const EMLINK = 31; /// Too many links35pub const ENOMEM = 12;
34pub const EPIPE = 32; /// Broken pipe36
37/// Permission denied
38pub const EACCES = 13;
39
40/// Bad address
41pub const EFAULT = 14;
42
43/// Block device required
44pub const ENOTBLK = 15;
45
46/// Device / Resource busy
47pub const EBUSY = 16;
48
49/// File exists
50pub const EEXIST = 17;
51
52/// Cross-device link
53pub const EXDEV = 18;
54
55/// Operation not supported by device
56pub const ENODEV = 19;
57
58/// Not a directory
59pub const ENOTDIR = 20;
60
61/// Is a directory
62pub const EISDIR = 21;
63
64/// Invalid argument
65pub const EINVAL = 22;
66
67/// Too many open files in system
68pub const ENFILE = 23;
69
70/// Too many open files
71pub const EMFILE = 24;
72
73/// Inappropriate ioctl for device
74pub const ENOTTY = 25;
75
76/// Text file busy
77pub const ETXTBSY = 26;
78
79/// File too large
80pub const EFBIG = 27;
81
82/// No space left on device
83pub const ENOSPC = 28;
84
85/// Illegal seek
86pub const ESPIPE = 29;
87
88/// Read-only file system
89pub const EROFS = 30;
90
91/// Too many links
92pub const EMLINK = 31;
93/// Broken pipe
3594
36// math software95// math software
37pub const EDOM = 33; /// Numerical argument out of domain96pub const EPIPE = 32;
38pub const ERANGE = 34; /// Result too large97
98/// Numerical argument out of domain
99pub const EDOM = 33;
100/// Result too large
39101
40// non-blocking and interrupt i/o102// non-blocking and interrupt i/o
41pub const EAGAIN = 35; /// Resource temporarily unavailable103pub const ERANGE = 34;
42pub const EWOULDBLOCK = EAGAIN; /// Operation would block104
43pub const EINPROGRESS = 36; /// Operation now in progress105/// Resource temporarily unavailable
44pub const EALREADY = 37; /// Operation already in progress106pub const EAGAIN = 35;
107
108/// Operation would block
109pub const EWOULDBLOCK = EAGAIN;
110
111/// Operation now in progress
112pub const EINPROGRESS = 36;
113/// Operation already in progress
45114
46// ipc/network software -- argument errors115// ipc/network software -- argument errors
47pub const ENOTSOCK = 38; /// Socket operation on non-socket116pub const EALREADY = 37;
48pub const EDESTADDRREQ = 39; /// Destination address required117
49pub const EMSGSIZE = 40; /// Message too long118/// Socket operation on non-socket
50pub const EPROTOTYPE = 41; /// Protocol wrong type for socket119pub const ENOTSOCK = 38;
51pub const ENOPROTOOPT = 42; /// Protocol not available120
52pub const EPROTONOSUPPORT = 43; /// Protocol not supported121/// Destination address required
122pub const EDESTADDRREQ = 39;
123
124/// Message too long
125pub const EMSGSIZE = 40;
126
127/// Protocol wrong type for socket
128pub const EPROTOTYPE = 41;
129
130/// Protocol not available
131pub const ENOPROTOOPT = 42;
132
133/// Protocol not supported
134pub const EPROTONOSUPPORT = 43;
135
136/// Socket type not supported
137pub const ESOCKTNOSUPPORT = 44;
53138
54pub const ESOCKTNOSUPPORT = 44; /// Socket type not supported139/// Operation not supported
140pub const ENOTSUP = 45;
55141
56pub const ENOTSUP = 45; /// Operation not supported142/// Protocol family not supported
143pub const EPFNOSUPPORT = 46;
57144
58pub const EPFNOSUPPORT = 46; /// Protocol family not supported145/// Address family not supported by protocol family
59pub const EAFNOSUPPORT = 47; /// Address family not supported by protocol family146pub const EAFNOSUPPORT = 47;
60pub const EADDRINUSE = 48; /// Address already in use147
61pub const EADDRNOTAVAIL = 49; /// Can't assign requested address148/// Address already in use
149pub const EADDRINUSE = 48;
150/// Can't assign requested address
62151
63// ipc/network software -- operational errors152// ipc/network software -- operational errors
64pub const ENETDOWN = 50; /// Network is down153pub const EADDRNOTAVAIL = 49;
65pub const ENETUNREACH = 51; /// Network is unreachable154
66pub const ENETRESET = 52; /// Network dropped connection on reset155/// Network is down
67pub const ECONNABORTED = 53; /// Software caused connection abort156pub const ENETDOWN = 50;
68pub const ECONNRESET = 54; /// Connection reset by peer157
69pub const ENOBUFS = 55; /// No buffer space available158/// Network is unreachable
70pub const EISCONN = 56; /// Socket is already connected159pub const ENETUNREACH = 51;
71pub const ENOTCONN = 57; /// Socket is not connected160
161/// Network dropped connection on reset
162pub const ENETRESET = 52;
163
164/// Software caused connection abort
165pub const ECONNABORTED = 53;
166
167/// Connection reset by peer
168pub const ECONNRESET = 54;
169
170/// No buffer space available
171pub const ENOBUFS = 55;
172
173/// Socket is already connected
174pub const EISCONN = 56;
175
176/// Socket is not connected
177pub const ENOTCONN = 57;
178
179/// Can't send after socket shutdown
180pub const ESHUTDOWN = 58;
72181
73pub const ESHUTDOWN = 58; /// Can't send after socket shutdown182/// Too many references: can't splice
74pub const ETOOMANYREFS = 59; /// Too many references: can't splice183pub const ETOOMANYREFS = 59;
75184
76pub const ETIMEDOUT = 60; /// Operation timed out185/// Operation timed out
77pub const ECONNREFUSED = 61; /// Connection refused186pub const ETIMEDOUT = 60;
78187
79pub const ELOOP = 62; /// Too many levels of symbolic links188/// Connection refused
80pub const ENAMETOOLONG = 63; /// File name too long189pub const ECONNREFUSED = 61;
81190
82pub const EHOSTDOWN = 64; /// Host is down191/// Too many levels of symbolic links
83pub const EHOSTUNREACH = 65; /// No route to host192pub const ELOOP = 62;
84pub const ENOTEMPTY = 66; /// Directory not empty193
194/// File name too long
195pub const ENAMETOOLONG = 63;
196
197/// Host is down
198pub const EHOSTDOWN = 64;
199
200/// No route to host
201pub const EHOSTUNREACH = 65;
202/// Directory not empty
85203
86// quotas & mush204// quotas & mush
87pub const EPROCLIM = 67; /// Too many processes205pub const ENOTEMPTY = 66;
88pub const EUSERS = 68; /// Too many users206
89pub const EDQUOT = 69; /// Disc quota exceeded207/// Too many processes
208pub const EPROCLIM = 67;
209
210/// Too many users
211pub const EUSERS = 68;
212/// Disc quota exceeded
90213
91// Network File System214// Network File System
92pub const ESTALE = 70; /// Stale NFS file handle215pub const EDQUOT = 69;
93pub const EREMOTE = 71; /// Too many levels of remote in path216
94pub const EBADRPC = 72; /// RPC struct is bad217/// Stale NFS file handle
95pub const ERPCMISMATCH = 73; /// RPC version wrong218pub const ESTALE = 70;
96pub const EPROGUNAVAIL = 74; /// RPC prog. not avail219
97pub const EPROGMISMATCH = 75; /// Program version wrong220/// Too many levels of remote in path
98pub const EPROCUNAVAIL = 76; /// Bad procedure for program221pub const EREMOTE = 71;
222
223/// RPC struct is bad
224pub const EBADRPC = 72;
225
226/// RPC version wrong
227pub const ERPCMISMATCH = 73;
228
229/// RPC prog. not avail
230pub const EPROGUNAVAIL = 74;
99231
100pub const ENOLCK = 77; /// No locks available232/// Program version wrong
101pub const ENOSYS = 78; /// Function not implemented233pub const EPROGMISMATCH = 75;
102234
103pub const EFTYPE = 79; /// Inappropriate file type or format235/// Bad procedure for program
104pub const EAUTH = 80; /// Authentication error236pub const EPROCUNAVAIL = 76;
105pub const ENEEDAUTH = 81; /// Need authenticator237
238/// No locks available
239pub const ENOLCK = 77;
240
241/// Function not implemented
242pub const ENOSYS = 78;
243
244/// Inappropriate file type or format
245pub const EFTYPE = 79;
246
247/// Authentication error
248pub const EAUTH = 80;
249/// Need authenticator
106250
107// Intelligent device errors251// Intelligent device errors
108pub const EPWROFF = 82; /// Device power is off252pub const ENEEDAUTH = 81;
109pub const EDEVERR = 83; /// Device error, e.g. paper out253
254/// Device power is off
255pub const EPWROFF = 82;
110256
111pub const EOVERFLOW = 84; /// Value too large to be stored in data type257/// Device error, e.g. paper out
258pub const EDEVERR = 83;
259/// Value too large to be stored in data type
112260
113// Program loading errors261// Program loading errors
114pub const EBADEXEC = 85; /// Bad executable262pub const EOVERFLOW = 84;
115pub const EBADARCH = 86; /// Bad CPU type in executable263
116pub const ESHLIBVERS = 87; /// Shared library version mismatch264/// Bad executable
117pub const EBADMACHO = 88; /// Malformed Macho file265pub const EBADEXEC = 85;
266
267/// Bad CPU type in executable
268pub const EBADARCH = 86;
269
270/// Shared library version mismatch
271pub const ESHLIBVERS = 87;
272
273/// Malformed Macho file
274pub const EBADMACHO = 88;
275
276/// Operation canceled
277pub const ECANCELED = 89;
278
279/// Identifier removed
280pub const EIDRM = 90;
281
282/// No message of desired type
283pub const ENOMSG = 91;
284
285/// Illegal byte sequence
286pub const EILSEQ = 92;
287
288/// Attribute not found
289pub const ENOATTR = 93;
290
291/// Bad message
292pub const EBADMSG = 94;
293
294/// Reserved
295pub const EMULTIHOP = 95;
296
297/// No message available on STREAM
298pub const ENODATA = 96;
299
300/// Reserved
301pub const ENOLINK = 97;
302
303/// No STREAM resources
304pub const ENOSR = 98;
305
306/// Not a STREAM
307pub const ENOSTR = 99;
118308
119pub const ECANCELED = 89; /// Operation canceled309/// Protocol error
310pub const EPROTO = 100;
120311
121pub const EIDRM = 90; /// Identifier removed312/// STREAM ioctl timeout
122pub const ENOMSG = 91; /// No message of desired type313pub const ETIME = 101;
123pub const EILSEQ = 92; /// Illegal byte sequence
124pub const ENOATTR = 93; /// Attribute not found
125314
126pub const EBADMSG = 94; /// Bad message315/// No such policy registered
127pub const EMULTIHOP = 95; /// Reserved316pub const ENOPOLICY = 103;
128pub const ENODATA = 96; /// No message available on STREAM
129pub const ENOLINK = 97; /// Reserved
130pub const ENOSR = 98; /// No STREAM resources
131pub const ENOSTR = 99; /// Not a STREAM
132pub const EPROTO = 100; /// Protocol error
133pub const ETIME = 101; /// STREAM ioctl timeout
134317
135pub const ENOPOLICY = 103; /// No such policy registered318/// State not recoverable
319pub const ENOTRECOVERABLE = 104;
136320
137pub const ENOTRECOVERABLE = 104; /// State not recoverable321/// Previous owner died
138pub const EOWNERDEAD = 105; /// Previous owner died322pub const EOWNERDEAD = 105;
139323
140pub const EQFULL = 106; /// Interface output queue is full324/// Interface output queue is full
141pub const ELAST = 106; /// Must be equal largest errno325pub const EQFULL = 106;
142326
327/// Must be equal largest errno
328pub const ELAST = 106;
std/os/epoch.zig+23-23
...@@ -1,26 +1,26 @@...@@ -1,26 +1,26 @@
1/// Epoch reference times in terms of their difference from1/// Epoch reference times in terms of their difference from
2/// posix epoch in seconds.2/// posix epoch in seconds.
3pub const posix = 0; //Jan 01, 1970 AD3pub const posix = 0; //Jan 01, 1970 AD
4pub const dos = 315532800; //Jan 01, 1980 AD4pub const dos = 315532800; //Jan 01, 1980 AD
5pub const ios = 978307200; //Jan 01, 2001 AD5pub const ios = 978307200; //Jan 01, 2001 AD
6pub const openvms = -3506716800; //Nov 17, 1858 AD6pub const openvms = -3506716800; //Nov 17, 1858 AD
7pub const zos = -2208988800; //Jan 01, 1900 AD7pub const zos = -2208988800; //Jan 01, 1900 AD
8pub const windows = -11644473600; //Jan 01, 1601 AD8pub const windows = -11644473600; //Jan 01, 1601 AD
9pub const amiga = 252460800; //Jan 01, 1978 AD9pub const amiga = 252460800; //Jan 01, 1978 AD
10pub const pickos = -63244800; //Dec 31, 1967 AD10pub const pickos = -63244800; //Dec 31, 1967 AD
11pub const gps = 315964800; //Jan 06, 1980 AD11pub const gps = 315964800; //Jan 06, 1980 AD
12pub const clr = -62135769600; //Jan 01, 0001 AD12pub const clr = -62135769600; //Jan 01, 0001 AD
1313
14pub const unix = posix;
15pub const android = posix;
16pub const os2 = dos;
17pub const bios = dos;
18pub const vfat = dos;
19pub const ntfs = windows;
20pub const ntp = zos;
21pub const jbase = pickos;
22pub const aros = amiga;
23pub const morphos = amiga;
24pub const brew = gps;
25pub const atsc = gps;
26pub const go = clr;
\ No newline at end of file
14pub const unix = posix;
15pub const android = posix;
16pub const os2 = dos;
17pub const bios = dos;
18pub const vfat = dos;
19pub const ntfs = windows;
20pub const ntp = zos;
21pub const jbase = pickos;
22pub const aros = amiga;
23pub const morphos = amiga;
24pub const brew = gps;
25pub const atsc = gps;
26pub const go = clr;
std/os/file.zig+52-41
...@@ -19,14 +19,20 @@ pub const File = struct {...@@ -19,14 +19,20 @@ pub const File = struct {
1919
20 /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator.20 /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator.
21 /// Call close to clean up.21 /// Call close to clean up.
22 pub fn openRead(allocator: &mem.Allocator, path: []const u8) OpenError!File {22 pub fn openRead(allocator: *mem.Allocator, path: []const u8) OpenError!File {
23 if (is_posix) {23 if (is_posix) {
24 const flags = posix.O_LARGEFILE|posix.O_RDONLY;24 const flags = posix.O_LARGEFILE | posix.O_RDONLY;
25 const fd = try os.posixOpen(allocator, path, flags, 0);25 const fd = try os.posixOpen(allocator, path, flags, 0);
26 return openHandle(fd);26 return openHandle(fd);
27 } else if (is_windows) {27 } else if (is_windows) {
28 const handle = try os.windowsOpen(allocator, path, windows.GENERIC_READ, windows.FILE_SHARE_READ,28 const handle = try os.windowsOpen(
29 windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL);29 allocator,
30 path,
31 windows.GENERIC_READ,
32 windows.FILE_SHARE_READ,
33 windows.OPEN_EXISTING,
34 windows.FILE_ATTRIBUTE_NORMAL,
35 );
30 return openHandle(handle);36 return openHandle(handle);
31 } else {37 } else {
32 @compileError("TODO implement openRead for this OS");38 @compileError("TODO implement openRead for this OS");
...@@ -34,58 +40,63 @@ pub const File = struct {...@@ -34,58 +40,63 @@ pub const File = struct {
34 }40 }
3541
36 /// Calls `openWriteMode` with os.default_file_mode for the mode.42 /// Calls `openWriteMode` with os.default_file_mode for the mode.
37 pub fn openWrite(allocator: &mem.Allocator, path: []const u8) OpenError!File {43 pub fn openWrite(allocator: *mem.Allocator, path: []const u8) OpenError!File {
38 return openWriteMode(allocator, path, os.default_file_mode);44 return openWriteMode(allocator, path, os.default_file_mode);
39
40 }45 }
4146
42 /// If the path does not exist it will be created.47 /// If the path does not exist it will be created.
43 /// If a file already exists in the destination it will be truncated.48 /// If a file already exists in the destination it will be truncated.
44 /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator.49 /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator.
45 /// Call close to clean up.50 /// Call close to clean up.
46 pub fn openWriteMode(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File {51 pub fn openWriteMode(allocator: *mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File {
47 if (is_posix) {52 if (is_posix) {
48 const flags = posix.O_LARGEFILE|posix.O_WRONLY|posix.O_CREAT|posix.O_CLOEXEC|posix.O_TRUNC;53 const flags = posix.O_LARGEFILE | posix.O_WRONLY | posix.O_CREAT | posix.O_CLOEXEC | posix.O_TRUNC;
49 const fd = try os.posixOpen(allocator, path, flags, file_mode);54 const fd = try os.posixOpen(allocator, path, flags, file_mode);
50 return openHandle(fd);55 return openHandle(fd);
51 } else if (is_windows) {56 } else if (is_windows) {
52 const handle = try os.windowsOpen(allocator, path, windows.GENERIC_WRITE,57 const handle = try os.windowsOpen(
53 windows.FILE_SHARE_WRITE|windows.FILE_SHARE_READ|windows.FILE_SHARE_DELETE,58 allocator,
54 windows.CREATE_ALWAYS, windows.FILE_ATTRIBUTE_NORMAL);59 path,
60 windows.GENERIC_WRITE,
61 windows.FILE_SHARE_WRITE | windows.FILE_SHARE_READ | windows.FILE_SHARE_DELETE,
62 windows.CREATE_ALWAYS,
63 windows.FILE_ATTRIBUTE_NORMAL,
64 );
55 return openHandle(handle);65 return openHandle(handle);
56 } else {66 } else {
57 @compileError("TODO implement openWriteMode for this OS");67 @compileError("TODO implement openWriteMode for this OS");
58 }68 }
59
60 }69 }
6170
62 /// If the path does not exist it will be created.71 /// If the path does not exist it will be created.
63 /// If a file already exists in the destination this returns OpenError.PathAlreadyExists72 /// If a file already exists in the destination this returns OpenError.PathAlreadyExists
64 /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator.73 /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator.
65 /// Call close to clean up.74 /// Call close to clean up.
66 pub fn openWriteNoClobber(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File {75 pub fn openWriteNoClobber(allocator: *mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File {
67 if (is_posix) {76 if (is_posix) {
68 const flags = posix.O_LARGEFILE|posix.O_WRONLY|posix.O_CREAT|posix.O_CLOEXEC|posix.O_EXCL;77 const flags = posix.O_LARGEFILE | posix.O_WRONLY | posix.O_CREAT | posix.O_CLOEXEC | posix.O_EXCL;
69 const fd = try os.posixOpen(allocator, path, flags, file_mode);78 const fd = try os.posixOpen(allocator, path, flags, file_mode);
70 return openHandle(fd);79 return openHandle(fd);
71 } else if (is_windows) {80 } else if (is_windows) {
72 const handle = try os.windowsOpen(allocator, path, windows.GENERIC_WRITE,81 const handle = try os.windowsOpen(
73 windows.FILE_SHARE_WRITE|windows.FILE_SHARE_READ|windows.FILE_SHARE_DELETE,82 allocator,
74 windows.CREATE_NEW, windows.FILE_ATTRIBUTE_NORMAL);83 path,
84 windows.GENERIC_WRITE,
85 windows.FILE_SHARE_WRITE | windows.FILE_SHARE_READ | windows.FILE_SHARE_DELETE,
86 windows.CREATE_NEW,
87 windows.FILE_ATTRIBUTE_NORMAL,
88 );
75 return openHandle(handle);89 return openHandle(handle);
76 } else {90 } else {
77 @compileError("TODO implement openWriteMode for this OS");91 @compileError("TODO implement openWriteMode for this OS");
78 }92 }
79
80 }93 }
8194
82 pub fn openHandle(handle: os.FileHandle) File {95 pub fn openHandle(handle: os.FileHandle) File {
83 return File {96 return File{ .handle = handle };
84 .handle = handle,
85 };
86 }97 }
8798
88 pub fn access(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) !bool {99 pub fn access(allocator: *mem.Allocator, path: []const u8, file_mode: os.FileMode) !bool {
89 const path_with_null = try std.cstr.addNullByte(allocator, path);100 const path_with_null = try std.cstr.addNullByte(allocator, path);
90 defer allocator.free(path_with_null);101 defer allocator.free(path_with_null);
91102
...@@ -129,17 +140,17 @@ pub const File = struct {...@@ -129,17 +140,17 @@ pub const File = struct {
129140
130 /// Upon success, the stream is in an uninitialized state. To continue using it,141 /// Upon success, the stream is in an uninitialized state. To continue using it,
131 /// you must use the open() function.142 /// you must use the open() function.
132 pub fn close(self: &File) void {143 pub fn close(self: *File) void {
133 os.close(self.handle);144 os.close(self.handle);
134 self.handle = undefined;145 self.handle = undefined;
135 }146 }
136147
137 /// Calls `os.isTty` on `self.handle`.148 /// Calls `os.isTty` on `self.handle`.
138 pub fn isTty(self: &File) bool {149 pub fn isTty(self: *File) bool {
139 return os.isTty(self.handle);150 return os.isTty(self.handle);
140 }151 }
141152
142 pub fn seekForward(self: &File, amount: isize) !void {153 pub fn seekForward(self: *File, amount: isize) !void {
143 switch (builtin.os) {154 switch (builtin.os) {
144 Os.linux, Os.macosx, Os.ios => {155 Os.linux, Os.macosx, Os.ios => {
145 const result = posix.lseek(self.handle, amount, posix.SEEK_CUR);156 const result = posix.lseek(self.handle, amount, posix.SEEK_CUR);
...@@ -168,7 +179,7 @@ pub const File = struct {...@@ -168,7 +179,7 @@ pub const File = struct {
168 }179 }
169 }180 }
170181
171 pub fn seekTo(self: &File, pos: usize) !void {182 pub fn seekTo(self: *File, pos: usize) !void {
172 switch (builtin.os) {183 switch (builtin.os) {
173 Os.linux, Os.macosx, Os.ios => {184 Os.linux, Os.macosx, Os.ios => {
174 const ipos = try math.cast(isize, pos);185 const ipos = try math.cast(isize, pos);
...@@ -199,7 +210,7 @@ pub const File = struct {...@@ -199,7 +210,7 @@ pub const File = struct {
199 }210 }
200 }211 }
201212
202 pub fn getPos(self: &File) !usize {213 pub fn getPos(self: *File) !usize {
203 switch (builtin.os) {214 switch (builtin.os) {
204 Os.linux, Os.macosx, Os.ios => {215 Os.linux, Os.macosx, Os.ios => {
205 const result = posix.lseek(self.handle, 0, posix.SEEK_CUR);216 const result = posix.lseek(self.handle, 0, posix.SEEK_CUR);
...@@ -217,8 +228,8 @@ pub const File = struct {...@@ -217,8 +228,8 @@ pub const File = struct {
217 return result;228 return result;
218 },229 },
219 Os.windows => {230 Os.windows => {
220 var pos : windows.LARGE_INTEGER = undefined;231 var pos: windows.LARGE_INTEGER = undefined;
221 if (windows.SetFilePointerEx(self.handle, 0, &pos, windows.FILE_CURRENT) == 0) {232 if (windows.SetFilePointerEx(self.handle, 0, *pos, windows.FILE_CURRENT) == 0) {
222 const err = windows.GetLastError();233 const err = windows.GetLastError();
223 return switch (err) {234 return switch (err) {
224 windows.ERROR.INVALID_PARAMETER => error.BadFd,235 windows.ERROR.INVALID_PARAMETER => error.BadFd,
...@@ -239,7 +250,7 @@ pub const File = struct {...@@ -239,7 +250,7 @@ pub const File = struct {
239 }250 }
240 }251 }
241252
242 pub fn getEndPos(self: &File) !usize {253 pub fn getEndPos(self: *File) !usize {
243 if (is_posix) {254 if (is_posix) {
244 var stat: posix.Stat = undefined;255 var stat: posix.Stat = undefined;
245 const err = posix.getErrno(posix.fstat(self.handle, &stat));256 const err = posix.getErrno(posix.fstat(self.handle, &stat));
...@@ -268,13 +279,13 @@ pub const File = struct {...@@ -268,13 +279,13 @@ pub const File = struct {
268 }279 }
269 }280 }
270281
271 pub const ModeError = error {282 pub const ModeError = error{
272 BadFd,283 BadFd,
273 SystemResources,284 SystemResources,
274 Unexpected,285 Unexpected,
275 };286 };
276287
277 fn mode(self: &File) ModeError!os.FileMode {288 fn mode(self: *File) ModeError!os.FileMode {
278 if (is_posix) {289 if (is_posix) {
279 var stat: posix.Stat = undefined;290 var stat: posix.Stat = undefined;
280 const err = posix.getErrno(posix.fstat(self.handle, &stat));291 const err = posix.getErrno(posix.fstat(self.handle, &stat));
...@@ -296,22 +307,22 @@ pub const File = struct {...@@ -296,22 +307,22 @@ pub const File = struct {
296 }307 }
297 }308 }
298309
299 pub const ReadError = error {};310 pub const ReadError = error{};
300311
301 pub fn read(self: &File, buffer: []u8) !usize {312 pub fn read(self: *File, buffer: []u8) !usize {
302 if (is_posix) {313 if (is_posix) {
303 var index: usize = 0;314 var index: usize = 0;
304 while (index < buffer.len) {315 while (index < buffer.len) {
305 const amt_read = posix.read(self.handle, &buffer[index], buffer.len - index);316 const amt_read = posix.read(self.handle, buffer.ptr + index, buffer.len - index);
306 const read_err = posix.getErrno(amt_read);317 const read_err = posix.getErrno(amt_read);
307 if (read_err > 0) {318 if (read_err > 0) {
308 switch (read_err) {319 switch (read_err) {
309 posix.EINTR => continue,320 posix.EINTR => continue,
310 posix.EINVAL => unreachable,321 posix.EINVAL => unreachable,
311 posix.EFAULT => unreachable,322 posix.EFAULT => unreachable,
312 posix.EBADF => return error.BadFd,323 posix.EBADF => return error.BadFd,
313 posix.EIO => return error.Io,324 posix.EIO => return error.Io,
314 else => return os.unexpectedErrorPosix(read_err),325 else => return os.unexpectedErrorPosix(read_err),
315 }326 }
316 }327 }
317 if (amt_read == 0) return index;328 if (amt_read == 0) return index;
...@@ -323,7 +334,7 @@ pub const File = struct {...@@ -323,7 +334,7 @@ pub const File = struct {
323 while (index < buffer.len) {334 while (index < buffer.len) {
324 const want_read_count = windows.DWORD(math.min(windows.DWORD(@maxValue(windows.DWORD)), buffer.len - index));335 const want_read_count = windows.DWORD(math.min(windows.DWORD(@maxValue(windows.DWORD)), buffer.len - index));
325 var amt_read: windows.DWORD = undefined;336 var amt_read: windows.DWORD = undefined;
326 if (windows.ReadFile(self.handle, @ptrCast(&c_void, &buffer[index]), want_read_count, &amt_read, null) == 0) {337 if (windows.ReadFile(self.handle, @ptrCast([*]c_void, buffer.ptr + index), want_read_count, &amt_read, null) == 0) {
327 const err = windows.GetLastError();338 const err = windows.GetLastError();
328 return switch (err) {339 return switch (err) {
329 windows.ERROR.OPERATION_ABORTED => continue,340 windows.ERROR.OPERATION_ABORTED => continue,
...@@ -342,7 +353,7 @@ pub const File = struct {...@@ -342,7 +353,7 @@ pub const File = struct {
342353
343 pub const WriteError = os.WindowsWriteError || os.PosixWriteError;354 pub const WriteError = os.WindowsWriteError || os.PosixWriteError;
344355
345 fn write(self: &File, bytes: []const u8) WriteError!void {356 fn write(self: *File, bytes: []const u8) WriteError!void {
346 if (is_posix) {357 if (is_posix) {
347 try os.posixWrite(self.handle, bytes);358 try os.posixWrite(self.handle, bytes);
348 } else if (is_windows) {359 } else if (is_windows) {
std/os/get_user_id.zig+7-7
...@@ -74,27 +74,27 @@ pub fn posixGetUserInfo(name: []const u8) !UserInfo {...@@ -74,27 +74,27 @@ pub fn posixGetUserInfo(name: []const u8) !UserInfo {
74 '\n' => return error.CorruptPasswordFile,74 '\n' => return error.CorruptPasswordFile,
75 else => {75 else => {
76 const digit = switch (byte) {76 const digit = switch (byte) {
77 '0' ... '9' => byte - '0',77 '0'...'9' => byte - '0',
78 else => return error.CorruptPasswordFile,78 else => return error.CorruptPasswordFile,
79 };79 };
80 if (@mulWithOverflow(u32, uid, 10, &uid)) return error.CorruptPasswordFile;80 if (@mulWithOverflow(u32, uid, 10, *uid)) return error.CorruptPasswordFile;
81 if (@addWithOverflow(u32, uid, digit, &uid)) return error.CorruptPasswordFile;81 if (@addWithOverflow(u32, uid, digit, *uid)) return error.CorruptPasswordFile;
82 },82 },
83 },83 },
84 State.ReadGroupId => switch (byte) {84 State.ReadGroupId => switch (byte) {
85 '\n', ':' => {85 '\n', ':' => {
86 return UserInfo {86 return UserInfo{
87 .uid = uid,87 .uid = uid,
88 .gid = gid,88 .gid = gid,
89 };89 };
90 },90 },
91 else => {91 else => {
92 const digit = switch (byte) {92 const digit = switch (byte) {
93 '0' ... '9' => byte - '0',93 '0'...'9' => byte - '0',
94 else => return error.CorruptPasswordFile,94 else => return error.CorruptPasswordFile,
95 };95 };
96 if (@mulWithOverflow(u32, gid, 10, &gid)) return error.CorruptPasswordFile;96 if (@mulWithOverflow(u32, gid, 10, *gid)) return error.CorruptPasswordFile;
97 if (@addWithOverflow(u32, gid, digit, &gid)) return error.CorruptPasswordFile;97 if (@addWithOverflow(u32, gid, digit, *gid)) return error.CorruptPasswordFile;
98 },98 },
99 },99 },
100 }100 }
std/os/index.zig+176-253
...@@ -3,8 +3,7 @@ const builtin = @import("builtin");...@@ -3,8 +3,7 @@ const builtin = @import("builtin");
3const Os = builtin.Os;3const Os = builtin.Os;
4const is_windows = builtin.os == Os.windows;4const is_windows = builtin.os == Os.windows;
5const is_posix = switch (builtin.os) {5const is_posix = switch (builtin.os) {
6 builtin.Os.linux,6 builtin.Os.linux, builtin.Os.macosx => true,
7 builtin.Os.macosx => true,
8 else => false,7 else => false,
9};8};
10const os = this;9const os = this;
...@@ -27,8 +26,7 @@ pub const linux = @import("linux/index.zig");...@@ -27,8 +26,7 @@ pub const linux = @import("linux/index.zig");
27pub const zen = @import("zen.zig");26pub const zen = @import("zen.zig");
28pub const posix = switch (builtin.os) {27pub const posix = switch (builtin.os) {
29 Os.linux => linux,28 Os.linux => linux,
30 Os.macosx,29 Os.macosx, Os.ios => darwin,
31 Os.ios => darwin,
32 Os.zen => zen,30 Os.zen => zen,
33 else => @compileError("Unsupported OS"),31 else => @compileError("Unsupported OS"),
34};32};
...@@ -112,8 +110,7 @@ pub fn getRandomBytes(buf: []u8) !void {...@@ -112,8 +110,7 @@ pub fn getRandomBytes(buf: []u8) !void {
112 }110 }
113 return;111 return;
114 },112 },
115 Os.macosx,113 Os.macosx, Os.ios => {
116 Os.ios => {
117 const fd = try posixOpenC(c"/dev/urandom", posix.O_RDONLY | posix.O_CLOEXEC, 0);114 const fd = try posixOpenC(c"/dev/urandom", posix.O_RDONLY | posix.O_CLOEXEC, 0);
118 defer close(fd);115 defer close(fd);
119116
...@@ -137,20 +134,7 @@ pub fn getRandomBytes(buf: []u8) !void {...@@ -137,20 +134,7 @@ pub fn getRandomBytes(buf: []u8) !void {
137 }134 }
138 },135 },
139 Os.zen => {136 Os.zen => {
140 const randomness = []u8{137 const randomness = []u8{ 42, 1, 7, 12, 22, 17, 99, 16, 26, 87, 41, 45 };
141 42,
142 1,
143 7,
144 12,
145 22,
146 17,
147 99,
148 16,
149 26,
150 87,
151 41,
152 45,
153 };
154 var i: usize = 0;138 var i: usize = 0;
155 while (i < buf.len) : (i += 1) {139 while (i < buf.len) : (i += 1) {
156 if (i > randomness.len) return error.Unknown;140 if (i > randomness.len) return error.Unknown;
...@@ -175,9 +159,7 @@ pub fn abort() noreturn {...@@ -175,9 +159,7 @@ pub fn abort() noreturn {
175 c.abort();159 c.abort();
176 }160 }
177 switch (builtin.os) {161 switch (builtin.os) {
178 Os.linux,162 Os.linux, Os.macosx, Os.ios => {
179 Os.macosx,
180 Os.ios => {
181 _ = posix.raise(posix.SIGABRT);163 _ = posix.raise(posix.SIGABRT);
182 _ = posix.raise(posix.SIGKILL);164 _ = posix.raise(posix.SIGKILL);
183 while (true) {}165 while (true) {}
...@@ -199,9 +181,7 @@ pub fn exit(status: u8) noreturn {...@@ -199,9 +181,7 @@ pub fn exit(status: u8) noreturn {
199 c.exit(status);181 c.exit(status);
200 }182 }
201 switch (builtin.os) {183 switch (builtin.os) {
202 Os.linux,184 Os.linux, Os.macosx, Os.ios => {
203 Os.macosx,
204 Os.ios => {
205 posix.exit(status);185 posix.exit(status);
206 },186 },
207 Os.windows => {187 Os.windows => {
...@@ -245,19 +225,17 @@ pub fn posixRead(fd: i32, buf: []u8) !void {...@@ -245,19 +225,17 @@ pub fn posixRead(fd: i32, buf: []u8) !void {
245 var index: usize = 0;225 var index: usize = 0;
246 while (index < buf.len) {226 while (index < buf.len) {
247 const want_to_read = math.min(buf.len - index, usize(max_buf_len));227 const want_to_read = math.min(buf.len - index, usize(max_buf_len));
248 const rc = posix.read(fd, &buf[index], want_to_read);228 const rc = posix.read(fd, buf.ptr + index, want_to_read);
249 const err = posix.getErrno(rc);229 const err = posix.getErrno(rc);
250 if (err > 0) {230 if (err > 0) {
251 return switch (err) {231 return switch (err) {
252 posix.EINTR => continue,232 posix.EINTR => continue,
253 posix.EINVAL,233 posix.EINVAL, posix.EFAULT => unreachable,
254 posix.EFAULT => unreachable,
255 posix.EAGAIN => error.WouldBlock,234 posix.EAGAIN => error.WouldBlock,
256 posix.EBADF => error.FileClosed,235 posix.EBADF => error.FileClosed,
257 posix.EIO => error.InputOutput,236 posix.EIO => error.InputOutput,
258 posix.EISDIR => error.IsDir,237 posix.EISDIR => error.IsDir,
259 posix.ENOBUFS,238 posix.ENOBUFS, posix.ENOMEM => error.SystemResources,
260 posix.ENOMEM => error.SystemResources,
261 else => unexpectedErrorPosix(err),239 else => unexpectedErrorPosix(err),
262 };240 };
263 }241 }
...@@ -287,13 +265,12 @@ pub fn posixWrite(fd: i32, bytes: []const u8) !void {...@@ -287,13 +265,12 @@ pub fn posixWrite(fd: i32, bytes: []const u8) !void {
287 var index: usize = 0;265 var index: usize = 0;
288 while (index < bytes.len) {266 while (index < bytes.len) {
289 const amt_to_write = math.min(bytes.len - index, usize(max_bytes_len));267 const amt_to_write = math.min(bytes.len - index, usize(max_bytes_len));
290 const rc = posix.write(fd, &bytes[index], amt_to_write);268 const rc = posix.write(fd, bytes.ptr + index, amt_to_write);
291 const write_err = posix.getErrno(rc);269 const write_err = posix.getErrno(rc);
292 if (write_err > 0) {270 if (write_err > 0) {
293 return switch (write_err) {271 return switch (write_err) {
294 posix.EINTR => continue,272 posix.EINTR => continue,
295 posix.EINVAL,273 posix.EINVAL, posix.EFAULT => unreachable,
296 posix.EFAULT => unreachable,
297 posix.EAGAIN => PosixWriteError.WouldBlock,274 posix.EAGAIN => PosixWriteError.WouldBlock,
298 posix.EBADF => PosixWriteError.FileClosed,275 posix.EBADF => PosixWriteError.FileClosed,
299 posix.EDESTADDRREQ => PosixWriteError.DestinationAddressRequired,276 posix.EDESTADDRREQ => PosixWriteError.DestinationAddressRequired,
...@@ -331,14 +308,15 @@ pub const PosixOpenError = error{...@@ -331,14 +308,15 @@ pub const PosixOpenError = error{
331/// ::file_path needs to be copied in memory to add a null terminating byte.308/// ::file_path needs to be copied in memory to add a null terminating byte.
332/// Calls POSIX open, keeps trying if it gets interrupted, and translates309/// Calls POSIX open, keeps trying if it gets interrupted, and translates
333/// the return value into zig errors.310/// the return value into zig errors.
334pub fn posixOpen(allocator: &Allocator, file_path: []const u8, flags: u32, perm: usize) PosixOpenError!i32 {311pub fn posixOpen(allocator: *Allocator, file_path: []const u8, flags: u32, perm: usize) PosixOpenError!i32 {
335 const path_with_null = try cstr.addNullByte(allocator, file_path);312 const path_with_null = try cstr.addNullByte(allocator, file_path);
336 defer allocator.free(path_with_null);313 defer allocator.free(path_with_null);
337314
338 return posixOpenC(path_with_null.ptr, flags, perm);315 return posixOpenC(path_with_null.ptr, flags, perm);
339}316}
340317
341pub fn posixOpenC(file_path: &const u8, flags: u32, perm: usize) !i32 {318// TODO https://github.com/ziglang/zig/issues/265
319pub fn posixOpenC(file_path: [*]const u8, flags: u32, perm: usize) !i32 {
342 while (true) {320 while (true) {
343 const result = posix.open(file_path, flags, perm);321 const result = posix.open(file_path, flags, perm);
344 const err = posix.getErrno(result);322 const err = posix.getErrno(result);
...@@ -349,8 +327,7 @@ pub fn posixOpenC(file_path: &const u8, flags: u32, perm: usize) !i32 {...@@ -349,8 +327,7 @@ pub fn posixOpenC(file_path: &const u8, flags: u32, perm: usize) !i32 {
349 posix.EFAULT => unreachable,327 posix.EFAULT => unreachable,
350 posix.EINVAL => unreachable,328 posix.EINVAL => unreachable,
351 posix.EACCES => return PosixOpenError.AccessDenied,329 posix.EACCES => return PosixOpenError.AccessDenied,
352 posix.EFBIG,330 posix.EFBIG, posix.EOVERFLOW => return PosixOpenError.FileTooBig,
353 posix.EOVERFLOW => return PosixOpenError.FileTooBig,
354 posix.EISDIR => return PosixOpenError.IsDir,331 posix.EISDIR => return PosixOpenError.IsDir,
355 posix.ELOOP => return PosixOpenError.SymLinkLoop,332 posix.ELOOP => return PosixOpenError.SymLinkLoop,
356 posix.EMFILE => return PosixOpenError.ProcessFdQuotaExceeded,333 posix.EMFILE => return PosixOpenError.ProcessFdQuotaExceeded,
...@@ -375,8 +352,7 @@ pub fn posixDup2(old_fd: i32, new_fd: i32) !void {...@@ -375,8 +352,7 @@ pub fn posixDup2(old_fd: i32, new_fd: i32) !void {
375 const err = posix.getErrno(posix.dup2(old_fd, new_fd));352 const err = posix.getErrno(posix.dup2(old_fd, new_fd));
376 if (err > 0) {353 if (err > 0) {
377 return switch (err) {354 return switch (err) {
378 posix.EBUSY,355 posix.EBUSY, posix.EINTR => continue,
379 posix.EINTR => continue,
380 posix.EMFILE => error.ProcessFdQuotaExceeded,356 posix.EMFILE => error.ProcessFdQuotaExceeded,
381 posix.EINVAL => unreachable,357 posix.EINVAL => unreachable,
382 else => unexpectedErrorPosix(err),358 else => unexpectedErrorPosix(err),
...@@ -386,19 +362,19 @@ pub fn posixDup2(old_fd: i32, new_fd: i32) !void {...@@ -386,19 +362,19 @@ pub fn posixDup2(old_fd: i32, new_fd: i32) !void {
386 }362 }
387}363}
388364
389pub fn createNullDelimitedEnvMap(allocator: &Allocator, env_map: &const BufMap) ![]?&u8 {365pub fn createNullDelimitedEnvMap(allocator: *Allocator, env_map: *const BufMap) ![]?[*]u8 {
390 const envp_count = env_map.count();366 const envp_count = env_map.count();
391 const envp_buf = try allocator.alloc(?&u8, envp_count + 1);367 const envp_buf = try allocator.alloc(?[*]u8, envp_count + 1);
392 mem.set(?&u8, envp_buf, null);368 mem.set(?[*]u8, envp_buf, null);
393 errdefer freeNullDelimitedEnvMap(allocator, envp_buf);369 errdefer freeNullDelimitedEnvMap(allocator, envp_buf);
394 {370 {
395 var it = env_map.iterator();371 var it = env_map.iterator();
396 var i: usize = 0;372 var i: usize = 0;
397 while (it.next()) |pair| : (i += 1) {373 while (it.next()) |pair| : (i += 1) {
398 const env_buf = try allocator.alloc(u8, pair.key.len + pair.value.len + 2);374 const env_buf = try allocator.alloc(u8, pair.key.len + pair.value.len + 2);
399 @memcpy(&env_buf[0], pair.key.ptr, pair.key.len);375 @memcpy(env_buf.ptr, pair.key.ptr, pair.key.len);
400 env_buf[pair.key.len] = '=';376 env_buf[pair.key.len] = '=';
401 @memcpy(&env_buf[pair.key.len + 1], pair.value.ptr, pair.value.len);377 @memcpy(env_buf.ptr + pair.key.len + 1, pair.value.ptr, pair.value.len);
402 env_buf[env_buf.len - 1] = 0;378 env_buf[env_buf.len - 1] = 0;
403379
404 envp_buf[i] = env_buf.ptr;380 envp_buf[i] = env_buf.ptr;
...@@ -409,9 +385,9 @@ pub fn createNullDelimitedEnvMap(allocator: &Allocator, env_map: &const BufMap)...@@ -409,9 +385,9 @@ pub fn createNullDelimitedEnvMap(allocator: &Allocator, env_map: &const BufMap)
409 return envp_buf;385 return envp_buf;
410}386}
411387
412pub fn freeNullDelimitedEnvMap(allocator: &Allocator, envp_buf: []?&u8) void {388pub fn freeNullDelimitedEnvMap(allocator: *Allocator, envp_buf: []?[*]u8) void {
413 for (envp_buf) |env| {389 for (envp_buf) |env| {
414 const env_buf = if (env) |ptr| ptr[0..cstr.len(ptr) + 1] else break;390 const env_buf = if (env) |ptr| ptr[0 .. cstr.len(ptr) + 1] else break;
415 allocator.free(env_buf);391 allocator.free(env_buf);
416 }392 }
417 allocator.free(envp_buf);393 allocator.free(envp_buf);
...@@ -422,9 +398,9 @@ pub fn freeNullDelimitedEnvMap(allocator: &Allocator, envp_buf: []?&u8) void {...@@ -422,9 +398,9 @@ pub fn freeNullDelimitedEnvMap(allocator: &Allocator, envp_buf: []?&u8) void {
422/// pointers after the args and after the environment variables.398/// pointers after the args and after the environment variables.
423/// `argv[0]` is the executable path.399/// `argv[0]` is the executable path.
424/// This function also uses the PATH environment variable to get the full path to the executable.400/// This function also uses the PATH environment variable to get the full path to the executable.
425pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap, allocator: &Allocator) !void {401pub fn posixExecve(argv: []const []const u8, env_map: *const BufMap, allocator: *Allocator) !void {
426 const argv_buf = try allocator.alloc(?&u8, argv.len + 1);402 const argv_buf = try allocator.alloc(?[*]u8, argv.len + 1);
427 mem.set(?&u8, argv_buf, null);403 mem.set(?[*]u8, argv_buf, null);
428 defer {404 defer {
429 for (argv_buf) |arg| {405 for (argv_buf) |arg| {
430 const arg_buf = if (arg) |ptr| cstr.toSlice(ptr) else break;406 const arg_buf = if (arg) |ptr| cstr.toSlice(ptr) else break;
...@@ -434,7 +410,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap, allocator:...@@ -434,7 +410,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap, allocator:
434 }410 }
435 for (argv) |arg, i| {411 for (argv) |arg, i| {
436 const arg_buf = try allocator.alloc(u8, arg.len + 1);412 const arg_buf = try allocator.alloc(u8, arg.len + 1);
437 @memcpy(&arg_buf[0], arg.ptr, arg.len);413 @memcpy(arg_buf.ptr, arg.ptr, arg.len);
438 arg_buf[arg.len] = 0;414 arg_buf[arg.len] = 0;
439415
440 argv_buf[i] = arg_buf.ptr;416 argv_buf[i] = arg_buf.ptr;
...@@ -461,7 +437,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap, allocator:...@@ -461,7 +437,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap, allocator:
461 while (it.next()) |search_path| {437 while (it.next()) |search_path| {
462 mem.copy(u8, path_buf, search_path);438 mem.copy(u8, path_buf, search_path);
463 path_buf[search_path.len] = '/';439 path_buf[search_path.len] = '/';
464 mem.copy(u8, path_buf[search_path.len + 1..], exe_path);440 mem.copy(u8, path_buf[search_path.len + 1 ..], exe_path);
465 path_buf[search_path.len + exe_path.len + 1] = 0;441 path_buf[search_path.len + exe_path.len + 1] = 0;
466 err = posix.getErrno(posix.execve(path_buf.ptr, argv_buf.ptr, envp_buf.ptr));442 err = posix.getErrno(posix.execve(path_buf.ptr, argv_buf.ptr, envp_buf.ptr));
467 assert(err > 0);443 assert(err > 0);
...@@ -493,17 +469,10 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError {...@@ -493,17 +469,10 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError {
493 assert(err > 0);469 assert(err > 0);
494 return switch (err) {470 return switch (err) {
495 posix.EFAULT => unreachable,471 posix.EFAULT => unreachable,
496 posix.E2BIG,472 posix.E2BIG, posix.EMFILE, posix.ENAMETOOLONG, posix.ENFILE, posix.ENOMEM => error.SystemResources,
497 posix.EMFILE,473 posix.EACCES, posix.EPERM => error.AccessDenied,
498 posix.ENAMETOOLONG,474 posix.EINVAL, posix.ENOEXEC => error.InvalidExe,
499 posix.ENFILE,475 posix.EIO, posix.ELOOP => error.FileSystem,
500 posix.ENOMEM => error.SystemResources,
501 posix.EACCES,
502 posix.EPERM => error.AccessDenied,
503 posix.EINVAL,
504 posix.ENOEXEC => error.InvalidExe,
505 posix.EIO,
506 posix.ELOOP => error.FileSystem,
507 posix.EISDIR => error.IsDir,476 posix.EISDIR => error.IsDir,
508 posix.ENOENT => error.FileNotFound,477 posix.ENOENT => error.FileNotFound,
509 posix.ENOTDIR => error.NotDir,478 posix.ENOTDIR => error.NotDir,
...@@ -513,10 +482,10 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError {...@@ -513,10 +482,10 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError {
513}482}
514483
515pub var linux_aux_raw = []usize{0} ** 38;484pub var linux_aux_raw = []usize{0} ** 38;
516pub var posix_environ_raw: []&u8 = undefined;485pub var posix_environ_raw: [][*]u8 = undefined;
517486
518/// Caller must free result when done.487/// Caller must free result when done.
519pub fn getEnvMap(allocator: &Allocator) !BufMap {488pub fn getEnvMap(allocator: *Allocator) !BufMap {
520 var result = BufMap.init(allocator);489 var result = BufMap.init(allocator);
521 errdefer result.deinit();490 errdefer result.deinit();
522491
...@@ -551,7 +520,7 @@ pub fn getEnvMap(allocator: &Allocator) !BufMap {...@@ -551,7 +520,7 @@ pub fn getEnvMap(allocator: &Allocator) !BufMap {
551520
552 var end_i: usize = line_i;521 var end_i: usize = line_i;
553 while (ptr[end_i] != 0) : (end_i += 1) {}522 while (ptr[end_i] != 0) : (end_i += 1) {}
554 const value = ptr[line_i + 1..end_i];523 const value = ptr[line_i + 1 .. end_i];
555524
556 try result.set(key, value);525 try result.set(key, value);
557 }526 }
...@@ -568,7 +537,7 @@ pub fn getEnvPosix(key: []const u8) ?[]const u8 {...@@ -568,7 +537,7 @@ pub fn getEnvPosix(key: []const u8) ?[]const u8 {
568537
569 var end_i: usize = line_i;538 var end_i: usize = line_i;
570 while (ptr[end_i] != 0) : (end_i += 1) {}539 while (ptr[end_i] != 0) : (end_i += 1) {}
571 const this_value = ptr[line_i + 1..end_i];540 const this_value = ptr[line_i + 1 .. end_i];
572541
573 return this_value;542 return this_value;
574 }543 }
...@@ -576,7 +545,7 @@ pub fn getEnvPosix(key: []const u8) ?[]const u8 {...@@ -576,7 +545,7 @@ pub fn getEnvPosix(key: []const u8) ?[]const u8 {
576}545}
577546
578/// Caller must free returned memory.547/// Caller must free returned memory.
579pub fn getEnvVarOwned(allocator: &mem.Allocator, key: []const u8) ![]u8 {548pub fn getEnvVarOwned(allocator: *mem.Allocator, key: []const u8) ![]u8 {
580 if (is_windows) {549 if (is_windows) {
581 const key_with_null = try cstr.addNullByte(allocator, key);550 const key_with_null = try cstr.addNullByte(allocator, key);
582 defer allocator.free(key_with_null);551 defer allocator.free(key_with_null);
...@@ -610,7 +579,7 @@ pub fn getEnvVarOwned(allocator: &mem.Allocator, key: []const u8) ![]u8 {...@@ -610,7 +579,7 @@ pub fn getEnvVarOwned(allocator: &mem.Allocator, key: []const u8) ![]u8 {
610}579}
611580
612/// Caller must free the returned memory.581/// Caller must free the returned memory.
613pub fn getCwd(allocator: &Allocator) ![]u8 {582pub fn getCwd(allocator: *Allocator) ![]u8 {
614 switch (builtin.os) {583 switch (builtin.os) {
615 Os.windows => {584 Os.windows => {
616 var buf = try allocator.alloc(u8, 256);585 var buf = try allocator.alloc(u8, 256);
...@@ -659,7 +628,7 @@ test "os.getCwd" {...@@ -659,7 +628,7 @@ test "os.getCwd" {
659628
660pub const SymLinkError = PosixSymLinkError || WindowsSymLinkError;629pub const SymLinkError = PosixSymLinkError || WindowsSymLinkError;
661630
662pub fn symLink(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) SymLinkError!void {631pub fn symLink(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) SymLinkError!void {
663 if (is_windows) {632 if (is_windows) {
664 return symLinkWindows(allocator, existing_path, new_path);633 return symLinkWindows(allocator, existing_path, new_path);
665 } else {634 } else {
...@@ -672,7 +641,7 @@ pub const WindowsSymLinkError = error{...@@ -672,7 +641,7 @@ pub const WindowsSymLinkError = error{
672 Unexpected,641 Unexpected,
673};642};
674643
675pub fn symLinkWindows(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) WindowsSymLinkError!void {644pub fn symLinkWindows(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) WindowsSymLinkError!void {
676 const existing_with_null = try cstr.addNullByte(allocator, existing_path);645 const existing_with_null = try cstr.addNullByte(allocator, existing_path);
677 defer allocator.free(existing_with_null);646 defer allocator.free(existing_with_null);
678 const new_with_null = try cstr.addNullByte(allocator, new_path);647 const new_with_null = try cstr.addNullByte(allocator, new_path);
...@@ -702,7 +671,7 @@ pub const PosixSymLinkError = error{...@@ -702,7 +671,7 @@ pub const PosixSymLinkError = error{
702 Unexpected,671 Unexpected,
703};672};
704673
705pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) PosixSymLinkError!void {674pub fn symLinkPosix(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) PosixSymLinkError!void {
706 const full_buf = try allocator.alloc(u8, existing_path.len + new_path.len + 2);675 const full_buf = try allocator.alloc(u8, existing_path.len + new_path.len + 2);
707 defer allocator.free(full_buf);676 defer allocator.free(full_buf);
708677
...@@ -710,17 +679,15 @@ pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path:...@@ -710,17 +679,15 @@ pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path:
710 mem.copy(u8, existing_buf, existing_path);679 mem.copy(u8, existing_buf, existing_path);
711 existing_buf[existing_path.len] = 0;680 existing_buf[existing_path.len] = 0;
712681
713 const new_buf = full_buf[existing_path.len + 1..];682 const new_buf = full_buf[existing_path.len + 1 ..];
714 mem.copy(u8, new_buf, new_path);683 mem.copy(u8, new_buf, new_path);
715 new_buf[new_path.len] = 0;684 new_buf[new_path.len] = 0;
716685
717 const err = posix.getErrno(posix.symlink(existing_buf.ptr, new_buf.ptr));686 const err = posix.getErrno(posix.symlink(existing_buf.ptr, new_buf.ptr));
718 if (err > 0) {687 if (err > 0) {
719 return switch (err) {688 return switch (err) {
720 posix.EFAULT,689 posix.EFAULT, posix.EINVAL => unreachable,
721 posix.EINVAL => unreachable,690 posix.EACCES, posix.EPERM => error.AccessDenied,
722 posix.EACCES,
723 posix.EPERM => error.AccessDenied,
724 posix.EDQUOT => error.DiskQuota,691 posix.EDQUOT => error.DiskQuota,
725 posix.EEXIST => error.PathAlreadyExists,692 posix.EEXIST => error.PathAlreadyExists,
726 posix.EIO => error.FileSystem,693 posix.EIO => error.FileSystem,
...@@ -739,7 +706,7 @@ pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path:...@@ -739,7 +706,7 @@ pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path:
739// here we replace the standard +/ with -_ so that it can be used in a file name706// here we replace the standard +/ with -_ so that it can be used in a file name
740const b64_fs_encoder = base64.Base64Encoder.init("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", base64.standard_pad_char);707const b64_fs_encoder = base64.Base64Encoder.init("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", base64.standard_pad_char);
741708
742pub fn atomicSymLink(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) !void {709pub fn atomicSymLink(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) !void {
743 if (symLink(allocator, existing_path, new_path)) {710 if (symLink(allocator, existing_path, new_path)) {
744 return;711 return;
745 } else |err| switch (err) {712 } else |err| switch (err) {
...@@ -756,7 +723,7 @@ pub fn atomicSymLink(allocator: &Allocator, existing_path: []const u8, new_path:...@@ -756,7 +723,7 @@ pub fn atomicSymLink(allocator: &Allocator, existing_path: []const u8, new_path:
756 tmp_path[dirname.len] = os.path.sep;723 tmp_path[dirname.len] = os.path.sep;
757 while (true) {724 while (true) {
758 try getRandomBytes(rand_buf[0..]);725 try getRandomBytes(rand_buf[0..]);
759 b64_fs_encoder.encode(tmp_path[dirname.len + 1..], rand_buf);726 b64_fs_encoder.encode(tmp_path[dirname.len + 1 ..], rand_buf);
760727
761 if (symLink(allocator, existing_path, tmp_path)) {728 if (symLink(allocator, existing_path, tmp_path)) {
762 return rename(allocator, tmp_path, new_path);729 return rename(allocator, tmp_path, new_path);
...@@ -767,7 +734,7 @@ pub fn atomicSymLink(allocator: &Allocator, existing_path: []const u8, new_path:...@@ -767,7 +734,7 @@ pub fn atomicSymLink(allocator: &Allocator, existing_path: []const u8, new_path:
767 }734 }
768}735}
769736
770pub fn deleteFile(allocator: &Allocator, file_path: []const u8) !void {737pub fn deleteFile(allocator: *Allocator, file_path: []const u8) !void {
771 if (builtin.os == Os.windows) {738 if (builtin.os == Os.windows) {
772 return deleteFileWindows(allocator, file_path);739 return deleteFileWindows(allocator, file_path);
773 } else {740 } else {
...@@ -775,7 +742,7 @@ pub fn deleteFile(allocator: &Allocator, file_path: []const u8) !void {...@@ -775,7 +742,7 @@ pub fn deleteFile(allocator: &Allocator, file_path: []const u8) !void {
775 }742 }
776}743}
777744
778pub fn deleteFileWindows(allocator: &Allocator, file_path: []const u8) !void {745pub fn deleteFileWindows(allocator: *Allocator, file_path: []const u8) !void {
779 const buf = try allocator.alloc(u8, file_path.len + 1);746 const buf = try allocator.alloc(u8, file_path.len + 1);
780 defer allocator.free(buf);747 defer allocator.free(buf);
781748
...@@ -787,14 +754,13 @@ pub fn deleteFileWindows(allocator: &Allocator, file_path: []const u8) !void {...@@ -787,14 +754,13 @@ pub fn deleteFileWindows(allocator: &Allocator, file_path: []const u8) !void {
787 return switch (err) {754 return switch (err) {
788 windows.ERROR.FILE_NOT_FOUND => error.FileNotFound,755 windows.ERROR.FILE_NOT_FOUND => error.FileNotFound,
789 windows.ERROR.ACCESS_DENIED => error.AccessDenied,756 windows.ERROR.ACCESS_DENIED => error.AccessDenied,
790 windows.ERROR.FILENAME_EXCED_RANGE,757 windows.ERROR.FILENAME_EXCED_RANGE, windows.ERROR.INVALID_PARAMETER => error.NameTooLong,
791 windows.ERROR.INVALID_PARAMETER => error.NameTooLong,
792 else => unexpectedErrorWindows(err),758 else => unexpectedErrorWindows(err),
793 };759 };
794 }760 }
795}761}
796762
797pub fn deleteFilePosix(allocator: &Allocator, file_path: []const u8) !void {763pub fn deleteFilePosix(allocator: *Allocator, file_path: []const u8) !void {
798 const buf = try allocator.alloc(u8, file_path.len + 1);764 const buf = try allocator.alloc(u8, file_path.len + 1);
799 defer allocator.free(buf);765 defer allocator.free(buf);
800766
...@@ -804,11 +770,9 @@ pub fn deleteFilePosix(allocator: &Allocator, file_path: []const u8) !void {...@@ -804,11 +770,9 @@ pub fn deleteFilePosix(allocator: &Allocator, file_path: []const u8) !void {
804 const err = posix.getErrno(posix.unlink(buf.ptr));770 const err = posix.getErrno(posix.unlink(buf.ptr));
805 if (err > 0) {771 if (err > 0) {
806 return switch (err) {772 return switch (err) {
807 posix.EACCES,773 posix.EACCES, posix.EPERM => error.AccessDenied,
808 posix.EPERM => error.AccessDenied,
809 posix.EBUSY => error.FileBusy,774 posix.EBUSY => error.FileBusy,
810 posix.EFAULT,775 posix.EFAULT, posix.EINVAL => unreachable,
811 posix.EINVAL => unreachable,
812 posix.EIO => error.FileSystem,776 posix.EIO => error.FileSystem,
813 posix.EISDIR => error.IsDir,777 posix.EISDIR => error.IsDir,
814 posix.ELOOP => error.SymLinkLoop,778 posix.ELOOP => error.SymLinkLoop,
...@@ -827,7 +791,7 @@ pub fn deleteFilePosix(allocator: &Allocator, file_path: []const u8) !void {...@@ -827,7 +791,7 @@ pub fn deleteFilePosix(allocator: &Allocator, file_path: []const u8) !void {
827/// there is a possibility of power loss or application termination leaving temporary files present791/// there is a possibility of power loss or application termination leaving temporary files present
828/// in the same directory as dest_path.792/// in the same directory as dest_path.
829/// Destination file will have the same mode as the source file.793/// Destination file will have the same mode as the source file.
830pub fn copyFile(allocator: &Allocator, source_path: []const u8, dest_path: []const u8) !void {794pub fn copyFile(allocator: *Allocator, source_path: []const u8, dest_path: []const u8) !void {
831 var in_file = try os.File.openRead(allocator, source_path);795 var in_file = try os.File.openRead(allocator, source_path);
832 defer in_file.close();796 defer in_file.close();
833797
...@@ -849,7 +813,7 @@ pub fn copyFile(allocator: &Allocator, source_path: []const u8, dest_path: []con...@@ -849,7 +813,7 @@ pub fn copyFile(allocator: &Allocator, source_path: []const u8, dest_path: []con
849/// Guaranteed to be atomic. However until https://patchwork.kernel.org/patch/9636735/ is813/// Guaranteed to be atomic. However until https://patchwork.kernel.org/patch/9636735/ is
850/// merged and readily available,814/// merged and readily available,
851/// there is a possibility of power loss or application termination leaving temporary files present815/// there is a possibility of power loss or application termination leaving temporary files present
852pub fn copyFileMode(allocator: &Allocator, source_path: []const u8, dest_path: []const u8, mode: FileMode) !void {816pub fn copyFileMode(allocator: *Allocator, source_path: []const u8, dest_path: []const u8, mode: FileMode) !void {
853 var in_file = try os.File.openRead(allocator, source_path);817 var in_file = try os.File.openRead(allocator, source_path);
854 defer in_file.close();818 defer in_file.close();
855819
...@@ -867,7 +831,7 @@ pub fn copyFileMode(allocator: &Allocator, source_path: []const u8, dest_path: [...@@ -867,7 +831,7 @@ pub fn copyFileMode(allocator: &Allocator, source_path: []const u8, dest_path: [
867}831}
868832
869pub const AtomicFile = struct {833pub const AtomicFile = struct {
870 allocator: &Allocator,834 allocator: *Allocator,
871 file: os.File,835 file: os.File,
872 tmp_path: []u8,836 tmp_path: []u8,
873 dest_path: []const u8,837 dest_path: []const u8,
...@@ -875,18 +839,24 @@ pub const AtomicFile = struct {...@@ -875,18 +839,24 @@ pub const AtomicFile = struct {
875839
876 /// dest_path must remain valid for the lifetime of AtomicFile840 /// dest_path must remain valid for the lifetime of AtomicFile
877 /// call finish to atomically replace dest_path with contents841 /// call finish to atomically replace dest_path with contents
878 pub fn init(allocator: &Allocator, dest_path: []const u8, mode: FileMode) !AtomicFile {842 pub fn init(allocator: *Allocator, dest_path: []const u8, mode: FileMode) !AtomicFile {
879 const dirname = os.path.dirname(dest_path);843 const dirname = os.path.dirname(dest_path);
880844
881 var rand_buf: [12]u8 = undefined;845 var rand_buf: [12]u8 = undefined;
882 const tmp_path = try allocator.alloc(u8, dirname.len + 1 + base64.Base64Encoder.calcSize(rand_buf.len));846
847 const dirname_component_len = if (dirname.len == 0) 0 else dirname.len + 1;
848 const tmp_path = try allocator.alloc(u8, dirname_component_len +
849 base64.Base64Encoder.calcSize(rand_buf.len));
883 errdefer allocator.free(tmp_path);850 errdefer allocator.free(tmp_path);
884 mem.copy(u8, tmp_path[0..], dirname);851
885 tmp_path[dirname.len] = os.path.sep;852 if (dirname.len != 0) {
853 mem.copy(u8, tmp_path[0..], dirname);
854 tmp_path[dirname.len] = os.path.sep;
855 }
886856
887 while (true) {857 while (true) {
888 try getRandomBytes(rand_buf[0..]);858 try getRandomBytes(rand_buf[0..]);
889 b64_fs_encoder.encode(tmp_path[dirname.len + 1..], rand_buf);859 b64_fs_encoder.encode(tmp_path[dirname_component_len..], rand_buf);
890860
891 const file = os.File.openWriteNoClobber(allocator, tmp_path, mode) catch |err| switch (err) {861 const file = os.File.openWriteNoClobber(allocator, tmp_path, mode) catch |err| switch (err) {
892 error.PathAlreadyExists => continue,862 error.PathAlreadyExists => continue,
...@@ -906,7 +876,7 @@ pub const AtomicFile = struct {...@@ -906,7 +876,7 @@ pub const AtomicFile = struct {
906 }876 }
907877
908 /// always call deinit, even after successful finish()878 /// always call deinit, even after successful finish()
909 pub fn deinit(self: &AtomicFile) void {879 pub fn deinit(self: *AtomicFile) void {
910 if (!self.finished) {880 if (!self.finished) {
911 self.file.close();881 self.file.close();
912 deleteFile(self.allocator, self.tmp_path) catch {};882 deleteFile(self.allocator, self.tmp_path) catch {};
...@@ -915,7 +885,7 @@ pub const AtomicFile = struct {...@@ -915,7 +885,7 @@ pub const AtomicFile = struct {
915 }885 }
916 }886 }
917887
918 pub fn finish(self: &AtomicFile) !void {888 pub fn finish(self: *AtomicFile) !void {
919 assert(!self.finished);889 assert(!self.finished);
920 self.file.close();890 self.file.close();
921 try rename(self.allocator, self.tmp_path, self.dest_path);891 try rename(self.allocator, self.tmp_path, self.dest_path);
...@@ -924,7 +894,7 @@ pub const AtomicFile = struct {...@@ -924,7 +894,7 @@ pub const AtomicFile = struct {
924 }894 }
925};895};
926896
927pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8) !void {897pub fn rename(allocator: *Allocator, old_path: []const u8, new_path: []const u8) !void {
928 const full_buf = try allocator.alloc(u8, old_path.len + new_path.len + 2);898 const full_buf = try allocator.alloc(u8, old_path.len + new_path.len + 2);
929 defer allocator.free(full_buf);899 defer allocator.free(full_buf);
930900
...@@ -932,7 +902,7 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8)...@@ -932,7 +902,7 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8)
932 mem.copy(u8, old_buf, old_path);902 mem.copy(u8, old_buf, old_path);
933 old_buf[old_path.len] = 0;903 old_buf[old_path.len] = 0;
934904
935 const new_buf = full_buf[old_path.len + 1..];905 const new_buf = full_buf[old_path.len + 1 ..];
936 mem.copy(u8, new_buf, new_path);906 mem.copy(u8, new_buf, new_path);
937 new_buf[new_path.len] = 0;907 new_buf[new_path.len] = 0;
938908
...@@ -948,12 +918,10 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8)...@@ -948,12 +918,10 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8)
948 const err = posix.getErrno(posix.rename(old_buf.ptr, new_buf.ptr));918 const err = posix.getErrno(posix.rename(old_buf.ptr, new_buf.ptr));
949 if (err > 0) {919 if (err > 0) {
950 return switch (err) {920 return switch (err) {
951 posix.EACCES,921 posix.EACCES, posix.EPERM => error.AccessDenied,
952 posix.EPERM => error.AccessDenied,
953 posix.EBUSY => error.FileBusy,922 posix.EBUSY => error.FileBusy,
954 posix.EDQUOT => error.DiskQuota,923 posix.EDQUOT => error.DiskQuota,
955 posix.EFAULT,924 posix.EFAULT, posix.EINVAL => unreachable,
956 posix.EINVAL => unreachable,
957 posix.EISDIR => error.IsDir,925 posix.EISDIR => error.IsDir,
958 posix.ELOOP => error.SymLinkLoop,926 posix.ELOOP => error.SymLinkLoop,
959 posix.EMLINK => error.LinkQuotaExceeded,927 posix.EMLINK => error.LinkQuotaExceeded,
...@@ -962,8 +930,7 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8)...@@ -962,8 +930,7 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8)
962 posix.ENOTDIR => error.NotDir,930 posix.ENOTDIR => error.NotDir,
963 posix.ENOMEM => error.SystemResources,931 posix.ENOMEM => error.SystemResources,
964 posix.ENOSPC => error.NoSpaceLeft,932 posix.ENOSPC => error.NoSpaceLeft,
965 posix.EEXIST,933 posix.EEXIST, posix.ENOTEMPTY => error.PathAlreadyExists,
966 posix.ENOTEMPTY => error.PathAlreadyExists,
967 posix.EROFS => error.ReadOnlyFileSystem,934 posix.EROFS => error.ReadOnlyFileSystem,
968 posix.EXDEV => error.RenameAcrossMountPoints,935 posix.EXDEV => error.RenameAcrossMountPoints,
969 else => unexpectedErrorPosix(err),936 else => unexpectedErrorPosix(err),
...@@ -972,7 +939,7 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8)...@@ -972,7 +939,7 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8)
972 }939 }
973}940}
974941
975pub fn makeDir(allocator: &Allocator, dir_path: []const u8) !void {942pub fn makeDir(allocator: *Allocator, dir_path: []const u8) !void {
976 if (is_windows) {943 if (is_windows) {
977 return makeDirWindows(allocator, dir_path);944 return makeDirWindows(allocator, dir_path);
978 } else {945 } else {
...@@ -980,7 +947,7 @@ pub fn makeDir(allocator: &Allocator, dir_path: []const u8) !void {...@@ -980,7 +947,7 @@ pub fn makeDir(allocator: &Allocator, dir_path: []const u8) !void {
980 }947 }
981}948}
982949
983pub fn makeDirWindows(allocator: &Allocator, dir_path: []const u8) !void {950pub fn makeDirWindows(allocator: *Allocator, dir_path: []const u8) !void {
984 const path_buf = try cstr.addNullByte(allocator, dir_path);951 const path_buf = try cstr.addNullByte(allocator, dir_path);
985 defer allocator.free(path_buf);952 defer allocator.free(path_buf);
986953
...@@ -994,15 +961,14 @@ pub fn makeDirWindows(allocator: &Allocator, dir_path: []const u8) !void {...@@ -994,15 +961,14 @@ pub fn makeDirWindows(allocator: &Allocator, dir_path: []const u8) !void {
994 }961 }
995}962}
996963
997pub fn makeDirPosix(allocator: &Allocator, dir_path: []const u8) !void {964pub fn makeDirPosix(allocator: *Allocator, dir_path: []const u8) !void {
998 const path_buf = try cstr.addNullByte(allocator, dir_path);965 const path_buf = try cstr.addNullByte(allocator, dir_path);
999 defer allocator.free(path_buf);966 defer allocator.free(path_buf);
1000967
1001 const err = posix.getErrno(posix.mkdir(path_buf.ptr, 0o755));968 const err = posix.getErrno(posix.mkdir(path_buf.ptr, 0o755));
1002 if (err > 0) {969 if (err > 0) {
1003 return switch (err) {970 return switch (err) {
1004 posix.EACCES,971 posix.EACCES, posix.EPERM => error.AccessDenied,
1005 posix.EPERM => error.AccessDenied,
1006 posix.EDQUOT => error.DiskQuota,972 posix.EDQUOT => error.DiskQuota,
1007 posix.EEXIST => error.PathAlreadyExists,973 posix.EEXIST => error.PathAlreadyExists,
1008 posix.EFAULT => unreachable,974 posix.EFAULT => unreachable,
...@@ -1021,7 +987,7 @@ pub fn makeDirPosix(allocator: &Allocator, dir_path: []const u8) !void {...@@ -1021,7 +987,7 @@ pub fn makeDirPosix(allocator: &Allocator, dir_path: []const u8) !void {
1021987
1022/// Calls makeDir recursively to make an entire path. Returns success if the path988/// Calls makeDir recursively to make an entire path. Returns success if the path
1023/// already exists and is a directory.989/// already exists and is a directory.
1024pub fn makePath(allocator: &Allocator, full_path: []const u8) !void {990pub fn makePath(allocator: *Allocator, full_path: []const u8) !void {
1025 const resolved_path = try path.resolve(allocator, full_path);991 const resolved_path = try path.resolve(allocator, full_path);
1026 defer allocator.free(resolved_path);992 defer allocator.free(resolved_path);
1027993
...@@ -1055,7 +1021,7 @@ pub fn makePath(allocator: &Allocator, full_path: []const u8) !void {...@@ -1055,7 +1021,7 @@ pub fn makePath(allocator: &Allocator, full_path: []const u8) !void {
10551021
1056/// Returns ::error.DirNotEmpty if the directory is not empty.1022/// Returns ::error.DirNotEmpty if the directory is not empty.
1057/// To delete a directory recursively, see ::deleteTree1023/// To delete a directory recursively, see ::deleteTree
1058pub fn deleteDir(allocator: &Allocator, dir_path: []const u8) !void {1024pub fn deleteDir(allocator: *Allocator, dir_path: []const u8) !void {
1059 const path_buf = try allocator.alloc(u8, dir_path.len + 1);1025 const path_buf = try allocator.alloc(u8, dir_path.len + 1);
1060 defer allocator.free(path_buf);1026 defer allocator.free(path_buf);
10611027
...@@ -1065,18 +1031,15 @@ pub fn deleteDir(allocator: &Allocator, dir_path: []const u8) !void {...@@ -1065,18 +1031,15 @@ pub fn deleteDir(allocator: &Allocator, dir_path: []const u8) !void {
1065 const err = posix.getErrno(posix.rmdir(path_buf.ptr));1031 const err = posix.getErrno(posix.rmdir(path_buf.ptr));
1066 if (err > 0) {1032 if (err > 0) {
1067 return switch (err) {1033 return switch (err) {
1068 posix.EACCES,1034 posix.EACCES, posix.EPERM => error.AccessDenied,
1069 posix.EPERM => error.AccessDenied,
1070 posix.EBUSY => error.FileBusy,1035 posix.EBUSY => error.FileBusy,
1071 posix.EFAULT,1036 posix.EFAULT, posix.EINVAL => unreachable,
1072 posix.EINVAL => unreachable,
1073 posix.ELOOP => error.SymLinkLoop,1037 posix.ELOOP => error.SymLinkLoop,
1074 posix.ENAMETOOLONG => error.NameTooLong,1038 posix.ENAMETOOLONG => error.NameTooLong,
1075 posix.ENOENT => error.FileNotFound,1039 posix.ENOENT => error.FileNotFound,
1076 posix.ENOMEM => error.SystemResources,1040 posix.ENOMEM => error.SystemResources,
1077 posix.ENOTDIR => error.NotDir,1041 posix.ENOTDIR => error.NotDir,
1078 posix.EEXIST,1042 posix.EEXIST, posix.ENOTEMPTY => error.DirNotEmpty,
1079 posix.ENOTEMPTY => error.DirNotEmpty,
1080 posix.EROFS => error.ReadOnlyFileSystem,1043 posix.EROFS => error.ReadOnlyFileSystem,
1081 else => unexpectedErrorPosix(err),1044 else => unexpectedErrorPosix(err),
1082 };1045 };
...@@ -1109,7 +1072,7 @@ const DeleteTreeError = error{...@@ -1109,7 +1072,7 @@ const DeleteTreeError = error{
1109 DirNotEmpty,1072 DirNotEmpty,
1110 Unexpected,1073 Unexpected,
1111};1074};
1112pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError!void {1075pub fn deleteTree(allocator: *Allocator, full_path: []const u8) DeleteTreeError!void {
1113 start_over: while (true) {1076 start_over: while (true) {
1114 var got_access_denied = false;1077 var got_access_denied = false;
1115 // First, try deleting the item as a file. This way we don't follow sym links.1078 // First, try deleting the item as a file. This way we don't follow sym links.
...@@ -1128,7 +1091,8 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError!...@@ -1128,7 +1091,8 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError!
1128 error.NotDir,1091 error.NotDir,
1129 error.FileSystem,1092 error.FileSystem,
1130 error.FileBusy,1093 error.FileBusy,
1131 error.Unexpected => return err,1094 error.Unexpected,
1095 => return err,
1132 }1096 }
1133 {1097 {
1134 var dir = Dir.open(allocator, full_path) catch |err| switch (err) {1098 var dir = Dir.open(allocator, full_path) catch |err| switch (err) {
...@@ -1152,7 +1116,8 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError!...@@ -1152,7 +1116,8 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError!
1152 error.SystemResources,1116 error.SystemResources,
1153 error.NoSpaceLeft,1117 error.NoSpaceLeft,
1154 error.PathAlreadyExists,1118 error.PathAlreadyExists,
1155 error.Unexpected => return err,1119 error.Unexpected,
1120 => return err,
1156 };1121 };
1157 defer dir.close();1122 defer dir.close();
11581123
...@@ -1164,7 +1129,7 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError!...@@ -1164,7 +1129,7 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError!
1164 const full_entry_path = full_entry_buf.toSlice();1129 const full_entry_path = full_entry_buf.toSlice();
1165 mem.copy(u8, full_entry_path, full_path);1130 mem.copy(u8, full_entry_path, full_path);
1166 full_entry_path[full_path.len] = '/';1131 full_entry_path[full_path.len] = '/';
1167 mem.copy(u8, full_entry_path[full_path.len + 1..], entry.name);1132 mem.copy(u8, full_entry_path[full_path.len + 1 ..], entry.name);
11681133
1169 try deleteTree(allocator, full_entry_path);1134 try deleteTree(allocator, full_entry_path);
1170 }1135 }
...@@ -1176,14 +1141,13 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError!...@@ -1176,14 +1141,13 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError!
1176pub const Dir = struct {1141pub const Dir = struct {
1177 fd: i32,1142 fd: i32,
1178 darwin_seek: darwin_seek_t,1143 darwin_seek: darwin_seek_t,
1179 allocator: &Allocator,1144 allocator: *Allocator,
1180 buf: []u8,1145 buf: []u8,
1181 index: usize,1146 index: usize,
1182 end_index: usize,1147 end_index: usize,
11831148
1184 const darwin_seek_t = switch (builtin.os) {1149 const darwin_seek_t = switch (builtin.os) {
1185 Os.macosx,1150 Os.macosx, Os.ios => i64,
1186 Os.ios => i64,
1187 else => void,1151 else => void,
1188 };1152 };
11891153
...@@ -1204,17 +1168,20 @@ pub const Dir = struct {...@@ -1204,17 +1168,20 @@ pub const Dir = struct {
1204 };1168 };
1205 };1169 };
12061170
1207 pub fn open(allocator: &Allocator, dir_path: []const u8) !Dir {1171 pub fn open(allocator: *Allocator, dir_path: []const u8) !Dir {
1208 const fd = switch (builtin.os) {1172 const fd = switch (builtin.os) {
1209 Os.windows => @compileError("TODO support Dir.open for windows"),1173 Os.windows => @compileError("TODO support Dir.open for windows"),
1210 Os.linux => try posixOpen(allocator, dir_path, posix.O_RDONLY | posix.O_DIRECTORY | posix.O_CLOEXEC, 0),1174 Os.linux => try posixOpen(allocator, dir_path, posix.O_RDONLY | posix.O_DIRECTORY | posix.O_CLOEXEC, 0),
1211 Os.macosx,1175 Os.macosx, Os.ios => try posixOpen(
1212 Os.ios => try posixOpen(allocator, dir_path, posix.O_RDONLY | posix.O_NONBLOCK | posix.O_DIRECTORY | posix.O_CLOEXEC, 0),1176 allocator,
1177 dir_path,
1178 posix.O_RDONLY | posix.O_NONBLOCK | posix.O_DIRECTORY | posix.O_CLOEXEC,
1179 0,
1180 ),
1213 else => @compileError("Dir.open is not supported for this platform"),1181 else => @compileError("Dir.open is not supported for this platform"),
1214 };1182 };
1215 const darwin_seek_init = switch (builtin.os) {1183 const darwin_seek_init = switch (builtin.os) {
1216 Os.macosx,1184 Os.macosx, Os.ios => 0,
1217 Os.ios => 0,
1218 else => {},1185 else => {},
1219 };1186 };
1220 return Dir{1187 return Dir{
...@@ -1227,24 +1194,23 @@ pub const Dir = struct {...@@ -1227,24 +1194,23 @@ pub const Dir = struct {
1227 };1194 };
1228 }1195 }
12291196
1230 pub fn close(self: &Dir) void {1197 pub fn close(self: *Dir) void {
1231 self.allocator.free(self.buf);1198 self.allocator.free(self.buf);
1232 os.close(self.fd);1199 os.close(self.fd);
1233 }1200 }
12341201
1235 /// Memory such as file names referenced in this returned entry becomes invalid1202 /// Memory such as file names referenced in this returned entry becomes invalid
1236 /// with subsequent calls to next, as well as when this ::Dir is deinitialized.1203 /// with subsequent calls to next, as well as when this ::Dir is deinitialized.
1237 pub fn next(self: &Dir) !?Entry {1204 pub fn next(self: *Dir) !?Entry {
1238 switch (builtin.os) {1205 switch (builtin.os) {
1239 Os.linux => return self.nextLinux(),1206 Os.linux => return self.nextLinux(),
1240 Os.macosx,1207 Os.macosx, Os.ios => return self.nextDarwin(),
1241 Os.ios => return self.nextDarwin(),
1242 Os.windows => return self.nextWindows(),1208 Os.windows => return self.nextWindows(),
1243 else => @compileError("Dir.next not supported on " ++ @tagName(builtin.os)),1209 else => @compileError("Dir.next not supported on " ++ @tagName(builtin.os)),
1244 }1210 }
1245 }1211 }
12461212
1247 fn nextDarwin(self: &Dir) !?Entry {1213 fn nextDarwin(self: *Dir) !?Entry {
1248 start_over: while (true) {1214 start_over: while (true) {
1249 if (self.index >= self.end_index) {1215 if (self.index >= self.end_index) {
1250 if (self.buf.len == 0) {1216 if (self.buf.len == 0) {
...@@ -1256,9 +1222,7 @@ pub const Dir = struct {...@@ -1256,9 +1222,7 @@ pub const Dir = struct {
1256 const err = posix.getErrno(result);1222 const err = posix.getErrno(result);
1257 if (err > 0) {1223 if (err > 0) {
1258 switch (err) {1224 switch (err) {
1259 posix.EBADF,1225 posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable,
1260 posix.EFAULT,
1261 posix.ENOTDIR => unreachable,
1262 posix.EINVAL => {1226 posix.EINVAL => {
1263 self.buf = try self.allocator.realloc(u8, self.buf, self.buf.len * 2);1227 self.buf = try self.allocator.realloc(u8, self.buf, self.buf.len * 2);
1264 continue;1228 continue;
...@@ -1272,7 +1236,7 @@ pub const Dir = struct {...@@ -1272,7 +1236,7 @@ pub const Dir = struct {
1272 break;1236 break;
1273 }1237 }
1274 }1238 }
1275 const darwin_entry = @ptrCast(&align(1) posix.dirent, &self.buf[self.index]);1239 const darwin_entry = @ptrCast(*align(1) posix.dirent, &self.buf[self.index]);
1276 const next_index = self.index + darwin_entry.d_reclen;1240 const next_index = self.index + darwin_entry.d_reclen;
1277 self.index = next_index;1241 self.index = next_index;
12781242
...@@ -1301,11 +1265,11 @@ pub const Dir = struct {...@@ -1301,11 +1265,11 @@ pub const Dir = struct {
1301 }1265 }
1302 }1266 }
13031267
1304 fn nextWindows(self: &Dir) !?Entry {1268 fn nextWindows(self: *Dir) !?Entry {
1305 @compileError("TODO support Dir.next for windows");1269 @compileError("TODO support Dir.next for windows");
1306 }1270 }
13071271
1308 fn nextLinux(self: &Dir) !?Entry {1272 fn nextLinux(self: *Dir) !?Entry {
1309 start_over: while (true) {1273 start_over: while (true) {
1310 if (self.index >= self.end_index) {1274 if (self.index >= self.end_index) {
1311 if (self.buf.len == 0) {1275 if (self.buf.len == 0) {
...@@ -1317,9 +1281,7 @@ pub const Dir = struct {...@@ -1317,9 +1281,7 @@ pub const Dir = struct {
1317 const err = posix.getErrno(result);1281 const err = posix.getErrno(result);
1318 if (err > 0) {1282 if (err > 0) {
1319 switch (err) {1283 switch (err) {
1320 posix.EBADF,1284 posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable,
1321 posix.EFAULT,
1322 posix.ENOTDIR => unreachable,
1323 posix.EINVAL => {1285 posix.EINVAL => {
1324 self.buf = try self.allocator.realloc(u8, self.buf, self.buf.len * 2);1286 self.buf = try self.allocator.realloc(u8, self.buf, self.buf.len * 2);
1325 continue;1287 continue;
...@@ -1333,11 +1295,11 @@ pub const Dir = struct {...@@ -1333,11 +1295,11 @@ pub const Dir = struct {
1333 break;1295 break;
1334 }1296 }
1335 }1297 }
1336 const linux_entry = @ptrCast(&align(1) posix.dirent, &self.buf[self.index]);1298 const linux_entry = @ptrCast(*align(1) posix.dirent, &self.buf[self.index]);
1337 const next_index = self.index + linux_entry.d_reclen;1299 const next_index = self.index + linux_entry.d_reclen;
1338 self.index = next_index;1300 self.index = next_index;
13391301
1340 const name = cstr.toSlice(&linux_entry.d_name);1302 const name = cstr.toSlice(@ptrCast([*]u8, &linux_entry.d_name));
13411303
1342 // skip . and .. entries1304 // skip . and .. entries
1343 if (mem.eql(u8, name, ".") or mem.eql(u8, name, "..")) {1305 if (mem.eql(u8, name, ".") or mem.eql(u8, name, "..")) {
...@@ -1363,7 +1325,7 @@ pub const Dir = struct {...@@ -1363,7 +1325,7 @@ pub const Dir = struct {
1363 }1325 }
1364};1326};
13651327
1366pub fn changeCurDir(allocator: &Allocator, dir_path: []const u8) !void {1328pub fn changeCurDir(allocator: *Allocator, dir_path: []const u8) !void {
1367 const path_buf = try allocator.alloc(u8, dir_path.len + 1);1329 const path_buf = try allocator.alloc(u8, dir_path.len + 1);
1368 defer allocator.free(path_buf);1330 defer allocator.free(path_buf);
13691331
...@@ -1387,7 +1349,7 @@ pub fn changeCurDir(allocator: &Allocator, dir_path: []const u8) !void {...@@ -1387,7 +1349,7 @@ pub fn changeCurDir(allocator: &Allocator, dir_path: []const u8) !void {
1387}1349}
13881350
1389/// Read value of a symbolic link.1351/// Read value of a symbolic link.
1390pub fn readLink(allocator: &Allocator, pathname: []const u8) ![]u8 {1352pub fn readLink(allocator: *Allocator, pathname: []const u8) ![]u8 {
1391 const path_buf = try allocator.alloc(u8, pathname.len + 1);1353 const path_buf = try allocator.alloc(u8, pathname.len + 1);
1392 defer allocator.free(path_buf);1354 defer allocator.free(path_buf);
13931355
...@@ -1402,8 +1364,7 @@ pub fn readLink(allocator: &Allocator, pathname: []const u8) ![]u8 {...@@ -1402,8 +1364,7 @@ pub fn readLink(allocator: &Allocator, pathname: []const u8) ![]u8 {
1402 if (err > 0) {1364 if (err > 0) {
1403 return switch (err) {1365 return switch (err) {
1404 posix.EACCES => error.AccessDenied,1366 posix.EACCES => error.AccessDenied,
1405 posix.EFAULT,1367 posix.EFAULT, posix.EINVAL => unreachable,
1406 posix.EINVAL => unreachable,
1407 posix.EIO => error.FileSystem,1368 posix.EIO => error.FileSystem,
1408 posix.ELOOP => error.SymLinkLoop,1369 posix.ELOOP => error.SymLinkLoop,
1409 posix.ENAMETOOLONG => error.NameTooLong,1370 posix.ENAMETOOLONG => error.NameTooLong,
...@@ -1495,7 +1456,7 @@ pub const ArgIteratorPosix = struct {...@@ -1495,7 +1456,7 @@ pub const ArgIteratorPosix = struct {
1495 };1456 };
1496 }1457 }
14971458
1498 pub fn next(self: &ArgIteratorPosix) ?[]const u8 {1459 pub fn next(self: *ArgIteratorPosix) ?[]const u8 {
1499 if (self.index == self.count) return null;1460 if (self.index == self.count) return null;
15001461
1501 const s = raw[self.index];1462 const s = raw[self.index];
...@@ -1503,7 +1464,7 @@ pub const ArgIteratorPosix = struct {...@@ -1503,7 +1464,7 @@ pub const ArgIteratorPosix = struct {
1503 return cstr.toSlice(s);1464 return cstr.toSlice(s);
1504 }1465 }
15051466
1506 pub fn skip(self: &ArgIteratorPosix) bool {1467 pub fn skip(self: *ArgIteratorPosix) bool {
1507 if (self.index == self.count) return false;1468 if (self.index == self.count) return false;
15081469
1509 self.index += 1;1470 self.index += 1;
...@@ -1512,12 +1473,12 @@ pub const ArgIteratorPosix = struct {...@@ -1512,12 +1473,12 @@ pub const ArgIteratorPosix = struct {
15121473
1513 /// This is marked as public but actually it's only meant to be used1474 /// This is marked as public but actually it's only meant to be used
1514 /// internally by zig's startup code.1475 /// internally by zig's startup code.
1515 pub var raw: []&u8 = undefined;1476 pub var raw: [][*]u8 = undefined;
1516};1477};
15171478
1518pub const ArgIteratorWindows = struct {1479pub const ArgIteratorWindows = struct {
1519 index: usize,1480 index: usize,
1520 cmd_line: &const u8,1481 cmd_line: [*]const u8,
1521 in_quote: bool,1482 in_quote: bool,
1522 quote_count: usize,1483 quote_count: usize,
1523 seen_quote_count: usize,1484 seen_quote_count: usize,
...@@ -1528,7 +1489,7 @@ pub const ArgIteratorWindows = struct {...@@ -1528,7 +1489,7 @@ pub const ArgIteratorWindows = struct {
1528 return initWithCmdLine(windows.GetCommandLineA());1489 return initWithCmdLine(windows.GetCommandLineA());
1529 }1490 }
15301491
1531 pub fn initWithCmdLine(cmd_line: &const u8) ArgIteratorWindows {1492 pub fn initWithCmdLine(cmd_line: [*]const u8) ArgIteratorWindows {
1532 return ArgIteratorWindows{1493 return ArgIteratorWindows{
1533 .index = 0,1494 .index = 0,
1534 .cmd_line = cmd_line,1495 .cmd_line = cmd_line,
...@@ -1539,14 +1500,13 @@ pub const ArgIteratorWindows = struct {...@@ -1539,14 +1500,13 @@ pub const ArgIteratorWindows = struct {
1539 }1500 }
15401501
1541 /// You must free the returned memory when done.1502 /// You must free the returned memory when done.
1542 pub fn next(self: &ArgIteratorWindows, allocator: &Allocator) ?(NextError![]u8) {1503 pub fn next(self: *ArgIteratorWindows, allocator: *Allocator) ?(NextError![]u8) {
1543 // march forward over whitespace1504 // march forward over whitespace
1544 while (true) : (self.index += 1) {1505 while (true) : (self.index += 1) {
1545 const byte = self.cmd_line[self.index];1506 const byte = self.cmd_line[self.index];
1546 switch (byte) {1507 switch (byte) {
1547 0 => return null,1508 0 => return null,
1548 ' ',1509 ' ', '\t' => continue,
1549 '\t' => continue,
1550 else => break,1510 else => break,
1551 }1511 }
1552 }1512 }
...@@ -1554,14 +1514,13 @@ pub const ArgIteratorWindows = struct {...@@ -1554,14 +1514,13 @@ pub const ArgIteratorWindows = struct {
1554 return self.internalNext(allocator);1514 return self.internalNext(allocator);
1555 }1515 }
15561516
1557 pub fn skip(self: &ArgIteratorWindows) bool {1517 pub fn skip(self: *ArgIteratorWindows) bool {
1558 // march forward over whitespace1518 // march forward over whitespace
1559 while (true) : (self.index += 1) {1519 while (true) : (self.index += 1) {
1560 const byte = self.cmd_line[self.index];1520 const byte = self.cmd_line[self.index];
1561 switch (byte) {1521 switch (byte) {
1562 0 => return false,1522 0 => return false,
1563 ' ',1523 ' ', '\t' => continue,
1564 '\t' => continue,
1565 else => break,1524 else => break,
1566 }1525 }
1567 }1526 }
...@@ -1580,8 +1539,7 @@ pub const ArgIteratorWindows = struct {...@@ -1580,8 +1539,7 @@ pub const ArgIteratorWindows = struct {
1580 '\\' => {1539 '\\' => {
1581 backslash_count += 1;1540 backslash_count += 1;
1582 },1541 },
1583 ' ',1542 ' ', '\t' => {
1584 '\t' => {
1585 if (self.seen_quote_count % 2 == 0 or self.seen_quote_count == self.quote_count) {1543 if (self.seen_quote_count % 2 == 0 or self.seen_quote_count == self.quote_count) {
1586 return true;1544 return true;
1587 }1545 }
...@@ -1595,7 +1553,7 @@ pub const ArgIteratorWindows = struct {...@@ -1595,7 +1553,7 @@ pub const ArgIteratorWindows = struct {
1595 }1553 }
1596 }1554 }
15971555
1598 fn internalNext(self: &ArgIteratorWindows, allocator: &Allocator) NextError![]u8 {1556 fn internalNext(self: *ArgIteratorWindows, allocator: *Allocator) NextError![]u8 {
1599 var buf = try Buffer.initSize(allocator, 0);1557 var buf = try Buffer.initSize(allocator, 0);
1600 defer buf.deinit();1558 defer buf.deinit();
16011559
...@@ -1621,8 +1579,7 @@ pub const ArgIteratorWindows = struct {...@@ -1621,8 +1579,7 @@ pub const ArgIteratorWindows = struct {
1621 '\\' => {1579 '\\' => {
1622 backslash_count += 1;1580 backslash_count += 1;
1623 },1581 },
1624 ' ',1582 ' ', '\t' => {
1625 '\t' => {
1626 try self.emitBackslashes(&buf, backslash_count);1583 try self.emitBackslashes(&buf, backslash_count);
1627 backslash_count = 0;1584 backslash_count = 0;
1628 if (self.seen_quote_count % 2 == 1 and self.seen_quote_count != self.quote_count) {1585 if (self.seen_quote_count % 2 == 1 and self.seen_quote_count != self.quote_count) {
...@@ -1640,14 +1597,14 @@ pub const ArgIteratorWindows = struct {...@@ -1640,14 +1597,14 @@ pub const ArgIteratorWindows = struct {
1640 }1597 }
1641 }1598 }
16421599
1643 fn emitBackslashes(self: &ArgIteratorWindows, buf: &Buffer, emit_count: usize) !void {1600 fn emitBackslashes(self: *ArgIteratorWindows, buf: *Buffer, emit_count: usize) !void {
1644 var i: usize = 0;1601 var i: usize = 0;
1645 while (i < emit_count) : (i += 1) {1602 while (i < emit_count) : (i += 1) {
1646 try buf.appendByte('\\');1603 try buf.appendByte('\\');
1647 }1604 }
1648 }1605 }
16491606
1650 fn countQuotes(cmd_line: &const u8) usize {1607 fn countQuotes(cmd_line: [*]const u8) usize {
1651 var result: usize = 0;1608 var result: usize = 0;
1652 var backslash_count: usize = 0;1609 var backslash_count: usize = 0;
1653 var index: usize = 0;1610 var index: usize = 0;
...@@ -1680,7 +1637,7 @@ pub const ArgIterator = struct {...@@ -1680,7 +1637,7 @@ pub const ArgIterator = struct {
1680 pub const NextError = ArgIteratorWindows.NextError;1637 pub const NextError = ArgIteratorWindows.NextError;
16811638
1682 /// You must free the returned memory when done.1639 /// You must free the returned memory when done.
1683 pub fn next(self: &ArgIterator, allocator: &Allocator) ?(NextError![]u8) {1640 pub fn next(self: *ArgIterator, allocator: *Allocator) ?(NextError![]u8) {
1684 if (builtin.os == Os.windows) {1641 if (builtin.os == Os.windows) {
1685 return self.inner.next(allocator);1642 return self.inner.next(allocator);
1686 } else {1643 } else {
...@@ -1689,13 +1646,13 @@ pub const ArgIterator = struct {...@@ -1689,13 +1646,13 @@ pub const ArgIterator = struct {
1689 }1646 }
16901647
1691 /// If you only are targeting posix you can call this and not need an allocator.1648 /// If you only are targeting posix you can call this and not need an allocator.
1692 pub fn nextPosix(self: &ArgIterator) ?[]const u8 {1649 pub fn nextPosix(self: *ArgIterator) ?[]const u8 {
1693 return self.inner.next();1650 return self.inner.next();
1694 }1651 }
16951652
1696 /// Parse past 1 argument without capturing it.1653 /// Parse past 1 argument without capturing it.
1697 /// Returns `true` if skipped an arg, `false` if we are at the end.1654 /// Returns `true` if skipped an arg, `false` if we are at the end.
1698 pub fn skip(self: &ArgIterator) bool {1655 pub fn skip(self: *ArgIterator) bool {
1699 return self.inner.skip();1656 return self.inner.skip();
1700 }1657 }
1701};1658};
...@@ -1705,7 +1662,7 @@ pub fn args() ArgIterator {...@@ -1705,7 +1662,7 @@ pub fn args() ArgIterator {
1705}1662}
17061663
1707/// Caller must call freeArgs on result.1664/// Caller must call freeArgs on result.
1708pub fn argsAlloc(allocator: &mem.Allocator) ![]const []u8 {1665pub fn argsAlloc(allocator: *mem.Allocator) ![]const []u8 {
1709 // TODO refactor to only make 1 allocation.1666 // TODO refactor to only make 1 allocation.
1710 var it = args();1667 var it = args();
1711 var contents = try Buffer.initSize(allocator, 0);1668 var contents = try Buffer.initSize(allocator, 0);
...@@ -1742,50 +1699,23 @@ pub fn argsAlloc(allocator: &mem.Allocator) ![]const []u8 {...@@ -1742,50 +1699,23 @@ pub fn argsAlloc(allocator: &mem.Allocator) ![]const []u8 {
1742 return result_slice_list;1699 return result_slice_list;
1743}1700}
17441701
1745pub fn argsFree(allocator: &mem.Allocator, args_alloc: []const []u8) void {1702pub fn argsFree(allocator: *mem.Allocator, args_alloc: []const []u8) void {
1746 var total_bytes: usize = 0;1703 var total_bytes: usize = 0;
1747 for (args_alloc) |arg| {1704 for (args_alloc) |arg| {
1748 total_bytes += @sizeOf([]u8) + arg.len;1705 total_bytes += @sizeOf([]u8) + arg.len;
1749 }1706 }
1750 const unaligned_allocated_buf = @ptrCast(&const u8, args_alloc.ptr)[0..total_bytes];1707 const unaligned_allocated_buf = @ptrCast(*const u8, args_alloc.ptr)[0..total_bytes];
1751 const aligned_allocated_buf = @alignCast(@alignOf([]u8), unaligned_allocated_buf);1708 const aligned_allocated_buf = @alignCast(@alignOf([]u8), unaligned_allocated_buf);
1752 return allocator.free(aligned_allocated_buf);1709 return allocator.free(aligned_allocated_buf);
1753}1710}
17541711
1755test "windows arg parsing" {1712test "windows arg parsing" {
1756 testWindowsCmdLine(c"a b\tc d", [][]const u8{1713 testWindowsCmdLine(c"a b\tc d", [][]const u8{ "a", "b", "c", "d" });
1757 "a",1714 testWindowsCmdLine(c"\"abc\" d e", [][]const u8{ "abc", "d", "e" });
1758 "b",1715 testWindowsCmdLine(c"a\\\\\\b d\"e f\"g h", [][]const u8{ "a\\\\\\b", "de fg", "h" });
1759 "c",1716 testWindowsCmdLine(c"a\\\\\\\"b c d", [][]const u8{ "a\\\"b", "c", "d" });
1760 "d",1717 testWindowsCmdLine(c"a\\\\\\\\\"b c\" d e", [][]const u8{ "a\\\\b c", "d", "e" });
1761 });1718 testWindowsCmdLine(c"a b\tc \"d f", [][]const u8{ "a", "b", "c", "\"d", "f" });
1762 testWindowsCmdLine(c"\"abc\" d e", [][]const u8{
1763 "abc",
1764 "d",
1765 "e",
1766 });
1767 testWindowsCmdLine(c"a\\\\\\b d\"e f\"g h", [][]const u8{
1768 "a\\\\\\b",
1769 "de fg",
1770 "h",
1771 });
1772 testWindowsCmdLine(c"a\\\\\\\"b c d", [][]const u8{
1773 "a\\\"b",
1774 "c",
1775 "d",
1776 });
1777 testWindowsCmdLine(c"a\\\\\\\\\"b c\" d e", [][]const u8{
1778 "a\\\\b c",
1779 "d",
1780 "e",
1781 });
1782 testWindowsCmdLine(c"a b\tc \"d f", [][]const u8{
1783 "a",
1784 "b",
1785 "c",
1786 "\"d",
1787 "f",
1788 });
17891719
1790 testWindowsCmdLine(c"\".\\..\\zig-cache\\build\" \"bin\\zig.exe\" \".\\..\" \".\\..\\zig-cache\" \"--help\"", [][]const u8{1720 testWindowsCmdLine(c"\".\\..\\zig-cache\\build\" \"bin\\zig.exe\" \".\\..\" \".\\..\\zig-cache\" \"--help\"", [][]const u8{
1791 ".\\..\\zig-cache\\build",1721 ".\\..\\zig-cache\\build",
...@@ -1796,7 +1726,7 @@ test "windows arg parsing" {...@@ -1796,7 +1726,7 @@ test "windows arg parsing" {
1796 });1726 });
1797}1727}
17981728
1799fn testWindowsCmdLine(input_cmd_line: &const u8, expected_args: []const []const u8) void {1729fn testWindowsCmdLine(input_cmd_line: [*]const u8, expected_args: []const []const u8) void {
1800 var it = ArgIteratorWindows.initWithCmdLine(input_cmd_line);1730 var it = ArgIteratorWindows.initWithCmdLine(input_cmd_line);
1801 for (expected_args) |expected_arg| {1731 for (expected_args) |expected_arg| {
1802 const arg = ??it.next(debug.global_allocator) catch unreachable;1732 const arg = ??it.next(debug.global_allocator) catch unreachable;
...@@ -1840,8 +1770,7 @@ pub fn openSelfExe() !os.File {...@@ -1840,8 +1770,7 @@ pub fn openSelfExe() !os.File {
1840 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);1770 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
1841 return os.File.openRead(&fixed_allocator.allocator, proc_file_path);1771 return os.File.openRead(&fixed_allocator.allocator, proc_file_path);
1842 },1772 },
1843 Os.macosx,1773 Os.macosx, Os.ios => {
1844 Os.ios => {
1845 var fixed_buffer_mem: [darwin.PATH_MAX * 2]u8 = undefined;1774 var fixed_buffer_mem: [darwin.PATH_MAX * 2]u8 = undefined;
1846 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);1775 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
1847 const self_exe_path = try selfExePath(&fixed_allocator.allocator);1776 const self_exe_path = try selfExePath(&fixed_allocator.allocator);
...@@ -1853,9 +1782,7 @@ pub fn openSelfExe() !os.File {...@@ -1853,9 +1782,7 @@ pub fn openSelfExe() !os.File {
18531782
1854test "openSelfExe" {1783test "openSelfExe" {
1855 switch (builtin.os) {1784 switch (builtin.os) {
1856 Os.linux,1785 Os.linux, Os.macosx, Os.ios => (try openSelfExe()).close(),
1857 Os.macosx,
1858 Os.ios => (try openSelfExe()).close(),
1859 else => return, // Unsupported OS.1786 else => return, // Unsupported OS.
1860 }1787 }
1861}1788}
...@@ -1866,7 +1793,7 @@ test "openSelfExe" {...@@ -1866,7 +1793,7 @@ test "openSelfExe" {
1866/// This function may return an error if the current executable1793/// This function may return an error if the current executable
1867/// was deleted after spawning.1794/// was deleted after spawning.
1868/// Caller owns returned memory.1795/// Caller owns returned memory.
1869pub fn selfExePath(allocator: &mem.Allocator) ![]u8 {1796pub fn selfExePath(allocator: *mem.Allocator) ![]u8 {
1870 switch (builtin.os) {1797 switch (builtin.os) {
1871 Os.linux => {1798 Os.linux => {
1872 // If the currently executing binary has been deleted,1799 // If the currently executing binary has been deleted,
...@@ -1893,8 +1820,7 @@ pub fn selfExePath(allocator: &mem.Allocator) ![]u8 {...@@ -1893,8 +1820,7 @@ pub fn selfExePath(allocator: &mem.Allocator) ![]u8 {
1893 try out_path.resize(new_len);1820 try out_path.resize(new_len);
1894 }1821 }
1895 },1822 },
1896 Os.macosx,1823 Os.macosx, Os.ios => {
1897 Os.ios => {
1898 var u32_len: u32 = 0;1824 var u32_len: u32 = 0;
1899 const ret1 = c._NSGetExecutablePath(undefined, &u32_len);1825 const ret1 = c._NSGetExecutablePath(undefined, &u32_len);
1900 assert(ret1 != 0);1826 assert(ret1 != 0);
...@@ -1910,7 +1836,7 @@ pub fn selfExePath(allocator: &mem.Allocator) ![]u8 {...@@ -1910,7 +1836,7 @@ pub fn selfExePath(allocator: &mem.Allocator) ![]u8 {
19101836
1911/// Get the directory path that contains the current executable.1837/// Get the directory path that contains the current executable.
1912/// Caller owns returned memory.1838/// Caller owns returned memory.
1913pub fn selfExeDirPath(allocator: &mem.Allocator) ![]u8 {1839pub fn selfExeDirPath(allocator: *mem.Allocator) ![]u8 {
1914 switch (builtin.os) {1840 switch (builtin.os) {
1915 Os.linux => {1841 Os.linux => {
1916 // If the currently executing binary has been deleted,1842 // If the currently executing binary has been deleted,
...@@ -1922,9 +1848,7 @@ pub fn selfExeDirPath(allocator: &mem.Allocator) ![]u8 {...@@ -1922,9 +1848,7 @@ pub fn selfExeDirPath(allocator: &mem.Allocator) ![]u8 {
1922 const dir = path.dirname(full_exe_path);1848 const dir = path.dirname(full_exe_path);
1923 return allocator.shrink(u8, full_exe_path, dir.len);1849 return allocator.shrink(u8, full_exe_path, dir.len);
1924 },1850 },
1925 Os.windows,1851 Os.windows, Os.macosx, Os.ios => {
1926 Os.macosx,
1927 Os.ios => {
1928 const self_exe_path = try selfExePath(allocator);1852 const self_exe_path = try selfExePath(allocator);
1929 errdefer allocator.free(self_exe_path);1853 errdefer allocator.free(self_exe_path);
1930 const dirname = os.path.dirname(self_exe_path);1854 const dirname = os.path.dirname(self_exe_path);
...@@ -1981,8 +1905,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 {...@@ -1981,8 +1905,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 {
1981 posix.EINVAL => return PosixSocketError.ProtocolFamilyNotAvailable,1905 posix.EINVAL => return PosixSocketError.ProtocolFamilyNotAvailable,
1982 posix.EMFILE => return PosixSocketError.ProcessFdQuotaExceeded,1906 posix.EMFILE => return PosixSocketError.ProcessFdQuotaExceeded,
1983 posix.ENFILE => return PosixSocketError.SystemFdQuotaExceeded,1907 posix.ENFILE => return PosixSocketError.SystemFdQuotaExceeded,
1984 posix.ENOBUFS,1908 posix.ENOBUFS, posix.ENOMEM => return PosixSocketError.SystemResources,
1985 posix.ENOMEM => return PosixSocketError.SystemResources,
1986 posix.EPROTONOSUPPORT => return PosixSocketError.ProtocolNotSupported,1909 posix.EPROTONOSUPPORT => return PosixSocketError.ProtocolNotSupported,
1987 else => return unexpectedErrorPosix(err),1910 else => return unexpectedErrorPosix(err),
1988 }1911 }
...@@ -1990,7 +1913,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 {...@@ -1990,7 +1913,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 {
19901913
1991pub const PosixBindError = error{1914pub const PosixBindError = error{
1992 /// The address is protected, and the user is not the superuser.1915 /// The address is protected, and the user is not the superuser.
1993 /// For UNIX domain sockets: Search permission is denied on a component 1916 /// For UNIX domain sockets: Search permission is denied on a component
1994 /// of the path prefix.1917 /// of the path prefix.
1995 AccessDenied,1918 AccessDenied,
19961919
...@@ -2039,7 +1962,7 @@ pub const PosixBindError = error{...@@ -2039,7 +1962,7 @@ pub const PosixBindError = error{
2039};1962};
20401963
2041/// addr is `&const T` where T is one of the sockaddr1964/// addr is `&const T` where T is one of the sockaddr
2042pub fn posixBind(fd: i32, addr: &const posix.sockaddr) PosixBindError!void {1965pub fn posixBind(fd: i32, addr: *const posix.sockaddr) PosixBindError!void {
2043 const rc = posix.bind(fd, addr, @sizeOf(posix.sockaddr));1966 const rc = posix.bind(fd, addr, @sizeOf(posix.sockaddr));
2044 const err = posix.getErrno(rc);1967 const err = posix.getErrno(rc);
2045 switch (err) {1968 switch (err) {
...@@ -2134,7 +2057,7 @@ pub const PosixAcceptError = error{...@@ -2134,7 +2057,7 @@ pub const PosixAcceptError = error{
2134 Unexpected,2057 Unexpected,
2135};2058};
21362059
2137pub fn posixAccept(fd: i32, addr: &posix.sockaddr, flags: u32) PosixAcceptError!i32 {2060pub fn posixAccept(fd: i32, addr: *posix.sockaddr, flags: u32) PosixAcceptError!i32 {
2138 while (true) {2061 while (true) {
2139 var sockaddr_size = u32(@sizeOf(posix.sockaddr));2062 var sockaddr_size = u32(@sizeOf(posix.sockaddr));
2140 const rc = posix.accept4(fd, addr, &sockaddr_size, flags);2063 const rc = posix.accept4(fd, addr, &sockaddr_size, flags);
...@@ -2151,8 +2074,7 @@ pub fn posixAccept(fd: i32, addr: &posix.sockaddr, flags: u32) PosixAcceptError!...@@ -2151,8 +2074,7 @@ pub fn posixAccept(fd: i32, addr: &posix.sockaddr, flags: u32) PosixAcceptError!
2151 posix.EINVAL => return PosixAcceptError.InvalidSyscall,2074 posix.EINVAL => return PosixAcceptError.InvalidSyscall,
2152 posix.EMFILE => return PosixAcceptError.ProcessFdQuotaExceeded,2075 posix.EMFILE => return PosixAcceptError.ProcessFdQuotaExceeded,
2153 posix.ENFILE => return PosixAcceptError.SystemFdQuotaExceeded,2076 posix.ENFILE => return PosixAcceptError.SystemFdQuotaExceeded,
2154 posix.ENOBUFS,2077 posix.ENOBUFS, posix.ENOMEM => return PosixAcceptError.SystemResources,
2155 posix.ENOMEM => return PosixAcceptError.SystemResources,
2156 posix.ENOTSOCK => return PosixAcceptError.FileDescriptorNotASocket,2078 posix.ENOTSOCK => return PosixAcceptError.FileDescriptorNotASocket,
2157 posix.EOPNOTSUPP => return PosixAcceptError.OperationNotSupported,2079 posix.EOPNOTSUPP => return PosixAcceptError.OperationNotSupported,
2158 posix.EPROTO => return PosixAcceptError.ProtocolFailure,2080 posix.EPROTO => return PosixAcceptError.ProtocolFailure,
...@@ -2234,7 +2156,7 @@ pub const LinuxEpollCtlError = error{...@@ -2234,7 +2156,7 @@ pub const LinuxEpollCtlError = error{
2234 Unexpected,2156 Unexpected,
2235};2157};
22362158
2237pub fn linuxEpollCtl(epfd: i32, op: u32, fd: i32, event: &linux.epoll_event) LinuxEpollCtlError!void {2159pub fn linuxEpollCtl(epfd: i32, op: u32, fd: i32, event: *linux.epoll_event) LinuxEpollCtlError!void {
2238 const rc = posix.epoll_ctl(epfd, op, fd, event);2160 const rc = posix.epoll_ctl(epfd, op, fd, event);
2239 const err = posix.getErrno(rc);2161 const err = posix.getErrno(rc);
2240 switch (err) {2162 switch (err) {
...@@ -2327,7 +2249,7 @@ pub const PosixConnectError = error{...@@ -2327,7 +2249,7 @@ pub const PosixConnectError = error{
2327 Unexpected,2249 Unexpected,
2328};2250};
23292251
2330pub fn posixConnect(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConnectError!void {2252pub fn posixConnect(sockfd: i32, sockaddr: *const posix.sockaddr) PosixConnectError!void {
2331 while (true) {2253 while (true) {
2332 const rc = posix.connect(sockfd, sockaddr, @sizeOf(posix.sockaddr));2254 const rc = posix.connect(sockfd, sockaddr, @sizeOf(posix.sockaddr));
2333 const err = posix.getErrno(rc);2255 const err = posix.getErrno(rc);
...@@ -2358,13 +2280,12 @@ pub fn posixConnect(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConnectEr...@@ -2358,13 +2280,12 @@ pub fn posixConnect(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConnectEr
23582280
2359/// Same as posixConnect except it is for blocking socket file descriptors.2281/// Same as posixConnect except it is for blocking socket file descriptors.
2360/// It expects to receive EINPROGRESS.2282/// It expects to receive EINPROGRESS.
2361pub fn posixConnectAsync(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConnectError!void {2283pub fn posixConnectAsync(sockfd: i32, sockaddr: *const posix.sockaddr) PosixConnectError!void {
2362 while (true) {2284 while (true) {
2363 const rc = posix.connect(sockfd, sockaddr, @sizeOf(posix.sockaddr));2285 const rc = posix.connect(sockfd, sockaddr, @sizeOf(posix.sockaddr));
2364 const err = posix.getErrno(rc);2286 const err = posix.getErrno(rc);
2365 switch (err) {2287 switch (err) {
2366 0,2288 0, posix.EINPROGRESS => return,
2367 posix.EINPROGRESS => return,
2368 else => return unexpectedErrorPosix(err),2289 else => return unexpectedErrorPosix(err),
23692290
2370 posix.EACCES => return PosixConnectError.PermissionDenied,2291 posix.EACCES => return PosixConnectError.PermissionDenied,
...@@ -2390,7 +2311,7 @@ pub fn posixConnectAsync(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConn...@@ -2390,7 +2311,7 @@ pub fn posixConnectAsync(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConn
2390pub fn posixGetSockOptConnectError(sockfd: i32) PosixConnectError!void {2311pub fn posixGetSockOptConnectError(sockfd: i32) PosixConnectError!void {
2391 var err_code: i32 = undefined;2312 var err_code: i32 = undefined;
2392 var size: u32 = @sizeOf(i32);2313 var size: u32 = @sizeOf(i32);
2393 const rc = posix.getsockopt(sockfd, posix.SOL_SOCKET, posix.SO_ERROR, @ptrCast(&u8, &err_code), &size);2314 const rc = posix.getsockopt(sockfd, posix.SOL_SOCKET, posix.SO_ERROR, @ptrCast([*]u8, &err_code), &size);
2394 assert(size == 4);2315 assert(size == 4);
2395 const err = posix.getErrno(rc);2316 const err = posix.getErrno(rc);
2396 switch (err) {2317 switch (err) {
...@@ -2416,7 +2337,7 @@ pub fn posixGetSockOptConnectError(sockfd: i32) PosixConnectError!void {...@@ -2416,7 +2337,7 @@ pub fn posixGetSockOptConnectError(sockfd: i32) PosixConnectError!void {
2416 },2337 },
2417 else => return unexpectedErrorPosix(err),2338 else => return unexpectedErrorPosix(err),
2418 posix.EBADF => unreachable, // The argument sockfd is not a valid file descriptor.2339 posix.EBADF => unreachable, // The argument sockfd is not a valid file descriptor.
2419 posix.EFAULT => unreachable, // The address pointed to by optval or optlen is not in a valid part of the process address space. 2340 posix.EFAULT => unreachable, // The address pointed to by optval or optlen is not in a valid part of the process address space.
2420 posix.EINVAL => unreachable,2341 posix.EINVAL => unreachable,
2421 posix.ENOPROTOOPT => unreachable, // The option is unknown at the level indicated.2342 posix.ENOPROTOOPT => unreachable, // The option is unknown at the level indicated.
2422 posix.ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.2343 posix.ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
...@@ -2427,11 +2348,13 @@ pub const Thread = struct {...@@ -2427,11 +2348,13 @@ pub const Thread = struct {
2427 data: Data,2348 data: Data,
24282349
2429 pub const use_pthreads = is_posix and builtin.link_libc;2350 pub const use_pthreads = is_posix and builtin.link_libc;
2430 const Data = if (use_pthreads) struct {2351 const Data = if (use_pthreads)
2431 handle: c.pthread_t,2352 struct {
2432 stack_addr: usize,2353 handle: c.pthread_t,
2433 stack_len: usize,2354 stack_addr: usize,
2434 } else switch (builtin.os) {2355 stack_len: usize,
2356 }
2357 else switch (builtin.os) {
2435 builtin.Os.linux => struct {2358 builtin.Os.linux => struct {
2436 pid: i32,2359 pid: i32,
2437 stack_addr: usize,2360 stack_addr: usize,
...@@ -2439,13 +2362,13 @@ pub const Thread = struct {...@@ -2439,13 +2362,13 @@ pub const Thread = struct {
2439 },2362 },
2440 builtin.Os.windows => struct {2363 builtin.Os.windows => struct {
2441 handle: windows.HANDLE,2364 handle: windows.HANDLE,
2442 alloc_start: &c_void,2365 alloc_start: [*]c_void,
2443 heap_handle: windows.HANDLE,2366 heap_handle: windows.HANDLE,
2444 },2367 },
2445 else => @compileError("Unsupported OS"),2368 else => @compileError("Unsupported OS"),
2446 };2369 };
24472370
2448 pub fn wait(self: &const Thread) void {2371 pub fn wait(self: *const Thread) void {
2449 if (use_pthreads) {2372 if (use_pthreads) {
2450 const err = c.pthread_join(self.data.handle, null);2373 const err = c.pthread_join(self.data.handle, null);
2451 switch (err) {2374 switch (err) {
...@@ -2511,7 +2434,7 @@ pub const SpawnThreadError = error{...@@ -2511,7 +2434,7 @@ pub const SpawnThreadError = error{
2511/// fn startFn(@typeOf(context)) T2434/// fn startFn(@typeOf(context)) T
2512/// where T is u8, noreturn, void, or !void2435/// where T is u8, noreturn, void, or !void
2513/// caller must call wait on the returned thread2436/// caller must call wait on the returned thread
2514pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread {2437pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread {
2515 // TODO compile-time call graph analysis to determine stack upper bound2438 // TODO compile-time call graph analysis to determine stack upper bound
2516 // https://github.com/ziglang/zig/issues/1572439 // https://github.com/ziglang/zig/issues/157
2517 const default_stack_size = 8 * 1024 * 1024;2440 const default_stack_size = 8 * 1024 * 1024;
...@@ -2529,7 +2452,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread...@@ -2529,7 +2452,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread
2529 if (@sizeOf(Context) == 0) {2452 if (@sizeOf(Context) == 0) {
2530 return startFn({});2453 return startFn({});
2531 } else {2454 } else {
2532 return startFn(@ptrCast(&Context, @alignCast(@alignOf(Context), arg)).*);2455 return startFn(@ptrCast(*Context, @alignCast(@alignOf(Context), arg)).*);
2533 }2456 }
2534 }2457 }
2535 };2458 };
...@@ -2538,13 +2461,13 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread...@@ -2538,13 +2461,13 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread
2538 const byte_count = @alignOf(WinThread.OuterContext) + @sizeOf(WinThread.OuterContext);2461 const byte_count = @alignOf(WinThread.OuterContext) + @sizeOf(WinThread.OuterContext);
2539 const bytes_ptr = windows.HeapAlloc(heap_handle, 0, byte_count) ?? return SpawnThreadError.OutOfMemory;2462 const bytes_ptr = windows.HeapAlloc(heap_handle, 0, byte_count) ?? return SpawnThreadError.OutOfMemory;
2540 errdefer assert(windows.HeapFree(heap_handle, 0, bytes_ptr) != 0);2463 errdefer assert(windows.HeapFree(heap_handle, 0, bytes_ptr) != 0);
2541 const bytes = @ptrCast(&u8, bytes_ptr)[0..byte_count];2464 const bytes = @ptrCast([*]u8, bytes_ptr)[0..byte_count];
2542 const outer_context = std.heap.FixedBufferAllocator.init(bytes).allocator.create(WinThread.OuterContext) catch unreachable;2465 const outer_context = std.heap.FixedBufferAllocator.init(bytes).allocator.create(WinThread.OuterContext) catch unreachable;
2543 outer_context.inner = context;2466 outer_context.inner = context;
2544 outer_context.thread.data.heap_handle = heap_handle;2467 outer_context.thread.data.heap_handle = heap_handle;
2545 outer_context.thread.data.alloc_start = bytes_ptr;2468 outer_context.thread.data.alloc_start = bytes_ptr;
25462469
2547 const parameter = if (@sizeOf(Context) == 0) null else @ptrCast(&c_void, &outer_context.inner);2470 const parameter = if (@sizeOf(Context) == 0) null else @ptrCast(*c_void, &outer_context.inner);
2548 outer_context.thread.data.handle = windows.CreateThread(null, default_stack_size, WinThread.threadMain, parameter, 0, null) ?? {2471 outer_context.thread.data.handle = windows.CreateThread(null, default_stack_size, WinThread.threadMain, parameter, 0, null) ?? {
2549 const err = windows.GetLastError();2472 const err = windows.GetLastError();
2550 return switch (err) {2473 return switch (err) {
...@@ -2559,15 +2482,15 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread...@@ -2559,15 +2482,15 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread
2559 if (@sizeOf(Context) == 0) {2482 if (@sizeOf(Context) == 0) {
2560 return startFn({});2483 return startFn({});
2561 } else {2484 } else {
2562 return startFn(@intToPtr(&const Context, ctx_addr).*);2485 return startFn(@intToPtr(*const Context, ctx_addr).*);
2563 }2486 }
2564 }2487 }
2565 extern fn posixThreadMain(ctx: ?&c_void) ?&c_void {2488 extern fn posixThreadMain(ctx: ?*c_void) ?*c_void {
2566 if (@sizeOf(Context) == 0) {2489 if (@sizeOf(Context) == 0) {
2567 _ = startFn({});2490 _ = startFn({});
2568 return null;2491 return null;
2569 } else {2492 } else {
2570 _ = startFn(@ptrCast(&const Context, @alignCast(@alignOf(Context), ctx)).*);2493 _ = startFn(@ptrCast(*const Context, @alignCast(@alignOf(Context), ctx)).*);
2571 return null;2494 return null;
2572 }2495 }
2573 }2496 }
...@@ -2586,7 +2509,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread...@@ -2586,7 +2509,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread
2586 stack_end -= @sizeOf(Context);2509 stack_end -= @sizeOf(Context);
2587 stack_end -= stack_end % @alignOf(Context);2510 stack_end -= stack_end % @alignOf(Context);
2588 assert(stack_end >= stack_addr);2511 assert(stack_end >= stack_addr);
2589 const context_ptr = @alignCast(@alignOf(Context), @intToPtr(&Context, stack_end));2512 const context_ptr = @alignCast(@alignOf(Context), @intToPtr(*Context, stack_end));
2590 context_ptr.* = context;2513 context_ptr.* = context;
2591 arg = stack_end;2514 arg = stack_end;
2592 }2515 }
...@@ -2594,7 +2517,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread...@@ -2594,7 +2517,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread
2594 stack_end -= @sizeOf(Thread);2517 stack_end -= @sizeOf(Thread);
2595 stack_end -= stack_end % @alignOf(Thread);2518 stack_end -= stack_end % @alignOf(Thread);
2596 assert(stack_end >= stack_addr);2519 assert(stack_end >= stack_addr);
2597 const thread_ptr = @alignCast(@alignOf(Thread), @intToPtr(&Thread, stack_end));2520 const thread_ptr = @alignCast(@alignOf(Thread), @intToPtr(*Thread, stack_end));
25982521
2599 thread_ptr.data.stack_addr = stack_addr;2522 thread_ptr.data.stack_addr = stack_addr;
2600 thread_ptr.data.stack_len = mmap_len;2523 thread_ptr.data.stack_len = mmap_len;
...@@ -2610,9 +2533,9 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread...@@ -2610,9 +2533,9 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread
26102533
2611 // align to page2534 // align to page
2612 stack_end -= stack_end % os.page_size;2535 stack_end -= stack_end % os.page_size;
2613 assert(c.pthread_attr_setstack(&attr, @intToPtr(&c_void, stack_addr), stack_end - stack_addr) == 0);2536 assert(c.pthread_attr_setstack(&attr, @intToPtr([*]c_void, stack_addr), stack_end - stack_addr) == 0);
26142537
2615 const err = c.pthread_create(&thread_ptr.data.handle, &attr, MainFuncs.posixThreadMain, @intToPtr(&c_void, arg));2538 const err = c.pthread_create(&thread_ptr.data.handle, &attr, MainFuncs.posixThreadMain, @intToPtr(*c_void, arg));
2616 switch (err) {2539 switch (err) {
2617 0 => return thread_ptr,2540 0 => return thread_ptr,
2618 posix.EAGAIN => return SpawnThreadError.SystemResources,2541 posix.EAGAIN => return SpawnThreadError.SystemResources,
std/os/linux/errno.zig+425-144
...@@ -1,146 +1,427 @@...@@ -1,146 +1,427 @@
1pub const EPERM = 1; /// Operation not permitted1/// Operation not permitted
2pub const ENOENT = 2; /// No such file or directory2pub const EPERM = 1;
3pub const ESRCH = 3; /// No such process3
4pub const EINTR = 4; /// Interrupted system call4/// No such file or directory
5pub const EIO = 5; /// I/O error5pub const ENOENT = 2;
6pub const ENXIO = 6; /// No such device or address6
7pub const E2BIG = 7; /// Arg list too long7/// No such process
8pub const ENOEXEC = 8; /// Exec format error8pub const ESRCH = 3;
9pub const EBADF = 9; /// Bad file number9
10pub const ECHILD = 10; /// No child processes10/// Interrupted system call
11pub const EAGAIN = 11; /// Try again11pub const EINTR = 4;
12pub const ENOMEM = 12; /// Out of memory12
13pub const EACCES = 13; /// Permission denied13/// I/O error
14pub const EFAULT = 14; /// Bad address14pub const EIO = 5;
15pub const ENOTBLK = 15; /// Block device required15
16pub const EBUSY = 16; /// Device or resource busy16/// No such device or address
17pub const EEXIST = 17; /// File exists17pub const ENXIO = 6;
18pub const EXDEV = 18; /// Cross-device link18
19pub const ENODEV = 19; /// No such device19/// Arg list too long
20pub const ENOTDIR = 20; /// Not a directory20pub const E2BIG = 7;
21pub const EISDIR = 21; /// Is a directory21
22pub const EINVAL = 22; /// Invalid argument22/// Exec format error
23pub const ENFILE = 23; /// File table overflow23pub const ENOEXEC = 8;
24pub const EMFILE = 24; /// Too many open files24
25pub const ENOTTY = 25; /// Not a typewriter25/// Bad file number
26pub const ETXTBSY = 26; /// Text file busy26pub const EBADF = 9;
27pub const EFBIG = 27; /// File too large27
28pub const ENOSPC = 28; /// No space left on device28/// No child processes
29pub const ESPIPE = 29; /// Illegal seek29pub const ECHILD = 10;
30pub const EROFS = 30; /// Read-only file system30
31pub const EMLINK = 31; /// Too many links31/// Try again
32pub const EPIPE = 32; /// Broken pipe32pub const EAGAIN = 11;
33pub const EDOM = 33; /// Math argument out of domain of func33
34pub const ERANGE = 34; /// Math result not representable34/// Out of memory
35pub const EDEADLK = 35; /// Resource deadlock would occur35pub const ENOMEM = 12;
36pub const ENAMETOOLONG = 36; /// File name too long36
37pub const ENOLCK = 37; /// No record locks available37/// Permission denied
38pub const ENOSYS = 38; /// Function not implemented38pub const EACCES = 13;
39pub const ENOTEMPTY = 39; /// Directory not empty39
40pub const ELOOP = 40; /// Too many symbolic links encountered40/// Bad address
41pub const EWOULDBLOCK = EAGAIN; /// Operation would block41pub const EFAULT = 14;
42pub const ENOMSG = 42; /// No message of desired type42
43pub const EIDRM = 43; /// Identifier removed43/// Block device required
44pub const ECHRNG = 44; /// Channel number out of range44pub const ENOTBLK = 15;
45pub const EL2NSYNC = 45; /// Level 2 not synchronized45
46pub const EL3HLT = 46; /// Level 3 halted46/// Device or resource busy
47pub const EL3RST = 47; /// Level 3 reset47pub const EBUSY = 16;
48pub const ELNRNG = 48; /// Link number out of range48
49pub const EUNATCH = 49; /// Protocol driver not attached49/// File exists
50pub const ENOCSI = 50; /// No CSI structure available50pub const EEXIST = 17;
51pub const EL2HLT = 51; /// Level 2 halted51
52pub const EBADE = 52; /// Invalid exchange52/// Cross-device link
53pub const EBADR = 53; /// Invalid request descriptor53pub const EXDEV = 18;
54pub const EXFULL = 54; /// Exchange full54
55pub const ENOANO = 55; /// No anode55/// No such device
56pub const EBADRQC = 56; /// Invalid request code56pub const ENODEV = 19;
57pub const EBADSLT = 57; /// Invalid slot57
5858/// Not a directory
59pub const EBFONT = 59; /// Bad font file format59pub const ENOTDIR = 20;
60pub const ENOSTR = 60; /// Device not a stream60
61pub const ENODATA = 61; /// No data available61/// Is a directory
62pub const ETIME = 62; /// Timer expired62pub const EISDIR = 21;
63pub const ENOSR = 63; /// Out of streams resources63
64pub const ENONET = 64; /// Machine is not on the network64/// Invalid argument
65pub const ENOPKG = 65; /// Package not installed65pub const EINVAL = 22;
66pub const EREMOTE = 66; /// Object is remote66
67pub const ENOLINK = 67; /// Link has been severed67/// File table overflow
68pub const EADV = 68; /// Advertise error68pub const ENFILE = 23;
69pub const ESRMNT = 69; /// Srmount error69
70pub const ECOMM = 70; /// Communication error on send70/// Too many open files
71pub const EPROTO = 71; /// Protocol error71pub const EMFILE = 24;
72pub const EMULTIHOP = 72; /// Multihop attempted72
73pub const EDOTDOT = 73; /// RFS specific error73/// Not a typewriter
74pub const EBADMSG = 74; /// Not a data message74pub const ENOTTY = 25;
75pub const EOVERFLOW = 75; /// Value too large for defined data type75
76pub const ENOTUNIQ = 76; /// Name not unique on network76/// Text file busy
77pub const EBADFD = 77; /// File descriptor in bad state77pub const ETXTBSY = 26;
78pub const EREMCHG = 78; /// Remote address changed78
79pub const ELIBACC = 79; /// Can not access a needed shared library79/// File too large
80pub const ELIBBAD = 80; /// Accessing a corrupted shared library80pub const EFBIG = 27;
81pub const ELIBSCN = 81; /// .lib section in a.out corrupted81
82pub const ELIBMAX = 82; /// Attempting to link in too many shared libraries82/// No space left on device
83pub const ELIBEXEC = 83; /// Cannot exec a shared library directly83pub const ENOSPC = 28;
84pub const EILSEQ = 84; /// Illegal byte sequence84
85pub const ERESTART = 85; /// Interrupted system call should be restarted85/// Illegal seek
86pub const ESTRPIPE = 86; /// Streams pipe error86pub const ESPIPE = 29;
87pub const EUSERS = 87; /// Too many users87
88pub const ENOTSOCK = 88; /// Socket operation on non-socket88/// Read-only file system
89pub const EDESTADDRREQ = 89; /// Destination address required89pub const EROFS = 30;
90pub const EMSGSIZE = 90; /// Message too long90
91pub const EPROTOTYPE = 91; /// Protocol wrong type for socket91/// Too many links
92pub const ENOPROTOOPT = 92; /// Protocol not available92pub const EMLINK = 31;
93pub const EPROTONOSUPPORT = 93; /// Protocol not supported93
94pub const ESOCKTNOSUPPORT = 94; /// Socket type not supported94/// Broken pipe
95pub const EOPNOTSUPP = 95; /// Operation not supported on transport endpoint95pub const EPIPE = 32;
96pub const EPFNOSUPPORT = 96; /// Protocol family not supported96
97pub const EAFNOSUPPORT = 97; /// Address family not supported by protocol97/// Math argument out of domain of func
98pub const EADDRINUSE = 98; /// Address already in use98pub const EDOM = 33;
99pub const EADDRNOTAVAIL = 99; /// Cannot assign requested address99
100pub const ENETDOWN = 100; /// Network is down100/// Math result not representable
101pub const ENETUNREACH = 101; /// Network is unreachable101pub const ERANGE = 34;
102pub const ENETRESET = 102; /// Network dropped connection because of reset102
103pub const ECONNABORTED = 103; /// Software caused connection abort103/// Resource deadlock would occur
104pub const ECONNRESET = 104; /// Connection reset by peer104pub const EDEADLK = 35;
105pub const ENOBUFS = 105; /// No buffer space available105
106pub const EISCONN = 106; /// Transport endpoint is already connected106/// File name too long
107pub const ENOTCONN = 107; /// Transport endpoint is not connected107pub const ENAMETOOLONG = 36;
108pub const ESHUTDOWN = 108; /// Cannot send after transport endpoint shutdown108
109pub const ETOOMANYREFS = 109; /// Too many references: cannot splice109/// No record locks available
110pub const ETIMEDOUT = 110; /// Connection timed out110pub const ENOLCK = 37;
111pub const ECONNREFUSED = 111; /// Connection refused111
112pub const EHOSTDOWN = 112; /// Host is down112/// Function not implemented
113pub const EHOSTUNREACH = 113; /// No route to host113pub const ENOSYS = 38;
114pub const EALREADY = 114; /// Operation already in progress114
115pub const EINPROGRESS = 115; /// Operation now in progress115/// Directory not empty
116pub const ESTALE = 116; /// Stale NFS file handle116pub const ENOTEMPTY = 39;
117pub const EUCLEAN = 117; /// Structure needs cleaning117
118pub const ENOTNAM = 118; /// Not a XENIX named type file118/// Too many symbolic links encountered
119pub const ENAVAIL = 119; /// No XENIX semaphores available119pub const ELOOP = 40;
120pub const EISNAM = 120; /// Is a named type file120
121pub const EREMOTEIO = 121; /// Remote I/O error121/// Operation would block
122pub const EDQUOT = 122; /// Quota exceeded122pub const EWOULDBLOCK = EAGAIN;
123123
124pub const ENOMEDIUM = 123; /// No medium found124/// No message of desired type
125pub const EMEDIUMTYPE = 124; /// Wrong medium type125pub const ENOMSG = 42;
126
127/// Identifier removed
128pub const EIDRM = 43;
129
130/// Channel number out of range
131pub const ECHRNG = 44;
132
133/// Level 2 not synchronized
134pub const EL2NSYNC = 45;
135
136/// Level 3 halted
137pub const EL3HLT = 46;
138
139/// Level 3 reset
140pub const EL3RST = 47;
141
142/// Link number out of range
143pub const ELNRNG = 48;
144
145/// Protocol driver not attached
146pub const EUNATCH = 49;
147
148/// No CSI structure available
149pub const ENOCSI = 50;
150
151/// Level 2 halted
152pub const EL2HLT = 51;
153
154/// Invalid exchange
155pub const EBADE = 52;
156
157/// Invalid request descriptor
158pub const EBADR = 53;
159
160/// Exchange full
161pub const EXFULL = 54;
162
163/// No anode
164pub const ENOANO = 55;
165
166/// Invalid request code
167pub const EBADRQC = 56;
168
169/// Invalid slot
170pub const EBADSLT = 57;
171
172/// Bad font file format
173pub const EBFONT = 59;
174
175/// Device not a stream
176pub const ENOSTR = 60;
177
178/// No data available
179pub const ENODATA = 61;
180
181/// Timer expired
182pub const ETIME = 62;
183
184/// Out of streams resources
185pub const ENOSR = 63;
186
187/// Machine is not on the network
188pub const ENONET = 64;
189
190/// Package not installed
191pub const ENOPKG = 65;
192
193/// Object is remote
194pub const EREMOTE = 66;
195
196/// Link has been severed
197pub const ENOLINK = 67;
198
199/// Advertise error
200pub const EADV = 68;
201
202/// Srmount error
203pub const ESRMNT = 69;
204
205/// Communication error on send
206pub const ECOMM = 70;
207
208/// Protocol error
209pub const EPROTO = 71;
210
211/// Multihop attempted
212pub const EMULTIHOP = 72;
213
214/// RFS specific error
215pub const EDOTDOT = 73;
216
217/// Not a data message
218pub const EBADMSG = 74;
219
220/// Value too large for defined data type
221pub const EOVERFLOW = 75;
222
223/// Name not unique on network
224pub const ENOTUNIQ = 76;
225
226/// File descriptor in bad state
227pub const EBADFD = 77;
228
229/// Remote address changed
230pub const EREMCHG = 78;
231
232/// Can not access a needed shared library
233pub const ELIBACC = 79;
234
235/// Accessing a corrupted shared library
236pub const ELIBBAD = 80;
237
238/// .lib section in a.out corrupted
239pub const ELIBSCN = 81;
240
241/// Attempting to link in too many shared libraries
242pub const ELIBMAX = 82;
243
244/// Cannot exec a shared library directly
245pub const ELIBEXEC = 83;
246
247/// Illegal byte sequence
248pub const EILSEQ = 84;
249
250/// Interrupted system call should be restarted
251pub const ERESTART = 85;
252
253/// Streams pipe error
254pub const ESTRPIPE = 86;
255
256/// Too many users
257pub const EUSERS = 87;
258
259/// Socket operation on non-socket
260pub const ENOTSOCK = 88;
261
262/// Destination address required
263pub const EDESTADDRREQ = 89;
264
265/// Message too long
266pub const EMSGSIZE = 90;
267
268/// Protocol wrong type for socket
269pub const EPROTOTYPE = 91;
270
271/// Protocol not available
272pub const ENOPROTOOPT = 92;
273
274/// Protocol not supported
275pub const EPROTONOSUPPORT = 93;
276
277/// Socket type not supported
278pub const ESOCKTNOSUPPORT = 94;
279
280/// Operation not supported on transport endpoint
281pub const EOPNOTSUPP = 95;
282
283/// Protocol family not supported
284pub const EPFNOSUPPORT = 96;
285
286/// Address family not supported by protocol
287pub const EAFNOSUPPORT = 97;
288
289/// Address already in use
290pub const EADDRINUSE = 98;
291
292/// Cannot assign requested address
293pub const EADDRNOTAVAIL = 99;
294
295/// Network is down
296pub const ENETDOWN = 100;
297
298/// Network is unreachable
299pub const ENETUNREACH = 101;
300
301/// Network dropped connection because of reset
302pub const ENETRESET = 102;
303
304/// Software caused connection abort
305pub const ECONNABORTED = 103;
306
307/// Connection reset by peer
308pub const ECONNRESET = 104;
309
310/// No buffer space available
311pub const ENOBUFS = 105;
312
313/// Transport endpoint is already connected
314pub const EISCONN = 106;
315
316/// Transport endpoint is not connected
317pub const ENOTCONN = 107;
318
319/// Cannot send after transport endpoint shutdown
320pub const ESHUTDOWN = 108;
321
322/// Too many references: cannot splice
323pub const ETOOMANYREFS = 109;
324
325/// Connection timed out
326pub const ETIMEDOUT = 110;
327
328/// Connection refused
329pub const ECONNREFUSED = 111;
330
331/// Host is down
332pub const EHOSTDOWN = 112;
333
334/// No route to host
335pub const EHOSTUNREACH = 113;
336
337/// Operation already in progress
338pub const EALREADY = 114;
339
340/// Operation now in progress
341pub const EINPROGRESS = 115;
342
343/// Stale NFS file handle
344pub const ESTALE = 116;
345
346/// Structure needs cleaning
347pub const EUCLEAN = 117;
348
349/// Not a XENIX named type file
350pub const ENOTNAM = 118;
351
352/// No XENIX semaphores available
353pub const ENAVAIL = 119;
354
355/// Is a named type file
356pub const EISNAM = 120;
357
358/// Remote I/O error
359pub const EREMOTEIO = 121;
360
361/// Quota exceeded
362pub const EDQUOT = 122;
363
364/// No medium found
365pub const ENOMEDIUM = 123;
366
367/// Wrong medium type
368pub const EMEDIUMTYPE = 124;
126369
127// nameserver query return codes370// nameserver query return codes
128pub const ENSROK = 0; /// DNS server returned answer with no data371
129pub const ENSRNODATA = 160; /// DNS server returned answer with no data372/// DNS server returned answer with no data
130pub const ENSRFORMERR = 161; /// DNS server claims query was misformatted373pub const ENSROK = 0;
131pub const ENSRSERVFAIL = 162; /// DNS server returned general failure374
132pub const ENSRNOTFOUND = 163; /// Domain name not found375/// DNS server returned answer with no data
133pub const ENSRNOTIMP = 164; /// DNS server does not implement requested operation376pub const ENSRNODATA = 160;
134pub const ENSRREFUSED = 165; /// DNS server refused query377
135pub const ENSRBADQUERY = 166; /// Misformatted DNS query378/// DNS server claims query was misformatted
136pub const ENSRBADNAME = 167; /// Misformatted domain name379pub const ENSRFORMERR = 161;
137pub const ENSRBADFAMILY = 168; /// Unsupported address family380
138pub const ENSRBADRESP = 169; /// Misformatted DNS reply381/// DNS server returned general failure
139pub const ENSRCONNREFUSED = 170; /// Could not contact DNS servers382pub const ENSRSERVFAIL = 162;
140pub const ENSRTIMEOUT = 171; /// Timeout while contacting DNS servers383
141pub const ENSROF = 172; /// End of file384/// Domain name not found
142pub const ENSRFILE = 173; /// Error reading file385pub const ENSRNOTFOUND = 163;
143pub const ENSRNOMEM = 174; /// Out of memory386
144pub const ENSRDESTRUCTION = 175; /// Application terminated lookup387/// DNS server does not implement requested operation
145pub const ENSRQUERYDOMAINTOOLONG = 176; /// Domain name is too long388pub const ENSRNOTIMP = 164;
146pub const ENSRCNAMELOOP = 177; /// Domain name is too long389
390/// DNS server refused query
391pub const ENSRREFUSED = 165;
392
393/// Misformatted DNS query
394pub const ENSRBADQUERY = 166;
395
396/// Misformatted domain name
397pub const ENSRBADNAME = 167;
398
399/// Unsupported address family
400pub const ENSRBADFAMILY = 168;
401
402/// Misformatted DNS reply
403pub const ENSRBADRESP = 169;
404
405/// Could not contact DNS servers
406pub const ENSRCONNREFUSED = 170;
407
408/// Timeout while contacting DNS servers
409pub const ENSRTIMEOUT = 171;
410
411/// End of file
412pub const ENSROF = 172;
413
414/// Error reading file
415pub const ENSRFILE = 173;
416
417/// Out of memory
418pub const ENSRNOMEM = 174;
419
420/// Application terminated lookup
421pub const ENSRDESTRUCTION = 175;
422
423/// Domain name is too long
424pub const ENSRQUERYDOMAINTOOLONG = 176;
425
426/// Domain name is too long
427pub const ENSRCNAMELOOP = 177;
std/os/linux/index.zig+123-95
...@@ -665,15 +665,18 @@ pub fn dup2(old: i32, new: i32) usize {...@@ -665,15 +665,18 @@ pub fn dup2(old: i32, new: i32) usize {
665 return syscall2(SYS_dup2, usize(old), usize(new));665 return syscall2(SYS_dup2, usize(old), usize(new));
666}666}
667667
668pub fn chdir(path: &const u8) usize {668// TODO https://github.com/ziglang/zig/issues/265
669pub fn chdir(path: [*]const u8) usize {
669 return syscall1(SYS_chdir, @ptrToInt(path));670 return syscall1(SYS_chdir, @ptrToInt(path));
670}671}
671672
672pub fn chroot(path: &const u8) usize {673// TODO https://github.com/ziglang/zig/issues/265
674pub fn chroot(path: [*]const u8) usize {
673 return syscall1(SYS_chroot, @ptrToInt(path));675 return syscall1(SYS_chroot, @ptrToInt(path));
674}676}
675677
676pub fn execve(path: &const u8, argv: &const ?&const u8, envp: &const ?&const u8) usize {678// TODO https://github.com/ziglang/zig/issues/265
679pub fn execve(path: [*]const u8, argv: [*]const ?[*]const u8, envp: [*]const ?[*]const u8) usize {
677 return syscall3(SYS_execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp));680 return syscall3(SYS_execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp));
678}681}
679682
...@@ -681,15 +684,15 @@ pub fn fork() usize {...@@ -681,15 +684,15 @@ pub fn fork() usize {
681 return syscall0(SYS_fork);684 return syscall0(SYS_fork);
682}685}
683686
684pub fn futex_wait(uaddr: usize, futex_op: u32, val: i32, timeout: ?&timespec) usize {687pub fn futex_wait(uaddr: usize, futex_op: u32, val: i32, timeout: ?*timespec) usize {
685 return syscall4(SYS_futex, uaddr, futex_op, @bitCast(u32, val), @ptrToInt(timeout));688 return syscall4(SYS_futex, uaddr, futex_op, @bitCast(u32, val), @ptrToInt(timeout));
686}689}
687690
688pub fn getcwd(buf: &u8, size: usize) usize {691pub fn getcwd(buf: [*]u8, size: usize) usize {
689 return syscall2(SYS_getcwd, @ptrToInt(buf), size);692 return syscall2(SYS_getcwd, @ptrToInt(buf), size);
690}693}
691694
692pub fn getdents(fd: i32, dirp: &u8, count: usize) usize {695pub fn getdents(fd: i32, dirp: [*]u8, count: usize) usize {
693 return syscall3(SYS_getdents, usize(fd), @ptrToInt(dirp), count);696 return syscall3(SYS_getdents, usize(fd), @ptrToInt(dirp), count);
694}697}
695698
...@@ -698,27 +701,32 @@ pub fn isatty(fd: i32) bool {...@@ -698,27 +701,32 @@ pub fn isatty(fd: i32) bool {
698 return syscall3(SYS_ioctl, usize(fd), TIOCGWINSZ, @ptrToInt(&wsz)) == 0;701 return syscall3(SYS_ioctl, usize(fd), TIOCGWINSZ, @ptrToInt(&wsz)) == 0;
699}702}
700703
701pub fn readlink(noalias path: &const u8, noalias buf_ptr: &u8, buf_len: usize) usize {704// TODO https://github.com/ziglang/zig/issues/265
705pub fn readlink(noalias path: [*]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {
702 return syscall3(SYS_readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);706 return syscall3(SYS_readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
703}707}
704708
705pub fn mkdir(path: &const u8, mode: u32) usize {709// TODO https://github.com/ziglang/zig/issues/265
710pub fn mkdir(path: [*]const u8, mode: u32) usize {
706 return syscall2(SYS_mkdir, @ptrToInt(path), mode);711 return syscall2(SYS_mkdir, @ptrToInt(path), mode);
707}712}
708713
709pub fn mount(special: &const u8, dir: &const u8, fstype: &const u8, flags: usize, data: usize) usize {714// TODO https://github.com/ziglang/zig/issues/265
715pub fn mount(special: [*]const u8, dir: [*]const u8, fstype: [*]const u8, flags: usize, data: usize) usize {
710 return syscall5(SYS_mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data);716 return syscall5(SYS_mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data);
711}717}
712718
713pub fn umount(special: &const u8) usize {719// TODO https://github.com/ziglang/zig/issues/265
720pub fn umount(special: [*]const u8) usize {
714 return syscall2(SYS_umount2, @ptrToInt(special), 0);721 return syscall2(SYS_umount2, @ptrToInt(special), 0);
715}722}
716723
717pub fn umount2(special: &const u8, flags: u32) usize {724// TODO https://github.com/ziglang/zig/issues/265
725pub fn umount2(special: [*]const u8, flags: u32) usize {
718 return syscall2(SYS_umount2, @ptrToInt(special), flags);726 return syscall2(SYS_umount2, @ptrToInt(special), flags);
719}727}
720728
721pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize {729pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize {
722 return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), @bitCast(usize, offset));730 return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), @bitCast(usize, offset));
723}731}
724732
...@@ -726,60 +734,67 @@ pub fn munmap(address: usize, length: usize) usize {...@@ -726,60 +734,67 @@ pub fn munmap(address: usize, length: usize) usize {
726 return syscall2(SYS_munmap, address, length);734 return syscall2(SYS_munmap, address, length);
727}735}
728736
729pub fn read(fd: i32, buf: &u8, count: usize) usize {737pub fn read(fd: i32, buf: [*]u8, count: usize) usize {
730 return syscall3(SYS_read, usize(fd), @ptrToInt(buf), count);738 return syscall3(SYS_read, usize(fd), @ptrToInt(buf), count);
731}739}
732740
733pub fn rmdir(path: &const u8) usize {741// TODO https://github.com/ziglang/zig/issues/265
742pub fn rmdir(path: [*]const u8) usize {
734 return syscall1(SYS_rmdir, @ptrToInt(path));743 return syscall1(SYS_rmdir, @ptrToInt(path));
735}744}
736745
737pub fn symlink(existing: &const u8, new: &const u8) usize {746// TODO https://github.com/ziglang/zig/issues/265
747pub fn symlink(existing: [*]const u8, new: [*]const u8) usize {
738 return syscall2(SYS_symlink, @ptrToInt(existing), @ptrToInt(new));748 return syscall2(SYS_symlink, @ptrToInt(existing), @ptrToInt(new));
739}749}
740750
741pub fn pread(fd: i32, buf: &u8, count: usize, offset: usize) usize {751pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: usize) usize {
742 return syscall4(SYS_pread, usize(fd), @ptrToInt(buf), count, offset);752 return syscall4(SYS_pread, usize(fd), @ptrToInt(buf), count, offset);
743}753}
744754
745pub fn access(path: &const u8, mode: u32) usize {755// TODO https://github.com/ziglang/zig/issues/265
756pub fn access(path: [*]const u8, mode: u32) usize {
746 return syscall2(SYS_access, @ptrToInt(path), mode);757 return syscall2(SYS_access, @ptrToInt(path), mode);
747}758}
748759
749pub fn pipe(fd: &[2]i32) usize {760pub fn pipe(fd: *[2]i32) usize {
750 return pipe2(fd, 0);761 return pipe2(fd, 0);
751}762}
752763
753pub fn pipe2(fd: &[2]i32, flags: usize) usize {764pub fn pipe2(fd: *[2]i32, flags: usize) usize {
754 return syscall2(SYS_pipe2, @ptrToInt(fd), flags);765 return syscall2(SYS_pipe2, @ptrToInt(fd), flags);
755}766}
756767
757pub fn write(fd: i32, buf: &const u8, count: usize) usize {768pub fn write(fd: i32, buf: [*]const u8, count: usize) usize {
758 return syscall3(SYS_write, usize(fd), @ptrToInt(buf), count);769 return syscall3(SYS_write, usize(fd), @ptrToInt(buf), count);
759}770}
760771
761pub fn pwrite(fd: i32, buf: &const u8, count: usize, offset: usize) usize {772pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {
762 return syscall4(SYS_pwrite, usize(fd), @ptrToInt(buf), count, offset);773 return syscall4(SYS_pwrite, usize(fd), @ptrToInt(buf), count, offset);
763}774}
764775
765pub fn rename(old: &const u8, new: &const u8) usize {776// TODO https://github.com/ziglang/zig/issues/265
777pub fn rename(old: [*]const u8, new: [*]const u8) usize {
766 return syscall2(SYS_rename, @ptrToInt(old), @ptrToInt(new));778 return syscall2(SYS_rename, @ptrToInt(old), @ptrToInt(new));
767}779}
768780
769pub fn open(path: &const u8, flags: u32, perm: usize) usize {781// TODO https://github.com/ziglang/zig/issues/265
782pub fn open(path: [*]const u8, flags: u32, perm: usize) usize {
770 return syscall3(SYS_open, @ptrToInt(path), flags, perm);783 return syscall3(SYS_open, @ptrToInt(path), flags, perm);
771}784}
772785
773pub fn create(path: &const u8, perm: usize) usize {786// TODO https://github.com/ziglang/zig/issues/265
787pub fn create(path: [*]const u8, perm: usize) usize {
774 return syscall2(SYS_creat, @ptrToInt(path), perm);788 return syscall2(SYS_creat, @ptrToInt(path), perm);
775}789}
776790
777pub fn openat(dirfd: i32, path: &const u8, flags: usize, mode: usize) usize {791// TODO https://github.com/ziglang/zig/issues/265
792pub fn openat(dirfd: i32, path: [*]const u8, flags: usize, mode: usize) usize {
778 return syscall4(SYS_openat, usize(dirfd), @ptrToInt(path), flags, mode);793 return syscall4(SYS_openat, usize(dirfd), @ptrToInt(path), flags, mode);
779}794}
780795
781/// See also `clone` (from the arch-specific include)796/// See also `clone` (from the arch-specific include)
782pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: &i32, child_tid: &i32, newtls: usize) usize {797pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: *i32, child_tid: *i32, newtls: usize) usize {
783 return syscall5(SYS_clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls);798 return syscall5(SYS_clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls);
784}799}
785800
...@@ -801,7 +816,7 @@ pub fn exit(status: i32) noreturn {...@@ -801,7 +816,7 @@ pub fn exit(status: i32) noreturn {
801 unreachable;816 unreachable;
802}817}
803818
804pub fn getrandom(buf: &u8, count: usize, flags: u32) usize {819pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize {
805 return syscall3(SYS_getrandom, @ptrToInt(buf), count, usize(flags));820 return syscall3(SYS_getrandom, @ptrToInt(buf), count, usize(flags));
806}821}
807822
...@@ -809,22 +824,22 @@ pub fn kill(pid: i32, sig: i32) usize {...@@ -809,22 +824,22 @@ pub fn kill(pid: i32, sig: i32) usize {
809 return syscall2(SYS_kill, @bitCast(usize, isize(pid)), usize(sig));824 return syscall2(SYS_kill, @bitCast(usize, isize(pid)), usize(sig));
810}825}
811826
812pub fn unlink(path: &const u8) usize {827// TODO https://github.com/ziglang/zig/issues/265
828pub fn unlink(path: [*]const u8) usize {
813 return syscall1(SYS_unlink, @ptrToInt(path));829 return syscall1(SYS_unlink, @ptrToInt(path));
814}830}
815831
816pub fn waitpid(pid: i32, status: &i32, options: i32) usize {832pub fn waitpid(pid: i32, status: *i32, options: i32) usize {
817 return syscall4(SYS_wait4, @bitCast(usize, isize(pid)), @ptrToInt(status), @bitCast(usize, isize(options)), 0);833 return syscall4(SYS_wait4, @bitCast(usize, isize(pid)), @ptrToInt(status), @bitCast(usize, isize(options)), 0);
818}834}
819835
820pub fn clock_gettime(clk_id: i32, tp: &timespec) usize {836pub fn clock_gettime(clk_id: i32, tp: *timespec) usize {
821 if (VDSO_CGT_SYM.len != 0) {837 if (VDSO_CGT_SYM.len != 0) {
822 const f = @atomicLoad(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, builtin.AtomicOrder.Unordered);838 const f = @atomicLoad(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, builtin.AtomicOrder.Unordered);
823 if (@ptrToInt(f) != 0) {839 if (@ptrToInt(f) != 0) {
824 const rc = f(clk_id, tp);840 const rc = f(clk_id, tp);
825 switch (rc) {841 switch (rc) {
826 0,842 0, @bitCast(usize, isize(-EINVAL)) => return rc,
827 @bitCast(usize, isize(-EINVAL)) => return rc,
828 else => {},843 else => {},
829 }844 }
830 }845 }
...@@ -832,7 +847,7 @@ pub fn clock_gettime(clk_id: i32, tp: &timespec) usize {...@@ -832,7 +847,7 @@ pub fn clock_gettime(clk_id: i32, tp: &timespec) usize {
832 return syscall2(SYS_clock_gettime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));847 return syscall2(SYS_clock_gettime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
833}848}
834var vdso_clock_gettime = init_vdso_clock_gettime;849var vdso_clock_gettime = init_vdso_clock_gettime;
835extern fn init_vdso_clock_gettime(clk: i32, ts: &timespec) usize {850extern fn init_vdso_clock_gettime(clk: i32, ts: *timespec) usize {
836 const addr = vdso.lookup(VDSO_CGT_VER, VDSO_CGT_SYM);851 const addr = vdso.lookup(VDSO_CGT_VER, VDSO_CGT_SYM);
837 var f = @intToPtr(@typeOf(init_vdso_clock_gettime), addr);852 var f = @intToPtr(@typeOf(init_vdso_clock_gettime), addr);
838 _ = @cmpxchgStrong(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, init_vdso_clock_gettime, f, builtin.AtomicOrder.Monotonic, builtin.AtomicOrder.Monotonic);853 _ = @cmpxchgStrong(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, init_vdso_clock_gettime, f, builtin.AtomicOrder.Monotonic, builtin.AtomicOrder.Monotonic);
...@@ -840,23 +855,23 @@ extern fn init_vdso_clock_gettime(clk: i32, ts: &timespec) usize {...@@ -840,23 +855,23 @@ extern fn init_vdso_clock_gettime(clk: i32, ts: &timespec) usize {
840 return f(clk, ts);855 return f(clk, ts);
841}856}
842857
843pub fn clock_getres(clk_id: i32, tp: &timespec) usize {858pub fn clock_getres(clk_id: i32, tp: *timespec) usize {
844 return syscall2(SYS_clock_getres, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));859 return syscall2(SYS_clock_getres, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
845}860}
846861
847pub fn clock_settime(clk_id: i32, tp: &const timespec) usize {862pub fn clock_settime(clk_id: i32, tp: *const timespec) usize {
848 return syscall2(SYS_clock_settime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));863 return syscall2(SYS_clock_settime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp));
849}864}
850865
851pub fn gettimeofday(tv: &timeval, tz: &timezone) usize {866pub fn gettimeofday(tv: *timeval, tz: *timezone) usize {
852 return syscall2(SYS_gettimeofday, @ptrToInt(tv), @ptrToInt(tz));867 return syscall2(SYS_gettimeofday, @ptrToInt(tv), @ptrToInt(tz));
853}868}
854869
855pub fn settimeofday(tv: &const timeval, tz: &const timezone) usize {870pub fn settimeofday(tv: *const timeval, tz: *const timezone) usize {
856 return syscall2(SYS_settimeofday, @ptrToInt(tv), @ptrToInt(tz));871 return syscall2(SYS_settimeofday, @ptrToInt(tv), @ptrToInt(tz));
857}872}
858873
859pub fn nanosleep(req: &const timespec, rem: ?&timespec) usize {874pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize {
860 return syscall2(SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem));875 return syscall2(SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem));
861}876}
862877
...@@ -900,11 +915,11 @@ pub fn setegid(egid: u32) usize {...@@ -900,11 +915,11 @@ pub fn setegid(egid: u32) usize {
900 return syscall1(SYS_setegid, egid);915 return syscall1(SYS_setegid, egid);
901}916}
902917
903pub fn getresuid(ruid: &u32, euid: &u32, suid: &u32) usize {918pub fn getresuid(ruid: *u32, euid: *u32, suid: *u32) usize {
904 return syscall3(SYS_getresuid, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid));919 return syscall3(SYS_getresuid, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid));
905}920}
906921
907pub fn getresgid(rgid: &u32, egid: &u32, sgid: &u32) usize {922pub fn getresgid(rgid: *u32, egid: *u32, sgid: *u32) usize {
908 return syscall3(SYS_getresgid, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid));923 return syscall3(SYS_getresgid, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid));
909}924}
910925
...@@ -916,11 +931,11 @@ pub fn setresgid(rgid: u32, egid: u32, sgid: u32) usize {...@@ -916,11 +931,11 @@ pub fn setresgid(rgid: u32, egid: u32, sgid: u32) usize {
916 return syscall3(SYS_setresgid, rgid, egid, sgid);931 return syscall3(SYS_setresgid, rgid, egid, sgid);
917}932}
918933
919pub fn getgroups(size: usize, list: &u32) usize {934pub fn getgroups(size: usize, list: *u32) usize {
920 return syscall2(SYS_getgroups, size, @ptrToInt(list));935 return syscall2(SYS_getgroups, size, @ptrToInt(list));
921}936}
922937
923pub fn setgroups(size: usize, list: &const u32) usize {938pub fn setgroups(size: usize, list: *const u32) usize {
924 return syscall2(SYS_setgroups, size, @ptrToInt(list));939 return syscall2(SYS_setgroups, size, @ptrToInt(list));
925}940}
926941
...@@ -928,11 +943,11 @@ pub fn getpid() i32 {...@@ -928,11 +943,11 @@ pub fn getpid() i32 {
928 return @bitCast(i32, u32(syscall0(SYS_getpid)));943 return @bitCast(i32, u32(syscall0(SYS_getpid)));
929}944}
930945
931pub fn sigprocmask(flags: u32, noalias set: &const sigset_t, noalias oldset: ?&sigset_t) usize {946pub fn sigprocmask(flags: u32, noalias set: *const sigset_t, noalias oldset: ?*sigset_t) usize {
932 return syscall4(SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8);947 return syscall4(SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8);
933}948}
934949
935pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigaction) usize {950pub fn sigaction(sig: u6, noalias act: *const Sigaction, noalias oact: ?*Sigaction) usize {
936 assert(sig >= 1);951 assert(sig >= 1);
937 assert(sig != SIGKILL);952 assert(sig != SIGKILL);
938 assert(sig != SIGSTOP);953 assert(sig != SIGSTOP);
...@@ -940,10 +955,10 @@ pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigacti...@@ -940,10 +955,10 @@ pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigacti
940 .handler = act.handler,955 .handler = act.handler,
941 .flags = act.flags | SA_RESTORER,956 .flags = act.flags | SA_RESTORER,
942 .mask = undefined,957 .mask = undefined,
943 .restorer = @ptrCast(extern fn() void, restore_rt),958 .restorer = @ptrCast(extern fn () void, restore_rt),
944 };959 };
945 var ksa_old: k_sigaction = undefined;960 var ksa_old: k_sigaction = undefined;
946 @memcpy(@ptrCast(&u8, &ksa.mask), @ptrCast(&const u8, &act.mask), 8);961 @memcpy(@ptrCast([*]u8, &ksa.mask), @ptrCast([*]const u8, &act.mask), 8);
947 const result = syscall4(SYS_rt_sigaction, sig, @ptrToInt(&ksa), @ptrToInt(&ksa_old), @sizeOf(@typeOf(ksa.mask)));962 const result = syscall4(SYS_rt_sigaction, sig, @ptrToInt(&ksa), @ptrToInt(&ksa_old), @sizeOf(@typeOf(ksa.mask)));
948 const err = getErrno(result);963 const err = getErrno(result);
949 if (err != 0) {964 if (err != 0) {
...@@ -952,7 +967,7 @@ pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigacti...@@ -952,7 +967,7 @@ pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigacti
952 if (oact) |old| {967 if (oact) |old| {
953 old.handler = ksa_old.handler;968 old.handler = ksa_old.handler;
954 old.flags = @truncate(u32, ksa_old.flags);969 old.flags = @truncate(u32, ksa_old.flags);
955 @memcpy(@ptrCast(&u8, &old.mask), @ptrCast(&const u8, &ksa_old.mask), @sizeOf(@typeOf(ksa_old.mask)));970 @memcpy(@ptrCast([*]u8, &old.mask), @ptrCast([*]const u8, &ksa_old.mask), @sizeOf(@typeOf(ksa_old.mask)));
956 }971 }
957 return 0;972 return 0;
958}973}
...@@ -963,22 +978,22 @@ const all_mask = []usize{@maxValue(usize)};...@@ -963,22 +978,22 @@ const all_mask = []usize{@maxValue(usize)};
963const app_mask = []usize{0xfffffffc7fffffff};978const app_mask = []usize{0xfffffffc7fffffff};
964979
965const k_sigaction = extern struct {980const k_sigaction = extern struct {
966 handler: extern fn(i32) void,981 handler: extern fn (i32) void,
967 flags: usize,982 flags: usize,
968 restorer: extern fn() void,983 restorer: extern fn () void,
969 mask: [2]u32,984 mask: [2]u32,
970};985};
971986
972/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.987/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
973pub const Sigaction = struct {988pub const Sigaction = struct {
974 handler: extern fn(i32) void,989 handler: extern fn (i32) void,
975 mask: sigset_t,990 mask: sigset_t,
976 flags: u32,991 flags: u32,
977};992};
978993
979pub const SIG_ERR = @intToPtr(extern fn(i32) void, @maxValue(usize));994pub const SIG_ERR = @intToPtr(extern fn (i32) void, @maxValue(usize));
980pub const SIG_DFL = @intToPtr(extern fn(i32) void, 0);995pub const SIG_DFL = @intToPtr(extern fn (i32) void, 0);
981pub const SIG_IGN = @intToPtr(extern fn(i32) void, 1);996pub const SIG_IGN = @intToPtr(extern fn (i32) void, 1);
982pub const empty_sigset = []usize{0} ** sigset_t.len;997pub const empty_sigset = []usize{0} ** sigset_t.len;
983998
984pub fn raise(sig: i32) usize {999pub fn raise(sig: i32) usize {
...@@ -990,24 +1005,24 @@ pub fn raise(sig: i32) usize {...@@ -990,24 +1005,24 @@ pub fn raise(sig: i32) usize {
990 return ret;1005 return ret;
991}1006}
9921007
993fn blockAllSignals(set: &sigset_t) void {1008fn blockAllSignals(set: *sigset_t) void {
994 _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&all_mask), @ptrToInt(set), NSIG / 8);1009 _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&all_mask), @ptrToInt(set), NSIG / 8);
995}1010}
9961011
997fn blockAppSignals(set: &sigset_t) void {1012fn blockAppSignals(set: *sigset_t) void {
998 _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&app_mask), @ptrToInt(set), NSIG / 8);1013 _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&app_mask), @ptrToInt(set), NSIG / 8);
999}1014}
10001015
1001fn restoreSignals(set: &sigset_t) void {1016fn restoreSignals(set: *sigset_t) void {
1002 _ = syscall4(SYS_rt_sigprocmask, SIG_SETMASK, @ptrToInt(set), 0, NSIG / 8);1017 _ = syscall4(SYS_rt_sigprocmask, SIG_SETMASK, @ptrToInt(set), 0, NSIG / 8);
1003}1018}
10041019
1005pub fn sigaddset(set: &sigset_t, sig: u6) void {1020pub fn sigaddset(set: *sigset_t, sig: u6) void {
1006 const s = sig - 1;1021 const s = sig - 1;
1007 (set.*)[usize(s) / usize.bit_count] |= usize(1) << (s & (usize.bit_count - 1));1022 (set.*)[usize(s) / usize.bit_count] |= usize(1) << (s & (usize.bit_count - 1));
1008}1023}
10091024
1010pub fn sigismember(set: &const sigset_t, sig: u6) bool {1025pub fn sigismember(set: *const sigset_t, sig: u6) bool {
1011 const s = sig - 1;1026 const s = sig - 1;
1012 return ((set.*)[usize(s) / usize.bit_count] & (usize(1) << (s & (usize.bit_count - 1)))) != 0;1027 return ((set.*)[usize(s) / usize.bit_count] & (usize(1) << (s & (usize.bit_count - 1)))) != 0;
1013}1028}
...@@ -1037,15 +1052,15 @@ pub const sockaddr_in6 = extern struct {...@@ -1037,15 +1052,15 @@ pub const sockaddr_in6 = extern struct {
1037};1052};
10381053
1039pub const iovec = extern struct {1054pub const iovec = extern struct {
1040 iov_base: &u8,1055 iov_base: [*]u8,
1041 iov_len: usize,1056 iov_len: usize,
1042};1057};
10431058
1044pub fn getsockname(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t) usize {1059pub fn getsockname(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
1045 return syscall3(SYS_getsockname, usize(fd), @ptrToInt(addr), @ptrToInt(len));1060 return syscall3(SYS_getsockname, usize(fd), @ptrToInt(addr), @ptrToInt(len));
1046}1061}
10471062
1048pub fn getpeername(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t) usize {1063pub fn getpeername(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
1049 return syscall3(SYS_getpeername, usize(fd), @ptrToInt(addr), @ptrToInt(len));1064 return syscall3(SYS_getpeername, usize(fd), @ptrToInt(addr), @ptrToInt(len));
1050}1065}
10511066
...@@ -1053,27 +1068,27 @@ pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize {...@@ -1053,27 +1068,27 @@ pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize {
1053 return syscall3(SYS_socket, domain, socket_type, protocol);1068 return syscall3(SYS_socket, domain, socket_type, protocol);
1054}1069}
10551070
1056pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: &const u8, optlen: socklen_t) usize {1071pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: [*]const u8, optlen: socklen_t) usize {
1057 return syscall5(SYS_setsockopt, usize(fd), level, optname, usize(optval), @ptrToInt(optlen));1072 return syscall5(SYS_setsockopt, usize(fd), level, optname, usize(optval), @ptrToInt(optlen));
1058}1073}
10591074
1060pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: &u8, noalias optlen: &socklen_t) usize {1075pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: [*]u8, noalias optlen: *socklen_t) usize {
1061 return syscall5(SYS_getsockopt, usize(fd), level, optname, @ptrToInt(optval), @ptrToInt(optlen));1076 return syscall5(SYS_getsockopt, usize(fd), level, optname, @ptrToInt(optval), @ptrToInt(optlen));
1062}1077}
10631078
1064pub fn sendmsg(fd: i32, msg: &const msghdr, flags: u32) usize {1079pub fn sendmsg(fd: i32, msg: *const msghdr, flags: u32) usize {
1065 return syscall3(SYS_sendmsg, usize(fd), @ptrToInt(msg), flags);1080 return syscall3(SYS_sendmsg, usize(fd), @ptrToInt(msg), flags);
1066}1081}
10671082
1068pub fn connect(fd: i32, addr: &const sockaddr, len: socklen_t) usize {1083pub fn connect(fd: i32, addr: *const sockaddr, len: socklen_t) usize {
1069 return syscall3(SYS_connect, usize(fd), @ptrToInt(addr), usize(len));1084 return syscall3(SYS_connect, usize(fd), @ptrToInt(addr), usize(len));
1070}1085}
10711086
1072pub fn recvmsg(fd: i32, msg: &msghdr, flags: u32) usize {1087pub fn recvmsg(fd: i32, msg: *msghdr, flags: u32) usize {
1073 return syscall3(SYS_recvmsg, usize(fd), @ptrToInt(msg), flags);1088 return syscall3(SYS_recvmsg, usize(fd), @ptrToInt(msg), flags);
1074}1089}
10751090
1076pub fn recvfrom(fd: i32, noalias buf: &u8, len: usize, flags: u32, noalias addr: ?&sockaddr, noalias alen: ?&socklen_t) usize {1091pub fn recvfrom(fd: i32, noalias buf: [*]u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize {
1077 return syscall6(SYS_recvfrom, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen));1092 return syscall6(SYS_recvfrom, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen));
1078}1093}
10791094
...@@ -1081,7 +1096,7 @@ pub fn shutdown(fd: i32, how: i32) usize {...@@ -1081,7 +1096,7 @@ pub fn shutdown(fd: i32, how: i32) usize {
1081 return syscall2(SYS_shutdown, usize(fd), usize(how));1096 return syscall2(SYS_shutdown, usize(fd), usize(how));
1082}1097}
10831098
1084pub fn bind(fd: i32, addr: &const sockaddr, len: socklen_t) usize {1099pub fn bind(fd: i32, addr: *const sockaddr, len: socklen_t) usize {
1085 return syscall3(SYS_bind, usize(fd), @ptrToInt(addr), usize(len));1100 return syscall3(SYS_bind, usize(fd), @ptrToInt(addr), usize(len));
1086}1101}
10871102
...@@ -1089,79 +1104,92 @@ pub fn listen(fd: i32, backlog: u32) usize {...@@ -1089,79 +1104,92 @@ pub fn listen(fd: i32, backlog: u32) usize {
1089 return syscall2(SYS_listen, usize(fd), backlog);1104 return syscall2(SYS_listen, usize(fd), backlog);
1090}1105}
10911106
1092pub fn sendto(fd: i32, buf: &const u8, len: usize, flags: u32, addr: ?&const sockaddr, alen: socklen_t) usize {1107pub fn sendto(fd: i32, buf: [*]const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize {
1093 return syscall6(SYS_sendto, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), usize(alen));1108 return syscall6(SYS_sendto, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), usize(alen));
1094}1109}
10951110
1096pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usize {1111pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usize {
1097 return syscall4(SYS_socketpair, usize(domain), usize(socket_type), usize(protocol), @ptrToInt(&fd[0]));1112 return syscall4(SYS_socketpair, usize(domain), usize(socket_type), usize(protocol), @ptrToInt(*fd[0]));
1098}1113}
10991114
1100pub fn accept(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t) usize {1115pub fn accept(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
1101 return accept4(fd, addr, len, 0);1116 return accept4(fd, addr, len, 0);
1102}1117}
11031118
1104pub fn accept4(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t, flags: u32) usize {1119pub fn accept4(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t, flags: u32) usize {
1105 return syscall4(SYS_accept4, usize(fd), @ptrToInt(addr), @ptrToInt(len), flags);1120 return syscall4(SYS_accept4, usize(fd), @ptrToInt(addr), @ptrToInt(len), flags);
1106}1121}
11071122
1108pub fn fstat(fd: i32, stat_buf: &Stat) usize {1123pub fn fstat(fd: i32, stat_buf: *Stat) usize {
1109 return syscall2(SYS_fstat, usize(fd), @ptrToInt(stat_buf));1124 return syscall2(SYS_fstat, usize(fd), @ptrToInt(stat_buf));
1110}1125}
11111126
1112pub fn stat(pathname: &const u8, statbuf: &Stat) usize {1127// TODO https://github.com/ziglang/zig/issues/265
1128pub fn stat(pathname: [*]const u8, statbuf: *Stat) usize {
1113 return syscall2(SYS_stat, @ptrToInt(pathname), @ptrToInt(statbuf));1129 return syscall2(SYS_stat, @ptrToInt(pathname), @ptrToInt(statbuf));
1114}1130}
11151131
1116pub fn lstat(pathname: &const u8, statbuf: &Stat) usize {1132// TODO https://github.com/ziglang/zig/issues/265
1133pub fn lstat(pathname: [*]const u8, statbuf: *Stat) usize {
1117 return syscall2(SYS_lstat, @ptrToInt(pathname), @ptrToInt(statbuf));1134 return syscall2(SYS_lstat, @ptrToInt(pathname), @ptrToInt(statbuf));
1118}1135}
11191136
1120pub fn listxattr(path: &const u8, list: &u8, size: usize) usize {1137// TODO https://github.com/ziglang/zig/issues/265
1138pub fn listxattr(path: [*]const u8, list: [*]u8, size: usize) usize {
1121 return syscall3(SYS_listxattr, @ptrToInt(path), @ptrToInt(list), size);1139 return syscall3(SYS_listxattr, @ptrToInt(path), @ptrToInt(list), size);
1122}1140}
11231141
1124pub fn llistxattr(path: &const u8, list: &u8, size: usize) usize {1142// TODO https://github.com/ziglang/zig/issues/265
1143pub fn llistxattr(path: [*]const u8, list: [*]u8, size: usize) usize {
1125 return syscall3(SYS_llistxattr, @ptrToInt(path), @ptrToInt(list), size);1144 return syscall3(SYS_llistxattr, @ptrToInt(path), @ptrToInt(list), size);
1126}1145}
11271146
1128pub fn flistxattr(fd: usize, list: &u8, size: usize) usize {1147pub fn flistxattr(fd: usize, list: [*]u8, size: usize) usize {
1129 return syscall3(SYS_flistxattr, fd, @ptrToInt(list), size);1148 return syscall3(SYS_flistxattr, fd, @ptrToInt(list), size);
1130}1149}
11311150
1132pub fn getxattr(path: &const u8, name: &const u8, value: &void, size: usize) usize {1151// TODO https://github.com/ziglang/zig/issues/265
1152pub fn getxattr(path: [*]const u8, name: [*]const u8, value: [*]u8, size: usize) usize {
1133 return syscall4(SYS_getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);1153 return syscall4(SYS_getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);
1134}1154}
11351155
1136pub fn lgetxattr(path: &const u8, name: &const u8, value: &void, size: usize) usize {1156// TODO https://github.com/ziglang/zig/issues/265
1157pub fn lgetxattr(path: [*]const u8, name: [*]const u8, value: [*]u8, size: usize) usize {
1137 return syscall4(SYS_lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);1158 return syscall4(SYS_lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);
1138}1159}
11391160
1140pub fn fgetxattr(fd: usize, name: &const u8, value: &void, size: usize) usize {1161// TODO https://github.com/ziglang/zig/issues/265
1162pub fn fgetxattr(fd: usize, name: [*]const u8, value: [*]u8, size: usize) usize {
1141 return syscall4(SYS_lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size);1163 return syscall4(SYS_lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size);
1142}1164}
11431165
1144pub fn setxattr(path: &const u8, name: &const u8, value: &const void, size: usize, flags: usize) usize {1166// TODO https://github.com/ziglang/zig/issues/265
1167pub fn setxattr(path: [*]const u8, name: [*]const u8, value: *const void, size: usize, flags: usize) usize {
1145 return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);1168 return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);
1146}1169}
11471170
1148pub fn lsetxattr(path: &const u8, name: &const u8, value: &const void, size: usize, flags: usize) usize {1171// TODO https://github.com/ziglang/zig/issues/265
1172pub fn lsetxattr(path: [*]const u8, name: [*]const u8, value: *const void, size: usize, flags: usize) usize {
1149 return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);1173 return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);
1150}1174}
11511175
1152pub fn fsetxattr(fd: usize, name: &const u8, value: &const void, size: usize, flags: usize) usize {1176// TODO https://github.com/ziglang/zig/issues/265
1177pub fn fsetxattr(fd: usize, name: [*]const u8, value: *const void, size: usize, flags: usize) usize {
1153 return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags);1178 return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags);
1154}1179}
11551180
1156pub fn removexattr(path: &const u8, name: &const u8) usize {1181// TODO https://github.com/ziglang/zig/issues/265
1182pub fn removexattr(path: [*]const u8, name: [*]const u8) usize {
1157 return syscall2(SYS_removexattr, @ptrToInt(path), @ptrToInt(name));1183 return syscall2(SYS_removexattr, @ptrToInt(path), @ptrToInt(name));
1158}1184}
11591185
1160pub fn lremovexattr(path: &const u8, name: &const u8) usize {1186// TODO https://github.com/ziglang/zig/issues/265
1187pub fn lremovexattr(path: [*]const u8, name: [*]const u8) usize {
1161 return syscall2(SYS_lremovexattr, @ptrToInt(path), @ptrToInt(name));1188 return syscall2(SYS_lremovexattr, @ptrToInt(path), @ptrToInt(name));
1162}1189}
11631190
1164pub fn fremovexattr(fd: usize, name: &const u8) usize {1191// TODO https://github.com/ziglang/zig/issues/265
1192pub fn fremovexattr(fd: usize, name: [*]const u8) usize {
1165 return syscall2(SYS_fremovexattr, fd, @ptrToInt(name));1193 return syscall2(SYS_fremovexattr, fd, @ptrToInt(name));
1166}1194}
11671195
...@@ -1185,11 +1213,11 @@ pub fn epoll_create1(flags: usize) usize {...@@ -1185,11 +1213,11 @@ pub fn epoll_create1(flags: usize) usize {
1185 return syscall1(SYS_epoll_create1, flags);1213 return syscall1(SYS_epoll_create1, flags);
1186}1214}
11871215
1188pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: &epoll_event) usize {1216pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: *epoll_event) usize {
1189 return syscall4(SYS_epoll_ctl, usize(epoll_fd), usize(op), usize(fd), @ptrToInt(ev));1217 return syscall4(SYS_epoll_ctl, usize(epoll_fd), usize(op), usize(fd), @ptrToInt(ev));
1190}1218}
11911219
1192pub fn epoll_wait(epoll_fd: i32, events: &epoll_event, maxevents: u32, timeout: i32) usize {1220pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32) usize {
1193 return syscall4(SYS_epoll_wait, usize(epoll_fd), @ptrToInt(events), usize(maxevents), usize(timeout));1221 return syscall4(SYS_epoll_wait, usize(epoll_fd), @ptrToInt(events), usize(maxevents), usize(timeout));
1194}1222}
11951223
...@@ -1202,11 +1230,11 @@ pub const itimerspec = extern struct {...@@ -1202,11 +1230,11 @@ pub const itimerspec = extern struct {
1202 it_value: timespec,1230 it_value: timespec,
1203};1231};
12041232
1205pub fn timerfd_gettime(fd: i32, curr_value: &itimerspec) usize {1233pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) usize {
1206 return syscall2(SYS_timerfd_gettime, usize(fd), @ptrToInt(curr_value));1234 return syscall2(SYS_timerfd_gettime, usize(fd), @ptrToInt(curr_value));
1207}1235}
12081236
1209pub fn timerfd_settime(fd: i32, flags: u32, new_value: &const itimerspec, old_value: ?&itimerspec) usize {1237pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const itimerspec, old_value: ?*itimerspec) usize {
1210 return syscall4(SYS_timerfd_settime, usize(fd), usize(flags), @ptrToInt(new_value), @ptrToInt(old_value));1238 return syscall4(SYS_timerfd_settime, usize(fd), usize(flags), @ptrToInt(new_value), @ptrToInt(old_value));
1211}1239}
12121240
...@@ -1301,8 +1329,8 @@ pub fn CAP_TO_INDEX(cap: u8) u8 {...@@ -1301,8 +1329,8 @@ pub fn CAP_TO_INDEX(cap: u8) u8 {
1301}1329}
13021330
1303pub const cap_t = extern struct {1331pub const cap_t = extern struct {
1304 hdrp: &cap_user_header_t,1332 hdrp: *cap_user_header_t,
1305 datap: &cap_user_data_t,1333 datap: *cap_user_data_t,
1306};1334};
13071335
1308pub const cap_user_header_t = extern struct {1336pub const cap_user_header_t = extern struct {
...@@ -1320,11 +1348,11 @@ pub fn unshare(flags: usize) usize {...@@ -1320,11 +1348,11 @@ pub fn unshare(flags: usize) usize {
1320 return syscall1(SYS_unshare, usize(flags));1348 return syscall1(SYS_unshare, usize(flags));
1321}1349}
13221350
1323pub fn capget(hdrp: &cap_user_header_t, datap: &cap_user_data_t) usize {1351pub fn capget(hdrp: *cap_user_header_t, datap: *cap_user_data_t) usize {
1324 return syscall2(SYS_capget, @ptrToInt(hdrp), @ptrToInt(datap));1352 return syscall2(SYS_capget, @ptrToInt(hdrp), @ptrToInt(datap));
1325}1353}
13261354
1327pub fn capset(hdrp: &cap_user_header_t, datap: &const cap_user_data_t) usize {1355pub fn capset(hdrp: *cap_user_header_t, datap: *const cap_user_data_t) usize {
1328 return syscall2(SYS_capset, @ptrToInt(hdrp), @ptrToInt(datap));1356 return syscall2(SYS_capset, @ptrToInt(hdrp), @ptrToInt(datap));
1329}1357}
13301358
std/os/linux/test.zig+8-7
...@@ -11,22 +11,22 @@ test "timer" {...@@ -11,22 +11,22 @@ test "timer" {
11 const timer_fd = linux.timerfd_create(linux.CLOCK_MONOTONIC, 0);11 const timer_fd = linux.timerfd_create(linux.CLOCK_MONOTONIC, 0);
12 assert(linux.getErrno(timer_fd) == 0);12 assert(linux.getErrno(timer_fd) == 0);
1313
14 const time_interval = linux.timespec {14 const time_interval = linux.timespec{
15 .tv_sec = 0,15 .tv_sec = 0,
16 .tv_nsec = 200000016 .tv_nsec = 2000000,
17 };17 };
1818
19 const new_time = linux.itimerspec {19 const new_time = linux.itimerspec{
20 .it_interval = time_interval,20 .it_interval = time_interval,
21 .it_value = time_interval21 .it_value = time_interval,
22 };22 };
2323
24 err = linux.timerfd_settime(i32(timer_fd), 0, &new_time, null);24 err = linux.timerfd_settime(i32(timer_fd), 0, &new_time, null);
25 assert(err == 0);25 assert(err == 0);
2626
27 var event = linux.epoll_event {27 var event = linux.epoll_event{
28 .events = linux.EPOLLIN | linux.EPOLLOUT | linux.EPOLLET,28 .events = linux.EPOLLIN | linux.EPOLLOUT | linux.EPOLLET,
29 .data = linux.epoll_data { .ptr = 0 },29 .data = linux.epoll_data{ .ptr = 0 },
30 };30 };
3131
32 err = linux.epoll_ctl(i32(epoll_fd), linux.EPOLL_CTL_ADD, i32(timer_fd), &event);32 err = linux.epoll_ctl(i32(epoll_fd), linux.EPOLL_CTL_ADD, i32(timer_fd), &event);
...@@ -35,5 +35,6 @@ test "timer" {...@@ -35,5 +35,6 @@ test "timer" {
35 const events_one: linux.epoll_event = undefined;35 const events_one: linux.epoll_event = undefined;
36 var events = []linux.epoll_event{events_one} ** 8;36 var events = []linux.epoll_event{events_one} ** 8;
3737
38 err = linux.epoll_wait(i32(epoll_fd), &events[0], 8, -1);38 // TODO implicit cast from *[N]T to [*]T
39 err = linux.epoll_wait(i32(epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1);
39}40}
std/os/linux/vdso.zig+30-28
...@@ -8,19 +8,22 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {...@@ -8,19 +8,22 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {
8 const vdso_addr = std.os.linux_aux_raw[std.elf.AT_SYSINFO_EHDR];8 const vdso_addr = std.os.linux_aux_raw[std.elf.AT_SYSINFO_EHDR];
9 if (vdso_addr == 0) return 0;9 if (vdso_addr == 0) return 0;
1010
11 const eh = @intToPtr(&elf.Ehdr, vdso_addr);11 const eh = @intToPtr(*elf.Ehdr, vdso_addr);
12 var ph_addr: usize = vdso_addr + eh.e_phoff;12 var ph_addr: usize = vdso_addr + eh.e_phoff;
13 const ph = @intToPtr(&elf.Phdr, ph_addr);13 const ph = @intToPtr(*elf.Phdr, ph_addr);
1414
15 var maybe_dynv: ?&usize = null;15 var maybe_dynv: ?[*]usize = null;
16 var base: usize = @maxValue(usize);16 var base: usize = @maxValue(usize);
17 {17 {
18 var i: usize = 0;18 var i: usize = 0;
19 while (i < eh.e_phnum) : ({i += 1; ph_addr += eh.e_phentsize;}) {19 while (i < eh.e_phnum) : ({
20 const this_ph = @intToPtr(&elf.Phdr, ph_addr);20 i += 1;
21 ph_addr += eh.e_phentsize;
22 }) {
23 const this_ph = @intToPtr(*elf.Phdr, ph_addr);
21 switch (this_ph.p_type) {24 switch (this_ph.p_type) {
22 elf.PT_LOAD => base = vdso_addr + this_ph.p_offset - this_ph.p_vaddr,25 elf.PT_LOAD => base = vdso_addr + this_ph.p_offset - this_ph.p_vaddr,
23 elf.PT_DYNAMIC => maybe_dynv = @intToPtr(&usize, vdso_addr + this_ph.p_offset),26 elf.PT_DYNAMIC => maybe_dynv = @intToPtr([*]usize, vdso_addr + this_ph.p_offset),
24 else => {},27 else => {},
25 }28 }
26 }29 }
...@@ -28,22 +31,22 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {...@@ -28,22 +31,22 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {
28 const dynv = maybe_dynv ?? return 0;31 const dynv = maybe_dynv ?? return 0;
29 if (base == @maxValue(usize)) return 0;32 if (base == @maxValue(usize)) return 0;
3033
31 var maybe_strings: ?&u8 = null;34 var maybe_strings: ?[*]u8 = null;
32 var maybe_syms: ?&elf.Sym = null;35 var maybe_syms: ?[*]elf.Sym = null;
33 var maybe_hashtab: ?&linux.Elf_Symndx = null;36 var maybe_hashtab: ?[*]linux.Elf_Symndx = null;
34 var maybe_versym: ?&u16 = null;37 var maybe_versym: ?[*]u16 = null;
35 var maybe_verdef: ?&elf.Verdef = null;38 var maybe_verdef: ?*elf.Verdef = null;
3639
37 {40 {
38 var i: usize = 0;41 var i: usize = 0;
39 while (dynv[i] != 0) : (i += 2) {42 while (dynv[i] != 0) : (i += 2) {
40 const p = base + dynv[i + 1];43 const p = base + dynv[i + 1];
41 switch (dynv[i]) {44 switch (dynv[i]) {
42 elf.DT_STRTAB => maybe_strings = @intToPtr(&u8, p),45 elf.DT_STRTAB => maybe_strings = @intToPtr([*]u8, p),
43 elf.DT_SYMTAB => maybe_syms = @intToPtr(&elf.Sym, p),46 elf.DT_SYMTAB => maybe_syms = @intToPtr([*]elf.Sym, p),
44 elf.DT_HASH => maybe_hashtab = @intToPtr(&linux.Elf_Symndx, p),47 elf.DT_HASH => maybe_hashtab = @intToPtr([*]linux.Elf_Symndx, p),
45 elf.DT_VERSYM => maybe_versym = @intToPtr(&u16, p),48 elf.DT_VERSYM => maybe_versym = @intToPtr([*]u16, p),
46 elf.DT_VERDEF => maybe_verdef = @intToPtr(&elf.Verdef, p),49 elf.DT_VERDEF => maybe_verdef = @intToPtr(*elf.Verdef, p),
47 else => {},50 else => {},
48 }51 }
49 }52 }
...@@ -54,16 +57,15 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {...@@ -54,16 +57,15 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {
54 const hashtab = maybe_hashtab ?? return 0;57 const hashtab = maybe_hashtab ?? return 0;
55 if (maybe_verdef == null) maybe_versym = null;58 if (maybe_verdef == null) maybe_versym = null;
5659
5760 const OK_TYPES = (1 << elf.STT_NOTYPE | 1 << elf.STT_OBJECT | 1 << elf.STT_FUNC | 1 << elf.STT_COMMON);
58 const OK_TYPES = (1<<elf.STT_NOTYPE | 1<<elf.STT_OBJECT | 1<<elf.STT_FUNC | 1<<elf.STT_COMMON);61 const OK_BINDS = (1 << elf.STB_GLOBAL | 1 << elf.STB_WEAK | 1 << elf.STB_GNU_UNIQUE);
59 const OK_BINDS = (1<<elf.STB_GLOBAL | 1<<elf.STB_WEAK | 1<<elf.STB_GNU_UNIQUE);
6062
61 var i: usize = 0;63 var i: usize = 0;
62 while (i < hashtab[1]) : (i += 1) {64 while (i < hashtab[1]) : (i += 1) {
63 if (0==(u32(1)<<u5(syms[i].st_info&0xf) & OK_TYPES)) continue;65 if (0 == (u32(1) << u5(syms[i].st_info & 0xf) & OK_TYPES)) continue;
64 if (0==(u32(1)<<u5(syms[i].st_info>>4) & OK_BINDS)) continue;66 if (0 == (u32(1) << u5(syms[i].st_info >> 4) & OK_BINDS)) continue;
65 if (0==syms[i].st_shndx) continue;67 if (0 == syms[i].st_shndx) continue;
66 if (!mem.eql(u8, name, cstr.toSliceConst(&strings[syms[i].st_name]))) continue;68 if (!mem.eql(u8, name, cstr.toSliceConst(strings + syms[i].st_name))) continue;
67 if (maybe_versym) |versym| {69 if (maybe_versym) |versym| {
68 if (!checkver(??maybe_verdef, versym[i], vername, strings))70 if (!checkver(??maybe_verdef, versym[i], vername, strings))
69 continue;71 continue;
...@@ -74,16 +76,16 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {...@@ -74,16 +76,16 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {
74 return 0;76 return 0;
75}77}
7678
77fn checkver(def_arg: &elf.Verdef, vsym_arg: i32, vername: []const u8, strings: &u8) bool {79fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: [*]u8) bool {
78 var def = def_arg;80 var def = def_arg;
79 const vsym = @bitCast(u32, vsym_arg) & 0x7fff;81 const vsym = @bitCast(u32, vsym_arg) & 0x7fff;
80 while (true) {82 while (true) {
81 if (0==(def.vd_flags & elf.VER_FLG_BASE) and (def.vd_ndx & 0x7fff) == vsym)83 if (0 == (def.vd_flags & elf.VER_FLG_BASE) and (def.vd_ndx & 0x7fff) == vsym)
82 break;84 break;
83 if (def.vd_next == 0)85 if (def.vd_next == 0)
84 return false;86 return false;
85 def = @intToPtr(&elf.Verdef, @ptrToInt(def) + def.vd_next);87 def = @intToPtr(*elf.Verdef, @ptrToInt(def) + def.vd_next);
86 }88 }
87 const aux = @intToPtr(&elf.Verdaux, @ptrToInt(def ) + def.vd_aux);89 const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux);
88 return mem.eql(u8, vername, cstr.toSliceConst(&strings[aux.vda_name]));90 return mem.eql(u8, vername, cstr.toSliceConst(strings + aux.vda_name));
89}91}
std/os/linux/x86_64.zig+67-55
...@@ -330,26 +330,26 @@ pub const SYS_userfaultfd = 323;...@@ -330,26 +330,26 @@ pub const SYS_userfaultfd = 323;
330pub const SYS_membarrier = 324;330pub const SYS_membarrier = 324;
331pub const SYS_mlock2 = 325;331pub const SYS_mlock2 = 325;
332332
333pub const O_CREAT = 0o100;333pub const O_CREAT = 0o100;
334pub const O_EXCL = 0o200;334pub const O_EXCL = 0o200;
335pub const O_NOCTTY = 0o400;335pub const O_NOCTTY = 0o400;
336pub const O_TRUNC = 0o1000;336pub const O_TRUNC = 0o1000;
337pub const O_APPEND = 0o2000;337pub const O_APPEND = 0o2000;
338pub const O_NONBLOCK = 0o4000;338pub const O_NONBLOCK = 0o4000;
339pub const O_DSYNC = 0o10000;339pub const O_DSYNC = 0o10000;
340pub const O_SYNC = 0o4010000;340pub const O_SYNC = 0o4010000;
341pub const O_RSYNC = 0o4010000;341pub const O_RSYNC = 0o4010000;
342pub const O_DIRECTORY = 0o200000;342pub const O_DIRECTORY = 0o200000;
343pub const O_NOFOLLOW = 0o400000;343pub const O_NOFOLLOW = 0o400000;
344pub const O_CLOEXEC = 0o2000000;344pub const O_CLOEXEC = 0o2000000;
345345
346pub const O_ASYNC = 0o20000;346pub const O_ASYNC = 0o20000;
347pub const O_DIRECT = 0o40000;347pub const O_DIRECT = 0o40000;
348pub const O_LARGEFILE = 0;348pub const O_LARGEFILE = 0;
349pub const O_NOATIME = 0o1000000;349pub const O_NOATIME = 0o1000000;
350pub const O_PATH = 0o10000000;350pub const O_PATH = 0o10000000;
351pub const O_TMPFILE = 0o20200000;351pub const O_TMPFILE = 0o20200000;
352pub const O_NDELAY = O_NONBLOCK;352pub const O_NDELAY = O_NONBLOCK;
353353
354pub const F_DUPFD = 0;354pub const F_DUPFD = 0;
355pub const F_GETFD = 1;355pub const F_GETFD = 1;
...@@ -371,7 +371,6 @@ pub const F_GETOWN_EX = 16;...@@ -371,7 +371,6 @@ pub const F_GETOWN_EX = 16;
371371
372pub const F_GETOWNER_UIDS = 17;372pub const F_GETOWNER_UIDS = 17;
373373
374
375pub const VDSO_USEFUL = true;374pub const VDSO_USEFUL = true;
376pub const VDSO_CGT_SYM = "__vdso_clock_gettime";375pub const VDSO_CGT_SYM = "__vdso_clock_gettime";
377pub const VDSO_CGT_VER = "LINUX_2.6";376pub const VDSO_CGT_VER = "LINUX_2.6";
...@@ -382,92 +381,105 @@ pub fn syscall0(number: usize) usize {...@@ -382,92 +381,105 @@ pub fn syscall0(number: usize) usize {
382 return asm volatile ("syscall"381 return asm volatile ("syscall"
383 : [ret] "={rax}" (-> usize)382 : [ret] "={rax}" (-> usize)
384 : [number] "{rax}" (number)383 : [number] "{rax}" (number)
385 : "rcx", "r11");384 : "rcx", "r11"
385 );
386}386}
387387
388pub fn syscall1(number: usize, arg1: usize) usize {388pub fn syscall1(number: usize, arg1: usize) usize {
389 return asm volatile ("syscall"389 return asm volatile ("syscall"
390 : [ret] "={rax}" (-> usize)390 : [ret] "={rax}" (-> usize)
391 : [number] "{rax}" (number),391 : [number] "{rax}" (number),
392 [arg1] "{rdi}" (arg1)392 [arg1] "{rdi}" (arg1)
393 : "rcx", "r11");393 : "rcx", "r11"
394 );
394}395}
395396
396pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize {397pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize {
397 return asm volatile ("syscall"398 return asm volatile ("syscall"
398 : [ret] "={rax}" (-> usize)399 : [ret] "={rax}" (-> usize)
399 : [number] "{rax}" (number),400 : [number] "{rax}" (number),
400 [arg1] "{rdi}" (arg1),401 [arg1] "{rdi}" (arg1),
401 [arg2] "{rsi}" (arg2)402 [arg2] "{rsi}" (arg2)
402 : "rcx", "r11");403 : "rcx", "r11"
404 );
403}405}
404406
405pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {407pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {
406 return asm volatile ("syscall"408 return asm volatile ("syscall"
407 : [ret] "={rax}" (-> usize)409 : [ret] "={rax}" (-> usize)
408 : [number] "{rax}" (number),410 : [number] "{rax}" (number),
409 [arg1] "{rdi}" (arg1),411 [arg1] "{rdi}" (arg1),
410 [arg2] "{rsi}" (arg2),412 [arg2] "{rsi}" (arg2),
411 [arg3] "{rdx}" (arg3)413 [arg3] "{rdx}" (arg3)
412 : "rcx", "r11");414 : "rcx", "r11"
415 );
413}416}
414417
415pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {418pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {
416 return asm volatile ("syscall"419 return asm volatile ("syscall"
417 : [ret] "={rax}" (-> usize)420 : [ret] "={rax}" (-> usize)
418 : [number] "{rax}" (number),421 : [number] "{rax}" (number),
419 [arg1] "{rdi}" (arg1),422 [arg1] "{rdi}" (arg1),
420 [arg2] "{rsi}" (arg2),423 [arg2] "{rsi}" (arg2),
421 [arg3] "{rdx}" (arg3),424 [arg3] "{rdx}" (arg3),
422 [arg4] "{r10}" (arg4)425 [arg4] "{r10}" (arg4)
423 : "rcx", "r11");426 : "rcx", "r11"
427 );
424}428}
425429
426pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {430pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {
427 return asm volatile ("syscall"431 return asm volatile ("syscall"
428 : [ret] "={rax}" (-> usize)432 : [ret] "={rax}" (-> usize)
429 : [number] "{rax}" (number),433 : [number] "{rax}" (number),
430 [arg1] "{rdi}" (arg1),434 [arg1] "{rdi}" (arg1),
431 [arg2] "{rsi}" (arg2),435 [arg2] "{rsi}" (arg2),
432 [arg3] "{rdx}" (arg3),436 [arg3] "{rdx}" (arg3),
433 [arg4] "{r10}" (arg4),437 [arg4] "{r10}" (arg4),
434 [arg5] "{r8}" (arg5)438 [arg5] "{r8}" (arg5)
435 : "rcx", "r11");439 : "rcx", "r11"
440 );
436}441}
437442
438pub fn syscall6(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize,443pub fn syscall6(
439 arg5: usize, arg6: usize) usize444 number: usize,
440{445 arg1: usize,
446 arg2: usize,
447 arg3: usize,
448 arg4: usize,
449 arg5: usize,
450 arg6: usize,
451) usize {
441 return asm volatile ("syscall"452 return asm volatile ("syscall"
442 : [ret] "={rax}" (-> usize)453 : [ret] "={rax}" (-> usize)
443 : [number] "{rax}" (number),454 : [number] "{rax}" (number),
444 [arg1] "{rdi}" (arg1),455 [arg1] "{rdi}" (arg1),
445 [arg2] "{rsi}" (arg2),456 [arg2] "{rsi}" (arg2),
446 [arg3] "{rdx}" (arg3),457 [arg3] "{rdx}" (arg3),
447 [arg4] "{r10}" (arg4),458 [arg4] "{r10}" (arg4),
448 [arg5] "{r8}" (arg5),459 [arg5] "{r8}" (arg5),
449 [arg6] "{r9}" (arg6)460 [arg6] "{r9}" (arg6)
450 : "rcx", "r11");461 : "rcx", "r11"
462 );
451}463}
452464
453/// This matches the libc clone function.465/// This matches the libc clone function.
454pub extern fn clone(func: extern fn(arg: usize) u8, stack: usize, flags: usize, arg: usize, ptid: &i32, tls: usize, ctid: &i32) usize;466pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: usize, arg: usize, ptid: *i32, tls: usize, ctid: *i32) usize;
455467
456pub nakedcc fn restore_rt() void {468pub nakedcc fn restore_rt() void {
457 return asm volatile ("syscall"469 return asm volatile ("syscall"
458 :470 :
459 : [number] "{rax}" (usize(SYS_rt_sigreturn))471 : [number] "{rax}" (usize(SYS_rt_sigreturn))
460 : "rcx", "r11");472 : "rcx", "r11"
473 );
461}474}
462475
463
464pub const msghdr = extern struct {476pub const msghdr = extern struct {
465 msg_name: &u8,477 msg_name: *u8,
466 msg_namelen: socklen_t,478 msg_namelen: socklen_t,
467 msg_iov: &iovec,479 msg_iov: *iovec,
468 msg_iovlen: i32,480 msg_iovlen: i32,
469 __pad1: i32,481 __pad1: i32,
470 msg_control: &u8,482 msg_control: *u8,
471 msg_controllen: socklen_t,483 msg_controllen: socklen_t,
472 __pad2: socklen_t,484 __pad2: socklen_t,
473 msg_flags: i32,485 msg_flags: i32,
std/os/path.zig+57-66
...@@ -32,7 +32,7 @@ pub fn isSep(byte: u8) bool {...@@ -32,7 +32,7 @@ pub fn isSep(byte: u8) bool {
3232
33/// Naively combines a series of paths with the native path seperator.33/// Naively combines a series of paths with the native path seperator.
34/// Allocates memory for the result, which must be freed by the caller.34/// Allocates memory for the result, which must be freed by the caller.
35pub fn join(allocator: &Allocator, paths: ...) ![]u8 {35pub fn join(allocator: *Allocator, paths: ...) ![]u8 {
36 if (is_windows) {36 if (is_windows) {
37 return joinWindows(allocator, paths);37 return joinWindows(allocator, paths);
38 } else {38 } else {
...@@ -40,11 +40,11 @@ pub fn join(allocator: &Allocator, paths: ...) ![]u8 {...@@ -40,11 +40,11 @@ pub fn join(allocator: &Allocator, paths: ...) ![]u8 {
40 }40 }
41}41}
4242
43pub fn joinWindows(allocator: &Allocator, paths: ...) ![]u8 {43pub fn joinWindows(allocator: *Allocator, paths: ...) ![]u8 {
44 return mem.join(allocator, sep_windows, paths);44 return mem.join(allocator, sep_windows, paths);
45}45}
4646
47pub fn joinPosix(allocator: &Allocator, paths: ...) ![]u8 {47pub fn joinPosix(allocator: *Allocator, paths: ...) ![]u8 {
48 return mem.join(allocator, sep_posix, paths);48 return mem.join(allocator, sep_posix, paths);
49}49}
5050
...@@ -55,9 +55,7 @@ test "os.path.join" {...@@ -55,9 +55,7 @@ test "os.path.join" {
55 assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\", "a", "b\\", "c"), "c:\\a\\b\\c"));55 assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\", "a", "b\\", "c"), "c:\\a\\b\\c"));
56 assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\a\\", "b\\", "c"), "c:\\a\\b\\c"));56 assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\a\\", "b\\", "c"), "c:\\a\\b\\c"));
5757
58 assert(mem.eql(u8, try joinWindows(debug.global_allocator,58 assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std", "io.zig"), "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std\\io.zig"));
59 "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std", "io.zig"),
60 "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std\\io.zig"));
6159
62 assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/b", "c"), "/a/b/c"));60 assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/b", "c"), "/a/b/c"));
63 assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/b/", "c"), "/a/b/c"));61 assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/b/", "c"), "/a/b/c"));
...@@ -65,8 +63,7 @@ test "os.path.join" {...@@ -65,8 +63,7 @@ test "os.path.join" {
65 assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/", "a", "b/", "c"), "/a/b/c"));63 assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/", "a", "b/", "c"), "/a/b/c"));
66 assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/", "b/", "c"), "/a/b/c"));64 assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/", "b/", "c"), "/a/b/c"));
6765
68 assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/home/andy/dev/zig/build/lib/zig/std", "io.zig"),66 assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/home/andy/dev/zig/build/lib/zig/std", "io.zig"), "/home/andy/dev/zig/build/lib/zig/std/io.zig"));
69 "/home/andy/dev/zig/build/lib/zig/std/io.zig"));
70}67}
7168
72pub fn isAbsolute(path: []const u8) bool {69pub fn isAbsolute(path: []const u8) bool {
...@@ -151,22 +148,22 @@ pub const WindowsPath = struct {...@@ -151,22 +148,22 @@ pub const WindowsPath = struct {
151148
152pub fn windowsParsePath(path: []const u8) WindowsPath {149pub fn windowsParsePath(path: []const u8) WindowsPath {
153 if (path.len >= 2 and path[1] == ':') {150 if (path.len >= 2 and path[1] == ':') {
154 return WindowsPath {151 return WindowsPath{
155 .is_abs = isAbsoluteWindows(path),152 .is_abs = isAbsoluteWindows(path),
156 .kind = WindowsPath.Kind.Drive,153 .kind = WindowsPath.Kind.Drive,
157 .disk_designator = path[0..2],154 .disk_designator = path[0..2],
158 };155 };
159 }156 }
160 if (path.len >= 1 and (path[0] == '/' or path[0] == '\\') and157 if (path.len >= 1 and (path[0] == '/' or path[0] == '\\') and
161 (path.len == 1 or (path[1] != '/' and path[1] != '\\')))158 (path.len == 1 or (path[1] != '/' and path[1] != '\\')))
162 {159 {
163 return WindowsPath {160 return WindowsPath{
164 .is_abs = true,161 .is_abs = true,
165 .kind = WindowsPath.Kind.None,162 .kind = WindowsPath.Kind.None,
166 .disk_designator = path[0..0],163 .disk_designator = path[0..0],
167 };164 };
168 }165 }
169 const relative_path = WindowsPath {166 const relative_path = WindowsPath{
170 .kind = WindowsPath.Kind.None,167 .kind = WindowsPath.Kind.None,
171 .disk_designator = []u8{},168 .disk_designator = []u8{},
172 .is_abs = false,169 .is_abs = false,
...@@ -178,7 +175,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {...@@ -178,7 +175,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {
178 // TODO when I combined these together with `inline for` the compiler crashed175 // TODO when I combined these together with `inline for` the compiler crashed
179 {176 {
180 const this_sep = '/';177 const this_sep = '/';
181 const two_sep = []u8{this_sep, this_sep};178 const two_sep = []u8{ this_sep, this_sep };
182 if (mem.startsWith(u8, path, two_sep)) {179 if (mem.startsWith(u8, path, two_sep)) {
183 if (path[2] == this_sep) {180 if (path[2] == this_sep) {
184 return relative_path;181 return relative_path;
...@@ -187,7 +184,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {...@@ -187,7 +184,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {
187 var it = mem.split(path, []u8{this_sep});184 var it = mem.split(path, []u8{this_sep});
188 _ = (it.next() ?? return relative_path);185 _ = (it.next() ?? return relative_path);
189 _ = (it.next() ?? return relative_path);186 _ = (it.next() ?? return relative_path);
190 return WindowsPath {187 return WindowsPath{
191 .is_abs = isAbsoluteWindows(path),188 .is_abs = isAbsoluteWindows(path),
192 .kind = WindowsPath.Kind.NetworkShare,189 .kind = WindowsPath.Kind.NetworkShare,
193 .disk_designator = path[0..it.index],190 .disk_designator = path[0..it.index],
...@@ -196,7 +193,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {...@@ -196,7 +193,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {
196 }193 }
197 {194 {
198 const this_sep = '\\';195 const this_sep = '\\';
199 const two_sep = []u8{this_sep, this_sep};196 const two_sep = []u8{ this_sep, this_sep };
200 if (mem.startsWith(u8, path, two_sep)) {197 if (mem.startsWith(u8, path, two_sep)) {
201 if (path[2] == this_sep) {198 if (path[2] == this_sep) {
202 return relative_path;199 return relative_path;
...@@ -205,7 +202,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {...@@ -205,7 +202,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {
205 var it = mem.split(path, []u8{this_sep});202 var it = mem.split(path, []u8{this_sep});
206 _ = (it.next() ?? return relative_path);203 _ = (it.next() ?? return relative_path);
207 _ = (it.next() ?? return relative_path);204 _ = (it.next() ?? return relative_path);
208 return WindowsPath {205 return WindowsPath{
209 .is_abs = isAbsoluteWindows(path),206 .is_abs = isAbsoluteWindows(path),
210 .kind = WindowsPath.Kind.NetworkShare,207 .kind = WindowsPath.Kind.NetworkShare,
211 .disk_designator = path[0..it.index],208 .disk_designator = path[0..it.index],
...@@ -296,7 +293,7 @@ fn compareDiskDesignators(kind: WindowsPath.Kind, p1: []const u8, p2: []const u8...@@ -296,7 +293,7 @@ fn compareDiskDesignators(kind: WindowsPath.Kind, p1: []const u8, p2: []const u8
296293
297fn asciiUpper(byte: u8) u8 {294fn asciiUpper(byte: u8) u8 {
298 return switch (byte) {295 return switch (byte) {
299 'a' ... 'z' => 'A' + (byte - 'a'),296 'a'...'z' => 'A' + (byte - 'a'),
300 else => byte,297 else => byte,
301 };298 };
302}299}
...@@ -313,7 +310,7 @@ fn asciiEqlIgnoreCase(s1: []const u8, s2: []const u8) bool {...@@ -313,7 +310,7 @@ fn asciiEqlIgnoreCase(s1: []const u8, s2: []const u8) bool {
313}310}
314311
315/// Converts the command line arguments into a slice and calls `resolveSlice`.312/// Converts the command line arguments into a slice and calls `resolveSlice`.
316pub fn resolve(allocator: &Allocator, args: ...) ![]u8 {313pub fn resolve(allocator: *Allocator, args: ...) ![]u8 {
317 var paths: [args.len][]const u8 = undefined;314 var paths: [args.len][]const u8 = undefined;
318 comptime var arg_i = 0;315 comptime var arg_i = 0;
319 inline while (arg_i < args.len) : (arg_i += 1) {316 inline while (arg_i < args.len) : (arg_i += 1) {
...@@ -323,7 +320,7 @@ pub fn resolve(allocator: &Allocator, args: ...) ![]u8 {...@@ -323,7 +320,7 @@ pub fn resolve(allocator: &Allocator, args: ...) ![]u8 {
323}320}
324321
325/// On Windows, this calls `resolveWindows` and on POSIX it calls `resolvePosix`.322/// On Windows, this calls `resolveWindows` and on POSIX it calls `resolvePosix`.
326pub fn resolveSlice(allocator: &Allocator, paths: []const []const u8) ![]u8 {323pub fn resolveSlice(allocator: *Allocator, paths: []const []const u8) ![]u8 {
327 if (is_windows) {324 if (is_windows) {
328 return resolveWindows(allocator, paths);325 return resolveWindows(allocator, paths);
329 } else {326 } else {
...@@ -337,7 +334,7 @@ pub fn resolveSlice(allocator: &Allocator, paths: []const []const u8) ![]u8 {...@@ -337,7 +334,7 @@ pub fn resolveSlice(allocator: &Allocator, paths: []const []const u8) ![]u8 {
337/// If all paths are relative it uses the current working directory as a starting point.334/// If all paths are relative it uses the current working directory as a starting point.
338/// Each drive has its own current working directory.335/// Each drive has its own current working directory.
339/// Path separators are canonicalized to '\\' and drives are canonicalized to capital letters.336/// Path separators are canonicalized to '\\' and drives are canonicalized to capital letters.
340pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {337pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
341 if (paths.len == 0) {338 if (paths.len == 0) {
342 assert(is_windows); // resolveWindows called on non windows can't use getCwd339 assert(is_windows); // resolveWindows called on non windows can't use getCwd
343 return os.getCwd(allocator);340 return os.getCwd(allocator);
...@@ -372,7 +369,6 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {...@@ -372,7 +369,6 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {
372 max_size += p.len + 1;369 max_size += p.len + 1;
373 }370 }
374371
375
376 // if we will result with a disk designator, loop again to determine372 // if we will result with a disk designator, loop again to determine
377 // which is the last time the disk designator is absolutely specified, if any373 // which is the last time the disk designator is absolutely specified, if any
378 // and count up the max bytes for paths related to this disk designator374 // and count up the max bytes for paths related to this disk designator
...@@ -386,8 +382,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {...@@ -386,8 +382,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {
386 const parsed = windowsParsePath(p);382 const parsed = windowsParsePath(p);
387 if (parsed.kind != WindowsPath.Kind.None) {383 if (parsed.kind != WindowsPath.Kind.None) {
388 if (parsed.kind == have_drive_kind) {384 if (parsed.kind == have_drive_kind) {
389 correct_disk_designator = compareDiskDesignators(have_drive_kind,385 correct_disk_designator = compareDiskDesignators(have_drive_kind, result_disk_designator, parsed.disk_designator);
390 result_disk_designator, parsed.disk_designator);
391 } else {386 } else {
392 continue;387 continue;
393 }388 }
...@@ -404,7 +399,6 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {...@@ -404,7 +399,6 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {
404 }399 }
405 }400 }
406401
407
408 // Allocate result and fill in the disk designator, calling getCwd if we have to.402 // Allocate result and fill in the disk designator, calling getCwd if we have to.
409 var result: []u8 = undefined;403 var result: []u8 = undefined;
410 var result_index: usize = 0;404 var result_index: usize = 0;
...@@ -433,7 +427,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {...@@ -433,7 +427,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {
433 result_index += 1;427 result_index += 1;
434 mem.copy(u8, result[result_index..], other_name);428 mem.copy(u8, result[result_index..], other_name);
435 result_index += other_name.len;429 result_index += other_name.len;
436 430
437 result_disk_designator = result[0..result_index];431 result_disk_designator = result[0..result_index];
438 },432 },
439 WindowsPath.Kind.None => {433 WindowsPath.Kind.None => {
...@@ -478,8 +472,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {...@@ -478,8 +472,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {
478472
479 if (parsed.kind != WindowsPath.Kind.None) {473 if (parsed.kind != WindowsPath.Kind.None) {
480 if (parsed.kind == have_drive_kind) {474 if (parsed.kind == have_drive_kind) {
481 correct_disk_designator = compareDiskDesignators(have_drive_kind,475 correct_disk_designator = compareDiskDesignators(have_drive_kind, result_disk_designator, parsed.disk_designator);
482 result_disk_designator, parsed.disk_designator);
483 } else {476 } else {
484 continue;477 continue;
485 }478 }
...@@ -520,7 +513,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {...@@ -520,7 +513,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 {
520/// It resolves "." and "..".513/// It resolves "." and "..".
521/// The result does not have a trailing path separator.514/// The result does not have a trailing path separator.
522/// If all paths are relative it uses the current working directory as a starting point.515/// If all paths are relative it uses the current working directory as a starting point.
523pub fn resolvePosix(allocator: &Allocator, paths: []const []const u8) ![]u8 {516pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
524 if (paths.len == 0) {517 if (paths.len == 0) {
525 assert(!is_windows); // resolvePosix called on windows can't use getCwd518 assert(!is_windows); // resolvePosix called on windows can't use getCwd
526 return os.getCwd(allocator);519 return os.getCwd(allocator);
...@@ -591,7 +584,7 @@ test "os.path.resolve" {...@@ -591,7 +584,7 @@ test "os.path.resolve" {
591 }584 }
592 assert(mem.eql(u8, testResolveWindows([][]const u8{"."}), cwd));585 assert(mem.eql(u8, testResolveWindows([][]const u8{"."}), cwd));
593 } else {586 } else {
594 assert(mem.eql(u8, testResolvePosix([][]const u8{"a/b/c/", "../../.."}), cwd));587 assert(mem.eql(u8, testResolvePosix([][]const u8{ "a/b/c/", "../../.." }), cwd));
595 assert(mem.eql(u8, testResolvePosix([][]const u8{"."}), cwd));588 assert(mem.eql(u8, testResolvePosix([][]const u8{"."}), cwd));
596 }589 }
597}590}
...@@ -601,16 +594,15 @@ test "os.path.resolveWindows" {...@@ -601,16 +594,15 @@ test "os.path.resolveWindows" {
601 const cwd = try os.getCwd(debug.global_allocator);594 const cwd = try os.getCwd(debug.global_allocator);
602 const parsed_cwd = windowsParsePath(cwd);595 const parsed_cwd = windowsParsePath(cwd);
603 {596 {
604 const result = testResolveWindows([][]const u8{"/usr/local", "lib\\zig\\std\\array_list.zig"});597 const result = testResolveWindows([][]const u8{ "/usr/local", "lib\\zig\\std\\array_list.zig" });
605 const expected = try join(debug.global_allocator,598 const expected = try join(debug.global_allocator, parsed_cwd.disk_designator, "usr\\local\\lib\\zig\\std\\array_list.zig");
606 parsed_cwd.disk_designator, "usr\\local\\lib\\zig\\std\\array_list.zig");
607 if (parsed_cwd.kind == WindowsPath.Kind.Drive) {599 if (parsed_cwd.kind == WindowsPath.Kind.Drive) {
608 expected[0] = asciiUpper(parsed_cwd.disk_designator[0]);600 expected[0] = asciiUpper(parsed_cwd.disk_designator[0]);
609 }601 }
610 assert(mem.eql(u8, result, expected));602 assert(mem.eql(u8, result, expected));
611 }603 }
612 {604 {
613 const result = testResolveWindows([][]const u8{"usr/local", "lib\\zig"});605 const result = testResolveWindows([][]const u8{ "usr/local", "lib\\zig" });
614 const expected = try join(debug.global_allocator, cwd, "usr\\local\\lib\\zig");606 const expected = try join(debug.global_allocator, cwd, "usr\\local\\lib\\zig");
615 if (parsed_cwd.kind == WindowsPath.Kind.Drive) {607 if (parsed_cwd.kind == WindowsPath.Kind.Drive) {
616 expected[0] = asciiUpper(parsed_cwd.disk_designator[0]);608 expected[0] = asciiUpper(parsed_cwd.disk_designator[0]);
...@@ -619,33 +611,32 @@ test "os.path.resolveWindows" {...@@ -619,33 +611,32 @@ test "os.path.resolveWindows" {
619 }611 }
620 }612 }
621613
622 assert(mem.eql(u8, testResolveWindows([][]const u8{"c:\\a\\b\\c", "/hi", "ok"}), "C:\\hi\\ok"));614 assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:\\a\\b\\c", "/hi", "ok" }), "C:\\hi\\ok"));
623 assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/blah\\blah", "d:/games", "c:../a"}), "C:\\blah\\a"));615 assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/blah\\blah", "d:/games", "c:../a" }), "C:\\blah\\a"));
624 assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/blah\\blah", "d:/games", "C:../a"}), "C:\\blah\\a"));616 assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/blah\\blah", "d:/games", "C:../a" }), "C:\\blah\\a"));
625 assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/ignore", "d:\\a/b\\c/d", "\\e.exe"}), "D:\\e.exe"));617 assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/ignore", "d:\\a/b\\c/d", "\\e.exe" }), "D:\\e.exe"));
626 assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/ignore", "c:/some/file"}), "C:\\some\\file"));618 assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/ignore", "c:/some/file" }), "C:\\some\\file"));
627 assert(mem.eql(u8, testResolveWindows([][]const u8{"d:/ignore", "d:some/dir//"}), "D:\\ignore\\some\\dir"));619 assert(mem.eql(u8, testResolveWindows([][]const u8{ "d:/ignore", "d:some/dir//" }), "D:\\ignore\\some\\dir"));
628 assert(mem.eql(u8, testResolveWindows([][]const u8{"//server/share", "..", "relative\\"}), "\\\\server\\share\\relative"));620 assert(mem.eql(u8, testResolveWindows([][]const u8{ "//server/share", "..", "relative\\" }), "\\\\server\\share\\relative"));
629 assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//"}), "C:\\"));621 assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//" }), "C:\\"));
630 assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//dir"}), "C:\\dir"));622 assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//dir" }), "C:\\dir"));
631 assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//server/share"}), "\\\\server\\share\\"));623 assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//server/share" }), "\\\\server\\share\\"));
632 assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//server//share"}), "\\\\server\\share\\"));624 assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//server//share" }), "\\\\server\\share\\"));
633 assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "///some//dir"}), "C:\\some\\dir"));625 assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "///some//dir" }), "C:\\some\\dir"));
634 assert(mem.eql(u8, testResolveWindows([][]const u8{"C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js"}),626 assert(mem.eql(u8, testResolveWindows([][]const u8{ "C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js" }), "C:\\foo\\tmp.3\\cycles\\root.js"));
635 "C:\\foo\\tmp.3\\cycles\\root.js"));
636}627}
637628
638test "os.path.resolvePosix" {629test "os.path.resolvePosix" {
639 assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b", "c"}), "/a/b/c"));630 assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b", "c" }), "/a/b/c"));
640 assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b", "c", "//d", "e///"}), "/d/e"));631 assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b", "c", "//d", "e///" }), "/d/e"));
641 assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b/c", "..", "../"}), "/a"));632 assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b/c", "..", "../" }), "/a"));
642 assert(mem.eql(u8, testResolvePosix([][]const u8{"/", "..", ".."}), "/"));633 assert(mem.eql(u8, testResolvePosix([][]const u8{ "/", "..", ".." }), "/"));
643 assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b/c/"}), "/a/b/c"));634 assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b/c/"}), "/a/b/c"));
644635
645 assert(mem.eql(u8, testResolvePosix([][]const u8{"/var/lib", "../", "file/"}), "/var/file"));636 assert(mem.eql(u8, testResolvePosix([][]const u8{ "/var/lib", "../", "file/" }), "/var/file"));
646 assert(mem.eql(u8, testResolvePosix([][]const u8{"/var/lib", "/../", "file/"}), "/file"));637 assert(mem.eql(u8, testResolvePosix([][]const u8{ "/var/lib", "/../", "file/" }), "/file"));
647 assert(mem.eql(u8, testResolvePosix([][]const u8{"/some/dir", ".", "/absolute/"}), "/absolute"));638 assert(mem.eql(u8, testResolvePosix([][]const u8{ "/some/dir", ".", "/absolute/" }), "/absolute"));
648 assert(mem.eql(u8, testResolvePosix([][]const u8{"/foo/tmp.3/", "../tmp.3/cycles/root.js"}), "/foo/tmp.3/cycles/root.js"));639 assert(mem.eql(u8, testResolvePosix([][]const u8{ "/foo/tmp.3/", "../tmp.3/cycles/root.js" }), "/foo/tmp.3/cycles/root.js"));
649}640}
650641
651fn testResolveWindows(paths: []const []const u8) []u8 {642fn testResolveWindows(paths: []const []const u8) []u8 {
...@@ -656,6 +647,8 @@ fn testResolvePosix(paths: []const []const u8) []u8 {...@@ -656,6 +647,8 @@ fn testResolvePosix(paths: []const []const u8) []u8 {
656 return resolvePosix(debug.global_allocator, paths) catch unreachable;647 return resolvePosix(debug.global_allocator, paths) catch unreachable;
657}648}
658649
650/// If the path is a file in the current directory (no directory component)
651/// then the returned slice has .len = 0.
659pub fn dirname(path: []const u8) []const u8 {652pub fn dirname(path: []const u8) []const u8 {
660 if (is_windows) {653 if (is_windows) {
661 return dirnameWindows(path);654 return dirnameWindows(path);
...@@ -800,7 +793,7 @@ pub fn basenamePosix(path: []const u8) []const u8 {...@@ -800,7 +793,7 @@ pub fn basenamePosix(path: []const u8) []const u8 {
800 start_index -= 1;793 start_index -= 1;
801 }794 }
802795
803 return path[start_index + 1..end_index];796 return path[start_index + 1 .. end_index];
804}797}
805798
806pub fn basenameWindows(path: []const u8) []const u8 {799pub fn basenameWindows(path: []const u8) []const u8 {
...@@ -832,7 +825,7 @@ pub fn basenameWindows(path: []const u8) []const u8 {...@@ -832,7 +825,7 @@ pub fn basenameWindows(path: []const u8) []const u8 {
832 start_index -= 1;825 start_index -= 1;
833 }826 }
834827
835 return path[start_index + 1..end_index];828 return path[start_index + 1 .. end_index];
836}829}
837830
838test "os.path.basename" {831test "os.path.basename" {
...@@ -890,7 +883,7 @@ fn testBasenameWindows(input: []const u8, expected_output: []const u8) void {...@@ -890,7 +883,7 @@ fn testBasenameWindows(input: []const u8, expected_output: []const u8) void {
890/// resolve to the same path (after calling `resolve` on each), a zero-length883/// resolve to the same path (after calling `resolve` on each), a zero-length
891/// string is returned.884/// string is returned.
892/// On Windows this canonicalizes the drive to a capital letter and paths to `\\`.885/// On Windows this canonicalizes the drive to a capital letter and paths to `\\`.
893pub fn relative(allocator: &Allocator, from: []const u8, to: []const u8) ![]u8 {886pub fn relative(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
894 if (is_windows) {887 if (is_windows) {
895 return relativeWindows(allocator, from, to);888 return relativeWindows(allocator, from, to);
896 } else {889 } else {
...@@ -898,7 +891,7 @@ pub fn relative(allocator: &Allocator, from: []const u8, to: []const u8) ![]u8 {...@@ -898,7 +891,7 @@ pub fn relative(allocator: &Allocator, from: []const u8, to: []const u8) ![]u8 {
898 }891 }
899}892}
900893
901pub fn relativeWindows(allocator: &Allocator, from: []const u8, to: []const u8) ![]u8 {894pub fn relativeWindows(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
902 const resolved_from = try resolveWindows(allocator, [][]const u8{from});895 const resolved_from = try resolveWindows(allocator, [][]const u8{from});
903 defer allocator.free(resolved_from);896 defer allocator.free(resolved_from);
904897
...@@ -971,7 +964,7 @@ pub fn relativeWindows(allocator: &Allocator, from: []const u8, to: []const u8)...@@ -971,7 +964,7 @@ pub fn relativeWindows(allocator: &Allocator, from: []const u8, to: []const u8)
971 return []u8{};964 return []u8{};
972}965}
973966
974pub fn relativePosix(allocator: &Allocator, from: []const u8, to: []const u8) ![]u8 {967pub fn relativePosix(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
975 const resolved_from = try resolvePosix(allocator, [][]const u8{from});968 const resolved_from = try resolvePosix(allocator, [][]const u8{from});
976 defer allocator.free(resolved_from);969 defer allocator.free(resolved_from);
977970
...@@ -1006,7 +999,7 @@ pub fn relativePosix(allocator: &Allocator, from: []const u8, to: []const u8) ![...@@ -1006,7 +999,7 @@ pub fn relativePosix(allocator: &Allocator, from: []const u8, to: []const u8) ![
1006 }999 }
1007 if (to_rest.len == 0) {1000 if (to_rest.len == 0) {
1008 // shave off the trailing slash1001 // shave off the trailing slash
1009 return result[0..result_index - 1];1002 return result[0 .. result_index - 1];
1010 }1003 }
10111004
1012 mem.copy(u8, result[result_index..], to_rest);1005 mem.copy(u8, result[result_index..], to_rest);
...@@ -1070,7 +1063,7 @@ fn testRelativeWindows(from: []const u8, to: []const u8, expected_output: []cons...@@ -1070,7 +1063,7 @@ fn testRelativeWindows(from: []const u8, to: []const u8, expected_output: []cons
1070/// Expands all symbolic links and resolves references to `.`, `..`, and1063/// Expands all symbolic links and resolves references to `.`, `..`, and
1071/// extra `/` characters in ::pathname.1064/// extra `/` characters in ::pathname.
1072/// Caller must deallocate result.1065/// Caller must deallocate result.
1073pub fn real(allocator: &Allocator, pathname: []const u8) ![]u8 {1066pub fn real(allocator: *Allocator, pathname: []const u8) ![]u8 {
1074 switch (builtin.os) {1067 switch (builtin.os) {
1075 Os.windows => {1068 Os.windows => {
1076 const pathname_buf = try allocator.alloc(u8, pathname.len + 1);1069 const pathname_buf = try allocator.alloc(u8, pathname.len + 1);
...@@ -1079,9 +1072,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) ![]u8 {...@@ -1079,9 +1072,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) ![]u8 {
1079 mem.copy(u8, pathname_buf, pathname);1072 mem.copy(u8, pathname_buf, pathname);
1080 pathname_buf[pathname.len] = 0;1073 pathname_buf[pathname.len] = 0;
10811074
1082 const h_file = windows.CreateFileA(pathname_buf.ptr,1075 const h_file = windows.CreateFileA(pathname_buf.ptr, windows.GENERIC_READ, windows.FILE_SHARE_READ, null, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, null);
1083 windows.GENERIC_READ, windows.FILE_SHARE_READ, null, windows.OPEN_EXISTING,
1084 windows.FILE_ATTRIBUTE_NORMAL, null);
1085 if (h_file == windows.INVALID_HANDLE_VALUE) {1076 if (h_file == windows.INVALID_HANDLE_VALUE) {
1086 const err = windows.GetLastError();1077 const err = windows.GetLastError();
1087 return switch (err) {1078 return switch (err) {
...@@ -1161,7 +1152,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) ![]u8 {...@@ -1161,7 +1152,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) ![]u8 {
1161 return allocator.shrink(u8, result_buf, cstr.len(result_buf.ptr));1152 return allocator.shrink(u8, result_buf, cstr.len(result_buf.ptr));
1162 },1153 },
1163 Os.linux => {1154 Os.linux => {
1164 const fd = try os.posixOpen(allocator, pathname, posix.O_PATH|posix.O_NONBLOCK|posix.O_CLOEXEC, 0);1155 const fd = try os.posixOpen(allocator, pathname, posix.O_PATH | posix.O_NONBLOCK | posix.O_CLOEXEC, 0);
1165 defer os.close(fd);1156 defer os.close(fd);
11661157
1167 var buf: ["/proc/self/fd/-2147483648".len]u8 = undefined;1158 var buf: ["/proc/self/fd/-2147483648".len]u8 = undefined;
std/os/test.zig+1-1
...@@ -63,7 +63,7 @@ fn start1(ctx: void) u8 {...@@ -63,7 +63,7 @@ fn start1(ctx: void) u8 {
63 return 0;63 return 0;
64}64}
6565
66fn start2(ctx: &i32) u8 {66fn start2(ctx: *i32) u8 {
67 _ = @atomicRmw(i32, ctx, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst);67 _ = @atomicRmw(i32, ctx, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst);
68 return 0;68 return 0;
69}69}
std/os/time.zig+33-40
...@@ -27,7 +27,7 @@ pub fn sleep(seconds: usize, nanoseconds: usize) void {...@@ -27,7 +27,7 @@ pub fn sleep(seconds: usize, nanoseconds: usize) void {
2727
28const u63 = @IntType(false, 63);28const u63 = @IntType(false, 63);
29pub fn posixSleep(seconds: u63, nanoseconds: u63) void {29pub fn posixSleep(seconds: u63, nanoseconds: u63) void {
30 var req = posix.timespec {30 var req = posix.timespec{
31 .tv_sec = seconds,31 .tv_sec = seconds,
32 .tv_nsec = nanoseconds,32 .tv_nsec = nanoseconds,
33 };33 };
...@@ -71,7 +71,7 @@ fn milliTimestampWindows() u64 {...@@ -71,7 +71,7 @@ fn milliTimestampWindows() u64 {
71 var ft: i64 = undefined;71 var ft: i64 = undefined;
72 windows.GetSystemTimeAsFileTime(&ft);72 windows.GetSystemTimeAsFileTime(&ft);
73 const hns_per_ms = (ns_per_s / 100) / ms_per_s;73 const hns_per_ms = (ns_per_s / 100) / ms_per_s;
74 const epoch_adj = epoch.windows * ms_per_s;74 const epoch_adj = epoch.windows * ms_per_s;
75 return u64(@divFloor(ft, hns_per_ms) + epoch_adj);75 return u64(@divFloor(ft, hns_per_ms) + epoch_adj);
76}76}
7777
...@@ -83,7 +83,7 @@ fn milliTimestampDarwin() u64 {...@@ -83,7 +83,7 @@ fn milliTimestampDarwin() u64 {
83 debug.assert(err == 0);83 debug.assert(err == 0);
84 const sec_ms = u64(tv.tv_sec) * ms_per_s;84 const sec_ms = u64(tv.tv_sec) * ms_per_s;
85 const usec_ms = @divFloor(u64(tv.tv_usec), us_per_s / ms_per_s);85 const usec_ms = @divFloor(u64(tv.tv_usec), us_per_s / ms_per_s);
86 return u64(sec_ms) + u64(usec_ms); 86 return u64(sec_ms) + u64(usec_ms);
87}87}
8888
89fn milliTimestampPosix() u64 {89fn milliTimestampPosix() u64 {
...@@ -110,17 +110,16 @@ pub const s_per_hour = s_per_min * 60;...@@ -110,17 +110,16 @@ pub const s_per_hour = s_per_min * 60;
110pub const s_per_day = s_per_hour * 24;110pub const s_per_day = s_per_hour * 24;
111pub const s_per_week = s_per_day * 7;111pub const s_per_week = s_per_day * 7;
112112
113
114/// A monotonic high-performance timer.113/// A monotonic high-performance timer.
115/// Timer.start() must be called to initialize the struct, which captures114/// Timer.start() must be called to initialize the struct, which captures
116/// the counter frequency on windows and darwin, records the resolution,115/// the counter frequency on windows and darwin, records the resolution,
117/// and gives the user an oportunity to check for the existnece of116/// and gives the user an oportunity to check for the existnece of
118/// monotonic clocks without forcing them to check for error on each read.117/// monotonic clocks without forcing them to check for error on each read.
119/// .resolution is in nanoseconds on all platforms but .start_time's meaning 118/// .resolution is in nanoseconds on all platforms but .start_time's meaning
120/// depends on the OS. On Windows and Darwin it is a hardware counter 119/// depends on the OS. On Windows and Darwin it is a hardware counter
121/// value that requires calculation to convert to a meaninful unit.120/// value that requires calculation to convert to a meaninful unit.
122pub const Timer = struct {121pub const Timer = struct {
123 122
124 //if we used resolution's value when performing the123 //if we used resolution's value when performing the
125 // performance counter calc on windows/darwin, it would124 // performance counter calc on windows/darwin, it would
126 // be less precise125 // be less precise
...@@ -131,10 +130,9 @@ pub const Timer = struct {...@@ -131,10 +130,9 @@ pub const Timer = struct {
131 },130 },
132 resolution: u64,131 resolution: u64,
133 start_time: u64,132 start_time: u64,
134 133
135
136 //At some point we may change our minds on RAW, but for now we're134 //At some point we may change our minds on RAW, but for now we're
137 // sticking with posix standard MONOTONIC. For more information, see: 135 // sticking with posix standard MONOTONIC. For more information, see:
138 // https://github.com/ziglang/zig/pull/933136 // https://github.com/ziglang/zig/pull/933
139 //137 //
140 //const monotonic_clock_id = switch(builtin.os) {138 //const monotonic_clock_id = switch(builtin.os) {
...@@ -142,20 +140,21 @@ pub const Timer = struct {...@@ -142,20 +140,21 @@ pub const Timer = struct {
142 // else => posix.CLOCK_MONOTONIC,140 // else => posix.CLOCK_MONOTONIC,
143 //};141 //};
144 const monotonic_clock_id = posix.CLOCK_MONOTONIC;142 const monotonic_clock_id = posix.CLOCK_MONOTONIC;
145
146
147 /// Initialize the timer structure.143 /// Initialize the timer structure.
148 //This gives us an oportunity to grab the counter frequency in windows.144 //This gives us an oportunity to grab the counter frequency in windows.
149 //On Windows: QueryPerformanceCounter will succeed on anything >= XP/2000.145 //On Windows: QueryPerformanceCounter will succeed on anything >= XP/2000.
150 //On Posix: CLOCK_MONOTONIC will only fail if the monotonic counter is not 146 //On Posix: CLOCK_MONOTONIC will only fail if the monotonic counter is not
151 // supported, or if the timespec pointer is out of bounds, which should be 147 // supported, or if the timespec pointer is out of bounds, which should be
152 // impossible here barring cosmic rays or other such occurances of148 // impossible here barring cosmic rays or other such occurances of
153 // incredibly bad luck.149 // incredibly bad luck.
154 //On Darwin: This cannot fail, as far as I am able to tell.150 //On Darwin: This cannot fail, as far as I am able to tell.
155 const TimerError = error{TimerUnsupported, Unexpected};151 const TimerError = error{
152 TimerUnsupported,
153 Unexpected,
154 };
156 pub fn start() TimerError!Timer {155 pub fn start() TimerError!Timer {
157 var self: Timer = undefined;156 var self: Timer = undefined;
158 157
159 switch (builtin.os) {158 switch (builtin.os) {
160 Os.windows => {159 Os.windows => {
161 var freq: i64 = undefined;160 var freq: i64 = undefined;
...@@ -163,7 +162,7 @@ pub const Timer = struct {...@@ -163,7 +162,7 @@ pub const Timer = struct {
163 if (err == windows.FALSE) return error.TimerUnsupported;162 if (err == windows.FALSE) return error.TimerUnsupported;
164 self.frequency = u64(freq);163 self.frequency = u64(freq);
165 self.resolution = @divFloor(ns_per_s, self.frequency);164 self.resolution = @divFloor(ns_per_s, self.frequency);
166 165
167 var start_time: i64 = undefined;166 var start_time: i64 = undefined;
168 err = windows.QueryPerformanceCounter(&start_time);167 err = windows.QueryPerformanceCounter(&start_time);
169 debug.assert(err != windows.FALSE);168 debug.assert(err != windows.FALSE);
...@@ -171,9 +170,9 @@ pub const Timer = struct {...@@ -171,9 +170,9 @@ pub const Timer = struct {
171 },170 },
172 Os.linux => {171 Os.linux => {
173 //On Linux, seccomp can do arbitrary things to our ability to call172 //On Linux, seccomp can do arbitrary things to our ability to call
174 // syscalls, including return any errno value it wants and 173 // syscalls, including return any errno value it wants and
175 // inconsistently throwing errors. Since we can't account for174 // inconsistently throwing errors. Since we can't account for
176 // abuses of seccomp in a reasonable way, we'll assume that if 175 // abuses of seccomp in a reasonable way, we'll assume that if
177 // seccomp is going to block us it will at least do so consistently176 // seccomp is going to block us it will at least do so consistently
178 var ts: posix.timespec = undefined;177 var ts: posix.timespec = undefined;
179 var result = posix.clock_getres(monotonic_clock_id, &ts);178 var result = posix.clock_getres(monotonic_clock_id, &ts);
...@@ -184,7 +183,7 @@ pub const Timer = struct {...@@ -184,7 +183,7 @@ pub const Timer = struct {
184 else => return std.os.unexpectedErrorPosix(errno),183 else => return std.os.unexpectedErrorPosix(errno),
185 }184 }
186 self.resolution = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec);185 self.resolution = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec);
187 186
188 result = posix.clock_gettime(monotonic_clock_id, &ts);187 result = posix.clock_gettime(monotonic_clock_id, &ts);
189 errno = posix.getErrno(result);188 errno = posix.getErrno(result);
190 if (errno != 0) return std.os.unexpectedErrorPosix(errno);189 if (errno != 0) return std.os.unexpectedErrorPosix(errno);
...@@ -199,9 +198,9 @@ pub const Timer = struct {...@@ -199,9 +198,9 @@ pub const Timer = struct {
199 }198 }
200 return self;199 return self;
201 }200 }
202 201
203 /// Reads the timer value since start or the last reset in nanoseconds202 /// Reads the timer value since start or the last reset in nanoseconds
204 pub fn read(self: &Timer) u64 {203 pub fn read(self: *Timer) u64 {
205 var clock = clockNative() - self.start_time;204 var clock = clockNative() - self.start_time;
206 return switch (builtin.os) {205 return switch (builtin.os) {
207 Os.windows => @divFloor(clock * ns_per_s, self.frequency),206 Os.windows => @divFloor(clock * ns_per_s, self.frequency),
...@@ -210,40 +209,38 @@ pub const Timer = struct {...@@ -210,40 +209,38 @@ pub const Timer = struct {
210 else => @compileError("Unsupported OS"),209 else => @compileError("Unsupported OS"),
211 };210 };
212 }211 }
213 212
214 /// Resets the timer value to 0/now.213 /// Resets the timer value to 0/now.
215 pub fn reset(self: &Timer) void214 pub fn reset(self: *Timer) void {
216 {
217 self.start_time = clockNative();215 self.start_time = clockNative();
218 }216 }
219 217
220 /// Returns the current value of the timer in nanoseconds, then resets it218 /// Returns the current value of the timer in nanoseconds, then resets it
221 pub fn lap(self: &Timer) u64 {219 pub fn lap(self: *Timer) u64 {
222 var now = clockNative();220 var now = clockNative();
223 var lap_time = self.read();221 var lap_time = self.read();
224 self.start_time = now;222 self.start_time = now;
225 return lap_time;223 return lap_time;
226 }224 }
227 225
228
229 const clockNative = switch (builtin.os) {226 const clockNative = switch (builtin.os) {
230 Os.windows => clockWindows,227 Os.windows => clockWindows,
231 Os.linux => clockLinux,228 Os.linux => clockLinux,
232 Os.macosx, Os.ios => clockDarwin,229 Os.macosx, Os.ios => clockDarwin,
233 else => @compileError("Unsupported OS"),230 else => @compileError("Unsupported OS"),
234 };231 };
235 232
236 fn clockWindows() u64 {233 fn clockWindows() u64 {
237 var result: i64 = undefined;234 var result: i64 = undefined;
238 var err = windows.QueryPerformanceCounter(&result);235 var err = windows.QueryPerformanceCounter(&result);
239 debug.assert(err != windows.FALSE);236 debug.assert(err != windows.FALSE);
240 return u64(result);237 return u64(result);
241 }238 }
242 239
243 fn clockDarwin() u64 {240 fn clockDarwin() u64 {
244 return darwin.mach_absolute_time();241 return darwin.mach_absolute_time();
245 }242 }
246 243
247 fn clockLinux() u64 {244 fn clockLinux() u64 {
248 var ts: posix.timespec = undefined;245 var ts: posix.timespec = undefined;
249 var result = posix.clock_gettime(monotonic_clock_id, &ts);246 var result = posix.clock_gettime(monotonic_clock_id, &ts);
...@@ -252,10 +249,6 @@ pub const Timer = struct {...@@ -252,10 +249,6 @@ pub const Timer = struct {
252 }249 }
253};250};
254251
255
256
257
258
259test "os.time.sleep" {252test "os.time.sleep" {
260 sleep(0, 1);253 sleep(0, 1);
261}254}
...@@ -263,7 +256,7 @@ test "os.time.sleep" {...@@ -263,7 +256,7 @@ test "os.time.sleep" {
263test "os.time.timestamp" {256test "os.time.timestamp" {
264 const ns_per_ms = (ns_per_s / ms_per_s);257 const ns_per_ms = (ns_per_s / ms_per_s);
265 const margin = 50;258 const margin = 50;
266 259
267 const time_0 = milliTimestamp();260 const time_0 = milliTimestamp();
268 sleep(0, ns_per_ms);261 sleep(0, ns_per_ms);
269 const time_1 = milliTimestamp();262 const time_1 = milliTimestamp();
...@@ -274,15 +267,15 @@ test "os.time.timestamp" {...@@ -274,15 +267,15 @@ test "os.time.timestamp" {
274test "os.time.Timer" {267test "os.time.Timer" {
275 const ns_per_ms = (ns_per_s / ms_per_s);268 const ns_per_ms = (ns_per_s / ms_per_s);
276 const margin = ns_per_ms * 50;269 const margin = ns_per_ms * 50;
277 270
278 var timer = try Timer.start();271 var timer = try Timer.start();
279 sleep(0, 10 * ns_per_ms);272 sleep(0, 10 * ns_per_ms);
280 const time_0 = timer.read();273 const time_0 = timer.read();
281 debug.assert(time_0 > 0 and time_0 < margin);274 debug.assert(time_0 > 0 and time_0 < margin);
282 275
283 const time_1 = timer.lap();276 const time_1 = timer.lap();
284 debug.assert(time_1 >= time_0);277 debug.assert(time_1 >= time_0);
285 278
286 timer.reset();279 timer.reset();
287 debug.assert(timer.read() < time_1);280 debug.assert(timer.read() < time_1);
288}281}
std/os/windows/error.zig+1188
...@@ -1,2379 +1,3567 @@...@@ -1,2379 +1,3567 @@
1/// The operation completed successfully.1/// The operation completed successfully.
2pub const SUCCESS = 0;2pub const SUCCESS = 0;
3
3/// Incorrect function.4/// Incorrect function.
4pub const INVALID_FUNCTION = 1;5pub const INVALID_FUNCTION = 1;
6
5/// The system cannot find the file specified.7/// The system cannot find the file specified.
6pub const FILE_NOT_FOUND = 2;8pub const FILE_NOT_FOUND = 2;
9
7/// The system cannot find the path specified.10/// The system cannot find the path specified.
8pub const PATH_NOT_FOUND = 3;11pub const PATH_NOT_FOUND = 3;
12
9/// The system cannot open the file.13/// The system cannot open the file.
10pub const TOO_MANY_OPEN_FILES = 4;14pub const TOO_MANY_OPEN_FILES = 4;
15
11/// Access is denied.16/// Access is denied.
12pub const ACCESS_DENIED = 5;17pub const ACCESS_DENIED = 5;
18
13/// The handle is invalid.19/// The handle is invalid.
14pub const INVALID_HANDLE = 6;20pub const INVALID_HANDLE = 6;
21
15/// The storage control blocks were destroyed.22/// The storage control blocks were destroyed.
16pub const ARENA_TRASHED = 7;23pub const ARENA_TRASHED = 7;
24
17/// Not enough storage is available to process this command.25/// Not enough storage is available to process this command.
18pub const NOT_ENOUGH_MEMORY = 8;26pub const NOT_ENOUGH_MEMORY = 8;
27
19/// The storage control block address is invalid.28/// The storage control block address is invalid.
20pub const INVALID_BLOCK = 9;29pub const INVALID_BLOCK = 9;
30
21/// The environment is incorrect.31/// The environment is incorrect.
22pub const BAD_ENVIRONMENT = 10;32pub const BAD_ENVIRONMENT = 10;
33
23/// An attempt was made to load a program with an incorrect format.34/// An attempt was made to load a program with an incorrect format.
24pub const BAD_FORMAT = 11;35pub const BAD_FORMAT = 11;
36
25/// The access code is invalid.37/// The access code is invalid.
26pub const INVALID_ACCESS = 12;38pub const INVALID_ACCESS = 12;
39
27/// The data is invalid.40/// The data is invalid.
28pub const INVALID_DATA = 13;41pub const INVALID_DATA = 13;
42
29/// Not enough storage is available to complete this operation.43/// Not enough storage is available to complete this operation.
30pub const OUTOFMEMORY = 14;44pub const OUTOFMEMORY = 14;
45
31/// The system cannot find the drive specified.46/// The system cannot find the drive specified.
32pub const INVALID_DRIVE = 15;47pub const INVALID_DRIVE = 15;
48
33/// The directory cannot be removed.49/// The directory cannot be removed.
34pub const CURRENT_DIRECTORY = 16;50pub const CURRENT_DIRECTORY = 16;
51
35/// The system cannot move the file to a different disk drive.52/// The system cannot move the file to a different disk drive.
36pub const NOT_SAME_DEVICE = 17;53pub const NOT_SAME_DEVICE = 17;
54
37/// There are no more files.55/// There are no more files.
38pub const NO_MORE_FILES = 18;56pub const NO_MORE_FILES = 18;
57
39/// The media is write protected.58/// The media is write protected.
40pub const WRITE_PROTECT = 19;59pub const WRITE_PROTECT = 19;
60
41/// The system cannot find the device specified.61/// The system cannot find the device specified.
42pub const BAD_UNIT = 20;62pub const BAD_UNIT = 20;
63
43/// The device is not ready.64/// The device is not ready.
44pub const NOT_READY = 21;65pub const NOT_READY = 21;
66
45/// The device does not recognize the command.67/// The device does not recognize the command.
46pub const BAD_COMMAND = 22;68pub const BAD_COMMAND = 22;
69
47/// Data error (cyclic redundancy check).70/// Data error (cyclic redundancy check).
48pub const CRC = 23;71pub const CRC = 23;
72
49/// The program issued a command but the command length is incorrect.73/// The program issued a command but the command length is incorrect.
50pub const BAD_LENGTH = 24;74pub const BAD_LENGTH = 24;
75
51/// The drive cannot locate a specific area or track on the disk.76/// The drive cannot locate a specific area or track on the disk.
52pub const SEEK = 25;77pub const SEEK = 25;
78
53/// The specified disk or diskette cannot be accessed.79/// The specified disk or diskette cannot be accessed.
54pub const NOT_DOS_DISK = 26;80pub const NOT_DOS_DISK = 26;
81
55/// The drive cannot find the sector requested.82/// The drive cannot find the sector requested.
56pub const SECTOR_NOT_FOUND = 27;83pub const SECTOR_NOT_FOUND = 27;
84
57/// The printer is out of paper.85/// The printer is out of paper.
58pub const OUT_OF_PAPER = 28;86pub const OUT_OF_PAPER = 28;
87
59/// The system cannot write to the specified device.88/// The system cannot write to the specified device.
60pub const WRITE_FAULT = 29;89pub const WRITE_FAULT = 29;
90
61/// The system cannot read from the specified device.91/// The system cannot read from the specified device.
62pub const READ_FAULT = 30;92pub const READ_FAULT = 30;
93
63/// A device attached to the system is not functioning.94/// A device attached to the system is not functioning.
64pub const GEN_FAILURE = 31;95pub const GEN_FAILURE = 31;
96
65/// The process cannot access the file because it is being used by another process.97/// The process cannot access the file because it is being used by another process.
66pub const SHARING_VIOLATION = 32;98pub const SHARING_VIOLATION = 32;
99
67/// The process cannot access the file because another process has locked a portion of the file.100/// The process cannot access the file because another process has locked a portion of the file.
68pub const LOCK_VIOLATION = 33;101pub const LOCK_VIOLATION = 33;
102
69/// The wrong diskette is in the drive. Insert %2 (Volume Serial Number: %3) into drive %1.103/// The wrong diskette is in the drive. Insert %2 (Volume Serial Number: %3) into drive %1.
70pub const WRONG_DISK = 34;104pub const WRONG_DISK = 34;
105
71/// Too many files opened for sharing.106/// Too many files opened for sharing.
72pub const SHARING_BUFFER_EXCEEDED = 36;107pub const SHARING_BUFFER_EXCEEDED = 36;
108
73/// Reached the end of the file.109/// Reached the end of the file.
74pub const HANDLE_EOF = 38;110pub const HANDLE_EOF = 38;
111
75/// The disk is full.112/// The disk is full.
76pub const HANDLE_DISK_FULL = 39;113pub const HANDLE_DISK_FULL = 39;
114
77/// The request is not supported.115/// The request is not supported.
78pub const NOT_SUPPORTED = 50;116pub const NOT_SUPPORTED = 50;
117
79/// Windows cannot find the network path. Verify that the network path is correct and the destination computer is not busy or turned off. If Windows still cannot find the network path, contact your network administrator.118/// Windows cannot find the network path. Verify that the network path is correct and the destination computer is not busy or turned off. If Windows still cannot find the network path, contact your network administrator.
80pub const REM_NOT_LIST = 51;119pub const REM_NOT_LIST = 51;
120
81/// You were not connected because a duplicate name exists on the network. If joining a domain, go to System in Control Panel to change the computer name and try again. If joining a workgroup, choose another workgroup name.121/// You were not connected because a duplicate name exists on the network. If joining a domain, go to System in Control Panel to change the computer name and try again. If joining a workgroup, choose another workgroup name.
82pub const DUP_NAME = 52;122pub const DUP_NAME = 52;
123
83/// The network path was not found.124/// The network path was not found.
84pub const BAD_NETPATH = 53;125pub const BAD_NETPATH = 53;
126
85/// The network is busy.127/// The network is busy.
86pub const NETWORK_BUSY = 54;128pub const NETWORK_BUSY = 54;
129
87/// The specified network resource or device is no longer available.130/// The specified network resource or device is no longer available.
88pub const DEV_NOT_EXIST = 55;131pub const DEV_NOT_EXIST = 55;
132
89/// The network BIOS command limit has been reached.133/// The network BIOS command limit has been reached.
90pub const TOO_MANY_CMDS = 56;134pub const TOO_MANY_CMDS = 56;
135
91/// A network adapter hardware error occurred.136/// A network adapter hardware error occurred.
92pub const ADAP_HDW_ERR = 57;137pub const ADAP_HDW_ERR = 57;
138
93/// The specified server cannot perform the requested operation.139/// The specified server cannot perform the requested operation.
94pub const BAD_NET_RESP = 58;140pub const BAD_NET_RESP = 58;
141
95/// An unexpected network error occurred.142/// An unexpected network error occurred.
96pub const UNEXP_NET_ERR = 59;143pub const UNEXP_NET_ERR = 59;
144
97/// The remote adapter is not compatible.145/// The remote adapter is not compatible.
98pub const BAD_REM_ADAP = 60;146pub const BAD_REM_ADAP = 60;
147
99/// The printer queue is full.148/// The printer queue is full.
100pub const PRINTQ_FULL = 61;149pub const PRINTQ_FULL = 61;
150
101/// Space to store the file waiting to be printed is not available on the server.151/// Space to store the file waiting to be printed is not available on the server.
102pub const NO_SPOOL_SPACE = 62;152pub const NO_SPOOL_SPACE = 62;
153
103/// Your file waiting to be printed was deleted.154/// Your file waiting to be printed was deleted.
104pub const PRINT_CANCELLED = 63;155pub const PRINT_CANCELLED = 63;
156
105/// The specified network name is no longer available.157/// The specified network name is no longer available.
106pub const NETNAME_DELETED = 64;158pub const NETNAME_DELETED = 64;
159
107/// Network access is denied.160/// Network access is denied.
108pub const NETWORK_ACCESS_DENIED = 65;161pub const NETWORK_ACCESS_DENIED = 65;
162
109/// The network resource type is not correct.163/// The network resource type is not correct.
110pub const BAD_DEV_TYPE = 66;164pub const BAD_DEV_TYPE = 66;
165
111/// The network name cannot be found.166/// The network name cannot be found.
112pub const BAD_NET_NAME = 67;167pub const BAD_NET_NAME = 67;
168
113/// The name limit for the local computer network adapter card was exceeded.169/// The name limit for the local computer network adapter card was exceeded.
114pub const TOO_MANY_NAMES = 68;170pub const TOO_MANY_NAMES = 68;
171
115/// The network BIOS session limit was exceeded.172/// The network BIOS session limit was exceeded.
116pub const TOO_MANY_SESS = 69;173pub const TOO_MANY_SESS = 69;
174
117/// The remote server has been paused or is in the process of being started.175/// The remote server has been paused or is in the process of being started.
118pub const SHARING_PAUSED = 70;176pub const SHARING_PAUSED = 70;
177
119/// No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept.178/// No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept.
120pub const REQ_NOT_ACCEP = 71;179pub const REQ_NOT_ACCEP = 71;
180
121/// The specified printer or disk device has been paused.181/// The specified printer or disk device has been paused.
122pub const REDIR_PAUSED = 72;182pub const REDIR_PAUSED = 72;
183
123/// The file exists.184/// The file exists.
124pub const FILE_EXISTS = 80;185pub const FILE_EXISTS = 80;
186
125/// The directory or file cannot be created.187/// The directory or file cannot be created.
126pub const CANNOT_MAKE = 82;188pub const CANNOT_MAKE = 82;
189
127/// Fail on INT 24.190/// Fail on INT 24.
128pub const FAIL_I24 = 83;191pub const FAIL_I24 = 83;
192
129/// Storage to process this request is not available.193/// Storage to process this request is not available.
130pub const OUT_OF_STRUCTURES = 84;194pub const OUT_OF_STRUCTURES = 84;
195
131/// The local device name is already in use.196/// The local device name is already in use.
132pub const ALREADY_ASSIGNED = 85;197pub const ALREADY_ASSIGNED = 85;
198
133/// The specified network password is not correct.199/// The specified network password is not correct.
134pub const INVALID_PASSWORD = 86;200pub const INVALID_PASSWORD = 86;
201
135/// The parameter is incorrect.202/// The parameter is incorrect.
136pub const INVALID_PARAMETER = 87;203pub const INVALID_PARAMETER = 87;
204
137/// A write fault occurred on the network.205/// A write fault occurred on the network.
138pub const NET_WRITE_FAULT = 88;206pub const NET_WRITE_FAULT = 88;
207
139/// The system cannot start another process at this time.208/// The system cannot start another process at this time.
140pub const NO_PROC_SLOTS = 89;209pub const NO_PROC_SLOTS = 89;
210
141/// Cannot create another system semaphore.211/// Cannot create another system semaphore.
142pub const TOO_MANY_SEMAPHORES = 100;212pub const TOO_MANY_SEMAPHORES = 100;
213
143/// The exclusive semaphore is owned by another process.214/// The exclusive semaphore is owned by another process.
144pub const EXCL_SEM_ALREADY_OWNED = 101;215pub const EXCL_SEM_ALREADY_OWNED = 101;
216
145/// The semaphore is set and cannot be closed.217/// The semaphore is set and cannot be closed.
146pub const SEM_IS_SET = 102;218pub const SEM_IS_SET = 102;
219
147/// The semaphore cannot be set again.220/// The semaphore cannot be set again.
148pub const TOO_MANY_SEM_REQUESTS = 103;221pub const TOO_MANY_SEM_REQUESTS = 103;
222
149/// Cannot request exclusive semaphores at interrupt time.223/// Cannot request exclusive semaphores at interrupt time.
150pub const INVALID_AT_INTERRUPT_TIME = 104;224pub const INVALID_AT_INTERRUPT_TIME = 104;
225
151/// The previous ownership of this semaphore has ended.226/// The previous ownership of this semaphore has ended.
152pub const SEM_OWNER_DIED = 105;227pub const SEM_OWNER_DIED = 105;
228
153/// Insert the diskette for drive %1.229/// Insert the diskette for drive %1.
154pub const SEM_USER_LIMIT = 106;230pub const SEM_USER_LIMIT = 106;
231
155/// The program stopped because an alternate diskette was not inserted.232/// The program stopped because an alternate diskette was not inserted.
156pub const DISK_CHANGE = 107;233pub const DISK_CHANGE = 107;
234
157/// The disk is in use or locked by another process.235/// The disk is in use or locked by another process.
158pub const DRIVE_LOCKED = 108;236pub const DRIVE_LOCKED = 108;
237
159/// The pipe has been ended.238/// The pipe has been ended.
160pub const BROKEN_PIPE = 109;239pub const BROKEN_PIPE = 109;
240
161/// The system cannot open the device or file specified.241/// The system cannot open the device or file specified.
162pub const OPEN_FAILED = 110;242pub const OPEN_FAILED = 110;
243
163/// The file name is too long.244/// The file name is too long.
164pub const BUFFER_OVERFLOW = 111;245pub const BUFFER_OVERFLOW = 111;
246
165/// There is not enough space on the disk.247/// There is not enough space on the disk.
166pub const DISK_FULL = 112;248pub const DISK_FULL = 112;
249
167/// No more internal file identifiers available.250/// No more internal file identifiers available.
168pub const NO_MORE_SEARCH_HANDLES = 113;251pub const NO_MORE_SEARCH_HANDLES = 113;
252
169/// The target internal file identifier is incorrect.253/// The target internal file identifier is incorrect.
170pub const INVALID_TARGET_HANDLE = 114;254pub const INVALID_TARGET_HANDLE = 114;
255
171/// The IOCTL call made by the application program is not correct.256/// The IOCTL call made by the application program is not correct.
172pub const INVALID_CATEGORY = 117;257pub const INVALID_CATEGORY = 117;
258
173/// The verify-on-write switch parameter value is not correct.259/// The verify-on-write switch parameter value is not correct.
174pub const INVALID_VERIFY_SWITCH = 118;260pub const INVALID_VERIFY_SWITCH = 118;
261
175/// The system does not support the command requested.262/// The system does not support the command requested.
176pub const BAD_DRIVER_LEVEL = 119;263pub const BAD_DRIVER_LEVEL = 119;
264
177/// This function is not supported on this system.265/// This function is not supported on this system.
178pub const CALL_NOT_IMPLEMENTED = 120;266pub const CALL_NOT_IMPLEMENTED = 120;
267
179/// The semaphore timeout period has expired.268/// The semaphore timeout period has expired.
180pub const SEM_TIMEOUT = 121;269pub const SEM_TIMEOUT = 121;
270
181/// The data area passed to a system call is too small.271/// The data area passed to a system call is too small.
182pub const INSUFFICIENT_BUFFER = 122;272pub const INSUFFICIENT_BUFFER = 122;
273
183/// The filename, directory name, or volume label syntax is incorrect.274/// The filename, directory name, or volume label syntax is incorrect.
184pub const INVALID_NAME = 123;275pub const INVALID_NAME = 123;
276
185/// The system call level is not correct.277/// The system call level is not correct.
186pub const INVALID_LEVEL = 124;278pub const INVALID_LEVEL = 124;
279
187/// The disk has no volume label.280/// The disk has no volume label.
188pub const NO_VOLUME_LABEL = 125;281pub const NO_VOLUME_LABEL = 125;
282
189/// The specified module could not be found.283/// The specified module could not be found.
190pub const MOD_NOT_FOUND = 126;284pub const MOD_NOT_FOUND = 126;
285
191/// The specified procedure could not be found.286/// The specified procedure could not be found.
192pub const PROC_NOT_FOUND = 127;287pub const PROC_NOT_FOUND = 127;
288
193/// There are no child processes to wait for.289/// There are no child processes to wait for.
194pub const WAIT_NO_CHILDREN = 128;290pub const WAIT_NO_CHILDREN = 128;
291
195/// The %1 application cannot be run in Win32 mode.292/// The %1 application cannot be run in Win32 mode.
196pub const CHILD_NOT_COMPLETE = 129;293pub const CHILD_NOT_COMPLETE = 129;
294
197/// Attempt to use a file handle to an open disk partition for an operation other than raw disk I/O.295/// Attempt to use a file handle to an open disk partition for an operation other than raw disk I/O.
198pub const DIRECT_ACCESS_HANDLE = 130;296pub const DIRECT_ACCESS_HANDLE = 130;
297
199/// An attempt was made to move the file pointer before the beginning of the file.298/// An attempt was made to move the file pointer before the beginning of the file.
200pub const NEGATIVE_SEEK = 131;299pub const NEGATIVE_SEEK = 131;
300
201/// The file pointer cannot be set on the specified device or file.301/// The file pointer cannot be set on the specified device or file.
202pub const SEEK_ON_DEVICE = 132;302pub const SEEK_ON_DEVICE = 132;
303
203/// A JOIN or SUBST command cannot be used for a drive that contains previously joined drives.304/// A JOIN or SUBST command cannot be used for a drive that contains previously joined drives.
204pub const IS_JOIN_TARGET = 133;305pub const IS_JOIN_TARGET = 133;
306
205/// An attempt was made to use a JOIN or SUBST command on a drive that has already been joined.307/// An attempt was made to use a JOIN or SUBST command on a drive that has already been joined.
206pub const IS_JOINED = 134;308pub const IS_JOINED = 134;
309
207/// An attempt was made to use a JOIN or SUBST command on a drive that has already been substituted.310/// An attempt was made to use a JOIN or SUBST command on a drive that has already been substituted.
208pub const IS_SUBSTED = 135;311pub const IS_SUBSTED = 135;
312
209/// The system tried to delete the JOIN of a drive that is not joined.313/// The system tried to delete the JOIN of a drive that is not joined.
210pub const NOT_JOINED = 136;314pub const NOT_JOINED = 136;
315
211/// The system tried to delete the substitution of a drive that is not substituted.316/// The system tried to delete the substitution of a drive that is not substituted.
212pub const NOT_SUBSTED = 137;317pub const NOT_SUBSTED = 137;
318
213/// The system tried to join a drive to a directory on a joined drive.319/// The system tried to join a drive to a directory on a joined drive.
214pub const JOIN_TO_JOIN = 138;320pub const JOIN_TO_JOIN = 138;
321
215/// The system tried to substitute a drive to a directory on a substituted drive.322/// The system tried to substitute a drive to a directory on a substituted drive.
216pub const SUBST_TO_SUBST = 139;323pub const SUBST_TO_SUBST = 139;
324
217/// The system tried to join a drive to a directory on a substituted drive.325/// The system tried to join a drive to a directory on a substituted drive.
218pub const JOIN_TO_SUBST = 140;326pub const JOIN_TO_SUBST = 140;
327
219/// The system tried to SUBST a drive to a directory on a joined drive.328/// The system tried to SUBST a drive to a directory on a joined drive.
220pub const SUBST_TO_JOIN = 141;329pub const SUBST_TO_JOIN = 141;
330
221/// The system cannot perform a JOIN or SUBST at this time.331/// The system cannot perform a JOIN or SUBST at this time.
222pub const BUSY_DRIVE = 142;332pub const BUSY_DRIVE = 142;
333
223/// The system cannot join or substitute a drive to or for a directory on the same drive.334/// The system cannot join or substitute a drive to or for a directory on the same drive.
224pub const SAME_DRIVE = 143;335pub const SAME_DRIVE = 143;
336
225/// The directory is not a subdirectory of the root directory.337/// The directory is not a subdirectory of the root directory.
226pub const DIR_NOT_ROOT = 144;338pub const DIR_NOT_ROOT = 144;
339
227/// The directory is not empty.340/// The directory is not empty.
228pub const DIR_NOT_EMPTY = 145;341pub const DIR_NOT_EMPTY = 145;
342
229/// The path specified is being used in a substitute.343/// The path specified is being used in a substitute.
230pub const IS_SUBST_PATH = 146;344pub const IS_SUBST_PATH = 146;
345
231/// Not enough resources are available to process this command.346/// Not enough resources are available to process this command.
232pub const IS_JOIN_PATH = 147;347pub const IS_JOIN_PATH = 147;
348
233/// The path specified cannot be used at this time.349/// The path specified cannot be used at this time.
234pub const PATH_BUSY = 148;350pub const PATH_BUSY = 148;
351
235/// An attempt was made to join or substitute a drive for which a directory on the drive is the target of a previous substitute.352/// An attempt was made to join or substitute a drive for which a directory on the drive is the target of a previous substitute.
236pub const IS_SUBST_TARGET = 149;353pub const IS_SUBST_TARGET = 149;
354
237/// System trace information was not specified in your CONFIG.SYS file, or tracing is disallowed.355/// System trace information was not specified in your CONFIG.SYS file, or tracing is disallowed.
238pub const SYSTEM_TRACE = 150;356pub const SYSTEM_TRACE = 150;
357
239/// The number of specified semaphore events for DosMuxSemWait is not correct.358/// The number of specified semaphore events for DosMuxSemWait is not correct.
240pub const INVALID_EVENT_COUNT = 151;359pub const INVALID_EVENT_COUNT = 151;
360
241/// DosMuxSemWait did not execute; too many semaphores are already set.361/// DosMuxSemWait did not execute; too many semaphores are already set.
242pub const TOO_MANY_MUXWAITERS = 152;362pub const TOO_MANY_MUXWAITERS = 152;
363
243/// The DosMuxSemWait list is not correct.364/// The DosMuxSemWait list is not correct.
244pub const INVALID_LIST_FORMAT = 153;365pub const INVALID_LIST_FORMAT = 153;
366
245/// The volume label you entered exceeds the label character limit of the target file system.367/// The volume label you entered exceeds the label character limit of the target file system.
246pub const LABEL_TOO_LONG = 154;368pub const LABEL_TOO_LONG = 154;
369
247/// Cannot create another thread.370/// Cannot create another thread.
248pub const TOO_MANY_TCBS = 155;371pub const TOO_MANY_TCBS = 155;
372
249/// The recipient process has refused the signal.373/// The recipient process has refused the signal.
250pub const SIGNAL_REFUSED = 156;374pub const SIGNAL_REFUSED = 156;
375
251/// The segment is already discarded and cannot be locked.376/// The segment is already discarded and cannot be locked.
252pub const DISCARDED = 157;377pub const DISCARDED = 157;
378
253/// The segment is already unlocked.379/// The segment is already unlocked.
254pub const NOT_LOCKED = 158;380pub const NOT_LOCKED = 158;
381
255/// The address for the thread ID is not correct.382/// The address for the thread ID is not correct.
256pub const BAD_THREADID_ADDR = 159;383pub const BAD_THREADID_ADDR = 159;
384
257/// One or more arguments are not correct.385/// One or more arguments are not correct.
258pub const BAD_ARGUMENTS = 160;386pub const BAD_ARGUMENTS = 160;
387
259/// The specified path is invalid.388/// The specified path is invalid.
260pub const BAD_PATHNAME = 161;389pub const BAD_PATHNAME = 161;
390
261/// A signal is already pending.391/// A signal is already pending.
262pub const SIGNAL_PENDING = 162;392pub const SIGNAL_PENDING = 162;
393
263/// No more threads can be created in the system.394/// No more threads can be created in the system.
264pub const MAX_THRDS_REACHED = 164;395pub const MAX_THRDS_REACHED = 164;
396
265/// Unable to lock a region of a file.397/// Unable to lock a region of a file.
266pub const LOCK_FAILED = 167;398pub const LOCK_FAILED = 167;
399
267/// The requested resource is in use.400/// The requested resource is in use.
268pub const BUSY = 170;401pub const BUSY = 170;
402
269/// Device's command support detection is in progress.403/// Device's command support detection is in progress.
270pub const DEVICE_SUPPORT_IN_PROGRESS = 171;404pub const DEVICE_SUPPORT_IN_PROGRESS = 171;
405
271/// A lock request was not outstanding for the supplied cancel region.406/// A lock request was not outstanding for the supplied cancel region.
272pub const CANCEL_VIOLATION = 173;407pub const CANCEL_VIOLATION = 173;
408
273/// The file system does not support atomic changes to the lock type.409/// The file system does not support atomic changes to the lock type.
274pub const ATOMIC_LOCKS_NOT_SUPPORTED = 174;410pub const ATOMIC_LOCKS_NOT_SUPPORTED = 174;
411
275/// The system detected a segment number that was not correct.412/// The system detected a segment number that was not correct.
276pub const INVALID_SEGMENT_NUMBER = 180;413pub const INVALID_SEGMENT_NUMBER = 180;
414
277/// The operating system cannot run %1.415/// The operating system cannot run %1.
278pub const INVALID_ORDINAL = 182;416pub const INVALID_ORDINAL = 182;
417
279/// Cannot create a file when that file already exists.418/// Cannot create a file when that file already exists.
280pub const ALREADY_EXISTS = 183;419pub const ALREADY_EXISTS = 183;
420
281/// The flag passed is not correct.421/// The flag passed is not correct.
282pub const INVALID_FLAG_NUMBER = 186;422pub const INVALID_FLAG_NUMBER = 186;
423
283/// The specified system semaphore name was not found.424/// The specified system semaphore name was not found.
284pub const SEM_NOT_FOUND = 187;425pub const SEM_NOT_FOUND = 187;
426
285/// The operating system cannot run %1.427/// The operating system cannot run %1.
286pub const INVALID_STARTING_CODESEG = 188;428pub const INVALID_STARTING_CODESEG = 188;
429
287/// The operating system cannot run %1.430/// The operating system cannot run %1.
288pub const INVALID_STACKSEG = 189;431pub const INVALID_STACKSEG = 189;
432
289/// The operating system cannot run %1.433/// The operating system cannot run %1.
290pub const INVALID_MODULETYPE = 190;434pub const INVALID_MODULETYPE = 190;
435
291/// Cannot run %1 in Win32 mode.436/// Cannot run %1 in Win32 mode.
292pub const INVALID_EXE_SIGNATURE = 191;437pub const INVALID_EXE_SIGNATURE = 191;
438
293/// The operating system cannot run %1.439/// The operating system cannot run %1.
294pub const EXE_MARKED_INVALID = 192;440pub const EXE_MARKED_INVALID = 192;
441
295/// %1 is not a valid Win32 application.442/// %1 is not a valid Win32 application.
296pub const BAD_EXE_FORMAT = 193;443pub const BAD_EXE_FORMAT = 193;
444
297/// The operating system cannot run %1.445/// The operating system cannot run %1.
298pub const ITERATED_DATA_EXCEEDS_64k = 194;446pub const ITERATED_DATA_EXCEEDS_64k = 194;
447
299/// The operating system cannot run %1.448/// The operating system cannot run %1.
300pub const INVALID_MINALLOCSIZE = 195;449pub const INVALID_MINALLOCSIZE = 195;
450
301/// The operating system cannot run this application program.451/// The operating system cannot run this application program.
302pub const DYNLINK_FROM_INVALID_RING = 196;452pub const DYNLINK_FROM_INVALID_RING = 196;
453
303/// The operating system is not presently configured to run this application.454/// The operating system is not presently configured to run this application.
304pub const IOPL_NOT_ENABLED = 197;455pub const IOPL_NOT_ENABLED = 197;
456
305/// The operating system cannot run %1.457/// The operating system cannot run %1.
306pub const INVALID_SEGDPL = 198;458pub const INVALID_SEGDPL = 198;
459
307/// The operating system cannot run this application program.460/// The operating system cannot run this application program.
308pub const AUTODATASEG_EXCEEDS_64k = 199;461pub const AUTODATASEG_EXCEEDS_64k = 199;
462
309/// The code segment cannot be greater than or equal to 64K.463/// The code segment cannot be greater than or equal to 64K.
310pub const RING2SEG_MUST_BE_MOVABLE = 200;464pub const RING2SEG_MUST_BE_MOVABLE = 200;
465
311/// The operating system cannot run %1.466/// The operating system cannot run %1.
312pub const RELOC_CHAIN_XEEDS_SEGLIM = 201;467pub const RELOC_CHAIN_XEEDS_SEGLIM = 201;
468
313/// The operating system cannot run %1.469/// The operating system cannot run %1.
314pub const INFLOOP_IN_RELOC_CHAIN = 202;470pub const INFLOOP_IN_RELOC_CHAIN = 202;
471
315/// The system could not find the environment option that was entered.472/// The system could not find the environment option that was entered.
316pub const ENVVAR_NOT_FOUND = 203;473pub const ENVVAR_NOT_FOUND = 203;
474
317/// No process in the command subtree has a signal handler.475/// No process in the command subtree has a signal handler.
318pub const NO_SIGNAL_SENT = 205;476pub const NO_SIGNAL_SENT = 205;
477
319/// The filename or extension is too long.478/// The filename or extension is too long.
320pub const FILENAME_EXCED_RANGE = 206;479pub const FILENAME_EXCED_RANGE = 206;
480
321/// The ring 2 stack is in use.481/// The ring 2 stack is in use.
322pub const RING2_STACK_IN_USE = 207;482pub const RING2_STACK_IN_USE = 207;
483
323/// The global filename characters, * or ?, are entered incorrectly or too many global filename characters are specified.484/// The global filename characters, * or ?, are entered incorrectly or too many global filename characters are specified.
324pub const META_EXPANSION_TOO_LONG = 208;485pub const META_EXPANSION_TOO_LONG = 208;
486
325/// The signal being posted is not correct.487/// The signal being posted is not correct.
326pub const INVALID_SIGNAL_NUMBER = 209;488pub const INVALID_SIGNAL_NUMBER = 209;
489
327/// The signal handler cannot be set.490/// The signal handler cannot be set.
328pub const THREAD_1_INACTIVE = 210;491pub const THREAD_1_INACTIVE = 210;
492
329/// The segment is locked and cannot be reallocated.493/// The segment is locked and cannot be reallocated.
330pub const LOCKED = 212;494pub const LOCKED = 212;
495
331/// Too many dynamic-link modules are attached to this program or dynamic-link module.496/// Too many dynamic-link modules are attached to this program or dynamic-link module.
332pub const TOO_MANY_MODULES = 214;497pub const TOO_MANY_MODULES = 214;
498
333/// Cannot nest calls to LoadModule.499/// Cannot nest calls to LoadModule.
334pub const NESTING_NOT_ALLOWED = 215;500pub const NESTING_NOT_ALLOWED = 215;
501
335/// This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher.502/// This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher.
336pub const EXE_MACHINE_TYPE_MISMATCH = 216;503pub const EXE_MACHINE_TYPE_MISMATCH = 216;
504
337/// The image file %1 is signed, unable to modify.505/// The image file %1 is signed, unable to modify.
338pub const EXE_CANNOT_MODIFY_SIGNED_BINARY = 217;506pub const EXE_CANNOT_MODIFY_SIGNED_BINARY = 217;
507
339/// The image file %1 is strong signed, unable to modify.508/// The image file %1 is strong signed, unable to modify.
340pub const EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY = 218;509pub const EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY = 218;
510
341/// This file is checked out or locked for editing by another user.511/// This file is checked out or locked for editing by another user.
342pub const FILE_CHECKED_OUT = 220;512pub const FILE_CHECKED_OUT = 220;
513
343/// The file must be checked out before saving changes.514/// The file must be checked out before saving changes.
344pub const CHECKOUT_REQUIRED = 221;515pub const CHECKOUT_REQUIRED = 221;
516
345/// The file type being saved or retrieved has been blocked.517/// The file type being saved or retrieved has been blocked.
346pub const BAD_FILE_TYPE = 222;518pub const BAD_FILE_TYPE = 222;
519
347/// The file size exceeds the limit allowed and cannot be saved.520/// The file size exceeds the limit allowed and cannot be saved.
348pub const FILE_TOO_LARGE = 223;521pub const FILE_TOO_LARGE = 223;
522
349/// Access Denied. Before opening files in this location, you must first add the web site to your trusted sites list, browse to the web site, and select the option to login automatically.523/// Access Denied. Before opening files in this location, you must first add the web site to your trusted sites list, browse to the web site, and select the option to login automatically.
350pub const FORMS_AUTH_REQUIRED = 224;524pub const FORMS_AUTH_REQUIRED = 224;
525
351/// Operation did not complete successfully because the file contains a virus or potentially unwanted software.526/// Operation did not complete successfully because the file contains a virus or potentially unwanted software.
352pub const VIRUS_INFECTED = 225;527pub const VIRUS_INFECTED = 225;
528
353/// This file contains a virus or potentially unwanted software and cannot be opened. Due to the nature of this virus or potentially unwanted software, the file has been removed from this location.529/// This file contains a virus or potentially unwanted software and cannot be opened. Due to the nature of this virus or potentially unwanted software, the file has been removed from this location.
354pub const VIRUS_DELETED = 226;530pub const VIRUS_DELETED = 226;
531
355/// The pipe is local.532/// The pipe is local.
356pub const PIPE_LOCAL = 229;533pub const PIPE_LOCAL = 229;
534
357/// The pipe state is invalid.535/// The pipe state is invalid.
358pub const BAD_PIPE = 230;536pub const BAD_PIPE = 230;
537
359/// All pipe instances are busy.538/// All pipe instances are busy.
360pub const PIPE_BUSY = 231;539pub const PIPE_BUSY = 231;
540
361/// The pipe is being closed.541/// The pipe is being closed.
362pub const NO_DATA = 232;542pub const NO_DATA = 232;
543
363/// No process is on the other end of the pipe.544/// No process is on the other end of the pipe.
364pub const PIPE_NOT_CONNECTED = 233;545pub const PIPE_NOT_CONNECTED = 233;
546
365/// More data is available.547/// More data is available.
366pub const MORE_DATA = 234;548pub const MORE_DATA = 234;
549
367/// The session was canceled.550/// The session was canceled.
368pub const VC_DISCONNECTED = 240;551pub const VC_DISCONNECTED = 240;
552
369/// The specified extended attribute name was invalid.553/// The specified extended attribute name was invalid.
370pub const INVALID_EA_NAME = 254;554pub const INVALID_EA_NAME = 254;
555
371/// The extended attributes are inconsistent.556/// The extended attributes are inconsistent.
372pub const EA_LIST_INCONSISTENT = 255;557pub const EA_LIST_INCONSISTENT = 255;
558
373/// The wait operation timed out.559/// The wait operation timed out.
374pub const IMEOUT = 258;560pub const IMEOUT = 258;
561
375/// No more data is available.562/// No more data is available.
376pub const NO_MORE_ITEMS = 259;563pub const NO_MORE_ITEMS = 259;
564
377/// The copy functions cannot be used.565/// The copy functions cannot be used.
378pub const CANNOT_COPY = 266;566pub const CANNOT_COPY = 266;
567
379/// The directory name is invalid.568/// The directory name is invalid.
380pub const DIRECTORY = 267;569pub const DIRECTORY = 267;
570
381/// The extended attributes did not fit in the buffer.571/// The extended attributes did not fit in the buffer.
382pub const EAS_DIDNT_FIT = 275;572pub const EAS_DIDNT_FIT = 275;
573
383/// The extended attribute file on the mounted file system is corrupt.574/// The extended attribute file on the mounted file system is corrupt.
384pub const EA_FILE_CORRUPT = 276;575pub const EA_FILE_CORRUPT = 276;
576
385/// The extended attribute table file is full.577/// The extended attribute table file is full.
386pub const EA_TABLE_FULL = 277;578pub const EA_TABLE_FULL = 277;
579
387/// The specified extended attribute handle is invalid.580/// The specified extended attribute handle is invalid.
388pub const INVALID_EA_HANDLE = 278;581pub const INVALID_EA_HANDLE = 278;
582
389/// The mounted file system does not support extended attributes.583/// The mounted file system does not support extended attributes.
390pub const EAS_NOT_SUPPORTED = 282;584pub const EAS_NOT_SUPPORTED = 282;
585
391/// Attempt to release mutex not owned by caller.586/// Attempt to release mutex not owned by caller.
392pub const NOT_OWNER = 288;587pub const NOT_OWNER = 288;
588
393/// Too many posts were made to a semaphore.589/// Too many posts were made to a semaphore.
394pub const TOO_MANY_POSTS = 298;590pub const TOO_MANY_POSTS = 298;
591
395/// Only part of a ReadProcessMemory or WriteProcessMemory request was completed.592/// Only part of a ReadProcessMemory or WriteProcessMemory request was completed.
396pub const PARTIAL_COPY = 299;593pub const PARTIAL_COPY = 299;
594
397/// The oplock request is denied.595/// The oplock request is denied.
398pub const OPLOCK_NOT_GRANTED = 300;596pub const OPLOCK_NOT_GRANTED = 300;
597
399/// An invalid oplock acknowledgment was received by the system.598/// An invalid oplock acknowledgment was received by the system.
400pub const INVALID_OPLOCK_PROTOCOL = 301;599pub const INVALID_OPLOCK_PROTOCOL = 301;
600
401/// The volume is too fragmented to complete this operation.601/// The volume is too fragmented to complete this operation.
402pub const DISK_TOO_FRAGMENTED = 302;602pub const DISK_TOO_FRAGMENTED = 302;
603
403/// The file cannot be opened because it is in the process of being deleted.604/// The file cannot be opened because it is in the process of being deleted.
404pub const DELETE_PENDING = 303;605pub const DELETE_PENDING = 303;
606
405/// Short name settings may not be changed on this volume due to the global registry setting.607/// Short name settings may not be changed on this volume due to the global registry setting.
406pub const INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING = 304;608pub const INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING = 304;
609
407/// Short names are not enabled on this volume.610/// Short names are not enabled on this volume.
408pub const SHORT_NAMES_NOT_ENABLED_ON_VOLUME = 305;611pub const SHORT_NAMES_NOT_ENABLED_ON_VOLUME = 305;
612
409/// The security stream for the given volume is in an inconsistent state. Please run CHKDSK on the volume.613/// The security stream for the given volume is in an inconsistent state. Please run CHKDSK on the volume.
410pub const SECURITY_STREAM_IS_INCONSISTENT = 306;614pub const SECURITY_STREAM_IS_INCONSISTENT = 306;
615
411/// A requested file lock operation cannot be processed due to an invalid byte range.616/// A requested file lock operation cannot be processed due to an invalid byte range.
412pub const INVALID_LOCK_RANGE = 307;617pub const INVALID_LOCK_RANGE = 307;
618
413/// The subsystem needed to support the image type is not present.619/// The subsystem needed to support the image type is not present.
414pub const IMAGE_SUBSYSTEM_NOT_PRESENT = 308;620pub const IMAGE_SUBSYSTEM_NOT_PRESENT = 308;
621
415/// The specified file already has a notification GUID associated with it.622/// The specified file already has a notification GUID associated with it.
416pub const NOTIFICATION_GUID_ALREADY_DEFINED = 309;623pub const NOTIFICATION_GUID_ALREADY_DEFINED = 309;
624
417/// An invalid exception handler routine has been detected.625/// An invalid exception handler routine has been detected.
418pub const INVALID_EXCEPTION_HANDLER = 310;626pub const INVALID_EXCEPTION_HANDLER = 310;
627
419/// Duplicate privileges were specified for the token.628/// Duplicate privileges were specified for the token.
420pub const DUPLICATE_PRIVILEGES = 311;629pub const DUPLICATE_PRIVILEGES = 311;
630
421/// No ranges for the specified operation were able to be processed.631/// No ranges for the specified operation were able to be processed.
422pub const NO_RANGES_PROCESSED = 312;632pub const NO_RANGES_PROCESSED = 312;
633
423/// Operation is not allowed on a file system internal file.634/// Operation is not allowed on a file system internal file.
424pub const NOT_ALLOWED_ON_SYSTEM_FILE = 313;635pub const NOT_ALLOWED_ON_SYSTEM_FILE = 313;
636
425/// The physical resources of this disk have been exhausted.637/// The physical resources of this disk have been exhausted.
426pub const DISK_RESOURCES_EXHAUSTED = 314;638pub const DISK_RESOURCES_EXHAUSTED = 314;
639
427/// The token representing the data is invalid.640/// The token representing the data is invalid.
428pub const INVALID_TOKEN = 315;641pub const INVALID_TOKEN = 315;
642
429/// The device does not support the command feature.643/// The device does not support the command feature.
430pub const DEVICE_FEATURE_NOT_SUPPORTED = 316;644pub const DEVICE_FEATURE_NOT_SUPPORTED = 316;
645
431/// The system cannot find message text for message number 0x%1 in the message file for %2.646/// The system cannot find message text for message number 0x%1 in the message file for %2.
432pub const MR_MID_NOT_FOUND = 317;647pub const MR_MID_NOT_FOUND = 317;
648
433/// The scope specified was not found.649/// The scope specified was not found.
434pub const SCOPE_NOT_FOUND = 318;650pub const SCOPE_NOT_FOUND = 318;
651
435/// The Central Access Policy specified is not defined on the target machine.652/// The Central Access Policy specified is not defined on the target machine.
436pub const UNDEFINED_SCOPE = 319;653pub const UNDEFINED_SCOPE = 319;
654
437/// The Central Access Policy obtained from Active Directory is invalid.655/// The Central Access Policy obtained from Active Directory is invalid.
438pub const INVALID_CAP = 320;656pub const INVALID_CAP = 320;
657
439/// The device is unreachable.658/// The device is unreachable.
440pub const DEVICE_UNREACHABLE = 321;659pub const DEVICE_UNREACHABLE = 321;
660
441/// The target device has insufficient resources to complete the operation.661/// The target device has insufficient resources to complete the operation.
442pub const DEVICE_NO_RESOURCES = 322;662pub const DEVICE_NO_RESOURCES = 322;
663
443/// A data integrity checksum error occurred. Data in the file stream is corrupt.664/// A data integrity checksum error occurred. Data in the file stream is corrupt.
444pub const DATA_CHECKSUM_ERROR = 323;665pub const DATA_CHECKSUM_ERROR = 323;
666
445/// An attempt was made to modify both a KERNEL and normal Extended Attribute (EA) in the same operation.667/// An attempt was made to modify both a KERNEL and normal Extended Attribute (EA) in the same operation.
446pub const INTERMIXED_KERNEL_EA_OPERATION = 324;668pub const INTERMIXED_KERNEL_EA_OPERATION = 324;
669
447/// Device does not support file-level TRIM.670/// Device does not support file-level TRIM.
448pub const FILE_LEVEL_TRIM_NOT_SUPPORTED = 326;671pub const FILE_LEVEL_TRIM_NOT_SUPPORTED = 326;
672
449/// The command specified a data offset that does not align to the device's granularity/alignment.673/// The command specified a data offset that does not align to the device's granularity/alignment.
450pub const OFFSET_ALIGNMENT_VIOLATION = 327;674pub const OFFSET_ALIGNMENT_VIOLATION = 327;
675
451/// The command specified an invalid field in its parameter list.676/// The command specified an invalid field in its parameter list.
452pub const INVALID_FIELD_IN_PARAMETER_LIST = 328;677pub const INVALID_FIELD_IN_PARAMETER_LIST = 328;
678
453/// An operation is currently in progress with the device.679/// An operation is currently in progress with the device.
454pub const OPERATION_IN_PROGRESS = 329;680pub const OPERATION_IN_PROGRESS = 329;
681
455/// An attempt was made to send down the command via an invalid path to the target device.682/// An attempt was made to send down the command via an invalid path to the target device.
456pub const BAD_DEVICE_PATH = 330;683pub const BAD_DEVICE_PATH = 330;
684
457/// The command specified a number of descriptors that exceeded the maximum supported by the device.685/// The command specified a number of descriptors that exceeded the maximum supported by the device.
458pub const TOO_MANY_DESCRIPTORS = 331;686pub const TOO_MANY_DESCRIPTORS = 331;
687
459/// Scrub is disabled on the specified file.688/// Scrub is disabled on the specified file.
460pub const SCRUB_DATA_DISABLED = 332;689pub const SCRUB_DATA_DISABLED = 332;
690
461/// The storage device does not provide redundancy.691/// The storage device does not provide redundancy.
462pub const NOT_REDUNDANT_STORAGE = 333;692pub const NOT_REDUNDANT_STORAGE = 333;
693
463/// An operation is not supported on a resident file.694/// An operation is not supported on a resident file.
464pub const RESIDENT_FILE_NOT_SUPPORTED = 334;695pub const RESIDENT_FILE_NOT_SUPPORTED = 334;
696
465/// An operation is not supported on a compressed file.697/// An operation is not supported on a compressed file.
466pub const COMPRESSED_FILE_NOT_SUPPORTED = 335;698pub const COMPRESSED_FILE_NOT_SUPPORTED = 335;
699
467/// An operation is not supported on a directory.700/// An operation is not supported on a directory.
468pub const DIRECTORY_NOT_SUPPORTED = 336;701pub const DIRECTORY_NOT_SUPPORTED = 336;
702
469/// The specified copy of the requested data could not be read.703/// The specified copy of the requested data could not be read.
470pub const NOT_READ_FROM_COPY = 337;704pub const NOT_READ_FROM_COPY = 337;
705
471/// No action was taken as a system reboot is required.706/// No action was taken as a system reboot is required.
472pub const FAIL_NOACTION_REBOOT = 350;707pub const FAIL_NOACTION_REBOOT = 350;
708
473/// The shutdown operation failed.709/// The shutdown operation failed.
474pub const FAIL_SHUTDOWN = 351;710pub const FAIL_SHUTDOWN = 351;
711
475/// The restart operation failed.712/// The restart operation failed.
476pub const FAIL_RESTART = 352;713pub const FAIL_RESTART = 352;
714
477/// The maximum number of sessions has been reached.715/// The maximum number of sessions has been reached.
478pub const MAX_SESSIONS_REACHED = 353;716pub const MAX_SESSIONS_REACHED = 353;
717
479/// The thread is already in background processing mode.718/// The thread is already in background processing mode.
480pub const THREAD_MODE_ALREADY_BACKGROUND = 400;719pub const THREAD_MODE_ALREADY_BACKGROUND = 400;
720
481/// The thread is not in background processing mode.721/// The thread is not in background processing mode.
482pub const THREAD_MODE_NOT_BACKGROUND = 401;722pub const THREAD_MODE_NOT_BACKGROUND = 401;
723
483/// The process is already in background processing mode.724/// The process is already in background processing mode.
484pub const PROCESS_MODE_ALREADY_BACKGROUND = 402;725pub const PROCESS_MODE_ALREADY_BACKGROUND = 402;
726
485/// The process is not in background processing mode.727/// The process is not in background processing mode.
486pub const PROCESS_MODE_NOT_BACKGROUND = 403;728pub const PROCESS_MODE_NOT_BACKGROUND = 403;
729
487/// Attempt to access invalid address.730/// Attempt to access invalid address.
488pub const INVALID_ADDRESS = 487;731pub const INVALID_ADDRESS = 487;
732
489/// User profile cannot be loaded.733/// User profile cannot be loaded.
490pub const USER_PROFILE_LOAD = 500;734pub const USER_PROFILE_LOAD = 500;
735
491/// Arithmetic result exceeded 32 bits.736/// Arithmetic result exceeded 32 bits.
492pub const ARITHMETIC_OVERFLOW = 534;737pub const ARITHMETIC_OVERFLOW = 534;
738
493/// There is a process on other end of the pipe.739/// There is a process on other end of the pipe.
494pub const PIPE_CONNECTED = 535;740pub const PIPE_CONNECTED = 535;
741
495/// Waiting for a process to open the other end of the pipe.742/// Waiting for a process to open the other end of the pipe.
496pub const PIPE_LISTENING = 536;743pub const PIPE_LISTENING = 536;
744
497/// Application verifier has found an error in the current process.745/// Application verifier has found an error in the current process.
498pub const VERIFIER_STOP = 537;746pub const VERIFIER_STOP = 537;
747
499/// An error occurred in the ABIOS subsystem.748/// An error occurred in the ABIOS subsystem.
500pub const ABIOS_ERROR = 538;749pub const ABIOS_ERROR = 538;
750
501/// A warning occurred in the WX86 subsystem.751/// A warning occurred in the WX86 subsystem.
502pub const WX86_WARNING = 539;752pub const WX86_WARNING = 539;
753
503/// An error occurred in the WX86 subsystem.754/// An error occurred in the WX86 subsystem.
504pub const WX86_ERROR = 540;755pub const WX86_ERROR = 540;
756
505/// An attempt was made to cancel or set a timer that has an associated APC and the subject thread is not the thread that originally set the timer with an associated APC routine.757/// An attempt was made to cancel or set a timer that has an associated APC and the subject thread is not the thread that originally set the timer with an associated APC routine.
506pub const TIMER_NOT_CANCELED = 541;758pub const TIMER_NOT_CANCELED = 541;
759
507/// Unwind exception code.760/// Unwind exception code.
508pub const UNWIND = 542;761pub const UNWIND = 542;
762
509/// An invalid or unaligned stack was encountered during an unwind operation.763/// An invalid or unaligned stack was encountered during an unwind operation.
510pub const BAD_STACK = 543;764pub const BAD_STACK = 543;
765
511/// An invalid unwind target was encountered during an unwind operation.766/// An invalid unwind target was encountered during an unwind operation.
512pub const INVALID_UNWIND_TARGET = 544;767pub const INVALID_UNWIND_TARGET = 544;
768
513/// Invalid Object Attributes specified to NtCreatePort or invalid Port Attributes specified to NtConnectPort769/// Invalid Object Attributes specified to NtCreatePort or invalid Port Attributes specified to NtConnectPort
514pub const INVALID_PORT_ATTRIBUTES = 545;770pub const INVALID_PORT_ATTRIBUTES = 545;
771
515/// Length of message passed to NtRequestPort or NtRequestWaitReplyPort was longer than the maximum message allowed by the port.772/// Length of message passed to NtRequestPort or NtRequestWaitReplyPort was longer than the maximum message allowed by the port.
516pub const PORT_MESSAGE_TOO_LONG = 546;773pub const PORT_MESSAGE_TOO_LONG = 546;
774
517/// An attempt was made to lower a quota limit below the current usage.775/// An attempt was made to lower a quota limit below the current usage.
518pub const INVALID_QUOTA_LOWER = 547;776pub const INVALID_QUOTA_LOWER = 547;
777
519/// An attempt was made to attach to a device that was already attached to another device.778/// An attempt was made to attach to a device that was already attached to another device.
520pub const DEVICE_ALREADY_ATTACHED = 548;779pub const DEVICE_ALREADY_ATTACHED = 548;
780
521/// An attempt was made to execute an instruction at an unaligned address and the host system does not support unaligned instruction references.781/// An attempt was made to execute an instruction at an unaligned address and the host system does not support unaligned instruction references.
522pub const INSTRUCTION_MISALIGNMENT = 549;782pub const INSTRUCTION_MISALIGNMENT = 549;
783
523/// Profiling not started.784/// Profiling not started.
524pub const PROFILING_NOT_STARTED = 550;785pub const PROFILING_NOT_STARTED = 550;
786
525/// Profiling not stopped.787/// Profiling not stopped.
526pub const PROFILING_NOT_STOPPED = 551;788pub const PROFILING_NOT_STOPPED = 551;
789
527/// The passed ACL did not contain the minimum required information.790/// The passed ACL did not contain the minimum required information.
528pub const COULD_NOT_INTERPRET = 552;791pub const COULD_NOT_INTERPRET = 552;
792
529/// The number of active profiling objects is at the maximum and no more may be started.793/// The number of active profiling objects is at the maximum and no more may be started.
530pub const PROFILING_AT_LIMIT = 553;794pub const PROFILING_AT_LIMIT = 553;
795
531/// Used to indicate that an operation cannot continue without blocking for I/O.796/// Used to indicate that an operation cannot continue without blocking for I/O.
532pub const CANT_WAIT = 554;797pub const CANT_WAIT = 554;
798
533/// Indicates that a thread attempted to terminate itself by default (called NtTerminateThread with NULL) and it was the last thread in the current process.799/// Indicates that a thread attempted to terminate itself by default (called NtTerminateThread with NULL) and it was the last thread in the current process.
534pub const CANT_TERMINATE_SELF = 555;800pub const CANT_TERMINATE_SELF = 555;
801
535/// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception.802/// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception.
536pub const UNEXPECTED_MM_CREATE_ERR = 556;803pub const UNEXPECTED_MM_CREATE_ERR = 556;
804
537/// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception.805/// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception.
538pub const UNEXPECTED_MM_MAP_ERROR = 557;806pub const UNEXPECTED_MM_MAP_ERROR = 557;
807
539/// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception.808/// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception.
540pub const UNEXPECTED_MM_EXTEND_ERR = 558;809pub const UNEXPECTED_MM_EXTEND_ERR = 558;
810
541/// A malformed function table was encountered during an unwind operation.811/// A malformed function table was encountered during an unwind operation.
542pub const BAD_FUNCTION_TABLE = 559;812pub const BAD_FUNCTION_TABLE = 559;
813
543/// Indicates that an attempt was made to assign protection to a file system file or directory and one of the SIDs in the security descriptor could not be translated into a GUID that could be stored by the file system. This causes the protection attempt to fail, which may cause a file creation attempt to fail.814/// Indicates that an attempt was made to assign protection to a file system file or directory and one of the SIDs in the security descriptor could not be translated into a GUID that could be stored by the file system. This causes the protection attempt to fail, which may cause a file creation attempt to fail.
544pub const NO_GUID_TRANSLATION = 560;815pub const NO_GUID_TRANSLATION = 560;
816
545/// Indicates that an attempt was made to grow an LDT by setting its size, or that the size was not an even number of selectors.817/// Indicates that an attempt was made to grow an LDT by setting its size, or that the size was not an even number of selectors.
546pub const INVALID_LDT_SIZE = 561;818pub const INVALID_LDT_SIZE = 561;
819
547/// Indicates that the starting value for the LDT information was not an integral multiple of the selector size.820/// Indicates that the starting value for the LDT information was not an integral multiple of the selector size.
548pub const INVALID_LDT_OFFSET = 563;821pub const INVALID_LDT_OFFSET = 563;
822
549/// Indicates that the user supplied an invalid descriptor when trying to set up Ldt descriptors.823/// Indicates that the user supplied an invalid descriptor when trying to set up Ldt descriptors.
550pub const INVALID_LDT_DESCRIPTOR = 564;824pub const INVALID_LDT_DESCRIPTOR = 564;
825
551/// Indicates a process has too many threads to perform the requested action. For example, assignment of a primary token may only be performed when a process has zero or one threads.826/// Indicates a process has too many threads to perform the requested action. For example, assignment of a primary token may only be performed when a process has zero or one threads.
552pub const TOO_MANY_THREADS = 565;827pub const TOO_MANY_THREADS = 565;
828
553/// An attempt was made to operate on a thread within a specific process, but the thread specified is not in the process specified.829/// An attempt was made to operate on a thread within a specific process, but the thread specified is not in the process specified.
554pub const THREAD_NOT_IN_PROCESS = 566;830pub const THREAD_NOT_IN_PROCESS = 566;
831
555/// Page file quota was exceeded.832/// Page file quota was exceeded.
556pub const PAGEFILE_QUOTA_EXCEEDED = 567;833pub const PAGEFILE_QUOTA_EXCEEDED = 567;
834
557/// The Netlogon service cannot start because another Netlogon service running in the domain conflicts with the specified role.835/// The Netlogon service cannot start because another Netlogon service running in the domain conflicts with the specified role.
558pub const LOGON_SERVER_CONFLICT = 568;836pub const LOGON_SERVER_CONFLICT = 568;
837
559/// The SAM database on a Windows Server is significantly out of synchronization with the copy on the Domain Controller. A complete synchronization is required.838/// The SAM database on a Windows Server is significantly out of synchronization with the copy on the Domain Controller. A complete synchronization is required.
560pub const SYNCHRONIZATION_REQUIRED = 569;839pub const SYNCHRONIZATION_REQUIRED = 569;
840
561/// The NtCreateFile API failed. This error should never be returned to an application, it is a place holder for the Windows Lan Manager Redirector to use in its internal error mapping routines.841/// The NtCreateFile API failed. This error should never be returned to an application, it is a place holder for the Windows Lan Manager Redirector to use in its internal error mapping routines.
562pub const NET_OPEN_FAILED = 570;842pub const NET_OPEN_FAILED = 570;
843
563/// {Privilege Failed} The I/O permissions for the process could not be changed.844/// {Privilege Failed} The I/O permissions for the process could not be changed.
564pub const IO_PRIVILEGE_FAILED = 571;845pub const IO_PRIVILEGE_FAILED = 571;
846
565/// {Application Exit by CTRL+C} The application terminated as a result of a CTRL+C.847/// {Application Exit by CTRL+C} The application terminated as a result of a CTRL+C.
566pub const CONTROL_C_EXIT = 572;848pub const CONTROL_C_EXIT = 572;
849
567/// {Missing System File} The required system file %hs is bad or missing.850/// {Missing System File} The required system file %hs is bad or missing.
568pub const MISSING_SYSTEMFILE = 573;851pub const MISSING_SYSTEMFILE = 573;
852
569/// {Application Error} The exception %s (0x%08lx) occurred in the application at location 0x%08lx.853/// {Application Error} The exception %s (0x%08lx) occurred in the application at location 0x%08lx.
570pub const UNHANDLED_EXCEPTION = 574;854pub const UNHANDLED_EXCEPTION = 574;
855
571/// {Application Error} The application was unable to start correctly (0x%lx). Click OK to close the application.856/// {Application Error} The application was unable to start correctly (0x%lx). Click OK to close the application.
572pub const APP_INIT_FAILURE = 575;857pub const APP_INIT_FAILURE = 575;
858
573/// {Unable to Create Paging File} The creation of the paging file %hs failed (%lx). The requested size was %ld.859/// {Unable to Create Paging File} The creation of the paging file %hs failed (%lx). The requested size was %ld.
574pub const PAGEFILE_CREATE_FAILED = 576;860pub const PAGEFILE_CREATE_FAILED = 576;
861
575/// Windows cannot verify the digital signature for this file. A recent hardware or software change might have installed a file that is signed incorrectly or damaged, or that might be malicious software from an unknown source.862/// Windows cannot verify the digital signature for this file. A recent hardware or software change might have installed a file that is signed incorrectly or damaged, or that might be malicious software from an unknown source.
576pub const INVALID_IMAGE_HASH = 577;863pub const INVALID_IMAGE_HASH = 577;
864
577/// {No Paging File Specified} No paging file was specified in the system configuration.865/// {No Paging File Specified} No paging file was specified in the system configuration.
578pub const NO_PAGEFILE = 578;866pub const NO_PAGEFILE = 578;
867
579/// {EXCEPTION} A real-mode application issued a floating-point instruction and floating-point hardware is not present.868/// {EXCEPTION} A real-mode application issued a floating-point instruction and floating-point hardware is not present.
580pub const ILLEGAL_FLOAT_CONTEXT = 579;869pub const ILLEGAL_FLOAT_CONTEXT = 579;
870
581/// An event pair synchronization operation was performed using the thread specific client/server event pair object, but no event pair object was associated with the thread.871/// An event pair synchronization operation was performed using the thread specific client/server event pair object, but no event pair object was associated with the thread.
582pub const NO_EVENT_PAIR = 580;872pub const NO_EVENT_PAIR = 580;
873
583/// A Windows Server has an incorrect configuration.874/// A Windows Server has an incorrect configuration.
584pub const DOMAIN_CTRLR_CONFIG_ERROR = 581;875pub const DOMAIN_CTRLR_CONFIG_ERROR = 581;
876
585/// An illegal character was encountered. For a multi-byte character set this includes a lead byte without a succeeding trail byte. For the Unicode character set this includes the characters 0xFFFF and 0xFFFE.877/// An illegal character was encountered. For a multi-byte character set this includes a lead byte without a succeeding trail byte. For the Unicode character set this includes the characters 0xFFFF and 0xFFFE.
586pub const ILLEGAL_CHARACTER = 582;878pub const ILLEGAL_CHARACTER = 582;
879
587/// The Unicode character is not defined in the Unicode character set installed on the system.880/// The Unicode character is not defined in the Unicode character set installed on the system.
588pub const UNDEFINED_CHARACTER = 583;881pub const UNDEFINED_CHARACTER = 583;
882
589/// The paging file cannot be created on a floppy diskette.883/// The paging file cannot be created on a floppy diskette.
590pub const FLOPPY_VOLUME = 584;884pub const FLOPPY_VOLUME = 584;
885
591/// The system BIOS failed to connect a system interrupt to the device or bus for which the device is connected.886/// The system BIOS failed to connect a system interrupt to the device or bus for which the device is connected.
592pub const BIOS_FAILED_TO_CONNECT_INTERRUPT = 585;887pub const BIOS_FAILED_TO_CONNECT_INTERRUPT = 585;
888
593/// This operation is only allowed for the Primary Domain Controller of the domain.889/// This operation is only allowed for the Primary Domain Controller of the domain.
594pub const BACKUP_CONTROLLER = 586;890pub const BACKUP_CONTROLLER = 586;
891
595/// An attempt was made to acquire a mutant such that its maximum count would have been exceeded.892/// An attempt was made to acquire a mutant such that its maximum count would have been exceeded.
596pub const MUTANT_LIMIT_EXCEEDED = 587;893pub const MUTANT_LIMIT_EXCEEDED = 587;
894
597/// A volume has been accessed for which a file system driver is required that has not yet been loaded.895/// A volume has been accessed for which a file system driver is required that has not yet been loaded.
598pub const FS_DRIVER_REQUIRED = 588;896pub const FS_DRIVER_REQUIRED = 588;
897
599/// {Registry File Failure} The registry cannot load the hive (file): %hs or its log or alternate. It is corrupt, absent, or not writable.898/// {Registry File Failure} The registry cannot load the hive (file): %hs or its log or alternate. It is corrupt, absent, or not writable.
600pub const CANNOT_LOAD_REGISTRY_FILE = 589;899pub const CANNOT_LOAD_REGISTRY_FILE = 589;
900
601/// {Unexpected Failure in DebugActiveProcess} An unexpected failure occurred while processing a DebugActiveProcess API request. You may choose OK to terminate the process, or Cancel to ignore the error.901/// {Unexpected Failure in DebugActiveProcess} An unexpected failure occurred while processing a DebugActiveProcess API request. You may choose OK to terminate the process, or Cancel to ignore the error.
602pub const DEBUG_ATTACH_FAILED = 590;902pub const DEBUG_ATTACH_FAILED = 590;
903
603/// {Fatal System Error} The %hs system process terminated unexpectedly with a status of 0x%08x (0x%08x 0x%08x). The system has been shut down.904/// {Fatal System Error} The %hs system process terminated unexpectedly with a status of 0x%08x (0x%08x 0x%08x). The system has been shut down.
604pub const SYSTEM_PROCESS_TERMINATED = 591;905pub const SYSTEM_PROCESS_TERMINATED = 591;
906
605/// {Data Not Accepted} The TDI client could not handle the data received during an indication.907/// {Data Not Accepted} The TDI client could not handle the data received during an indication.
606pub const DATA_NOT_ACCEPTED = 592;908pub const DATA_NOT_ACCEPTED = 592;
909
607/// NTVDM encountered a hard error.910/// NTVDM encountered a hard error.
608pub const VDM_HARD_ERROR = 593;911pub const VDM_HARD_ERROR = 593;
912
609/// {Cancel Timeout} The driver %hs failed to complete a cancelled I/O request in the allotted time.913/// {Cancel Timeout} The driver %hs failed to complete a cancelled I/O request in the allotted time.
610pub const DRIVER_CANCEL_TIMEOUT = 594;914pub const DRIVER_CANCEL_TIMEOUT = 594;
915
611/// {Reply Message Mismatch} An attempt was made to reply to an LPC message, but the thread specified by the client ID in the message was not waiting on that message.916/// {Reply Message Mismatch} An attempt was made to reply to an LPC message, but the thread specified by the client ID in the message was not waiting on that message.
612pub const REPLY_MESSAGE_MISMATCH = 595;917pub const REPLY_MESSAGE_MISMATCH = 595;
918
613/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs. The data has been lost. This error may be caused by a failure of your computer hardware or network connection. Please try to save this file elsewhere.919/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs. The data has been lost. This error may be caused by a failure of your computer hardware or network connection. Please try to save this file elsewhere.
614pub const LOST_WRITEBEHIND_DATA = 596;920pub const LOST_WRITEBEHIND_DATA = 596;
921
615/// The parameter(s) passed to the server in the client/server shared memory window were invalid. Too much data may have been put in the shared memory window.922/// The parameter(s) passed to the server in the client/server shared memory window were invalid. Too much data may have been put in the shared memory window.
616pub const CLIENT_SERVER_PARAMETERS_INVALID = 597;923pub const CLIENT_SERVER_PARAMETERS_INVALID = 597;
924
617/// The stream is not a tiny stream.925/// The stream is not a tiny stream.
618pub const NOT_TINY_STREAM = 598;926pub const NOT_TINY_STREAM = 598;
927
619/// The request must be handled by the stack overflow code.928/// The request must be handled by the stack overflow code.
620pub const STACK_OVERFLOW_READ = 599;929pub const STACK_OVERFLOW_READ = 599;
930
621/// Internal OFS status codes indicating how an allocation operation is handled. Either it is retried after the containing onode is moved or the extent stream is converted to a large stream.931/// Internal OFS status codes indicating how an allocation operation is handled. Either it is retried after the containing onode is moved or the extent stream is converted to a large stream.
622pub const CONVERT_TO_LARGE = 600;932pub const CONVERT_TO_LARGE = 600;
933
623/// The attempt to find the object found an object matching by ID on the volume but it is out of the scope of the handle used for the operation.934/// The attempt to find the object found an object matching by ID on the volume but it is out of the scope of the handle used for the operation.
624pub const FOUND_OUT_OF_SCOPE = 601;935pub const FOUND_OUT_OF_SCOPE = 601;
936
625/// The bucket array must be grown. Retry transaction after doing so.937/// The bucket array must be grown. Retry transaction after doing so.
626pub const ALLOCATE_BUCKET = 602;938pub const ALLOCATE_BUCKET = 602;
939
627/// The user/kernel marshalling buffer has overflowed.940/// The user/kernel marshalling buffer has overflowed.
628pub const MARSHALL_OVERFLOW = 603;941pub const MARSHALL_OVERFLOW = 603;
942
629/// The supplied variant structure contains invalid data.943/// The supplied variant structure contains invalid data.
630pub const INVALID_VARIANT = 604;944pub const INVALID_VARIANT = 604;
945
631/// The specified buffer contains ill-formed data.946/// The specified buffer contains ill-formed data.
632pub const BAD_COMPRESSION_BUFFER = 605;947pub const BAD_COMPRESSION_BUFFER = 605;
948
633/// {Audit Failed} An attempt to generate a security audit failed.949/// {Audit Failed} An attempt to generate a security audit failed.
634pub const AUDIT_FAILED = 606;950pub const AUDIT_FAILED = 606;
951
635/// The timer resolution was not previously set by the current process.952/// The timer resolution was not previously set by the current process.
636pub const TIMER_RESOLUTION_NOT_SET = 607;953pub const TIMER_RESOLUTION_NOT_SET = 607;
954
637/// There is insufficient account information to log you on.955/// There is insufficient account information to log you on.
638pub const INSUFFICIENT_LOGON_INFO = 608;956pub const INSUFFICIENT_LOGON_INFO = 608;
957
639/// {Invalid DLL Entrypoint} The dynamic link library %hs is not written correctly. The stack pointer has been left in an inconsistent state. The entrypoint should be declared as WINAPI or STDCALL. Select YES to fail the DLL load. Select NO to continue execution. Selecting NO may cause the application to operate incorrectly.958/// {Invalid DLL Entrypoint} The dynamic link library %hs is not written correctly. The stack pointer has been left in an inconsistent state. The entrypoint should be declared as WINAPI or STDCALL. Select YES to fail the DLL load. Select NO to continue execution. Selecting NO may cause the application to operate incorrectly.
640pub const BAD_DLL_ENTRYPOINT = 609;959pub const BAD_DLL_ENTRYPOINT = 609;
960
641/// {Invalid Service Callback Entrypoint} The %hs service is not written correctly. The stack pointer has been left in an inconsistent state. The callback entrypoint should be declared as WINAPI or STDCALL. Selecting OK will cause the service to continue operation. However, the service process may operate incorrectly.961/// {Invalid Service Callback Entrypoint} The %hs service is not written correctly. The stack pointer has been left in an inconsistent state. The callback entrypoint should be declared as WINAPI or STDCALL. Selecting OK will cause the service to continue operation. However, the service process may operate incorrectly.
642pub const BAD_SERVICE_ENTRYPOINT = 610;962pub const BAD_SERVICE_ENTRYPOINT = 610;
963
643/// There is an IP address conflict with another system on the network.964/// There is an IP address conflict with another system on the network.
644pub const IP_ADDRESS_CONFLICT1 = 611;965pub const IP_ADDRESS_CONFLICT1 = 611;
966
645/// There is an IP address conflict with another system on the network.967/// There is an IP address conflict with another system on the network.
646pub const IP_ADDRESS_CONFLICT2 = 612;968pub const IP_ADDRESS_CONFLICT2 = 612;
969
647/// {Low On Registry Space} The system has reached the maximum size allowed for the system part of the registry. Additional storage requests will be ignored.970/// {Low On Registry Space} The system has reached the maximum size allowed for the system part of the registry. Additional storage requests will be ignored.
648pub const REGISTRY_QUOTA_LIMIT = 613;971pub const REGISTRY_QUOTA_LIMIT = 613;
972
649/// A callback return system service cannot be executed when no callback is active.973/// A callback return system service cannot be executed when no callback is active.
650pub const NO_CALLBACK_ACTIVE = 614;974pub const NO_CALLBACK_ACTIVE = 614;
975
651/// The password provided is too short to meet the policy of your user account. Please choose a longer password.976/// The password provided is too short to meet the policy of your user account. Please choose a longer password.
652pub const PWD_TOO_SHORT = 615;977pub const PWD_TOO_SHORT = 615;
978
653/// The policy of your user account does not allow you to change passwords too frequently. This is done to prevent users from changing back to a familiar, but potentially discovered, password. If you feel your password has been compromised then please contact your administrator immediately to have a new one assigned.979/// The policy of your user account does not allow you to change passwords too frequently. This is done to prevent users from changing back to a familiar, but potentially discovered, password. If you feel your password has been compromised then please contact your administrator immediately to have a new one assigned.
654pub const PWD_TOO_RECENT = 616;980pub const PWD_TOO_RECENT = 616;
981
655/// You have attempted to change your password to one that you have used in the past. The policy of your user account does not allow this. Please select a password that you have not previously used.982/// You have attempted to change your password to one that you have used in the past. The policy of your user account does not allow this. Please select a password that you have not previously used.
656pub const PWD_HISTORY_CONFLICT = 617;983pub const PWD_HISTORY_CONFLICT = 617;
984
657/// The specified compression format is unsupported.985/// The specified compression format is unsupported.
658pub const UNSUPPORTED_COMPRESSION = 618;986pub const UNSUPPORTED_COMPRESSION = 618;
987
659/// The specified hardware profile configuration is invalid.988/// The specified hardware profile configuration is invalid.
660pub const INVALID_HW_PROFILE = 619;989pub const INVALID_HW_PROFILE = 619;
990
661/// The specified Plug and Play registry device path is invalid.991/// The specified Plug and Play registry device path is invalid.
662pub const INVALID_PLUGPLAY_DEVICE_PATH = 620;992pub const INVALID_PLUGPLAY_DEVICE_PATH = 620;
993
663/// The specified quota list is internally inconsistent with its descriptor.994/// The specified quota list is internally inconsistent with its descriptor.
664pub const QUOTA_LIST_INCONSISTENT = 621;995pub const QUOTA_LIST_INCONSISTENT = 621;
996
665/// {Windows Evaluation Notification} The evaluation period for this installation of Windows has expired. This system will shutdown in 1 hour. To restore access to this installation of Windows, please upgrade this installation using a licensed distribution of this product.997/// {Windows Evaluation Notification} The evaluation period for this installation of Windows has expired. This system will shutdown in 1 hour. To restore access to this installation of Windows, please upgrade this installation using a licensed distribution of this product.
666pub const EVALUATION_EXPIRATION = 622;998pub const EVALUATION_EXPIRATION = 622;
999
667/// {Illegal System DLL Relocation} The system DLL %hs was relocated in memory. The application will not run properly. The relocation occurred because the DLL %hs occupied an address range reserved for Windows system DLLs. The vendor supplying the DLL should be contacted for a new DLL.1000/// {Illegal System DLL Relocation} The system DLL %hs was relocated in memory. The application will not run properly. The relocation occurred because the DLL %hs occupied an address range reserved for Windows system DLLs. The vendor supplying the DLL should be contacted for a new DLL.
668pub const ILLEGAL_DLL_RELOCATION = 623;1001pub const ILLEGAL_DLL_RELOCATION = 623;
1002
669/// {DLL Initialization Failed} The application failed to initialize because the window station is shutting down.1003/// {DLL Initialization Failed} The application failed to initialize because the window station is shutting down.
670pub const DLL_INIT_FAILED_LOGOFF = 624;1004pub const DLL_INIT_FAILED_LOGOFF = 624;
1005
671/// The validation process needs to continue on to the next step.1006/// The validation process needs to continue on to the next step.
672pub const VALIDATE_CONTINUE = 625;1007pub const VALIDATE_CONTINUE = 625;
1008
673/// There are no more matches for the current index enumeration.1009/// There are no more matches for the current index enumeration.
674pub const NO_MORE_MATCHES = 626;1010pub const NO_MORE_MATCHES = 626;
1011
675/// The range could not be added to the range list because of a conflict.1012/// The range could not be added to the range list because of a conflict.
676pub const RANGE_LIST_CONFLICT = 627;1013pub const RANGE_LIST_CONFLICT = 627;
1014
677/// The server process is running under a SID different than that required by client.1015/// The server process is running under a SID different than that required by client.
678pub const SERVER_SID_MISMATCH = 628;1016pub const SERVER_SID_MISMATCH = 628;
1017
679/// A group marked use for deny only cannot be enabled.1018/// A group marked use for deny only cannot be enabled.
680pub const CANT_ENABLE_DENY_ONLY = 629;1019pub const CANT_ENABLE_DENY_ONLY = 629;
1020
681/// {EXCEPTION} Multiple floating point faults.1021/// {EXCEPTION} Multiple floating point faults.
682pub const FLOAT_MULTIPLE_FAULTS = 630;1022pub const FLOAT_MULTIPLE_FAULTS = 630;
1023
683/// {EXCEPTION} Multiple floating point traps.1024/// {EXCEPTION} Multiple floating point traps.
684pub const FLOAT_MULTIPLE_TRAPS = 631;1025pub const FLOAT_MULTIPLE_TRAPS = 631;
1026
685/// The requested interface is not supported.1027/// The requested interface is not supported.
686pub const NOINTERFACE = 632;1028pub const NOINTERFACE = 632;
1029
687/// {System Standby Failed} The driver %hs does not support standby mode. Updating this driver may allow the system to go to standby mode.1030/// {System Standby Failed} The driver %hs does not support standby mode. Updating this driver may allow the system to go to standby mode.
688pub const DRIVER_FAILED_SLEEP = 633;1031pub const DRIVER_FAILED_SLEEP = 633;
1032
689/// The system file %1 has become corrupt and has been replaced.1033/// The system file %1 has become corrupt and has been replaced.
690pub const CORRUPT_SYSTEM_FILE = 634;1034pub const CORRUPT_SYSTEM_FILE = 634;
1035
691/// {Virtual Memory Minimum Too Low} Your system is low on virtual memory. Windows is increasing the size of your virtual memory paging file. During this process, memory requests for some applications may be denied. For more information, see Help.1036/// {Virtual Memory Minimum Too Low} Your system is low on virtual memory. Windows is increasing the size of your virtual memory paging file. During this process, memory requests for some applications may be denied. For more information, see Help.
692pub const COMMITMENT_MINIMUM = 635;1037pub const COMMITMENT_MINIMUM = 635;
1038
693/// A device was removed so enumeration must be restarted.1039/// A device was removed so enumeration must be restarted.
694pub const PNP_RESTART_ENUMERATION = 636;1040pub const PNP_RESTART_ENUMERATION = 636;
1041
695/// {Fatal System Error} The system image %s is not properly signed. The file has been replaced with the signed file. The system has been shut down.1042/// {Fatal System Error} The system image %s is not properly signed. The file has been replaced with the signed file. The system has been shut down.
696pub const SYSTEM_IMAGE_BAD_SIGNATURE = 637;1043pub const SYSTEM_IMAGE_BAD_SIGNATURE = 637;
1044
697/// Device will not start without a reboot.1045/// Device will not start without a reboot.
698pub const PNP_REBOOT_REQUIRED = 638;1046pub const PNP_REBOOT_REQUIRED = 638;
1047
699/// There is not enough power to complete the requested operation.1048/// There is not enough power to complete the requested operation.
700pub const INSUFFICIENT_POWER = 639;1049pub const INSUFFICIENT_POWER = 639;
1050
701/// ERROR_MULTIPLE_FAULT_VIOLATION1051/// ERROR_MULTIPLE_FAULT_VIOLATION
702pub const MULTIPLE_FAULT_VIOLATION = 640;1052pub const MULTIPLE_FAULT_VIOLATION = 640;
1053
703/// The system is in the process of shutting down.1054/// The system is in the process of shutting down.
704pub const SYSTEM_SHUTDOWN = 641;1055pub const SYSTEM_SHUTDOWN = 641;
1056
705/// An attempt to remove a processes DebugPort was made, but a port was not already associated with the process.1057/// An attempt to remove a processes DebugPort was made, but a port was not already associated with the process.
706pub const PORT_NOT_SET = 642;1058pub const PORT_NOT_SET = 642;
1059
707/// This version of Windows is not compatible with the behavior version of directory forest, domain or domain controller.1060/// This version of Windows is not compatible with the behavior version of directory forest, domain or domain controller.
708pub const DS_VERSION_CHECK_FAILURE = 643;1061pub const DS_VERSION_CHECK_FAILURE = 643;
1062
709/// The specified range could not be found in the range list.1063/// The specified range could not be found in the range list.
710pub const RANGE_NOT_FOUND = 644;1064pub const RANGE_NOT_FOUND = 644;
1065
711/// The driver was not loaded because the system is booting into safe mode.1066/// The driver was not loaded because the system is booting into safe mode.
712pub const NOT_SAFE_MODE_DRIVER = 646;1067pub const NOT_SAFE_MODE_DRIVER = 646;
1068
713/// The driver was not loaded because it failed its initialization call.1069/// The driver was not loaded because it failed its initialization call.
714pub const FAILED_DRIVER_ENTRY = 647;1070pub const FAILED_DRIVER_ENTRY = 647;
1071
715/// The "%hs" encountered an error while applying power or reading the device configuration. This may be caused by a failure of your hardware or by a poor connection.1072/// The "%hs" encountered an error while applying power or reading the device configuration. This may be caused by a failure of your hardware or by a poor connection.
716pub const DEVICE_ENUMERATION_ERROR = 648;1073pub const DEVICE_ENUMERATION_ERROR = 648;
1074
717/// The create operation failed because the name contained at least one mount point which resolves to a volume to which the specified device object is not attached.1075/// The create operation failed because the name contained at least one mount point which resolves to a volume to which the specified device object is not attached.
718pub const MOUNT_POINT_NOT_RESOLVED = 649;1076pub const MOUNT_POINT_NOT_RESOLVED = 649;
1077
719/// The device object parameter is either not a valid device object or is not attached to the volume specified by the file name.1078/// The device object parameter is either not a valid device object or is not attached to the volume specified by the file name.
720pub const INVALID_DEVICE_OBJECT_PARAMETER = 650;1079pub const INVALID_DEVICE_OBJECT_PARAMETER = 650;
1080
721/// A Machine Check Error has occurred. Please check the system eventlog for additional information.1081/// A Machine Check Error has occurred. Please check the system eventlog for additional information.
722pub const MCA_OCCURED = 651;1082pub const MCA_OCCURED = 651;
1083
723/// There was error [%2] processing the driver database.1084/// There was error [%2] processing the driver database.
724pub const DRIVER_DATABASE_ERROR = 652;1085pub const DRIVER_DATABASE_ERROR = 652;
1086
725/// System hive size has exceeded its limit.1087/// System hive size has exceeded its limit.
726pub const SYSTEM_HIVE_TOO_LARGE = 653;1088pub const SYSTEM_HIVE_TOO_LARGE = 653;
1089
727/// The driver could not be loaded because a previous version of the driver is still in memory.1090/// The driver could not be loaded because a previous version of the driver is still in memory.
728pub const DRIVER_FAILED_PRIOR_UNLOAD = 654;1091pub const DRIVER_FAILED_PRIOR_UNLOAD = 654;
1092
729/// {Volume Shadow Copy Service} Please wait while the Volume Shadow Copy Service prepares volume %hs for hibernation.1093/// {Volume Shadow Copy Service} Please wait while the Volume Shadow Copy Service prepares volume %hs for hibernation.
730pub const VOLSNAP_PREPARE_HIBERNATE = 655;1094pub const VOLSNAP_PREPARE_HIBERNATE = 655;
1095
731/// The system has failed to hibernate (The error code is %hs). Hibernation will be disabled until the system is restarted.1096/// The system has failed to hibernate (The error code is %hs). Hibernation will be disabled until the system is restarted.
732pub const HIBERNATION_FAILURE = 656;1097pub const HIBERNATION_FAILURE = 656;
1098
733/// The password provided is too long to meet the policy of your user account. Please choose a shorter password.1099/// The password provided is too long to meet the policy of your user account. Please choose a shorter password.
734pub const PWD_TOO_LONG = 657;1100pub const PWD_TOO_LONG = 657;
1101
735/// The requested operation could not be completed due to a file system limitation.1102/// The requested operation could not be completed due to a file system limitation.
736pub const FILE_SYSTEM_LIMITATION = 665;1103pub const FILE_SYSTEM_LIMITATION = 665;
1104
737/// An assertion failure has occurred.1105/// An assertion failure has occurred.
738pub const ASSERTION_FAILURE = 668;1106pub const ASSERTION_FAILURE = 668;
1107
739/// An error occurred in the ACPI subsystem.1108/// An error occurred in the ACPI subsystem.
740pub const ACPI_ERROR = 669;1109pub const ACPI_ERROR = 669;
1110
741/// WOW Assertion Error.1111/// WOW Assertion Error.
742pub const WOW_ASSERTION = 670;1112pub const WOW_ASSERTION = 670;
1113
743/// A device is missing in the system BIOS MPS table. This device will not be used. Please contact your system vendor for system BIOS update.1114/// A device is missing in the system BIOS MPS table. This device will not be used. Please contact your system vendor for system BIOS update.
744pub const PNP_BAD_MPS_TABLE = 671;1115pub const PNP_BAD_MPS_TABLE = 671;
1116
745/// A translator failed to translate resources.1117/// A translator failed to translate resources.
746pub const PNP_TRANSLATION_FAILED = 672;1118pub const PNP_TRANSLATION_FAILED = 672;
1119
747/// A IRQ translator failed to translate resources.1120/// A IRQ translator failed to translate resources.
748pub const PNP_IRQ_TRANSLATION_FAILED = 673;1121pub const PNP_IRQ_TRANSLATION_FAILED = 673;
1122
749/// Driver %2 returned invalid ID for a child device (%3).1123/// Driver %2 returned invalid ID for a child device (%3).
750pub const PNP_INVALID_ID = 674;1124pub const PNP_INVALID_ID = 674;
1125
751/// {Kernel Debugger Awakened} the system debugger was awakened by an interrupt.1126/// {Kernel Debugger Awakened} the system debugger was awakened by an interrupt.
752pub const WAKE_SYSTEM_DEBUGGER = 675;1127pub const WAKE_SYSTEM_DEBUGGER = 675;
1128
753/// {Handles Closed} Handles to objects have been automatically closed as a result of the requested operation.1129/// {Handles Closed} Handles to objects have been automatically closed as a result of the requested operation.
754pub const HANDLES_CLOSED = 676;1130pub const HANDLES_CLOSED = 676;
1131
755/// {Too Much Information} The specified access control list (ACL) contained more information than was expected.1132/// {Too Much Information} The specified access control list (ACL) contained more information than was expected.
756pub const EXTRANEOUS_INFORMATION = 677;1133pub const EXTRANEOUS_INFORMATION = 677;
1134
757/// This warning level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted. The commit has NOT been completed, but has not been rolled back either (so it may still be committed if desired).1135/// This warning level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted. The commit has NOT been completed, but has not been rolled back either (so it may still be committed if desired).
758pub const RXACT_COMMIT_NECESSARY = 678;1136pub const RXACT_COMMIT_NECESSARY = 678;
1137
759/// {Media Changed} The media may have changed.1138/// {Media Changed} The media may have changed.
760pub const MEDIA_CHECK = 679;1139pub const MEDIA_CHECK = 679;
1140
761/// {GUID Substitution} During the translation of a global identifier (GUID) to a Windows security ID (SID), no administratively-defined GUID prefix was found. A substitute prefix was used, which will not compromise system security. However, this may provide a more restrictive access than intended.1141/// {GUID Substitution} During the translation of a global identifier (GUID) to a Windows security ID (SID), no administratively-defined GUID prefix was found. A substitute prefix was used, which will not compromise system security. However, this may provide a more restrictive access than intended.
762pub const GUID_SUBSTITUTION_MADE = 680;1142pub const GUID_SUBSTITUTION_MADE = 680;
1143
763/// The create operation stopped after reaching a symbolic link.1144/// The create operation stopped after reaching a symbolic link.
764pub const STOPPED_ON_SYMLINK = 681;1145pub const STOPPED_ON_SYMLINK = 681;
1146
765/// A long jump has been executed.1147/// A long jump has been executed.
766pub const LONGJUMP = 682;1148pub const LONGJUMP = 682;
1149
767/// The Plug and Play query operation was not successful.1150/// The Plug and Play query operation was not successful.
768pub const PLUGPLAY_QUERY_VETOED = 683;1151pub const PLUGPLAY_QUERY_VETOED = 683;
1152
769/// A frame consolidation has been executed.1153/// A frame consolidation has been executed.
770pub const UNWIND_CONSOLIDATE = 684;1154pub const UNWIND_CONSOLIDATE = 684;
1155
771/// {Registry Hive Recovered} Registry hive (file): %hs was corrupted and it has been recovered. Some data might have been lost.1156/// {Registry Hive Recovered} Registry hive (file): %hs was corrupted and it has been recovered. Some data might have been lost.
772pub const REGISTRY_HIVE_RECOVERED = 685;1157pub const REGISTRY_HIVE_RECOVERED = 685;
1158
773/// The application is attempting to run executable code from the module %hs. This may be insecure. An alternative, %hs, is available. Should the application use the secure module %hs?1159/// The application is attempting to run executable code from the module %hs. This may be insecure. An alternative, %hs, is available. Should the application use the secure module %hs?
774pub const DLL_MIGHT_BE_INSECURE = 686;1160pub const DLL_MIGHT_BE_INSECURE = 686;
1161
775/// The application is loading executable code from the module %hs. This is secure, but may be incompatible with previous releases of the operating system. An alternative, %hs, is available. Should the application use the secure module %hs?1162/// The application is loading executable code from the module %hs. This is secure, but may be incompatible with previous releases of the operating system. An alternative, %hs, is available. Should the application use the secure module %hs?
776pub const DLL_MIGHT_BE_INCOMPATIBLE = 687;1163pub const DLL_MIGHT_BE_INCOMPATIBLE = 687;
1164
777/// Debugger did not handle the exception.1165/// Debugger did not handle the exception.
778pub const DBG_EXCEPTION_NOT_HANDLED = 688;1166pub const DBG_EXCEPTION_NOT_HANDLED = 688;
1167
779/// Debugger will reply later.1168/// Debugger will reply later.
780pub const DBG_REPLY_LATER = 689;1169pub const DBG_REPLY_LATER = 689;
1170
781/// Debugger cannot provide handle.1171/// Debugger cannot provide handle.
782pub const DBG_UNABLE_TO_PROVIDE_HANDLE = 690;1172pub const DBG_UNABLE_TO_PROVIDE_HANDLE = 690;
1173
783/// Debugger terminated thread.1174/// Debugger terminated thread.
784pub const DBG_TERMINATE_THREAD = 691;1175pub const DBG_TERMINATE_THREAD = 691;
1176
785/// Debugger terminated process.1177/// Debugger terminated process.
786pub const DBG_TERMINATE_PROCESS = 692;1178pub const DBG_TERMINATE_PROCESS = 692;
1179
787/// Debugger got control C.1180/// Debugger got control C.
788pub const DBG_CONTROL_C = 693;1181pub const DBG_CONTROL_C = 693;
1182
789/// Debugger printed exception on control C.1183/// Debugger printed exception on control C.
790pub const DBG_PRINTEXCEPTION_C = 694;1184pub const DBG_PRINTEXCEPTION_C = 694;
1185
791/// Debugger received RIP exception.1186/// Debugger received RIP exception.
792pub const DBG_RIPEXCEPTION = 695;1187pub const DBG_RIPEXCEPTION = 695;
1188
793/// Debugger received control break.1189/// Debugger received control break.
794pub const DBG_CONTROL_BREAK = 696;1190pub const DBG_CONTROL_BREAK = 696;
1191
795/// Debugger command communication exception.1192/// Debugger command communication exception.
796pub const DBG_COMMAND_EXCEPTION = 697;1193pub const DBG_COMMAND_EXCEPTION = 697;
1194
797/// {Object Exists} An attempt was made to create an object and the object name already existed.1195/// {Object Exists} An attempt was made to create an object and the object name already existed.
798pub const OBJECT_NAME_EXISTS = 698;1196pub const OBJECT_NAME_EXISTS = 698;
1197
799/// {Thread Suspended} A thread termination occurred while the thread was suspended. The thread was resumed, and termination proceeded.1198/// {Thread Suspended} A thread termination occurred while the thread was suspended. The thread was resumed, and termination proceeded.
800pub const THREAD_WAS_SUSPENDED = 699;1199pub const THREAD_WAS_SUSPENDED = 699;
1200
801/// {Image Relocated} An image file could not be mapped at the address specified in the image file. Local fixups must be performed on this image.1201/// {Image Relocated} An image file could not be mapped at the address specified in the image file. Local fixups must be performed on this image.
802pub const IMAGE_NOT_AT_BASE = 700;1202pub const IMAGE_NOT_AT_BASE = 700;
1203
803/// This informational level status indicates that a specified registry sub-tree transaction state did not yet exist and had to be created.1204/// This informational level status indicates that a specified registry sub-tree transaction state did not yet exist and had to be created.
804pub const RXACT_STATE_CREATED = 701;1205pub const RXACT_STATE_CREATED = 701;
1206
805/// {Segment Load} A virtual DOS machine (VDM) is loading, unloading, or moving an MS-DOS or Win16 program segment image. An exception is raised so a debugger can load, unload or track symbols and breakpoints within these 16-bit segments.1207/// {Segment Load} A virtual DOS machine (VDM) is loading, unloading, or moving an MS-DOS or Win16 program segment image. An exception is raised so a debugger can load, unload or track symbols and breakpoints within these 16-bit segments.
806pub const SEGMENT_NOTIFICATION = 702;1208pub const SEGMENT_NOTIFICATION = 702;
1209
807/// {Invalid Current Directory} The process cannot switch to the startup current directory %hs. Select OK to set current directory to %hs, or select CANCEL to exit.1210/// {Invalid Current Directory} The process cannot switch to the startup current directory %hs. Select OK to set current directory to %hs, or select CANCEL to exit.
808pub const BAD_CURRENT_DIRECTORY = 703;1211pub const BAD_CURRENT_DIRECTORY = 703;
1212
809/// {Redundant Read} To satisfy a read request, the NT fault-tolerant file system successfully read the requested data from a redundant copy. This was done because the file system encountered a failure on a member of the fault-tolerant volume, but was unable to reassign the failing area of the device.1213/// {Redundant Read} To satisfy a read request, the NT fault-tolerant file system successfully read the requested data from a redundant copy. This was done because the file system encountered a failure on a member of the fault-tolerant volume, but was unable to reassign the failing area of the device.
810pub const FT_READ_RECOVERY_FROM_BACKUP = 704;1214pub const FT_READ_RECOVERY_FROM_BACKUP = 704;
1215
811/// {Redundant Write} To satisfy a write request, the NT fault-tolerant file system successfully wrote a redundant copy of the information. This was done because the file system encountered a failure on a member of the fault-tolerant volume, but was not able to reassign the failing area of the device.1216/// {Redundant Write} To satisfy a write request, the NT fault-tolerant file system successfully wrote a redundant copy of the information. This was done because the file system encountered a failure on a member of the fault-tolerant volume, but was not able to reassign the failing area of the device.
812pub const FT_WRITE_RECOVERY = 705;1217pub const FT_WRITE_RECOVERY = 705;
1218
813/// {Machine Type Mismatch} The image file %hs is valid, but is for a machine type other than the current machine. Select OK to continue, or CANCEL to fail the DLL load.1219/// {Machine Type Mismatch} The image file %hs is valid, but is for a machine type other than the current machine. Select OK to continue, or CANCEL to fail the DLL load.
814pub const IMAGE_MACHINE_TYPE_MISMATCH = 706;1220pub const IMAGE_MACHINE_TYPE_MISMATCH = 706;
1221
815/// {Partial Data Received} The network transport returned partial data to its client. The remaining data will be sent later.1222/// {Partial Data Received} The network transport returned partial data to its client. The remaining data will be sent later.
816pub const RECEIVE_PARTIAL = 707;1223pub const RECEIVE_PARTIAL = 707;
1224
817/// {Expedited Data Received} The network transport returned data to its client that was marked as expedited by the remote system.1225/// {Expedited Data Received} The network transport returned data to its client that was marked as expedited by the remote system.
818pub const RECEIVE_EXPEDITED = 708;1226pub const RECEIVE_EXPEDITED = 708;
1227
819/// {Partial Expedited Data Received} The network transport returned partial data to its client and this data was marked as expedited by the remote system. The remaining data will be sent later.1228/// {Partial Expedited Data Received} The network transport returned partial data to its client and this data was marked as expedited by the remote system. The remaining data will be sent later.
820pub const RECEIVE_PARTIAL_EXPEDITED = 709;1229pub const RECEIVE_PARTIAL_EXPEDITED = 709;
1230
821/// {TDI Event Done} The TDI indication has completed successfully.1231/// {TDI Event Done} The TDI indication has completed successfully.
822pub const EVENT_DONE = 710;1232pub const EVENT_DONE = 710;
1233
823/// {TDI Event Pending} The TDI indication has entered the pending state.1234/// {TDI Event Pending} The TDI indication has entered the pending state.
824pub const EVENT_PENDING = 711;1235pub const EVENT_PENDING = 711;
1236
825/// Checking file system on %wZ.1237/// Checking file system on %wZ.
826pub const CHECKING_FILE_SYSTEM = 712;1238pub const CHECKING_FILE_SYSTEM = 712;
1239
827/// {Fatal Application Exit} %hs.1240/// {Fatal Application Exit} %hs.
828pub const FATAL_APP_EXIT = 713;1241pub const FATAL_APP_EXIT = 713;
1242
829/// The specified registry key is referenced by a predefined handle.1243/// The specified registry key is referenced by a predefined handle.
830pub const PREDEFINED_HANDLE = 714;1244pub const PREDEFINED_HANDLE = 714;
1245
831/// {Page Unlocked} The page protection of a locked page was changed to 'No Access' and the page was unlocked from memory and from the process.1246/// {Page Unlocked} The page protection of a locked page was changed to 'No Access' and the page was unlocked from memory and from the process.
832pub const WAS_UNLOCKED = 715;1247pub const WAS_UNLOCKED = 715;
1248
833/// %hs1249/// %hs
834pub const SERVICE_NOTIFICATION = 716;1250pub const SERVICE_NOTIFICATION = 716;
1251
835/// {Page Locked} One of the pages to lock was already locked.1252/// {Page Locked} One of the pages to lock was already locked.
836pub const WAS_LOCKED = 717;1253pub const WAS_LOCKED = 717;
1254
837/// Application popup: %1 : %21255/// Application popup: %1 : %2
838pub const LOG_HARD_ERROR = 718;1256pub const LOG_HARD_ERROR = 718;
1257
839/// ERROR_ALREADY_WIN321258/// ERROR_ALREADY_WIN32
840pub const ALREADY_WIN32 = 719;1259pub const ALREADY_WIN32 = 719;
1260
841/// {Machine Type Mismatch} The image file %hs is valid, but is for a machine type other than the current machine.1261/// {Machine Type Mismatch} The image file %hs is valid, but is for a machine type other than the current machine.
842pub const IMAGE_MACHINE_TYPE_MISMATCH_EXE = 720;1262pub const IMAGE_MACHINE_TYPE_MISMATCH_EXE = 720;
1263
843/// A yield execution was performed and no thread was available to run.1264/// A yield execution was performed and no thread was available to run.
844pub const NO_YIELD_PERFORMED = 721;1265pub const NO_YIELD_PERFORMED = 721;
1266
845/// The resumable flag to a timer API was ignored.1267/// The resumable flag to a timer API was ignored.
846pub const TIMER_RESUME_IGNORED = 722;1268pub const TIMER_RESUME_IGNORED = 722;
1269
847/// The arbiter has deferred arbitration of these resources to its parent.1270/// The arbiter has deferred arbitration of these resources to its parent.
848pub const ARBITRATION_UNHANDLED = 723;1271pub const ARBITRATION_UNHANDLED = 723;
1272
849/// The inserted CardBus device cannot be started because of a configuration error on "%hs".1273/// The inserted CardBus device cannot be started because of a configuration error on "%hs".
850pub const CARDBUS_NOT_SUPPORTED = 724;1274pub const CARDBUS_NOT_SUPPORTED = 724;
1275
851/// The CPUs in this multiprocessor system are not all the same revision level. To use all processors the operating system restricts itself to the features of the least capable processor in the system. Should problems occur with this system, contact the CPU manufacturer to see if this mix of processors is supported.1276/// The CPUs in this multiprocessor system are not all the same revision level. To use all processors the operating system restricts itself to the features of the least capable processor in the system. Should problems occur with this system, contact the CPU manufacturer to see if this mix of processors is supported.
852pub const MP_PROCESSOR_MISMATCH = 725;1277pub const MP_PROCESSOR_MISMATCH = 725;
1278
853/// The system was put into hibernation.1279/// The system was put into hibernation.
854pub const HIBERNATED = 726;1280pub const HIBERNATED = 726;
1281
855/// The system was resumed from hibernation.1282/// The system was resumed from hibernation.
856pub const RESUME_HIBERNATION = 727;1283pub const RESUME_HIBERNATION = 727;
1284
857/// Windows has detected that the system firmware (BIOS) was updated [previous firmware date = %2, current firmware date %3].1285/// Windows has detected that the system firmware (BIOS) was updated [previous firmware date = %2, current firmware date %3].
858pub const FIRMWARE_UPDATED = 728;1286pub const FIRMWARE_UPDATED = 728;
1287
859/// A device driver is leaking locked I/O pages causing system degradation. The system has automatically enabled tracking code in order to try and catch the culprit.1288/// A device driver is leaking locked I/O pages causing system degradation. The system has automatically enabled tracking code in order to try and catch the culprit.
860pub const DRIVERS_LEAKING_LOCKED_PAGES = 729;1289pub const DRIVERS_LEAKING_LOCKED_PAGES = 729;
1290
861/// The system has awoken.1291/// The system has awoken.
862pub const WAKE_SYSTEM = 730;1292pub const WAKE_SYSTEM = 730;
1293
863/// ERROR_WAIT_11294/// ERROR_WAIT_1
864pub const WAIT_1 = 731;1295pub const WAIT_1 = 731;
1296
865/// ERROR_WAIT_21297/// ERROR_WAIT_2
866pub const WAIT_2 = 732;1298pub const WAIT_2 = 732;
1299
867/// ERROR_WAIT_31300/// ERROR_WAIT_3
868pub const WAIT_3 = 733;1301pub const WAIT_3 = 733;
1302
869/// ERROR_WAIT_631303/// ERROR_WAIT_63
870pub const WAIT_63 = 734;1304pub const WAIT_63 = 734;
1305
871/// ERROR_ABANDONED_WAIT_01306/// ERROR_ABANDONED_WAIT_0
872pub const ABANDONED_WAIT_0 = 735;1307pub const ABANDONED_WAIT_0 = 735;
1308
873/// ERROR_ABANDONED_WAIT_631309/// ERROR_ABANDONED_WAIT_63
874pub const ABANDONED_WAIT_63 = 736;1310pub const ABANDONED_WAIT_63 = 736;
1311
875/// ERROR_USER_APC1312/// ERROR_USER_APC
876pub const USER_APC = 737;1313pub const USER_APC = 737;
1314
877/// ERROR_KERNEL_APC1315/// ERROR_KERNEL_APC
878pub const KERNEL_APC = 738;1316pub const KERNEL_APC = 738;
1317
879/// ERROR_ALERTED1318/// ERROR_ALERTED
880pub const ALERTED = 739;1319pub const ALERTED = 739;
1320
881/// The requested operation requires elevation.1321/// The requested operation requires elevation.
882pub const ELEVATION_REQUIRED = 740;1322pub const ELEVATION_REQUIRED = 740;
1323
883/// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link.1324/// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link.
884pub const REPARSE = 741;1325pub const REPARSE = 741;
1326
885/// An open/create operation completed while an oplock break is underway.1327/// An open/create operation completed while an oplock break is underway.
886pub const OPLOCK_BREAK_IN_PROGRESS = 742;1328pub const OPLOCK_BREAK_IN_PROGRESS = 742;
1329
887/// A new volume has been mounted by a file system.1330/// A new volume has been mounted by a file system.
888pub const VOLUME_MOUNTED = 743;1331pub const VOLUME_MOUNTED = 743;
1332
889/// This success level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted. The commit has now been completed.1333/// This success level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted. The commit has now been completed.
890pub const RXACT_COMMITTED = 744;1334pub const RXACT_COMMITTED = 744;
1335
891/// This indicates that a notify change request has been completed due to closing the handle which made the notify change request.1336/// This indicates that a notify change request has been completed due to closing the handle which made the notify change request.
892pub const NOTIFY_CLEANUP = 745;1337pub const NOTIFY_CLEANUP = 745;
1338
893/// {Connect Failure on Primary Transport} An attempt was made to connect to the remote server %hs on the primary transport, but the connection failed. The computer WAS able to connect on a secondary transport.1339/// {Connect Failure on Primary Transport} An attempt was made to connect to the remote server %hs on the primary transport, but the connection failed. The computer WAS able to connect on a secondary transport.
894pub const PRIMARY_TRANSPORT_CONNECT_FAILED = 746;1340pub const PRIMARY_TRANSPORT_CONNECT_FAILED = 746;
1341
895/// Page fault was a transition fault.1342/// Page fault was a transition fault.
896pub const PAGE_FAULT_TRANSITION = 747;1343pub const PAGE_FAULT_TRANSITION = 747;
1344
897/// Page fault was a demand zero fault.1345/// Page fault was a demand zero fault.
898pub const PAGE_FAULT_DEMAND_ZERO = 748;1346pub const PAGE_FAULT_DEMAND_ZERO = 748;
1347
899/// Page fault was a demand zero fault.1348/// Page fault was a demand zero fault.
900pub const PAGE_FAULT_COPY_ON_WRITE = 749;1349pub const PAGE_FAULT_COPY_ON_WRITE = 749;
1350
901/// Page fault was a demand zero fault.1351/// Page fault was a demand zero fault.
902pub const PAGE_FAULT_GUARD_PAGE = 750;1352pub const PAGE_FAULT_GUARD_PAGE = 750;
1353
903/// Page fault was satisfied by reading from a secondary storage device.1354/// Page fault was satisfied by reading from a secondary storage device.
904pub const PAGE_FAULT_PAGING_FILE = 751;1355pub const PAGE_FAULT_PAGING_FILE = 751;
1356
905/// Cached page was locked during operation.1357/// Cached page was locked during operation.
906pub const CACHE_PAGE_LOCKED = 752;1358pub const CACHE_PAGE_LOCKED = 752;
1359
907/// Crash dump exists in paging file.1360/// Crash dump exists in paging file.
908pub const CRASH_DUMP = 753;1361pub const CRASH_DUMP = 753;
1362
909/// Specified buffer contains all zeros.1363/// Specified buffer contains all zeros.
910pub const BUFFER_ALL_ZEROS = 754;1364pub const BUFFER_ALL_ZEROS = 754;
1365
911/// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link.1366/// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link.
912pub const REPARSE_OBJECT = 755;1367pub const REPARSE_OBJECT = 755;
1368
913/// The device has succeeded a query-stop and its resource requirements have changed.1369/// The device has succeeded a query-stop and its resource requirements have changed.
914pub const RESOURCE_REQUIREMENTS_CHANGED = 756;1370pub const RESOURCE_REQUIREMENTS_CHANGED = 756;
1371
915/// The translator has translated these resources into the global space and no further translations should be performed.1372/// The translator has translated these resources into the global space and no further translations should be performed.
916pub const TRANSLATION_COMPLETE = 757;1373pub const TRANSLATION_COMPLETE = 757;
1374
917/// A process being terminated has no threads to terminate.1375/// A process being terminated has no threads to terminate.
918pub const NOTHING_TO_TERMINATE = 758;1376pub const NOTHING_TO_TERMINATE = 758;
1377
919/// The specified process is not part of a job.1378/// The specified process is not part of a job.
920pub const PROCESS_NOT_IN_JOB = 759;1379pub const PROCESS_NOT_IN_JOB = 759;
1380
921/// The specified process is part of a job.1381/// The specified process is part of a job.
922pub const PROCESS_IN_JOB = 760;1382pub const PROCESS_IN_JOB = 760;
1383
923/// {Volume Shadow Copy Service} The system is now ready for hibernation.1384/// {Volume Shadow Copy Service} The system is now ready for hibernation.
924pub const VOLSNAP_HIBERNATE_READY = 761;1385pub const VOLSNAP_HIBERNATE_READY = 761;
1386
925/// A file system or file system filter driver has successfully completed an FsFilter operation.1387/// A file system or file system filter driver has successfully completed an FsFilter operation.
926pub const FSFILTER_OP_COMPLETED_SUCCESSFULLY = 762;1388pub const FSFILTER_OP_COMPLETED_SUCCESSFULLY = 762;
1389
927/// The specified interrupt vector was already connected.1390/// The specified interrupt vector was already connected.
928pub const INTERRUPT_VECTOR_ALREADY_CONNECTED = 763;1391pub const INTERRUPT_VECTOR_ALREADY_CONNECTED = 763;
1392
929/// The specified interrupt vector is still connected.1393/// The specified interrupt vector is still connected.
930pub const INTERRUPT_STILL_CONNECTED = 764;1394pub const INTERRUPT_STILL_CONNECTED = 764;
1395
931/// An operation is blocked waiting for an oplock.1396/// An operation is blocked waiting for an oplock.
932pub const WAIT_FOR_OPLOCK = 765;1397pub const WAIT_FOR_OPLOCK = 765;
1398
933/// Debugger handled exception.1399/// Debugger handled exception.
934pub const DBG_EXCEPTION_HANDLED = 766;1400pub const DBG_EXCEPTION_HANDLED = 766;
1401
935/// Debugger continued.1402/// Debugger continued.
936pub const DBG_CONTINUE = 767;1403pub const DBG_CONTINUE = 767;
1404
937/// An exception occurred in a user mode callback and the kernel callback frame should be removed.1405/// An exception occurred in a user mode callback and the kernel callback frame should be removed.
938pub const CALLBACK_POP_STACK = 768;1406pub const CALLBACK_POP_STACK = 768;
1407
939/// Compression is disabled for this volume.1408/// Compression is disabled for this volume.
940pub const COMPRESSION_DISABLED = 769;1409pub const COMPRESSION_DISABLED = 769;
1410
941/// The data provider cannot fetch backwards through a result set.1411/// The data provider cannot fetch backwards through a result set.
942pub const CANTFETCHBACKWARDS = 770;1412pub const CANTFETCHBACKWARDS = 770;
1413
943/// The data provider cannot scroll backwards through a result set.1414/// The data provider cannot scroll backwards through a result set.
944pub const CANTSCROLLBACKWARDS = 771;1415pub const CANTSCROLLBACKWARDS = 771;
1416
945/// The data provider requires that previously fetched data is released before asking for more data.1417/// The data provider requires that previously fetched data is released before asking for more data.
946pub const ROWSNOTRELEASED = 772;1418pub const ROWSNOTRELEASED = 772;
1419
947/// The data provider was not able to interpret the flags set for a column binding in an accessor.1420/// The data provider was not able to interpret the flags set for a column binding in an accessor.
948pub const BAD_ACCESSOR_FLAGS = 773;1421pub const BAD_ACCESSOR_FLAGS = 773;
1422
949/// One or more errors occurred while processing the request.1423/// One or more errors occurred while processing the request.
950pub const ERRORS_ENCOUNTERED = 774;1424pub const ERRORS_ENCOUNTERED = 774;
1425
951/// The implementation is not capable of performing the request.1426/// The implementation is not capable of performing the request.
952pub const NOT_CAPABLE = 775;1427pub const NOT_CAPABLE = 775;
1428
953/// The client of a component requested an operation which is not valid given the state of the component instance.1429/// The client of a component requested an operation which is not valid given the state of the component instance.
954pub const REQUEST_OUT_OF_SEQUENCE = 776;1430pub const REQUEST_OUT_OF_SEQUENCE = 776;
1431
955/// A version number could not be parsed.1432/// A version number could not be parsed.
956pub const VERSION_PARSE_ERROR = 777;1433pub const VERSION_PARSE_ERROR = 777;
1434
957/// The iterator's start position is invalid.1435/// The iterator's start position is invalid.
958pub const BADSTARTPOSITION = 778;1436pub const BADSTARTPOSITION = 778;
1437
959/// The hardware has reported an uncorrectable memory error.1438/// The hardware has reported an uncorrectable memory error.
960pub const MEMORY_HARDWARE = 779;1439pub const MEMORY_HARDWARE = 779;
1440
961/// The attempted operation required self healing to be enabled.1441/// The attempted operation required self healing to be enabled.
962pub const DISK_REPAIR_DISABLED = 780;1442pub const DISK_REPAIR_DISABLED = 780;
1443
963/// The Desktop heap encountered an error while allocating session memory. There is more information in the system event log.1444/// The Desktop heap encountered an error while allocating session memory. There is more information in the system event log.
964pub const INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE = 781;1445pub const INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE = 781;
1446
965/// The system power state is transitioning from %2 to %3.1447/// The system power state is transitioning from %2 to %3.
966pub const SYSTEM_POWERSTATE_TRANSITION = 782;1448pub const SYSTEM_POWERSTATE_TRANSITION = 782;
1449
967/// The system power state is transitioning from %2 to %3 but could enter %4.1450/// The system power state is transitioning from %2 to %3 but could enter %4.
968pub const SYSTEM_POWERSTATE_COMPLEX_TRANSITION = 783;1451pub const SYSTEM_POWERSTATE_COMPLEX_TRANSITION = 783;
1452
969/// A thread is getting dispatched with MCA EXCEPTION because of MCA.1453/// A thread is getting dispatched with MCA EXCEPTION because of MCA.
970pub const MCA_EXCEPTION = 784;1454pub const MCA_EXCEPTION = 784;
1455
971/// Access to %1 is monitored by policy rule %2.1456/// Access to %1 is monitored by policy rule %2.
972pub const ACCESS_AUDIT_BY_POLICY = 785;1457pub const ACCESS_AUDIT_BY_POLICY = 785;
1458
973/// Access to %1 has been restricted by your Administrator by policy rule %2.1459/// Access to %1 has been restricted by your Administrator by policy rule %2.
974pub const ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY = 786;1460pub const ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY = 786;
1461
975/// A valid hibernation file has been invalidated and should be abandoned.1462/// A valid hibernation file has been invalidated and should be abandoned.
976pub const ABANDON_HIBERFILE = 787;1463pub const ABANDON_HIBERFILE = 787;
1464
977/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error may be caused by network connectivity issues. Please try to save this file elsewhere.1465/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error may be caused by network connectivity issues. Please try to save this file elsewhere.
978pub const LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED = 788;1466pub const LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED = 788;
1467
979/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error was returned by the server on which the file exists. Please try to save this file elsewhere.1468/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error was returned by the server on which the file exists. Please try to save this file elsewhere.
980pub const LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR = 789;1469pub const LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR = 789;
1470
981/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error may be caused if the device has been removed or the media is write-protected.1471/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error may be caused if the device has been removed or the media is write-protected.
982pub const LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR = 790;1472pub const LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR = 790;
1473
983/// The resources required for this device conflict with the MCFG table.1474/// The resources required for this device conflict with the MCFG table.
984pub const BAD_MCFG_TABLE = 791;1475pub const BAD_MCFG_TABLE = 791;
1476
985/// The volume repair could not be performed while it is online. Please schedule to take the volume offline so that it can be repaired.1477/// The volume repair could not be performed while it is online. Please schedule to take the volume offline so that it can be repaired.
986pub const DISK_REPAIR_REDIRECTED = 792;1478pub const DISK_REPAIR_REDIRECTED = 792;
1479
987/// The volume repair was not successful.1480/// The volume repair was not successful.
988pub const DISK_REPAIR_UNSUCCESSFUL = 793;1481pub const DISK_REPAIR_UNSUCCESSFUL = 793;
1482
989/// One of the volume corruption logs is full. Further corruptions that may be detected won't be logged.1483/// One of the volume corruption logs is full. Further corruptions that may be detected won't be logged.
990pub const CORRUPT_LOG_OVERFULL = 794;1484pub const CORRUPT_LOG_OVERFULL = 794;
1485
991/// One of the volume corruption logs is internally corrupted and needs to be recreated. The volume may contain undetected corruptions and must be scanned.1486/// One of the volume corruption logs is internally corrupted and needs to be recreated. The volume may contain undetected corruptions and must be scanned.
992pub const CORRUPT_LOG_CORRUPTED = 795;1487pub const CORRUPT_LOG_CORRUPTED = 795;
1488
993/// One of the volume corruption logs is unavailable for being operated on.1489/// One of the volume corruption logs is unavailable for being operated on.
994pub const CORRUPT_LOG_UNAVAILABLE = 796;1490pub const CORRUPT_LOG_UNAVAILABLE = 796;
1491
995/// One of the volume corruption logs was deleted while still having corruption records in them. The volume contains detected corruptions and must be scanned.1492/// One of the volume corruption logs was deleted while still having corruption records in them. The volume contains detected corruptions and must be scanned.
996pub const CORRUPT_LOG_DELETED_FULL = 797;1493pub const CORRUPT_LOG_DELETED_FULL = 797;
1494
997/// One of the volume corruption logs was cleared by chkdsk and no longer contains real corruptions.1495/// One of the volume corruption logs was cleared by chkdsk and no longer contains real corruptions.
998pub const CORRUPT_LOG_CLEARED = 798;1496pub const CORRUPT_LOG_CLEARED = 798;
1497
999/// Orphaned files exist on the volume but could not be recovered because no more new names could be created in the recovery directory. Files must be moved from the recovery directory.1498/// Orphaned files exist on the volume but could not be recovered because no more new names could be created in the recovery directory. Files must be moved from the recovery directory.
1000pub const ORPHAN_NAME_EXHAUSTED = 799;1499pub const ORPHAN_NAME_EXHAUSTED = 799;
1500
1001/// The oplock that was associated with this handle is now associated with a different handle.1501/// The oplock that was associated with this handle is now associated with a different handle.
1002pub const OPLOCK_SWITCHED_TO_NEW_HANDLE = 800;1502pub const OPLOCK_SWITCHED_TO_NEW_HANDLE = 800;
1503
1003/// An oplock of the requested level cannot be granted. An oplock of a lower level may be available.1504/// An oplock of the requested level cannot be granted. An oplock of a lower level may be available.
1004pub const CANNOT_GRANT_REQUESTED_OPLOCK = 801;1505pub const CANNOT_GRANT_REQUESTED_OPLOCK = 801;
1506
1005/// The operation did not complete successfully because it would cause an oplock to be broken. The caller has requested that existing oplocks not be broken.1507/// The operation did not complete successfully because it would cause an oplock to be broken. The caller has requested that existing oplocks not be broken.
1006pub const CANNOT_BREAK_OPLOCK = 802;1508pub const CANNOT_BREAK_OPLOCK = 802;
1509
1007/// The handle with which this oplock was associated has been closed. The oplock is now broken.1510/// The handle with which this oplock was associated has been closed. The oplock is now broken.
1008pub const OPLOCK_HANDLE_CLOSED = 803;1511pub const OPLOCK_HANDLE_CLOSED = 803;
1512
1009/// The specified access control entry (ACE) does not contain a condition.1513/// The specified access control entry (ACE) does not contain a condition.
1010pub const NO_ACE_CONDITION = 804;1514pub const NO_ACE_CONDITION = 804;
1515
1011/// The specified access control entry (ACE) contains an invalid condition.1516/// The specified access control entry (ACE) contains an invalid condition.
1012pub const INVALID_ACE_CONDITION = 805;1517pub const INVALID_ACE_CONDITION = 805;
1518
1013/// Access to the specified file handle has been revoked.1519/// Access to the specified file handle has been revoked.
1014pub const FILE_HANDLE_REVOKED = 806;1520pub const FILE_HANDLE_REVOKED = 806;
1521
1015/// An image file was mapped at a different address from the one specified in the image file but fixups will still be automatically performed on the image.1522/// An image file was mapped at a different address from the one specified in the image file but fixups will still be automatically performed on the image.
1016pub const IMAGE_AT_DIFFERENT_BASE = 807;1523pub const IMAGE_AT_DIFFERENT_BASE = 807;
1524
1017/// Access to the extended attribute was denied.1525/// Access to the extended attribute was denied.
1018pub const EA_ACCESS_DENIED = 994;1526pub const EA_ACCESS_DENIED = 994;
1527
1019/// The I/O operation has been aborted because of either a thread exit or an application request.1528/// The I/O operation has been aborted because of either a thread exit or an application request.
1020pub const OPERATION_ABORTED = 995;1529pub const OPERATION_ABORTED = 995;
1530
1021/// Overlapped I/O event is not in a signaled state.1531/// Overlapped I/O event is not in a signaled state.
1022pub const IO_INCOMPLETE = 996;1532pub const IO_INCOMPLETE = 996;
1533
1023/// Overlapped I/O operation is in progress.1534/// Overlapped I/O operation is in progress.
1024pub const IO_PENDING = 997;1535pub const IO_PENDING = 997;
1536
1025/// Invalid access to memory location.1537/// Invalid access to memory location.
1026pub const NOACCESS = 998;1538pub const NOACCESS = 998;
1539
1027/// Error performing inpage operation.1540/// Error performing inpage operation.
1028pub const SWAPERROR = 999;1541pub const SWAPERROR = 999;
1542
1029/// Recursion too deep; the stack overflowed.1543/// Recursion too deep; the stack overflowed.
1030pub const STACK_OVERFLOW = 1001;1544pub const STACK_OVERFLOW = 1001;
1545
1031/// The window cannot act on the sent message.1546/// The window cannot act on the sent message.
1032pub const INVALID_MESSAGE = 1002;1547pub const INVALID_MESSAGE = 1002;
1548
1033/// Cannot complete this function.1549/// Cannot complete this function.
1034pub const CAN_NOT_COMPLETE = 1003;1550pub const CAN_NOT_COMPLETE = 1003;
1551
1035/// Invalid flags.1552/// Invalid flags.
1036pub const INVALID_FLAGS = 1004;1553pub const INVALID_FLAGS = 1004;
1554
1037/// The volume does not contain a recognized file system. Please make sure that all required file system drivers are loaded and that the volume is not corrupted.1555/// The volume does not contain a recognized file system. Please make sure that all required file system drivers are loaded and that the volume is not corrupted.
1038pub const UNRECOGNIZED_VOLUME = 1005;1556pub const UNRECOGNIZED_VOLUME = 1005;
1557
1039/// The volume for a file has been externally altered so that the opened file is no longer valid.1558/// The volume for a file has been externally altered so that the opened file is no longer valid.
1040pub const FILE_INVALID = 1006;1559pub const FILE_INVALID = 1006;
1560
1041/// The requested operation cannot be performed in full-screen mode.1561/// The requested operation cannot be performed in full-screen mode.
1042pub const FULLSCREEN_MODE = 1007;1562pub const FULLSCREEN_MODE = 1007;
1563
1043/// An attempt was made to reference a token that does not exist.1564/// An attempt was made to reference a token that does not exist.
1044pub const NO_TOKEN = 1008;1565pub const NO_TOKEN = 1008;
1566
1045/// The configuration registry database is corrupt.1567/// The configuration registry database is corrupt.
1046pub const BADDB = 1009;1568pub const BADDB = 1009;
1569
1047/// The configuration registry key is invalid.1570/// The configuration registry key is invalid.
1048pub const BADKEY = 1010;1571pub const BADKEY = 1010;
1572
1049/// The configuration registry key could not be opened.1573/// The configuration registry key could not be opened.
1050pub const CANTOPEN = 1011;1574pub const CANTOPEN = 1011;
1575
1051/// The configuration registry key could not be read.1576/// The configuration registry key could not be read.
1052pub const CANTREAD = 1012;1577pub const CANTREAD = 1012;
1578
1053/// The configuration registry key could not be written.1579/// The configuration registry key could not be written.
1054pub const CANTWRITE = 1013;1580pub const CANTWRITE = 1013;
1581
1055/// One of the files in the registry database had to be recovered by use of a log or alternate copy. The recovery was successful.1582/// One of the files in the registry database had to be recovered by use of a log or alternate copy. The recovery was successful.
1056pub const REGISTRY_RECOVERED = 1014;1583pub const REGISTRY_RECOVERED = 1014;
1584
1057/// The registry is corrupted. The structure of one of the files containing registry data is corrupted, or the system's memory image of the file is corrupted, or the file could not be recovered because the alternate copy or log was absent or corrupted.1585/// The registry is corrupted. The structure of one of the files containing registry data is corrupted, or the system's memory image of the file is corrupted, or the file could not be recovered because the alternate copy or log was absent or corrupted.
1058pub const REGISTRY_CORRUPT = 1015;1586pub const REGISTRY_CORRUPT = 1015;
1587
1059/// An I/O operation initiated by the registry failed unrecoverably. The registry could not read in, or write out, or flush, one of the files that contain the system's image of the registry.1588/// An I/O operation initiated by the registry failed unrecoverably. The registry could not read in, or write out, or flush, one of the files that contain the system's image of the registry.
1060pub const REGISTRY_IO_FAILED = 1016;1589pub const REGISTRY_IO_FAILED = 1016;
1590
1061/// The system has attempted to load or restore a file into the registry, but the specified file is not in a registry file format.1591/// The system has attempted to load or restore a file into the registry, but the specified file is not in a registry file format.
1062pub const NOT_REGISTRY_FILE = 1017;1592pub const NOT_REGISTRY_FILE = 1017;
1593
1063/// Illegal operation attempted on a registry key that has been marked for deletion.1594/// Illegal operation attempted on a registry key that has been marked for deletion.
1064pub const KEY_DELETED = 1018;1595pub const KEY_DELETED = 1018;
1596
1065/// System could not allocate the required space in a registry log.1597/// System could not allocate the required space in a registry log.
1066pub const NO_LOG_SPACE = 1019;1598pub const NO_LOG_SPACE = 1019;
1599
1067/// Cannot create a symbolic link in a registry key that already has subkeys or values.1600/// Cannot create a symbolic link in a registry key that already has subkeys or values.
1068pub const KEY_HAS_CHILDREN = 1020;1601pub const KEY_HAS_CHILDREN = 1020;
1602
1069/// Cannot create a stable subkey under a volatile parent key.1603/// Cannot create a stable subkey under a volatile parent key.
1070pub const CHILD_MUST_BE_VOLATILE = 1021;1604pub const CHILD_MUST_BE_VOLATILE = 1021;
1605
1071/// A notify change request is being completed and the information is not being returned in the caller's buffer. The caller now needs to enumerate the files to find the changes.1606/// A notify change request is being completed and the information is not being returned in the caller's buffer. The caller now needs to enumerate the files to find the changes.
1072pub const NOTIFY_ENUM_DIR = 1022;1607pub const NOTIFY_ENUM_DIR = 1022;
1608
1073/// A stop control has been sent to a service that other running services are dependent on.1609/// A stop control has been sent to a service that other running services are dependent on.
1074pub const DEPENDENT_SERVICES_RUNNING = 1051;1610pub const DEPENDENT_SERVICES_RUNNING = 1051;
1611
1075/// The requested control is not valid for this service.1612/// The requested control is not valid for this service.
1076pub const INVALID_SERVICE_CONTROL = 1052;1613pub const INVALID_SERVICE_CONTROL = 1052;
1614
1077/// The service did not respond to the start or control request in a timely fashion.1615/// The service did not respond to the start or control request in a timely fashion.
1078pub const SERVICE_REQUEST_TIMEOUT = 1053;1616pub const SERVICE_REQUEST_TIMEOUT = 1053;
1617
1079/// A thread could not be created for the service.1618/// A thread could not be created for the service.
1080pub const SERVICE_NO_THREAD = 1054;1619pub const SERVICE_NO_THREAD = 1054;
1620
1081/// The service database is locked.1621/// The service database is locked.
1082pub const SERVICE_DATABASE_LOCKED = 1055;1622pub const SERVICE_DATABASE_LOCKED = 1055;
1623
1083/// An instance of the service is already running.1624/// An instance of the service is already running.
1084pub const SERVICE_ALREADY_RUNNING = 1056;1625pub const SERVICE_ALREADY_RUNNING = 1056;
1626
1085/// The account name is invalid or does not exist, or the password is invalid for the account name specified.1627/// The account name is invalid or does not exist, or the password is invalid for the account name specified.
1086pub const INVALID_SERVICE_ACCOUNT = 1057;1628pub const INVALID_SERVICE_ACCOUNT = 1057;
1629
1087/// The service cannot be started, either because it is disabled or because it has no enabled devices associated with it.1630/// The service cannot be started, either because it is disabled or because it has no enabled devices associated with it.
1088pub const SERVICE_DISABLED = 1058;1631pub const SERVICE_DISABLED = 1058;
1632
1089/// Circular service dependency was specified.1633/// Circular service dependency was specified.
1090pub const CIRCULAR_DEPENDENCY = 1059;1634pub const CIRCULAR_DEPENDENCY = 1059;
1635
1091/// The specified service does not exist as an installed service.1636/// The specified service does not exist as an installed service.
1092pub const SERVICE_DOES_NOT_EXIST = 1060;1637pub const SERVICE_DOES_NOT_EXIST = 1060;
1638
1093/// The service cannot accept control messages at this time.1639/// The service cannot accept control messages at this time.
1094pub const SERVICE_CANNOT_ACCEPT_CTRL = 1061;1640pub const SERVICE_CANNOT_ACCEPT_CTRL = 1061;
1641
1095/// The service has not been started.1642/// The service has not been started.
1096pub const SERVICE_NOT_ACTIVE = 1062;1643pub const SERVICE_NOT_ACTIVE = 1062;
1644
1097/// The service process could not connect to the service controller.1645/// The service process could not connect to the service controller.
1098pub const FAILED_SERVICE_CONTROLLER_CONNECT = 1063;1646pub const FAILED_SERVICE_CONTROLLER_CONNECT = 1063;
1647
1099/// An exception occurred in the service when handling the control request.1648/// An exception occurred in the service when handling the control request.
1100pub const EXCEPTION_IN_SERVICE = 1064;1649pub const EXCEPTION_IN_SERVICE = 1064;
1650
1101/// The database specified does not exist.1651/// The database specified does not exist.
1102pub const DATABASE_DOES_NOT_EXIST = 1065;1652pub const DATABASE_DOES_NOT_EXIST = 1065;
1653
1103/// The service has returned a service-specific error code.1654/// The service has returned a service-specific error code.
1104pub const SERVICE_SPECIFIC_ERROR = 1066;1655pub const SERVICE_SPECIFIC_ERROR = 1066;
1656
1105/// The process terminated unexpectedly.1657/// The process terminated unexpectedly.
1106pub const PROCESS_ABORTED = 1067;1658pub const PROCESS_ABORTED = 1067;
1659
1107/// The dependency service or group failed to start.1660/// The dependency service or group failed to start.
1108pub const SERVICE_DEPENDENCY_FAIL = 1068;1661pub const SERVICE_DEPENDENCY_FAIL = 1068;
1662
1109/// The service did not start due to a logon failure.1663/// The service did not start due to a logon failure.
1110pub const SERVICE_LOGON_FAILED = 1069;1664pub const SERVICE_LOGON_FAILED = 1069;
1665
1111/// After starting, the service hung in a start-pending state.1666/// After starting, the service hung in a start-pending state.
1112pub const SERVICE_START_HANG = 1070;1667pub const SERVICE_START_HANG = 1070;
1668
1113/// The specified service database lock is invalid.1669/// The specified service database lock is invalid.
1114pub const INVALID_SERVICE_LOCK = 1071;1670pub const INVALID_SERVICE_LOCK = 1071;
1671
1115/// The specified service has been marked for deletion.1672/// The specified service has been marked for deletion.
1116pub const SERVICE_MARKED_FOR_DELETE = 1072;1673pub const SERVICE_MARKED_FOR_DELETE = 1072;
1674
1117/// The specified service already exists.1675/// The specified service already exists.
1118pub const SERVICE_EXISTS = 1073;1676pub const SERVICE_EXISTS = 1073;
1677
1119/// The system is currently running with the last-known-good configuration.1678/// The system is currently running with the last-known-good configuration.
1120pub const ALREADY_RUNNING_LKG = 1074;1679pub const ALREADY_RUNNING_LKG = 1074;
1680
1121/// The dependency service does not exist or has been marked for deletion.1681/// The dependency service does not exist or has been marked for deletion.
1122pub const SERVICE_DEPENDENCY_DELETED = 1075;1682pub const SERVICE_DEPENDENCY_DELETED = 1075;
1683
1123/// The current boot has already been accepted for use as the last-known-good control set.1684/// The current boot has already been accepted for use as the last-known-good control set.
1124pub const BOOT_ALREADY_ACCEPTED = 1076;1685pub const BOOT_ALREADY_ACCEPTED = 1076;
1686
1125/// No attempts to start the service have been made since the last boot.1687/// No attempts to start the service have been made since the last boot.
1126pub const SERVICE_NEVER_STARTED = 1077;1688pub const SERVICE_NEVER_STARTED = 1077;
1689
1127/// The name is already in use as either a service name or a service display name.1690/// The name is already in use as either a service name or a service display name.
1128pub const DUPLICATE_SERVICE_NAME = 1078;1691pub const DUPLICATE_SERVICE_NAME = 1078;
1692
1129/// The account specified for this service is different from the account specified for other services running in the same process.1693/// The account specified for this service is different from the account specified for other services running in the same process.
1130pub const DIFFERENT_SERVICE_ACCOUNT = 1079;1694pub const DIFFERENT_SERVICE_ACCOUNT = 1079;
1695
1131/// Failure actions can only be set for Win32 services, not for drivers.1696/// Failure actions can only be set for Win32 services, not for drivers.
1132pub const CANNOT_DETECT_DRIVER_FAILURE = 1080;1697pub const CANNOT_DETECT_DRIVER_FAILURE = 1080;
1698
1133/// This service runs in the same process as the service control manager. Therefore, the service control manager cannot take action if this service's process terminates unexpectedly.1699/// This service runs in the same process as the service control manager. Therefore, the service control manager cannot take action if this service's process terminates unexpectedly.
1134pub const CANNOT_DETECT_PROCESS_ABORT = 1081;1700pub const CANNOT_DETECT_PROCESS_ABORT = 1081;
1701
1135/// No recovery program has been configured for this service.1702/// No recovery program has been configured for this service.
1136pub const NO_RECOVERY_PROGRAM = 1082;1703pub const NO_RECOVERY_PROGRAM = 1082;
1704
1137/// The executable program that this service is configured to run in does not implement the service.1705/// The executable program that this service is configured to run in does not implement the service.
1138pub const SERVICE_NOT_IN_EXE = 1083;1706pub const SERVICE_NOT_IN_EXE = 1083;
1707
1139/// This service cannot be started in Safe Mode.1708/// This service cannot be started in Safe Mode.
1140pub const NOT_SAFEBOOT_SERVICE = 1084;1709pub const NOT_SAFEBOOT_SERVICE = 1084;
1710
1141/// The physical end of the tape has been reached.1711/// The physical end of the tape has been reached.
1142pub const END_OF_MEDIA = 1100;1712pub const END_OF_MEDIA = 1100;
1713
1143/// A tape access reached a filemark.1714/// A tape access reached a filemark.
1144pub const FILEMARK_DETECTED = 1101;1715pub const FILEMARK_DETECTED = 1101;
1716
1145/// The beginning of the tape or a partition was encountered.1717/// The beginning of the tape or a partition was encountered.
1146pub const BEGINNING_OF_MEDIA = 1102;1718pub const BEGINNING_OF_MEDIA = 1102;
1719
1147/// A tape access reached the end of a set of files.1720/// A tape access reached the end of a set of files.
1148pub const SETMARK_DETECTED = 1103;1721pub const SETMARK_DETECTED = 1103;
1722
1149/// No more data is on the tape.1723/// No more data is on the tape.
1150pub const NO_DATA_DETECTED = 1104;1724pub const NO_DATA_DETECTED = 1104;
1725
1151/// Tape could not be partitioned.1726/// Tape could not be partitioned.
1152pub const PARTITION_FAILURE = 1105;1727pub const PARTITION_FAILURE = 1105;
1728
1153/// When accessing a new tape of a multivolume partition, the current block size is incorrect.1729/// When accessing a new tape of a multivolume partition, the current block size is incorrect.
1154pub const INVALID_BLOCK_LENGTH = 1106;1730pub const INVALID_BLOCK_LENGTH = 1106;
1731
1155/// Tape partition information could not be found when loading a tape.1732/// Tape partition information could not be found when loading a tape.
1156pub const DEVICE_NOT_PARTITIONED = 1107;1733pub const DEVICE_NOT_PARTITIONED = 1107;
1734
1157/// Unable to lock the media eject mechanism.1735/// Unable to lock the media eject mechanism.
1158pub const UNABLE_TO_LOCK_MEDIA = 1108;1736pub const UNABLE_TO_LOCK_MEDIA = 1108;
1737
1159/// Unable to unload the media.1738/// Unable to unload the media.
1160pub const UNABLE_TO_UNLOAD_MEDIA = 1109;1739pub const UNABLE_TO_UNLOAD_MEDIA = 1109;
1740
1161/// The media in the drive may have changed.1741/// The media in the drive may have changed.
1162pub const MEDIA_CHANGED = 1110;1742pub const MEDIA_CHANGED = 1110;
1743
1163/// The I/O bus was reset.1744/// The I/O bus was reset.
1164pub const BUS_RESET = 1111;1745pub const BUS_RESET = 1111;
1746
1165/// No media in drive.1747/// No media in drive.
1166pub const NO_MEDIA_IN_DRIVE = 1112;1748pub const NO_MEDIA_IN_DRIVE = 1112;
1749
1167/// No mapping for the Unicode character exists in the target multi-byte code page.1750/// No mapping for the Unicode character exists in the target multi-byte code page.
1168pub const NO_UNICODE_TRANSLATION = 1113;1751pub const NO_UNICODE_TRANSLATION = 1113;
1752
1169/// A dynamic link library (DLL) initialization routine failed.1753/// A dynamic link library (DLL) initialization routine failed.
1170pub const DLL_INIT_FAILED = 1114;1754pub const DLL_INIT_FAILED = 1114;
1755
1171/// A system shutdown is in progress.1756/// A system shutdown is in progress.
1172pub const SHUTDOWN_IN_PROGRESS = 1115;1757pub const SHUTDOWN_IN_PROGRESS = 1115;
1758
1173/// Unable to abort the system shutdown because no shutdown was in progress.1759/// Unable to abort the system shutdown because no shutdown was in progress.
1174pub const NO_SHUTDOWN_IN_PROGRESS = 1116;1760pub const NO_SHUTDOWN_IN_PROGRESS = 1116;
1761
1175/// The request could not be performed because of an I/O device error.1762/// The request could not be performed because of an I/O device error.
1176pub const IO_DEVICE = 1117;1763pub const IO_DEVICE = 1117;
1764
1177/// No serial device was successfully initialized. The serial driver will unload.1765/// No serial device was successfully initialized. The serial driver will unload.
1178pub const SERIAL_NO_DEVICE = 1118;1766pub const SERIAL_NO_DEVICE = 1118;
1767
1179/// Unable to open a device that was sharing an interrupt request (IRQ) with other devices. At least one other device that uses that IRQ was already opened.1768/// Unable to open a device that was sharing an interrupt request (IRQ) with other devices. At least one other device that uses that IRQ was already opened.
1180pub const IRQ_BUSY = 1119;1769pub const IRQ_BUSY = 1119;
1770
1181/// A serial I/O operation was completed by another write to the serial port. The IOCTL_SERIAL_XOFF_COUNTER reached zero.)1771/// A serial I/O operation was completed by another write to the serial port. The IOCTL_SERIAL_XOFF_COUNTER reached zero.)
1182pub const MORE_WRITES = 1120;1772pub const MORE_WRITES = 1120;
1773
1183/// A serial I/O operation completed because the timeout period expired. The IOCTL_SERIAL_XOFF_COUNTER did not reach zero.)1774/// A serial I/O operation completed because the timeout period expired. The IOCTL_SERIAL_XOFF_COUNTER did not reach zero.)
1184pub const COUNTER_TIMEOUT = 1121;1775pub const COUNTER_TIMEOUT = 1121;
1776
1185/// No ID address mark was found on the floppy disk.1777/// No ID address mark was found on the floppy disk.
1186pub const FLOPPY_ID_MARK_NOT_FOUND = 1122;1778pub const FLOPPY_ID_MARK_NOT_FOUND = 1122;
1779
1187/// Mismatch between the floppy disk sector ID field and the floppy disk controller track address.1780/// Mismatch between the floppy disk sector ID field and the floppy disk controller track address.
1188pub const FLOPPY_WRONG_CYLINDER = 1123;1781pub const FLOPPY_WRONG_CYLINDER = 1123;
1782
1189/// The floppy disk controller reported an error that is not recognized by the floppy disk driver.1783/// The floppy disk controller reported an error that is not recognized by the floppy disk driver.
1190pub const FLOPPY_UNKNOWN_ERROR = 1124;1784pub const FLOPPY_UNKNOWN_ERROR = 1124;
1785
1191/// The floppy disk controller returned inconsistent results in its registers.1786/// The floppy disk controller returned inconsistent results in its registers.
1192pub const FLOPPY_BAD_REGISTERS = 1125;1787pub const FLOPPY_BAD_REGISTERS = 1125;
1788
1193/// While accessing the hard disk, a recalibrate operation failed, even after retries.1789/// While accessing the hard disk, a recalibrate operation failed, even after retries.
1194pub const DISK_RECALIBRATE_FAILED = 1126;1790pub const DISK_RECALIBRATE_FAILED = 1126;
1791
1195/// While accessing the hard disk, a disk operation failed even after retries.1792/// While accessing the hard disk, a disk operation failed even after retries.
1196pub const DISK_OPERATION_FAILED = 1127;1793pub const DISK_OPERATION_FAILED = 1127;
1794
1197/// While accessing the hard disk, a disk controller reset was needed, but even that failed.1795/// While accessing the hard disk, a disk controller reset was needed, but even that failed.
1198pub const DISK_RESET_FAILED = 1128;1796pub const DISK_RESET_FAILED = 1128;
1797
1199/// Physical end of tape encountered.1798/// Physical end of tape encountered.
1200pub const EOM_OVERFLOW = 1129;1799pub const EOM_OVERFLOW = 1129;
1800
1201/// Not enough server storage is available to process this command.1801/// Not enough server storage is available to process this command.
1202pub const NOT_ENOUGH_SERVER_MEMORY = 1130;1802pub const NOT_ENOUGH_SERVER_MEMORY = 1130;
1803
1203/// A potential deadlock condition has been detected.1804/// A potential deadlock condition has been detected.
1204pub const POSSIBLE_DEADLOCK = 1131;1805pub const POSSIBLE_DEADLOCK = 1131;
1806
1205/// The base address or the file offset specified does not have the proper alignment.1807/// The base address or the file offset specified does not have the proper alignment.
1206pub const MAPPED_ALIGNMENT = 1132;1808pub const MAPPED_ALIGNMENT = 1132;
1809
1207/// An attempt to change the system power state was vetoed by another application or driver.1810/// An attempt to change the system power state was vetoed by another application or driver.
1208pub const SET_POWER_STATE_VETOED = 1140;1811pub const SET_POWER_STATE_VETOED = 1140;
1812
1209/// The system BIOS failed an attempt to change the system power state.1813/// The system BIOS failed an attempt to change the system power state.
1210pub const SET_POWER_STATE_FAILED = 1141;1814pub const SET_POWER_STATE_FAILED = 1141;
1815
1211/// An attempt was made to create more links on a file than the file system supports.1816/// An attempt was made to create more links on a file than the file system supports.
1212pub const TOO_MANY_LINKS = 1142;1817pub const TOO_MANY_LINKS = 1142;
1818
1213/// The specified program requires a newer version of Windows.1819/// The specified program requires a newer version of Windows.
1214pub const OLD_WIN_VERSION = 1150;1820pub const OLD_WIN_VERSION = 1150;
1821
1215/// The specified program is not a Windows or MS-DOS program.1822/// The specified program is not a Windows or MS-DOS program.
1216pub const APP_WRONG_OS = 1151;1823pub const APP_WRONG_OS = 1151;
1824
1217/// Cannot start more than one instance of the specified program.1825/// Cannot start more than one instance of the specified program.
1218pub const SINGLE_INSTANCE_APP = 1152;1826pub const SINGLE_INSTANCE_APP = 1152;
1827
1219/// The specified program was written for an earlier version of Windows.1828/// The specified program was written for an earlier version of Windows.
1220pub const RMODE_APP = 1153;1829pub const RMODE_APP = 1153;
1830
1221/// One of the library files needed to run this application is damaged.1831/// One of the library files needed to run this application is damaged.
1222pub const INVALID_DLL = 1154;1832pub const INVALID_DLL = 1154;
1833
1223/// No application is associated with the specified file for this operation.1834/// No application is associated with the specified file for this operation.
1224pub const NO_ASSOCIATION = 1155;1835pub const NO_ASSOCIATION = 1155;
1836
1225/// An error occurred in sending the command to the application.1837/// An error occurred in sending the command to the application.
1226pub const DDE_FAIL = 1156;1838pub const DDE_FAIL = 1156;
1839
1227/// One of the library files needed to run this application cannot be found.1840/// One of the library files needed to run this application cannot be found.
1228pub const DLL_NOT_FOUND = 1157;1841pub const DLL_NOT_FOUND = 1157;
1842
1229/// The current process has used all of its system allowance of handles for Window Manager objects.1843/// The current process has used all of its system allowance of handles for Window Manager objects.
1230pub const NO_MORE_USER_HANDLES = 1158;1844pub const NO_MORE_USER_HANDLES = 1158;
1845
1231/// The message can be used only with synchronous operations.1846/// The message can be used only with synchronous operations.
1232pub const MESSAGE_SYNC_ONLY = 1159;1847pub const MESSAGE_SYNC_ONLY = 1159;
1848
1233/// The indicated source element has no media.1849/// The indicated source element has no media.
1234pub const SOURCE_ELEMENT_EMPTY = 1160;1850pub const SOURCE_ELEMENT_EMPTY = 1160;
1851
1235/// The indicated destination element already contains media.1852/// The indicated destination element already contains media.
1236pub const DESTINATION_ELEMENT_FULL = 1161;1853pub const DESTINATION_ELEMENT_FULL = 1161;
1854
1237/// The indicated element does not exist.1855/// The indicated element does not exist.
1238pub const ILLEGAL_ELEMENT_ADDRESS = 1162;1856pub const ILLEGAL_ELEMENT_ADDRESS = 1162;
1857
1239/// The indicated element is part of a magazine that is not present.1858/// The indicated element is part of a magazine that is not present.
1240pub const MAGAZINE_NOT_PRESENT = 1163;1859pub const MAGAZINE_NOT_PRESENT = 1163;
1860
1241/// The indicated device requires reinitialization due to hardware errors.1861/// The indicated device requires reinitialization due to hardware errors.
1242pub const DEVICE_REINITIALIZATION_NEEDED = 1164;1862pub const DEVICE_REINITIALIZATION_NEEDED = 1164;
1863
1243/// The device has indicated that cleaning is required before further operations are attempted.1864/// The device has indicated that cleaning is required before further operations are attempted.
1244pub const DEVICE_REQUIRES_CLEANING = 1165;1865pub const DEVICE_REQUIRES_CLEANING = 1165;
1866
1245/// The device has indicated that its door is open.1867/// The device has indicated that its door is open.
1246pub const DEVICE_DOOR_OPEN = 1166;1868pub const DEVICE_DOOR_OPEN = 1166;
1869
1247/// The device is not connected.1870/// The device is not connected.
1248pub const DEVICE_NOT_CONNECTED = 1167;1871pub const DEVICE_NOT_CONNECTED = 1167;
1872
1249/// Element not found.1873/// Element not found.
1250pub const NOT_FOUND = 1168;1874pub const NOT_FOUND = 1168;
1875
1251/// There was no match for the specified key in the index.1876/// There was no match for the specified key in the index.
1252pub const NO_MATCH = 1169;1877pub const NO_MATCH = 1169;
1878
1253/// The property set specified does not exist on the object.1879/// The property set specified does not exist on the object.
1254pub const SET_NOT_FOUND = 1170;1880pub const SET_NOT_FOUND = 1170;
1881
1255/// The point passed to GetMouseMovePoints is not in the buffer.1882/// The point passed to GetMouseMovePoints is not in the buffer.
1256pub const POINT_NOT_FOUND = 1171;1883pub const POINT_NOT_FOUND = 1171;
1884
1257/// The tracking (workstation) service is not running.1885/// The tracking (workstation) service is not running.
1258pub const NO_TRACKING_SERVICE = 1172;1886pub const NO_TRACKING_SERVICE = 1172;
1887
1259/// The Volume ID could not be found.1888/// The Volume ID could not be found.
1260pub const NO_VOLUME_ID = 1173;1889pub const NO_VOLUME_ID = 1173;
1890
1261/// Unable to remove the file to be replaced.1891/// Unable to remove the file to be replaced.
1262pub const UNABLE_TO_REMOVE_REPLACED = 1175;1892pub const UNABLE_TO_REMOVE_REPLACED = 1175;
1893
1263/// Unable to move the replacement file to the file to be replaced. The file to be replaced has retained its original name.1894/// Unable to move the replacement file to the file to be replaced. The file to be replaced has retained its original name.
1264pub const UNABLE_TO_MOVE_REPLACEMENT = 1176;1895pub const UNABLE_TO_MOVE_REPLACEMENT = 1176;
1896
1265/// Unable to move the replacement file to the file to be replaced. The file to be replaced has been renamed using the backup name.1897/// Unable to move the replacement file to the file to be replaced. The file to be replaced has been renamed using the backup name.
1266pub const UNABLE_TO_MOVE_REPLACEMENT_2 = 1177;1898pub const UNABLE_TO_MOVE_REPLACEMENT_2 = 1177;
1899
1267/// The volume change journal is being deleted.1900/// The volume change journal is being deleted.
1268pub const JOURNAL_DELETE_IN_PROGRESS = 1178;1901pub const JOURNAL_DELETE_IN_PROGRESS = 1178;
1902
1269/// The volume change journal is not active.1903/// The volume change journal is not active.
1270pub const JOURNAL_NOT_ACTIVE = 1179;1904pub const JOURNAL_NOT_ACTIVE = 1179;
1905
1271/// A file was found, but it may not be the correct file.1906/// A file was found, but it may not be the correct file.
1272pub const POTENTIAL_FILE_FOUND = 1180;1907pub const POTENTIAL_FILE_FOUND = 1180;
1908
1273/// The journal entry has been deleted from the journal.1909/// The journal entry has been deleted from the journal.
1274pub const JOURNAL_ENTRY_DELETED = 1181;1910pub const JOURNAL_ENTRY_DELETED = 1181;
1911
1275/// A system shutdown has already been scheduled.1912/// A system shutdown has already been scheduled.
1276pub const SHUTDOWN_IS_SCHEDULED = 1190;1913pub const SHUTDOWN_IS_SCHEDULED = 1190;
1914
1277/// The system shutdown cannot be initiated because there are other users logged on to the computer.1915/// The system shutdown cannot be initiated because there are other users logged on to the computer.
1278pub const SHUTDOWN_USERS_LOGGED_ON = 1191;1916pub const SHUTDOWN_USERS_LOGGED_ON = 1191;
1917
1279/// The specified device name is invalid.1918/// The specified device name is invalid.
1280pub const BAD_DEVICE = 1200;1919pub const BAD_DEVICE = 1200;
1920
1281/// The device is not currently connected but it is a remembered connection.1921/// The device is not currently connected but it is a remembered connection.
1282pub const CONNECTION_UNAVAIL = 1201;1922pub const CONNECTION_UNAVAIL = 1201;
1923
1283/// The local device name has a remembered connection to another network resource.1924/// The local device name has a remembered connection to another network resource.
1284pub const DEVICE_ALREADY_REMEMBERED = 1202;1925pub const DEVICE_ALREADY_REMEMBERED = 1202;
1926
1285/// The network path was either typed incorrectly, does not exist, or the network provider is not currently available. Please try retyping the path or contact your network administrator.1927/// The network path was either typed incorrectly, does not exist, or the network provider is not currently available. Please try retyping the path or contact your network administrator.
1286pub const NO_NET_OR_BAD_PATH = 1203;1928pub const NO_NET_OR_BAD_PATH = 1203;
1929
1287/// The specified network provider name is invalid.1930/// The specified network provider name is invalid.
1288pub const BAD_PROVIDER = 1204;1931pub const BAD_PROVIDER = 1204;
1932
1289/// Unable to open the network connection profile.1933/// Unable to open the network connection profile.
1290pub const CANNOT_OPEN_PROFILE = 1205;1934pub const CANNOT_OPEN_PROFILE = 1205;
1935
1291/// The network connection profile is corrupted.1936/// The network connection profile is corrupted.
1292pub const BAD_PROFILE = 1206;1937pub const BAD_PROFILE = 1206;
1938
1293/// Cannot enumerate a noncontainer.1939/// Cannot enumerate a noncontainer.
1294pub const NOT_CONTAINER = 1207;1940pub const NOT_CONTAINER = 1207;
1941
1295/// An extended error has occurred.1942/// An extended error has occurred.
1296pub const EXTENDED_ERROR = 1208;1943pub const EXTENDED_ERROR = 1208;
1944
1297/// The format of the specified group name is invalid.1945/// The format of the specified group name is invalid.
1298pub const INVALID_GROUPNAME = 1209;1946pub const INVALID_GROUPNAME = 1209;
1947
1299/// The format of the specified computer name is invalid.1948/// The format of the specified computer name is invalid.
1300pub const INVALID_COMPUTERNAME = 1210;1949pub const INVALID_COMPUTERNAME = 1210;
1950
1301/// The format of the specified event name is invalid.1951/// The format of the specified event name is invalid.
1302pub const INVALID_EVENTNAME = 1211;1952pub const INVALID_EVENTNAME = 1211;
1953
1303/// The format of the specified domain name is invalid.1954/// The format of the specified domain name is invalid.
1304pub const INVALID_DOMAINNAME = 1212;1955pub const INVALID_DOMAINNAME = 1212;
1956
1305/// The format of the specified service name is invalid.1957/// The format of the specified service name is invalid.
1306pub const INVALID_SERVICENAME = 1213;1958pub const INVALID_SERVICENAME = 1213;
1959
1307/// The format of the specified network name is invalid.1960/// The format of the specified network name is invalid.
1308pub const INVALID_NETNAME = 1214;1961pub const INVALID_NETNAME = 1214;
1962
1309/// The format of the specified share name is invalid.1963/// The format of the specified share name is invalid.
1310pub const INVALID_SHARENAME = 1215;1964pub const INVALID_SHARENAME = 1215;
1965
1311/// The format of the specified password is invalid.1966/// The format of the specified password is invalid.
1312pub const INVALID_PASSWORDNAME = 1216;1967pub const INVALID_PASSWORDNAME = 1216;
1968
1313/// The format of the specified message name is invalid.1969/// The format of the specified message name is invalid.
1314pub const INVALID_MESSAGENAME = 1217;1970pub const INVALID_MESSAGENAME = 1217;
1971
1315/// The format of the specified message destination is invalid.1972/// The format of the specified message destination is invalid.
1316pub const INVALID_MESSAGEDEST = 1218;1973pub const INVALID_MESSAGEDEST = 1218;
1974
1317/// Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again.1975/// Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again.
1318pub const SESSION_CREDENTIAL_CONFLICT = 1219;1976pub const SESSION_CREDENTIAL_CONFLICT = 1219;
1977
1319/// An attempt was made to establish a session to a network server, but there are already too many sessions established to that server.1978/// An attempt was made to establish a session to a network server, but there are already too many sessions established to that server.
1320pub const REMOTE_SESSION_LIMIT_EXCEEDED = 1220;1979pub const REMOTE_SESSION_LIMIT_EXCEEDED = 1220;
1980
1321/// The workgroup or domain name is already in use by another computer on the network.1981/// The workgroup or domain name is already in use by another computer on the network.
1322pub const DUP_DOMAINNAME = 1221;1982pub const DUP_DOMAINNAME = 1221;
1983
1323/// The network is not present or not started.1984/// The network is not present or not started.
1324pub const NO_NETWORK = 1222;1985pub const NO_NETWORK = 1222;
1986
1325/// The operation was canceled by the user.1987/// The operation was canceled by the user.
1326pub const CANCELLED = 1223;1988pub const CANCELLED = 1223;
1989
1327/// The requested operation cannot be performed on a file with a user-mapped section open.1990/// The requested operation cannot be performed on a file with a user-mapped section open.
1328pub const USER_MAPPED_FILE = 1224;1991pub const USER_MAPPED_FILE = 1224;
1992
1329/// The remote computer refused the network connection.1993/// The remote computer refused the network connection.
1330pub const CONNECTION_REFUSED = 1225;1994pub const CONNECTION_REFUSED = 1225;
1995
1331/// The network connection was gracefully closed.1996/// The network connection was gracefully closed.
1332pub const GRACEFUL_DISCONNECT = 1226;1997pub const GRACEFUL_DISCONNECT = 1226;
1998
1333/// The network transport endpoint already has an address associated with it.1999/// The network transport endpoint already has an address associated with it.
1334pub const ADDRESS_ALREADY_ASSOCIATED = 1227;2000pub const ADDRESS_ALREADY_ASSOCIATED = 1227;
2001
1335/// An address has not yet been associated with the network endpoint.2002/// An address has not yet been associated with the network endpoint.
1336pub const ADDRESS_NOT_ASSOCIATED = 1228;2003pub const ADDRESS_NOT_ASSOCIATED = 1228;
2004
1337/// An operation was attempted on a nonexistent network connection.2005/// An operation was attempted on a nonexistent network connection.
1338pub const CONNECTION_INVALID = 1229;2006pub const CONNECTION_INVALID = 1229;
2007
1339/// An invalid operation was attempted on an active network connection.2008/// An invalid operation was attempted on an active network connection.
1340pub const CONNECTION_ACTIVE = 1230;2009pub const CONNECTION_ACTIVE = 1230;
2010
1341/// The network location cannot be reached. For information about network troubleshooting, see Windows Help.2011/// The network location cannot be reached. For information about network troubleshooting, see Windows Help.
1342pub const NETWORK_UNREACHABLE = 1231;2012pub const NETWORK_UNREACHABLE = 1231;
2013
1343/// The network location cannot be reached. For information about network troubleshooting, see Windows Help.2014/// The network location cannot be reached. For information about network troubleshooting, see Windows Help.
1344pub const HOST_UNREACHABLE = 1232;2015pub const HOST_UNREACHABLE = 1232;
2016
1345/// The network location cannot be reached. For information about network troubleshooting, see Windows Help.2017/// The network location cannot be reached. For information about network troubleshooting, see Windows Help.
1346pub const PROTOCOL_UNREACHABLE = 1233;2018pub const PROTOCOL_UNREACHABLE = 1233;
2019
1347/// No service is operating at the destination network endpoint on the remote system.2020/// No service is operating at the destination network endpoint on the remote system.
1348pub const PORT_UNREACHABLE = 1234;2021pub const PORT_UNREACHABLE = 1234;
2022
1349/// The request was aborted.2023/// The request was aborted.
1350pub const REQUEST_ABORTED = 1235;2024pub const REQUEST_ABORTED = 1235;
2025
1351/// The network connection was aborted by the local system.2026/// The network connection was aborted by the local system.
1352pub const CONNECTION_ABORTED = 1236;2027pub const CONNECTION_ABORTED = 1236;
2028
1353/// The operation could not be completed. A retry should be performed.2029/// The operation could not be completed. A retry should be performed.
1354pub const RETRY = 1237;2030pub const RETRY = 1237;
2031
1355/// A connection to the server could not be made because the limit on the number of concurrent connections for this account has been reached.2032/// A connection to the server could not be made because the limit on the number of concurrent connections for this account has been reached.
1356pub const CONNECTION_COUNT_LIMIT = 1238;2033pub const CONNECTION_COUNT_LIMIT = 1238;
2034
1357/// Attempting to log in during an unauthorized time of day for this account.2035/// Attempting to log in during an unauthorized time of day for this account.
1358pub const LOGIN_TIME_RESTRICTION = 1239;2036pub const LOGIN_TIME_RESTRICTION = 1239;
2037
1359/// The account is not authorized to log in from this station.2038/// The account is not authorized to log in from this station.
1360pub const LOGIN_WKSTA_RESTRICTION = 1240;2039pub const LOGIN_WKSTA_RESTRICTION = 1240;
2040
1361/// The network address could not be used for the operation requested.2041/// The network address could not be used for the operation requested.
1362pub const INCORRECT_ADDRESS = 1241;2042pub const INCORRECT_ADDRESS = 1241;
2043
1363/// The service is already registered.2044/// The service is already registered.
1364pub const ALREADY_REGISTERED = 1242;2045pub const ALREADY_REGISTERED = 1242;
2046
1365/// The specified service does not exist.2047/// The specified service does not exist.
1366pub const SERVICE_NOT_FOUND = 1243;2048pub const SERVICE_NOT_FOUND = 1243;
2049
1367/// The operation being requested was not performed because the user has not been authenticated.2050/// The operation being requested was not performed because the user has not been authenticated.
1368pub const NOT_AUTHENTICATED = 1244;2051pub const NOT_AUTHENTICATED = 1244;
2052
1369/// The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist.2053/// The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist.
1370pub const NOT_LOGGED_ON = 1245;2054pub const NOT_LOGGED_ON = 1245;
2055
1371/// Continue with work in progress.2056/// Continue with work in progress.
1372pub const CONTINUE = 1246;2057pub const CONTINUE = 1246;
2058
1373/// An attempt was made to perform an initialization operation when initialization has already been completed.2059/// An attempt was made to perform an initialization operation when initialization has already been completed.
1374pub const ALREADY_INITIALIZED = 1247;2060pub const ALREADY_INITIALIZED = 1247;
2061
1375/// No more local devices.2062/// No more local devices.
1376pub const NO_MORE_DEVICES = 1248;2063pub const NO_MORE_DEVICES = 1248;
2064
1377/// The specified site does not exist.2065/// The specified site does not exist.
1378pub const NO_SUCH_SITE = 1249;2066pub const NO_SUCH_SITE = 1249;
2067
1379/// A domain controller with the specified name already exists.2068/// A domain controller with the specified name already exists.
1380pub const DOMAIN_CONTROLLER_EXISTS = 1250;2069pub const DOMAIN_CONTROLLER_EXISTS = 1250;
2070
1381/// This operation is supported only when you are connected to the server.2071/// This operation is supported only when you are connected to the server.
1382pub const ONLY_IF_CONNECTED = 1251;2072pub const ONLY_IF_CONNECTED = 1251;
2073
1383/// The group policy framework should call the extension even if there are no changes.2074/// The group policy framework should call the extension even if there are no changes.
1384pub const OVERRIDE_NOCHANGES = 1252;2075pub const OVERRIDE_NOCHANGES = 1252;
2076
1385/// The specified user does not have a valid profile.2077/// The specified user does not have a valid profile.
1386pub const BAD_USER_PROFILE = 1253;2078pub const BAD_USER_PROFILE = 1253;
2079
1387/// This operation is not supported on a computer running Windows Server 2003 for Small Business Server.2080/// This operation is not supported on a computer running Windows Server 2003 for Small Business Server.
1388pub const NOT_SUPPORTED_ON_SBS = 1254;2081pub const NOT_SUPPORTED_ON_SBS = 1254;
2082
1389/// The server machine is shutting down.2083/// The server machine is shutting down.
1390pub const SERVER_SHUTDOWN_IN_PROGRESS = 1255;2084pub const SERVER_SHUTDOWN_IN_PROGRESS = 1255;
2085
1391/// The remote system is not available. For information about network troubleshooting, see Windows Help.2086/// The remote system is not available. For information about network troubleshooting, see Windows Help.
1392pub const HOST_DOWN = 1256;2087pub const HOST_DOWN = 1256;
2088
1393/// The security identifier provided is not from an account domain.2089/// The security identifier provided is not from an account domain.
1394pub const NON_ACCOUNT_SID = 1257;2090pub const NON_ACCOUNT_SID = 1257;
2091
1395/// The security identifier provided does not have a domain component.2092/// The security identifier provided does not have a domain component.
1396pub const NON_DOMAIN_SID = 1258;2093pub const NON_DOMAIN_SID = 1258;
2094
1397/// AppHelp dialog canceled thus preventing the application from starting.2095/// AppHelp dialog canceled thus preventing the application from starting.
1398pub const APPHELP_BLOCK = 1259;2096pub const APPHELP_BLOCK = 1259;
2097
1399/// This program is blocked by group policy. For more information, contact your system administrator.2098/// This program is blocked by group policy. For more information, contact your system administrator.
1400pub const ACCESS_DISABLED_BY_POLICY = 1260;2099pub const ACCESS_DISABLED_BY_POLICY = 1260;
2100
1401/// A program attempt to use an invalid register value. Normally caused by an uninitialized register. This error is Itanium specific.2101/// A program attempt to use an invalid register value. Normally caused by an uninitialized register. This error is Itanium specific.
1402pub const REG_NAT_CONSUMPTION = 1261;2102pub const REG_NAT_CONSUMPTION = 1261;
2103
1403/// The share is currently offline or does not exist.2104/// The share is currently offline or does not exist.
1404pub const CSCSHARE_OFFLINE = 1262;2105pub const CSCSHARE_OFFLINE = 1262;
2106
1405/// The Kerberos protocol encountered an error while validating the KDC certificate during smartcard logon. There is more information in the system event log.2107/// The Kerberos protocol encountered an error while validating the KDC certificate during smartcard logon. There is more information in the system event log.
1406pub const PKINIT_FAILURE = 1263;2108pub const PKINIT_FAILURE = 1263;
2109
1407/// The Kerberos protocol encountered an error while attempting to utilize the smartcard subsystem.2110/// The Kerberos protocol encountered an error while attempting to utilize the smartcard subsystem.
1408pub const SMARTCARD_SUBSYSTEM_FAILURE = 1264;2111pub const SMARTCARD_SUBSYSTEM_FAILURE = 1264;
2112
1409/// The system cannot contact a domain controller to service the authentication request. Please try again later.2113/// The system cannot contact a domain controller to service the authentication request. Please try again later.
1410pub const DOWNGRADE_DETECTED = 1265;2114pub const DOWNGRADE_DETECTED = 1265;
2115
1411/// The machine is locked and cannot be shut down without the force option.2116/// The machine is locked and cannot be shut down without the force option.
1412pub const MACHINE_LOCKED = 1271;2117pub const MACHINE_LOCKED = 1271;
2118
1413/// An application-defined callback gave invalid data when called.2119/// An application-defined callback gave invalid data when called.
1414pub const CALLBACK_SUPPLIED_INVALID_DATA = 1273;2120pub const CALLBACK_SUPPLIED_INVALID_DATA = 1273;
2121
1415/// The group policy framework should call the extension in the synchronous foreground policy refresh.2122/// The group policy framework should call the extension in the synchronous foreground policy refresh.
1416pub const SYNC_FOREGROUND_REFRESH_REQUIRED = 1274;2123pub const SYNC_FOREGROUND_REFRESH_REQUIRED = 1274;
2124
1417/// This driver has been blocked from loading.2125/// This driver has been blocked from loading.
1418pub const DRIVER_BLOCKED = 1275;2126pub const DRIVER_BLOCKED = 1275;
2127
1419/// A dynamic link library (DLL) referenced a module that was neither a DLL nor the process's executable image.2128/// A dynamic link library (DLL) referenced a module that was neither a DLL nor the process's executable image.
1420pub const INVALID_IMPORT_OF_NON_DLL = 1276;2129pub const INVALID_IMPORT_OF_NON_DLL = 1276;
2130
1421/// Windows cannot open this program since it has been disabled.2131/// Windows cannot open this program since it has been disabled.
1422pub const ACCESS_DISABLED_WEBBLADE = 1277;2132pub const ACCESS_DISABLED_WEBBLADE = 1277;
2133
1423/// Windows cannot open this program because the license enforcement system has been tampered with or become corrupted.2134/// Windows cannot open this program because the license enforcement system has been tampered with or become corrupted.
1424pub const ACCESS_DISABLED_WEBBLADE_TAMPER = 1278;2135pub const ACCESS_DISABLED_WEBBLADE_TAMPER = 1278;
2136
1425/// A transaction recover failed.2137/// A transaction recover failed.
1426pub const RECOVERY_FAILURE = 1279;2138pub const RECOVERY_FAILURE = 1279;
2139
1427/// The current thread has already been converted to a fiber.2140/// The current thread has already been converted to a fiber.
1428pub const ALREADY_FIBER = 1280;2141pub const ALREADY_FIBER = 1280;
2142
1429/// The current thread has already been converted from a fiber.2143/// The current thread has already been converted from a fiber.
1430pub const ALREADY_THREAD = 1281;2144pub const ALREADY_THREAD = 1281;
2145
1431/// The system detected an overrun of a stack-based buffer in this application. This overrun could potentially allow a malicious user to gain control of this application.2146/// The system detected an overrun of a stack-based buffer in this application. This overrun could potentially allow a malicious user to gain control of this application.
1432pub const STACK_BUFFER_OVERRUN = 1282;2147pub const STACK_BUFFER_OVERRUN = 1282;
2148
1433/// Data present in one of the parameters is more than the function can operate on.2149/// Data present in one of the parameters is more than the function can operate on.
1434pub const PARAMETER_QUOTA_EXCEEDED = 1283;2150pub const PARAMETER_QUOTA_EXCEEDED = 1283;
2151
1435/// An attempt to do an operation on a debug object failed because the object is in the process of being deleted.2152/// An attempt to do an operation on a debug object failed because the object is in the process of being deleted.
1436pub const DEBUGGER_INACTIVE = 1284;2153pub const DEBUGGER_INACTIVE = 1284;
2154
1437/// An attempt to delay-load a .dll or get a function address in a delay-loaded .dll failed.2155/// An attempt to delay-load a .dll or get a function address in a delay-loaded .dll failed.
1438pub const DELAY_LOAD_FAILED = 1285;2156pub const DELAY_LOAD_FAILED = 1285;
2157
1439/// %1 is a 16-bit application. You do not have permissions to execute 16-bit applications. Check your permissions with your system administrator.2158/// %1 is a 16-bit application. You do not have permissions to execute 16-bit applications. Check your permissions with your system administrator.
1440pub const VDM_DISALLOWED = 1286;2159pub const VDM_DISALLOWED = 1286;
2160
1441/// Insufficient information exists to identify the cause of failure.2161/// Insufficient information exists to identify the cause of failure.
1442pub const UNIDENTIFIED_ERROR = 1287;2162pub const UNIDENTIFIED_ERROR = 1287;
2163
1443/// The parameter passed to a C runtime function is incorrect.2164/// The parameter passed to a C runtime function is incorrect.
1444pub const INVALID_CRUNTIME_PARAMETER = 1288;2165pub const INVALID_CRUNTIME_PARAMETER = 1288;
2166
1445/// The operation occurred beyond the valid data length of the file.2167/// The operation occurred beyond the valid data length of the file.
1446pub const BEYOND_VDL = 1289;2168pub const BEYOND_VDL = 1289;
2169
1447/// The service start failed since one or more services in the same process have an incompatible service SID type setting. A service with restricted service SID type can only coexist in the same process with other services with a restricted SID type. If the service SID type for this service was just configured, the hosting process must be restarted in order to start this service.2170/// The service start failed since one or more services in the same process have an incompatible service SID type setting. A service with restricted service SID type can only coexist in the same process with other services with a restricted SID type. If the service SID type for this service was just configured, the hosting process must be restarted in order to start this service.
1448/// On Windows Server 2003 and Windows XP, an unrestricted service cannot coexist in the same process with other services. The service with the unrestricted service SID type must be moved to an owned process in order to start this service.2171/// On Windows Server 2003 and Windows XP, an unrestricted service cannot coexist in the same process with other services. The service with the unrestricted service SID type must be moved to an owned process in order to start this service.
1449pub const INCOMPATIBLE_SERVICE_SID_TYPE = 1290;2172pub const INCOMPATIBLE_SERVICE_SID_TYPE = 1290;
2173
1450/// The process hosting the driver for this device has been terminated.2174/// The process hosting the driver for this device has been terminated.
1451pub const DRIVER_PROCESS_TERMINATED = 1291;2175pub const DRIVER_PROCESS_TERMINATED = 1291;
2176
1452/// An operation attempted to exceed an implementation-defined limit.2177/// An operation attempted to exceed an implementation-defined limit.
1453pub const IMPLEMENTATION_LIMIT = 1292;2178pub const IMPLEMENTATION_LIMIT = 1292;
2179
1454/// Either the target process, or the target thread's containing process, is a protected process.2180/// Either the target process, or the target thread's containing process, is a protected process.
1455pub const PROCESS_IS_PROTECTED = 1293;2181pub const PROCESS_IS_PROTECTED = 1293;
2182
1456/// The service notification client is lagging too far behind the current state of services in the machine.2183/// The service notification client is lagging too far behind the current state of services in the machine.
1457pub const SERVICE_NOTIFY_CLIENT_LAGGING = 1294;2184pub const SERVICE_NOTIFY_CLIENT_LAGGING = 1294;
2185
1458/// The requested file operation failed because the storage quota was exceeded. To free up disk space, move files to a different location or delete unnecessary files. For more information, contact your system administrator.2186/// The requested file operation failed because the storage quota was exceeded. To free up disk space, move files to a different location or delete unnecessary files. For more information, contact your system administrator.
1459pub const DISK_QUOTA_EXCEEDED = 1295;2187pub const DISK_QUOTA_EXCEEDED = 1295;
2188
1460/// The requested file operation failed because the storage policy blocks that type of file. For more information, contact your system administrator.2189/// The requested file operation failed because the storage policy blocks that type of file. For more information, contact your system administrator.
1461pub const CONTENT_BLOCKED = 1296;2190pub const CONTENT_BLOCKED = 1296;
2191
1462/// A privilege that the service requires to function properly does not exist in the service account configuration. You may use the Services Microsoft Management Console (MMC) snap-in (services.msc) and the Local Security Settings MMC snap-in (secpol.msc) to view the service configuration and the account configuration.2192/// A privilege that the service requires to function properly does not exist in the service account configuration. You may use the Services Microsoft Management Console (MMC) snap-in (services.msc) and the Local Security Settings MMC snap-in (secpol.msc) to view the service configuration and the account configuration.
1463pub const INCOMPATIBLE_SERVICE_PRIVILEGE = 1297;2193pub const INCOMPATIBLE_SERVICE_PRIVILEGE = 1297;
2194
1464/// A thread involved in this operation appears to be unresponsive.2195/// A thread involved in this operation appears to be unresponsive.
1465pub const APP_HANG = 1298;2196pub const APP_HANG = 1298;
2197
1466/// Indicates a particular Security ID may not be assigned as the label of an object.2198/// Indicates a particular Security ID may not be assigned as the label of an object.
1467pub const INVALID_LABEL = 1299;2199pub const INVALID_LABEL = 1299;
2200
1468/// Not all privileges or groups referenced are assigned to the caller.2201/// Not all privileges or groups referenced are assigned to the caller.
1469pub const NOT_ALL_ASSIGNED = 1300;2202pub const NOT_ALL_ASSIGNED = 1300;
2203
1470/// Some mapping between account names and security IDs was not done.2204/// Some mapping between account names and security IDs was not done.
1471pub const SOME_NOT_MAPPED = 1301;2205pub const SOME_NOT_MAPPED = 1301;
2206
1472/// No system quota limits are specifically set for this account.2207/// No system quota limits are specifically set for this account.
1473pub const NO_QUOTAS_FOR_ACCOUNT = 1302;2208pub const NO_QUOTAS_FOR_ACCOUNT = 1302;
2209
1474/// No encryption key is available. A well-known encryption key was returned.2210/// No encryption key is available. A well-known encryption key was returned.
1475pub const LOCAL_USER_SESSION_KEY = 1303;2211pub const LOCAL_USER_SESSION_KEY = 1303;
2212
1476/// The password is too complex to be converted to a LAN Manager password. The LAN Manager password returned is a NULL string.2213/// The password is too complex to be converted to a LAN Manager password. The LAN Manager password returned is a NULL string.
1477pub const NULL_LM_PASSWORD = 1304;2214pub const NULL_LM_PASSWORD = 1304;
2215
1478/// The revision level is unknown.2216/// The revision level is unknown.
1479pub const UNKNOWN_REVISION = 1305;2217pub const UNKNOWN_REVISION = 1305;
2218
1480/// Indicates two revision levels are incompatible.2219/// Indicates two revision levels are incompatible.
1481pub const REVISION_MISMATCH = 1306;2220pub const REVISION_MISMATCH = 1306;
2221
1482/// This security ID may not be assigned as the owner of this object.2222/// This security ID may not be assigned as the owner of this object.
1483pub const INVALID_OWNER = 1307;2223pub const INVALID_OWNER = 1307;
2224
1484/// This security ID may not be assigned as the primary group of an object.2225/// This security ID may not be assigned as the primary group of an object.
1485pub const INVALID_PRIMARY_GROUP = 1308;2226pub const INVALID_PRIMARY_GROUP = 1308;
2227
1486/// An attempt has been made to operate on an impersonation token by a thread that is not currently impersonating a client.2228/// An attempt has been made to operate on an impersonation token by a thread that is not currently impersonating a client.
1487pub const NO_IMPERSONATION_TOKEN = 1309;2229pub const NO_IMPERSONATION_TOKEN = 1309;
2230
1488/// The group may not be disabled.2231/// The group may not be disabled.
1489pub const CANT_DISABLE_MANDATORY = 1310;2232pub const CANT_DISABLE_MANDATORY = 1310;
2233
1490/// There are currently no logon servers available to service the logon request.2234/// There are currently no logon servers available to service the logon request.
1491pub const NO_LOGON_SERVERS = 1311;2235pub const NO_LOGON_SERVERS = 1311;
2236
1492/// A specified logon session does not exist. It may already have been terminated.2237/// A specified logon session does not exist. It may already have been terminated.
1493pub const NO_SUCH_LOGON_SESSION = 1312;2238pub const NO_SUCH_LOGON_SESSION = 1312;
2239
1494/// A specified privilege does not exist.2240/// A specified privilege does not exist.
1495pub const NO_SUCH_PRIVILEGE = 1313;2241pub const NO_SUCH_PRIVILEGE = 1313;
2242
1496/// A required privilege is not held by the client.2243/// A required privilege is not held by the client.
1497pub const PRIVILEGE_NOT_HELD = 1314;2244pub const PRIVILEGE_NOT_HELD = 1314;
2245
1498/// The name provided is not a properly formed account name.2246/// The name provided is not a properly formed account name.
1499pub const INVALID_ACCOUNT_NAME = 1315;2247pub const INVALID_ACCOUNT_NAME = 1315;
2248
1500/// The specified account already exists.2249/// The specified account already exists.
1501pub const USER_EXISTS = 1316;2250pub const USER_EXISTS = 1316;
2251
1502/// The specified account does not exist.2252/// The specified account does not exist.
1503pub const NO_SUCH_USER = 1317;2253pub const NO_SUCH_USER = 1317;
2254
1504/// The specified group already exists.2255/// The specified group already exists.
1505pub const GROUP_EXISTS = 1318;2256pub const GROUP_EXISTS = 1318;
2257
1506/// The specified group does not exist.2258/// The specified group does not exist.
1507pub const NO_SUCH_GROUP = 1319;2259pub const NO_SUCH_GROUP = 1319;
2260
1508/// Either the specified user account is already a member of the specified group, or the specified group cannot be deleted because it contains a member.2261/// Either the specified user account is already a member of the specified group, or the specified group cannot be deleted because it contains a member.
1509pub const MEMBER_IN_GROUP = 1320;2262pub const MEMBER_IN_GROUP = 1320;
2263
1510/// The specified user account is not a member of the specified group account.2264/// The specified user account is not a member of the specified group account.
1511pub const MEMBER_NOT_IN_GROUP = 1321;2265pub const MEMBER_NOT_IN_GROUP = 1321;
2266
1512/// This operation is disallowed as it could result in an administration account being disabled, deleted or unable to log on.2267/// This operation is disallowed as it could result in an administration account being disabled, deleted or unable to log on.
1513pub const LAST_ADMIN = 1322;2268pub const LAST_ADMIN = 1322;
2269
1514/// Unable to update the password. The value provided as the current password is incorrect.2270/// Unable to update the password. The value provided as the current password is incorrect.
1515pub const WRONG_PASSWORD = 1323;2271pub const WRONG_PASSWORD = 1323;
2272
1516/// Unable to update the password. The value provided for the new password contains values that are not allowed in passwords.2273/// Unable to update the password. The value provided for the new password contains values that are not allowed in passwords.
1517pub const ILL_FORMED_PASSWORD = 1324;2274pub const ILL_FORMED_PASSWORD = 1324;
2275
1518/// Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain.2276/// Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain.
1519pub const PASSWORD_RESTRICTION = 1325;2277pub const PASSWORD_RESTRICTION = 1325;
2278
1520/// The user name or password is incorrect.2279/// The user name or password is incorrect.
1521pub const LOGON_FAILURE = 1326;2280pub const LOGON_FAILURE = 1326;
2281
1522/// Account restrictions are preventing this user from signing in. For example: blank passwords aren't allowed, sign-in times are limited, or a policy restriction has been enforced.2282/// Account restrictions are preventing this user from signing in. For example: blank passwords aren't allowed, sign-in times are limited, or a policy restriction has been enforced.
1523pub const ACCOUNT_RESTRICTION = 1327;2283pub const ACCOUNT_RESTRICTION = 1327;
2284
1524/// Your account has time restrictions that keep you from signing in right now.2285/// Your account has time restrictions that keep you from signing in right now.
1525pub const INVALID_LOGON_HOURS = 1328;2286pub const INVALID_LOGON_HOURS = 1328;
2287
1526/// This user isn't allowed to sign in to this computer.2288/// This user isn't allowed to sign in to this computer.
1527pub const INVALID_WORKSTATION = 1329;2289pub const INVALID_WORKSTATION = 1329;
2290
1528/// The password for this account has expired.2291/// The password for this account has expired.
1529pub const PASSWORD_EXPIRED = 1330;2292pub const PASSWORD_EXPIRED = 1330;
2293
1530/// This user can't sign in because this account is currently disabled.2294/// This user can't sign in because this account is currently disabled.
1531pub const ACCOUNT_DISABLED = 1331;2295pub const ACCOUNT_DISABLED = 1331;
2296
1532/// No mapping between account names and security IDs was done.2297/// No mapping between account names and security IDs was done.
1533pub const NONE_MAPPED = 1332;2298pub const NONE_MAPPED = 1332;
2299
1534/// Too many local user identifiers (LUIDs) were requested at one time.2300/// Too many local user identifiers (LUIDs) were requested at one time.
1535pub const TOO_MANY_LUIDS_REQUESTED = 1333;2301pub const TOO_MANY_LUIDS_REQUESTED = 1333;
2302
1536/// No more local user identifiers (LUIDs) are available.2303/// No more local user identifiers (LUIDs) are available.
1537pub const LUIDS_EXHAUSTED = 1334;2304pub const LUIDS_EXHAUSTED = 1334;
2305
1538/// The subauthority part of a security ID is invalid for this particular use.2306/// The subauthority part of a security ID is invalid for this particular use.
1539pub const INVALID_SUB_AUTHORITY = 1335;2307pub const INVALID_SUB_AUTHORITY = 1335;
2308
1540/// The access control list (ACL) structure is invalid.2309/// The access control list (ACL) structure is invalid.
1541pub const INVALID_ACL = 1336;2310pub const INVALID_ACL = 1336;
2311
1542/// The security ID structure is invalid.2312/// The security ID structure is invalid.
1543pub const INVALID_SID = 1337;2313pub const INVALID_SID = 1337;
2314
1544/// The security descriptor structure is invalid.2315/// The security descriptor structure is invalid.
1545pub const INVALID_SECURITY_DESCR = 1338;2316pub const INVALID_SECURITY_DESCR = 1338;
2317
1546/// The inherited access control list (ACL) or access control entry (ACE) could not be built.2318/// The inherited access control list (ACL) or access control entry (ACE) could not be built.
1547pub const BAD_INHERITANCE_ACL = 1340;2319pub const BAD_INHERITANCE_ACL = 1340;
2320
1548/// The server is currently disabled.2321/// The server is currently disabled.
1549pub const SERVER_DISABLED = 1341;2322pub const SERVER_DISABLED = 1341;
2323
1550/// The server is currently enabled.2324/// The server is currently enabled.
1551pub const SERVER_NOT_DISABLED = 1342;2325pub const SERVER_NOT_DISABLED = 1342;
2326
1552/// The value provided was an invalid value for an identifier authority.2327/// The value provided was an invalid value for an identifier authority.
1553pub const INVALID_ID_AUTHORITY = 1343;2328pub const INVALID_ID_AUTHORITY = 1343;
2329
1554/// No more memory is available for security information updates.2330/// No more memory is available for security information updates.
1555pub const ALLOTTED_SPACE_EXCEEDED = 1344;2331pub const ALLOTTED_SPACE_EXCEEDED = 1344;
2332
1556/// The specified attributes are invalid, or incompatible with the attributes for the group as a whole.2333/// The specified attributes are invalid, or incompatible with the attributes for the group as a whole.
1557pub const INVALID_GROUP_ATTRIBUTES = 1345;2334pub const INVALID_GROUP_ATTRIBUTES = 1345;
2335
1558/// Either a required impersonation level was not provided, or the provided impersonation level is invalid.2336/// Either a required impersonation level was not provided, or the provided impersonation level is invalid.
1559pub const BAD_IMPERSONATION_LEVEL = 1346;2337pub const BAD_IMPERSONATION_LEVEL = 1346;
2338
1560/// Cannot open an anonymous level security token.2339/// Cannot open an anonymous level security token.
1561pub const CANT_OPEN_ANONYMOUS = 1347;2340pub const CANT_OPEN_ANONYMOUS = 1347;
2341
1562/// The validation information class requested was invalid.2342/// The validation information class requested was invalid.
1563pub const BAD_VALIDATION_CLASS = 1348;2343pub const BAD_VALIDATION_CLASS = 1348;
2344
1564/// The type of the token is inappropriate for its attempted use.2345/// The type of the token is inappropriate for its attempted use.
1565pub const BAD_TOKEN_TYPE = 1349;2346pub const BAD_TOKEN_TYPE = 1349;
2347
1566/// Unable to perform a security operation on an object that has no associated security.2348/// Unable to perform a security operation on an object that has no associated security.
1567pub const NO_SECURITY_ON_OBJECT = 1350;2349pub const NO_SECURITY_ON_OBJECT = 1350;
2350
1568/// Configuration information could not be read from the domain controller, either because the machine is unavailable, or access has been denied.2351/// Configuration information could not be read from the domain controller, either because the machine is unavailable, or access has been denied.
1569pub const CANT_ACCESS_DOMAIN_INFO = 1351;2352pub const CANT_ACCESS_DOMAIN_INFO = 1351;
2353
1570/// The security account manager (SAM) or local security authority (LSA) server was in the wrong state to perform the security operation.2354/// The security account manager (SAM) or local security authority (LSA) server was in the wrong state to perform the security operation.
1571pub const INVALID_SERVER_STATE = 1352;2355pub const INVALID_SERVER_STATE = 1352;
2356
1572/// The domain was in the wrong state to perform the security operation.2357/// The domain was in the wrong state to perform the security operation.
1573pub const INVALID_DOMAIN_STATE = 1353;2358pub const INVALID_DOMAIN_STATE = 1353;
2359
1574/// This operation is only allowed for the Primary Domain Controller of the domain.2360/// This operation is only allowed for the Primary Domain Controller of the domain.
1575pub const INVALID_DOMAIN_ROLE = 1354;2361pub const INVALID_DOMAIN_ROLE = 1354;
2362
1576/// The specified domain either does not exist or could not be contacted.2363/// The specified domain either does not exist or could not be contacted.
1577pub const NO_SUCH_DOMAIN = 1355;2364pub const NO_SUCH_DOMAIN = 1355;
2365
1578/// The specified domain already exists.2366/// The specified domain already exists.
1579pub const DOMAIN_EXISTS = 1356;2367pub const DOMAIN_EXISTS = 1356;
2368
1580/// An attempt was made to exceed the limit on the number of domains per server.2369/// An attempt was made to exceed the limit on the number of domains per server.
1581pub const DOMAIN_LIMIT_EXCEEDED = 1357;2370pub const DOMAIN_LIMIT_EXCEEDED = 1357;
2371
1582/// Unable to complete the requested operation because of either a catastrophic media failure or a data structure corruption on the disk.2372/// Unable to complete the requested operation because of either a catastrophic media failure or a data structure corruption on the disk.
1583pub const INTERNAL_DB_CORRUPTION = 1358;2373pub const INTERNAL_DB_CORRUPTION = 1358;
2374
1584/// An internal error occurred.2375/// An internal error occurred.
1585pub const INTERNAL_ERROR = 1359;2376pub const INTERNAL_ERROR = 1359;
2377
1586/// Generic access types were contained in an access mask which should already be mapped to nongeneric types.2378/// Generic access types were contained in an access mask which should already be mapped to nongeneric types.
1587pub const GENERIC_NOT_MAPPED = 1360;2379pub const GENERIC_NOT_MAPPED = 1360;
2380
1588/// A security descriptor is not in the right format (absolute or self-relative).2381/// A security descriptor is not in the right format (absolute or self-relative).
1589pub const BAD_DESCRIPTOR_FORMAT = 1361;2382pub const BAD_DESCRIPTOR_FORMAT = 1361;
2383
1590/// The requested action is restricted for use by logon processes only. The calling process has not registered as a logon process.2384/// The requested action is restricted for use by logon processes only. The calling process has not registered as a logon process.
1591pub const NOT_LOGON_PROCESS = 1362;2385pub const NOT_LOGON_PROCESS = 1362;
2386
1592/// Cannot start a new logon session with an ID that is already in use.2387/// Cannot start a new logon session with an ID that is already in use.
1593pub const LOGON_SESSION_EXISTS = 1363;2388pub const LOGON_SESSION_EXISTS = 1363;
2389
1594/// A specified authentication package is unknown.2390/// A specified authentication package is unknown.
1595pub const NO_SUCH_PACKAGE = 1364;2391pub const NO_SUCH_PACKAGE = 1364;
2392
1596/// The logon session is not in a state that is consistent with the requested operation.2393/// The logon session is not in a state that is consistent with the requested operation.
1597pub const BAD_LOGON_SESSION_STATE = 1365;2394pub const BAD_LOGON_SESSION_STATE = 1365;
2395
1598/// The logon session ID is already in use.2396/// The logon session ID is already in use.
1599pub const LOGON_SESSION_COLLISION = 1366;2397pub const LOGON_SESSION_COLLISION = 1366;
2398
1600/// A logon request contained an invalid logon type value.2399/// A logon request contained an invalid logon type value.
1601pub const INVALID_LOGON_TYPE = 1367;2400pub const INVALID_LOGON_TYPE = 1367;
2401
1602/// Unable to impersonate using a named pipe until data has been read from that pipe.2402/// Unable to impersonate using a named pipe until data has been read from that pipe.
1603pub const CANNOT_IMPERSONATE = 1368;2403pub const CANNOT_IMPERSONATE = 1368;
2404
1604/// The transaction state of a registry subtree is incompatible with the requested operation.2405/// The transaction state of a registry subtree is incompatible with the requested operation.
1605pub const RXACT_INVALID_STATE = 1369;2406pub const RXACT_INVALID_STATE = 1369;
2407
1606/// An internal security database corruption has been encountered.2408/// An internal security database corruption has been encountered.
1607pub const RXACT_COMMIT_FAILURE = 1370;2409pub const RXACT_COMMIT_FAILURE = 1370;
2410
1608/// Cannot perform this operation on built-in accounts.2411/// Cannot perform this operation on built-in accounts.
1609pub const SPECIAL_ACCOUNT = 1371;2412pub const SPECIAL_ACCOUNT = 1371;
2413
1610/// Cannot perform this operation on this built-in special group.2414/// Cannot perform this operation on this built-in special group.
1611pub const SPECIAL_GROUP = 1372;2415pub const SPECIAL_GROUP = 1372;
2416
1612/// Cannot perform this operation on this built-in special user.2417/// Cannot perform this operation on this built-in special user.
1613pub const SPECIAL_USER = 1373;2418pub const SPECIAL_USER = 1373;
2419
1614/// The user cannot be removed from a group because the group is currently the user's primary group.2420/// The user cannot be removed from a group because the group is currently the user's primary group.
1615pub const MEMBERS_PRIMARY_GROUP = 1374;2421pub const MEMBERS_PRIMARY_GROUP = 1374;
2422
1616/// The token is already in use as a primary token.2423/// The token is already in use as a primary token.
1617pub const TOKEN_ALREADY_IN_USE = 1375;2424pub const TOKEN_ALREADY_IN_USE = 1375;
2425
1618/// The specified local group does not exist.2426/// The specified local group does not exist.
1619pub const NO_SUCH_ALIAS = 1376;2427pub const NO_SUCH_ALIAS = 1376;
2428
1620/// The specified account name is not a member of the group.2429/// The specified account name is not a member of the group.
1621pub const MEMBER_NOT_IN_ALIAS = 1377;2430pub const MEMBER_NOT_IN_ALIAS = 1377;
2431
1622/// The specified account name is already a member of the group.2432/// The specified account name is already a member of the group.
1623pub const MEMBER_IN_ALIAS = 1378;2433pub const MEMBER_IN_ALIAS = 1378;
2434
1624/// The specified local group already exists.2435/// The specified local group already exists.
1625pub const ALIAS_EXISTS = 1379;2436pub const ALIAS_EXISTS = 1379;
2437
1626/// Logon failure: the user has not been granted the requested logon type at this computer.2438/// Logon failure: the user has not been granted the requested logon type at this computer.
1627pub const LOGON_NOT_GRANTED = 1380;2439pub const LOGON_NOT_GRANTED = 1380;
2440
1628/// The maximum number of secrets that may be stored in a single system has been exceeded.2441/// The maximum number of secrets that may be stored in a single system has been exceeded.
1629pub const TOO_MANY_SECRETS = 1381;2442pub const TOO_MANY_SECRETS = 1381;
2443
1630/// The length of a secret exceeds the maximum length allowed.2444/// The length of a secret exceeds the maximum length allowed.
1631pub const SECRET_TOO_LONG = 1382;2445pub const SECRET_TOO_LONG = 1382;
2446
1632/// The local security authority database contains an internal inconsistency.2447/// The local security authority database contains an internal inconsistency.
1633pub const INTERNAL_DB_ERROR = 1383;2448pub const INTERNAL_DB_ERROR = 1383;
2449
1634/// During a logon attempt, the user's security context accumulated too many security IDs.2450/// During a logon attempt, the user's security context accumulated too many security IDs.
1635pub const TOO_MANY_CONTEXT_IDS = 1384;2451pub const TOO_MANY_CONTEXT_IDS = 1384;
2452
1636/// Logon failure: the user has not been granted the requested logon type at this computer.2453/// Logon failure: the user has not been granted the requested logon type at this computer.
1637pub const LOGON_TYPE_NOT_GRANTED = 1385;2454pub const LOGON_TYPE_NOT_GRANTED = 1385;
2455
1638/// A cross-encrypted password is necessary to change a user password.2456/// A cross-encrypted password is necessary to change a user password.
1639pub const NT_CROSS_ENCRYPTION_REQUIRED = 1386;2457pub const NT_CROSS_ENCRYPTION_REQUIRED = 1386;
2458
1640/// A member could not be added to or removed from the local group because the member does not exist.2459/// A member could not be added to or removed from the local group because the member does not exist.
1641pub const NO_SUCH_MEMBER = 1387;2460pub const NO_SUCH_MEMBER = 1387;
2461
1642/// A new member could not be added to a local group because the member has the wrong account type.2462/// A new member could not be added to a local group because the member has the wrong account type.
1643pub const INVALID_MEMBER = 1388;2463pub const INVALID_MEMBER = 1388;
2464
1644/// Too many security IDs have been specified.2465/// Too many security IDs have been specified.
1645pub const TOO_MANY_SIDS = 1389;2466pub const TOO_MANY_SIDS = 1389;
2467
1646/// A cross-encrypted password is necessary to change this user password.2468/// A cross-encrypted password is necessary to change this user password.
1647pub const LM_CROSS_ENCRYPTION_REQUIRED = 1390;2469pub const LM_CROSS_ENCRYPTION_REQUIRED = 1390;
2470
1648/// Indicates an ACL contains no inheritable components.2471/// Indicates an ACL contains no inheritable components.
1649pub const NO_INHERITANCE = 1391;2472pub const NO_INHERITANCE = 1391;
2473
1650/// The file or directory is corrupted and unreadable.2474/// The file or directory is corrupted and unreadable.
1651pub const FILE_CORRUPT = 1392;2475pub const FILE_CORRUPT = 1392;
2476
1652/// The disk structure is corrupted and unreadable.2477/// The disk structure is corrupted and unreadable.
1653pub const DISK_CORRUPT = 1393;2478pub const DISK_CORRUPT = 1393;
2479
1654/// There is no user session key for the specified logon session.2480/// There is no user session key for the specified logon session.
1655pub const NO_USER_SESSION_KEY = 1394;2481pub const NO_USER_SESSION_KEY = 1394;
2482
1656/// The service being accessed is licensed for a particular number of connections. No more connections can be made to the service at this time because there are already as many connections as the service can accept.2483/// The service being accessed is licensed for a particular number of connections. No more connections can be made to the service at this time because there are already as many connections as the service can accept.
1657pub const LICENSE_QUOTA_EXCEEDED = 1395;2484pub const LICENSE_QUOTA_EXCEEDED = 1395;
2485
1658/// The target account name is incorrect.2486/// The target account name is incorrect.
1659pub const WRONG_TARGET_NAME = 1396;2487pub const WRONG_TARGET_NAME = 1396;
2488
1660/// Mutual Authentication failed. The server's password is out of date at the domain controller.2489/// Mutual Authentication failed. The server's password is out of date at the domain controller.
1661pub const MUTUAL_AUTH_FAILED = 1397;2490pub const MUTUAL_AUTH_FAILED = 1397;
2491
1662/// There is a time and/or date difference between the client and server.2492/// There is a time and/or date difference between the client and server.
1663pub const TIME_SKEW = 1398;2493pub const TIME_SKEW = 1398;
2494
1664/// This operation cannot be performed on the current domain.2495/// This operation cannot be performed on the current domain.
1665pub const CURRENT_DOMAIN_NOT_ALLOWED = 1399;2496pub const CURRENT_DOMAIN_NOT_ALLOWED = 1399;
2497
1666/// Invalid window handle.2498/// Invalid window handle.
1667pub const INVALID_WINDOW_HANDLE = 1400;2499pub const INVALID_WINDOW_HANDLE = 1400;
2500
1668/// Invalid menu handle.2501/// Invalid menu handle.
1669pub const INVALID_MENU_HANDLE = 1401;2502pub const INVALID_MENU_HANDLE = 1401;
2503
1670/// Invalid cursor handle.2504/// Invalid cursor handle.
1671pub const INVALID_CURSOR_HANDLE = 1402;2505pub const INVALID_CURSOR_HANDLE = 1402;
2506
1672/// Invalid accelerator table handle.2507/// Invalid accelerator table handle.
1673pub const INVALID_ACCEL_HANDLE = 1403;2508pub const INVALID_ACCEL_HANDLE = 1403;
2509
1674/// Invalid hook handle.2510/// Invalid hook handle.
1675pub const INVALID_HOOK_HANDLE = 1404;2511pub const INVALID_HOOK_HANDLE = 1404;
2512
1676/// Invalid handle to a multiple-window position structure.2513/// Invalid handle to a multiple-window position structure.
1677pub const INVALID_DWP_HANDLE = 1405;2514pub const INVALID_DWP_HANDLE = 1405;
2515
1678/// Cannot create a top-level child window.2516/// Cannot create a top-level child window.
1679pub const TLW_WITH_WSCHILD = 1406;2517pub const TLW_WITH_WSCHILD = 1406;
2518
1680/// Cannot find window class.2519/// Cannot find window class.
1681pub const CANNOT_FIND_WND_CLASS = 1407;2520pub const CANNOT_FIND_WND_CLASS = 1407;
2521
1682/// Invalid window; it belongs to other thread.2522/// Invalid window; it belongs to other thread.
1683pub const WINDOW_OF_OTHER_THREAD = 1408;2523pub const WINDOW_OF_OTHER_THREAD = 1408;
2524
1684/// Hot key is already registered.2525/// Hot key is already registered.
1685pub const HOTKEY_ALREADY_REGISTERED = 1409;2526pub const HOTKEY_ALREADY_REGISTERED = 1409;
2527
1686/// Class already exists.2528/// Class already exists.
1687pub const CLASS_ALREADY_EXISTS = 1410;2529pub const CLASS_ALREADY_EXISTS = 1410;
2530
1688/// Class does not exist.2531/// Class does not exist.
1689pub const CLASS_DOES_NOT_EXIST = 1411;2532pub const CLASS_DOES_NOT_EXIST = 1411;
2533
1690/// Class still has open windows.2534/// Class still has open windows.
1691pub const CLASS_HAS_WINDOWS = 1412;2535pub const CLASS_HAS_WINDOWS = 1412;
2536
1692/// Invalid index.2537/// Invalid index.
1693pub const INVALID_INDEX = 1413;2538pub const INVALID_INDEX = 1413;
2539
1694/// Invalid icon handle.2540/// Invalid icon handle.
1695pub const INVALID_ICON_HANDLE = 1414;2541pub const INVALID_ICON_HANDLE = 1414;
2542
1696/// Using private DIALOG window words.2543/// Using private DIALOG window words.
1697pub const PRIVATE_DIALOG_INDEX = 1415;2544pub const PRIVATE_DIALOG_INDEX = 1415;
2545
1698/// The list box identifier was not found.2546/// The list box identifier was not found.
1699pub const LISTBOX_ID_NOT_FOUND = 1416;2547pub const LISTBOX_ID_NOT_FOUND = 1416;
2548
1700/// No wildcards were found.2549/// No wildcards were found.
1701pub const NO_WILDCARD_CHARACTERS = 1417;2550pub const NO_WILDCARD_CHARACTERS = 1417;
2551
1702/// Thread does not have a clipboard open.2552/// Thread does not have a clipboard open.
1703pub const CLIPBOARD_NOT_OPEN = 1418;2553pub const CLIPBOARD_NOT_OPEN = 1418;
2554
1704/// Hot key is not registered.2555/// Hot key is not registered.
1705pub const HOTKEY_NOT_REGISTERED = 1419;2556pub const HOTKEY_NOT_REGISTERED = 1419;
2557
1706/// The window is not a valid dialog window.2558/// The window is not a valid dialog window.
1707pub const WINDOW_NOT_DIALOG = 1420;2559pub const WINDOW_NOT_DIALOG = 1420;
2560
1708/// Control ID not found.2561/// Control ID not found.
1709pub const CONTROL_ID_NOT_FOUND = 1421;2562pub const CONTROL_ID_NOT_FOUND = 1421;
2563
1710/// Invalid message for a combo box because it does not have an edit control.2564/// Invalid message for a combo box because it does not have an edit control.
1711pub const INVALID_COMBOBOX_MESSAGE = 1422;2565pub const INVALID_COMBOBOX_MESSAGE = 1422;
2566
1712/// The window is not a combo box.2567/// The window is not a combo box.
1713pub const WINDOW_NOT_COMBOBOX = 1423;2568pub const WINDOW_NOT_COMBOBOX = 1423;
2569
1714/// Height must be less than 256.2570/// Height must be less than 256.
1715pub const INVALID_EDIT_HEIGHT = 1424;2571pub const INVALID_EDIT_HEIGHT = 1424;
2572
1716/// Invalid device context (DC) handle.2573/// Invalid device context (DC) handle.
1717pub const DC_NOT_FOUND = 1425;2574pub const DC_NOT_FOUND = 1425;
2575
1718/// Invalid hook procedure type.2576/// Invalid hook procedure type.
1719pub const INVALID_HOOK_FILTER = 1426;2577pub const INVALID_HOOK_FILTER = 1426;
2578
1720/// Invalid hook procedure.2579/// Invalid hook procedure.
1721pub const INVALID_FILTER_PROC = 1427;2580pub const INVALID_FILTER_PROC = 1427;
2581
1722/// Cannot set nonlocal hook without a module handle.2582/// Cannot set nonlocal hook without a module handle.
1723pub const HOOK_NEEDS_HMOD = 1428;2583pub const HOOK_NEEDS_HMOD = 1428;
2584
1724/// This hook procedure can only be set globally.2585/// This hook procedure can only be set globally.
1725pub const GLOBAL_ONLY_HOOK = 1429;2586pub const GLOBAL_ONLY_HOOK = 1429;
2587
1726/// The journal hook procedure is already installed.2588/// The journal hook procedure is already installed.
1727pub const JOURNAL_HOOK_SET = 1430;2589pub const JOURNAL_HOOK_SET = 1430;
2590
1728/// The hook procedure is not installed.2591/// The hook procedure is not installed.
1729pub const HOOK_NOT_INSTALLED = 1431;2592pub const HOOK_NOT_INSTALLED = 1431;
2593
1730/// Invalid message for single-selection list box.2594/// Invalid message for single-selection list box.
1731pub const INVALID_LB_MESSAGE = 1432;2595pub const INVALID_LB_MESSAGE = 1432;
2596
1732/// LB_SETCOUNT sent to non-lazy list box.2597/// LB_SETCOUNT sent to non-lazy list box.
1733pub const SETCOUNT_ON_BAD_LB = 1433;2598pub const SETCOUNT_ON_BAD_LB = 1433;
2599
1734/// This list box does not support tab stops.2600/// This list box does not support tab stops.
1735pub const LB_WITHOUT_TABSTOPS = 1434;2601pub const LB_WITHOUT_TABSTOPS = 1434;
2602
1736/// Cannot destroy object created by another thread.2603/// Cannot destroy object created by another thread.
1737pub const DESTROY_OBJECT_OF_OTHER_THREAD = 1435;2604pub const DESTROY_OBJECT_OF_OTHER_THREAD = 1435;
2605
1738/// Child windows cannot have menus.2606/// Child windows cannot have menus.
1739pub const CHILD_WINDOW_MENU = 1436;2607pub const CHILD_WINDOW_MENU = 1436;
2608
1740/// The window does not have a system menu.2609/// The window does not have a system menu.
1741pub const NO_SYSTEM_MENU = 1437;2610pub const NO_SYSTEM_MENU = 1437;
2611
1742/// Invalid message box style.2612/// Invalid message box style.
1743pub const INVALID_MSGBOX_STYLE = 1438;2613pub const INVALID_MSGBOX_STYLE = 1438;
2614
1744/// Invalid system-wide (SPI_*) parameter.2615/// Invalid system-wide (SPI_*) parameter.
1745pub const INVALID_SPI_VALUE = 1439;2616pub const INVALID_SPI_VALUE = 1439;
2617
1746/// Screen already locked.2618/// Screen already locked.
1747pub const SCREEN_ALREADY_LOCKED = 1440;2619pub const SCREEN_ALREADY_LOCKED = 1440;
2620
1748/// All handles to windows in a multiple-window position structure must have the same parent.2621/// All handles to windows in a multiple-window position structure must have the same parent.
1749pub const HWNDS_HAVE_DIFF_PARENT = 1441;2622pub const HWNDS_HAVE_DIFF_PARENT = 1441;
2623
1750/// The window is not a child window.2624/// The window is not a child window.
1751pub const NOT_CHILD_WINDOW = 1442;2625pub const NOT_CHILD_WINDOW = 1442;
2626
1752/// Invalid GW_* command.2627/// Invalid GW_* command.
1753pub const INVALID_GW_COMMAND = 1443;2628pub const INVALID_GW_COMMAND = 1443;
2629
1754/// Invalid thread identifier.2630/// Invalid thread identifier.
1755pub const INVALID_THREAD_ID = 1444;2631pub const INVALID_THREAD_ID = 1444;
2632
1756/// Cannot process a message from a window that is not a multiple document interface (MDI) window.2633/// Cannot process a message from a window that is not a multiple document interface (MDI) window.
1757pub const NON_MDICHILD_WINDOW = 1445;2634pub const NON_MDICHILD_WINDOW = 1445;
2635
1758/// Popup menu already active.2636/// Popup menu already active.
1759pub const POPUP_ALREADY_ACTIVE = 1446;2637pub const POPUP_ALREADY_ACTIVE = 1446;
2638
1760/// The window does not have scroll bars.2639/// The window does not have scroll bars.
1761pub const NO_SCROLLBARS = 1447;2640pub const NO_SCROLLBARS = 1447;
2641
1762/// Scroll bar range cannot be greater than MAXLONG.2642/// Scroll bar range cannot be greater than MAXLONG.
1763pub const INVALID_SCROLLBAR_RANGE = 1448;2643pub const INVALID_SCROLLBAR_RANGE = 1448;
2644
1764/// Cannot show or remove the window in the way specified.2645/// Cannot show or remove the window in the way specified.
1765pub const INVALID_SHOWWIN_COMMAND = 1449;2646pub const INVALID_SHOWWIN_COMMAND = 1449;
2647
1766/// Insufficient system resources exist to complete the requested service.2648/// Insufficient system resources exist to complete the requested service.
1767pub const NO_SYSTEM_RESOURCES = 1450;2649pub const NO_SYSTEM_RESOURCES = 1450;
2650
1768/// Insufficient system resources exist to complete the requested service.2651/// Insufficient system resources exist to complete the requested service.
1769pub const NONPAGED_SYSTEM_RESOURCES = 1451;2652pub const NONPAGED_SYSTEM_RESOURCES = 1451;
2653
1770/// Insufficient system resources exist to complete the requested service.2654/// Insufficient system resources exist to complete the requested service.
1771pub const PAGED_SYSTEM_RESOURCES = 1452;2655pub const PAGED_SYSTEM_RESOURCES = 1452;
2656
1772/// Insufficient quota to complete the requested service.2657/// Insufficient quota to complete the requested service.
1773pub const WORKING_SET_QUOTA = 1453;2658pub const WORKING_SET_QUOTA = 1453;
2659
1774/// Insufficient quota to complete the requested service.2660/// Insufficient quota to complete the requested service.
1775pub const PAGEFILE_QUOTA = 1454;2661pub const PAGEFILE_QUOTA = 1454;
2662
1776/// The paging file is too small for this operation to complete.2663/// The paging file is too small for this operation to complete.
1777pub const COMMITMENT_LIMIT = 1455;2664pub const COMMITMENT_LIMIT = 1455;
2665
1778/// A menu item was not found.2666/// A menu item was not found.
1779pub const MENU_ITEM_NOT_FOUND = 1456;2667pub const MENU_ITEM_NOT_FOUND = 1456;
2668
1780/// Invalid keyboard layout handle.2669/// Invalid keyboard layout handle.
1781pub const INVALID_KEYBOARD_HANDLE = 1457;2670pub const INVALID_KEYBOARD_HANDLE = 1457;
2671
1782/// Hook type not allowed.2672/// Hook type not allowed.
1783pub const HOOK_TYPE_NOT_ALLOWED = 1458;2673pub const HOOK_TYPE_NOT_ALLOWED = 1458;
2674
1784/// This operation requires an interactive window station.2675/// This operation requires an interactive window station.
1785pub const REQUIRES_INTERACTIVE_WINDOWSTATION = 1459;2676pub const REQUIRES_INTERACTIVE_WINDOWSTATION = 1459;
2677
1786/// This operation returned because the timeout period expired.2678/// This operation returned because the timeout period expired.
1787pub const TIMEOUT = 1460;2679pub const TIMEOUT = 1460;
2680
1788/// Invalid monitor handle.2681/// Invalid monitor handle.
1789pub const INVALID_MONITOR_HANDLE = 1461;2682pub const INVALID_MONITOR_HANDLE = 1461;
2683
1790/// Incorrect size argument.2684/// Incorrect size argument.
1791pub const INCORRECT_SIZE = 1462;2685pub const INCORRECT_SIZE = 1462;
2686
1792/// The symbolic link cannot be followed because its type is disabled.2687/// The symbolic link cannot be followed because its type is disabled.
1793pub const SYMLINK_CLASS_DISABLED = 1463;2688pub const SYMLINK_CLASS_DISABLED = 1463;
2689
1794/// This application does not support the current operation on symbolic links.2690/// This application does not support the current operation on symbolic links.
1795pub const SYMLINK_NOT_SUPPORTED = 1464;2691pub const SYMLINK_NOT_SUPPORTED = 1464;
2692
1796/// Windows was unable to parse the requested XML data.2693/// Windows was unable to parse the requested XML data.
1797pub const XML_PARSE_ERROR = 1465;2694pub const XML_PARSE_ERROR = 1465;
2695
1798/// An error was encountered while processing an XML digital signature.2696/// An error was encountered while processing an XML digital signature.
1799pub const XMLDSIG_ERROR = 1466;2697pub const XMLDSIG_ERROR = 1466;
2698
1800/// This application must be restarted.2699/// This application must be restarted.
1801pub const RESTART_APPLICATION = 1467;2700pub const RESTART_APPLICATION = 1467;
2701
1802/// The caller made the connection request in the wrong routing compartment.2702/// The caller made the connection request in the wrong routing compartment.
1803pub const WRONG_COMPARTMENT = 1468;2703pub const WRONG_COMPARTMENT = 1468;
2704
1804/// There was an AuthIP failure when attempting to connect to the remote host.2705/// There was an AuthIP failure when attempting to connect to the remote host.
1805pub const AUTHIP_FAILURE = 1469;2706pub const AUTHIP_FAILURE = 1469;
2707
1806/// Insufficient NVRAM resources exist to complete the requested service. A reboot might be required.2708/// Insufficient NVRAM resources exist to complete the requested service. A reboot might be required.
1807pub const NO_NVRAM_RESOURCES = 1470;2709pub const NO_NVRAM_RESOURCES = 1470;
2710
1808/// Unable to finish the requested operation because the specified process is not a GUI process.2711/// Unable to finish the requested operation because the specified process is not a GUI process.
1809pub const NOT_GUI_PROCESS = 1471;2712pub const NOT_GUI_PROCESS = 1471;
2713
1810/// The event log file is corrupted.2714/// The event log file is corrupted.
1811pub const EVENTLOG_FILE_CORRUPT = 1500;2715pub const EVENTLOG_FILE_CORRUPT = 1500;
2716
1812/// No event log file could be opened, so the event logging service did not start.2717/// No event log file could be opened, so the event logging service did not start.
1813pub const EVENTLOG_CANT_START = 1501;2718pub const EVENTLOG_CANT_START = 1501;
2719
1814/// The event log file is full.2720/// The event log file is full.
1815pub const LOG_FILE_FULL = 1502;2721pub const LOG_FILE_FULL = 1502;
2722
1816/// The event log file has changed between read operations.2723/// The event log file has changed between read operations.
1817pub const EVENTLOG_FILE_CHANGED = 1503;2724pub const EVENTLOG_FILE_CHANGED = 1503;
2725
1818/// The specified task name is invalid.2726/// The specified task name is invalid.
1819pub const INVALID_TASK_NAME = 1550;2727pub const INVALID_TASK_NAME = 1550;
2728
1820/// The specified task index is invalid.2729/// The specified task index is invalid.
1821pub const INVALID_TASK_INDEX = 1551;2730pub const INVALID_TASK_INDEX = 1551;
2731
1822/// The specified thread is already joining a task.2732/// The specified thread is already joining a task.
1823pub const THREAD_ALREADY_IN_TASK = 1552;2733pub const THREAD_ALREADY_IN_TASK = 1552;
2734
1824/// The Windows Installer Service could not be accessed. This can occur if the Windows Installer is not correctly installed. Contact your support personnel for assistance.2735/// The Windows Installer Service could not be accessed. This can occur if the Windows Installer is not correctly installed. Contact your support personnel for assistance.
1825pub const INSTALL_SERVICE_FAILURE = 1601;2736pub const INSTALL_SERVICE_FAILURE = 1601;
2737
1826/// User cancelled installation.2738/// User cancelled installation.
1827pub const INSTALL_USEREXIT = 1602;2739pub const INSTALL_USEREXIT = 1602;
2740
1828/// Fatal error during installation.2741/// Fatal error during installation.
1829pub const INSTALL_FAILURE = 1603;2742pub const INSTALL_FAILURE = 1603;
2743
1830/// Installation suspended, incomplete.2744/// Installation suspended, incomplete.
1831pub const INSTALL_SUSPEND = 1604;2745pub const INSTALL_SUSPEND = 1604;
2746
1832/// This action is only valid for products that are currently installed.2747/// This action is only valid for products that are currently installed.
1833pub const UNKNOWN_PRODUCT = 1605;2748pub const UNKNOWN_PRODUCT = 1605;
2749
1834/// Feature ID not registered.2750/// Feature ID not registered.
1835pub const UNKNOWN_FEATURE = 1606;2751pub const UNKNOWN_FEATURE = 1606;
2752
1836/// Component ID not registered.2753/// Component ID not registered.
1837pub const UNKNOWN_COMPONENT = 1607;2754pub const UNKNOWN_COMPONENT = 1607;
2755
1838/// Unknown property.2756/// Unknown property.
1839pub const UNKNOWN_PROPERTY = 1608;2757pub const UNKNOWN_PROPERTY = 1608;
2758
1840/// Handle is in an invalid state.2759/// Handle is in an invalid state.
1841pub const INVALID_HANDLE_STATE = 1609;2760pub const INVALID_HANDLE_STATE = 1609;
2761
1842/// The configuration data for this product is corrupt. Contact your support personnel.2762/// The configuration data for this product is corrupt. Contact your support personnel.
1843pub const BAD_CONFIGURATION = 1610;2763pub const BAD_CONFIGURATION = 1610;
2764
1844/// Component qualifier not present.2765/// Component qualifier not present.
1845pub const INDEX_ABSENT = 1611;2766pub const INDEX_ABSENT = 1611;
2767
1846/// The installation source for this product is not available. Verify that the source exists and that you can access it.2768/// The installation source for this product is not available. Verify that the source exists and that you can access it.
1847pub const INSTALL_SOURCE_ABSENT = 1612;2769pub const INSTALL_SOURCE_ABSENT = 1612;
2770
1848/// This installation package cannot be installed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.2771/// This installation package cannot be installed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.
1849pub const INSTALL_PACKAGE_VERSION = 1613;2772pub const INSTALL_PACKAGE_VERSION = 1613;
2773
1850/// Product is uninstalled.2774/// Product is uninstalled.
1851pub const PRODUCT_UNINSTALLED = 1614;2775pub const PRODUCT_UNINSTALLED = 1614;
2776
1852/// SQL query syntax invalid or unsupported.2777/// SQL query syntax invalid or unsupported.
1853pub const BAD_QUERY_SYNTAX = 1615;2778pub const BAD_QUERY_SYNTAX = 1615;
2779
1854/// Record field does not exist.2780/// Record field does not exist.
1855pub const INVALID_FIELD = 1616;2781pub const INVALID_FIELD = 1616;
2782
1856/// The device has been removed.2783/// The device has been removed.
1857pub const DEVICE_REMOVED = 1617;2784pub const DEVICE_REMOVED = 1617;
2785
1858/// Another installation is already in progress. Complete that installation before proceeding with this install.2786/// Another installation is already in progress. Complete that installation before proceeding with this install.
1859pub const INSTALL_ALREADY_RUNNING = 1618;2787pub const INSTALL_ALREADY_RUNNING = 1618;
2788
1860/// This installation package could not be opened. Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package.2789/// This installation package could not be opened. Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package.
1861pub const INSTALL_PACKAGE_OPEN_FAILED = 1619;2790pub const INSTALL_PACKAGE_OPEN_FAILED = 1619;
2791
1862/// This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package.2792/// This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package.
1863pub const INSTALL_PACKAGE_INVALID = 1620;2793pub const INSTALL_PACKAGE_INVALID = 1620;
2794
1864/// There was an error starting the Windows Installer service user interface. Contact your support personnel.2795/// There was an error starting the Windows Installer service user interface. Contact your support personnel.
1865pub const INSTALL_UI_FAILURE = 1621;2796pub const INSTALL_UI_FAILURE = 1621;
2797
1866/// Error opening installation log file. Verify that the specified log file location exists and that you can write to it.2798/// Error opening installation log file. Verify that the specified log file location exists and that you can write to it.
1867pub const INSTALL_LOG_FAILURE = 1622;2799pub const INSTALL_LOG_FAILURE = 1622;
2800
1868/// The language of this installation package is not supported by your system.2801/// The language of this installation package is not supported by your system.
1869pub const INSTALL_LANGUAGE_UNSUPPORTED = 1623;2802pub const INSTALL_LANGUAGE_UNSUPPORTED = 1623;
2803
1870/// Error applying transforms. Verify that the specified transform paths are valid.2804/// Error applying transforms. Verify that the specified transform paths are valid.
1871pub const INSTALL_TRANSFORM_FAILURE = 1624;2805pub const INSTALL_TRANSFORM_FAILURE = 1624;
2806
1872/// This installation is forbidden by system policy. Contact your system administrator.2807/// This installation is forbidden by system policy. Contact your system administrator.
1873pub const INSTALL_PACKAGE_REJECTED = 1625;2808pub const INSTALL_PACKAGE_REJECTED = 1625;
2809
1874/// Function could not be executed.2810/// Function could not be executed.
1875pub const FUNCTION_NOT_CALLED = 1626;2811pub const FUNCTION_NOT_CALLED = 1626;
2812
1876/// Function failed during execution.2813/// Function failed during execution.
1877pub const FUNCTION_FAILED = 1627;2814pub const FUNCTION_FAILED = 1627;
2815
1878/// Invalid or unknown table specified.2816/// Invalid or unknown table specified.
1879pub const INVALID_TABLE = 1628;2817pub const INVALID_TABLE = 1628;
2818
1880/// Data supplied is of wrong type.2819/// Data supplied is of wrong type.
1881pub const DATATYPE_MISMATCH = 1629;2820pub const DATATYPE_MISMATCH = 1629;
2821
1882/// Data of this type is not supported.2822/// Data of this type is not supported.
1883pub const UNSUPPORTED_TYPE = 1630;2823pub const UNSUPPORTED_TYPE = 1630;
2824
1884/// The Windows Installer service failed to start. Contact your support personnel.2825/// The Windows Installer service failed to start. Contact your support personnel.
1885pub const CREATE_FAILED = 1631;2826pub const CREATE_FAILED = 1631;
2827
1886/// The Temp folder is on a drive that is full or is inaccessible. Free up space on the drive or verify that you have write permission on the Temp folder.2828/// The Temp folder is on a drive that is full or is inaccessible. Free up space on the drive or verify that you have write permission on the Temp folder.
1887pub const INSTALL_TEMP_UNWRITABLE = 1632;2829pub const INSTALL_TEMP_UNWRITABLE = 1632;
2830
1888/// This installation package is not supported by this processor type. Contact your product vendor.2831/// This installation package is not supported by this processor type. Contact your product vendor.
1889pub const INSTALL_PLATFORM_UNSUPPORTED = 1633;2832pub const INSTALL_PLATFORM_UNSUPPORTED = 1633;
2833
1890/// Component not used on this computer.2834/// Component not used on this computer.
1891pub const INSTALL_NOTUSED = 1634;2835pub const INSTALL_NOTUSED = 1634;
2836
1892/// This update package could not be opened. Verify that the update package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer update package.2837/// This update package could not be opened. Verify that the update package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer update package.
1893pub const PATCH_PACKAGE_OPEN_FAILED = 1635;2838pub const PATCH_PACKAGE_OPEN_FAILED = 1635;
2839
1894/// This update package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer update package.2840/// This update package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer update package.
1895pub const PATCH_PACKAGE_INVALID = 1636;2841pub const PATCH_PACKAGE_INVALID = 1636;
2842
1896/// This update package cannot be processed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.2843/// This update package cannot be processed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.
1897pub const PATCH_PACKAGE_UNSUPPORTED = 1637;2844pub const PATCH_PACKAGE_UNSUPPORTED = 1637;
2845
1898/// Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs on the Control Panel.2846/// Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs on the Control Panel.
1899pub const PRODUCT_VERSION = 1638;2847pub const PRODUCT_VERSION = 1638;
2848
1900/// Invalid command line argument. Consult the Windows Installer SDK for detailed command line help.2849/// Invalid command line argument. Consult the Windows Installer SDK for detailed command line help.
1901pub const INVALID_COMMAND_LINE = 1639;2850pub const INVALID_COMMAND_LINE = 1639;
2851
1902/// Only administrators have permission to add, remove, or configure server software during a Terminal services remote session. If you want to install or configure software on the server, contact your network administrator.2852/// Only administrators have permission to add, remove, or configure server software during a Terminal services remote session. If you want to install or configure software on the server, contact your network administrator.
1903pub const INSTALL_REMOTE_DISALLOWED = 1640;2853pub const INSTALL_REMOTE_DISALLOWED = 1640;
2854
1904/// The requested operation completed successfully. The system will be restarted so the changes can take effect.2855/// The requested operation completed successfully. The system will be restarted so the changes can take effect.
1905pub const SUCCESS_REBOOT_INITIATED = 1641;2856pub const SUCCESS_REBOOT_INITIATED = 1641;
2857
1906/// The upgrade cannot be installed by the Windows Installer service because the program to be upgraded may be missing, or the upgrade may update a different version of the program. Verify that the program to be upgraded exists on your computer and that you have the correct upgrade.2858/// The upgrade cannot be installed by the Windows Installer service because the program to be upgraded may be missing, or the upgrade may update a different version of the program. Verify that the program to be upgraded exists on your computer and that you have the correct upgrade.
1907pub const PATCH_TARGET_NOT_FOUND = 1642;2859pub const PATCH_TARGET_NOT_FOUND = 1642;
2860
1908/// The update package is not permitted by software restriction policy.2861/// The update package is not permitted by software restriction policy.
1909pub const PATCH_PACKAGE_REJECTED = 1643;2862pub const PATCH_PACKAGE_REJECTED = 1643;
2863
1910/// One or more customizations are not permitted by software restriction policy.2864/// One or more customizations are not permitted by software restriction policy.
1911pub const INSTALL_TRANSFORM_REJECTED = 1644;2865pub const INSTALL_TRANSFORM_REJECTED = 1644;
2866
1912/// The Windows Installer does not permit installation from a Remote Desktop Connection.2867/// The Windows Installer does not permit installation from a Remote Desktop Connection.
1913pub const INSTALL_REMOTE_PROHIBITED = 1645;2868pub const INSTALL_REMOTE_PROHIBITED = 1645;
2869
1914/// Uninstallation of the update package is not supported.2870/// Uninstallation of the update package is not supported.
1915pub const PATCH_REMOVAL_UNSUPPORTED = 1646;2871pub const PATCH_REMOVAL_UNSUPPORTED = 1646;
2872
1916/// The update is not applied to this product.2873/// The update is not applied to this product.
1917pub const UNKNOWN_PATCH = 1647;2874pub const UNKNOWN_PATCH = 1647;
2875
1918/// No valid sequence could be found for the set of updates.2876/// No valid sequence could be found for the set of updates.
1919pub const PATCH_NO_SEQUENCE = 1648;2877pub const PATCH_NO_SEQUENCE = 1648;
2878
1920/// Update removal was disallowed by policy.2879/// Update removal was disallowed by policy.
1921pub const PATCH_REMOVAL_DISALLOWED = 1649;2880pub const PATCH_REMOVAL_DISALLOWED = 1649;
2881
1922/// The XML update data is invalid.2882/// The XML update data is invalid.
1923pub const INVALID_PATCH_XML = 1650;2883pub const INVALID_PATCH_XML = 1650;
2884
1924/// Windows Installer does not permit updating of managed advertised products. At least one feature of the product must be installed before applying the update.2885/// Windows Installer does not permit updating of managed advertised products. At least one feature of the product must be installed before applying the update.
1925pub const PATCH_MANAGED_ADVERTISED_PRODUCT = 1651;2886pub const PATCH_MANAGED_ADVERTISED_PRODUCT = 1651;
2887
1926/// The Windows Installer service is not accessible in Safe Mode. Please try again when your computer is not in Safe Mode or you can use System Restore to return your machine to a previous good state.2888/// The Windows Installer service is not accessible in Safe Mode. Please try again when your computer is not in Safe Mode or you can use System Restore to return your machine to a previous good state.
1927pub const INSTALL_SERVICE_SAFEBOOT = 1652;2889pub const INSTALL_SERVICE_SAFEBOOT = 1652;
2890
1928/// A fail fast exception occurred. Exception handlers will not be invoked and the process will be terminated immediately.2891/// A fail fast exception occurred. Exception handlers will not be invoked and the process will be terminated immediately.
1929pub const FAIL_FAST_EXCEPTION = 1653;2892pub const FAIL_FAST_EXCEPTION = 1653;
2893
1930/// The app that you are trying to run is not supported on this version of Windows.2894/// The app that you are trying to run is not supported on this version of Windows.
1931pub const INSTALL_REJECTED = 1654;2895pub const INSTALL_REJECTED = 1654;
2896
1932/// The string binding is invalid.2897/// The string binding is invalid.
1933pub const RPC_S_INVALID_STRING_BINDING = 1700;2898pub const RPC_S_INVALID_STRING_BINDING = 1700;
2899
1934/// The binding handle is not the correct type.2900/// The binding handle is not the correct type.
1935pub const RPC_S_WRONG_KIND_OF_BINDING = 1701;2901pub const RPC_S_WRONG_KIND_OF_BINDING = 1701;
2902
1936/// The binding handle is invalid.2903/// The binding handle is invalid.
1937pub const RPC_S_INVALID_BINDING = 1702;2904pub const RPC_S_INVALID_BINDING = 1702;
2905
1938/// The RPC protocol sequence is not supported.2906/// The RPC protocol sequence is not supported.
1939pub const RPC_S_PROTSEQ_NOT_SUPPORTED = 1703;2907pub const RPC_S_PROTSEQ_NOT_SUPPORTED = 1703;
2908
1940/// The RPC protocol sequence is invalid.2909/// The RPC protocol sequence is invalid.
1941pub const RPC_S_INVALID_RPC_PROTSEQ = 1704;2910pub const RPC_S_INVALID_RPC_PROTSEQ = 1704;
2911
1942/// The string universal unique identifier (UUID) is invalid.2912/// The string universal unique identifier (UUID) is invalid.
1943pub const RPC_S_INVALID_STRING_UUID = 1705;2913pub const RPC_S_INVALID_STRING_UUID = 1705;
2914
1944/// The endpoint format is invalid.2915/// The endpoint format is invalid.
1945pub const RPC_S_INVALID_ENDPOINT_FORMAT = 1706;2916pub const RPC_S_INVALID_ENDPOINT_FORMAT = 1706;
2917
1946/// The network address is invalid.2918/// The network address is invalid.
1947pub const RPC_S_INVALID_NET_ADDR = 1707;2919pub const RPC_S_INVALID_NET_ADDR = 1707;
2920
1948/// No endpoint was found.2921/// No endpoint was found.
1949pub const RPC_S_NO_ENDPOINT_FOUND = 1708;2922pub const RPC_S_NO_ENDPOINT_FOUND = 1708;
2923
1950/// The timeout value is invalid.2924/// The timeout value is invalid.
1951pub const RPC_S_INVALID_TIMEOUT = 1709;2925pub const RPC_S_INVALID_TIMEOUT = 1709;
2926
1952/// The object universal unique identifier (UUID) was not found.2927/// The object universal unique identifier (UUID) was not found.
1953pub const RPC_S_OBJECT_NOT_FOUND = 1710;2928pub const RPC_S_OBJECT_NOT_FOUND = 1710;
2929
1954/// The object universal unique identifier (UUID) has already been registered.2930/// The object universal unique identifier (UUID) has already been registered.
1955pub const RPC_S_ALREADY_REGISTERED = 1711;2931pub const RPC_S_ALREADY_REGISTERED = 1711;
2932
1956/// The type universal unique identifier (UUID) has already been registered.2933/// The type universal unique identifier (UUID) has already been registered.
1957pub const RPC_S_TYPE_ALREADY_REGISTERED = 1712;2934pub const RPC_S_TYPE_ALREADY_REGISTERED = 1712;
2935
1958/// The RPC server is already listening.2936/// The RPC server is already listening.
1959pub const RPC_S_ALREADY_LISTENING = 1713;2937pub const RPC_S_ALREADY_LISTENING = 1713;
2938
1960/// No protocol sequences have been registered.2939/// No protocol sequences have been registered.
1961pub const RPC_S_NO_PROTSEQS_REGISTERED = 1714;2940pub const RPC_S_NO_PROTSEQS_REGISTERED = 1714;
2941
1962/// The RPC server is not listening.2942/// The RPC server is not listening.
1963pub const RPC_S_NOT_LISTENING = 1715;2943pub const RPC_S_NOT_LISTENING = 1715;
2944
1964/// The manager type is unknown.2945/// The manager type is unknown.
1965pub const RPC_S_UNKNOWN_MGR_TYPE = 1716;2946pub const RPC_S_UNKNOWN_MGR_TYPE = 1716;
2947
1966/// The interface is unknown.2948/// The interface is unknown.
1967pub const RPC_S_UNKNOWN_IF = 1717;2949pub const RPC_S_UNKNOWN_IF = 1717;
2950
1968/// There are no bindings.2951/// There are no bindings.
1969pub const RPC_S_NO_BINDINGS = 1718;2952pub const RPC_S_NO_BINDINGS = 1718;
2953
1970/// There are no protocol sequences.2954/// There are no protocol sequences.
1971pub const RPC_S_NO_PROTSEQS = 1719;2955pub const RPC_S_NO_PROTSEQS = 1719;
2956
1972/// The endpoint cannot be created.2957/// The endpoint cannot be created.
1973pub const RPC_S_CANT_CREATE_ENDPOINT = 1720;2958pub const RPC_S_CANT_CREATE_ENDPOINT = 1720;
2959
1974/// Not enough resources are available to complete this operation.2960/// Not enough resources are available to complete this operation.
1975pub const RPC_S_OUT_OF_RESOURCES = 1721;2961pub const RPC_S_OUT_OF_RESOURCES = 1721;
2962
1976/// The RPC server is unavailable.2963/// The RPC server is unavailable.
1977pub const RPC_S_SERVER_UNAVAILABLE = 1722;2964pub const RPC_S_SERVER_UNAVAILABLE = 1722;
2965
1978/// The RPC server is too busy to complete this operation.2966/// The RPC server is too busy to complete this operation.
1979pub const RPC_S_SERVER_TOO_BUSY = 1723;2967pub const RPC_S_SERVER_TOO_BUSY = 1723;
2968
1980/// The network options are invalid.2969/// The network options are invalid.
1981pub const RPC_S_INVALID_NETWORK_OPTIONS = 1724;2970pub const RPC_S_INVALID_NETWORK_OPTIONS = 1724;
2971
1982/// There are no remote procedure calls active on this thread.2972/// There are no remote procedure calls active on this thread.
1983pub const RPC_S_NO_CALL_ACTIVE = 1725;2973pub const RPC_S_NO_CALL_ACTIVE = 1725;
2974
1984/// The remote procedure call failed.2975/// The remote procedure call failed.
1985pub const RPC_S_CALL_FAILED = 1726;2976pub const RPC_S_CALL_FAILED = 1726;
2977
1986/// The remote procedure call failed and did not execute.2978/// The remote procedure call failed and did not execute.
1987pub const RPC_S_CALL_FAILED_DNE = 1727;2979pub const RPC_S_CALL_FAILED_DNE = 1727;
2980
1988/// A remote procedure call (RPC) protocol error occurred.2981/// A remote procedure call (RPC) protocol error occurred.
1989pub const RPC_S_PROTOCOL_ERROR = 1728;2982pub const RPC_S_PROTOCOL_ERROR = 1728;
2983
1990/// Access to the HTTP proxy is denied.2984/// Access to the HTTP proxy is denied.
1991pub const RPC_S_PROXY_ACCESS_DENIED = 1729;2985pub const RPC_S_PROXY_ACCESS_DENIED = 1729;
2986
1992/// The transfer syntax is not supported by the RPC server.2987/// The transfer syntax is not supported by the RPC server.
1993pub const RPC_S_UNSUPPORTED_TRANS_SYN = 1730;2988pub const RPC_S_UNSUPPORTED_TRANS_SYN = 1730;
2989
1994/// The universal unique identifier (UUID) type is not supported.2990/// The universal unique identifier (UUID) type is not supported.
1995pub const RPC_S_UNSUPPORTED_TYPE = 1732;2991pub const RPC_S_UNSUPPORTED_TYPE = 1732;
2992
1996/// The tag is invalid.2993/// The tag is invalid.
1997pub const RPC_S_INVALID_TAG = 1733;2994pub const RPC_S_INVALID_TAG = 1733;
2995
1998/// The array bounds are invalid.2996/// The array bounds are invalid.
1999pub const RPC_S_INVALID_BOUND = 1734;2997pub const RPC_S_INVALID_BOUND = 1734;
2998
2000/// The binding does not contain an entry name.2999/// The binding does not contain an entry name.
2001pub const RPC_S_NO_ENTRY_NAME = 1735;3000pub const RPC_S_NO_ENTRY_NAME = 1735;
3001
2002/// The name syntax is invalid.3002/// The name syntax is invalid.
2003pub const RPC_S_INVALID_NAME_SYNTAX = 1736;3003pub const RPC_S_INVALID_NAME_SYNTAX = 1736;
3004
2004/// The name syntax is not supported.3005/// The name syntax is not supported.
2005pub const RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737;3006pub const RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737;
3007
2006/// No network address is available to use to construct a universal unique identifier (UUID).3008/// No network address is available to use to construct a universal unique identifier (UUID).
2007pub const RPC_S_UUID_NO_ADDRESS = 1739;3009pub const RPC_S_UUID_NO_ADDRESS = 1739;
3010
2008/// The endpoint is a duplicate.3011/// The endpoint is a duplicate.
2009pub const RPC_S_DUPLICATE_ENDPOINT = 1740;3012pub const RPC_S_DUPLICATE_ENDPOINT = 1740;
3013
2010/// The authentication type is unknown.3014/// The authentication type is unknown.
2011pub const RPC_S_UNKNOWN_AUTHN_TYPE = 1741;3015pub const RPC_S_UNKNOWN_AUTHN_TYPE = 1741;
3016
2012/// The maximum number of calls is too small.3017/// The maximum number of calls is too small.
2013pub const RPC_S_MAX_CALLS_TOO_SMALL = 1742;3018pub const RPC_S_MAX_CALLS_TOO_SMALL = 1742;
3019
2014/// The string is too long.3020/// The string is too long.
2015pub const RPC_S_STRING_TOO_LONG = 1743;3021pub const RPC_S_STRING_TOO_LONG = 1743;
3022
2016/// The RPC protocol sequence was not found.3023/// The RPC protocol sequence was not found.
2017pub const RPC_S_PROTSEQ_NOT_FOUND = 1744;3024pub const RPC_S_PROTSEQ_NOT_FOUND = 1744;
3025
2018/// The procedure number is out of range.3026/// The procedure number is out of range.
2019pub const RPC_S_PROCNUM_OUT_OF_RANGE = 1745;3027pub const RPC_S_PROCNUM_OUT_OF_RANGE = 1745;
3028
2020/// The binding does not contain any authentication information.3029/// The binding does not contain any authentication information.
2021pub const RPC_S_BINDING_HAS_NO_AUTH = 1746;3030pub const RPC_S_BINDING_HAS_NO_AUTH = 1746;
3031
2022/// The authentication service is unknown.3032/// The authentication service is unknown.
2023pub const RPC_S_UNKNOWN_AUTHN_SERVICE = 1747;3033pub const RPC_S_UNKNOWN_AUTHN_SERVICE = 1747;
3034
2024/// The authentication level is unknown.3035/// The authentication level is unknown.
2025pub const RPC_S_UNKNOWN_AUTHN_LEVEL = 1748;3036pub const RPC_S_UNKNOWN_AUTHN_LEVEL = 1748;
3037
2026/// The security context is invalid.3038/// The security context is invalid.
2027pub const RPC_S_INVALID_AUTH_IDENTITY = 1749;3039pub const RPC_S_INVALID_AUTH_IDENTITY = 1749;
3040
2028/// The authorization service is unknown.3041/// The authorization service is unknown.
2029pub const RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750;3042pub const RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750;
3043
2030/// The entry is invalid.3044/// The entry is invalid.
2031pub const EPT_S_INVALID_ENTRY = 1751;3045pub const EPT_S_INVALID_ENTRY = 1751;
3046
2032/// The server endpoint cannot perform the operation.3047/// The server endpoint cannot perform the operation.
2033pub const EPT_S_CANT_PERFORM_OP = 1752;3048pub const EPT_S_CANT_PERFORM_OP = 1752;
3049
2034/// There are no more endpoints available from the endpoint mapper.3050/// There are no more endpoints available from the endpoint mapper.
2035pub const EPT_S_NOT_REGISTERED = 1753;3051pub const EPT_S_NOT_REGISTERED = 1753;
3052
2036/// No interfaces have been exported.3053/// No interfaces have been exported.
2037pub const RPC_S_NOTHING_TO_EXPORT = 1754;3054pub const RPC_S_NOTHING_TO_EXPORT = 1754;
3055
2038/// The entry name is incomplete.3056/// The entry name is incomplete.
2039pub const RPC_S_INCOMPLETE_NAME = 1755;3057pub const RPC_S_INCOMPLETE_NAME = 1755;
3058
2040/// The version option is invalid.3059/// The version option is invalid.
2041pub const RPC_S_INVALID_VERS_OPTION = 1756;3060pub const RPC_S_INVALID_VERS_OPTION = 1756;
3061
2042/// There are no more members.3062/// There are no more members.
2043pub const RPC_S_NO_MORE_MEMBERS = 1757;3063pub const RPC_S_NO_MORE_MEMBERS = 1757;
3064
2044/// There is nothing to unexport.3065/// There is nothing to unexport.
2045pub const RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758;3066pub const RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758;
3067
2046/// The interface was not found.3068/// The interface was not found.
2047pub const RPC_S_INTERFACE_NOT_FOUND = 1759;3069pub const RPC_S_INTERFACE_NOT_FOUND = 1759;
3070
2048/// The entry already exists.3071/// The entry already exists.
2049pub const RPC_S_ENTRY_ALREADY_EXISTS = 1760;3072pub const RPC_S_ENTRY_ALREADY_EXISTS = 1760;
3073
2050/// The entry is not found.3074/// The entry is not found.
2051pub const RPC_S_ENTRY_NOT_FOUND = 1761;3075pub const RPC_S_ENTRY_NOT_FOUND = 1761;
3076
2052/// The name service is unavailable.3077/// The name service is unavailable.
2053pub const RPC_S_NAME_SERVICE_UNAVAILABLE = 1762;3078pub const RPC_S_NAME_SERVICE_UNAVAILABLE = 1762;
3079
2054/// The network address family is invalid.3080/// The network address family is invalid.
2055pub const RPC_S_INVALID_NAF_ID = 1763;3081pub const RPC_S_INVALID_NAF_ID = 1763;
3082
2056/// The requested operation is not supported.3083/// The requested operation is not supported.
2057pub const RPC_S_CANNOT_SUPPORT = 1764;3084pub const RPC_S_CANNOT_SUPPORT = 1764;
3085
2058/// No security context is available to allow impersonation.3086/// No security context is available to allow impersonation.
2059pub const RPC_S_NO_CONTEXT_AVAILABLE = 1765;3087pub const RPC_S_NO_CONTEXT_AVAILABLE = 1765;
3088
2060/// An internal error occurred in a remote procedure call (RPC).3089/// An internal error occurred in a remote procedure call (RPC).
2061pub const RPC_S_INTERNAL_ERROR = 1766;3090pub const RPC_S_INTERNAL_ERROR = 1766;
3091
2062/// The RPC server attempted an integer division by zero.3092/// The RPC server attempted an integer division by zero.
2063pub const RPC_S_ZERO_DIVIDE = 1767;3093pub const RPC_S_ZERO_DIVIDE = 1767;
3094
2064/// An addressing error occurred in the RPC server.3095/// An addressing error occurred in the RPC server.
2065pub const RPC_S_ADDRESS_ERROR = 1768;3096pub const RPC_S_ADDRESS_ERROR = 1768;
3097
2066/// A floating-point operation at the RPC server caused a division by zero.3098/// A floating-point operation at the RPC server caused a division by zero.
2067pub const RPC_S_FP_DIV_ZERO = 1769;3099pub const RPC_S_FP_DIV_ZERO = 1769;
3100
2068/// A floating-point underflow occurred at the RPC server.3101/// A floating-point underflow occurred at the RPC server.
2069pub const RPC_S_FP_UNDERFLOW = 1770;3102pub const RPC_S_FP_UNDERFLOW = 1770;
3103
2070/// A floating-point overflow occurred at the RPC server.3104/// A floating-point overflow occurred at the RPC server.
2071pub const RPC_S_FP_OVERFLOW = 1771;3105pub const RPC_S_FP_OVERFLOW = 1771;
3106
2072/// The list of RPC servers available for the binding of auto handles has been exhausted.3107/// The list of RPC servers available for the binding of auto handles has been exhausted.
2073pub const RPC_X_NO_MORE_ENTRIES = 1772;3108pub const RPC_X_NO_MORE_ENTRIES = 1772;
3109
2074/// Unable to open the character translation table file.3110/// Unable to open the character translation table file.
2075pub const RPC_X_SS_CHAR_TRANS_OPEN_FAIL = 1773;3111pub const RPC_X_SS_CHAR_TRANS_OPEN_FAIL = 1773;
3112
2076/// The file containing the character translation table has fewer than 512 bytes.3113/// The file containing the character translation table has fewer than 512 bytes.
2077pub const RPC_X_SS_CHAR_TRANS_SHORT_FILE = 1774;3114pub const RPC_X_SS_CHAR_TRANS_SHORT_FILE = 1774;
3115
2078/// A null context handle was passed from the client to the host during a remote procedure call.3116/// A null context handle was passed from the client to the host during a remote procedure call.
2079pub const RPC_X_SS_IN_NULL_CONTEXT = 1775;3117pub const RPC_X_SS_IN_NULL_CONTEXT = 1775;
3118
2080/// The context handle changed during a remote procedure call.3119/// The context handle changed during a remote procedure call.
2081pub const RPC_X_SS_CONTEXT_DAMAGED = 1777;3120pub const RPC_X_SS_CONTEXT_DAMAGED = 1777;
3121
2082/// The binding handles passed to a remote procedure call do not match.3122/// The binding handles passed to a remote procedure call do not match.
2083pub const RPC_X_SS_HANDLES_MISMATCH = 1778;3123pub const RPC_X_SS_HANDLES_MISMATCH = 1778;
3124
2084/// The stub is unable to get the remote procedure call handle.3125/// The stub is unable to get the remote procedure call handle.
2085pub const RPC_X_SS_CANNOT_GET_CALL_HANDLE = 1779;3126pub const RPC_X_SS_CANNOT_GET_CALL_HANDLE = 1779;
3127
2086/// A null reference pointer was passed to the stub.3128/// A null reference pointer was passed to the stub.
2087pub const RPC_X_NULL_REF_POINTER = 1780;3129pub const RPC_X_NULL_REF_POINTER = 1780;
3130
2088/// The enumeration value is out of range.3131/// The enumeration value is out of range.
2089pub const RPC_X_ENUM_VALUE_OUT_OF_RANGE = 1781;3132pub const RPC_X_ENUM_VALUE_OUT_OF_RANGE = 1781;
3133
2090/// The byte count is too small.3134/// The byte count is too small.
2091pub const RPC_X_BYTE_COUNT_TOO_SMALL = 1782;3135pub const RPC_X_BYTE_COUNT_TOO_SMALL = 1782;
3136
2092/// The stub received bad data.3137/// The stub received bad data.
2093pub const RPC_X_BAD_STUB_DATA = 1783;3138pub const RPC_X_BAD_STUB_DATA = 1783;
3139
2094/// The supplied user buffer is not valid for the requested operation.3140/// The supplied user buffer is not valid for the requested operation.
2095pub const INVALID_USER_BUFFER = 1784;3141pub const INVALID_USER_BUFFER = 1784;
3142
2096/// The disk media is not recognized. It may not be formatted.3143/// The disk media is not recognized. It may not be formatted.
2097pub const UNRECOGNIZED_MEDIA = 1785;3144pub const UNRECOGNIZED_MEDIA = 1785;
3145
2098/// The workstation does not have a trust secret.3146/// The workstation does not have a trust secret.
2099pub const NO_TRUST_LSA_SECRET = 1786;3147pub const NO_TRUST_LSA_SECRET = 1786;
3148
2100/// The security database on the server does not have a computer account for this workstation trust relationship.3149/// The security database on the server does not have a computer account for this workstation trust relationship.
2101pub const NO_TRUST_SAM_ACCOUNT = 1787;3150pub const NO_TRUST_SAM_ACCOUNT = 1787;
3151
2102/// The trust relationship between the primary domain and the trusted domain failed.3152/// The trust relationship between the primary domain and the trusted domain failed.
2103pub const TRUSTED_DOMAIN_FAILURE = 1788;3153pub const TRUSTED_DOMAIN_FAILURE = 1788;
3154
2104/// The trust relationship between this workstation and the primary domain failed.3155/// The trust relationship between this workstation and the primary domain failed.
2105pub const TRUSTED_RELATIONSHIP_FAILURE = 1789;3156pub const TRUSTED_RELATIONSHIP_FAILURE = 1789;
3157
2106/// The network logon failed.3158/// The network logon failed.
2107pub const TRUST_FAILURE = 1790;3159pub const TRUST_FAILURE = 1790;
3160
2108/// A remote procedure call is already in progress for this thread.3161/// A remote procedure call is already in progress for this thread.
2109pub const RPC_S_CALL_IN_PROGRESS = 1791;3162pub const RPC_S_CALL_IN_PROGRESS = 1791;
3163
2110/// An attempt was made to logon, but the network logon service was not started.3164/// An attempt was made to logon, but the network logon service was not started.
2111pub const NETLOGON_NOT_STARTED = 1792;3165pub const NETLOGON_NOT_STARTED = 1792;
3166
2112/// The user's account has expired.3167/// The user's account has expired.
2113pub const ACCOUNT_EXPIRED = 1793;3168pub const ACCOUNT_EXPIRED = 1793;
3169
2114/// The redirector is in use and cannot be unloaded.3170/// The redirector is in use and cannot be unloaded.
2115pub const REDIRECTOR_HAS_OPEN_HANDLES = 1794;3171pub const REDIRECTOR_HAS_OPEN_HANDLES = 1794;
3172
2116/// The specified printer driver is already installed.3173/// The specified printer driver is already installed.
2117pub const PRINTER_DRIVER_ALREADY_INSTALLED = 1795;3174pub const PRINTER_DRIVER_ALREADY_INSTALLED = 1795;
3175
2118/// The specified port is unknown.3176/// The specified port is unknown.
2119pub const UNKNOWN_PORT = 1796;3177pub const UNKNOWN_PORT = 1796;
3178
2120/// The printer driver is unknown.3179/// The printer driver is unknown.
2121pub const UNKNOWN_PRINTER_DRIVER = 1797;3180pub const UNKNOWN_PRINTER_DRIVER = 1797;
3181
2122/// The print processor is unknown.3182/// The print processor is unknown.
2123pub const UNKNOWN_PRINTPROCESSOR = 1798;3183pub const UNKNOWN_PRINTPROCESSOR = 1798;
3184
2124/// The specified separator file is invalid.3185/// The specified separator file is invalid.
2125pub const INVALID_SEPARATOR_FILE = 1799;3186pub const INVALID_SEPARATOR_FILE = 1799;
3187
2126/// The specified priority is invalid.3188/// The specified priority is invalid.
2127pub const INVALID_PRIORITY = 1800;3189pub const INVALID_PRIORITY = 1800;
3190
2128/// The printer name is invalid.3191/// The printer name is invalid.
2129pub const INVALID_PRINTER_NAME = 1801;3192pub const INVALID_PRINTER_NAME = 1801;
3193
2130/// The printer already exists.3194/// The printer already exists.
2131pub const PRINTER_ALREADY_EXISTS = 1802;3195pub const PRINTER_ALREADY_EXISTS = 1802;
3196
2132/// The printer command is invalid.3197/// The printer command is invalid.
2133pub const INVALID_PRINTER_COMMAND = 1803;3198pub const INVALID_PRINTER_COMMAND = 1803;
3199
2134/// The specified datatype is invalid.3200/// The specified datatype is invalid.
2135pub const INVALID_DATATYPE = 1804;3201pub const INVALID_DATATYPE = 1804;
3202
2136/// The environment specified is invalid.3203/// The environment specified is invalid.
2137pub const INVALID_ENVIRONMENT = 1805;3204pub const INVALID_ENVIRONMENT = 1805;
3205
2138/// There are no more bindings.3206/// There are no more bindings.
2139pub const RPC_S_NO_MORE_BINDINGS = 1806;3207pub const RPC_S_NO_MORE_BINDINGS = 1806;
3208
2140/// The account used is an interdomain trust account. Use your global user account or local user account to access this server.3209/// The account used is an interdomain trust account. Use your global user account or local user account to access this server.
2141pub const NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 1807;3210pub const NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 1807;
3211
2142/// The account used is a computer account. Use your global user account or local user account to access this server.3212/// The account used is a computer account. Use your global user account or local user account to access this server.
2143pub const NOLOGON_WORKSTATION_TRUST_ACCOUNT = 1808;3213pub const NOLOGON_WORKSTATION_TRUST_ACCOUNT = 1808;
3214
2144/// The account used is a server trust account. Use your global user account or local user account to access this server.3215/// The account used is a server trust account. Use your global user account or local user account to access this server.
2145pub const NOLOGON_SERVER_TRUST_ACCOUNT = 1809;3216pub const NOLOGON_SERVER_TRUST_ACCOUNT = 1809;
3217
2146/// The name or security ID (SID) of the domain specified is inconsistent with the trust information for that domain.3218/// The name or security ID (SID) of the domain specified is inconsistent with the trust information for that domain.
2147pub const DOMAIN_TRUST_INCONSISTENT = 1810;3219pub const DOMAIN_TRUST_INCONSISTENT = 1810;
3220
2148/// The server is in use and cannot be unloaded.3221/// The server is in use and cannot be unloaded.
2149pub const SERVER_HAS_OPEN_HANDLES = 1811;3222pub const SERVER_HAS_OPEN_HANDLES = 1811;
3223
2150/// The specified image file did not contain a resource section.3224/// The specified image file did not contain a resource section.
2151pub const RESOURCE_DATA_NOT_FOUND = 1812;3225pub const RESOURCE_DATA_NOT_FOUND = 1812;
3226
2152/// The specified resource type cannot be found in the image file.3227/// The specified resource type cannot be found in the image file.
2153pub const RESOURCE_TYPE_NOT_FOUND = 1813;3228pub const RESOURCE_TYPE_NOT_FOUND = 1813;
3229
2154/// The specified resource name cannot be found in the image file.3230/// The specified resource name cannot be found in the image file.
2155pub const RESOURCE_NAME_NOT_FOUND = 1814;3231pub const RESOURCE_NAME_NOT_FOUND = 1814;
3232
2156/// The specified resource language ID cannot be found in the image file.3233/// The specified resource language ID cannot be found in the image file.
2157pub const RESOURCE_LANG_NOT_FOUND = 1815;3234pub const RESOURCE_LANG_NOT_FOUND = 1815;
3235
2158/// Not enough quota is available to process this command.3236/// Not enough quota is available to process this command.
2159pub const NOT_ENOUGH_QUOTA = 1816;3237pub const NOT_ENOUGH_QUOTA = 1816;
3238
2160/// No interfaces have been registered.3239/// No interfaces have been registered.
2161pub const RPC_S_NO_INTERFACES = 1817;3240pub const RPC_S_NO_INTERFACES = 1817;
3241
2162/// The remote procedure call was cancelled.3242/// The remote procedure call was cancelled.
2163pub const RPC_S_CALL_CANCELLED = 1818;3243pub const RPC_S_CALL_CANCELLED = 1818;
3244
2164/// The binding handle does not contain all required information.3245/// The binding handle does not contain all required information.
2165pub const RPC_S_BINDING_INCOMPLETE = 1819;3246pub const RPC_S_BINDING_INCOMPLETE = 1819;
3247
2166/// A communications failure occurred during a remote procedure call.3248/// A communications failure occurred during a remote procedure call.
2167pub const RPC_S_COMM_FAILURE = 1820;3249pub const RPC_S_COMM_FAILURE = 1820;
3250
2168/// The requested authentication level is not supported.3251/// The requested authentication level is not supported.
2169pub const RPC_S_UNSUPPORTED_AUTHN_LEVEL = 1821;3252pub const RPC_S_UNSUPPORTED_AUTHN_LEVEL = 1821;
3253
2170/// No principal name registered.3254/// No principal name registered.
2171pub const RPC_S_NO_PRINC_NAME = 1822;3255pub const RPC_S_NO_PRINC_NAME = 1822;
3256
2172/// The error specified is not a valid Windows RPC error code.3257/// The error specified is not a valid Windows RPC error code.
2173pub const RPC_S_NOT_RPC_ERROR = 1823;3258pub const RPC_S_NOT_RPC_ERROR = 1823;
3259
2174/// A UUID that is valid only on this computer has been allocated.3260/// A UUID that is valid only on this computer has been allocated.
2175pub const RPC_S_UUID_LOCAL_ONLY = 1824;3261pub const RPC_S_UUID_LOCAL_ONLY = 1824;
3262
2176/// A security package specific error occurred.3263/// A security package specific error occurred.
2177pub const RPC_S_SEC_PKG_ERROR = 1825;3264pub const RPC_S_SEC_PKG_ERROR = 1825;
3265
2178/// Thread is not canceled.3266/// Thread is not canceled.
2179pub const RPC_S_NOT_CANCELLED = 1826;3267pub const RPC_S_NOT_CANCELLED = 1826;
3268
2180/// Invalid operation on the encoding/decoding handle.3269/// Invalid operation on the encoding/decoding handle.
2181pub const RPC_X_INVALID_ES_ACTION = 1827;3270pub const RPC_X_INVALID_ES_ACTION = 1827;
3271
2182/// Incompatible version of the serializing package.3272/// Incompatible version of the serializing package.
2183pub const RPC_X_WRONG_ES_VERSION = 1828;3273pub const RPC_X_WRONG_ES_VERSION = 1828;
3274
2184/// Incompatible version of the RPC stub.3275/// Incompatible version of the RPC stub.
2185pub const RPC_X_WRONG_STUB_VERSION = 1829;3276pub const RPC_X_WRONG_STUB_VERSION = 1829;
3277
2186/// The RPC pipe object is invalid or corrupted.3278/// The RPC pipe object is invalid or corrupted.
2187pub const RPC_X_INVALID_PIPE_OBJECT = 1830;3279pub const RPC_X_INVALID_PIPE_OBJECT = 1830;
3280
2188/// An invalid operation was attempted on an RPC pipe object.3281/// An invalid operation was attempted on an RPC pipe object.
2189pub const RPC_X_WRONG_PIPE_ORDER = 1831;3282pub const RPC_X_WRONG_PIPE_ORDER = 1831;
3283
2190/// Unsupported RPC pipe version.3284/// Unsupported RPC pipe version.
2191pub const RPC_X_WRONG_PIPE_VERSION = 1832;3285pub const RPC_X_WRONG_PIPE_VERSION = 1832;
3286
2192/// HTTP proxy server rejected the connection because the cookie authentication failed.3287/// HTTP proxy server rejected the connection because the cookie authentication failed.
2193pub const RPC_S_COOKIE_AUTH_FAILED = 1833;3288pub const RPC_S_COOKIE_AUTH_FAILED = 1833;
3289
2194/// The group member was not found.3290/// The group member was not found.
2195pub const RPC_S_GROUP_MEMBER_NOT_FOUND = 1898;3291pub const RPC_S_GROUP_MEMBER_NOT_FOUND = 1898;
3292
2196/// The endpoint mapper database entry could not be created.3293/// The endpoint mapper database entry could not be created.
2197pub const EPT_S_CANT_CREATE = 1899;3294pub const EPT_S_CANT_CREATE = 1899;
3295
2198/// The object universal unique identifier (UUID) is the nil UUID.3296/// The object universal unique identifier (UUID) is the nil UUID.
2199pub const RPC_S_INVALID_OBJECT = 1900;3297pub const RPC_S_INVALID_OBJECT = 1900;
3298
2200/// The specified time is invalid.3299/// The specified time is invalid.
2201pub const INVALID_TIME = 1901;3300pub const INVALID_TIME = 1901;
3301
2202/// The specified form name is invalid.3302/// The specified form name is invalid.
2203pub const INVALID_FORM_NAME = 1902;3303pub const INVALID_FORM_NAME = 1902;
3304
2204/// The specified form size is invalid.3305/// The specified form size is invalid.
2205pub const INVALID_FORM_SIZE = 1903;3306pub const INVALID_FORM_SIZE = 1903;
3307
2206/// The specified printer handle is already being waited on.3308/// The specified printer handle is already being waited on.
2207pub const ALREADY_WAITING = 1904;3309pub const ALREADY_WAITING = 1904;
3310
2208/// The specified printer has been deleted.3311/// The specified printer has been deleted.
2209pub const PRINTER_DELETED = 1905;3312pub const PRINTER_DELETED = 1905;
3313
2210/// The state of the printer is invalid.3314/// The state of the printer is invalid.
2211pub const INVALID_PRINTER_STATE = 1906;3315pub const INVALID_PRINTER_STATE = 1906;
3316
2212/// The user's password must be changed before signing in.3317/// The user's password must be changed before signing in.
2213pub const PASSWORD_MUST_CHANGE = 1907;3318pub const PASSWORD_MUST_CHANGE = 1907;
3319
2214/// Could not find the domain controller for this domain.3320/// Could not find the domain controller for this domain.
2215pub const DOMAIN_CONTROLLER_NOT_FOUND = 1908;3321pub const DOMAIN_CONTROLLER_NOT_FOUND = 1908;
3322
2216/// The referenced account is currently locked out and may not be logged on to.3323/// The referenced account is currently locked out and may not be logged on to.
2217pub const ACCOUNT_LOCKED_OUT = 1909;3324pub const ACCOUNT_LOCKED_OUT = 1909;
3325
2218/// The object exporter specified was not found.3326/// The object exporter specified was not found.
2219pub const OR_INVALID_OXID = 1910;3327pub const OR_INVALID_OXID = 1910;
3328
2220/// The object specified was not found.3329/// The object specified was not found.
2221pub const OR_INVALID_OID = 1911;3330pub const OR_INVALID_OID = 1911;
3331
2222/// The object resolver set specified was not found.3332/// The object resolver set specified was not found.
2223pub const OR_INVALID_SET = 1912;3333pub const OR_INVALID_SET = 1912;
3334
2224/// Some data remains to be sent in the request buffer.3335/// Some data remains to be sent in the request buffer.
2225pub const RPC_S_SEND_INCOMPLETE = 1913;3336pub const RPC_S_SEND_INCOMPLETE = 1913;
3337
2226/// Invalid asynchronous remote procedure call handle.3338/// Invalid asynchronous remote procedure call handle.
2227pub const RPC_S_INVALID_ASYNC_HANDLE = 1914;3339pub const RPC_S_INVALID_ASYNC_HANDLE = 1914;
3340
2228/// Invalid asynchronous RPC call handle for this operation.3341/// Invalid asynchronous RPC call handle for this operation.
2229pub const RPC_S_INVALID_ASYNC_CALL = 1915;3342pub const RPC_S_INVALID_ASYNC_CALL = 1915;
3343
2230/// The RPC pipe object has already been closed.3344/// The RPC pipe object has already been closed.
2231pub const RPC_X_PIPE_CLOSED = 1916;3345pub const RPC_X_PIPE_CLOSED = 1916;
3346
2232/// The RPC call completed before all pipes were processed.3347/// The RPC call completed before all pipes were processed.
2233pub const RPC_X_PIPE_DISCIPLINE_ERROR = 1917;3348pub const RPC_X_PIPE_DISCIPLINE_ERROR = 1917;
3349
2234/// No more data is available from the RPC pipe.3350/// No more data is available from the RPC pipe.
2235pub const RPC_X_PIPE_EMPTY = 1918;3351pub const RPC_X_PIPE_EMPTY = 1918;
3352
2236/// No site name is available for this machine.3353/// No site name is available for this machine.
2237pub const NO_SITENAME = 1919;3354pub const NO_SITENAME = 1919;
3355
2238/// The file cannot be accessed by the system.3356/// The file cannot be accessed by the system.
2239pub const CANT_ACCESS_FILE = 1920;3357pub const CANT_ACCESS_FILE = 1920;
3358
2240/// The name of the file cannot be resolved by the system.3359/// The name of the file cannot be resolved by the system.
2241pub const CANT_RESOLVE_FILENAME = 1921;3360pub const CANT_RESOLVE_FILENAME = 1921;
3361
2242/// The entry is not of the expected type.3362/// The entry is not of the expected type.
2243pub const RPC_S_ENTRY_TYPE_MISMATCH = 1922;3363pub const RPC_S_ENTRY_TYPE_MISMATCH = 1922;
3364
2244/// Not all object UUIDs could be exported to the specified entry.3365/// Not all object UUIDs could be exported to the specified entry.
2245pub const RPC_S_NOT_ALL_OBJS_EXPORTED = 1923;3366pub const RPC_S_NOT_ALL_OBJS_EXPORTED = 1923;
3367
2246/// Interface could not be exported to the specified entry.3368/// Interface could not be exported to the specified entry.
2247pub const RPC_S_INTERFACE_NOT_EXPORTED = 1924;3369pub const RPC_S_INTERFACE_NOT_EXPORTED = 1924;
3370
2248/// The specified profile entry could not be added.3371/// The specified profile entry could not be added.
2249pub const RPC_S_PROFILE_NOT_ADDED = 1925;3372pub const RPC_S_PROFILE_NOT_ADDED = 1925;
3373
2250/// The specified profile element could not be added.3374/// The specified profile element could not be added.
2251pub const RPC_S_PRF_ELT_NOT_ADDED = 1926;3375pub const RPC_S_PRF_ELT_NOT_ADDED = 1926;
3376
2252/// The specified profile element could not be removed.3377/// The specified profile element could not be removed.
2253pub const RPC_S_PRF_ELT_NOT_REMOVED = 1927;3378pub const RPC_S_PRF_ELT_NOT_REMOVED = 1927;
3379
2254/// The group element could not be added.3380/// The group element could not be added.
2255pub const RPC_S_GRP_ELT_NOT_ADDED = 1928;3381pub const RPC_S_GRP_ELT_NOT_ADDED = 1928;
3382
2256/// The group element could not be removed.3383/// The group element could not be removed.
2257pub const RPC_S_GRP_ELT_NOT_REMOVED = 1929;3384pub const RPC_S_GRP_ELT_NOT_REMOVED = 1929;
3385
2258/// The printer driver is not compatible with a policy enabled on your computer that blocks NT 4.0 drivers.3386/// The printer driver is not compatible with a policy enabled on your computer that blocks NT 4.0 drivers.
2259pub const KM_DRIVER_BLOCKED = 1930;3387pub const KM_DRIVER_BLOCKED = 1930;
3388
2260/// The context has expired and can no longer be used.3389/// The context has expired and can no longer be used.
2261pub const CONTEXT_EXPIRED = 1931;3390pub const CONTEXT_EXPIRED = 1931;
3391
2262/// The current user's delegated trust creation quota has been exceeded.3392/// The current user's delegated trust creation quota has been exceeded.
2263pub const PER_USER_TRUST_QUOTA_EXCEEDED = 1932;3393pub const PER_USER_TRUST_QUOTA_EXCEEDED = 1932;
3394
2264/// The total delegated trust creation quota has been exceeded.3395/// The total delegated trust creation quota has been exceeded.
2265pub const ALL_USER_TRUST_QUOTA_EXCEEDED = 1933;3396pub const ALL_USER_TRUST_QUOTA_EXCEEDED = 1933;
3397
2266/// The current user's delegated trust deletion quota has been exceeded.3398/// The current user's delegated trust deletion quota has been exceeded.
2267pub const USER_DELETE_TRUST_QUOTA_EXCEEDED = 1934;3399pub const USER_DELETE_TRUST_QUOTA_EXCEEDED = 1934;
3400
2268/// The computer you are signing into is protected by an authentication firewall. The specified account is not allowed to authenticate to the computer.3401/// The computer you are signing into is protected by an authentication firewall. The specified account is not allowed to authenticate to the computer.
2269pub const AUTHENTICATION_FIREWALL_FAILED = 1935;3402pub const AUTHENTICATION_FIREWALL_FAILED = 1935;
3403
2270/// Remote connections to the Print Spooler are blocked by a policy set on your machine.3404/// Remote connections to the Print Spooler are blocked by a policy set on your machine.
2271pub const REMOTE_PRINT_CONNECTIONS_BLOCKED = 1936;3405pub const REMOTE_PRINT_CONNECTIONS_BLOCKED = 1936;
3406
2272/// Authentication failed because NTLM authentication has been disabled.3407/// Authentication failed because NTLM authentication has been disabled.
2273pub const NTLM_BLOCKED = 1937;3408pub const NTLM_BLOCKED = 1937;
3409
2274/// Logon Failure: EAS policy requires that the user change their password before this operation can be performed.3410/// Logon Failure: EAS policy requires that the user change their password before this operation can be performed.
2275pub const PASSWORD_CHANGE_REQUIRED = 1938;3411pub const PASSWORD_CHANGE_REQUIRED = 1938;
3412
2276/// The pixel format is invalid.3413/// The pixel format is invalid.
2277pub const INVALID_PIXEL_FORMAT = 2000;3414pub const INVALID_PIXEL_FORMAT = 2000;
3415
2278/// The specified driver is invalid.3416/// The specified driver is invalid.
2279pub const BAD_DRIVER = 2001;3417pub const BAD_DRIVER = 2001;
3418
2280/// The window style or class attribute is invalid for this operation.3419/// The window style or class attribute is invalid for this operation.
2281pub const INVALID_WINDOW_STYLE = 2002;3420pub const INVALID_WINDOW_STYLE = 2002;
3421
2282/// The requested metafile operation is not supported.3422/// The requested metafile operation is not supported.
2283pub const METAFILE_NOT_SUPPORTED = 2003;3423pub const METAFILE_NOT_SUPPORTED = 2003;
3424
2284/// The requested transformation operation is not supported.3425/// The requested transformation operation is not supported.
2285pub const TRANSFORM_NOT_SUPPORTED = 2004;3426pub const TRANSFORM_NOT_SUPPORTED = 2004;
3427
2286/// The requested clipping operation is not supported.3428/// The requested clipping operation is not supported.
2287pub const CLIPPING_NOT_SUPPORTED = 2005;3429pub const CLIPPING_NOT_SUPPORTED = 2005;
3430
2288/// The specified color management module is invalid.3431/// The specified color management module is invalid.
2289pub const INVALID_CMM = 2010;3432pub const INVALID_CMM = 2010;
3433
2290/// The specified color profile is invalid.3434/// The specified color profile is invalid.
2291pub const INVALID_PROFILE = 2011;3435pub const INVALID_PROFILE = 2011;
3436
2292/// The specified tag was not found.3437/// The specified tag was not found.
2293pub const TAG_NOT_FOUND = 2012;3438pub const TAG_NOT_FOUND = 2012;
3439
2294/// A required tag is not present.3440/// A required tag is not present.
2295pub const TAG_NOT_PRESENT = 2013;3441pub const TAG_NOT_PRESENT = 2013;
3442
2296/// The specified tag is already present.3443/// The specified tag is already present.
2297pub const DUPLICATE_TAG = 2014;3444pub const DUPLICATE_TAG = 2014;
3445
2298/// The specified color profile is not associated with the specified device.3446/// The specified color profile is not associated with the specified device.
2299pub const PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015;3447pub const PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015;
3448
2300/// The specified color profile was not found.3449/// The specified color profile was not found.
2301pub const PROFILE_NOT_FOUND = 2016;3450pub const PROFILE_NOT_FOUND = 2016;
3451
2302/// The specified color space is invalid.3452/// The specified color space is invalid.
2303pub const INVALID_COLORSPACE = 2017;3453pub const INVALID_COLORSPACE = 2017;
3454
2304/// Image Color Management is not enabled.3455/// Image Color Management is not enabled.
2305pub const ICM_NOT_ENABLED = 2018;3456pub const ICM_NOT_ENABLED = 2018;
3457
2306/// There was an error while deleting the color transform.3458/// There was an error while deleting the color transform.
2307pub const DELETING_ICM_XFORM = 2019;3459pub const DELETING_ICM_XFORM = 2019;
3460
2308/// The specified color transform is invalid.3461/// The specified color transform is invalid.
2309pub const INVALID_TRANSFORM = 2020;3462pub const INVALID_TRANSFORM = 2020;
3463
2310/// The specified transform does not match the bitmap's color space.3464/// The specified transform does not match the bitmap's color space.
2311pub const COLORSPACE_MISMATCH = 2021;3465pub const COLORSPACE_MISMATCH = 2021;
3466
2312/// The specified named color index is not present in the profile.3467/// The specified named color index is not present in the profile.
2313pub const INVALID_COLORINDEX = 2022;3468pub const INVALID_COLORINDEX = 2022;
3469
2314/// The specified profile is intended for a device of a different type than the specified device.3470/// The specified profile is intended for a device of a different type than the specified device.
2315pub const PROFILE_DOES_NOT_MATCH_DEVICE = 2023;3471pub const PROFILE_DOES_NOT_MATCH_DEVICE = 2023;
3472
2316/// The network connection was made successfully, but the user had to be prompted for a password other than the one originally specified.3473/// The network connection was made successfully, but the user had to be prompted for a password other than the one originally specified.
2317pub const CONNECTED_OTHER_PASSWORD = 2108;3474pub const CONNECTED_OTHER_PASSWORD = 2108;
3475
2318/// The network connection was made successfully using default credentials.3476/// The network connection was made successfully using default credentials.
2319pub const CONNECTED_OTHER_PASSWORD_DEFAULT = 2109;3477pub const CONNECTED_OTHER_PASSWORD_DEFAULT = 2109;
3478
2320/// The specified username is invalid.3479/// The specified username is invalid.
2321pub const BAD_USERNAME = 2202;3480pub const BAD_USERNAME = 2202;
3481
2322/// This network connection does not exist.3482/// This network connection does not exist.
2323pub const NOT_CONNECTED = 2250;3483pub const NOT_CONNECTED = 2250;
3484
2324/// This network connection has files open or requests pending.3485/// This network connection has files open or requests pending.
2325pub const OPEN_FILES = 2401;3486pub const OPEN_FILES = 2401;
3487
2326/// Active connections still exist.3488/// Active connections still exist.
2327pub const ACTIVE_CONNECTIONS = 2402;3489pub const ACTIVE_CONNECTIONS = 2402;
3490
2328/// The device is in use by an active process and cannot be disconnected.3491/// The device is in use by an active process and cannot be disconnected.
2329pub const DEVICE_IN_USE = 2404;3492pub const DEVICE_IN_USE = 2404;
3493
2330/// The specified print monitor is unknown.3494/// The specified print monitor is unknown.
2331pub const UNKNOWN_PRINT_MONITOR = 3000;3495pub const UNKNOWN_PRINT_MONITOR = 3000;
3496
2332/// The specified printer driver is currently in use.3497/// The specified printer driver is currently in use.
2333pub const PRINTER_DRIVER_IN_USE = 3001;3498pub const PRINTER_DRIVER_IN_USE = 3001;
3499
2334/// The spool file was not found.3500/// The spool file was not found.
2335pub const SPOOL_FILE_NOT_FOUND = 3002;3501pub const SPOOL_FILE_NOT_FOUND = 3002;
3502
2336/// A StartDocPrinter call was not issued.3503/// A StartDocPrinter call was not issued.
2337pub const SPL_NO_STARTDOC = 3003;3504pub const SPL_NO_STARTDOC = 3003;
3505
2338/// An AddJob call was not issued.3506/// An AddJob call was not issued.
2339pub const SPL_NO_ADDJOB = 3004;3507pub const SPL_NO_ADDJOB = 3004;
3508
2340/// The specified print processor has already been installed.3509/// The specified print processor has already been installed.
2341pub const PRINT_PROCESSOR_ALREADY_INSTALLED = 3005;3510pub const PRINT_PROCESSOR_ALREADY_INSTALLED = 3005;
3511
2342/// The specified print monitor has already been installed.3512/// The specified print monitor has already been installed.
2343pub const PRINT_MONITOR_ALREADY_INSTALLED = 3006;3513pub const PRINT_MONITOR_ALREADY_INSTALLED = 3006;
3514
2344/// The specified print monitor does not have the required functions.3515/// The specified print monitor does not have the required functions.
2345pub const INVALID_PRINT_MONITOR = 3007;3516pub const INVALID_PRINT_MONITOR = 3007;
3517
2346/// The specified print monitor is currently in use.3518/// The specified print monitor is currently in use.
2347pub const PRINT_MONITOR_IN_USE = 3008;3519pub const PRINT_MONITOR_IN_USE = 3008;
3520
2348/// The requested operation is not allowed when there are jobs queued to the printer.3521/// The requested operation is not allowed when there are jobs queued to the printer.
2349pub const PRINTER_HAS_JOBS_QUEUED = 3009;3522pub const PRINTER_HAS_JOBS_QUEUED = 3009;
3523
2350/// The requested operation is successful. Changes will not be effective until the system is rebooted.3524/// The requested operation is successful. Changes will not be effective until the system is rebooted.
2351pub const SUCCESS_REBOOT_REQUIRED = 3010;3525pub const SUCCESS_REBOOT_REQUIRED = 3010;
3526
2352/// The requested operation is successful. Changes will not be effective until the service is restarted.3527/// The requested operation is successful. Changes will not be effective until the service is restarted.
2353pub const SUCCESS_RESTART_REQUIRED = 3011;3528pub const SUCCESS_RESTART_REQUIRED = 3011;
3529
2354/// No printers were found.3530/// No printers were found.
2355pub const PRINTER_NOT_FOUND = 3012;3531pub const PRINTER_NOT_FOUND = 3012;
3532
2356/// The printer driver is known to be unreliable.3533/// The printer driver is known to be unreliable.
2357pub const PRINTER_DRIVER_WARNED = 3013;3534pub const PRINTER_DRIVER_WARNED = 3013;
3535
2358/// The printer driver is known to harm the system.3536/// The printer driver is known to harm the system.
2359pub const PRINTER_DRIVER_BLOCKED = 3014;3537pub const PRINTER_DRIVER_BLOCKED = 3014;
3538
2360/// The specified printer driver package is currently in use.3539/// The specified printer driver package is currently in use.
2361pub const PRINTER_DRIVER_PACKAGE_IN_USE = 3015;3540pub const PRINTER_DRIVER_PACKAGE_IN_USE = 3015;
3541
2362/// Unable to find a core driver package that is required by the printer driver package.3542/// Unable to find a core driver package that is required by the printer driver package.
2363pub const CORE_DRIVER_PACKAGE_NOT_FOUND = 3016;3543pub const CORE_DRIVER_PACKAGE_NOT_FOUND = 3016;
3544
2364/// The requested operation failed. A system reboot is required to roll back changes made.3545/// The requested operation failed. A system reboot is required to roll back changes made.
2365pub const FAIL_REBOOT_REQUIRED = 3017;3546pub const FAIL_REBOOT_REQUIRED = 3017;
3547
2366/// The requested operation failed. A system reboot has been initiated to roll back changes made.3548/// The requested operation failed. A system reboot has been initiated to roll back changes made.
2367pub const FAIL_REBOOT_INITIATED = 3018;3549pub const FAIL_REBOOT_INITIATED = 3018;
3550
2368/// The specified printer driver was not found on the system and needs to be downloaded.3551/// The specified printer driver was not found on the system and needs to be downloaded.
2369pub const PRINTER_DRIVER_DOWNLOAD_NEEDED = 3019;3552pub const PRINTER_DRIVER_DOWNLOAD_NEEDED = 3019;
3553
2370/// The requested print job has failed to print. A print system update requires the job to be resubmitted.3554/// The requested print job has failed to print. A print system update requires the job to be resubmitted.
2371pub const PRINT_JOB_RESTART_REQUIRED = 3020;3555pub const PRINT_JOB_RESTART_REQUIRED = 3020;
3556
2372/// The printer driver does not contain a valid manifest, or contains too many manifests.3557/// The printer driver does not contain a valid manifest, or contains too many manifests.
2373pub const INVALID_PRINTER_DRIVER_MANIFEST = 3021;3558pub const INVALID_PRINTER_DRIVER_MANIFEST = 3021;
3559
2374/// The specified printer cannot be shared.3560/// The specified printer cannot be shared.
2375pub const PRINTER_NOT_SHAREABLE = 3022;3561pub const PRINTER_NOT_SHAREABLE = 3022;
3562
2376/// The operation was paused.3563/// The operation was paused.
2377pub const REQUEST_PAUSED = 3050;3564pub const REQUEST_PAUSED = 3050;
3565
2378/// Reissue the given operation as a cached IO operation.3566/// Reissue the given operation as a cached IO operation.
2379pub const IO_REISSUE_AS_CACHED = 3950;3567pub const IO_REISSUE_AS_CACHED = 3950;
std/os/windows/index.zig+146-98
...@@ -1,33 +1,59 @@...@@ -1,33 +1,59 @@
1pub const ERROR = @import("error.zig");1pub const ERROR = @import("error.zig");
22
3pub extern "advapi32" stdcallcc fn CryptAcquireContextA(phProv: &HCRYPTPROV, pszContainer: ?LPCSTR,3pub extern "advapi32" stdcallcc fn CryptAcquireContextA(
4 pszProvider: ?LPCSTR, dwProvType: DWORD, dwFlags: DWORD) BOOL;4 phProv: *HCRYPTPROV,
5 pszContainer: ?LPCSTR,
6 pszProvider: ?LPCSTR,
7 dwProvType: DWORD,
8 dwFlags: DWORD,
9) BOOL;
510
6pub extern "advapi32" stdcallcc fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) BOOL;11pub extern "advapi32" stdcallcc fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) BOOL;
712
8pub extern "advapi32" stdcallcc fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: &BYTE) BOOL;13pub extern "advapi32" stdcallcc fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: [*]BYTE) BOOL;
9
1014
11pub extern "kernel32" stdcallcc fn CloseHandle(hObject: HANDLE) BOOL;15pub extern "kernel32" stdcallcc fn CloseHandle(hObject: HANDLE) BOOL;
1216
13pub extern "kernel32" stdcallcc fn CreateDirectoryA(lpPathName: LPCSTR,17pub extern "kernel32" stdcallcc fn CreateDirectoryA(
14 lpSecurityAttributes: ?&SECURITY_ATTRIBUTES) BOOL;18 lpPathName: LPCSTR,
1519 lpSecurityAttributes: ?*SECURITY_ATTRIBUTES,
16pub extern "kernel32" stdcallcc fn CreateFileA(lpFileName: LPCSTR, dwDesiredAccess: DWORD,20) BOOL;
17 dwShareMode: DWORD, lpSecurityAttributes: ?LPSECURITY_ATTRIBUTES, dwCreationDisposition: DWORD,21
18 dwFlagsAndAttributes: DWORD, hTemplateFile: ?HANDLE) HANDLE;22pub extern "kernel32" stdcallcc fn CreateFileA(
1923 lpFileName: LPCSTR,
20pub extern "kernel32" stdcallcc fn CreatePipe(hReadPipe: &HANDLE, hWritePipe: &HANDLE,24 dwDesiredAccess: DWORD,
21 lpPipeAttributes: &const SECURITY_ATTRIBUTES, nSize: DWORD) BOOL;25 dwShareMode: DWORD,
2226 lpSecurityAttributes: ?LPSECURITY_ATTRIBUTES,
23pub extern "kernel32" stdcallcc fn CreateProcessA(lpApplicationName: ?LPCSTR, lpCommandLine: LPSTR,27 dwCreationDisposition: DWORD,
24 lpProcessAttributes: ?&SECURITY_ATTRIBUTES, lpThreadAttributes: ?&SECURITY_ATTRIBUTES, bInheritHandles: BOOL,28 dwFlagsAndAttributes: DWORD,
25 dwCreationFlags: DWORD, lpEnvironment: ?&c_void, lpCurrentDirectory: ?LPCSTR, lpStartupInfo: &STARTUPINFOA,29 hTemplateFile: ?HANDLE,
26 lpProcessInformation: &PROCESS_INFORMATION) BOOL;30) HANDLE;
2731
28pub extern "kernel32" stdcallcc fn CreateSymbolicLinkA(lpSymlinkFileName: LPCSTR, lpTargetFileName: LPCSTR,32pub extern "kernel32" stdcallcc fn CreatePipe(
29 dwFlags: DWORD) BOOLEAN;33 hReadPipe: *HANDLE,
3034 hWritePipe: *HANDLE,
35 lpPipeAttributes: *const SECURITY_ATTRIBUTES,
36 nSize: DWORD,
37) BOOL;
38
39pub extern "kernel32" stdcallcc fn CreateProcessA(
40 lpApplicationName: ?LPCSTR,
41 lpCommandLine: LPSTR,
42 lpProcessAttributes: ?*SECURITY_ATTRIBUTES,
43 lpThreadAttributes: ?*SECURITY_ATTRIBUTES,
44 bInheritHandles: BOOL,
45 dwCreationFlags: DWORD,
46 lpEnvironment: ?*c_void,
47 lpCurrentDirectory: ?LPCSTR,
48 lpStartupInfo: *STARTUPINFOA,
49 lpProcessInformation: *PROCESS_INFORMATION,
50) BOOL;
51
52pub extern "kernel32" stdcallcc fn CreateSymbolicLinkA(
53 lpSymlinkFileName: LPCSTR,
54 lpTargetFileName: LPCSTR,
55 dwFlags: DWORD,
56) BOOLEAN;
3157
32pub extern "kernel32" stdcallcc fn CreateThread(lpThreadAttributes: ?LPSECURITY_ATTRIBUTES, dwStackSize: SIZE_T, lpStartAddress: LPTHREAD_START_ROUTINE, lpParameter: ?LPVOID, dwCreationFlags: DWORD, lpThreadId: ?LPDWORD) ?HANDLE;58pub extern "kernel32" stdcallcc fn CreateThread(lpThreadAttributes: ?LPSECURITY_ATTRIBUTES, dwStackSize: SIZE_T, lpStartAddress: LPTHREAD_START_ROUTINE, lpParameter: ?LPVOID, dwCreationFlags: DWORD, lpThreadId: ?LPDWORD) ?HANDLE;
3359
...@@ -35,66 +61,84 @@ pub extern "kernel32" stdcallcc fn DeleteFileA(lpFileName: LPCSTR) BOOL;...@@ -35,66 +61,84 @@ pub extern "kernel32" stdcallcc fn DeleteFileA(lpFileName: LPCSTR) BOOL;
3561
36pub extern "kernel32" stdcallcc fn ExitProcess(exit_code: UINT) noreturn;62pub extern "kernel32" stdcallcc fn ExitProcess(exit_code: UINT) noreturn;
3763
38pub extern "kernel32" stdcallcc fn FreeEnvironmentStringsA(penv: LPCH) BOOL;64pub extern "kernel32" stdcallcc fn FreeEnvironmentStringsA(penv: [*]u8) BOOL;
3965
40pub extern "kernel32" stdcallcc fn GetCommandLineA() LPSTR;66pub extern "kernel32" stdcallcc fn GetCommandLineA() LPSTR;
4167
42pub extern "kernel32" stdcallcc fn GetConsoleMode(in_hConsoleHandle: HANDLE, out_lpMode: &DWORD) BOOL;68pub extern "kernel32" stdcallcc fn GetConsoleMode(in_hConsoleHandle: HANDLE, out_lpMode: *DWORD) BOOL;
4369
44pub extern "kernel32" stdcallcc fn GetCurrentDirectoryA(nBufferLength: WORD, lpBuffer: ?LPSTR) DWORD;70pub extern "kernel32" stdcallcc fn GetCurrentDirectoryA(nBufferLength: WORD, lpBuffer: ?LPSTR) DWORD;
4571
46pub extern "kernel32" stdcallcc fn GetEnvironmentStringsA() ?LPCH;72pub extern "kernel32" stdcallcc fn GetEnvironmentStringsA() ?[*]u8;
4773
48pub extern "kernel32" stdcallcc fn GetEnvironmentVariableA(lpName: LPCSTR, lpBuffer: LPSTR, nSize: DWORD) DWORD;74pub extern "kernel32" stdcallcc fn GetEnvironmentVariableA(lpName: LPCSTR, lpBuffer: LPSTR, nSize: DWORD) DWORD;
4975
50pub extern "kernel32" stdcallcc fn GetExitCodeProcess(hProcess: HANDLE, lpExitCode: &DWORD) BOOL;76pub extern "kernel32" stdcallcc fn GetExitCodeProcess(hProcess: HANDLE, lpExitCode: *DWORD) BOOL;
5177
52pub extern "kernel32" stdcallcc fn GetFileSizeEx(hFile: HANDLE, lpFileSize: &LARGE_INTEGER) BOOL;78pub extern "kernel32" stdcallcc fn GetFileSizeEx(hFile: HANDLE, lpFileSize: *LARGE_INTEGER) BOOL;
5379
54pub extern "kernel32" stdcallcc fn GetModuleFileNameA(hModule: ?HMODULE, lpFilename: LPSTR, nSize: DWORD) DWORD;80pub extern "kernel32" stdcallcc fn GetModuleFileNameA(hModule: ?HMODULE, lpFilename: LPSTR, nSize: DWORD) DWORD;
5581
56pub extern "kernel32" stdcallcc fn GetLastError() DWORD;82pub extern "kernel32" stdcallcc fn GetLastError() DWORD;
5783
58pub extern "kernel32" stdcallcc fn GetFileInformationByHandleEx(in_hFile: HANDLE,84pub extern "kernel32" stdcallcc fn GetFileInformationByHandleEx(
59 in_FileInformationClass: FILE_INFO_BY_HANDLE_CLASS, out_lpFileInformation: &c_void,85 in_hFile: HANDLE,
60 in_dwBufferSize: DWORD) BOOL;86 in_FileInformationClass: FILE_INFO_BY_HANDLE_CLASS,
6187 out_lpFileInformation: *c_void,
62pub extern "kernel32" stdcallcc fn GetFinalPathNameByHandleA(hFile: HANDLE, lpszFilePath: LPSTR,88 in_dwBufferSize: DWORD,
63 cchFilePath: DWORD, dwFlags: DWORD) DWORD;89) BOOL;
90
91pub extern "kernel32" stdcallcc fn GetFinalPathNameByHandleA(
92 hFile: HANDLE,
93 lpszFilePath: LPSTR,
94 cchFilePath: DWORD,
95 dwFlags: DWORD,
96) DWORD;
6497
65pub extern "kernel32" stdcallcc fn GetProcessHeap() ?HANDLE;98pub extern "kernel32" stdcallcc fn GetProcessHeap() ?HANDLE;
6699
67pub extern "kernel32" stdcallcc fn GetSystemTimeAsFileTime(?&FILETIME) void;100pub extern "kernel32" stdcallcc fn GetSystemTimeAsFileTime(?*FILETIME) void;
68101
69pub extern "kernel32" stdcallcc fn HeapCreate(flOptions: DWORD, dwInitialSize: SIZE_T, dwMaximumSize: SIZE_T) ?HANDLE;102pub extern "kernel32" stdcallcc fn HeapCreate(flOptions: DWORD, dwInitialSize: SIZE_T, dwMaximumSize: SIZE_T) ?HANDLE;
70pub extern "kernel32" stdcallcc fn HeapDestroy(hHeap: HANDLE) BOOL;103pub extern "kernel32" stdcallcc fn HeapDestroy(hHeap: HANDLE) BOOL;
71pub extern "kernel32" stdcallcc fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: &c_void, dwBytes: SIZE_T) ?&c_void;104pub extern "kernel32" stdcallcc fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: [*]c_void, dwBytes: SIZE_T) ?[*]c_void;
72pub extern "kernel32" stdcallcc fn HeapSize(hHeap: HANDLE, dwFlags: DWORD, lpMem: &const c_void) SIZE_T;105pub extern "kernel32" stdcallcc fn HeapSize(hHeap: HANDLE, dwFlags: DWORD, lpMem: [*]const c_void) SIZE_T;
73pub extern "kernel32" stdcallcc fn HeapValidate(hHeap: HANDLE, dwFlags: DWORD, lpMem: &const c_void) BOOL;106pub extern "kernel32" stdcallcc fn HeapValidate(hHeap: HANDLE, dwFlags: DWORD, lpMem: [*]const c_void) BOOL;
74pub extern "kernel32" stdcallcc fn HeapCompact(hHeap: HANDLE, dwFlags: DWORD) SIZE_T;107pub extern "kernel32" stdcallcc fn HeapCompact(hHeap: HANDLE, dwFlags: DWORD) SIZE_T;
75pub extern "kernel32" stdcallcc fn HeapSummary(hHeap: HANDLE, dwFlags: DWORD, lpSummary: LPHEAP_SUMMARY) BOOL;108pub extern "kernel32" stdcallcc fn HeapSummary(hHeap: HANDLE, dwFlags: DWORD, lpSummary: LPHEAP_SUMMARY) BOOL;
76109
77pub extern "kernel32" stdcallcc fn GetStdHandle(in_nStdHandle: DWORD) ?HANDLE;110pub extern "kernel32" stdcallcc fn GetStdHandle(in_nStdHandle: DWORD) ?HANDLE;
78111
79pub extern "kernel32" stdcallcc fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) ?&c_void;112pub extern "kernel32" stdcallcc fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) ?[*]c_void;
80113
81pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: &c_void) BOOL;114pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: [*]c_void) BOOL;
82115
83pub extern "kernel32" stdcallcc fn MoveFileExA(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR,116pub extern "kernel32" stdcallcc fn MoveFileExA(
84 dwFlags: DWORD) BOOL;117 lpExistingFileName: LPCSTR,
85 118 lpNewFileName: LPCSTR,
86pub extern "kernel32" stdcallcc fn QueryPerformanceCounter(lpPerformanceCount: &LARGE_INTEGER) BOOL;119 dwFlags: DWORD,
120) BOOL;
87121
88pub extern "kernel32" stdcallcc fn QueryPerformanceFrequency(lpFrequency: &LARGE_INTEGER) BOOL;122pub extern "kernel32" stdcallcc fn QueryPerformanceCounter(lpPerformanceCount: *LARGE_INTEGER) BOOL;
89123
90pub extern "kernel32" stdcallcc fn PathFileExists(pszPath: ?LPCTSTR) BOOL;124pub extern "kernel32" stdcallcc fn QueryPerformanceFrequency(lpFrequency: *LARGE_INTEGER) BOOL;
91125
92pub extern "kernel32" stdcallcc fn ReadFile(in_hFile: HANDLE, out_lpBuffer: &c_void,126pub extern "kernel32" stdcallcc fn PathFileExists(pszPath: ?LPCTSTR) BOOL;
93 in_nNumberOfBytesToRead: DWORD, out_lpNumberOfBytesRead: &DWORD,
94 in_out_lpOverlapped: ?&OVERLAPPED) BOOL;
95127
96pub extern "kernel32" stdcallcc fn SetFilePointerEx(in_fFile: HANDLE, in_liDistanceToMove: LARGE_INTEGER, 128pub extern "kernel32" stdcallcc fn ReadFile(
97 out_opt_ldNewFilePointer: ?&LARGE_INTEGER, in_dwMoveMethod: DWORD) BOOL;129 in_hFile: HANDLE,
130 out_lpBuffer: [*]c_void,
131 in_nNumberOfBytesToRead: DWORD,
132 out_lpNumberOfBytesRead: *DWORD,
133 in_out_lpOverlapped: ?*OVERLAPPED,
134) BOOL;
135
136pub extern "kernel32" stdcallcc fn SetFilePointerEx(
137 in_fFile: HANDLE,
138 in_liDistanceToMove: LARGE_INTEGER,
139 out_opt_ldNewFilePointer: ?*LARGE_INTEGER,
140 in_dwMoveMethod: DWORD,
141) BOOL;
98142
99pub extern "kernel32" stdcallcc fn SetHandleInformation(hObject: HANDLE, dwMask: DWORD, dwFlags: DWORD) BOOL;143pub extern "kernel32" stdcallcc fn SetHandleInformation(hObject: HANDLE, dwMask: DWORD, dwFlags: DWORD) BOOL;
100144
...@@ -104,14 +148,18 @@ pub extern "kernel32" stdcallcc fn TerminateProcess(hProcess: HANDLE, uExitCode:...@@ -104,14 +148,18 @@ pub extern "kernel32" stdcallcc fn TerminateProcess(hProcess: HANDLE, uExitCode:
104148
105pub extern "kernel32" stdcallcc fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) DWORD;149pub extern "kernel32" stdcallcc fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) DWORD;
106150
107pub extern "kernel32" stdcallcc fn WriteFile(in_hFile: HANDLE, in_lpBuffer: &const c_void,151pub extern "kernel32" stdcallcc fn WriteFile(
108 in_nNumberOfBytesToWrite: DWORD, out_lpNumberOfBytesWritten: ?&DWORD,152 in_hFile: HANDLE,
109 in_out_lpOverlapped: ?&OVERLAPPED) BOOL;153 in_lpBuffer: [*]const c_void,
154 in_nNumberOfBytesToWrite: DWORD,
155 out_lpNumberOfBytesWritten: ?*DWORD,
156 in_out_lpOverlapped: ?*OVERLAPPED,
157) BOOL;
110158
111//TODO: call unicode versions instead of relying on ANSI code page159//TODO: call unicode versions instead of relying on ANSI code page
112pub extern "kernel32" stdcallcc fn LoadLibraryA(lpLibFileName: LPCSTR) ?HMODULE;160pub extern "kernel32" stdcallcc fn LoadLibraryA(lpLibFileName: LPCSTR) ?HMODULE;
113161
114pub extern "kernel32" stdcallcc fn FreeLibrary(hModule: HMODULE) BOOL; 162pub extern "kernel32" stdcallcc fn FreeLibrary(hModule: HMODULE) BOOL;
115163
116pub extern "user32" stdcallcc fn MessageBoxA(hWnd: ?HANDLE, lpText: ?LPCTSTR, lpCaption: ?LPCTSTR, uType: UINT) c_int;164pub extern "user32" stdcallcc fn MessageBoxA(hWnd: ?HANDLE, lpText: ?LPCTSTR, lpCaption: ?LPCTSTR, uType: UINT) c_int;
117165
...@@ -123,23 +171,23 @@ pub const BYTE = u8;...@@ -123,23 +171,23 @@ pub const BYTE = u8;
123pub const CHAR = u8;171pub const CHAR = u8;
124pub const DWORD = u32;172pub const DWORD = u32;
125pub const FLOAT = f32;173pub const FLOAT = f32;
126pub const HANDLE = &c_void;174pub const HANDLE = *c_void;
127pub const HCRYPTPROV = ULONG_PTR;175pub const HCRYPTPROV = ULONG_PTR;
128pub const HINSTANCE = &@OpaqueType();176pub const HINSTANCE = *@OpaqueType();
129pub const HMODULE = &@OpaqueType();177pub const HMODULE = *@OpaqueType();
130pub const INT = c_int;178pub const INT = c_int;
131pub const LPBYTE = &BYTE;179pub const LPBYTE = *BYTE;
132pub const LPCH = &CHAR;180pub const LPCH = *CHAR;
133pub const LPCSTR = &const CHAR;181pub const LPCSTR = [*]const CHAR;
134pub const LPCTSTR = &const TCHAR;182pub const LPCTSTR = [*]const TCHAR;
135pub const LPCVOID = &const c_void;183pub const LPCVOID = *const c_void;
136pub const LPDWORD = &DWORD;184pub const LPDWORD = *DWORD;
137pub const LPSTR = &CHAR;185pub const LPSTR = [*]CHAR;
138pub const LPTSTR = if (UNICODE) LPWSTR else LPSTR;186pub const LPTSTR = if (UNICODE) LPWSTR else LPSTR;
139pub const LPVOID = &c_void;187pub const LPVOID = *c_void;
140pub const LPWSTR = &WCHAR;188pub const LPWSTR = [*]WCHAR;
141pub const PVOID = &c_void;189pub const PVOID = *c_void;
142pub const PWSTR = &WCHAR;190pub const PWSTR = [*]WCHAR;
143pub const SIZE_T = usize;191pub const SIZE_T = usize;
144pub const TCHAR = if (UNICODE) WCHAR else u8;192pub const TCHAR = if (UNICODE) WCHAR else u8;
145pub const UINT = c_uint;193pub const UINT = c_uint;
...@@ -170,63 +218,64 @@ pub const OVERLAPPED = extern struct {...@@ -170,63 +218,64 @@ pub const OVERLAPPED = extern struct {
170 Pointer: PVOID,218 Pointer: PVOID,
171 hEvent: HANDLE,219 hEvent: HANDLE,
172};220};
173pub const LPOVERLAPPED = &OVERLAPPED;221pub const LPOVERLAPPED = *OVERLAPPED;
174222
175pub const MAX_PATH = 260;223pub const MAX_PATH = 260;
176224
177// TODO issue #305225// TODO issue #305
178pub const FILE_INFO_BY_HANDLE_CLASS = u32;226pub const FILE_INFO_BY_HANDLE_CLASS = u32;
179pub const FileBasicInfo = 0;227pub const FileBasicInfo = 0;
180pub const FileStandardInfo = 1;228pub const FileStandardInfo = 1;
181pub const FileNameInfo = 2;229pub const FileNameInfo = 2;
182pub const FileRenameInfo = 3;230pub const FileRenameInfo = 3;
183pub const FileDispositionInfo = 4;231pub const FileDispositionInfo = 4;
184pub const FileAllocationInfo = 5;232pub const FileAllocationInfo = 5;
185pub const FileEndOfFileInfo = 6;233pub const FileEndOfFileInfo = 6;
186pub const FileStreamInfo = 7;234pub const FileStreamInfo = 7;
187pub const FileCompressionInfo = 8;235pub const FileCompressionInfo = 8;
188pub const FileAttributeTagInfo = 9;236pub const FileAttributeTagInfo = 9;
189pub const FileIdBothDirectoryInfo = 10;237pub const FileIdBothDirectoryInfo = 10;
190pub const FileIdBothDirectoryRestartInfo = 11;238pub const FileIdBothDirectoryRestartInfo = 11;
191pub const FileIoPriorityHintInfo = 12;239pub const FileIoPriorityHintInfo = 12;
192pub const FileRemoteProtocolInfo = 13;240pub const FileRemoteProtocolInfo = 13;
193pub const FileFullDirectoryInfo = 14;241pub const FileFullDirectoryInfo = 14;
194pub const FileFullDirectoryRestartInfo = 15;242pub const FileFullDirectoryRestartInfo = 15;
195pub const FileStorageInfo = 16;243pub const FileStorageInfo = 16;
196pub const FileAlignmentInfo = 17;244pub const FileAlignmentInfo = 17;
197pub const FileIdInfo = 18;245pub const FileIdInfo = 18;
198pub const FileIdExtdDirectoryInfo = 19;246pub const FileIdExtdDirectoryInfo = 19;
199pub const FileIdExtdDirectoryRestartInfo = 20;247pub const FileIdExtdDirectoryRestartInfo = 20;
200248
201pub const FILE_NAME_INFO = extern struct {249pub const FILE_NAME_INFO = extern struct {
202 FileNameLength: DWORD,250 FileNameLength: DWORD,
203 FileName: [1]WCHAR,251 FileName: [1]WCHAR,
204};252};
205253
206
207/// Return the normalized drive name. This is the default.254/// Return the normalized drive name. This is the default.
208pub const FILE_NAME_NORMALIZED = 0x0;255pub const FILE_NAME_NORMALIZED = 0x0;
256
209/// Return the opened file name (not normalized).257/// Return the opened file name (not normalized).
210pub const FILE_NAME_OPENED = 0x8;258pub const FILE_NAME_OPENED = 0x8;
211259
212/// Return the path with the drive letter. This is the default.260/// Return the path with the drive letter. This is the default.
213pub const VOLUME_NAME_DOS = 0x0;261pub const VOLUME_NAME_DOS = 0x0;
262
214/// Return the path with a volume GUID path instead of the drive name.263/// Return the path with a volume GUID path instead of the drive name.
215pub const VOLUME_NAME_GUID = 0x1;264pub const VOLUME_NAME_GUID = 0x1;
265
216/// Return the path with no drive information.266/// Return the path with no drive information.
217pub const VOLUME_NAME_NONE = 0x4;267pub const VOLUME_NAME_NONE = 0x4;
268
218/// Return the path with the volume device path.269/// Return the path with the volume device path.
219pub const VOLUME_NAME_NT = 0x2;270pub const VOLUME_NAME_NT = 0x2;
220271
221
222pub const SECURITY_ATTRIBUTES = extern struct {272pub const SECURITY_ATTRIBUTES = extern struct {
223 nLength: DWORD,273 nLength: DWORD,
224 lpSecurityDescriptor: ?&c_void,274 lpSecurityDescriptor: ?*c_void,
225 bInheritHandle: BOOL,275 bInheritHandle: BOOL,
226};276};
227pub const PSECURITY_ATTRIBUTES = &SECURITY_ATTRIBUTES;277pub const PSECURITY_ATTRIBUTES = *SECURITY_ATTRIBUTES;
228pub const LPSECURITY_ATTRIBUTES = &SECURITY_ATTRIBUTES;278pub const LPSECURITY_ATTRIBUTES = *SECURITY_ATTRIBUTES;
229
230279
231pub const GENERIC_READ = 0x80000000;280pub const GENERIC_READ = 0x80000000;
232pub const GENERIC_WRITE = 0x40000000;281pub const GENERIC_WRITE = 0x40000000;
...@@ -243,7 +292,6 @@ pub const OPEN_ALWAYS = 4;...@@ -243,7 +292,6 @@ pub const OPEN_ALWAYS = 4;
243pub const OPEN_EXISTING = 3;292pub const OPEN_EXISTING = 3;
244pub const TRUNCATE_EXISTING = 5;293pub const TRUNCATE_EXISTING = 5;
245294
246
247pub const FILE_ATTRIBUTE_ARCHIVE = 0x20;295pub const FILE_ATTRIBUTE_ARCHIVE = 0x20;
248pub const FILE_ATTRIBUTE_ENCRYPTED = 0x4000;296pub const FILE_ATTRIBUTE_ENCRYPTED = 0x4000;
249pub const FILE_ATTRIBUTE_HIDDEN = 0x2;297pub const FILE_ATTRIBUTE_HIDDEN = 0x2;
...@@ -321,7 +369,7 @@ pub const HEAP_CREATE_ENABLE_EXECUTE = 0x00040000;...@@ -321,7 +369,7 @@ pub const HEAP_CREATE_ENABLE_EXECUTE = 0x00040000;
321pub const HEAP_GENERATE_EXCEPTIONS = 0x00000004;369pub const HEAP_GENERATE_EXCEPTIONS = 0x00000004;
322pub const HEAP_NO_SERIALIZE = 0x00000001;370pub const HEAP_NO_SERIALIZE = 0x00000001;
323371
324pub const PTHREAD_START_ROUTINE = extern fn(LPVOID) DWORD;372pub const PTHREAD_START_ROUTINE = extern fn (LPVOID) DWORD;
325pub const LPTHREAD_START_ROUTINE = PTHREAD_START_ROUTINE;373pub const LPTHREAD_START_ROUTINE = PTHREAD_START_ROUTINE;
326374
327test "import" {375test "import" {
std/os/windows/util.zig+23-24
...@@ -7,7 +7,7 @@ const mem = std.mem;...@@ -7,7 +7,7 @@ const mem = std.mem;
7const BufMap = std.BufMap;7const BufMap = std.BufMap;
8const cstr = std.cstr;8const cstr = std.cstr;
99
10pub const WaitError = error {10pub const WaitError = error{
11 WaitAbandoned,11 WaitAbandoned,
12 WaitTimeOut,12 WaitTimeOut,
13 Unexpected,13 Unexpected,
...@@ -33,7 +33,7 @@ pub fn windowsClose(handle: windows.HANDLE) void {...@@ -33,7 +33,7 @@ pub fn windowsClose(handle: windows.HANDLE) void {
33 assert(windows.CloseHandle(handle) != 0);33 assert(windows.CloseHandle(handle) != 0);
34}34}
3535
36pub const WriteError = error {36pub const WriteError = error{
37 SystemResources,37 SystemResources,
38 OperationAborted,38 OperationAborted,
39 IoPending,39 IoPending,
...@@ -42,7 +42,7 @@ pub const WriteError = error {...@@ -42,7 +42,7 @@ pub const WriteError = error {
42};42};
4343
44pub fn windowsWrite(handle: windows.HANDLE, bytes: []const u8) WriteError!void {44pub fn windowsWrite(handle: windows.HANDLE, bytes: []const u8) WriteError!void {
45 if (windows.WriteFile(handle, @ptrCast(&const c_void, bytes.ptr), u32(bytes.len), null, null) == 0) {45 if (windows.WriteFile(handle, @ptrCast([*]const c_void, bytes.ptr), u32(bytes.len), null, null) == 0) {
46 const err = windows.GetLastError();46 const err = windows.GetLastError();
47 return switch (err) {47 return switch (err) {
48 windows.ERROR.INVALID_USER_BUFFER => WriteError.SystemResources,48 windows.ERROR.INVALID_USER_BUFFER => WriteError.SystemResources,
...@@ -68,20 +68,18 @@ pub fn windowsIsCygwinPty(handle: windows.HANDLE) bool {...@@ -68,20 +68,18 @@ pub fn windowsIsCygwinPty(handle: windows.HANDLE) bool {
68 const size = @sizeOf(windows.FILE_NAME_INFO);68 const size = @sizeOf(windows.FILE_NAME_INFO);
69 var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = []u8{0} ** (size + windows.MAX_PATH);69 var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = []u8{0} ** (size + windows.MAX_PATH);
7070
71 if (windows.GetFileInformationByHandleEx(handle, windows.FileNameInfo,71 if (windows.GetFileInformationByHandleEx(handle, windows.FileNameInfo, @ptrCast(*c_void, &name_info_bytes[0]), u32(name_info_bytes.len)) == 0) {
72 @ptrCast(&c_void, &name_info_bytes[0]), u32(name_info_bytes.len)) == 0)
73 {
74 return true;72 return true;
75 }73 }
7674
77 const name_info = @ptrCast(&const windows.FILE_NAME_INFO, &name_info_bytes[0]);75 const name_info = @ptrCast(*const windows.FILE_NAME_INFO, &name_info_bytes[0]);
78 const name_bytes = name_info_bytes[size..size + usize(name_info.FileNameLength)];76 const name_bytes = name_info_bytes[size .. size + usize(name_info.FileNameLength)];
79 const name_wide = ([]u16)(name_bytes);77 const name_wide = ([]u16)(name_bytes);
80 return mem.indexOf(u16, name_wide, []u16{'m','s','y','s','-'}) != null or78 return mem.indexOf(u16, name_wide, []u16{ 'm', 's', 'y', 's', '-' }) != null or
81 mem.indexOf(u16, name_wide, []u16{'-','p','t','y'}) != null;79 mem.indexOf(u16, name_wide, []u16{ '-', 'p', 't', 'y' }) != null;
82}80}
8381
84pub const OpenError = error {82pub const OpenError = error{
85 SharingViolation,83 SharingViolation,
86 PathAlreadyExists,84 PathAlreadyExists,
87 FileNotFound,85 FileNotFound,
...@@ -92,15 +90,18 @@ pub const OpenError = error {...@@ -92,15 +90,18 @@ pub const OpenError = error {
92};90};
9391
94/// `file_path` needs to be copied in memory to add a null terminating byte, hence the allocator.92/// `file_path` needs to be copied in memory to add a null terminating byte, hence the allocator.
95pub fn windowsOpen(allocator: &mem.Allocator, file_path: []const u8, desired_access: windows.DWORD, share_mode: windows.DWORD,93pub fn windowsOpen(
96 creation_disposition: windows.DWORD, flags_and_attrs: windows.DWORD)94 allocator: *mem.Allocator,
97 OpenError!windows.HANDLE95 file_path: []const u8,
98{96 desired_access: windows.DWORD,
97 share_mode: windows.DWORD,
98 creation_disposition: windows.DWORD,
99 flags_and_attrs: windows.DWORD,
100) OpenError!windows.HANDLE {
99 const path_with_null = try cstr.addNullByte(allocator, file_path);101 const path_with_null = try cstr.addNullByte(allocator, file_path);
100 defer allocator.free(path_with_null);102 defer allocator.free(path_with_null);
101103
102 const result = windows.CreateFileA(path_with_null.ptr, desired_access, share_mode, null, creation_disposition,104 const result = windows.CreateFileA(path_with_null.ptr, desired_access, share_mode, null, creation_disposition, flags_and_attrs, null);
103 flags_and_attrs, null);
104105
105 if (result == windows.INVALID_HANDLE_VALUE) {106 if (result == windows.INVALID_HANDLE_VALUE) {
106 const err = windows.GetLastError();107 const err = windows.GetLastError();
...@@ -118,7 +119,7 @@ pub fn windowsOpen(allocator: &mem.Allocator, file_path: []const u8, desired_acc...@@ -118,7 +119,7 @@ pub fn windowsOpen(allocator: &mem.Allocator, file_path: []const u8, desired_acc
118}119}
119120
120/// Caller must free result.121/// Caller must free result.
121pub fn createWindowsEnvBlock(allocator: &mem.Allocator, env_map: &const BufMap) ![]u8 {122pub fn createWindowsEnvBlock(allocator: *mem.Allocator, env_map: *const BufMap) ![]u8 {
122 // count bytes needed123 // count bytes needed
123 const bytes_needed = x: {124 const bytes_needed = x: {
124 var bytes_needed: usize = 1; // 1 for the final null byte125 var bytes_needed: usize = 1; // 1 for the final null byte
...@@ -149,25 +150,23 @@ pub fn createWindowsEnvBlock(allocator: &mem.Allocator, env_map: &const BufMap)...@@ -149,25 +150,23 @@ pub fn createWindowsEnvBlock(allocator: &mem.Allocator, env_map: &const BufMap)
149 return result;150 return result;
150}151}
151152
152pub fn windowsLoadDll(allocator: &mem.Allocator, dll_path: []const u8) !windows.HMODULE {153pub fn windowsLoadDll(allocator: *mem.Allocator, dll_path: []const u8) !windows.HMODULE {
153 const padded_buff = try cstr.addNullByte(allocator, dll_path);154 const padded_buff = try cstr.addNullByte(allocator, dll_path);
154 defer allocator.free(padded_buff);155 defer allocator.free(padded_buff);
155 return windows.LoadLibraryA(padded_buff.ptr) ?? error.DllNotFound;156 return windows.LoadLibraryA(padded_buff.ptr) ?? error.DllNotFound;
156}157}
157158
158pub fn windowsUnloadDll(hModule: windows.HMODULE) void {159pub fn windowsUnloadDll(hModule: windows.HMODULE) void {
159 assert(windows.FreeLibrary(hModule)!= 0);160 assert(windows.FreeLibrary(hModule) != 0);
160}161}
161162
162
163test "InvalidDll" {163test "InvalidDll" {
164 if (builtin.os != builtin.Os.windows) return;164 if (builtin.os != builtin.Os.windows) return;
165165
166 const DllName = "asdf.dll";166 const DllName = "asdf.dll";
167 const allocator = std.debug.global_allocator;167 const allocator = std.debug.global_allocator;
168 const handle = os.windowsLoadDll(allocator, DllName) catch |err| {168 const handle = os.windowsLoadDll(allocator, DllName) catch |err| {
169 assert(err == error.DllNotFound);169 assert(err == error.DllNotFound);
170 return;170 return;
171 };171 };
172}172}
173
std/os/zen.zig+86-72
...@@ -3,35 +3,35 @@...@@ -3,35 +3,35 @@
3//////////////////////////3//////////////////////////
44
5pub const Message = struct {5pub const Message = struct {
6 sender: MailboxId,6 sender: MailboxId,
7 receiver: MailboxId,7 receiver: MailboxId,
8 type: usize,8 type: usize,
9 payload: usize,9 payload: usize,
1010
11 pub fn from(mailbox_id: &const MailboxId) Message {11 pub fn from(mailbox_id: *const MailboxId) Message {
12 return Message {12 return Message{
13 .sender = MailboxId.Undefined,13 .sender = MailboxId.Undefined,
14 .receiver = *mailbox_id,14 .receiver = *mailbox_id,
15 .type = 0,15 .type = 0,
16 .payload = 0,16 .payload = 0,
17 };17 };
18 }18 }
1919
20 pub fn to(mailbox_id: &const MailboxId, msg_type: usize) Message {20 pub fn to(mailbox_id: *const MailboxId, msg_type: usize) Message {
21 return Message {21 return Message{
22 .sender = MailboxId.This,22 .sender = MailboxId.This,
23 .receiver = *mailbox_id,23 .receiver = *mailbox_id,
24 .type = msg_type,24 .type = msg_type,
25 .payload = 0,25 .payload = 0,
26 };26 };
27 }27 }
2828
29 pub fn withData(mailbox_id: &const MailboxId, msg_type: usize, payload: usize) Message {29 pub fn withData(mailbox_id: *const MailboxId, msg_type: usize, payload: usize) Message {
30 return Message {30 return Message{
31 .sender = MailboxId.This,31 .sender = MailboxId.This,
32 .receiver = *mailbox_id,32 .receiver = *mailbox_id,
33 .type = msg_type,33 .type = msg_type,
34 .payload = payload,34 .payload = payload,
35 };35 };
36 }36 }
37};37};
...@@ -40,27 +40,25 @@ pub const MailboxId = union(enum) {...@@ -40,27 +40,25 @@ pub const MailboxId = union(enum) {
40 Undefined,40 Undefined,
41 This,41 This,
42 Kernel,42 Kernel,
43 Port: u16,43 Port: u16,
44 Thread: u16,44 Thread: u16,
45};45};
4646
47
48//////////////////////////////////////47//////////////////////////////////////
49//// Ports reserved for servers ////48//// Ports reserved for servers ////
50//////////////////////////////////////49//////////////////////////////////////
5150
52pub const Server = struct {51pub const Server = struct {
53 pub const Keyboard = MailboxId { .Port = 0 };52 pub const Keyboard = MailboxId{ .Port = 0 };
54 pub const Terminal = MailboxId { .Port = 1 };53 pub const Terminal = MailboxId{ .Port = 1 };
55};54};
5655
57
58////////////////////////56////////////////////////
59//// POSIX things ////57//// POSIX things ////
60////////////////////////58////////////////////////
6159
62// Standard streams.60// Standard streams.
63pub const STDIN_FILENO = 0;61pub const STDIN_FILENO = 0;
64pub const STDOUT_FILENO = 1;62pub const STDOUT_FILENO = 1;
65pub const STDERR_FILENO = 2;63pub const STDERR_FILENO = 2;
6664
...@@ -69,7 +67,7 @@ pub const getErrno = @import("linux/index.zig").getErrno;...@@ -69,7 +67,7 @@ pub const getErrno = @import("linux/index.zig").getErrno;
69use @import("linux/errno.zig");67use @import("linux/errno.zig");
7068
71// TODO: implement this correctly.69// TODO: implement this correctly.
72pub fn read(fd: i32, buf: &u8, count: usize) usize {70pub fn read(fd: i32, buf: *u8, count: usize) usize {
73 switch (fd) {71 switch (fd) {
74 STDIN_FILENO => {72 STDIN_FILENO => {
75 var i: usize = 0;73 var i: usize = 0;
...@@ -77,7 +75,7 @@ pub fn read(fd: i32, buf: &u8, count: usize) usize {...@@ -77,7 +75,7 @@ pub fn read(fd: i32, buf: &u8, count: usize) usize {
77 send(Message.to(Server.Keyboard, 0));75 send(Message.to(Server.Keyboard, 0));
7876
79 var message = Message.from(MailboxId.This);77 var message = Message.from(MailboxId.This);
80 receive(&message);78 receive(*message);
8179
82 buf[i] = u8(message.payload);80 buf[i] = u8(message.payload);
83 }81 }
...@@ -88,7 +86,7 @@ pub fn read(fd: i32, buf: &u8, count: usize) usize {...@@ -88,7 +86,7 @@ pub fn read(fd: i32, buf: &u8, count: usize) usize {
88}86}
8987
90// TODO: implement this correctly.88// TODO: implement this correctly.
91pub fn write(fd: i32, buf: &const u8, count: usize) usize {89pub fn write(fd: i32, buf: *const u8, count: usize) usize {
92 switch (fd) {90 switch (fd) {
93 STDOUT_FILENO, STDERR_FILENO => {91 STDOUT_FILENO, STDERR_FILENO => {
94 var i: usize = 0;92 var i: usize = 0;
...@@ -101,26 +99,24 @@ pub fn write(fd: i32, buf: &const u8, count: usize) usize {...@@ -101,26 +99,24 @@ pub fn write(fd: i32, buf: &const u8, count: usize) usize {
101 return count;99 return count;
102}100}
103101
104
105///////////////////////////102///////////////////////////
106//// Syscall numbers ////103//// Syscall numbers ////
107///////////////////////////104///////////////////////////
108105
109pub const Syscall = enum(usize) {106pub const Syscall = enum(usize) {
110 exit = 0,107 exit = 0,
111 createPort = 1,108 createPort = 1,
112 send = 2,109 send = 2,
113 receive = 3,110 receive = 3,
114 subscribeIRQ = 4,111 subscribeIRQ = 4,
115 inb = 5,112 inb = 5,
116 map = 6,113 map = 6,
117 createThread = 7,114 createThread = 7,
118 createProcess = 8,115 createProcess = 8,
119 wait = 9,116 wait = 9,
120 portReady = 10,117 portReady = 10,
121};118};
122119
123
124////////////////////120////////////////////
125//// Syscalls ////121//// Syscalls ////
126////////////////////122////////////////////
...@@ -130,22 +126,22 @@ pub fn exit(status: i32) noreturn {...@@ -130,22 +126,22 @@ pub fn exit(status: i32) noreturn {
130 unreachable;126 unreachable;
131}127}
132128
133pub fn createPort(mailbox_id: &const MailboxId) void {129pub fn createPort(mailbox_id: *const MailboxId) void {
134 _ = switch (*mailbox_id) {130 _ = switch (*mailbox_id) {
135 MailboxId.Port => |id| syscall1(Syscall.createPort, id),131 MailboxId.Port => |id| syscall1(Syscall.createPort, id),
136 else => unreachable,132 else => unreachable,
137 };133 };
138}134}
139135
140pub fn send(message: &const Message) void {136pub fn send(message: *const Message) void {
141 _ = syscall1(Syscall.send, @ptrToInt(message));137 _ = syscall1(Syscall.send, @ptrToInt(message));
142}138}
143139
144pub fn receive(destination: &Message) void {140pub fn receive(destination: *Message) void {
145 _ = syscall1(Syscall.receive, @ptrToInt(destination));141 _ = syscall1(Syscall.receive, @ptrToInt(destination));
146}142}
147143
148pub fn subscribeIRQ(irq: u8, mailbox_id: &const MailboxId) void {144pub fn subscribeIRQ(irq: u8, mailbox_id: *const MailboxId) void {
149 _ = syscall2(Syscall.subscribeIRQ, irq, @ptrToInt(mailbox_id));145 _ = syscall2(Syscall.subscribeIRQ, irq, @ptrToInt(mailbox_id));
150}146}
151147
...@@ -157,7 +153,7 @@ pub fn map(v_addr: usize, p_addr: usize, size: usize, writable: bool) bool {...@@ -157,7 +153,7 @@ pub fn map(v_addr: usize, p_addr: usize, size: usize, writable: bool) bool {
157 return syscall4(Syscall.map, v_addr, p_addr, size, usize(writable)) != 0;153 return syscall4(Syscall.map, v_addr, p_addr, size, usize(writable)) != 0;
158}154}
159155
160pub fn createThread(function: fn()void) u16 {156pub fn createThread(function: fn () void) u16 {
161 return u16(syscall1(Syscall.createThread, @ptrToInt(function)));157 return u16(syscall1(Syscall.createThread, @ptrToInt(function)));
162}158}
163159
...@@ -180,66 +176,84 @@ pub fn portReady(port: u16) bool {...@@ -180,66 +176,84 @@ pub fn portReady(port: u16) bool {
180inline fn syscall0(number: Syscall) usize {176inline fn syscall0(number: Syscall) usize {
181 return asm volatile ("int $0x80"177 return asm volatile ("int $0x80"
182 : [ret] "={eax}" (-> usize)178 : [ret] "={eax}" (-> usize)
183 : [number] "{eax}" (number));179 : [number] "{eax}" (number)
180 );
184}181}
185182
186inline fn syscall1(number: Syscall, arg1: usize) usize {183inline fn syscall1(number: Syscall, arg1: usize) usize {
187 return asm volatile ("int $0x80"184 return asm volatile ("int $0x80"
188 : [ret] "={eax}" (-> usize)185 : [ret] "={eax}" (-> usize)
189 : [number] "{eax}" (number),186 : [number] "{eax}" (number),
190 [arg1] "{ecx}" (arg1));187 [arg1] "{ecx}" (arg1)
188 );
191}189}
192190
193inline fn syscall2(number: Syscall, arg1: usize, arg2: usize) usize {191inline fn syscall2(number: Syscall, arg1: usize, arg2: usize) usize {
194 return asm volatile ("int $0x80"192 return asm volatile ("int $0x80"
195 : [ret] "={eax}" (-> usize)193 : [ret] "={eax}" (-> usize)
196 : [number] "{eax}" (number),194 : [number] "{eax}" (number),
197 [arg1] "{ecx}" (arg1),195 [arg1] "{ecx}" (arg1),
198 [arg2] "{edx}" (arg2));196 [arg2] "{edx}" (arg2)
197 );
199}198}
200199
201inline fn syscall3(number: Syscall, arg1: usize, arg2: usize, arg3: usize) usize {200inline fn syscall3(number: Syscall, arg1: usize, arg2: usize, arg3: usize) usize {
202 return asm volatile ("int $0x80"201 return asm volatile ("int $0x80"
203 : [ret] "={eax}" (-> usize)202 : [ret] "={eax}" (-> usize)
204 : [number] "{eax}" (number),203 : [number] "{eax}" (number),
205 [arg1] "{ecx}" (arg1),204 [arg1] "{ecx}" (arg1),
206 [arg2] "{edx}" (arg2),205 [arg2] "{edx}" (arg2),
207 [arg3] "{ebx}" (arg3));206 [arg3] "{ebx}" (arg3)
207 );
208}208}
209209
210inline fn syscall4(number: Syscall, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {210inline fn syscall4(number: Syscall, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {
211 return asm volatile ("int $0x80"211 return asm volatile ("int $0x80"
212 : [ret] "={eax}" (-> usize)212 : [ret] "={eax}" (-> usize)
213 : [number] "{eax}" (number),213 : [number] "{eax}" (number),
214 [arg1] "{ecx}" (arg1),214 [arg1] "{ecx}" (arg1),
215 [arg2] "{edx}" (arg2),215 [arg2] "{edx}" (arg2),
216 [arg3] "{ebx}" (arg3),216 [arg3] "{ebx}" (arg3),
217 [arg4] "{esi}" (arg4));217 [arg4] "{esi}" (arg4)
218 );
218}219}
219220
220inline fn syscall5(number: Syscall, arg1: usize, arg2: usize, arg3: usize,221inline fn syscall5(
221 arg4: usize, arg5: usize) usize222 number: Syscall,
222{223 arg1: usize,
224 arg2: usize,
225 arg3: usize,
226 arg4: usize,
227 arg5: usize,
228) usize {
223 return asm volatile ("int $0x80"229 return asm volatile ("int $0x80"
224 : [ret] "={eax}" (-> usize)230 : [ret] "={eax}" (-> usize)
225 : [number] "{eax}" (number),231 : [number] "{eax}" (number),
226 [arg1] "{ecx}" (arg1),232 [arg1] "{ecx}" (arg1),
227 [arg2] "{edx}" (arg2),233 [arg2] "{edx}" (arg2),
228 [arg3] "{ebx}" (arg3),234 [arg3] "{ebx}" (arg3),
229 [arg4] "{esi}" (arg4),235 [arg4] "{esi}" (arg4),
230 [arg5] "{edi}" (arg5));236 [arg5] "{edi}" (arg5)
237 );
231}238}
232239
233inline fn syscall6(number: Syscall, arg1: usize, arg2: usize, arg3: usize,240inline fn syscall6(
234 arg4: usize, arg5: usize, arg6: usize) usize241 number: Syscall,
235{242 arg1: usize,
243 arg2: usize,
244 arg3: usize,
245 arg4: usize,
246 arg5: usize,
247 arg6: usize,
248) usize {
236 return asm volatile ("int $0x80"249 return asm volatile ("int $0x80"
237 : [ret] "={eax}" (-> usize)250 : [ret] "={eax}" (-> usize)
238 : [number] "{eax}" (number),251 : [number] "{eax}" (number),
239 [arg1] "{ecx}" (arg1),252 [arg1] "{ecx}" (arg1),
240 [arg2] "{edx}" (arg2),253 [arg2] "{edx}" (arg2),
241 [arg3] "{ebx}" (arg3),254 [arg3] "{ebx}" (arg3),
242 [arg4] "{esi}" (arg4),255 [arg4] "{esi}" (arg4),
243 [arg5] "{edi}" (arg5),256 [arg5] "{edi}" (arg5),
244 [arg6] "{ebp}" (arg6));257 [arg6] "{ebp}" (arg6)
258 );
245}259}
std/rand/index.zig+77-61
...@@ -28,15 +28,15 @@ pub const DefaultPrng = Xoroshiro128;...@@ -28,15 +28,15 @@ pub const DefaultPrng = Xoroshiro128;
28pub const DefaultCsprng = Isaac64;28pub const DefaultCsprng = Isaac64;
2929
30pub const Random = struct {30pub const Random = struct {
31 fillFn: fn(r: &Random, buf: []u8) void,31 fillFn: fn (r: *Random, buf: []u8) void,
3232
33 /// Read random bytes into the specified buffer until fill.33 /// Read random bytes into the specified buffer until fill.
34 pub fn bytes(r: &Random, buf: []u8) void {34 pub fn bytes(r: *Random, buf: []u8) void {
35 r.fillFn(r, buf);35 r.fillFn(r, buf);
36 }36 }
3737
38 /// Return a random integer/boolean type.38 /// Return a random integer/boolean type.
39 pub fn scalar(r: &Random, comptime T: type) T {39 pub fn scalar(r: *Random, comptime T: type) T {
40 var rand_bytes: [@sizeOf(T)]u8 = undefined;40 var rand_bytes: [@sizeOf(T)]u8 = undefined;
41 r.bytes(rand_bytes[0..]);41 r.bytes(rand_bytes[0..]);
4242
...@@ -50,7 +50,7 @@ pub const Random = struct {...@@ -50,7 +50,7 @@ pub const Random = struct {
5050
51 /// Get a random unsigned integer with even distribution between `start`51 /// Get a random unsigned integer with even distribution between `start`
52 /// inclusive and `end` exclusive.52 /// inclusive and `end` exclusive.
53 pub fn range(r: &Random, comptime T: type, start: T, end: T) T {53 pub fn range(r: *Random, comptime T: type, start: T, end: T) T {
54 assert(start <= end);54 assert(start <= end);
55 if (T.is_signed) {55 if (T.is_signed) {
56 const uint = @IntType(false, T.bit_count);56 const uint = @IntType(false, T.bit_count);
...@@ -69,7 +69,7 @@ pub const Random = struct {...@@ -69,7 +69,7 @@ pub const Random = struct {
69 break :x start;69 break :x start;
70 } else x: {70 } else x: {
71 // Can't overflow because the range is over signed ints71 // Can't overflow because the range is over signed ints
72 break :x math.negateCast(value - end_uint) catch unreachable;72 break :x math.negateCast(value - end_uint) catch unreachable;
73 };73 };
74 return result;74 return result;
75 } else {75 } else {
...@@ -92,7 +92,7 @@ pub const Random = struct {...@@ -92,7 +92,7 @@ pub const Random = struct {
92 }92 }
9393
94 /// Return a floating point value evenly distributed in the range [0, 1).94 /// Return a floating point value evenly distributed in the range [0, 1).
95 pub fn float(r: &Random, comptime T: type) T {95 pub fn float(r: *Random, comptime T: type) T {
96 // Generate a uniform value between [1, 2) and scale down to [0, 1).96 // Generate a uniform value between [1, 2) and scale down to [0, 1).
97 // Note: The lowest mantissa bit is always set to 0 so we only use half the available range.97 // Note: The lowest mantissa bit is always set to 0 so we only use half the available range.
98 switch (T) {98 switch (T) {
...@@ -113,7 +113,7 @@ pub const Random = struct {...@@ -113,7 +113,7 @@ pub const Random = struct {
113 /// Return a floating point value normally distributed with mean = 0, stddev = 1.113 /// Return a floating point value normally distributed with mean = 0, stddev = 1.
114 ///114 ///
115 /// To use different parameters, use: floatNorm(...) * desiredStddev + desiredMean.115 /// To use different parameters, use: floatNorm(...) * desiredStddev + desiredMean.
116 pub fn floatNorm(r: &Random, comptime T: type) T {116 pub fn floatNorm(r: *Random, comptime T: type) T {
117 const value = ziggurat.next_f64(r, ziggurat.NormDist);117 const value = ziggurat.next_f64(r, ziggurat.NormDist);
118 switch (T) {118 switch (T) {
119 f32 => return f32(value),119 f32 => return f32(value),
...@@ -125,7 +125,7 @@ pub const Random = struct {...@@ -125,7 +125,7 @@ pub const Random = struct {
125 /// Return an exponentially distributed float with a rate parameter of 1.125 /// Return an exponentially distributed float with a rate parameter of 1.
126 ///126 ///
127 /// To use a different rate parameter, use: floatExp(...) / desiredRate.127 /// To use a different rate parameter, use: floatExp(...) / desiredRate.
128 pub fn floatExp(r: &Random, comptime T: type) T {128 pub fn floatExp(r: *Random, comptime T: type) T {
129 const value = ziggurat.next_f64(r, ziggurat.ExpDist);129 const value = ziggurat.next_f64(r, ziggurat.ExpDist);
130 switch (T) {130 switch (T) {
131 f32 => return f32(value),131 f32 => return f32(value),
...@@ -135,7 +135,7 @@ pub const Random = struct {...@@ -135,7 +135,7 @@ pub const Random = struct {
135 }135 }
136136
137 /// Shuffle a slice into a random order.137 /// Shuffle a slice into a random order.
138 pub fn shuffle(r: &Random, comptime T: type, buf: []T) void {138 pub fn shuffle(r: *Random, comptime T: type, buf: []T) void {
139 if (buf.len < 2) {139 if (buf.len < 2) {
140 return;140 return;
141 }141 }
...@@ -156,10 +156,10 @@ const SplitMix64 = struct {...@@ -156,10 +156,10 @@ const SplitMix64 = struct {
156 s: u64,156 s: u64,
157157
158 pub fn init(seed: u64) SplitMix64 {158 pub fn init(seed: u64) SplitMix64 {
159 return SplitMix64 { .s = seed };159 return SplitMix64{ .s = seed };
160 }160 }
161161
162 pub fn next(self: &SplitMix64) u64 {162 pub fn next(self: *SplitMix64) u64 {
163 self.s +%= 0x9e3779b97f4a7c15;163 self.s +%= 0x9e3779b97f4a7c15;
164164
165 var z = self.s;165 var z = self.s;
...@@ -172,7 +172,7 @@ const SplitMix64 = struct {...@@ -172,7 +172,7 @@ const SplitMix64 = struct {
172test "splitmix64 sequence" {172test "splitmix64 sequence" {
173 var r = SplitMix64.init(0xaeecf86f7878dd75);173 var r = SplitMix64.init(0xaeecf86f7878dd75);
174174
175 const seq = []const u64 {175 const seq = []const u64{
176 0x5dbd39db0178eb44,176 0x5dbd39db0178eb44,
177 0xa9900fb66b397da3,177 0xa9900fb66b397da3,
178 0x5c1a28b1aeebcf5c,178 0x5c1a28b1aeebcf5c,
...@@ -198,8 +198,8 @@ pub const Pcg = struct {...@@ -198,8 +198,8 @@ pub const Pcg = struct {
198 i: u64,198 i: u64,
199199
200 pub fn init(init_s: u64) Pcg {200 pub fn init(init_s: u64) Pcg {
201 var pcg = Pcg {201 var pcg = Pcg{
202 .random = Random { .fillFn = fill },202 .random = Random{ .fillFn = fill },
203 .s = undefined,203 .s = undefined,
204 .i = undefined,204 .i = undefined,
205 };205 };
...@@ -208,7 +208,7 @@ pub const Pcg = struct {...@@ -208,7 +208,7 @@ pub const Pcg = struct {
208 return pcg;208 return pcg;
209 }209 }
210210
211 fn next(self: &Pcg) u32 {211 fn next(self: *Pcg) u32 {
212 const l = self.s;212 const l = self.s;
213 self.s = l *% default_multiplier +% (self.i | 1);213 self.s = l *% default_multiplier +% (self.i | 1);
214214
...@@ -218,13 +218,13 @@ pub const Pcg = struct {...@@ -218,13 +218,13 @@ pub const Pcg = struct {
218 return (xor_s >> u5(rot)) | (xor_s << u5((0 -% rot) & 31));218 return (xor_s >> u5(rot)) | (xor_s << u5((0 -% rot) & 31));
219 }219 }
220220
221 fn seed(self: &Pcg, init_s: u64) void {221 fn seed(self: *Pcg, init_s: u64) void {
222 // Pcg requires 128-bits of seed.222 // Pcg requires 128-bits of seed.
223 var gen = SplitMix64.init(init_s);223 var gen = SplitMix64.init(init_s);
224 self.seedTwo(gen.next(), gen.next());224 self.seedTwo(gen.next(), gen.next());
225 }225 }
226226
227 fn seedTwo(self: &Pcg, init_s: u64, init_i: u64) void {227 fn seedTwo(self: *Pcg, init_s: u64, init_i: u64) void {
228 self.s = 0;228 self.s = 0;
229 self.i = (init_s << 1) | 1;229 self.i = (init_s << 1) | 1;
230 self.s = self.s *% default_multiplier +% self.i;230 self.s = self.s *% default_multiplier +% self.i;
...@@ -232,7 +232,7 @@ pub const Pcg = struct {...@@ -232,7 +232,7 @@ pub const Pcg = struct {
232 self.s = self.s *% default_multiplier +% self.i;232 self.s = self.s *% default_multiplier +% self.i;
233 }233 }
234234
235 fn fill(r: &Random, buf: []u8) void {235 fn fill(r: *Random, buf: []u8) void {
236 const self = @fieldParentPtr(Pcg, "random", r);236 const self = @fieldParentPtr(Pcg, "random", r);
237237
238 var i: usize = 0;238 var i: usize = 0;
...@@ -265,7 +265,7 @@ test "pcg sequence" {...@@ -265,7 +265,7 @@ test "pcg sequence" {
265 const s1: u64 = 0x84e9c579ef59bbf7;265 const s1: u64 = 0x84e9c579ef59bbf7;
266 r.seedTwo(s0, s1);266 r.seedTwo(s0, s1);
267267
268 const seq = []const u32 {268 const seq = []const u32{
269 2881561918,269 2881561918,
270 3063928540,270 3063928540,
271 1199791034,271 1199791034,
...@@ -288,8 +288,8 @@ pub const Xoroshiro128 = struct {...@@ -288,8 +288,8 @@ pub const Xoroshiro128 = struct {
288 s: [2]u64,288 s: [2]u64,
289289
290 pub fn init(init_s: u64) Xoroshiro128 {290 pub fn init(init_s: u64) Xoroshiro128 {
291 var x = Xoroshiro128 {291 var x = Xoroshiro128{
292 .random = Random { .fillFn = fill },292 .random = Random{ .fillFn = fill },
293 .s = undefined,293 .s = undefined,
294 };294 };
295295
...@@ -297,7 +297,7 @@ pub const Xoroshiro128 = struct {...@@ -297,7 +297,7 @@ pub const Xoroshiro128 = struct {
297 return x;297 return x;
298 }298 }
299299
300 fn next(self: &Xoroshiro128) u64 {300 fn next(self: *Xoroshiro128) u64 {
301 const s0 = self.s[0];301 const s0 = self.s[0];
302 var s1 = self.s[1];302 var s1 = self.s[1];
303 const r = s0 +% s1;303 const r = s0 +% s1;
...@@ -310,13 +310,13 @@ pub const Xoroshiro128 = struct {...@@ -310,13 +310,13 @@ pub const Xoroshiro128 = struct {
310 }310 }
311311
312 // Skip 2^64 places ahead in the sequence312 // Skip 2^64 places ahead in the sequence
313 fn jump(self: &Xoroshiro128) void {313 fn jump(self: *Xoroshiro128) void {
314 var s0: u64 = 0;314 var s0: u64 = 0;
315 var s1: u64 = 0;315 var s1: u64 = 0;
316316
317 const table = []const u64 {317 const table = []const u64{
318 0xbeac0467eba5facb,318 0xbeac0467eba5facb,
319 0xd86b048b86aa9922319 0xd86b048b86aa9922,
320 };320 };
321321
322 inline for (table) |entry| {322 inline for (table) |entry| {
...@@ -334,7 +334,7 @@ pub const Xoroshiro128 = struct {...@@ -334,7 +334,7 @@ pub const Xoroshiro128 = struct {
334 self.s[1] = s1;334 self.s[1] = s1;
335 }335 }
336336
337 fn seed(self: &Xoroshiro128, init_s: u64) void {337 fn seed(self: *Xoroshiro128, init_s: u64) void {
338 // Xoroshiro requires 128-bits of seed.338 // Xoroshiro requires 128-bits of seed.
339 var gen = SplitMix64.init(init_s);339 var gen = SplitMix64.init(init_s);
340340
...@@ -342,7 +342,7 @@ pub const Xoroshiro128 = struct {...@@ -342,7 +342,7 @@ pub const Xoroshiro128 = struct {
342 self.s[1] = gen.next();342 self.s[1] = gen.next();
343 }343 }
344344
345 fn fill(r: &Random, buf: []u8) void {345 fn fill(r: *Random, buf: []u8) void {
346 const self = @fieldParentPtr(Xoroshiro128, "random", r);346 const self = @fieldParentPtr(Xoroshiro128, "random", r);
347347
348 var i: usize = 0;348 var i: usize = 0;
...@@ -374,7 +374,7 @@ test "xoroshiro sequence" {...@@ -374,7 +374,7 @@ test "xoroshiro sequence" {
374 r.s[0] = 0xaeecf86f7878dd75;374 r.s[0] = 0xaeecf86f7878dd75;
375 r.s[1] = 0x01cd153642e72622;375 r.s[1] = 0x01cd153642e72622;
376376
377 const seq1 = []const u64 {377 const seq1 = []const u64{
378 0xb0ba0da5bb600397,378 0xb0ba0da5bb600397,
379 0x18a08afde614dccc,379 0x18a08afde614dccc,
380 0xa2635b956a31b929,380 0xa2635b956a31b929,
...@@ -387,10 +387,9 @@ test "xoroshiro sequence" {...@@ -387,10 +387,9 @@ test "xoroshiro sequence" {
387 std.debug.assert(s == r.next());387 std.debug.assert(s == r.next());
388 }388 }
389389
390
391 r.jump();390 r.jump();
392391
393 const seq2 = []const u64 {392 const seq2 = []const u64{
394 0x95344a13556d3e22,393 0x95344a13556d3e22,
395 0xb4fb32dafa4d00df,394 0xb4fb32dafa4d00df,
396 0xb2011d9ccdcfe2dd,395 0xb2011d9ccdcfe2dd,
...@@ -421,8 +420,8 @@ pub const Isaac64 = struct {...@@ -421,8 +420,8 @@ pub const Isaac64 = struct {
421 i: usize,420 i: usize,
422421
423 pub fn init(init_s: u64) Isaac64 {422 pub fn init(init_s: u64) Isaac64 {
424 var isaac = Isaac64 {423 var isaac = Isaac64{
425 .random = Random { .fillFn = fill },424 .random = Random{ .fillFn = fill },
426 .r = undefined,425 .r = undefined,
427 .m = undefined,426 .m = undefined,
428 .a = undefined,427 .a = undefined,
...@@ -436,7 +435,7 @@ pub const Isaac64 = struct {...@@ -436,7 +435,7 @@ pub const Isaac64 = struct {
436 return isaac;435 return isaac;
437 }436 }
438437
439 fn step(self: &Isaac64, mix: u64, base: usize, comptime m1: usize, comptime m2: usize) void {438 fn step(self: *Isaac64, mix: u64, base: usize, comptime m1: usize, comptime m2: usize) void {
440 const x = self.m[base + m1];439 const x = self.m[base + m1];
441 self.a = mix +% self.m[base + m2];440 self.a = mix +% self.m[base + m2];
442441
...@@ -447,7 +446,7 @@ pub const Isaac64 = struct {...@@ -447,7 +446,7 @@ pub const Isaac64 = struct {
447 self.r[self.r.len - 1 - base - m1] = self.b;446 self.r[self.r.len - 1 - base - m1] = self.b;
448 }447 }
449448
450 fn refill(self: &Isaac64) void {449 fn refill(self: *Isaac64) void {
451 const midpoint = self.r.len / 2;450 const midpoint = self.r.len / 2;
452451
453 self.c +%= 1;452 self.c +%= 1;
...@@ -456,27 +455,27 @@ pub const Isaac64 = struct {...@@ -456,27 +455,27 @@ pub const Isaac64 = struct {
456 {455 {
457 var i: usize = 0;456 var i: usize = 0;
458 while (i < midpoint) : (i += 4) {457 while (i < midpoint) : (i += 4) {
459 self.step( ~(self.a ^ (self.a << 21)), i + 0, 0, midpoint);458 self.step(~(self.a ^ (self.a << 21)), i + 0, 0, midpoint);
460 self.step( self.a ^ (self.a >> 5) , i + 1, 0, midpoint);459 self.step(self.a ^ (self.a >> 5), i + 1, 0, midpoint);
461 self.step( self.a ^ (self.a << 12) , i + 2, 0, midpoint);460 self.step(self.a ^ (self.a << 12), i + 2, 0, midpoint);
462 self.step( self.a ^ (self.a >> 33) , i + 3, 0, midpoint);461 self.step(self.a ^ (self.a >> 33), i + 3, 0, midpoint);
463 }462 }
464 }463 }
465464
466 {465 {
467 var i: usize = 0;466 var i: usize = 0;
468 while (i < midpoint) : (i += 4) {467 while (i < midpoint) : (i += 4) {
469 self.step( ~(self.a ^ (self.a << 21)), i + 0, midpoint, 0);468 self.step(~(self.a ^ (self.a << 21)), i + 0, midpoint, 0);
470 self.step( self.a ^ (self.a >> 5) , i + 1, midpoint, 0);469 self.step(self.a ^ (self.a >> 5), i + 1, midpoint, 0);
471 self.step( self.a ^ (self.a << 12) , i + 2, midpoint, 0);470 self.step(self.a ^ (self.a << 12), i + 2, midpoint, 0);
472 self.step( self.a ^ (self.a >> 33) , i + 3, midpoint, 0);471 self.step(self.a ^ (self.a >> 33), i + 3, midpoint, 0);
473 }472 }
474 }473 }
475474
476 self.i = 0;475 self.i = 0;
477 }476 }
478477
479 fn next(self: &Isaac64) u64 {478 fn next(self: *Isaac64) u64 {
480 if (self.i >= self.r.len) {479 if (self.i >= self.r.len) {
481 self.refill();480 self.refill();
482 }481 }
...@@ -486,14 +485,14 @@ pub const Isaac64 = struct {...@@ -486,14 +485,14 @@ pub const Isaac64 = struct {
486 return value;485 return value;
487 }486 }
488487
489 fn seed(self: &Isaac64, init_s: u64, comptime rounds: usize) void {488 fn seed(self: *Isaac64, init_s: u64, comptime rounds: usize) void {
490 // We ignore the multi-pass requirement since we don't currently expose full access to489 // We ignore the multi-pass requirement since we don't currently expose full access to
491 // seeding the self.m array completely.490 // seeding the self.m array completely.
492 mem.set(u64, self.m[0..], 0);491 mem.set(u64, self.m[0..], 0);
493 self.m[0] = init_s;492 self.m[0] = init_s;
494493
495 // prescrambled golden ratio constants494 // prescrambled golden ratio constants
496 var a = []const u64 {495 var a = []const u64{
497 0x647c4677a2884b7c,496 0x647c4677a2884b7c,
498 0xb9f8b322c73ac862,497 0xb9f8b322c73ac862,
499 0x8c0ea5053d4712a0,498 0x8c0ea5053d4712a0,
...@@ -513,14 +512,30 @@ pub const Isaac64 = struct {...@@ -513,14 +512,30 @@ pub const Isaac64 = struct {
513 a[x1] +%= self.m[j + x1];512 a[x1] +%= self.m[j + x1];
514 }513 }
515514
516 a[0] -%= a[4]; a[5] ^= a[7] >> 9; a[7] +%= a[0];515 a[0] -%= a[4];
517 a[1] -%= a[5]; a[6] ^= a[0] << 9; a[0] +%= a[1];516 a[5] ^= a[7] >> 9;
518 a[2] -%= a[6]; a[7] ^= a[1] >> 23; a[1] +%= a[2];517 a[7] +%= a[0];
519 a[3] -%= a[7]; a[0] ^= a[2] << 15; a[2] +%= a[3];518 a[1] -%= a[5];
520 a[4] -%= a[0]; a[1] ^= a[3] >> 14; a[3] +%= a[4];519 a[6] ^= a[0] << 9;
521 a[5] -%= a[1]; a[2] ^= a[4] << 20; a[4] +%= a[5];520 a[0] +%= a[1];
522 a[6] -%= a[2]; a[3] ^= a[5] >> 17; a[5] +%= a[6];521 a[2] -%= a[6];
523 a[7] -%= a[3]; a[4] ^= a[6] << 14; a[6] +%= a[7];522 a[7] ^= a[1] >> 23;
523 a[1] +%= a[2];
524 a[3] -%= a[7];
525 a[0] ^= a[2] << 15;
526 a[2] +%= a[3];
527 a[4] -%= a[0];
528 a[1] ^= a[3] >> 14;
529 a[3] +%= a[4];
530 a[5] -%= a[1];
531 a[2] ^= a[4] << 20;
532 a[4] +%= a[5];
533 a[6] -%= a[2];
534 a[3] ^= a[5] >> 17;
535 a[5] +%= a[6];
536 a[7] -%= a[3];
537 a[4] ^= a[6] << 14;
538 a[6] +%= a[7];
524539
525 comptime var x2: usize = 0;540 comptime var x2: usize = 0;
526 inline while (x2 < 8) : (x2 += 1) {541 inline while (x2 < 8) : (x2 += 1) {
...@@ -533,10 +548,10 @@ pub const Isaac64 = struct {...@@ -533,10 +548,10 @@ pub const Isaac64 = struct {
533 self.a = 0;548 self.a = 0;
534 self.b = 0;549 self.b = 0;
535 self.c = 0;550 self.c = 0;
536 self.i = self.r.len; // trigger refill on first value551 self.i = self.r.len; // trigger refill on first value
537 }552 }
538553
539 fn fill(r: &Random, buf: []u8) void {554 fn fill(r: *Random, buf: []u8) void {
540 const self = @fieldParentPtr(Isaac64, "random", r);555 const self = @fieldParentPtr(Isaac64, "random", r);
541556
542 var i: usize = 0;557 var i: usize = 0;
...@@ -567,7 +582,7 @@ test "isaac64 sequence" {...@@ -567,7 +582,7 @@ test "isaac64 sequence" {
567 var r = Isaac64.init(0);582 var r = Isaac64.init(0);
568583
569 // from reference implementation584 // from reference implementation
570 const seq = []const u64 {585 const seq = []const u64{
571 0xf67dfba498e4937c,586 0xf67dfba498e4937c,
572 0x84a5066a9204f380,587 0x84a5066a9204f380,
573 0xfee34bd5f5514dbb,588 0xfee34bd5f5514dbb,
...@@ -609,7 +624,7 @@ test "Random float" {...@@ -609,7 +624,7 @@ test "Random float" {
609624
610test "Random scalar" {625test "Random scalar" {
611 var prng = DefaultPrng.init(0);626 var prng = DefaultPrng.init(0);
612 const s = prng .random.scalar(u64);627 const s = prng.random.scalar(u64);
613}628}
614629
615test "Random bytes" {630test "Random bytes" {
...@@ -621,8 +636,8 @@ test "Random bytes" {...@@ -621,8 +636,8 @@ test "Random bytes" {
621test "Random shuffle" {636test "Random shuffle" {
622 var prng = DefaultPrng.init(0);637 var prng = DefaultPrng.init(0);
623638
624 var seq = []const u8 { 0, 1, 2, 3, 4 };639 var seq = []const u8{ 0, 1, 2, 3, 4 };
625 var seen = []bool {false} ** 5;640 var seen = []bool{false} ** 5;
626641
627 var i: usize = 0;642 var i: usize = 0;
628 while (i < 1000) : (i += 1) {643 while (i < 1000) : (i += 1) {
...@@ -639,7 +654,8 @@ test "Random shuffle" {...@@ -639,7 +654,8 @@ test "Random shuffle" {
639654
640fn sumArray(s: []const u8) u32 {655fn sumArray(s: []const u8) u32 {
641 var r: u32 = 0;656 var r: u32 = 0;
642 for (s) |e| r += e;657 for (s) |e|
658 r += e;
643 return r;659 return r;
644}660}
645661
...@@ -650,7 +666,7 @@ test "Random range" {...@@ -650,7 +666,7 @@ test "Random range" {
650 testRange(&prng.random, 10, 14);666 testRange(&prng.random, 10, 14);
651}667}
652668
653fn testRange(r: &Random, start: i32, end: i32) void {669fn testRange(r: *Random, start: i32, end: i32) void {
654 const count = usize(end - start);670 const count = usize(end - start);
655 var values_buffer = []bool{false} ** 20;671 var values_buffer = []bool{false} ** 20;
656 const values = values_buffer[0..count];672 const values = values_buffer[0..count];
std/rand/ziggurat.zig+27-11
...@@ -12,7 +12,7 @@ const std = @import("../index.zig");...@@ -12,7 +12,7 @@ const std = @import("../index.zig");
12const math = std.math;12const math = std.math;
13const Random = std.rand.Random;13const Random = std.rand.Random;
1414
15pub fn next_f64(random: &Random, comptime tables: &const ZigTable) f64 {15pub fn next_f64(random: *Random, comptime tables: *const ZigTable) f64 {
16 while (true) {16 while (true) {
17 // We manually construct a float from parts as we can avoid an extra random lookup here by17 // We manually construct a float from parts as we can avoid an extra random lookup here by
18 // using the unused exponent for the lookup table entry.18 // using the unused exponent for the lookup table entry.
...@@ -56,16 +56,22 @@ pub const ZigTable = struct {...@@ -56,16 +56,22 @@ pub const ZigTable = struct {
56 f: [257]f64,56 f: [257]f64,
5757
58 // probability density function used as a fallback58 // probability density function used as a fallback
59 pdf: fn(f64) f64,59 pdf: fn (f64) f64,
60 // whether the distribution is symmetric60 // whether the distribution is symmetric
61 is_symmetric: bool,61 is_symmetric: bool,
62 // fallback calculation in the case we are in the 0 block62 // fallback calculation in the case we are in the 0 block
63 zero_case: fn(&Random, f64) f64,63 zero_case: fn (*Random, f64) f64,
64};64};
6565
66// zigNorInit66// zigNorInit
67fn ZigTableGen(comptime is_symmetric: bool, comptime r: f64, comptime v: f64, comptime f: fn(f64) f64,67fn ZigTableGen(
68 comptime f_inv: fn(f64) f64, comptime zero_case: fn(&Random, f64) f64) ZigTable {68 comptime is_symmetric: bool,
69 comptime r: f64,
70 comptime v: f64,
71 comptime f: fn (f64) f64,
72 comptime f_inv: fn (f64) f64,
73 comptime zero_case: fn (*Random, f64) f64,
74) ZigTable {
69 var tables: ZigTable = undefined;75 var tables: ZigTable = undefined;
7076
71 tables.is_symmetric = is_symmetric;77 tables.is_symmetric = is_symmetric;
...@@ -98,9 +104,13 @@ pub const NormDist = blk: {...@@ -98,9 +104,13 @@ pub const NormDist = blk: {
98const norm_r = 3.6541528853610088;104const norm_r = 3.6541528853610088;
99const norm_v = 0.00492867323399;105const norm_v = 0.00492867323399;
100106
101fn norm_f(x: f64) f64 { return math.exp(-x * x / 2.0); }107fn norm_f(x: f64) f64 {
102fn norm_f_inv(y: f64) f64 { return math.sqrt(-2.0 * math.ln(y)); }108 return math.exp(-x * x / 2.0);
103fn norm_zero_case(random: &Random, u: f64) f64 {109}
110fn norm_f_inv(y: f64) f64 {
111 return math.sqrt(-2.0 * math.ln(y));
112}
113fn norm_zero_case(random: *Random, u: f64) f64 {
104 var x: f64 = 1;114 var x: f64 = 1;
105 var y: f64 = 0;115 var y: f64 = 0;
106116
...@@ -133,9 +143,15 @@ pub const ExpDist = blk: {...@@ -133,9 +143,15 @@ pub const ExpDist = blk: {
133const exp_r = 7.69711747013104972;143const exp_r = 7.69711747013104972;
134const exp_v = 0.0039496598225815571993;144const exp_v = 0.0039496598225815571993;
135145
136fn exp_f(x: f64) f64 { return math.exp(-x); }146fn exp_f(x: f64) f64 {
137fn exp_f_inv(y: f64) f64 { return -math.ln(y); }147 return math.exp(-x);
138fn exp_zero_case(random: &Random, _: f64) f64 { return exp_r - math.ln(random.float(f64)); }148}
149fn exp_f_inv(y: f64) f64 {
150 return -math.ln(y);
151}
152fn exp_zero_case(random: *Random, _: f64) f64 {
153 return exp_r - math.ln(random.float(f64));
154}
139155
140test "ziggurant exp dist sanity" {156test "ziggurant exp dist sanity" {
141 var prng = std.rand.DefaultPrng.init(0);157 var prng = std.rand.DefaultPrng.init(0);
std/segmented_list.zig+30-30
...@@ -5,7 +5,7 @@ const Allocator = std.mem.Allocator;...@@ -5,7 +5,7 @@ const Allocator = std.mem.Allocator;
5// Imagine that `fn at(self: &Self, index: usize) &T` is a customer asking for a box5// Imagine that `fn at(self: &Self, index: usize) &T` is a customer asking for a box
6// from a warehouse, based on a flat array, boxes ordered from 0 to N - 1.6// from a warehouse, based on a flat array, boxes ordered from 0 to N - 1.
7// But the warehouse actually stores boxes in shelves of increasing powers of 2 sizes.7// But the warehouse actually stores boxes in shelves of increasing powers of 2 sizes.
8// So when the customer requests a box index, we have to translate it to shelf index 8// So when the customer requests a box index, we have to translate it to shelf index
9// and box index within that shelf. Illustration:9// and box index within that shelf. Illustration:
10//10//
11// customer indexes:11// customer indexes:
...@@ -37,14 +37,14 @@ const Allocator = std.mem.Allocator;...@@ -37,14 +37,14 @@ const Allocator = std.mem.Allocator;
37// Now we complicate it a little bit further by adding a preallocated shelf, which must be37// Now we complicate it a little bit further by adding a preallocated shelf, which must be
38// a power of 2:38// a power of 2:
39// prealloc=439// prealloc=4
40// 40//
41// customer indexes:41// customer indexes:
42// prealloc: 0 1 2 342// prealloc: 0 1 2 3
43// shelf 0: 4 5 6 7 8 9 10 1143// shelf 0: 4 5 6 7 8 9 10 11
44// shelf 1: 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2744// shelf 1: 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
45// shelf 2: 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 5945// shelf 2: 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
46// ...46// ...
47// 47//
48// warehouse indexes:48// warehouse indexes:
49// prealloc: 0 1 2 349// prealloc: 0 1 2 3
50// shelf 0: 0 1 2 3 4 5 6 750// shelf 0: 0 1 2 3 4 5 6 7
...@@ -87,49 +87,49 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -87,49 +87,49 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
87 const ShelfIndex = std.math.Log2Int(usize);87 const ShelfIndex = std.math.Log2Int(usize);
8888
89 prealloc_segment: [prealloc_item_count]T,89 prealloc_segment: [prealloc_item_count]T,
90 dynamic_segments: []&T,90 dynamic_segments: [][*]T,
91 allocator: &Allocator,91 allocator: *Allocator,
92 len: usize,92 len: usize,
9393
94 pub const prealloc_count = prealloc_item_count;94 pub const prealloc_count = prealloc_item_count;
9595
96 /// Deinitialize with `deinit`96 /// Deinitialize with `deinit`
97 pub fn init(allocator: &Allocator) Self {97 pub fn init(allocator: *Allocator) Self {
98 return Self{98 return Self{
99 .allocator = allocator,99 .allocator = allocator,
100 .len = 0,100 .len = 0,
101 .prealloc_segment = undefined,101 .prealloc_segment = undefined,
102 .dynamic_segments = []&T{},102 .dynamic_segments = [][*]T{},
103 };103 };
104 }104 }
105105
106 pub fn deinit(self: &Self) void {106 pub fn deinit(self: *Self) void {
107 self.freeShelves(ShelfIndex(self.dynamic_segments.len), 0);107 self.freeShelves(ShelfIndex(self.dynamic_segments.len), 0);
108 self.allocator.free(self.dynamic_segments);108 self.allocator.free(self.dynamic_segments);
109 self.* = undefined;109 self.* = undefined;
110 }110 }
111111
112 pub fn at(self: &Self, i: usize) &T {112 pub fn at(self: *Self, i: usize) *T {
113 assert(i < self.len);113 assert(i < self.len);
114 return self.uncheckedAt(i);114 return self.uncheckedAt(i);
115 }115 }
116116
117 pub fn count(self: &const Self) usize {117 pub fn count(self: *const Self) usize {
118 return self.len;118 return self.len;
119 }119 }
120120
121 pub fn push(self: &Self, item: &const T) !void {121 pub fn push(self: *Self, item: *const T) !void {
122 const new_item_ptr = try self.addOne();122 const new_item_ptr = try self.addOne();
123 new_item_ptr.* = item.*;123 new_item_ptr.* = item.*;
124 }124 }
125125
126 pub fn pushMany(self: &Self, items: []const T) !void {126 pub fn pushMany(self: *Self, items: []const T) !void {
127 for (items) |item| {127 for (items) |item| {
128 try self.push(item);128 try self.push(item);
129 }129 }
130 }130 }
131131
132 pub fn pop(self: &Self) ?T {132 pub fn pop(self: *Self) ?T {
133 if (self.len == 0) return null;133 if (self.len == 0) return null;
134134
135 const index = self.len - 1;135 const index = self.len - 1;
...@@ -138,7 +138,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -138,7 +138,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
138 return result;138 return result;
139 }139 }
140140
141 pub fn addOne(self: &Self) !&T {141 pub fn addOne(self: *Self) !*T {
142 const new_length = self.len + 1;142 const new_length = self.len + 1;
143 try self.growCapacity(new_length);143 try self.growCapacity(new_length);
144 const result = self.uncheckedAt(self.len);144 const result = self.uncheckedAt(self.len);
...@@ -147,7 +147,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -147,7 +147,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
147 }147 }
148148
149 /// Grows or shrinks capacity to match usage.149 /// Grows or shrinks capacity to match usage.
150 pub fn setCapacity(self: &Self, new_capacity: usize) !void {150 pub fn setCapacity(self: *Self, new_capacity: usize) !void {
151 if (new_capacity <= usize(1) << (prealloc_exp + self.dynamic_segments.len)) {151 if (new_capacity <= usize(1) << (prealloc_exp + self.dynamic_segments.len)) {
152 return self.shrinkCapacity(new_capacity);152 return self.shrinkCapacity(new_capacity);
153 } else {153 } else {
...@@ -156,15 +156,15 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -156,15 +156,15 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
156 }156 }
157157
158 /// Only grows capacity, or retains current capacity158 /// Only grows capacity, or retains current capacity
159 pub fn growCapacity(self: &Self, new_capacity: usize) !void {159 pub fn growCapacity(self: *Self, new_capacity: usize) !void {
160 const new_cap_shelf_count = shelfCount(new_capacity);160 const new_cap_shelf_count = shelfCount(new_capacity);
161 const old_shelf_count = ShelfIndex(self.dynamic_segments.len);161 const old_shelf_count = ShelfIndex(self.dynamic_segments.len);
162 if (new_cap_shelf_count > old_shelf_count) {162 if (new_cap_shelf_count > old_shelf_count) {
163 self.dynamic_segments = try self.allocator.realloc(&T, self.dynamic_segments, new_cap_shelf_count);163 self.dynamic_segments = try self.allocator.realloc([*]T, self.dynamic_segments, new_cap_shelf_count);
164 var i = old_shelf_count;164 var i = old_shelf_count;
165 errdefer {165 errdefer {
166 self.freeShelves(i, old_shelf_count);166 self.freeShelves(i, old_shelf_count);
167 self.dynamic_segments = self.allocator.shrink(&T, self.dynamic_segments, old_shelf_count);167 self.dynamic_segments = self.allocator.shrink([*]T, self.dynamic_segments, old_shelf_count);
168 }168 }
169 while (i < new_cap_shelf_count) : (i += 1) {169 while (i < new_cap_shelf_count) : (i += 1) {
170 self.dynamic_segments[i] = (try self.allocator.alloc(T, shelfSize(i))).ptr;170 self.dynamic_segments[i] = (try self.allocator.alloc(T, shelfSize(i))).ptr;
...@@ -173,12 +173,12 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -173,12 +173,12 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
173 }173 }
174174
175 /// Only shrinks capacity or retains current capacity175 /// Only shrinks capacity or retains current capacity
176 pub fn shrinkCapacity(self: &Self, new_capacity: usize) void {176 pub fn shrinkCapacity(self: *Self, new_capacity: usize) void {
177 if (new_capacity <= prealloc_item_count) {177 if (new_capacity <= prealloc_item_count) {
178 const len = ShelfIndex(self.dynamic_segments.len);178 const len = ShelfIndex(self.dynamic_segments.len);
179 self.freeShelves(len, 0);179 self.freeShelves(len, 0);
180 self.allocator.free(self.dynamic_segments);180 self.allocator.free(self.dynamic_segments);
181 self.dynamic_segments = []&T{};181 self.dynamic_segments = [][*]T{};
182 return;182 return;
183 }183 }
184184
...@@ -190,10 +190,10 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -190,10 +190,10 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
190 }190 }
191191
192 self.freeShelves(old_shelf_count, new_cap_shelf_count);192 self.freeShelves(old_shelf_count, new_cap_shelf_count);
193 self.dynamic_segments = self.allocator.shrink(&T, self.dynamic_segments, new_cap_shelf_count);193 self.dynamic_segments = self.allocator.shrink([*]T, self.dynamic_segments, new_cap_shelf_count);
194 }194 }
195195
196 pub fn uncheckedAt(self: &Self, index: usize) &T {196 pub fn uncheckedAt(self: *Self, index: usize) *T {
197 if (index < prealloc_item_count) {197 if (index < prealloc_item_count) {
198 return &self.prealloc_segment[index];198 return &self.prealloc_segment[index];
199 }199 }
...@@ -230,7 +230,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -230,7 +230,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
230 return list_index + prealloc_item_count - (usize(1) << ((prealloc_exp + 1) + shelf_index));230 return list_index + prealloc_item_count - (usize(1) << ((prealloc_exp + 1) + shelf_index));
231 }231 }
232232
233 fn freeShelves(self: &Self, from_count: ShelfIndex, to_count: ShelfIndex) void {233 fn freeShelves(self: *Self, from_count: ShelfIndex, to_count: ShelfIndex) void {
234 var i = from_count;234 var i = from_count;
235 while (i != to_count) {235 while (i != to_count) {
236 i -= 1;236 i -= 1;
...@@ -239,13 +239,13 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -239,13 +239,13 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
239 }239 }
240240
241 pub const Iterator = struct {241 pub const Iterator = struct {
242 list: &Self,242 list: *Self,
243 index: usize,243 index: usize,
244 box_index: usize,244 box_index: usize,
245 shelf_index: ShelfIndex,245 shelf_index: ShelfIndex,
246 shelf_size: usize,246 shelf_size: usize,
247247
248 pub fn next(it: &Iterator) ?&T {248 pub fn next(it: *Iterator) ?*T {
249 if (it.index >= it.list.len) return null;249 if (it.index >= it.list.len) return null;
250 if (it.index < prealloc_item_count) {250 if (it.index < prealloc_item_count) {
251 const ptr = &it.list.prealloc_segment[it.index];251 const ptr = &it.list.prealloc_segment[it.index];
...@@ -269,7 +269,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -269,7 +269,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
269 return ptr;269 return ptr;
270 }270 }
271271
272 pub fn prev(it: &Iterator) ?&T {272 pub fn prev(it: *Iterator) ?*T {
273 if (it.index == 0) return null;273 if (it.index == 0) return null;
274274
275 it.index -= 1;275 it.index -= 1;
...@@ -286,7 +286,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -286,7 +286,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
286 return &it.list.dynamic_segments[it.shelf_index][it.box_index];286 return &it.list.dynamic_segments[it.shelf_index][it.box_index];
287 }287 }
288288
289 pub fn peek(it: &Iterator) ?&T {289 pub fn peek(it: *Iterator) ?*T {
290 if (it.index >= it.list.len)290 if (it.index >= it.list.len)
291 return null;291 return null;
292 if (it.index < prealloc_item_count)292 if (it.index < prealloc_item_count)
...@@ -295,7 +295,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -295,7 +295,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
295 return &it.list.dynamic_segments[it.shelf_index][it.box_index];295 return &it.list.dynamic_segments[it.shelf_index][it.box_index];
296 }296 }
297297
298 pub fn set(it: &Iterator, index: usize) void {298 pub fn set(it: *Iterator, index: usize) void {
299 it.index = index;299 it.index = index;
300 if (index < prealloc_item_count) return;300 if (index < prealloc_item_count) return;
301 it.shelf_index = shelfIndex(index);301 it.shelf_index = shelfIndex(index);
...@@ -304,7 +304,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type...@@ -304,7 +304,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
304 }304 }
305 };305 };
306306
307 pub fn iterator(self: &Self, start_index: usize) Iterator {307 pub fn iterator(self: *Self, start_index: usize) Iterator {
308 var it = Iterator{308 var it = Iterator{
309 .list = self,309 .list = self,
310 .index = undefined,310 .index = undefined,
...@@ -331,7 +331,7 @@ test "std.SegmentedList" {...@@ -331,7 +331,7 @@ test "std.SegmentedList" {
331 try testSegmentedList(16, a);331 try testSegmentedList(16, a);
332}332}
333333
334fn testSegmentedList(comptime prealloc: usize, allocator: &Allocator) !void {334fn testSegmentedList(comptime prealloc: usize, allocator: *Allocator) !void {
335 var list = SegmentedList(i32, prealloc).init(allocator);335 var list = SegmentedList(i32, prealloc).init(allocator);
336 defer list.deinit();336 defer list.deinit();
337337
std/sort.zig+33-34
...@@ -5,7 +5,7 @@ const math = std.math;...@@ -5,7 +5,7 @@ const math = std.math;
5const builtin = @import("builtin");5const builtin = @import("builtin");
66
7/// Stable in-place sort. O(n) best case, O(pow(n, 2)) worst case. O(1) memory (no allocator required).7/// Stable in-place sort. O(n) best case, O(pow(n, 2)) worst case. O(1) memory (no allocator required).
8pub fn insertionSort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) void {8pub fn insertionSort(comptime T: type, items: []T, lessThan: fn (lhs: *const T, rhs: *const T) bool) void {
9 {9 {
10 var i: usize = 1;10 var i: usize = 1;
11 while (i < items.len) : (i += 1) {11 while (i < items.len) : (i += 1) {
...@@ -30,7 +30,7 @@ const Range = struct {...@@ -30,7 +30,7 @@ const Range = struct {
30 };30 };
31 }31 }
3232
33 fn length(self: &const Range) usize {33 fn length(self: *const Range) usize {
34 return self.end - self.start;34 return self.end - self.start;
35 }35 }
36};36};
...@@ -58,12 +58,12 @@ const Iterator = struct {...@@ -58,12 +58,12 @@ const Iterator = struct {
58 };58 };
59 }59 }
6060
61 fn begin(self: &Iterator) void {61 fn begin(self: *Iterator) void {
62 self.numerator = 0;62 self.numerator = 0;
63 self.decimal = 0;63 self.decimal = 0;
64 }64 }
6565
66 fn nextRange(self: &Iterator) Range {66 fn nextRange(self: *Iterator) Range {
67 const start = self.decimal;67 const start = self.decimal;
6868
69 self.decimal += self.decimal_step;69 self.decimal += self.decimal_step;
...@@ -79,11 +79,11 @@ const Iterator = struct {...@@ -79,11 +79,11 @@ const Iterator = struct {
79 };79 };
80 }80 }
8181
82 fn finished(self: &Iterator) bool {82 fn finished(self: *Iterator) bool {
83 return self.decimal >= self.size;83 return self.decimal >= self.size;
84 }84 }
8585
86 fn nextLevel(self: &Iterator) bool {86 fn nextLevel(self: *Iterator) bool {
87 self.decimal_step += self.decimal_step;87 self.decimal_step += self.decimal_step;
88 self.numerator_step += self.numerator_step;88 self.numerator_step += self.numerator_step;
89 if (self.numerator_step >= self.denominator) {89 if (self.numerator_step >= self.denominator) {
...@@ -94,7 +94,7 @@ const Iterator = struct {...@@ -94,7 +94,7 @@ const Iterator = struct {
94 return (self.decimal_step < self.size);94 return (self.decimal_step < self.size);
95 }95 }
9696
97 fn length(self: &Iterator) usize {97 fn length(self: *Iterator) usize {
98 return self.decimal_step;98 return self.decimal_step;
99 }99 }
100};100};
...@@ -108,7 +108,7 @@ const Pull = struct {...@@ -108,7 +108,7 @@ const Pull = struct {
108108
109/// Stable in-place sort. O(n) best case, O(n*log(n)) worst case and average case. O(1) memory (no allocator required).109/// Stable in-place sort. O(n) best case, O(n*log(n)) worst case and average case. O(1) memory (no allocator required).
110/// Currently implemented as block sort.110/// Currently implemented as block sort.
111pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) void {111pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: *const T, rhs: *const T) bool) void {
112 // Implementation ported from https://github.com/BonzaiThePenguin/WikiSort/blob/master/WikiSort.c112 // Implementation ported from https://github.com/BonzaiThePenguin/WikiSort/blob/master/WikiSort.c
113 var cache: [512]T = undefined;113 var cache: [512]T = undefined;
114114
...@@ -257,7 +257,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons...@@ -257,7 +257,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons
257 // merge A2 and B2 into the cache257 // merge A2 and B2 into the cache
258 if (lessThan(items[B2.end - 1], items[A2.start])) {258 if (lessThan(items[B2.end - 1], items[A2.start])) {
259 // the two ranges are in reverse order, so copy them in reverse order into the cache259 // the two ranges are in reverse order, so copy them in reverse order into the cache
260 mem.copy(T, cache[A1.length() + B2.length()..], items[A2.start..A2.end]);260 mem.copy(T, cache[A1.length() + B2.length() ..], items[A2.start..A2.end]);
261 mem.copy(T, cache[A1.length()..], items[B2.start..B2.end]);261 mem.copy(T, cache[A1.length()..], items[B2.start..B2.end]);
262 } else if (lessThan(items[B2.start], items[A2.end - 1])) {262 } else if (lessThan(items[B2.start], items[A2.end - 1])) {
263 // these two ranges weren't already in order, so merge them into the cache263 // these two ranges weren't already in order, so merge them into the cache
...@@ -265,7 +265,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons...@@ -265,7 +265,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons
265 } else {265 } else {
266 // copy A2 and B2 into the cache in the same order266 // copy A2 and B2 into the cache in the same order
267 mem.copy(T, cache[A1.length()..], items[A2.start..A2.end]);267 mem.copy(T, cache[A1.length()..], items[A2.start..A2.end]);
268 mem.copy(T, cache[A1.length() + A2.length()..], items[B2.start..B2.end]);268 mem.copy(T, cache[A1.length() + A2.length() ..], items[B2.start..B2.end]);
269 }269 }
270 A2 = Range.init(A2.start, B2.end);270 A2 = Range.init(A2.start, B2.end);
271271
...@@ -275,7 +275,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons...@@ -275,7 +275,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons
275275
276 if (lessThan(cache[B3.end - 1], cache[A3.start])) {276 if (lessThan(cache[B3.end - 1], cache[A3.start])) {
277 // the two ranges are in reverse order, so copy them in reverse order into the items277 // the two ranges are in reverse order, so copy them in reverse order into the items
278 mem.copy(T, items[A1.start + A2.length()..], cache[A3.start..A3.end]);278 mem.copy(T, items[A1.start + A2.length() ..], cache[A3.start..A3.end]);
279 mem.copy(T, items[A1.start..], cache[B3.start..B3.end]);279 mem.copy(T, items[A1.start..], cache[B3.start..B3.end]);
280 } else if (lessThan(cache[B3.start], cache[A3.end - 1])) {280 } else if (lessThan(cache[B3.start], cache[A3.end - 1])) {
281 // these two ranges weren't already in order, so merge them back into the items281 // these two ranges weren't already in order, so merge them back into the items
...@@ -283,7 +283,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons...@@ -283,7 +283,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons
283 } else {283 } else {
284 // copy A3 and B3 into the items in the same order284 // copy A3 and B3 into the items in the same order
285 mem.copy(T, items[A1.start..], cache[A3.start..A3.end]);285 mem.copy(T, items[A1.start..], cache[A3.start..A3.end]);
286 mem.copy(T, items[A1.start + A1.length()..], cache[B3.start..B3.end]);286 mem.copy(T, items[A1.start + A1.length() ..], cache[B3.start..B3.end]);
287 }287 }
288 }288 }
289289
...@@ -317,7 +317,6 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons...@@ -317,7 +317,6 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons
317 // 6. merge each A block with any B values that follow, using the cache or the second internal buffer317 // 6. merge each A block with any B values that follow, using the cache or the second internal buffer
318 // 7. sort the second internal buffer if it exists318 // 7. sort the second internal buffer if it exists
319 // 8. redistribute the two internal buffers back into the items319 // 8. redistribute the two internal buffers back into the items
320
321 var block_size: usize = math.sqrt(iterator.length());320 var block_size: usize = math.sqrt(iterator.length());
322 var buffer_size = iterator.length() / block_size + 1;321 var buffer_size = iterator.length() / block_size + 1;
323322
...@@ -641,7 +640,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons...@@ -641,7 +640,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons
641 if (buffer2.length() > 0 or block_size <= cache.len) {640 if (buffer2.length() > 0 or block_size <= cache.len) {
642 // copy the previous A block into the cache or buffer2, since that's where we need it to be when we go to merge it anyway641 // copy the previous A block into the cache or buffer2, since that's where we need it to be when we go to merge it anyway
643 if (block_size <= cache.len) {642 if (block_size <= cache.len) {
644 mem.copy(T, cache[0..], items[blockA.start..blockA.start + block_size]);643 mem.copy(T, cache[0..], items[blockA.start .. blockA.start + block_size]);
645 } else {644 } else {
646 blockSwap(T, items, blockA.start, buffer2.start, block_size);645 blockSwap(T, items, blockA.start, buffer2.start, block_size);
647 }646 }
...@@ -652,7 +651,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons...@@ -652,7 +651,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons
652 blockSwap(T, items, B_split, blockA.start + block_size - B_remaining, B_remaining);651 blockSwap(T, items, B_split, blockA.start + block_size - B_remaining, B_remaining);
653 } else {652 } else {
654 // we are unable to use the 'buffer2' trick to speed up the rotation operation since buffer2 doesn't exist, so perform a normal rotation653 // we are unable to use the 'buffer2' trick to speed up the rotation operation since buffer2 doesn't exist, so perform a normal rotation
655 mem.rotate(T, items[B_split..blockA.start + block_size], blockA.start - B_split);654 mem.rotate(T, items[B_split .. blockA.start + block_size], blockA.start - B_split);
656 }655 }
657656
658 // update the range for the remaining A blocks, and the range remaining from the B block after it was split657 // update the range for the remaining A blocks, and the range remaining from the B block after it was split
...@@ -742,7 +741,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons...@@ -742,7 +741,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons
742}741}
743742
744// merge operation without a buffer743// merge operation without a buffer
745fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const Range, lessThan: fn(&const T, &const T) bool) void {744fn mergeInPlace(comptime T: type, items: []T, A_arg: *const Range, B_arg: *const Range, lessThan: fn (*const T, *const T) bool) void {
746 if (A_arg.length() == 0 or B_arg.length() == 0) return;745 if (A_arg.length() == 0 or B_arg.length() == 0) return;
747746
748 // this just repeatedly binary searches into B and rotates A into position.747 // this just repeatedly binary searches into B and rotates A into position.
...@@ -784,7 +783,7 @@ fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const...@@ -784,7 +783,7 @@ fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const
784}783}
785784
786// merge operation using an internal buffer785// merge operation using an internal buffer
787fn mergeInternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, buffer: &const Range) void {786fn mergeInternal(comptime T: type, items: []T, A: *const Range, B: *const Range, lessThan: fn (*const T, *const T) bool, buffer: *const Range) void {
788 // whenever we find a value to add to the final array, swap it with the value that's already in that spot787 // whenever we find a value to add to the final array, swap it with the value that's already in that spot
789 // when this algorithm is finished, 'buffer' will contain its original contents, but in a different order788 // when this algorithm is finished, 'buffer' will contain its original contents, but in a different order
790 var A_count: usize = 0;789 var A_count: usize = 0;
...@@ -820,7 +819,7 @@ fn blockSwap(comptime T: type, items: []T, start1: usize, start2: usize, block_s...@@ -820,7 +819,7 @@ fn blockSwap(comptime T: type, items: []T, start1: usize, start2: usize, block_s
820819
821// combine a linear search with a binary search to reduce the number of comparisons in situations820// combine a linear search with a binary search to reduce the number of comparisons in situations
822// where have some idea as to how many unique values there are and where the next value might be821// where have some idea as to how many unique values there are and where the next value might be
823fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize {822fn findFirstForward(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool, unique: usize) usize {
824 if (range.length() == 0) return range.start;823 if (range.length() == 0) return range.start;
825 const skip = math.max(range.length() / unique, usize(1));824 const skip = math.max(range.length() / unique, usize(1));
826825
...@@ -834,7 +833,7 @@ fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const...@@ -834,7 +833,7 @@ fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const
834 return binaryFirst(T, items, value, Range.init(index - skip, index), lessThan);833 return binaryFirst(T, items, value, Range.init(index - skip, index), lessThan);
835}834}
836835
837fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize {836fn findFirstBackward(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool, unique: usize) usize {
838 if (range.length() == 0) return range.start;837 if (range.length() == 0) return range.start;
839 const skip = math.max(range.length() / unique, usize(1));838 const skip = math.max(range.length() / unique, usize(1));
840839
...@@ -848,7 +847,7 @@ fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &cons...@@ -848,7 +847,7 @@ fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &cons
848 return binaryFirst(T, items, value, Range.init(index, index + skip), lessThan);847 return binaryFirst(T, items, value, Range.init(index, index + skip), lessThan);
849}848}
850849
851fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize {850fn findLastForward(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool, unique: usize) usize {
852 if (range.length() == 0) return range.start;851 if (range.length() == 0) return range.start;
853 const skip = math.max(range.length() / unique, usize(1));852 const skip = math.max(range.length() / unique, usize(1));
854853
...@@ -862,7 +861,7 @@ fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const...@@ -862,7 +861,7 @@ fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const
862 return binaryLast(T, items, value, Range.init(index - skip, index), lessThan);861 return binaryLast(T, items, value, Range.init(index - skip, index), lessThan);
863}862}
864863
865fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize {864fn findLastBackward(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool, unique: usize) usize {
866 if (range.length() == 0) return range.start;865 if (range.length() == 0) return range.start;
867 const skip = math.max(range.length() / unique, usize(1));866 const skip = math.max(range.length() / unique, usize(1));
868867
...@@ -876,7 +875,7 @@ fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const...@@ -876,7 +875,7 @@ fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const
876 return binaryLast(T, items, value, Range.init(index, index + skip), lessThan);875 return binaryLast(T, items, value, Range.init(index, index + skip), lessThan);
877}876}
878877
879fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool) usize {878fn binaryFirst(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool) usize {
880 var start = range.start;879 var start = range.start;
881 var end = range.end - 1;880 var end = range.end - 1;
882 if (range.start >= range.end) return range.end;881 if (range.start >= range.end) return range.end;
...@@ -894,7 +893,7 @@ fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Rang...@@ -894,7 +893,7 @@ fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Rang
894 return start;893 return start;
895}894}
896895
897fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool) usize {896fn binaryLast(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool) usize {
898 var start = range.start;897 var start = range.start;
899 var end = range.end - 1;898 var end = range.end - 1;
900 if (range.start >= range.end) return range.end;899 if (range.start >= range.end) return range.end;
...@@ -912,7 +911,7 @@ fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range...@@ -912,7 +911,7 @@ fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range
912 return start;911 return start;
913}912}
914913
915fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, into: []T) void {914fn mergeInto(comptime T: type, from: []T, A: *const Range, B: *const Range, lessThan: fn (*const T, *const T) bool, into: []T) void {
916 var A_index: usize = A.start;915 var A_index: usize = A.start;
917 var B_index: usize = B.start;916 var B_index: usize = B.start;
918 const A_last = A.end;917 const A_last = A.end;
...@@ -942,7 +941,7 @@ fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, less...@@ -942,7 +941,7 @@ fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, less
942 }941 }
943}942}
944943
945fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, cache: []T) void {944fn mergeExternal(comptime T: type, items: []T, A: *const Range, B: *const Range, lessThan: fn (*const T, *const T) bool, cache: []T) void {
946 // A fits into the cache, so use that instead of the internal buffer945 // A fits into the cache, so use that instead of the internal buffer
947 var A_index: usize = 0;946 var A_index: usize = 0;
948 var B_index: usize = B.start;947 var B_index: usize = B.start;
...@@ -970,26 +969,26 @@ fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range,...@@ -970,26 +969,26 @@ fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range,
970 mem.copy(T, items[insert_index..], cache[A_index..A_last]);969 mem.copy(T, items[insert_index..], cache[A_index..A_last]);
971}970}
972971
973fn swap(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool, order: &[8]u8, x: usize, y: usize) void {972fn swap(comptime T: type, items: []T, lessThan: fn (lhs: *const T, rhs: *const T) bool, order: *[8]u8, x: usize, y: usize) void {
974 if (lessThan(items[y], items[x]) or ((order.*)[x] > (order.*)[y] and !lessThan(items[x], items[y]))) {973 if (lessThan(items[y], items[x]) or ((order.*)[x] > (order.*)[y] and !lessThan(items[x], items[y]))) {
975 mem.swap(T, &items[x], &items[y]);974 mem.swap(T, &items[x], &items[y]);
976 mem.swap(u8, &(order.*)[x], &(order.*)[y]);975 mem.swap(u8, &(order.*)[x], &(order.*)[y]);
977 }976 }
978}977}
979978
980fn i32asc(lhs: &const i32, rhs: &const i32) bool {979fn i32asc(lhs: *const i32, rhs: *const i32) bool {
981 return lhs.* < rhs.*;980 return lhs.* < rhs.*;
982}981}
983982
984fn i32desc(lhs: &const i32, rhs: &const i32) bool {983fn i32desc(lhs: *const i32, rhs: *const i32) bool {
985 return rhs.* < lhs.*;984 return rhs.* < lhs.*;
986}985}
987986
988fn u8asc(lhs: &const u8, rhs: &const u8) bool {987fn u8asc(lhs: *const u8, rhs: *const u8) bool {
989 return lhs.* < rhs.*;988 return lhs.* < rhs.*;
990}989}
991990
992fn u8desc(lhs: &const u8, rhs: &const u8) bool {991fn u8desc(lhs: *const u8, rhs: *const u8) bool {
993 return rhs.* < lhs.*;992 return rhs.* < lhs.*;
994}993}
995994
...@@ -1126,7 +1125,7 @@ const IdAndValue = struct {...@@ -1126,7 +1125,7 @@ const IdAndValue = struct {
1126 id: usize,1125 id: usize,
1127 value: i32,1126 value: i32,
1128};1127};
1129fn cmpByValue(a: &const IdAndValue, b: &const IdAndValue) bool {1128fn cmpByValue(a: *const IdAndValue, b: *const IdAndValue) bool {
1130 return i32asc(a.value, b.value);1129 return i32asc(a.value, b.value);
1131}1130}
11321131
...@@ -1325,7 +1324,7 @@ test "sort fuzz testing" {...@@ -1325,7 +1324,7 @@ test "sort fuzz testing" {
13251324
1326var fixed_buffer_mem: [100 * 1024]u8 = undefined;1325var fixed_buffer_mem: [100 * 1024]u8 = undefined;
13271326
1328fn fuzzTest(rng: &std.rand.Random) void {1327fn fuzzTest(rng: *std.rand.Random) void {
1329 const array_size = rng.range(usize, 0, 1000);1328 const array_size = rng.range(usize, 0, 1000);
1330 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);1329 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
1331 var array = fixed_allocator.allocator.alloc(IdAndValue, array_size) catch unreachable;1330 var array = fixed_allocator.allocator.alloc(IdAndValue, array_size) catch unreachable;
...@@ -1346,7 +1345,7 @@ fn fuzzTest(rng: &std.rand.Random) void {...@@ -1346,7 +1345,7 @@ fn fuzzTest(rng: &std.rand.Random) void {
1346 }1345 }
1347}1346}
13481347
1349pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) T {1348pub fn min(comptime T: type, items: []T, lessThan: fn (lhs: *const T, rhs: *const T) bool) T {
1350 var i: usize = 0;1349 var i: usize = 0;
1351 var smallest = items[0];1350 var smallest = items[0];
1352 for (items[1..]) |item| {1351 for (items[1..]) |item| {
...@@ -1357,7 +1356,7 @@ pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const...@@ -1357,7 +1356,7 @@ pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const
1357 return smallest;1356 return smallest;
1358}1357}
13591358
1360pub fn max(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) T {1359pub fn max(comptime T: type, items: []T, lessThan: fn (lhs: *const T, rhs: *const T) bool) T {
1361 var i: usize = 0;1360 var i: usize = 0;
1362 var biggest = items[0];1361 var biggest = items[0];
1363 for (items[1..]) |item| {1362 for (items[1..]) |item| {
std/special/bootstrap.zig+16-10
...@@ -5,7 +5,7 @@ const root = @import("@root");...@@ -5,7 +5,7 @@ const root = @import("@root");
5const std = @import("std");5const std = @import("std");
6const builtin = @import("builtin");6const builtin = @import("builtin");
77
8var argc_ptr: &usize = undefined;8var argc_ptr: [*]usize = undefined;
99
10comptime {10comptime {
11 const strong_linkage = builtin.GlobalLinkage.Strong;11 const strong_linkage = builtin.GlobalLinkage.Strong;
...@@ -27,10 +27,14 @@ extern fn zen_start() noreturn {...@@ -27,10 +27,14 @@ extern fn zen_start() noreturn {
27nakedcc fn _start() noreturn {27nakedcc fn _start() noreturn {
28 switch (builtin.arch) {28 switch (builtin.arch) {
29 builtin.Arch.x86_64 => {29 builtin.Arch.x86_64 => {
30 argc_ptr = asm ("lea (%%rsp), %[argc]" : [argc] "=r" (-> &usize));30 argc_ptr = asm ("lea (%%rsp), %[argc]"
31 : [argc] "=r" (-> [*]usize)
32 );
31 },33 },
32 builtin.Arch.i386 => {34 builtin.Arch.i386 => {
33 argc_ptr = asm ("lea (%%esp), %[argc]" : [argc] "=r" (-> &usize));35 argc_ptr = asm ("lea (%%esp), %[argc]"
36 : [argc] "=r" (-> [*]usize)
37 );
34 },38 },
35 else => @compileError("unsupported arch"),39 else => @compileError("unsupported arch"),
36 }40 }
...@@ -45,15 +49,17 @@ extern fn WinMainCRTStartup() noreturn {...@@ -45,15 +49,17 @@ extern fn WinMainCRTStartup() noreturn {
45 std.os.windows.ExitProcess(callMain());49 std.os.windows.ExitProcess(callMain());
46}50}
4751
52// TODO https://github.com/ziglang/zig/issues/265
48fn posixCallMainAndExit() noreturn {53fn posixCallMainAndExit() noreturn {
49 const argc = argc_ptr.*;54 const argc = argc_ptr.*;
50 const argv = @ptrCast(&&u8, &argc_ptr[1]);55 const argv = @ptrCast([*][*]u8, argc_ptr + 1);
51 const envp_nullable = @ptrCast(&?&u8, &argv[argc + 1]);56
57 const envp_nullable = @ptrCast([*]?[*]u8, argv + argc + 1);
52 var envp_count: usize = 0;58 var envp_count: usize = 0;
53 while (envp_nullable[envp_count]) |_| : (envp_count += 1) {}59 while (envp_nullable[envp_count]) |_| : (envp_count += 1) {}
54 const envp = @ptrCast(&&u8, envp_nullable)[0..envp_count];60 const envp = @ptrCast([*][*]u8, envp_nullable)[0..envp_count];
55 if (builtin.os == builtin.Os.linux) {61 if (builtin.os == builtin.Os.linux) {
56 const auxv = &@ptrCast(&usize, envp.ptr)[envp_count + 1];62 const auxv = @ptrCast([*]usize, envp.ptr + envp_count + 1);
57 var i: usize = 0;63 var i: usize = 0;
58 while (auxv[i] != 0) : (i += 2) {64 while (auxv[i] != 0) : (i += 2) {
59 if (auxv[i] < std.os.linux_aux_raw.len) std.os.linux_aux_raw[auxv[i]] = auxv[i + 1];65 if (auxv[i] < std.os.linux_aux_raw.len) std.os.linux_aux_raw[auxv[i]] = auxv[i + 1];
...@@ -64,16 +70,16 @@ fn posixCallMainAndExit() noreturn {...@@ -64,16 +70,16 @@ fn posixCallMainAndExit() noreturn {
64 std.os.posix.exit(callMainWithArgs(argc, argv, envp));70 std.os.posix.exit(callMainWithArgs(argc, argv, envp));
65}71}
6672
67fn callMainWithArgs(argc: usize, argv: &&u8, envp: []&u8) u8 {73fn callMainWithArgs(argc: usize, argv: [*][*]u8, envp: [][*]u8) u8 {
68 std.os.ArgIteratorPosix.raw = argv[0..argc];74 std.os.ArgIteratorPosix.raw = argv[0..argc];
69 std.os.posix_environ_raw = envp;75 std.os.posix_environ_raw = envp;
70 return callMain();76 return callMain();
71}77}
7278
73extern fn main(c_argc: i32, c_argv: &&u8, c_envp: &?&u8) i32 {79extern fn main(c_argc: i32, c_argv: [*][*]u8, c_envp: [*]?[*]u8) i32 {
74 var env_count: usize = 0;80 var env_count: usize = 0;
75 while (c_envp[env_count] != null) : (env_count += 1) {}81 while (c_envp[env_count] != null) : (env_count += 1) {}
76 const envp = @ptrCast(&&u8, c_envp)[0..env_count];82 const envp = @ptrCast([*][*]u8, c_envp)[0..env_count];
77 return callMainWithArgs(usize(c_argc), c_argv, envp);83 return callMainWithArgs(usize(c_argc), c_argv, envp);
78}84}
7985
std/special/bootstrap_lib.zig+5-3
...@@ -7,8 +7,10 @@ comptime {...@@ -7,8 +7,10 @@ comptime {
7 @export("_DllMainCRTStartup", _DllMainCRTStartup, builtin.GlobalLinkage.Strong);7 @export("_DllMainCRTStartup", _DllMainCRTStartup, builtin.GlobalLinkage.Strong);
8}8}
99
10stdcallcc fn _DllMainCRTStartup(hinstDLL: std.os.windows.HINSTANCE, fdwReason: std.os.windows.DWORD,10stdcallcc fn _DllMainCRTStartup(
11 lpReserved: std.os.windows.LPVOID) std.os.windows.BOOL11 hinstDLL: std.os.windows.HINSTANCE,
12{12 fdwReason: std.os.windows.DWORD,
13 lpReserved: std.os.windows.LPVOID,
14) std.os.windows.BOOL {
13 return std.os.windows.TRUE;15 return std.os.windows.TRUE;
14}16}
std/special/build_file_template.zig+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const Builder = @import("std").build.Builder;1const Builder = @import("std").build.Builder;
22
3pub fn build(b: &Builder) void {3pub fn build(b: *Builder) void {
4 const mode = b.standardReleaseOptions();4 const mode = b.standardReleaseOptions();
5 const exe = b.addExecutable("YOUR_NAME_HERE", "src/main.zig");5 const exe = b.addExecutable("YOUR_NAME_HERE", "src/main.zig");
6 exe.setBuildMode(mode);6 exe.setBuildMode(mode);
std/special/build_runner.zig+6-8
...@@ -24,7 +24,6 @@ pub fn main() !void {...@@ -24,7 +24,6 @@ pub fn main() !void {
2424
25 const allocator = &arena.allocator;25 const allocator = &arena.allocator;
2626
27
28 // skip my own exe name27 // skip my own exe name
29 _ = arg_it.skip();28 _ = arg_it.skip();
3029
...@@ -72,7 +71,7 @@ pub fn main() !void {...@@ -72,7 +71,7 @@ pub fn main() !void {
72 }71 }
73 if (mem.indexOfScalar(u8, option_contents, '=')) |name_end| {72 if (mem.indexOfScalar(u8, option_contents, '=')) |name_end| {
74 const option_name = option_contents[0..name_end];73 const option_name = option_contents[0..name_end];
75 const option_value = option_contents[name_end + 1..];74 const option_value = option_contents[name_end + 1 ..];
76 if (builder.addUserInputOption(option_name, option_value))75 if (builder.addUserInputOption(option_name, option_value))
77 return usageAndErr(&builder, false, try stderr_stream);76 return usageAndErr(&builder, false, try stderr_stream);
78 } else {77 } else {
...@@ -130,7 +129,7 @@ pub fn main() !void {...@@ -130,7 +129,7 @@ pub fn main() !void {
130 };129 };
131}130}
132131
133fn runBuild(builder: &Builder) error!void {132fn runBuild(builder: *Builder) error!void {
134 switch (@typeId(@typeOf(root.build).ReturnType)) {133 switch (@typeId(@typeOf(root.build).ReturnType)) {
135 builtin.TypeId.Void => root.build(builder),134 builtin.TypeId.Void => root.build(builder),
136 builtin.TypeId.ErrorUnion => try root.build(builder),135 builtin.TypeId.ErrorUnion => try root.build(builder),
...@@ -138,7 +137,7 @@ fn runBuild(builder: &Builder) error!void {...@@ -138,7 +137,7 @@ fn runBuild(builder: &Builder) error!void {
138 }137 }
139}138}
140139
141fn usage(builder: &Builder, already_ran_build: bool, out_stream: var) !void {140fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void {
142 // run the build script to collect the options141 // run the build script to collect the options
143 if (!already_ran_build) {142 if (!already_ran_build) {
144 builder.setInstallPrefix(null);143 builder.setInstallPrefix(null);
...@@ -175,8 +174,7 @@ fn usage(builder: &Builder, already_ran_build: bool, out_stream: var) !void {...@@ -175,8 +174,7 @@ fn usage(builder: &Builder, already_ran_build: bool, out_stream: var) !void {
175 try out_stream.print(" (none)\n");174 try out_stream.print(" (none)\n");
176 } else {175 } else {
177 for (builder.available_options_list.toSliceConst()) |option| {176 for (builder.available_options_list.toSliceConst()) |option| {
178 const name = try fmt.allocPrint(allocator,177 const name = try fmt.allocPrint(allocator, " -D{}=[{}]", option.name, Builder.typeIdName(option.type_id));
179 " -D{}=[{}]", option.name, Builder.typeIdName(option.type_id));
180 defer allocator.free(name);178 defer allocator.free(name);
181 try out_stream.print("{s24} {}\n", name, option.description);179 try out_stream.print("{s24} {}\n", name, option.description);
182 }180 }
...@@ -197,12 +195,12 @@ fn usage(builder: &Builder, already_ran_build: bool, out_stream: var) !void {...@@ -197,12 +195,12 @@ fn usage(builder: &Builder, already_ran_build: bool, out_stream: var) !void {
197 );195 );
198}196}
199197
200fn usageAndErr(builder: &Builder, already_ran_build: bool, out_stream: var) error {198fn usageAndErr(builder: *Builder, already_ran_build: bool, out_stream: var) error {
201 usage(builder, already_ran_build, out_stream) catch {};199 usage(builder, already_ran_build, out_stream) catch {};
202 return error.InvalidArgs;200 return error.InvalidArgs;
203}201}
204202
205const UnwrapArgError = error {OutOfMemory};203const UnwrapArgError = error{OutOfMemory};
206204
207fn unwrapArg(arg: UnwrapArgError![]u8) UnwrapArgError![]u8 {205fn unwrapArg(arg: UnwrapArgError![]u8) UnwrapArgError![]u8 {
208 return arg catch |err| {206 return arg catch |err| {
std/special/builtin.zig+45-23
...@@ -5,7 +5,7 @@ const builtin = @import("builtin");...@@ -5,7 +5,7 @@ const builtin = @import("builtin");
55
6// Avoid dragging in the runtime safety mechanisms into this .o file,6// Avoid dragging in the runtime safety mechanisms into this .o file,
7// unless we're trying to test this file.7// unless we're trying to test this file.
8pub fn panic(msg: []const u8, error_return_trace: ?&builtin.StackTrace) noreturn {8pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn {
9 if (builtin.is_test) {9 if (builtin.is_test) {
10 @setCold(true);10 @setCold(true);
11 @import("std").debug.panic("{}", msg);11 @import("std").debug.panic("{}", msg);
...@@ -14,7 +14,7 @@ pub fn panic(msg: []const u8, error_return_trace: ?&builtin.StackTrace) noreturn...@@ -14,7 +14,7 @@ pub fn panic(msg: []const u8, error_return_trace: ?&builtin.StackTrace) noreturn
14 }14 }
15}15}
1616
17export fn memset(dest: ?&u8, c: u8, n: usize) ?&u8 {17export fn memset(dest: ?[*]u8, c: u8, n: usize) ?[*]u8 {
18 @setRuntimeSafety(false);18 @setRuntimeSafety(false);
1919
20 var index: usize = 0;20 var index: usize = 0;
...@@ -24,7 +24,7 @@ export fn memset(dest: ?&u8, c: u8, n: usize) ?&u8 {...@@ -24,7 +24,7 @@ export fn memset(dest: ?&u8, c: u8, n: usize) ?&u8 {
24 return dest;24 return dest;
25}25}
2626
27export fn memcpy(noalias dest: ?&u8, noalias src: ?&const u8, n: usize) ?&u8 {27export fn memcpy(noalias dest: ?[*]u8, noalias src: ?[*]const u8, n: usize) ?[*]u8 {
28 @setRuntimeSafety(false);28 @setRuntimeSafety(false);
2929
30 var index: usize = 0;30 var index: usize = 0;
...@@ -34,7 +34,7 @@ export fn memcpy(noalias dest: ?&u8, noalias src: ?&const u8, n: usize) ?&u8 {...@@ -34,7 +34,7 @@ export fn memcpy(noalias dest: ?&u8, noalias src: ?&const u8, n: usize) ?&u8 {
34 return dest;34 return dest;
35}35}
3636
37export fn memmove(dest: ?&u8, src: ?&const u8, n: usize) ?&u8 {37export fn memmove(dest: ?[*]u8, src: ?[*]const u8, n: usize) ?[*]u8 {
38 @setRuntimeSafety(false);38 @setRuntimeSafety(false);
3939
40 if (@ptrToInt(dest) < @ptrToInt(src)) {40 if (@ptrToInt(dest) < @ptrToInt(src)) {
...@@ -56,7 +56,8 @@ export fn memmove(dest: ?&u8, src: ?&const u8, n: usize) ?&u8 {...@@ -56,7 +56,8 @@ export fn memmove(dest: ?&u8, src: ?&const u8, n: usize) ?&u8 {
56comptime {56comptime {
57 if (builtin.mode != builtin.Mode.ReleaseFast and57 if (builtin.mode != builtin.Mode.ReleaseFast and
58 builtin.mode != builtin.Mode.ReleaseSmall and58 builtin.mode != builtin.Mode.ReleaseSmall and
59 builtin.os != builtin.Os.windows) {59 builtin.os != builtin.Os.windows)
60 {
60 @export("__stack_chk_fail", __stack_chk_fail, builtin.GlobalLinkage.Strong);61 @export("__stack_chk_fail", __stack_chk_fail, builtin.GlobalLinkage.Strong);
61 }62 }
62 if (builtin.os == builtin.Os.linux and builtin.arch == builtin.Arch.x86_64) {63 if (builtin.os == builtin.Os.linux and builtin.arch == builtin.Arch.x86_64) {
...@@ -101,15 +102,27 @@ nakedcc fn clone() void {...@@ -101,15 +102,27 @@ nakedcc fn clone() void {
101102
102const math = @import("../math/index.zig");103const math = @import("../math/index.zig");
103104
104export fn fmodf(x: f32, y: f32) f32 { return generic_fmod(f32, x, y); }105export fn fmodf(x: f32, y: f32) f32 {
105export fn fmod(x: f64, y: f64) f64 { return generic_fmod(f64, x, y); }106 return generic_fmod(f32, x, y);
107}
108export fn fmod(x: f64, y: f64) f64 {
109 return generic_fmod(f64, x, y);
110}
106111
107// TODO add intrinsics for these (and probably the double version too)112// TODO add intrinsics for these (and probably the double version too)
108// and have the math stuff use the intrinsic. same as @mod and @rem113// and have the math stuff use the intrinsic. same as @mod and @rem
109export fn floorf(x: f32) f32 { return math.floor(x); }114export fn floorf(x: f32) f32 {
110export fn ceilf(x: f32) f32 { return math.ceil(x); }115 return math.floor(x);
111export fn floor(x: f64) f64 { return math.floor(x); }116}
112export fn ceil(x: f64) f64 { return math.ceil(x); }117export fn ceilf(x: f32) f32 {
118 return math.ceil(x);
119}
120export fn floor(x: f64) f64 {
121 return math.floor(x);
122}
123export fn ceil(x: f64) f64 {
124 return math.ceil(x);
125}
113126
114fn generic_fmod(comptime T: type, x: T, y: T) T {127fn generic_fmod(comptime T: type, x: T, y: T) T {
115 @setRuntimeSafety(false);128 @setRuntimeSafety(false);
...@@ -139,7 +152,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T {...@@ -139,7 +152,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T {
139 // normalize x and y152 // normalize x and y
140 if (ex == 0) {153 if (ex == 0) {
141 i = ux << exp_bits;154 i = ux << exp_bits;
142 while (i >> bits_minus_1 == 0) : (b: {ex -= 1; break :b i <<= 1;}) {}155 while (i >> bits_minus_1 == 0) : (b: {
156 ex -= 1;
157 i <<= 1;
158 }) {}
143 ux <<= log2uint(@bitCast(u32, -ex + 1));159 ux <<= log2uint(@bitCast(u32, -ex + 1));
144 } else {160 } else {
145 ux &= @maxValue(uint) >> exp_bits;161 ux &= @maxValue(uint) >> exp_bits;
...@@ -147,7 +163,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T {...@@ -147,7 +163,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T {
147 }163 }
148 if (ey == 0) {164 if (ey == 0) {
149 i = uy << exp_bits;165 i = uy << exp_bits;
150 while (i >> bits_minus_1 == 0) : (b: {ey -= 1; break :b i <<= 1;}) {}166 while (i >> bits_minus_1 == 0) : (b: {
167 ey -= 1;
168 i <<= 1;
169 }) {}
151 uy <<= log2uint(@bitCast(u32, -ey + 1));170 uy <<= log2uint(@bitCast(u32, -ey + 1));
152 } else {171 } else {
153 uy &= @maxValue(uint) >> exp_bits;172 uy &= @maxValue(uint) >> exp_bits;
...@@ -170,7 +189,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T {...@@ -170,7 +189,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T {
170 return 0 * x;189 return 0 * x;
171 ux = i;190 ux = i;
172 }191 }
173 while (ux >> digits == 0) : (b: {ux <<= 1; break :b ex -= 1;}) {}192 while (ux >> digits == 0) : (b: {
193 ux <<= 1;
194 ex -= 1;
195 }) {}
174196
175 // scale result up197 // scale result up
176 if (ex > 0) {198 if (ex > 0) {
...@@ -300,7 +322,7 @@ export fn sqrt(x: f64) f64 {...@@ -300,7 +322,7 @@ export fn sqrt(x: f64) f64 {
300322
301 // rounding direction323 // rounding direction
302 if (ix0 | ix1 != 0) {324 if (ix0 | ix1 != 0) {
303 var z = 1.0 - tiny; // raise inexact325 var z = 1.0 - tiny; // raise inexact
304 if (z >= 1.0) {326 if (z >= 1.0) {
305 z = 1.0 + tiny;327 z = 1.0 + tiny;
306 if (q1 == 0xFFFFFFFF) {328 if (q1 == 0xFFFFFFFF) {
...@@ -338,13 +360,13 @@ export fn sqrtf(x: f32) f32 {...@@ -338,13 +360,13 @@ export fn sqrtf(x: f32) f32 {
338 var ix: i32 = @bitCast(i32, x);360 var ix: i32 = @bitCast(i32, x);
339361
340 if ((ix & 0x7F800000) == 0x7F800000) {362 if ((ix & 0x7F800000) == 0x7F800000) {
341 return x * x + x; // sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = snan363 return x * x + x; // sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = snan
342 }364 }
343365
344 // zero366 // zero
345 if (ix <= 0) {367 if (ix <= 0) {
346 if (ix & ~sign == 0) {368 if (ix & ~sign == 0) {
347 return x; // sqrt (+-0) = +-0369 return x; // sqrt (+-0) = +-0
348 }370 }
349 if (ix < 0) {371 if (ix < 0) {
350 return math.snan(f32);372 return math.snan(f32);
...@@ -362,20 +384,20 @@ export fn sqrtf(x: f32) f32 {...@@ -362,20 +384,20 @@ export fn sqrtf(x: f32) f32 {
362 m -= i - 1;384 m -= i - 1;
363 }385 }
364386
365 m -= 127; // unbias exponent387 m -= 127; // unbias exponent
366 ix = (ix & 0x007FFFFF) | 0x00800000;388 ix = (ix & 0x007FFFFF) | 0x00800000;
367389
368 if (m & 1 != 0) { // odd m, double x to even390 if (m & 1 != 0) { // odd m, double x to even
369 ix += ix;391 ix += ix;
370 }392 }
371393
372 m >>= 1; // m = [m / 2]394 m >>= 1; // m = [m / 2]
373395
374 // sqrt(x) bit by bit396 // sqrt(x) bit by bit
375 ix += ix;397 ix += ix;
376 var q: i32 = 0; // q = sqrt(x)398 var q: i32 = 0; // q = sqrt(x)
377 var s: i32 = 0;399 var s: i32 = 0;
378 var r: i32 = 0x01000000; // r = moving bit right -> left400 var r: i32 = 0x01000000; // r = moving bit right -> left
379401
380 while (r != 0) {402 while (r != 0) {
381 const t = s + r;403 const t = s + r;
...@@ -390,7 +412,7 @@ export fn sqrtf(x: f32) f32 {...@@ -390,7 +412,7 @@ export fn sqrtf(x: f32) f32 {
390412
391 // floating add to find rounding direction413 // floating add to find rounding direction
392 if (ix != 0) {414 if (ix != 0) {
393 var z = 1.0 - tiny; // inexact415 var z = 1.0 - tiny; // inexact
394 if (z >= 1.0) {416 if (z >= 1.0) {
395 z = 1.0 + tiny;417 z = 1.0 + tiny;
396 if (z > 1.0) {418 if (z > 1.0) {
std/special/compiler_rt/comparetf2.zig+25-32
...@@ -38,25 +38,22 @@ pub extern fn __letf2(a: f128, b: f128) c_int {...@@ -38,25 +38,22 @@ pub extern fn __letf2(a: f128, b: f128) c_int {
3838
39 // If at least one of a and b is positive, we get the same result comparing39 // If at least one of a and b is positive, we get the same result comparing
40 // a and b as signed integers as we would with a floating-point compare.40 // a and b as signed integers as we would with a floating-point compare.
41 return if ((aInt & bInt) >= 0)41 return if ((aInt & bInt) >= 0) if (aInt < bInt)
42 if (aInt < bInt)42 LE_LESS
43 LE_LESS43 else if (aInt == bInt)
44 else if (aInt == bInt)44 LE_EQUAL
45 LE_EQUAL
46 else
47 LE_GREATER
48 else45 else
49 // Otherwise, both are negative, so we need to flip the sense of the46 LE_GREATER else
50 // comparison to get the correct result. (This assumes a twos- or ones-47 // Otherwise, both are negative, so we need to flip the sense of the
51 // complement integer representation; if integers are represented in a48 // comparison to get the correct result. (This assumes a twos- or ones-
52 // sign-magnitude representation, then this flip is incorrect).49 // complement integer representation; if integers are represented in a
53 if (aInt > bInt)50 // sign-magnitude representation, then this flip is incorrect).
54 LE_LESS51 if (aInt > bInt)
55 else if (aInt == bInt)52 LE_LESS
56 LE_EQUAL53 else if (aInt == bInt)
57 else54 LE_EQUAL
58 LE_GREATER55 else
59 ;56 LE_GREATER;
60}57}
6158
62// TODO https://github.com/ziglang/zig/issues/30559// TODO https://github.com/ziglang/zig/issues/305
...@@ -76,21 +73,17 @@ pub extern fn __getf2(a: f128, b: f128) c_int {...@@ -76,21 +73,17 @@ pub extern fn __getf2(a: f128, b: f128) c_int {
7673
77 if (aAbs > infRep or bAbs > infRep) return GE_UNORDERED;74 if (aAbs > infRep or bAbs > infRep) return GE_UNORDERED;
78 if ((aAbs | bAbs) == 0) return GE_EQUAL;75 if ((aAbs | bAbs) == 0) return GE_EQUAL;
79 return if ((aInt & bInt) >= 0)76 return if ((aInt & bInt) >= 0) if (aInt < bInt)
80 if (aInt < bInt)77 GE_LESS
81 GE_LESS78 else if (aInt == bInt)
82 else if (aInt == bInt)79 GE_EQUAL
83 GE_EQUAL80 else
84 else81 GE_GREATER else if (aInt > bInt)
85 GE_GREATER82 GE_LESS
83 else if (aInt == bInt)
84 GE_EQUAL
86 else85 else
87 if (aInt > bInt)86 GE_GREATER;
88 GE_LESS
89 else if (aInt == bInt)
90 GE_EQUAL
91 else
92 GE_GREATER
93 ;
94}87}
9588
96pub extern fn __unordtf2(a: f128, b: f128) c_int {89pub extern fn __unordtf2(a: f128, b: f128) c_int {
std/special/compiler_rt/fixunsdfti_test.zig-1
...@@ -44,4 +44,3 @@ test "fixunsdfti" {...@@ -44,4 +44,3 @@ test "fixunsdfti" {
44 test__fixunsdfti(-0x1.FFFFFFFFFFFFFp+62, 0);44 test__fixunsdfti(-0x1.FFFFFFFFFFFFFp+62, 0);
45 test__fixunsdfti(-0x1.FFFFFFFFFFFFEp+62, 0);45 test__fixunsdfti(-0x1.FFFFFFFFFFFFEp+62, 0);
46}46}
47
std/special/compiler_rt/index.zig+11-7
...@@ -78,7 +78,7 @@ const __udivmoddi4 = @import("udivmoddi4.zig").__udivmoddi4;...@@ -78,7 +78,7 @@ const __udivmoddi4 = @import("udivmoddi4.zig").__udivmoddi4;
7878
79// Avoid dragging in the runtime safety mechanisms into this .o file,79// Avoid dragging in the runtime safety mechanisms into this .o file,
80// unless we're trying to test this file.80// unless we're trying to test this file.
81pub fn panic(msg: []const u8, error_return_trace: ?&builtin.StackTrace) noreturn {81pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn {
82 @setCold(true);82 @setCold(true);
83 if (is_test) {83 if (is_test) {
84 std.debug.panic("{}", msg);84 std.debug.panic("{}", msg);
...@@ -92,10 +92,10 @@ pub fn setXmm0(comptime T: type, value: T) void {...@@ -92,10 +92,10 @@ pub fn setXmm0(comptime T: type, value: T) void {
92 const aligned_value: T align(16) = value;92 const aligned_value: T align(16) = value;
93 asm volatile (93 asm volatile (
94 \\movaps (%[ptr]), %%xmm094 \\movaps (%[ptr]), %%xmm0
95 95 :
96 :
97 : [ptr] "r" (&aligned_value)96 : [ptr] "r" (&aligned_value)
98 : "xmm0");97 : "xmm0"
98 );
99}99}
100100
101extern fn __udivdi3(a: u64, b: u64) u64 {101extern fn __udivdi3(a: u64, b: u64) u64 {
...@@ -159,7 +159,8 @@ fn isArmArch() bool {...@@ -159,7 +159,8 @@ fn isArmArch() bool {
159 builtin.Arch.armebv6t2,159 builtin.Arch.armebv6t2,
160 builtin.Arch.armebv5,160 builtin.Arch.armebv5,
161 builtin.Arch.armebv5te,161 builtin.Arch.armebv5te,
162 builtin.Arch.armebv4t => true,162 builtin.Arch.armebv4t,
163 => true,
163 else => false,164 else => false,
164 };165 };
165}166}
...@@ -174,7 +175,10 @@ nakedcc fn __aeabi_uidivmod() void {...@@ -174,7 +175,10 @@ nakedcc fn __aeabi_uidivmod() void {
174 \\ ldr r1, [sp]175 \\ ldr r1, [sp]
175 \\ add sp, sp, #4176 \\ add sp, sp, #4
176 \\ pop { pc }177 \\ pop { pc }
177 ::: "r2", "r1");178 :
179 :
180 : "r2", "r1"
181 );
178}182}
179183
180// _chkstk (_alloca) routine - probe stack between %esp and (%esp-%eax) in 4k increments,184// _chkstk (_alloca) routine - probe stack between %esp and (%esp-%eax) in 4k increments,
...@@ -280,7 +284,7 @@ nakedcc fn ___chkstk_ms() align(4) void {...@@ -280,7 +284,7 @@ nakedcc fn ___chkstk_ms() align(4) void {
280 );284 );
281}285}
282286
283extern fn __udivmodsi4(a: u32, b: u32, rem: &u32) u32 {287extern fn __udivmodsi4(a: u32, b: u32, rem: *u32) u32 {
284 @setRuntimeSafety(is_test);288 @setRuntimeSafety(is_test);
285289
286 const d = __udivsi3(a, b);290 const d = __udivsi3(a, b);
std/special/compiler_rt/udivmod.zig+9-9
...@@ -7,15 +7,15 @@ const low = switch (builtin.endian) {...@@ -7,15 +7,15 @@ const low = switch (builtin.endian) {
7};7};
8const high = 1 - low;8const high = 1 - low;
99
10pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: ?&DoubleInt) DoubleInt {10pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: ?*DoubleInt) DoubleInt {
11 @setRuntimeSafety(is_test);11 @setRuntimeSafety(is_test);
1212
13 const SingleInt = @IntType(false, @divExact(DoubleInt.bit_count, 2));13 const SingleInt = @IntType(false, @divExact(DoubleInt.bit_count, 2));
14 const SignedDoubleInt = @IntType(true, DoubleInt.bit_count);14 const SignedDoubleInt = @IntType(true, DoubleInt.bit_count);
15 const Log2SingleInt = @import("std").math.Log2Int(SingleInt);15 const Log2SingleInt = @import("std").math.Log2Int(SingleInt);
1616
17 const n = @ptrCast(&const [2]SingleInt, &a).*; // TODO issue #42117 const n = @ptrCast(*const [2]SingleInt, &a).*; // TODO issue #421
18 const d = @ptrCast(&const [2]SingleInt, &b).*; // TODO issue #42118 const d = @ptrCast(*const [2]SingleInt, &b).*; // TODO issue #421
19 var q: [2]SingleInt = undefined;19 var q: [2]SingleInt = undefined;
20 var r: [2]SingleInt = undefined;20 var r: [2]SingleInt = undefined;
21 var sr: c_uint = undefined;21 var sr: c_uint = undefined;
...@@ -57,7 +57,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem:...@@ -57,7 +57,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem:
57 if (maybe_rem) |rem| {57 if (maybe_rem) |rem| {
58 r[high] = n[high] % d[high];58 r[high] = n[high] % d[high];
59 r[low] = 0;59 r[low] = 0;
60 rem.* = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #42160 rem.* = @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421
61 }61 }
62 return n[high] / d[high];62 return n[high] / d[high];
63 }63 }
...@@ -69,7 +69,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem:...@@ -69,7 +69,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem:
69 if (maybe_rem) |rem| {69 if (maybe_rem) |rem| {
70 r[low] = n[low];70 r[low] = n[low];
71 r[high] = n[high] & (d[high] - 1);71 r[high] = n[high] & (d[high] - 1);
72 rem.* = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #42172 rem.* = @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421
73 }73 }
74 return n[high] >> Log2SingleInt(@ctz(d[high]));74 return n[high] >> Log2SingleInt(@ctz(d[high]));
75 }75 }
...@@ -109,7 +109,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem:...@@ -109,7 +109,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem:
109 sr = @ctz(d[low]);109 sr = @ctz(d[low]);
110 q[high] = n[high] >> Log2SingleInt(sr);110 q[high] = n[high] >> Log2SingleInt(sr);
111 q[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr));111 q[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr));
112 return @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0]).*; // TODO issue #421112 return @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &q[0]).*; // TODO issue #421
113 }113 }
114 // K X114 // K X
115 // ---115 // ---
...@@ -183,13 +183,13 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem:...@@ -183,13 +183,13 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem:
183 // r.all -= b;183 // r.all -= b;
184 // carry = 1;184 // carry = 1;
185 // }185 // }
186 r_all = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421186 r_all = @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421
187 const s: SignedDoubleInt = SignedDoubleInt(b -% r_all -% 1) >> (DoubleInt.bit_count - 1);187 const s: SignedDoubleInt = SignedDoubleInt(b -% r_all -% 1) >> (DoubleInt.bit_count - 1);
188 carry = u32(s & 1);188 carry = u32(s & 1);
189 r_all -= b & @bitCast(DoubleInt, s);189 r_all -= b & @bitCast(DoubleInt, s);
190 r = @ptrCast(&[2]SingleInt, &r_all).*; // TODO issue #421190 r = @ptrCast(*[2]SingleInt, &r_all).*; // TODO issue #421
191 }191 }
192 const q_all = ((@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0]).*) << 1) | carry; // TODO issue #421192 const q_all = ((@ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &q[0]).*) << 1) | carry; // TODO issue #421
193 if (maybe_rem) |rem| {193 if (maybe_rem) |rem| {
194 rem.* = r_all;194 rem.* = r_all;
195 }195 }
std/special/compiler_rt/udivmoddi4.zig+1-1
...@@ -1,7 +1,7 @@...@@ -1,7 +1,7 @@
1const udivmod = @import("udivmod.zig").udivmod;1const udivmod = @import("udivmod.zig").udivmod;
2const builtin = @import("builtin");2const builtin = @import("builtin");
33
4pub extern fn __udivmoddi4(a: u64, b: u64, maybe_rem: ?&u64) u64 {4pub extern fn __udivmoddi4(a: u64, b: u64, maybe_rem: ?*u64) u64 {
5 @setRuntimeSafety(builtin.is_test);5 @setRuntimeSafety(builtin.is_test);
6 return udivmod(u64, a, b, maybe_rem);6 return udivmod(u64, a, b, maybe_rem);
7}7}
std/special/compiler_rt/udivmodti4.zig+2-2
...@@ -2,12 +2,12 @@ const udivmod = @import("udivmod.zig").udivmod;...@@ -2,12 +2,12 @@ const udivmod = @import("udivmod.zig").udivmod;
2const builtin = @import("builtin");2const builtin = @import("builtin");
3const compiler_rt = @import("index.zig");3const compiler_rt = @import("index.zig");
44
5pub extern fn __udivmodti4(a: u128, b: u128, maybe_rem: ?&u128) u128 {5pub extern fn __udivmodti4(a: u128, b: u128, maybe_rem: ?*u128) u128 {
6 @setRuntimeSafety(builtin.is_test);6 @setRuntimeSafety(builtin.is_test);
7 return udivmod(u128, a, b, maybe_rem);7 return udivmod(u128, a, b, maybe_rem);
8}8}
99
10pub extern fn __udivmodti4_windows_x86_64(a: &const u128, b: &const u128, maybe_rem: ?&u128) void {10pub extern fn __udivmodti4_windows_x86_64(a: *const u128, b: *const u128, maybe_rem: ?*u128) void {
11 @setRuntimeSafety(builtin.is_test);11 @setRuntimeSafety(builtin.is_test);
12 compiler_rt.setXmm0(u128, udivmod(u128, a.*, b.*, maybe_rem));12 compiler_rt.setXmm0(u128, udivmod(u128, a.*, b.*, maybe_rem));
13}13}
std/special/compiler_rt/udivti3.zig+1-1
...@@ -6,7 +6,7 @@ pub extern fn __udivti3(a: u128, b: u128) u128 {...@@ -6,7 +6,7 @@ pub extern fn __udivti3(a: u128, b: u128) u128 {
6 return udivmodti4.__udivmodti4(a, b, null);6 return udivmodti4.__udivmodti4(a, b, null);
7}7}
88
9pub extern fn __udivti3_windows_x86_64(a: &const u128, b: &const u128) void {9pub extern fn __udivti3_windows_x86_64(a: *const u128, b: *const u128) void {
10 @setRuntimeSafety(builtin.is_test);10 @setRuntimeSafety(builtin.is_test);
11 udivmodti4.__udivmodti4_windows_x86_64(a, b, null);11 udivmodti4.__udivmodti4_windows_x86_64(a, b, null);
12}12}
std/special/compiler_rt/umodti3.zig+1-1
...@@ -9,7 +9,7 @@ pub extern fn __umodti3(a: u128, b: u128) u128 {...@@ -9,7 +9,7 @@ pub extern fn __umodti3(a: u128, b: u128) u128 {
9 return r;9 return r;
10}10}
1111
12pub extern fn __umodti3_windows_x86_64(a: &const u128, b: &const u128) void {12pub extern fn __umodti3_windows_x86_64(a: *const u128, b: *const u128) void {
13 @setRuntimeSafety(builtin.is_test);13 @setRuntimeSafety(builtin.is_test);
14 compiler_rt.setXmm0(u128, __umodti3(a.*, b.*));14 compiler_rt.setXmm0(u128, __umodti3(a.*, b.*));
15}15}
std/special/panic.zig+1-1
...@@ -6,7 +6,7 @@...@@ -6,7 +6,7 @@
6const builtin = @import("builtin");6const builtin = @import("builtin");
7const std = @import("std");7const std = @import("std");
88
9pub fn panic(msg: []const u8, error_return_trace: ?&builtin.StackTrace) noreturn {9pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn {
10 @setCold(true);10 @setCold(true);
11 switch (builtin.os) {11 switch (builtin.os) {
12 // TODO: fix panic in zen.12 // TODO: fix panic in zen.
std/unicode.zig+16-12
...@@ -58,6 +58,7 @@ pub fn utf8Encode(c: u32, out: []u8) !u3 {...@@ -58,6 +58,7 @@ pub fn utf8Encode(c: u32, out: []u8) !u3 {
58}58}
5959
60const Utf8DecodeError = Utf8Decode2Error || Utf8Decode3Error || Utf8Decode4Error;60const Utf8DecodeError = Utf8Decode2Error || Utf8Decode3Error || Utf8Decode4Error;
61
61/// Decodes the UTF-8 codepoint encoded in the given slice of bytes.62/// Decodes the UTF-8 codepoint encoded in the given slice of bytes.
62/// bytes.len must be equal to utf8ByteSequenceLength(bytes[0]) catch unreachable.63/// bytes.len must be equal to utf8ByteSequenceLength(bytes[0]) catch unreachable.
63/// If you already know the length at comptime, you can call one of64/// If you already know the length at comptime, you can call one of
...@@ -150,7 +151,9 @@ pub fn utf8ValidateSlice(s: []const u8) bool {...@@ -150,7 +151,9 @@ pub fn utf8ValidateSlice(s: []const u8) bool {
150 return false;151 return false;
151 }152 }
152153
153 if (utf8Decode(s[i..i+cp_len])) |_| {} else |_| { return false; }154 if (utf8Decode(s[i .. i + cp_len])) |_| {} else |_| {
155 return false;
156 }
154 i += cp_len;157 i += cp_len;
155 } else |err| {158 } else |err| {
156 return false;159 return false;
...@@ -179,9 +182,7 @@ pub const Utf8View = struct {...@@ -179,9 +182,7 @@ pub const Utf8View = struct {
179 }182 }
180183
181 pub fn initUnchecked(s: []const u8) Utf8View {184 pub fn initUnchecked(s: []const u8) Utf8View {
182 return Utf8View {185 return Utf8View{ .bytes = s };
183 .bytes = s,
184 };
185 }186 }
186187
187 pub fn initComptime(comptime s: []const u8) Utf8View {188 pub fn initComptime(comptime s: []const u8) Utf8View {
...@@ -191,12 +192,12 @@ pub const Utf8View = struct {...@@ -191,12 +192,12 @@ pub const Utf8View = struct {
191 error.InvalidUtf8 => {192 error.InvalidUtf8 => {
192 @compileError("invalid utf8");193 @compileError("invalid utf8");
193 unreachable;194 unreachable;
194 }195 },
195 }196 }
196 }197 }
197198
198 pub fn iterator(s: &const Utf8View) Utf8Iterator {199 pub fn iterator(s: *const Utf8View) Utf8Iterator {
199 return Utf8Iterator {200 return Utf8Iterator{
200 .bytes = s.bytes,201 .bytes = s.bytes,
201 .i = 0,202 .i = 0,
202 };203 };
...@@ -207,7 +208,7 @@ const Utf8Iterator = struct {...@@ -207,7 +208,7 @@ const Utf8Iterator = struct {
207 bytes: []const u8,208 bytes: []const u8,
208 i: usize,209 i: usize,
209210
210 pub fn nextCodepointSlice(it: &Utf8Iterator) ?[]const u8 {211 pub fn nextCodepointSlice(it: *Utf8Iterator) ?[]const u8 {
211 if (it.i >= it.bytes.len) {212 if (it.i >= it.bytes.len) {
212 return null;213 return null;
213 }214 }
...@@ -215,10 +216,10 @@ const Utf8Iterator = struct {...@@ -215,10 +216,10 @@ const Utf8Iterator = struct {
215 const cp_len = utf8ByteSequenceLength(it.bytes[it.i]) catch unreachable;216 const cp_len = utf8ByteSequenceLength(it.bytes[it.i]) catch unreachable;
216217
217 it.i += cp_len;218 it.i += cp_len;
218 return it.bytes[it.i-cp_len..it.i];219 return it.bytes[it.i - cp_len .. it.i];
219 }220 }
220221
221 pub fn nextCodepoint(it: &Utf8Iterator) ?u32 {222 pub fn nextCodepoint(it: *Utf8Iterator) ?u32 {
222 const slice = it.nextCodepointSlice() ?? return null;223 const slice = it.nextCodepointSlice() ?? return null;
223224
224 switch (slice.len) {225 switch (slice.len) {
...@@ -304,9 +305,12 @@ test "utf8 view bad" {...@@ -304,9 +305,12 @@ test "utf8 view bad" {
304fn testUtf8ViewBad() void {305fn testUtf8ViewBad() void {
305 // Compile-time error.306 // Compile-time error.
306 // const s3 = Utf8View.initComptime("\xfe\xf2");307 // const s3 = Utf8View.initComptime("\xfe\xf2");
307
308 const s = Utf8View.init("hel\xadlo");308 const s = Utf8View.init("hel\xadlo");
309 if (s) |_| { unreachable; } else |err| { debug.assert(err == error.InvalidUtf8); }309 if (s) |_| {
310 unreachable;
311 } else |err| {
312 debug.assert(err == error.InvalidUtf8);
313 }
310}314}
311315
312test "utf8 view ok" {316test "utf8 view ok" {
std/zig/ast.zig+298-293
...@@ -9,26 +9,26 @@ pub const TokenIndex = usize;...@@ -9,26 +9,26 @@ pub const TokenIndex = usize;
9pub const Tree = struct {9pub const Tree = struct {
10 source: []const u8,10 source: []const u8,
11 tokens: TokenList,11 tokens: TokenList,
12 root_node: &Node.Root,12 root_node: *Node.Root,
13 arena_allocator: std.heap.ArenaAllocator,13 arena_allocator: std.heap.ArenaAllocator,
14 errors: ErrorList,14 errors: ErrorList,
1515
16 pub const TokenList = SegmentedList(Token, 64);16 pub const TokenList = SegmentedList(Token, 64);
17 pub const ErrorList = SegmentedList(Error, 0);17 pub const ErrorList = SegmentedList(Error, 0);
1818
19 pub fn deinit(self: &Tree) void {19 pub fn deinit(self: *Tree) void {
20 self.arena_allocator.deinit();20 self.arena_allocator.deinit();
21 }21 }
2222
23 pub fn renderError(self: &Tree, parse_error: &Error, stream: var) !void {23 pub fn renderError(self: *Tree, parse_error: *Error, stream: var) !void {
24 return parse_error.render(&self.tokens, stream);24 return parse_error.render(&self.tokens, stream);
25 }25 }
2626
27 pub fn tokenSlice(self: &Tree, token_index: TokenIndex) []const u8 {27 pub fn tokenSlice(self: *Tree, token_index: TokenIndex) []const u8 {
28 return self.tokenSlicePtr(self.tokens.at(token_index));28 return self.tokenSlicePtr(self.tokens.at(token_index));
29 }29 }
3030
31 pub fn tokenSlicePtr(self: &Tree, token: &const Token) []const u8 {31 pub fn tokenSlicePtr(self: *Tree, token: *const Token) []const u8 {
32 return self.source[token.start..token.end];32 return self.source[token.start..token.end];
33 }33 }
3434
...@@ -39,7 +39,7 @@ pub const Tree = struct {...@@ -39,7 +39,7 @@ pub const Tree = struct {
39 line_end: usize,39 line_end: usize,
40 };40 };
4141
42 pub fn tokenLocationPtr(self: &Tree, start_index: usize, token: &const Token) Location {42 pub fn tokenLocationPtr(self: *Tree, start_index: usize, token: *const Token) Location {
43 var loc = Location{43 var loc = Location{
44 .line = 0,44 .line = 0,
45 .column = 0,45 .column = 0,
...@@ -64,24 +64,24 @@ pub const Tree = struct {...@@ -64,24 +64,24 @@ pub const Tree = struct {
64 return loc;64 return loc;
65 }65 }
6666
67 pub fn tokenLocation(self: &Tree, start_index: usize, token_index: TokenIndex) Location {67 pub fn tokenLocation(self: *Tree, start_index: usize, token_index: TokenIndex) Location {
68 return self.tokenLocationPtr(start_index, self.tokens.at(token_index));68 return self.tokenLocationPtr(start_index, self.tokens.at(token_index));
69 }69 }
7070
71 pub fn tokensOnSameLine(self: &Tree, token1_index: TokenIndex, token2_index: TokenIndex) bool {71 pub fn tokensOnSameLine(self: *Tree, token1_index: TokenIndex, token2_index: TokenIndex) bool {
72 return self.tokensOnSameLinePtr(self.tokens.at(token1_index), self.tokens.at(token2_index));72 return self.tokensOnSameLinePtr(self.tokens.at(token1_index), self.tokens.at(token2_index));
73 }73 }
7474
75 pub fn tokensOnSameLinePtr(self: &Tree, token1: &const Token, token2: &const Token) bool {75 pub fn tokensOnSameLinePtr(self: *Tree, token1: *const Token, token2: *const Token) bool {
76 return mem.indexOfScalar(u8, self.source[token1.end..token2.start], '\n') == null;76 return mem.indexOfScalar(u8, self.source[token1.end..token2.start], '\n') == null;
77 }77 }
7878
79 pub fn dump(self: &Tree) void {79 pub fn dump(self: *Tree) void {
80 self.root_node.base.dump(0);80 self.root_node.base.dump(0);
81 }81 }
8282
83 /// Skips over comments83 /// Skips over comments
84 pub fn prevToken(self: &Tree, token_index: TokenIndex) TokenIndex {84 pub fn prevToken(self: *Tree, token_index: TokenIndex) TokenIndex {
85 var index = token_index - 1;85 var index = token_index - 1;
86 while (self.tokens.at(index).id == Token.Id.LineComment) {86 while (self.tokens.at(index).id == Token.Id.LineComment) {
87 index -= 1;87 index -= 1;
...@@ -90,7 +90,7 @@ pub const Tree = struct {...@@ -90,7 +90,7 @@ pub const Tree = struct {
90 }90 }
9191
92 /// Skips over comments92 /// Skips over comments
93 pub fn nextToken(self: &Tree, token_index: TokenIndex) TokenIndex {93 pub fn nextToken(self: *Tree, token_index: TokenIndex) TokenIndex {
94 var index = token_index + 1;94 var index = token_index + 1;
95 while (self.tokens.at(index).id == Token.Id.LineComment) {95 while (self.tokens.at(index).id == Token.Id.LineComment) {
96 index += 1;96 index += 1;
...@@ -120,7 +120,7 @@ pub const Error = union(enum) {...@@ -120,7 +120,7 @@ pub const Error = union(enum) {
120 ExpectedToken: ExpectedToken,120 ExpectedToken: ExpectedToken,
121 ExpectedCommaOrEnd: ExpectedCommaOrEnd,121 ExpectedCommaOrEnd: ExpectedCommaOrEnd,
122122
123 pub fn render(self: &Error, tokens: &Tree.TokenList, stream: var) !void {123 pub fn render(self: *const Error, tokens: *Tree.TokenList, stream: var) !void {
124 switch (self.*) {124 switch (self.*) {
125 // TODO https://github.com/ziglang/zig/issues/683125 // TODO https://github.com/ziglang/zig/issues/683
126 @TagType(Error).InvalidToken => |*x| return x.render(tokens, stream),126 @TagType(Error).InvalidToken => |*x| return x.render(tokens, stream),
...@@ -145,7 +145,7 @@ pub const Error = union(enum) {...@@ -145,7 +145,7 @@ pub const Error = union(enum) {
145 }145 }
146 }146 }
147147
148 pub fn loc(self: &Error) TokenIndex {148 pub fn loc(self: *const Error) TokenIndex {
149 switch (self.*) {149 switch (self.*) {
150 // TODO https://github.com/ziglang/zig/issues/683150 // TODO https://github.com/ziglang/zig/issues/683
151 @TagType(Error).InvalidToken => |x| return x.token,151 @TagType(Error).InvalidToken => |x| return x.token,
...@@ -188,17 +188,17 @@ pub const Error = union(enum) {...@@ -188,17 +188,17 @@ pub const Error = union(enum) {
188 pub const ExtraVolatileQualifier = SimpleError("Extra volatile qualifier");188 pub const ExtraVolatileQualifier = SimpleError("Extra volatile qualifier");
189189
190 pub const ExpectedCall = struct {190 pub const ExpectedCall = struct {
191 node: &Node,191 node: *Node,
192192
193 pub fn render(self: &ExpectedCall, tokens: &Tree.TokenList, stream: var) !void {193 pub fn render(self: *const ExpectedCall, tokens: *Tree.TokenList, stream: var) !void {
194 return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ ", found {}", @tagName(self.node.id));194 return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ ", found {}", @tagName(self.node.id));
195 }195 }
196 };196 };
197197
198 pub const ExpectedCallOrFnProto = struct {198 pub const ExpectedCallOrFnProto = struct {
199 node: &Node,199 node: *Node,
200200
201 pub fn render(self: &ExpectedCallOrFnProto, tokens: &Tree.TokenList, stream: var) !void {201 pub fn render(self: *const ExpectedCallOrFnProto, tokens: *Tree.TokenList, stream: var) !void {
202 return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ " or " ++ @tagName(Node.Id.FnProto) ++ ", found {}", @tagName(self.node.id));202 return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ " or " ++ @tagName(Node.Id.FnProto) ++ ", found {}", @tagName(self.node.id));
203 }203 }
204 };204 };
...@@ -207,7 +207,7 @@ pub const Error = union(enum) {...@@ -207,7 +207,7 @@ pub const Error = union(enum) {
207 token: TokenIndex,207 token: TokenIndex,
208 expected_id: @TagType(Token.Id),208 expected_id: @TagType(Token.Id),
209209
210 pub fn render(self: &ExpectedToken, tokens: &Tree.TokenList, stream: var) !void {210 pub fn render(self: *const ExpectedToken, tokens: *Tree.TokenList, stream: var) !void {
211 const token_name = @tagName(tokens.at(self.token).id);211 const token_name = @tagName(tokens.at(self.token).id);
212 return stream.print("expected {}, found {}", @tagName(self.expected_id), token_name);212 return stream.print("expected {}, found {}", @tagName(self.expected_id), token_name);
213 }213 }
...@@ -217,7 +217,7 @@ pub const Error = union(enum) {...@@ -217,7 +217,7 @@ pub const Error = union(enum) {
217 token: TokenIndex,217 token: TokenIndex,
218 end_id: @TagType(Token.Id),218 end_id: @TagType(Token.Id),
219219
220 pub fn render(self: &ExpectedCommaOrEnd, tokens: &Tree.TokenList, stream: var) !void {220 pub fn render(self: *const ExpectedCommaOrEnd, tokens: *Tree.TokenList, stream: var) !void {
221 const token_name = @tagName(tokens.at(self.token).id);221 const token_name = @tagName(tokens.at(self.token).id);
222 return stream.print("expected ',' or {}, found {}", @tagName(self.end_id), token_name);222 return stream.print("expected ',' or {}, found {}", @tagName(self.end_id), token_name);
223 }223 }
...@@ -229,7 +229,7 @@ pub const Error = union(enum) {...@@ -229,7 +229,7 @@ pub const Error = union(enum) {
229229
230 token: TokenIndex,230 token: TokenIndex,
231231
232 pub fn render(self: &ThisError, tokens: &Tree.TokenList, stream: var) !void {232 pub fn render(self: *const ThisError, tokens: *Tree.TokenList, stream: var) !void {
233 const token_name = @tagName(tokens.at(self.token).id);233 const token_name = @tagName(tokens.at(self.token).id);
234 return stream.print(msg, token_name);234 return stream.print(msg, token_name);
235 }235 }
...@@ -242,7 +242,7 @@ pub const Error = union(enum) {...@@ -242,7 +242,7 @@ pub const Error = union(enum) {
242242
243 token: TokenIndex,243 token: TokenIndex,
244244
245 pub fn render(self: &ThisError, tokens: &Tree.TokenList, stream: var) !void {245 pub fn render(self: *const ThisError, tokens: *Tree.TokenList, stream: var) !void {
246 return stream.write(msg);246 return stream.write(msg);
247 }247 }
248 };248 };
...@@ -320,14 +320,14 @@ pub const Node = struct {...@@ -320,14 +320,14 @@ pub const Node = struct {
320 FieldInitializer,320 FieldInitializer,
321 };321 };
322322
323 pub fn cast(base: &Node, comptime T: type) ?&T {323 pub fn cast(base: *Node, comptime T: type) ?*T {
324 if (base.id == comptime typeToId(T)) {324 if (base.id == comptime typeToId(T)) {
325 return @fieldParentPtr(T, "base", base);325 return @fieldParentPtr(T, "base", base);
326 }326 }
327 return null;327 return null;
328 }328 }
329329
330 pub fn iterate(base: &Node, index: usize) ?&Node {330 pub fn iterate(base: *Node, index: usize) ?*Node {
331 comptime var i = 0;331 comptime var i = 0;
332 inline while (i < @memberCount(Id)) : (i += 1) {332 inline while (i < @memberCount(Id)) : (i += 1) {
333 if (base.id == @field(Id, @memberName(Id, i))) {333 if (base.id == @field(Id, @memberName(Id, i))) {
...@@ -338,7 +338,7 @@ pub const Node = struct {...@@ -338,7 +338,7 @@ pub const Node = struct {
338 unreachable;338 unreachable;
339 }339 }
340340
341 pub fn firstToken(base: &Node) TokenIndex {341 pub fn firstToken(base: *Node) TokenIndex {
342 comptime var i = 0;342 comptime var i = 0;
343 inline while (i < @memberCount(Id)) : (i += 1) {343 inline while (i < @memberCount(Id)) : (i += 1) {
344 if (base.id == @field(Id, @memberName(Id, i))) {344 if (base.id == @field(Id, @memberName(Id, i))) {
...@@ -349,7 +349,7 @@ pub const Node = struct {...@@ -349,7 +349,7 @@ pub const Node = struct {
349 unreachable;349 unreachable;
350 }350 }
351351
352 pub fn lastToken(base: &Node) TokenIndex {352 pub fn lastToken(base: *Node) TokenIndex {
353 comptime var i = 0;353 comptime var i = 0;
354 inline while (i < @memberCount(Id)) : (i += 1) {354 inline while (i < @memberCount(Id)) : (i += 1) {
355 if (base.id == @field(Id, @memberName(Id, i))) {355 if (base.id == @field(Id, @memberName(Id, i))) {
...@@ -370,7 +370,7 @@ pub const Node = struct {...@@ -370,7 +370,7 @@ pub const Node = struct {
370 unreachable;370 unreachable;
371 }371 }
372372
373 pub fn requireSemiColon(base: &const Node) bool {373 pub fn requireSemiColon(base: *const Node) bool {
374 var n = base;374 var n = base;
375 while (true) {375 while (true) {
376 switch (n.id) {376 switch (n.id) {
...@@ -388,7 +388,8 @@ pub const Node = struct {...@@ -388,7 +388,8 @@ pub const Node = struct {
388 Id.SwitchElse,388 Id.SwitchElse,
389 Id.FieldInitializer,389 Id.FieldInitializer,
390 Id.DocComment,390 Id.DocComment,
391 Id.TestDecl => return false,391 Id.TestDecl,
392 => return false,
392 Id.While => {393 Id.While => {
393 const while_node = @fieldParentPtr(While, "base", n);394 const while_node = @fieldParentPtr(While, "base", n);
394 if (while_node.@"else") |@"else"| {395 if (while_node.@"else") |@"else"| {
...@@ -442,7 +443,7 @@ pub const Node = struct {...@@ -442,7 +443,7 @@ pub const Node = struct {
442 }443 }
443 }444 }
444445
445 pub fn dump(self: &Node, indent: usize) void {446 pub fn dump(self: *Node, indent: usize) void {
446 {447 {
447 var i: usize = 0;448 var i: usize = 0;
448 while (i < indent) : (i += 1) {449 while (i < indent) : (i += 1) {
...@@ -459,44 +460,44 @@ pub const Node = struct {...@@ -459,44 +460,44 @@ pub const Node = struct {
459460
460 pub const Root = struct {461 pub const Root = struct {
461 base: Node,462 base: Node,
462 doc_comments: ?&DocComment,463 doc_comments: ?*DocComment,
463 decls: DeclList,464 decls: DeclList,
464 eof_token: TokenIndex,465 eof_token: TokenIndex,
465466
466 pub const DeclList = SegmentedList(&Node, 4);467 pub const DeclList = SegmentedList(*Node, 4);
467468
468 pub fn iterate(self: &Root, index: usize) ?&Node {469 pub fn iterate(self: *Root, index: usize) ?*Node {
469 if (index < self.decls.len) {470 if (index < self.decls.len) {
470 return self.decls.at(index).*;471 return self.decls.at(index).*;
471 }472 }
472 return null;473 return null;
473 }474 }
474475
475 pub fn firstToken(self: &Root) TokenIndex {476 pub fn firstToken(self: *Root) TokenIndex {
476 return if (self.decls.len == 0) self.eof_token else (self.decls.at(0).*).firstToken();477 return if (self.decls.len == 0) self.eof_token else (self.decls.at(0).*).firstToken();
477 }478 }
478479
479 pub fn lastToken(self: &Root) TokenIndex {480 pub fn lastToken(self: *Root) TokenIndex {
480 return if (self.decls.len == 0) self.eof_token else (self.decls.at(self.decls.len - 1).*).lastToken();481 return if (self.decls.len == 0) self.eof_token else (self.decls.at(self.decls.len - 1).*).lastToken();
481 }482 }
482 };483 };
483484
484 pub const VarDecl = struct {485 pub const VarDecl = struct {
485 base: Node,486 base: Node,
486 doc_comments: ?&DocComment,487 doc_comments: ?*DocComment,
487 visib_token: ?TokenIndex,488 visib_token: ?TokenIndex,
488 name_token: TokenIndex,489 name_token: TokenIndex,
489 eq_token: TokenIndex,490 eq_token: TokenIndex,
490 mut_token: TokenIndex,491 mut_token: TokenIndex,
491 comptime_token: ?TokenIndex,492 comptime_token: ?TokenIndex,
492 extern_export_token: ?TokenIndex,493 extern_export_token: ?TokenIndex,
493 lib_name: ?&Node,494 lib_name: ?*Node,
494 type_node: ?&Node,495 type_node: ?*Node,
495 align_node: ?&Node,496 align_node: ?*Node,
496 init_node: ?&Node,497 init_node: ?*Node,
497 semicolon_token: TokenIndex,498 semicolon_token: TokenIndex,
498499
499 pub fn iterate(self: &VarDecl, index: usize) ?&Node {500 pub fn iterate(self: *VarDecl, index: usize) ?*Node {
500 var i = index;501 var i = index;
501502
502 if (self.type_node) |type_node| {503 if (self.type_node) |type_node| {
...@@ -517,7 +518,7 @@ pub const Node = struct {...@@ -517,7 +518,7 @@ pub const Node = struct {
517 return null;518 return null;
518 }519 }
519520
520 pub fn firstToken(self: &VarDecl) TokenIndex {521 pub fn firstToken(self: *VarDecl) TokenIndex {
521 if (self.visib_token) |visib_token| return visib_token;522 if (self.visib_token) |visib_token| return visib_token;
522 if (self.comptime_token) |comptime_token| return comptime_token;523 if (self.comptime_token) |comptime_token| return comptime_token;
523 if (self.extern_export_token) |extern_export_token| return extern_export_token;524 if (self.extern_export_token) |extern_export_token| return extern_export_token;
...@@ -525,20 +526,20 @@ pub const Node = struct {...@@ -525,20 +526,20 @@ pub const Node = struct {
525 return self.mut_token;526 return self.mut_token;
526 }527 }
527528
528 pub fn lastToken(self: &VarDecl) TokenIndex {529 pub fn lastToken(self: *VarDecl) TokenIndex {
529 return self.semicolon_token;530 return self.semicolon_token;
530 }531 }
531 };532 };
532533
533 pub const Use = struct {534 pub const Use = struct {
534 base: Node,535 base: Node,
535 doc_comments: ?&DocComment,536 doc_comments: ?*DocComment,
536 visib_token: ?TokenIndex,537 visib_token: ?TokenIndex,
537 use_token: TokenIndex,538 use_token: TokenIndex,
538 expr: &Node,539 expr: *Node,
539 semicolon_token: TokenIndex,540 semicolon_token: TokenIndex,
540541
541 pub fn iterate(self: &Use, index: usize) ?&Node {542 pub fn iterate(self: *Use, index: usize) ?*Node {
542 var i = index;543 var i = index;
543544
544 if (i < 1) return self.expr;545 if (i < 1) return self.expr;
...@@ -547,12 +548,12 @@ pub const Node = struct {...@@ -547,12 +548,12 @@ pub const Node = struct {
547 return null;548 return null;
548 }549 }
549550
550 pub fn firstToken(self: &Use) TokenIndex {551 pub fn firstToken(self: *Use) TokenIndex {
551 if (self.visib_token) |visib_token| return visib_token;552 if (self.visib_token) |visib_token| return visib_token;
552 return self.use_token;553 return self.use_token;
553 }554 }
554555
555 pub fn lastToken(self: &Use) TokenIndex {556 pub fn lastToken(self: *Use) TokenIndex {
556 return self.semicolon_token;557 return self.semicolon_token;
557 }558 }
558 };559 };
...@@ -563,9 +564,9 @@ pub const Node = struct {...@@ -563,9 +564,9 @@ pub const Node = struct {
563 decls: DeclList,564 decls: DeclList,
564 rbrace_token: TokenIndex,565 rbrace_token: TokenIndex,
565566
566 pub const DeclList = SegmentedList(&Node, 2);567 pub const DeclList = SegmentedList(*Node, 2);
567568
568 pub fn iterate(self: &ErrorSetDecl, index: usize) ?&Node {569 pub fn iterate(self: *ErrorSetDecl, index: usize) ?*Node {
569 var i = index;570 var i = index;
570571
571 if (i < self.decls.len) return self.decls.at(i).*;572 if (i < self.decls.len) return self.decls.at(i).*;
...@@ -574,11 +575,11 @@ pub const Node = struct {...@@ -574,11 +575,11 @@ pub const Node = struct {
574 return null;575 return null;
575 }576 }
576577
577 pub fn firstToken(self: &ErrorSetDecl) TokenIndex {578 pub fn firstToken(self: *ErrorSetDecl) TokenIndex {
578 return self.error_token;579 return self.error_token;
579 }580 }
580581
581 pub fn lastToken(self: &ErrorSetDecl) TokenIndex {582 pub fn lastToken(self: *ErrorSetDecl) TokenIndex {
582 return self.rbrace_token;583 return self.rbrace_token;
583 }584 }
584 };585 };
...@@ -596,11 +597,11 @@ pub const Node = struct {...@@ -596,11 +597,11 @@ pub const Node = struct {
596597
597 const InitArg = union(enum) {598 const InitArg = union(enum) {
598 None,599 None,
599 Enum: ?&Node,600 Enum: ?*Node,
600 Type: &Node,601 Type: *Node,
601 };602 };
602603
603 pub fn iterate(self: &ContainerDecl, index: usize) ?&Node {604 pub fn iterate(self: *ContainerDecl, index: usize) ?*Node {
604 var i = index;605 var i = index;
605606
606 switch (self.init_arg_expr) {607 switch (self.init_arg_expr) {
...@@ -608,8 +609,7 @@ pub const Node = struct {...@@ -608,8 +609,7 @@ pub const Node = struct {
608 if (i < 1) return t;609 if (i < 1) return t;
609 i -= 1;610 i -= 1;
610 },611 },
611 InitArg.None,612 InitArg.None, InitArg.Enum => {},
612 InitArg.Enum => {},
613 }613 }
614614
615 if (i < self.fields_and_decls.len) return self.fields_and_decls.at(i).*;615 if (i < self.fields_and_decls.len) return self.fields_and_decls.at(i).*;
...@@ -618,26 +618,26 @@ pub const Node = struct {...@@ -618,26 +618,26 @@ pub const Node = struct {
618 return null;618 return null;
619 }619 }
620620
621 pub fn firstToken(self: &ContainerDecl) TokenIndex {621 pub fn firstToken(self: *ContainerDecl) TokenIndex {
622 if (self.layout_token) |layout_token| {622 if (self.layout_token) |layout_token| {
623 return layout_token;623 return layout_token;
624 }624 }
625 return self.kind_token;625 return self.kind_token;
626 }626 }
627627
628 pub fn lastToken(self: &ContainerDecl) TokenIndex {628 pub fn lastToken(self: *ContainerDecl) TokenIndex {
629 return self.rbrace_token;629 return self.rbrace_token;
630 }630 }
631 };631 };
632632
633 pub const StructField = struct {633 pub const StructField = struct {
634 base: Node,634 base: Node,
635 doc_comments: ?&DocComment,635 doc_comments: ?*DocComment,
636 visib_token: ?TokenIndex,636 visib_token: ?TokenIndex,
637 name_token: TokenIndex,637 name_token: TokenIndex,
638 type_expr: &Node,638 type_expr: *Node,
639639
640 pub fn iterate(self: &StructField, index: usize) ?&Node {640 pub fn iterate(self: *StructField, index: usize) ?*Node {
641 var i = index;641 var i = index;
642642
643 if (i < 1) return self.type_expr;643 if (i < 1) return self.type_expr;
...@@ -646,24 +646,24 @@ pub const Node = struct {...@@ -646,24 +646,24 @@ pub const Node = struct {
646 return null;646 return null;
647 }647 }
648648
649 pub fn firstToken(self: &StructField) TokenIndex {649 pub fn firstToken(self: *StructField) TokenIndex {
650 if (self.visib_token) |visib_token| return visib_token;650 if (self.visib_token) |visib_token| return visib_token;
651 return self.name_token;651 return self.name_token;
652 }652 }
653653
654 pub fn lastToken(self: &StructField) TokenIndex {654 pub fn lastToken(self: *StructField) TokenIndex {
655 return self.type_expr.lastToken();655 return self.type_expr.lastToken();
656 }656 }
657 };657 };
658658
659 pub const UnionTag = struct {659 pub const UnionTag = struct {
660 base: Node,660 base: Node,
661 doc_comments: ?&DocComment,661 doc_comments: ?*DocComment,
662 name_token: TokenIndex,662 name_token: TokenIndex,
663 type_expr: ?&Node,663 type_expr: ?*Node,
664 value_expr: ?&Node,664 value_expr: ?*Node,
665665
666 pub fn iterate(self: &UnionTag, index: usize) ?&Node {666 pub fn iterate(self: *UnionTag, index: usize) ?*Node {
667 var i = index;667 var i = index;
668668
669 if (self.type_expr) |type_expr| {669 if (self.type_expr) |type_expr| {
...@@ -679,11 +679,11 @@ pub const Node = struct {...@@ -679,11 +679,11 @@ pub const Node = struct {
679 return null;679 return null;
680 }680 }
681681
682 pub fn firstToken(self: &UnionTag) TokenIndex {682 pub fn firstToken(self: *UnionTag) TokenIndex {
683 return self.name_token;683 return self.name_token;
684 }684 }
685685
686 pub fn lastToken(self: &UnionTag) TokenIndex {686 pub fn lastToken(self: *UnionTag) TokenIndex {
687 if (self.value_expr) |value_expr| {687 if (self.value_expr) |value_expr| {
688 return value_expr.lastToken();688 return value_expr.lastToken();
689 }689 }
...@@ -697,11 +697,11 @@ pub const Node = struct {...@@ -697,11 +697,11 @@ pub const Node = struct {
697697
698 pub const EnumTag = struct {698 pub const EnumTag = struct {
699 base: Node,699 base: Node,
700 doc_comments: ?&DocComment,700 doc_comments: ?*DocComment,
701 name_token: TokenIndex,701 name_token: TokenIndex,
702 value: ?&Node,702 value: ?*Node,
703703
704 pub fn iterate(self: &EnumTag, index: usize) ?&Node {704 pub fn iterate(self: *EnumTag, index: usize) ?*Node {
705 var i = index;705 var i = index;
706706
707 if (self.value) |value| {707 if (self.value) |value| {
...@@ -712,11 +712,11 @@ pub const Node = struct {...@@ -712,11 +712,11 @@ pub const Node = struct {
712 return null;712 return null;
713 }713 }
714714
715 pub fn firstToken(self: &EnumTag) TokenIndex {715 pub fn firstToken(self: *EnumTag) TokenIndex {
716 return self.name_token;716 return self.name_token;
717 }717 }
718718
719 pub fn lastToken(self: &EnumTag) TokenIndex {719 pub fn lastToken(self: *EnumTag) TokenIndex {
720 if (self.value) |value| {720 if (self.value) |value| {
721 return value.lastToken();721 return value.lastToken();
722 }722 }
...@@ -727,25 +727,25 @@ pub const Node = struct {...@@ -727,25 +727,25 @@ pub const Node = struct {
727727
728 pub const ErrorTag = struct {728 pub const ErrorTag = struct {
729 base: Node,729 base: Node,
730 doc_comments: ?&DocComment,730 doc_comments: ?*DocComment,
731 name_token: TokenIndex,731 name_token: TokenIndex,
732732
733 pub fn iterate(self: &ErrorTag, index: usize) ?&Node {733 pub fn iterate(self: *ErrorTag, index: usize) ?*Node {
734 var i = index;734 var i = index;
735735
736 if (self.doc_comments) |comments| {736 if (self.doc_comments) |comments| {
737 if (i < 1) return &comments.base;737 if (i < 1) return *comments.base;
738 i -= 1;738 i -= 1;
739 }739 }
740740
741 return null;741 return null;
742 }742 }
743743
744 pub fn firstToken(self: &ErrorTag) TokenIndex {744 pub fn firstToken(self: *ErrorTag) TokenIndex {
745 return self.name_token;745 return self.name_token;
746 }746 }
747747
748 pub fn lastToken(self: &ErrorTag) TokenIndex {748 pub fn lastToken(self: *ErrorTag) TokenIndex {
749 return self.name_token;749 return self.name_token;
750 }750 }
751 };751 };
...@@ -754,15 +754,15 @@ pub const Node = struct {...@@ -754,15 +754,15 @@ pub const Node = struct {
754 base: Node,754 base: Node,
755 token: TokenIndex,755 token: TokenIndex,
756756
757 pub fn iterate(self: &Identifier, index: usize) ?&Node {757 pub fn iterate(self: *Identifier, index: usize) ?*Node {
758 return null;758 return null;
759 }759 }
760760
761 pub fn firstToken(self: &Identifier) TokenIndex {761 pub fn firstToken(self: *Identifier) TokenIndex {
762 return self.token;762 return self.token;
763 }763 }
764764
765 pub fn lastToken(self: &Identifier) TokenIndex {765 pub fn lastToken(self: *Identifier) TokenIndex {
766 return self.token;766 return self.token;
767 }767 }
768 };768 };
...@@ -770,10 +770,10 @@ pub const Node = struct {...@@ -770,10 +770,10 @@ pub const Node = struct {
770 pub const AsyncAttribute = struct {770 pub const AsyncAttribute = struct {
771 base: Node,771 base: Node,
772 async_token: TokenIndex,772 async_token: TokenIndex,
773 allocator_type: ?&Node,773 allocator_type: ?*Node,
774 rangle_bracket: ?TokenIndex,774 rangle_bracket: ?TokenIndex,
775775
776 pub fn iterate(self: &AsyncAttribute, index: usize) ?&Node {776 pub fn iterate(self: *AsyncAttribute, index: usize) ?*Node {
777 var i = index;777 var i = index;
778778
779 if (self.allocator_type) |allocator_type| {779 if (self.allocator_type) |allocator_type| {
...@@ -784,11 +784,11 @@ pub const Node = struct {...@@ -784,11 +784,11 @@ pub const Node = struct {
784 return null;784 return null;
785 }785 }
786786
787 pub fn firstToken(self: &AsyncAttribute) TokenIndex {787 pub fn firstToken(self: *AsyncAttribute) TokenIndex {
788 return self.async_token;788 return self.async_token;
789 }789 }
790790
791 pub fn lastToken(self: &AsyncAttribute) TokenIndex {791 pub fn lastToken(self: *AsyncAttribute) TokenIndex {
792 if (self.rangle_bracket) |rangle_bracket| {792 if (self.rangle_bracket) |rangle_bracket| {
793 return rangle_bracket;793 return rangle_bracket;
794 }794 }
...@@ -799,7 +799,7 @@ pub const Node = struct {...@@ -799,7 +799,7 @@ pub const Node = struct {
799799
800 pub const FnProto = struct {800 pub const FnProto = struct {
801 base: Node,801 base: Node,
802 doc_comments: ?&DocComment,802 doc_comments: ?*DocComment,
803 visib_token: ?TokenIndex,803 visib_token: ?TokenIndex,
804 fn_token: TokenIndex,804 fn_token: TokenIndex,
805 name_token: ?TokenIndex,805 name_token: ?TokenIndex,
...@@ -808,19 +808,19 @@ pub const Node = struct {...@@ -808,19 +808,19 @@ pub const Node = struct {
808 var_args_token: ?TokenIndex,808 var_args_token: ?TokenIndex,
809 extern_export_inline_token: ?TokenIndex,809 extern_export_inline_token: ?TokenIndex,
810 cc_token: ?TokenIndex,810 cc_token: ?TokenIndex,
811 async_attr: ?&AsyncAttribute,811 async_attr: ?*AsyncAttribute,
812 body_node: ?&Node,812 body_node: ?*Node,
813 lib_name: ?&Node, // populated if this is an extern declaration813 lib_name: ?*Node, // populated if this is an extern declaration
814 align_expr: ?&Node, // populated if align(A) is present814 align_expr: ?*Node, // populated if align(A) is present
815815
816 pub const ParamList = SegmentedList(&Node, 2);816 pub const ParamList = SegmentedList(*Node, 2);
817817
818 pub const ReturnType = union(enum) {818 pub const ReturnType = union(enum) {
819 Explicit: &Node,819 Explicit: *Node,
820 InferErrorSet: &Node,820 InferErrorSet: *Node,
821 };821 };
822822
823 pub fn iterate(self: &FnProto, index: usize) ?&Node {823 pub fn iterate(self: *FnProto, index: usize) ?*Node {
824 var i = index;824 var i = index;
825825
826 if (self.lib_name) |lib_name| {826 if (self.lib_name) |lib_name| {
...@@ -856,7 +856,7 @@ pub const Node = struct {...@@ -856,7 +856,7 @@ pub const Node = struct {
856 return null;856 return null;
857 }857 }
858858
859 pub fn firstToken(self: &FnProto) TokenIndex {859 pub fn firstToken(self: *FnProto) TokenIndex {
860 if (self.visib_token) |visib_token| return visib_token;860 if (self.visib_token) |visib_token| return visib_token;
861 if (self.extern_export_inline_token) |extern_export_inline_token| return extern_export_inline_token;861 if (self.extern_export_inline_token) |extern_export_inline_token| return extern_export_inline_token;
862 assert(self.lib_name == null);862 assert(self.lib_name == null);
...@@ -864,7 +864,7 @@ pub const Node = struct {...@@ -864,7 +864,7 @@ pub const Node = struct {
864 return self.fn_token;864 return self.fn_token;
865 }865 }
866866
867 pub fn lastToken(self: &FnProto) TokenIndex {867 pub fn lastToken(self: *FnProto) TokenIndex {
868 if (self.body_node) |body_node| return body_node.lastToken();868 if (self.body_node) |body_node| return body_node.lastToken();
869 switch (self.return_type) {869 switch (self.return_type) {
870 // TODO allow this and next prong to share bodies since the types are the same870 // TODO allow this and next prong to share bodies since the types are the same
...@@ -881,10 +881,10 @@ pub const Node = struct {...@@ -881,10 +881,10 @@ pub const Node = struct {
881881
882 pub const Result = struct {882 pub const Result = struct {
883 arrow_token: TokenIndex,883 arrow_token: TokenIndex,
884 return_type: &Node,884 return_type: *Node,
885 };885 };
886886
887 pub fn iterate(self: &PromiseType, index: usize) ?&Node {887 pub fn iterate(self: *PromiseType, index: usize) ?*Node {
888 var i = index;888 var i = index;
889889
890 if (self.result) |result| {890 if (self.result) |result| {
...@@ -895,11 +895,11 @@ pub const Node = struct {...@@ -895,11 +895,11 @@ pub const Node = struct {
895 return null;895 return null;
896 }896 }
897897
898 pub fn firstToken(self: &PromiseType) TokenIndex {898 pub fn firstToken(self: *PromiseType) TokenIndex {
899 return self.promise_token;899 return self.promise_token;
900 }900 }
901901
902 pub fn lastToken(self: &PromiseType) TokenIndex {902 pub fn lastToken(self: *PromiseType) TokenIndex {
903 if (self.result) |result| return result.return_type.lastToken();903 if (self.result) |result| return result.return_type.lastToken();
904 return self.promise_token;904 return self.promise_token;
905 }905 }
...@@ -910,10 +910,10 @@ pub const Node = struct {...@@ -910,10 +910,10 @@ pub const Node = struct {
910 comptime_token: ?TokenIndex,910 comptime_token: ?TokenIndex,
911 noalias_token: ?TokenIndex,911 noalias_token: ?TokenIndex,
912 name_token: ?TokenIndex,912 name_token: ?TokenIndex,
913 type_node: &Node,913 type_node: *Node,
914 var_args_token: ?TokenIndex,914 var_args_token: ?TokenIndex,
915915
916 pub fn iterate(self: &ParamDecl, index: usize) ?&Node {916 pub fn iterate(self: *ParamDecl, index: usize) ?*Node {
917 var i = index;917 var i = index;
918918
919 if (i < 1) return self.type_node;919 if (i < 1) return self.type_node;
...@@ -922,14 +922,14 @@ pub const Node = struct {...@@ -922,14 +922,14 @@ pub const Node = struct {
922 return null;922 return null;
923 }923 }
924924
925 pub fn firstToken(self: &ParamDecl) TokenIndex {925 pub fn firstToken(self: *ParamDecl) TokenIndex {
926 if (self.comptime_token) |comptime_token| return comptime_token;926 if (self.comptime_token) |comptime_token| return comptime_token;
927 if (self.noalias_token) |noalias_token| return noalias_token;927 if (self.noalias_token) |noalias_token| return noalias_token;
928 if (self.name_token) |name_token| return name_token;928 if (self.name_token) |name_token| return name_token;
929 return self.type_node.firstToken();929 return self.type_node.firstToken();
930 }930 }
931931
932 pub fn lastToken(self: &ParamDecl) TokenIndex {932 pub fn lastToken(self: *ParamDecl) TokenIndex {
933 if (self.var_args_token) |var_args_token| return var_args_token;933 if (self.var_args_token) |var_args_token| return var_args_token;
934 return self.type_node.lastToken();934 return self.type_node.lastToken();
935 }935 }
...@@ -944,7 +944,7 @@ pub const Node = struct {...@@ -944,7 +944,7 @@ pub const Node = struct {
944944
945 pub const StatementList = Root.DeclList;945 pub const StatementList = Root.DeclList;
946946
947 pub fn iterate(self: &Block, index: usize) ?&Node {947 pub fn iterate(self: *Block, index: usize) ?*Node {
948 var i = index;948 var i = index;
949949
950 if (i < self.statements.len) return self.statements.at(i).*;950 if (i < self.statements.len) return self.statements.at(i).*;
...@@ -953,7 +953,7 @@ pub const Node = struct {...@@ -953,7 +953,7 @@ pub const Node = struct {
953 return null;953 return null;
954 }954 }
955955
956 pub fn firstToken(self: &Block) TokenIndex {956 pub fn firstToken(self: *Block) TokenIndex {
957 if (self.label) |label| {957 if (self.label) |label| {
958 return label;958 return label;
959 }959 }
...@@ -961,7 +961,7 @@ pub const Node = struct {...@@ -961,7 +961,7 @@ pub const Node = struct {
961 return self.lbrace;961 return self.lbrace;
962 }962 }
963963
964 pub fn lastToken(self: &Block) TokenIndex {964 pub fn lastToken(self: *Block) TokenIndex {
965 return self.rbrace;965 return self.rbrace;
966 }966 }
967 };967 };
...@@ -970,14 +970,14 @@ pub const Node = struct {...@@ -970,14 +970,14 @@ pub const Node = struct {
970 base: Node,970 base: Node,
971 defer_token: TokenIndex,971 defer_token: TokenIndex,
972 kind: Kind,972 kind: Kind,
973 expr: &Node,973 expr: *Node,
974974
975 const Kind = enum {975 const Kind = enum {
976 Error,976 Error,
977 Unconditional,977 Unconditional,
978 };978 };
979979
980 pub fn iterate(self: &Defer, index: usize) ?&Node {980 pub fn iterate(self: *Defer, index: usize) ?*Node {
981 var i = index;981 var i = index;
982982
983 if (i < 1) return self.expr;983 if (i < 1) return self.expr;
...@@ -986,22 +986,22 @@ pub const Node = struct {...@@ -986,22 +986,22 @@ pub const Node = struct {
986 return null;986 return null;
987 }987 }
988988
989 pub fn firstToken(self: &Defer) TokenIndex {989 pub fn firstToken(self: *Defer) TokenIndex {
990 return self.defer_token;990 return self.defer_token;
991 }991 }
992992
993 pub fn lastToken(self: &Defer) TokenIndex {993 pub fn lastToken(self: *Defer) TokenIndex {
994 return self.expr.lastToken();994 return self.expr.lastToken();
995 }995 }
996 };996 };
997997
998 pub const Comptime = struct {998 pub const Comptime = struct {
999 base: Node,999 base: Node,
1000 doc_comments: ?&DocComment,1000 doc_comments: ?*DocComment,
1001 comptime_token: TokenIndex,1001 comptime_token: TokenIndex,
1002 expr: &Node,1002 expr: *Node,
10031003
1004 pub fn iterate(self: &Comptime, index: usize) ?&Node {1004 pub fn iterate(self: *Comptime, index: usize) ?*Node {
1005 var i = index;1005 var i = index;
10061006
1007 if (i < 1) return self.expr;1007 if (i < 1) return self.expr;
...@@ -1010,11 +1010,11 @@ pub const Node = struct {...@@ -1010,11 +1010,11 @@ pub const Node = struct {
1010 return null;1010 return null;
1011 }1011 }
10121012
1013 pub fn firstToken(self: &Comptime) TokenIndex {1013 pub fn firstToken(self: *Comptime) TokenIndex {
1014 return self.comptime_token;1014 return self.comptime_token;
1015 }1015 }
10161016
1017 pub fn lastToken(self: &Comptime) TokenIndex {1017 pub fn lastToken(self: *Comptime) TokenIndex {
1018 return self.expr.lastToken();1018 return self.expr.lastToken();
1019 }1019 }
1020 };1020 };
...@@ -1022,10 +1022,10 @@ pub const Node = struct {...@@ -1022,10 +1022,10 @@ pub const Node = struct {
1022 pub const Payload = struct {1022 pub const Payload = struct {
1023 base: Node,1023 base: Node,
1024 lpipe: TokenIndex,1024 lpipe: TokenIndex,
1025 error_symbol: &Node,1025 error_symbol: *Node,
1026 rpipe: TokenIndex,1026 rpipe: TokenIndex,
10271027
1028 pub fn iterate(self: &Payload, index: usize) ?&Node {1028 pub fn iterate(self: *Payload, index: usize) ?*Node {
1029 var i = index;1029 var i = index;
10301030
1031 if (i < 1) return self.error_symbol;1031 if (i < 1) return self.error_symbol;
...@@ -1034,11 +1034,11 @@ pub const Node = struct {...@@ -1034,11 +1034,11 @@ pub const Node = struct {
1034 return null;1034 return null;
1035 }1035 }
10361036
1037 pub fn firstToken(self: &Payload) TokenIndex {1037 pub fn firstToken(self: *Payload) TokenIndex {
1038 return self.lpipe;1038 return self.lpipe;
1039 }1039 }
10401040
1041 pub fn lastToken(self: &Payload) TokenIndex {1041 pub fn lastToken(self: *Payload) TokenIndex {
1042 return self.rpipe;1042 return self.rpipe;
1043 }1043 }
1044 };1044 };
...@@ -1047,10 +1047,10 @@ pub const Node = struct {...@@ -1047,10 +1047,10 @@ pub const Node = struct {
1047 base: Node,1047 base: Node,
1048 lpipe: TokenIndex,1048 lpipe: TokenIndex,
1049 ptr_token: ?TokenIndex,1049 ptr_token: ?TokenIndex,
1050 value_symbol: &Node,1050 value_symbol: *Node,
1051 rpipe: TokenIndex,1051 rpipe: TokenIndex,
10521052
1053 pub fn iterate(self: &PointerPayload, index: usize) ?&Node {1053 pub fn iterate(self: *PointerPayload, index: usize) ?*Node {
1054 var i = index;1054 var i = index;
10551055
1056 if (i < 1) return self.value_symbol;1056 if (i < 1) return self.value_symbol;
...@@ -1059,11 +1059,11 @@ pub const Node = struct {...@@ -1059,11 +1059,11 @@ pub const Node = struct {
1059 return null;1059 return null;
1060 }1060 }
10611061
1062 pub fn firstToken(self: &PointerPayload) TokenIndex {1062 pub fn firstToken(self: *PointerPayload) TokenIndex {
1063 return self.lpipe;1063 return self.lpipe;
1064 }1064 }
10651065
1066 pub fn lastToken(self: &PointerPayload) TokenIndex {1066 pub fn lastToken(self: *PointerPayload) TokenIndex {
1067 return self.rpipe;1067 return self.rpipe;
1068 }1068 }
1069 };1069 };
...@@ -1072,11 +1072,11 @@ pub const Node = struct {...@@ -1072,11 +1072,11 @@ pub const Node = struct {
1072 base: Node,1072 base: Node,
1073 lpipe: TokenIndex,1073 lpipe: TokenIndex,
1074 ptr_token: ?TokenIndex,1074 ptr_token: ?TokenIndex,
1075 value_symbol: &Node,1075 value_symbol: *Node,
1076 index_symbol: ?&Node,1076 index_symbol: ?*Node,
1077 rpipe: TokenIndex,1077 rpipe: TokenIndex,
10781078
1079 pub fn iterate(self: &PointerIndexPayload, index: usize) ?&Node {1079 pub fn iterate(self: *PointerIndexPayload, index: usize) ?*Node {
1080 var i = index;1080 var i = index;
10811081
1082 if (i < 1) return self.value_symbol;1082 if (i < 1) return self.value_symbol;
...@@ -1090,11 +1090,11 @@ pub const Node = struct {...@@ -1090,11 +1090,11 @@ pub const Node = struct {
1090 return null;1090 return null;
1091 }1091 }
10921092
1093 pub fn firstToken(self: &PointerIndexPayload) TokenIndex {1093 pub fn firstToken(self: *PointerIndexPayload) TokenIndex {
1094 return self.lpipe;1094 return self.lpipe;
1095 }1095 }
10961096
1097 pub fn lastToken(self: &PointerIndexPayload) TokenIndex {1097 pub fn lastToken(self: *PointerIndexPayload) TokenIndex {
1098 return self.rpipe;1098 return self.rpipe;
1099 }1099 }
1100 };1100 };
...@@ -1102,10 +1102,10 @@ pub const Node = struct {...@@ -1102,10 +1102,10 @@ pub const Node = struct {
1102 pub const Else = struct {1102 pub const Else = struct {
1103 base: Node,1103 base: Node,
1104 else_token: TokenIndex,1104 else_token: TokenIndex,
1105 payload: ?&Node,1105 payload: ?*Node,
1106 body: &Node,1106 body: *Node,
11071107
1108 pub fn iterate(self: &Else, index: usize) ?&Node {1108 pub fn iterate(self: *Else, index: usize) ?*Node {
1109 var i = index;1109 var i = index;
11101110
1111 if (self.payload) |payload| {1111 if (self.payload) |payload| {
...@@ -1119,11 +1119,11 @@ pub const Node = struct {...@@ -1119,11 +1119,11 @@ pub const Node = struct {
1119 return null;1119 return null;
1120 }1120 }
11211121
1122 pub fn firstToken(self: &Else) TokenIndex {1122 pub fn firstToken(self: *Else) TokenIndex {
1123 return self.else_token;1123 return self.else_token;
1124 }1124 }
11251125
1126 pub fn lastToken(self: &Else) TokenIndex {1126 pub fn lastToken(self: *Else) TokenIndex {
1127 return self.body.lastToken();1127 return self.body.lastToken();
1128 }1128 }
1129 };1129 };
...@@ -1131,15 +1131,15 @@ pub const Node = struct {...@@ -1131,15 +1131,15 @@ pub const Node = struct {
1131 pub const Switch = struct {1131 pub const Switch = struct {
1132 base: Node,1132 base: Node,
1133 switch_token: TokenIndex,1133 switch_token: TokenIndex,
1134 expr: &Node,1134 expr: *Node,
11351135
1136 /// these must be SwitchCase nodes1136 /// these must be SwitchCase nodes
1137 cases: CaseList,1137 cases: CaseList,
1138 rbrace: TokenIndex,1138 rbrace: TokenIndex,
11391139
1140 pub const CaseList = SegmentedList(&Node, 2);1140 pub const CaseList = SegmentedList(*Node, 2);
11411141
1142 pub fn iterate(self: &Switch, index: usize) ?&Node {1142 pub fn iterate(self: *Switch, index: usize) ?*Node {
1143 var i = index;1143 var i = index;
11441144
1145 if (i < 1) return self.expr;1145 if (i < 1) return self.expr;
...@@ -1151,11 +1151,11 @@ pub const Node = struct {...@@ -1151,11 +1151,11 @@ pub const Node = struct {
1151 return null;1151 return null;
1152 }1152 }
11531153
1154 pub fn firstToken(self: &Switch) TokenIndex {1154 pub fn firstToken(self: *Switch) TokenIndex {
1155 return self.switch_token;1155 return self.switch_token;
1156 }1156 }
11571157
1158 pub fn lastToken(self: &Switch) TokenIndex {1158 pub fn lastToken(self: *Switch) TokenIndex {
1159 return self.rbrace;1159 return self.rbrace;
1160 }1160 }
1161 };1161 };
...@@ -1164,12 +1164,12 @@ pub const Node = struct {...@@ -1164,12 +1164,12 @@ pub const Node = struct {
1164 base: Node,1164 base: Node,
1165 items: ItemList,1165 items: ItemList,
1166 arrow_token: TokenIndex,1166 arrow_token: TokenIndex,
1167 payload: ?&Node,1167 payload: ?*Node,
1168 expr: &Node,1168 expr: *Node,
11691169
1170 pub const ItemList = SegmentedList(&Node, 1);1170 pub const ItemList = SegmentedList(*Node, 1);
11711171
1172 pub fn iterate(self: &SwitchCase, index: usize) ?&Node {1172 pub fn iterate(self: *SwitchCase, index: usize) ?*Node {
1173 var i = index;1173 var i = index;
11741174
1175 if (i < self.items.len) return self.items.at(i).*;1175 if (i < self.items.len) return self.items.at(i).*;
...@@ -1186,11 +1186,11 @@ pub const Node = struct {...@@ -1186,11 +1186,11 @@ pub const Node = struct {
1186 return null;1186 return null;
1187 }1187 }
11881188
1189 pub fn firstToken(self: &SwitchCase) TokenIndex {1189 pub fn firstToken(self: *SwitchCase) TokenIndex {
1190 return (self.items.at(0).*).firstToken();1190 return (self.items.at(0).*).firstToken();
1191 }1191 }
11921192
1193 pub fn lastToken(self: &SwitchCase) TokenIndex {1193 pub fn lastToken(self: *SwitchCase) TokenIndex {
1194 return self.expr.lastToken();1194 return self.expr.lastToken();
1195 }1195 }
1196 };1196 };
...@@ -1199,15 +1199,15 @@ pub const Node = struct {...@@ -1199,15 +1199,15 @@ pub const Node = struct {
1199 base: Node,1199 base: Node,
1200 token: TokenIndex,1200 token: TokenIndex,
12011201
1202 pub fn iterate(self: &SwitchElse, index: usize) ?&Node {1202 pub fn iterate(self: *SwitchElse, index: usize) ?*Node {
1203 return null;1203 return null;
1204 }1204 }
12051205
1206 pub fn firstToken(self: &SwitchElse) TokenIndex {1206 pub fn firstToken(self: *SwitchElse) TokenIndex {
1207 return self.token;1207 return self.token;
1208 }1208 }
12091209
1210 pub fn lastToken(self: &SwitchElse) TokenIndex {1210 pub fn lastToken(self: *SwitchElse) TokenIndex {
1211 return self.token;1211 return self.token;
1212 }1212 }
1213 };1213 };
...@@ -1217,13 +1217,13 @@ pub const Node = struct {...@@ -1217,13 +1217,13 @@ pub const Node = struct {
1217 label: ?TokenIndex,1217 label: ?TokenIndex,
1218 inline_token: ?TokenIndex,1218 inline_token: ?TokenIndex,
1219 while_token: TokenIndex,1219 while_token: TokenIndex,
1220 condition: &Node,1220 condition: *Node,
1221 payload: ?&Node,1221 payload: ?*Node,
1222 continue_expr: ?&Node,1222 continue_expr: ?*Node,
1223 body: &Node,1223 body: *Node,
1224 @"else": ?&Else,1224 @"else": ?*Else,
12251225
1226 pub fn iterate(self: &While, index: usize) ?&Node {1226 pub fn iterate(self: *While, index: usize) ?*Node {
1227 var i = index;1227 var i = index;
12281228
1229 if (i < 1) return self.condition;1229 if (i < 1) return self.condition;
...@@ -1243,14 +1243,14 @@ pub const Node = struct {...@@ -1243,14 +1243,14 @@ pub const Node = struct {
1243 i -= 1;1243 i -= 1;
12441244
1245 if (self.@"else") |@"else"| {1245 if (self.@"else") |@"else"| {
1246 if (i < 1) return &@"else".base;1246 if (i < 1) return *@"else".base;
1247 i -= 1;1247 i -= 1;
1248 }1248 }
12491249
1250 return null;1250 return null;
1251 }1251 }
12521252
1253 pub fn firstToken(self: &While) TokenIndex {1253 pub fn firstToken(self: *While) TokenIndex {
1254 if (self.label) |label| {1254 if (self.label) |label| {
1255 return label;1255 return label;
1256 }1256 }
...@@ -1262,7 +1262,7 @@ pub const Node = struct {...@@ -1262,7 +1262,7 @@ pub const Node = struct {
1262 return self.while_token;1262 return self.while_token;
1263 }1263 }
12641264
1265 pub fn lastToken(self: &While) TokenIndex {1265 pub fn lastToken(self: *While) TokenIndex {
1266 if (self.@"else") |@"else"| {1266 if (self.@"else") |@"else"| {
1267 return @"else".body.lastToken();1267 return @"else".body.lastToken();
1268 }1268 }
...@@ -1276,12 +1276,12 @@ pub const Node = struct {...@@ -1276,12 +1276,12 @@ pub const Node = struct {
1276 label: ?TokenIndex,1276 label: ?TokenIndex,
1277 inline_token: ?TokenIndex,1277 inline_token: ?TokenIndex,
1278 for_token: TokenIndex,1278 for_token: TokenIndex,
1279 array_expr: &Node,1279 array_expr: *Node,
1280 payload: ?&Node,1280 payload: ?*Node,
1281 body: &Node,1281 body: *Node,
1282 @"else": ?&Else,1282 @"else": ?*Else,
12831283
1284 pub fn iterate(self: &For, index: usize) ?&Node {1284 pub fn iterate(self: *For, index: usize) ?*Node {
1285 var i = index;1285 var i = index;
12861286
1287 if (i < 1) return self.array_expr;1287 if (i < 1) return self.array_expr;
...@@ -1296,14 +1296,14 @@ pub const Node = struct {...@@ -1296,14 +1296,14 @@ pub const Node = struct {
1296 i -= 1;1296 i -= 1;
12971297
1298 if (self.@"else") |@"else"| {1298 if (self.@"else") |@"else"| {
1299 if (i < 1) return &@"else".base;1299 if (i < 1) return *@"else".base;
1300 i -= 1;1300 i -= 1;
1301 }1301 }
13021302
1303 return null;1303 return null;
1304 }1304 }
13051305
1306 pub fn firstToken(self: &For) TokenIndex {1306 pub fn firstToken(self: *For) TokenIndex {
1307 if (self.label) |label| {1307 if (self.label) |label| {
1308 return label;1308 return label;
1309 }1309 }
...@@ -1315,7 +1315,7 @@ pub const Node = struct {...@@ -1315,7 +1315,7 @@ pub const Node = struct {
1315 return self.for_token;1315 return self.for_token;
1316 }1316 }
13171317
1318 pub fn lastToken(self: &For) TokenIndex {1318 pub fn lastToken(self: *For) TokenIndex {
1319 if (self.@"else") |@"else"| {1319 if (self.@"else") |@"else"| {
1320 return @"else".body.lastToken();1320 return @"else".body.lastToken();
1321 }1321 }
...@@ -1327,12 +1327,12 @@ pub const Node = struct {...@@ -1327,12 +1327,12 @@ pub const Node = struct {
1327 pub const If = struct {1327 pub const If = struct {
1328 base: Node,1328 base: Node,
1329 if_token: TokenIndex,1329 if_token: TokenIndex,
1330 condition: &Node,1330 condition: *Node,
1331 payload: ?&Node,1331 payload: ?*Node,
1332 body: &Node,1332 body: *Node,
1333 @"else": ?&Else,1333 @"else": ?*Else,
13341334
1335 pub fn iterate(self: &If, index: usize) ?&Node {1335 pub fn iterate(self: *If, index: usize) ?*Node {
1336 var i = index;1336 var i = index;
13371337
1338 if (i < 1) return self.condition;1338 if (i < 1) return self.condition;
...@@ -1347,18 +1347,18 @@ pub const Node = struct {...@@ -1347,18 +1347,18 @@ pub const Node = struct {
1347 i -= 1;1347 i -= 1;
13481348
1349 if (self.@"else") |@"else"| {1349 if (self.@"else") |@"else"| {
1350 if (i < 1) return &@"else".base;1350 if (i < 1) return *@"else".base;
1351 i -= 1;1351 i -= 1;
1352 }1352 }
13531353
1354 return null;1354 return null;
1355 }1355 }
13561356
1357 pub fn firstToken(self: &If) TokenIndex {1357 pub fn firstToken(self: *If) TokenIndex {
1358 return self.if_token;1358 return self.if_token;
1359 }1359 }
13601360
1361 pub fn lastToken(self: &If) TokenIndex {1361 pub fn lastToken(self: *If) TokenIndex {
1362 if (self.@"else") |@"else"| {1362 if (self.@"else") |@"else"| {
1363 return @"else".body.lastToken();1363 return @"else".body.lastToken();
1364 }1364 }
...@@ -1370,9 +1370,9 @@ pub const Node = struct {...@@ -1370,9 +1370,9 @@ pub const Node = struct {
1370 pub const InfixOp = struct {1370 pub const InfixOp = struct {
1371 base: Node,1371 base: Node,
1372 op_token: TokenIndex,1372 op_token: TokenIndex,
1373 lhs: &Node,1373 lhs: *Node,
1374 op: Op,1374 op: Op,
1375 rhs: &Node,1375 rhs: *Node,
13761376
1377 pub const Op = union(enum) {1377 pub const Op = union(enum) {
1378 Add,1378 Add,
...@@ -1401,7 +1401,7 @@ pub const Node = struct {...@@ -1401,7 +1401,7 @@ pub const Node = struct {
1401 BitXor,1401 BitXor,
1402 BoolAnd,1402 BoolAnd,
1403 BoolOr,1403 BoolOr,
1404 Catch: ?&Node,1404 Catch: ?*Node,
1405 Div,1405 Div,
1406 EqualEqual,1406 EqualEqual,
1407 ErrorUnion,1407 ErrorUnion,
...@@ -1420,7 +1420,7 @@ pub const Node = struct {...@@ -1420,7 +1420,7 @@ pub const Node = struct {
1420 UnwrapMaybe,1420 UnwrapMaybe,
1421 };1421 };
14221422
1423 pub fn iterate(self: &InfixOp, index: usize) ?&Node {1423 pub fn iterate(self: *InfixOp, index: usize) ?*Node {
1424 var i = index;1424 var i = index;
14251425
1426 if (i < 1) return self.lhs;1426 if (i < 1) return self.lhs;
...@@ -1475,7 +1475,8 @@ pub const Node = struct {...@@ -1475,7 +1475,8 @@ pub const Node = struct {
1475 Op.Range,1475 Op.Range,
1476 Op.Sub,1476 Op.Sub,
1477 Op.SubWrap,1477 Op.SubWrap,
1478 Op.UnwrapMaybe => {},1478 Op.UnwrapMaybe,
1479 => {},
1479 }1480 }
14801481
1481 if (i < 1) return self.rhs;1482 if (i < 1) return self.rhs;
...@@ -1484,11 +1485,11 @@ pub const Node = struct {...@@ -1484,11 +1485,11 @@ pub const Node = struct {
1484 return null;1485 return null;
1485 }1486 }
14861487
1487 pub fn firstToken(self: &InfixOp) TokenIndex {1488 pub fn firstToken(self: *InfixOp) TokenIndex {
1488 return self.lhs.firstToken();1489 return self.lhs.firstToken();
1489 }1490 }
14901491
1491 pub fn lastToken(self: &InfixOp) TokenIndex {1492 pub fn lastToken(self: *InfixOp) TokenIndex {
1492 return self.rhs.lastToken();1493 return self.rhs.lastToken();
1493 }1494 }
1494 };1495 };
...@@ -1497,42 +1498,42 @@ pub const Node = struct {...@@ -1497,42 +1498,42 @@ pub const Node = struct {
1497 base: Node,1498 base: Node,
1498 op_token: TokenIndex,1499 op_token: TokenIndex,
1499 op: Op,1500 op: Op,
1500 rhs: &Node,1501 rhs: *Node,
15011502
1502 pub const Op = union(enum) {1503 pub const Op = union(enum) {
1503 AddrOf: AddrOfInfo,1504 AddressOf,
1504 ArrayType: &Node,1505 ArrayType: *Node,
1505 Await,1506 Await,
1506 BitNot,1507 BitNot,
1507 BoolNot,1508 BoolNot,
1508 Cancel,1509 Cancel,
1509 PointerType,
1510 MaybeType,1510 MaybeType,
1511 Negation,1511 Negation,
1512 NegationWrap,1512 NegationWrap,
1513 Resume,1513 Resume,
1514 SliceType: AddrOfInfo,1514 PtrType: PtrInfo,
1515 SliceType: PtrInfo,
1515 Try,1516 Try,
1516 UnwrapMaybe,1517 UnwrapMaybe,
1517 };1518 };
15181519
1519 pub const AddrOfInfo = struct {1520 pub const PtrInfo = struct {
1520 align_info: ?Align,1521 align_info: ?Align,
1521 const_token: ?TokenIndex,1522 const_token: ?TokenIndex,
1522 volatile_token: ?TokenIndex,1523 volatile_token: ?TokenIndex,
15231524
1524 pub const Align = struct {1525 pub const Align = struct {
1525 node: &Node,1526 node: *Node,
1526 bit_range: ?BitRange,1527 bit_range: ?BitRange,
15271528
1528 pub const BitRange = struct {1529 pub const BitRange = struct {
1529 start: &Node,1530 start: *Node,
1530 end: &Node,1531 end: *Node,
1531 };1532 };
1532 };1533 };
1533 };1534 };
15341535
1535 pub fn iterate(self: &PrefixOp, index: usize) ?&Node {1536 pub fn iterate(self: *PrefixOp, index: usize) ?*Node {
1536 var i = index;1537 var i = index;
15371538
1538 switch (self.op) {1539 switch (self.op) {
...@@ -1572,11 +1573,11 @@ pub const Node = struct {...@@ -1572,11 +1573,11 @@ pub const Node = struct {
1572 return null;1573 return null;
1573 }1574 }
15741575
1575 pub fn firstToken(self: &PrefixOp) TokenIndex {1576 pub fn firstToken(self: *PrefixOp) TokenIndex {
1576 return self.op_token;1577 return self.op_token;
1577 }1578 }
15781579
1579 pub fn lastToken(self: &PrefixOp) TokenIndex {1580 pub fn lastToken(self: *PrefixOp) TokenIndex {
1580 return self.rhs.lastToken();1581 return self.rhs.lastToken();
1581 }1582 }
1582 };1583 };
...@@ -1585,9 +1586,9 @@ pub const Node = struct {...@@ -1585,9 +1586,9 @@ pub const Node = struct {
1585 base: Node,1586 base: Node,
1586 period_token: TokenIndex,1587 period_token: TokenIndex,
1587 name_token: TokenIndex,1588 name_token: TokenIndex,
1588 expr: &Node,1589 expr: *Node,
15891590
1590 pub fn iterate(self: &FieldInitializer, index: usize) ?&Node {1591 pub fn iterate(self: *FieldInitializer, index: usize) ?*Node {
1591 var i = index;1592 var i = index;
15921593
1593 if (i < 1) return self.expr;1594 if (i < 1) return self.expr;
...@@ -1596,45 +1597,45 @@ pub const Node = struct {...@@ -1596,45 +1597,45 @@ pub const Node = struct {
1596 return null;1597 return null;
1597 }1598 }
15981599
1599 pub fn firstToken(self: &FieldInitializer) TokenIndex {1600 pub fn firstToken(self: *FieldInitializer) TokenIndex {
1600 return self.period_token;1601 return self.period_token;
1601 }1602 }
16021603
1603 pub fn lastToken(self: &FieldInitializer) TokenIndex {1604 pub fn lastToken(self: *FieldInitializer) TokenIndex {
1604 return self.expr.lastToken();1605 return self.expr.lastToken();
1605 }1606 }
1606 };1607 };
16071608
1608 pub const SuffixOp = struct {1609 pub const SuffixOp = struct {
1609 base: Node,1610 base: Node,
1610 lhs: &Node,1611 lhs: *Node,
1611 op: Op,1612 op: Op,
1612 rtoken: TokenIndex,1613 rtoken: TokenIndex,
16131614
1614 pub const Op = union(enum) {1615 pub const Op = union(enum) {
1615 Call: Call,1616 Call: Call,
1616 ArrayAccess: &Node,1617 ArrayAccess: *Node,
1617 Slice: Slice,1618 Slice: Slice,
1618 ArrayInitializer: InitList,1619 ArrayInitializer: InitList,
1619 StructInitializer: InitList,1620 StructInitializer: InitList,
1620 Deref,1621 Deref,
16211622
1622 pub const InitList = SegmentedList(&Node, 2);1623 pub const InitList = SegmentedList(*Node, 2);
16231624
1624 pub const Call = struct {1625 pub const Call = struct {
1625 params: ParamList,1626 params: ParamList,
1626 async_attr: ?&AsyncAttribute,1627 async_attr: ?*AsyncAttribute,
16271628
1628 pub const ParamList = SegmentedList(&Node, 2);1629 pub const ParamList = SegmentedList(*Node, 2);
1629 };1630 };
16301631
1631 pub const Slice = struct {1632 pub const Slice = struct {
1632 start: &Node,1633 start: *Node,
1633 end: ?&Node,1634 end: ?*Node,
1634 };1635 };
1635 };1636 };
16361637
1637 pub fn iterate(self: &SuffixOp, index: usize) ?&Node {1638 pub fn iterate(self: *SuffixOp, index: usize) ?*Node {
1638 var i = index;1639 var i = index;
16391640
1640 if (i < 1) return self.lhs;1641 if (i < 1) return self.lhs;
...@@ -1672,11 +1673,15 @@ pub const Node = struct {...@@ -1672,11 +1673,15 @@ pub const Node = struct {
1672 return null;1673 return null;
1673 }1674 }
16741675
1675 pub fn firstToken(self: &SuffixOp) TokenIndex {1676 pub fn firstToken(self: *SuffixOp) TokenIndex {
1677 switch (self.op) {
1678 @TagType(Op).Call => |*call_info| if (call_info.async_attr) |async_attr| return async_attr.firstToken(),
1679 else => {},
1680 }
1676 return self.lhs.firstToken();1681 return self.lhs.firstToken();
1677 }1682 }
16781683
1679 pub fn lastToken(self: &SuffixOp) TokenIndex {1684 pub fn lastToken(self: *SuffixOp) TokenIndex {
1680 return self.rtoken;1685 return self.rtoken;
1681 }1686 }
1682 };1687 };
...@@ -1684,10 +1689,10 @@ pub const Node = struct {...@@ -1684,10 +1689,10 @@ pub const Node = struct {
1684 pub const GroupedExpression = struct {1689 pub const GroupedExpression = struct {
1685 base: Node,1690 base: Node,
1686 lparen: TokenIndex,1691 lparen: TokenIndex,
1687 expr: &Node,1692 expr: *Node,
1688 rparen: TokenIndex,1693 rparen: TokenIndex,
16891694
1690 pub fn iterate(self: &GroupedExpression, index: usize) ?&Node {1695 pub fn iterate(self: *GroupedExpression, index: usize) ?*Node {
1691 var i = index;1696 var i = index;
16921697
1693 if (i < 1) return self.expr;1698 if (i < 1) return self.expr;
...@@ -1696,11 +1701,11 @@ pub const Node = struct {...@@ -1696,11 +1701,11 @@ pub const Node = struct {
1696 return null;1701 return null;
1697 }1702 }
16981703
1699 pub fn firstToken(self: &GroupedExpression) TokenIndex {1704 pub fn firstToken(self: *GroupedExpression) TokenIndex {
1700 return self.lparen;1705 return self.lparen;
1701 }1706 }
17021707
1703 pub fn lastToken(self: &GroupedExpression) TokenIndex {1708 pub fn lastToken(self: *GroupedExpression) TokenIndex {
1704 return self.rparen;1709 return self.rparen;
1705 }1710 }
1706 };1711 };
...@@ -1709,15 +1714,15 @@ pub const Node = struct {...@@ -1709,15 +1714,15 @@ pub const Node = struct {
1709 base: Node,1714 base: Node,
1710 ltoken: TokenIndex,1715 ltoken: TokenIndex,
1711 kind: Kind,1716 kind: Kind,
1712 rhs: ?&Node,1717 rhs: ?*Node,
17131718
1714 const Kind = union(enum) {1719 const Kind = union(enum) {
1715 Break: ?&Node,1720 Break: ?*Node,
1716 Continue: ?&Node,1721 Continue: ?*Node,
1717 Return,1722 Return,
1718 };1723 };
17191724
1720 pub fn iterate(self: &ControlFlowExpression, index: usize) ?&Node {1725 pub fn iterate(self: *ControlFlowExpression, index: usize) ?*Node {
1721 var i = index;1726 var i = index;
17221727
1723 switch (self.kind) {1728 switch (self.kind) {
...@@ -1744,11 +1749,11 @@ pub const Node = struct {...@@ -1744,11 +1749,11 @@ pub const Node = struct {
1744 return null;1749 return null;
1745 }1750 }
17461751
1747 pub fn firstToken(self: &ControlFlowExpression) TokenIndex {1752 pub fn firstToken(self: *ControlFlowExpression) TokenIndex {
1748 return self.ltoken;1753 return self.ltoken;
1749 }1754 }
17501755
1751 pub fn lastToken(self: &ControlFlowExpression) TokenIndex {1756 pub fn lastToken(self: *ControlFlowExpression) TokenIndex {
1752 if (self.rhs) |rhs| {1757 if (self.rhs) |rhs| {
1753 return rhs.lastToken();1758 return rhs.lastToken();
1754 }1759 }
...@@ -1775,10 +1780,10 @@ pub const Node = struct {...@@ -1775,10 +1780,10 @@ pub const Node = struct {
1775 base: Node,1780 base: Node,
1776 label: ?TokenIndex,1781 label: ?TokenIndex,
1777 suspend_token: TokenIndex,1782 suspend_token: TokenIndex,
1778 payload: ?&Node,1783 payload: ?*Node,
1779 body: ?&Node,1784 body: ?*Node,
17801785
1781 pub fn iterate(self: &Suspend, index: usize) ?&Node {1786 pub fn iterate(self: *Suspend, index: usize) ?*Node {
1782 var i = index;1787 var i = index;
17831788
1784 if (self.payload) |payload| {1789 if (self.payload) |payload| {
...@@ -1794,12 +1799,12 @@ pub const Node = struct {...@@ -1794,12 +1799,12 @@ pub const Node = struct {
1794 return null;1799 return null;
1795 }1800 }
17961801
1797 pub fn firstToken(self: &Suspend) TokenIndex {1802 pub fn firstToken(self: *Suspend) TokenIndex {
1798 if (self.label) |label| return label;1803 if (self.label) |label| return label;
1799 return self.suspend_token;1804 return self.suspend_token;
1800 }1805 }
18011806
1802 pub fn lastToken(self: &Suspend) TokenIndex {1807 pub fn lastToken(self: *Suspend) TokenIndex {
1803 if (self.body) |body| {1808 if (self.body) |body| {
1804 return body.lastToken();1809 return body.lastToken();
1805 }1810 }
...@@ -1816,15 +1821,15 @@ pub const Node = struct {...@@ -1816,15 +1821,15 @@ pub const Node = struct {
1816 base: Node,1821 base: Node,
1817 token: TokenIndex,1822 token: TokenIndex,
18181823
1819 pub fn iterate(self: &IntegerLiteral, index: usize) ?&Node {1824 pub fn iterate(self: *IntegerLiteral, index: usize) ?*Node {
1820 return null;1825 return null;
1821 }1826 }
18221827
1823 pub fn firstToken(self: &IntegerLiteral) TokenIndex {1828 pub fn firstToken(self: *IntegerLiteral) TokenIndex {
1824 return self.token;1829 return self.token;
1825 }1830 }
18261831
1827 pub fn lastToken(self: &IntegerLiteral) TokenIndex {1832 pub fn lastToken(self: *IntegerLiteral) TokenIndex {
1828 return self.token;1833 return self.token;
1829 }1834 }
1830 };1835 };
...@@ -1833,15 +1838,15 @@ pub const Node = struct {...@@ -1833,15 +1838,15 @@ pub const Node = struct {
1833 base: Node,1838 base: Node,
1834 token: TokenIndex,1839 token: TokenIndex,
18351840
1836 pub fn iterate(self: &FloatLiteral, index: usize) ?&Node {1841 pub fn iterate(self: *FloatLiteral, index: usize) ?*Node {
1837 return null;1842 return null;
1838 }1843 }
18391844
1840 pub fn firstToken(self: &FloatLiteral) TokenIndex {1845 pub fn firstToken(self: *FloatLiteral) TokenIndex {
1841 return self.token;1846 return self.token;
1842 }1847 }
18431848
1844 pub fn lastToken(self: &FloatLiteral) TokenIndex {1849 pub fn lastToken(self: *FloatLiteral) TokenIndex {
1845 return self.token;1850 return self.token;
1846 }1851 }
1847 };1852 };
...@@ -1852,9 +1857,9 @@ pub const Node = struct {...@@ -1852,9 +1857,9 @@ pub const Node = struct {
1852 params: ParamList,1857 params: ParamList,
1853 rparen_token: TokenIndex,1858 rparen_token: TokenIndex,
18541859
1855 pub const ParamList = SegmentedList(&Node, 2);1860 pub const ParamList = SegmentedList(*Node, 2);
18561861
1857 pub fn iterate(self: &BuiltinCall, index: usize) ?&Node {1862 pub fn iterate(self: *BuiltinCall, index: usize) ?*Node {
1858 var i = index;1863 var i = index;
18591864
1860 if (i < self.params.len) return self.params.at(i).*;1865 if (i < self.params.len) return self.params.at(i).*;
...@@ -1863,11 +1868,11 @@ pub const Node = struct {...@@ -1863,11 +1868,11 @@ pub const Node = struct {
1863 return null;1868 return null;
1864 }1869 }
18651870
1866 pub fn firstToken(self: &BuiltinCall) TokenIndex {1871 pub fn firstToken(self: *BuiltinCall) TokenIndex {
1867 return self.builtin_token;1872 return self.builtin_token;
1868 }1873 }
18691874
1870 pub fn lastToken(self: &BuiltinCall) TokenIndex {1875 pub fn lastToken(self: *BuiltinCall) TokenIndex {
1871 return self.rparen_token;1876 return self.rparen_token;
1872 }1877 }
1873 };1878 };
...@@ -1876,15 +1881,15 @@ pub const Node = struct {...@@ -1876,15 +1881,15 @@ pub const Node = struct {
1876 base: Node,1881 base: Node,
1877 token: TokenIndex,1882 token: TokenIndex,
18781883
1879 pub fn iterate(self: &StringLiteral, index: usize) ?&Node {1884 pub fn iterate(self: *StringLiteral, index: usize) ?*Node {
1880 return null;1885 return null;
1881 }1886 }
18821887
1883 pub fn firstToken(self: &StringLiteral) TokenIndex {1888 pub fn firstToken(self: *StringLiteral) TokenIndex {
1884 return self.token;1889 return self.token;
1885 }1890 }
18861891
1887 pub fn lastToken(self: &StringLiteral) TokenIndex {1892 pub fn lastToken(self: *StringLiteral) TokenIndex {
1888 return self.token;1893 return self.token;
1889 }1894 }
1890 };1895 };
...@@ -1895,15 +1900,15 @@ pub const Node = struct {...@@ -1895,15 +1900,15 @@ pub const Node = struct {
18951900
1896 pub const LineList = SegmentedList(TokenIndex, 4);1901 pub const LineList = SegmentedList(TokenIndex, 4);
18971902
1898 pub fn iterate(self: &MultilineStringLiteral, index: usize) ?&Node {1903 pub fn iterate(self: *MultilineStringLiteral, index: usize) ?*Node {
1899 return null;1904 return null;
1900 }1905 }
19011906
1902 pub fn firstToken(self: &MultilineStringLiteral) TokenIndex {1907 pub fn firstToken(self: *MultilineStringLiteral) TokenIndex {
1903 return self.lines.at(0).*;1908 return self.lines.at(0).*;
1904 }1909 }
19051910
1906 pub fn lastToken(self: &MultilineStringLiteral) TokenIndex {1911 pub fn lastToken(self: *MultilineStringLiteral) TokenIndex {
1907 return self.lines.at(self.lines.len - 1).*;1912 return self.lines.at(self.lines.len - 1).*;
1908 }1913 }
1909 };1914 };
...@@ -1912,15 +1917,15 @@ pub const Node = struct {...@@ -1912,15 +1917,15 @@ pub const Node = struct {
1912 base: Node,1917 base: Node,
1913 token: TokenIndex,1918 token: TokenIndex,
19141919
1915 pub fn iterate(self: &CharLiteral, index: usize) ?&Node {1920 pub fn iterate(self: *CharLiteral, index: usize) ?*Node {
1916 return null;1921 return null;
1917 }1922 }
19181923
1919 pub fn firstToken(self: &CharLiteral) TokenIndex {1924 pub fn firstToken(self: *CharLiteral) TokenIndex {
1920 return self.token;1925 return self.token;
1921 }1926 }
19221927
1923 pub fn lastToken(self: &CharLiteral) TokenIndex {1928 pub fn lastToken(self: *CharLiteral) TokenIndex {
1924 return self.token;1929 return self.token;
1925 }1930 }
1926 };1931 };
...@@ -1929,15 +1934,15 @@ pub const Node = struct {...@@ -1929,15 +1934,15 @@ pub const Node = struct {
1929 base: Node,1934 base: Node,
1930 token: TokenIndex,1935 token: TokenIndex,
19311936
1932 pub fn iterate(self: &BoolLiteral, index: usize) ?&Node {1937 pub fn iterate(self: *BoolLiteral, index: usize) ?*Node {
1933 return null;1938 return null;
1934 }1939 }
19351940
1936 pub fn firstToken(self: &BoolLiteral) TokenIndex {1941 pub fn firstToken(self: *BoolLiteral) TokenIndex {
1937 return self.token;1942 return self.token;
1938 }1943 }
19391944
1940 pub fn lastToken(self: &BoolLiteral) TokenIndex {1945 pub fn lastToken(self: *BoolLiteral) TokenIndex {
1941 return self.token;1946 return self.token;
1942 }1947 }
1943 };1948 };
...@@ -1946,15 +1951,15 @@ pub const Node = struct {...@@ -1946,15 +1951,15 @@ pub const Node = struct {
1946 base: Node,1951 base: Node,
1947 token: TokenIndex,1952 token: TokenIndex,
19481953
1949 pub fn iterate(self: &NullLiteral, index: usize) ?&Node {1954 pub fn iterate(self: *NullLiteral, index: usize) ?*Node {
1950 return null;1955 return null;
1951 }1956 }
19521957
1953 pub fn firstToken(self: &NullLiteral) TokenIndex {1958 pub fn firstToken(self: *NullLiteral) TokenIndex {
1954 return self.token;1959 return self.token;
1955 }1960 }
19561961
1957 pub fn lastToken(self: &NullLiteral) TokenIndex {1962 pub fn lastToken(self: *NullLiteral) TokenIndex {
1958 return self.token;1963 return self.token;
1959 }1964 }
1960 };1965 };
...@@ -1963,15 +1968,15 @@ pub const Node = struct {...@@ -1963,15 +1968,15 @@ pub const Node = struct {
1963 base: Node,1968 base: Node,
1964 token: TokenIndex,1969 token: TokenIndex,
19651970
1966 pub fn iterate(self: &UndefinedLiteral, index: usize) ?&Node {1971 pub fn iterate(self: *UndefinedLiteral, index: usize) ?*Node {
1967 return null;1972 return null;
1968 }1973 }
19691974
1970 pub fn firstToken(self: &UndefinedLiteral) TokenIndex {1975 pub fn firstToken(self: *UndefinedLiteral) TokenIndex {
1971 return self.token;1976 return self.token;
1972 }1977 }
19731978
1974 pub fn lastToken(self: &UndefinedLiteral) TokenIndex {1979 pub fn lastToken(self: *UndefinedLiteral) TokenIndex {
1975 return self.token;1980 return self.token;
1976 }1981 }
1977 };1982 };
...@@ -1980,15 +1985,15 @@ pub const Node = struct {...@@ -1980,15 +1985,15 @@ pub const Node = struct {
1980 base: Node,1985 base: Node,
1981 token: TokenIndex,1986 token: TokenIndex,
19821987
1983 pub fn iterate(self: &ThisLiteral, index: usize) ?&Node {1988 pub fn iterate(self: *ThisLiteral, index: usize) ?*Node {
1984 return null;1989 return null;
1985 }1990 }
19861991
1987 pub fn firstToken(self: &ThisLiteral) TokenIndex {1992 pub fn firstToken(self: *ThisLiteral) TokenIndex {
1988 return self.token;1993 return self.token;
1989 }1994 }
19901995
1991 pub fn lastToken(self: &ThisLiteral) TokenIndex {1996 pub fn lastToken(self: *ThisLiteral) TokenIndex {
1992 return self.token;1997 return self.token;
1993 }1998 }
1994 };1999 };
...@@ -1996,17 +2001,17 @@ pub const Node = struct {...@@ -1996,17 +2001,17 @@ pub const Node = struct {
1996 pub const AsmOutput = struct {2001 pub const AsmOutput = struct {
1997 base: Node,2002 base: Node,
1998 lbracket: TokenIndex,2003 lbracket: TokenIndex,
1999 symbolic_name: &Node,2004 symbolic_name: *Node,
2000 constraint: &Node,2005 constraint: *Node,
2001 kind: Kind,2006 kind: Kind,
2002 rparen: TokenIndex,2007 rparen: TokenIndex,
20032008
2004 const Kind = union(enum) {2009 const Kind = union(enum) {
2005 Variable: &Identifier,2010 Variable: *Identifier,
2006 Return: &Node,2011 Return: *Node,
2007 };2012 };
20082013
2009 pub fn iterate(self: &AsmOutput, index: usize) ?&Node {2014 pub fn iterate(self: *AsmOutput, index: usize) ?*Node {
2010 var i = index;2015 var i = index;
20112016
2012 if (i < 1) return self.symbolic_name;2017 if (i < 1) return self.symbolic_name;
...@@ -2017,7 +2022,7 @@ pub const Node = struct {...@@ -2017,7 +2022,7 @@ pub const Node = struct {
20172022
2018 switch (self.kind) {2023 switch (self.kind) {
2019 Kind.Variable => |variable_name| {2024 Kind.Variable => |variable_name| {
2020 if (i < 1) return &variable_name.base;2025 if (i < 1) return *variable_name.base;
2021 i -= 1;2026 i -= 1;
2022 },2027 },
2023 Kind.Return => |return_type| {2028 Kind.Return => |return_type| {
...@@ -2029,11 +2034,11 @@ pub const Node = struct {...@@ -2029,11 +2034,11 @@ pub const Node = struct {
2029 return null;2034 return null;
2030 }2035 }
20312036
2032 pub fn firstToken(self: &AsmOutput) TokenIndex {2037 pub fn firstToken(self: *AsmOutput) TokenIndex {
2033 return self.lbracket;2038 return self.lbracket;
2034 }2039 }
20352040
2036 pub fn lastToken(self: &AsmOutput) TokenIndex {2041 pub fn lastToken(self: *AsmOutput) TokenIndex {
2037 return self.rparen;2042 return self.rparen;
2038 }2043 }
2039 };2044 };
...@@ -2041,12 +2046,12 @@ pub const Node = struct {...@@ -2041,12 +2046,12 @@ pub const Node = struct {
2041 pub const AsmInput = struct {2046 pub const AsmInput = struct {
2042 base: Node,2047 base: Node,
2043 lbracket: TokenIndex,2048 lbracket: TokenIndex,
2044 symbolic_name: &Node,2049 symbolic_name: *Node,
2045 constraint: &Node,2050 constraint: *Node,
2046 expr: &Node,2051 expr: *Node,
2047 rparen: TokenIndex,2052 rparen: TokenIndex,
20482053
2049 pub fn iterate(self: &AsmInput, index: usize) ?&Node {2054 pub fn iterate(self: *AsmInput, index: usize) ?*Node {
2050 var i = index;2055 var i = index;
20512056
2052 if (i < 1) return self.symbolic_name;2057 if (i < 1) return self.symbolic_name;
...@@ -2061,11 +2066,11 @@ pub const Node = struct {...@@ -2061,11 +2066,11 @@ pub const Node = struct {
2061 return null;2066 return null;
2062 }2067 }
20632068
2064 pub fn firstToken(self: &AsmInput) TokenIndex {2069 pub fn firstToken(self: *AsmInput) TokenIndex {
2065 return self.lbracket;2070 return self.lbracket;
2066 }2071 }
20672072
2068 pub fn lastToken(self: &AsmInput) TokenIndex {2073 pub fn lastToken(self: *AsmInput) TokenIndex {
2069 return self.rparen;2074 return self.rparen;
2070 }2075 }
2071 };2076 };
...@@ -2074,33 +2079,33 @@ pub const Node = struct {...@@ -2074,33 +2079,33 @@ pub const Node = struct {
2074 base: Node,2079 base: Node,
2075 asm_token: TokenIndex,2080 asm_token: TokenIndex,
2076 volatile_token: ?TokenIndex,2081 volatile_token: ?TokenIndex,
2077 template: &Node,2082 template: *Node,
2078 outputs: OutputList,2083 outputs: OutputList,
2079 inputs: InputList,2084 inputs: InputList,
2080 clobbers: ClobberList,2085 clobbers: ClobberList,
2081 rparen: TokenIndex,2086 rparen: TokenIndex,
20822087
2083 const OutputList = SegmentedList(&AsmOutput, 2);2088 const OutputList = SegmentedList(*AsmOutput, 2);
2084 const InputList = SegmentedList(&AsmInput, 2);2089 const InputList = SegmentedList(*AsmInput, 2);
2085 const ClobberList = SegmentedList(TokenIndex, 2);2090 const ClobberList = SegmentedList(TokenIndex, 2);
20862091
2087 pub fn iterate(self: &Asm, index: usize) ?&Node {2092 pub fn iterate(self: *Asm, index: usize) ?*Node {
2088 var i = index;2093 var i = index;
20892094
2090 if (i < self.outputs.len) return &(self.outputs.at(index).*).base;2095 if (i < self.outputs.len) return *(self.outputs.at(index).*).base;
2091 i -= self.outputs.len;2096 i -= self.outputs.len;
20922097
2093 if (i < self.inputs.len) return &(self.inputs.at(index).*).base;2098 if (i < self.inputs.len) return *(self.inputs.at(index).*).base;
2094 i -= self.inputs.len;2099 i -= self.inputs.len;
20952100
2096 return null;2101 return null;
2097 }2102 }
20982103
2099 pub fn firstToken(self: &Asm) TokenIndex {2104 pub fn firstToken(self: *Asm) TokenIndex {
2100 return self.asm_token;2105 return self.asm_token;
2101 }2106 }
21022107
2103 pub fn lastToken(self: &Asm) TokenIndex {2108 pub fn lastToken(self: *Asm) TokenIndex {
2104 return self.rparen;2109 return self.rparen;
2105 }2110 }
2106 };2111 };
...@@ -2109,15 +2114,15 @@ pub const Node = struct {...@@ -2109,15 +2114,15 @@ pub const Node = struct {
2109 base: Node,2114 base: Node,
2110 token: TokenIndex,2115 token: TokenIndex,
21112116
2112 pub fn iterate(self: &Unreachable, index: usize) ?&Node {2117 pub fn iterate(self: *Unreachable, index: usize) ?*Node {
2113 return null;2118 return null;
2114 }2119 }
21152120
2116 pub fn firstToken(self: &Unreachable) TokenIndex {2121 pub fn firstToken(self: *Unreachable) TokenIndex {
2117 return self.token;2122 return self.token;
2118 }2123 }
21192124
2120 pub fn lastToken(self: &Unreachable) TokenIndex {2125 pub fn lastToken(self: *Unreachable) TokenIndex {
2121 return self.token;2126 return self.token;
2122 }2127 }
2123 };2128 };
...@@ -2126,15 +2131,15 @@ pub const Node = struct {...@@ -2126,15 +2131,15 @@ pub const Node = struct {
2126 base: Node,2131 base: Node,
2127 token: TokenIndex,2132 token: TokenIndex,
21282133
2129 pub fn iterate(self: &ErrorType, index: usize) ?&Node {2134 pub fn iterate(self: *ErrorType, index: usize) ?*Node {
2130 return null;2135 return null;
2131 }2136 }
21322137
2133 pub fn firstToken(self: &ErrorType) TokenIndex {2138 pub fn firstToken(self: *ErrorType) TokenIndex {
2134 return self.token;2139 return self.token;
2135 }2140 }
21362141
2137 pub fn lastToken(self: &ErrorType) TokenIndex {2142 pub fn lastToken(self: *ErrorType) TokenIndex {
2138 return self.token;2143 return self.token;
2139 }2144 }
2140 };2145 };
...@@ -2143,15 +2148,15 @@ pub const Node = struct {...@@ -2143,15 +2148,15 @@ pub const Node = struct {
2143 base: Node,2148 base: Node,
2144 token: TokenIndex,2149 token: TokenIndex,
21452150
2146 pub fn iterate(self: &VarType, index: usize) ?&Node {2151 pub fn iterate(self: *VarType, index: usize) ?*Node {
2147 return null;2152 return null;
2148 }2153 }
21492154
2150 pub fn firstToken(self: &VarType) TokenIndex {2155 pub fn firstToken(self: *VarType) TokenIndex {
2151 return self.token;2156 return self.token;
2152 }2157 }
21532158
2154 pub fn lastToken(self: &VarType) TokenIndex {2159 pub fn lastToken(self: *VarType) TokenIndex {
2155 return self.token;2160 return self.token;
2156 }2161 }
2157 };2162 };
...@@ -2162,27 +2167,27 @@ pub const Node = struct {...@@ -2162,27 +2167,27 @@ pub const Node = struct {
21622167
2163 pub const LineList = SegmentedList(TokenIndex, 4);2168 pub const LineList = SegmentedList(TokenIndex, 4);
21642169
2165 pub fn iterate(self: &DocComment, index: usize) ?&Node {2170 pub fn iterate(self: *DocComment, index: usize) ?*Node {
2166 return null;2171 return null;
2167 }2172 }
21682173
2169 pub fn firstToken(self: &DocComment) TokenIndex {2174 pub fn firstToken(self: *DocComment) TokenIndex {
2170 return self.lines.at(0).*;2175 return self.lines.at(0).*;
2171 }2176 }
21722177
2173 pub fn lastToken(self: &DocComment) TokenIndex {2178 pub fn lastToken(self: *DocComment) TokenIndex {
2174 return self.lines.at(self.lines.len - 1).*;2179 return self.lines.at(self.lines.len - 1).*;
2175 }2180 }
2176 };2181 };
21772182
2178 pub const TestDecl = struct {2183 pub const TestDecl = struct {
2179 base: Node,2184 base: Node,
2180 doc_comments: ?&DocComment,2185 doc_comments: ?*DocComment,
2181 test_token: TokenIndex,2186 test_token: TokenIndex,
2182 name: &Node,2187 name: *Node,
2183 body_node: &Node,2188 body_node: *Node,
21842189
2185 pub fn iterate(self: &TestDecl, index: usize) ?&Node {2190 pub fn iterate(self: *TestDecl, index: usize) ?*Node {
2186 var i = index;2191 var i = index;
21872192
2188 if (i < 1) return self.body_node;2193 if (i < 1) return self.body_node;
...@@ -2191,11 +2196,11 @@ pub const Node = struct {...@@ -2191,11 +2196,11 @@ pub const Node = struct {
2191 return null;2196 return null;
2192 }2197 }
21932198
2194 pub fn firstToken(self: &TestDecl) TokenIndex {2199 pub fn firstToken(self: *TestDecl) TokenIndex {
2195 return self.test_token;2200 return self.test_token;
2196 }2201 }
21972202
2198 pub fn lastToken(self: &TestDecl) TokenIndex {2203 pub fn lastToken(self: *TestDecl) TokenIndex {
2199 return self.body_node.lastToken();2204 return self.body_node.lastToken();
2200 }2205 }
2201 };2206 };
std/zig/bench.zig+3-3
...@@ -24,15 +24,15 @@ pub fn main() !void {...@@ -24,15 +24,15 @@ pub fn main() !void {
24 const mb_per_sec = bytes_per_sec / (1024 * 1024);24 const mb_per_sec = bytes_per_sec / (1024 * 1024);
2525
26 var stdout_file = try std.io.getStdOut();26 var stdout_file = try std.io.getStdOut();
27 const stdout = &std.io.FileOutStream.init(&stdout_file).stream;27 const stdout = *std.io.FileOutStream.init(*stdout_file).stream;
28 try stdout.print("{.3} MB/s, {} KB used \n", mb_per_sec, memory_used / 1024);28 try stdout.print("{.3} MB/s, {} KB used \n", mb_per_sec, memory_used / 1024);
29}29}
3030
31fn testOnce() usize {31fn testOnce() usize {
32 var fixed_buf_alloc = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);32 var fixed_buf_alloc = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
33 var allocator = &fixed_buf_alloc.allocator;33 var allocator = *fixed_buf_alloc.allocator;
34 var tokenizer = Tokenizer.init(source);34 var tokenizer = Tokenizer.init(source);
35 var parser = Parser.init(&tokenizer, allocator, "(memory buffer)");35 var parser = Parser.init(*tokenizer, allocator, "(memory buffer)");
36 _ = parser.parse() catch @panic("parse failure");36 _ = parser.parse() catch @panic("parse failure");
37 return fixed_buf_alloc.end_index;37 return fixed_buf_alloc.end_index;
38}38}
std/zig/parse.zig+610-485
...@@ -9,7 +9,7 @@ const Error = ast.Error;...@@ -9,7 +9,7 @@ const Error = ast.Error;
99
10/// Result should be freed with tree.deinit() when there are10/// Result should be freed with tree.deinit() when there are
11/// no more references to any of the tokens or nodes.11/// no more references to any of the tokens or nodes.
12pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {12pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
13 var tree_arena = std.heap.ArenaAllocator.init(allocator);13 var tree_arena = std.heap.ArenaAllocator.init(allocator);
14 errdefer tree_arena.deinit();14 errdefer tree_arena.deinit();
1515
...@@ -81,10 +81,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -81,10 +81,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
81 });81 });
82 try root_node.decls.push(&test_node.base);82 try root_node.decls.push(&test_node.base);
83 try stack.append(State{ .Block = block });83 try stack.append(State{ .Block = block });
84 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{84 try stack.append(State{
85 .id = Token.Id.LBrace,85 .ExpectTokenSave = ExpectTokenSave{
86 .ptr = &block.lbrace,86 .id = Token.Id.LBrace,
87 } });87 .ptr = &block.lbrace,
88 },
89 });
88 try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &test_node.name } });90 try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &test_node.name } });
89 continue;91 continue;
90 },92 },
...@@ -95,13 +97,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -95,13 +97,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
95 },97 },
96 Token.Id.Keyword_pub => {98 Token.Id.Keyword_pub => {
97 stack.append(State.TopLevel) catch unreachable;99 stack.append(State.TopLevel) catch unreachable;
98 try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{100 try stack.append(State{
99 .decls = &root_node.decls,101 .TopLevelExtern = TopLevelDeclCtx{
100 .visib_token = token_index,102 .decls = &root_node.decls,
101 .extern_export_inline_token = null,103 .visib_token = token_index,
102 .lib_name = null,104 .extern_export_inline_token = null,
103 .comments = comments,105 .lib_name = null,
104 } });106 .comments = comments,
107 },
108 });
105 continue;109 continue;
106 },110 },
107 Token.Id.Keyword_comptime => {111 Token.Id.Keyword_comptime => {
...@@ -122,22 +126,26 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -122,22 +126,26 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
122126
123 stack.append(State.TopLevel) catch unreachable;127 stack.append(State.TopLevel) catch unreachable;
124 try stack.append(State{ .Block = block });128 try stack.append(State{ .Block = block });
125 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{129 try stack.append(State{
126 .id = Token.Id.LBrace,130 .ExpectTokenSave = ExpectTokenSave{
127 .ptr = &block.lbrace,131 .id = Token.Id.LBrace,
128 } });132 .ptr = &block.lbrace,
133 },
134 });
129 continue;135 continue;
130 },136 },
131 else => {137 else => {
132 prevToken(&tok_it, &tree);138 prevToken(&tok_it, &tree);
133 stack.append(State.TopLevel) catch unreachable;139 stack.append(State.TopLevel) catch unreachable;
134 try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{140 try stack.append(State{
135 .decls = &root_node.decls,141 .TopLevelExtern = TopLevelDeclCtx{
136 .visib_token = null,142 .decls = &root_node.decls,
137 .extern_export_inline_token = null,143 .visib_token = null,
138 .lib_name = null,144 .extern_export_inline_token = null,
139 .comments = comments,145 .lib_name = null,
140 } });146 .comments = comments,
147 },
148 });
141 continue;149 continue;
142 },150 },
143 }151 }
...@@ -147,31 +155,34 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -147,31 +155,34 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
147 const token_index = token.index;155 const token_index = token.index;
148 const token_ptr = token.ptr;156 const token_ptr = token.ptr;
149 switch (token_ptr.id) {157 switch (token_ptr.id) {
150 Token.Id.Keyword_export,158 Token.Id.Keyword_export, Token.Id.Keyword_inline => {
151 Token.Id.Keyword_inline => {159 stack.append(State{
152 stack.append(State{ .TopLevelDecl = TopLevelDeclCtx{160 .TopLevelDecl = TopLevelDeclCtx{
153 .decls = ctx.decls,161 .decls = ctx.decls,
154 .visib_token = ctx.visib_token,162 .visib_token = ctx.visib_token,
155 .extern_export_inline_token = AnnotatedToken{163 .extern_export_inline_token = AnnotatedToken{
156 .index = token_index,164 .index = token_index,
157 .ptr = token_ptr,165 .ptr = token_ptr,
166 },
167 .lib_name = null,
168 .comments = ctx.comments,
158 },169 },
159 .lib_name = null,170 }) catch unreachable;
160 .comments = ctx.comments,
161 } }) catch unreachable;
162 continue;171 continue;
163 },172 },
164 Token.Id.Keyword_extern => {173 Token.Id.Keyword_extern => {
165 stack.append(State{ .TopLevelLibname = TopLevelDeclCtx{174 stack.append(State{
166 .decls = ctx.decls,175 .TopLevelLibname = TopLevelDeclCtx{
167 .visib_token = ctx.visib_token,176 .decls = ctx.decls,
168 .extern_export_inline_token = AnnotatedToken{177 .visib_token = ctx.visib_token,
169 .index = token_index,178 .extern_export_inline_token = AnnotatedToken{
170 .ptr = token_ptr,179 .index = token_index,
180 .ptr = token_ptr,
181 },
182 .lib_name = null,
183 .comments = ctx.comments,
171 },184 },
172 .lib_name = null,185 }) catch unreachable;
173 .comments = ctx.comments,
174 } }) catch unreachable;
175 continue;186 continue;
176 },187 },
177 else => {188 else => {
...@@ -192,13 +203,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -192,13 +203,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
192 };203 };
193 };204 };
194205
195 stack.append(State{ .TopLevelDecl = TopLevelDeclCtx{206 stack.append(State{
196 .decls = ctx.decls,207 .TopLevelDecl = TopLevelDeclCtx{
197 .visib_token = ctx.visib_token,208 .decls = ctx.decls,
198 .extern_export_inline_token = ctx.extern_export_inline_token,209 .visib_token = ctx.visib_token,
199 .lib_name = lib_name,210 .extern_export_inline_token = ctx.extern_export_inline_token,
200 .comments = ctx.comments,211 .lib_name = lib_name,
201 } }) catch unreachable;212 .comments = ctx.comments,
213 },
214 }) catch unreachable;
202 continue;215 continue;
203 },216 },
204 State.TopLevelDecl => |ctx| {217 State.TopLevelDecl => |ctx| {
...@@ -222,15 +235,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -222,15 +235,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
222 });235 });
223 try ctx.decls.push(&node.base);236 try ctx.decls.push(&node.base);
224237
225 stack.append(State{ .ExpectTokenSave = ExpectTokenSave{238 stack.append(State{
226 .id = Token.Id.Semicolon,239 .ExpectTokenSave = ExpectTokenSave{
227 .ptr = &node.semicolon_token,240 .id = Token.Id.Semicolon,
228 } }) catch unreachable;241 .ptr = &node.semicolon_token,
242 },
243 }) catch unreachable;
229 try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } });244 try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } });
230 continue;245 continue;
231 },246 },
232 Token.Id.Keyword_var,247 Token.Id.Keyword_var, Token.Id.Keyword_const => {
233 Token.Id.Keyword_const => {
234 if (ctx.extern_export_inline_token) |annotated_token| {248 if (ctx.extern_export_inline_token) |annotated_token| {
235 if (annotated_token.ptr.id == Token.Id.Keyword_inline) {249 if (annotated_token.ptr.id == Token.Id.Keyword_inline) {
236 ((try tree.errors.addOne())).* = Error{ .InvalidToken = Error.InvalidToken{ .token = annotated_token.index } };250 ((try tree.errors.addOne())).* = Error{ .InvalidToken = Error.InvalidToken{ .token = annotated_token.index } };
...@@ -238,21 +252,20 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -238,21 +252,20 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
238 }252 }
239 }253 }
240254
241 try stack.append(State{ .VarDecl = VarDeclCtx{255 try stack.append(State{
242 .comments = ctx.comments,256 .VarDecl = VarDeclCtx{
243 .visib_token = ctx.visib_token,257 .comments = ctx.comments,
244 .lib_name = ctx.lib_name,258 .visib_token = ctx.visib_token,
245 .comptime_token = null,259 .lib_name = ctx.lib_name,
246 .extern_export_token = if (ctx.extern_export_inline_token) |at| at.index else null,260 .comptime_token = null,
247 .mut_token = token_index,261 .extern_export_token = if (ctx.extern_export_inline_token) |at| at.index else null,
248 .list = ctx.decls,262 .mut_token = token_index,
249 } });263 .list = ctx.decls,
264 },
265 });
250 continue;266 continue;
251 },267 },
252 Token.Id.Keyword_fn,268 Token.Id.Keyword_fn, Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc, Token.Id.Keyword_async => {
253 Token.Id.Keyword_nakedcc,
254 Token.Id.Keyword_stdcallcc,
255 Token.Id.Keyword_async => {
256 const fn_proto = try arena.construct(ast.Node.FnProto{269 const fn_proto = try arena.construct(ast.Node.FnProto{
257 .base = ast.Node{ .id = ast.Node.Id.FnProto },270 .base = ast.Node{ .id = ast.Node.Id.FnProto },
258 .doc_comments = ctx.comments,271 .doc_comments = ctx.comments,
...@@ -274,13 +287,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -274,13 +287,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
274 try stack.append(State{ .FnProto = fn_proto });287 try stack.append(State{ .FnProto = fn_proto });
275288
276 switch (token_ptr.id) {289 switch (token_ptr.id) {
277 Token.Id.Keyword_nakedcc,290 Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc => {
278 Token.Id.Keyword_stdcallcc => {
279 fn_proto.cc_token = token_index;291 fn_proto.cc_token = token_index;
280 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{292 try stack.append(State{
281 .id = Token.Id.Keyword_fn,293 .ExpectTokenSave = ExpectTokenSave{
282 .ptr = &fn_proto.fn_token,294 .id = Token.Id.Keyword_fn,
283 } });295 .ptr = &fn_proto.fn_token,
296 },
297 });
284 continue;298 continue;
285 },299 },
286 Token.Id.Keyword_async => {300 Token.Id.Keyword_async => {
...@@ -292,10 +306,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -292,10 +306,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
292 });306 });
293 fn_proto.async_attr = async_node;307 fn_proto.async_attr = async_node;
294308
295 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{309 try stack.append(State{
296 .id = Token.Id.Keyword_fn,310 .ExpectTokenSave = ExpectTokenSave{
297 .ptr = &fn_proto.fn_token,311 .id = Token.Id.Keyword_fn,
298 } });312 .ptr = &fn_proto.fn_token,
313 },
314 });
299 try stack.append(State{ .AsyncAllocator = async_node });315 try stack.append(State{ .AsyncAllocator = async_node });
300 continue;316 continue;
301 },317 },
...@@ -331,13 +347,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -331,13 +347,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
331 }347 }
332348
333 stack.append(State{ .ContainerDecl = ctx.container_decl }) catch unreachable;349 stack.append(State{ .ContainerDecl = ctx.container_decl }) catch unreachable;
334 try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{350 try stack.append(State{
335 .decls = &ctx.container_decl.fields_and_decls,351 .TopLevelExtern = TopLevelDeclCtx{
336 .visib_token = ctx.visib_token,352 .decls = &ctx.container_decl.fields_and_decls,
337 .extern_export_inline_token = null,353 .visib_token = ctx.visib_token,
338 .lib_name = null,354 .extern_export_inline_token = null,
339 .comments = ctx.comments,355 .lib_name = null,
340 } });356 .comments = ctx.comments,
357 },
358 });
341 continue;359 continue;
342 },360 },
343361
...@@ -361,9 +379,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -361,9 +379,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
361 .base = ast.Node{ .id = ast.Node.Id.ContainerDecl },379 .base = ast.Node{ .id = ast.Node.Id.ContainerDecl },
362 .layout_token = ctx.layout_token,380 .layout_token = ctx.layout_token,
363 .kind_token = switch (token_ptr.id) {381 .kind_token = switch (token_ptr.id) {
364 Token.Id.Keyword_struct,382 Token.Id.Keyword_struct, Token.Id.Keyword_union, Token.Id.Keyword_enum => token_index,
365 Token.Id.Keyword_union,
366 Token.Id.Keyword_enum => token_index,
367 else => {383 else => {
368 ((try tree.errors.addOne())).* = Error{ .ExpectedAggregateKw = Error.ExpectedAggregateKw{ .token = token_index } };384 ((try tree.errors.addOne())).* = Error{ .ExpectedAggregateKw = Error.ExpectedAggregateKw{ .token = token_index } };
369 return tree;385 return tree;
...@@ -377,10 +393,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -377,10 +393,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
377 ctx.opt_ctx.store(&node.base);393 ctx.opt_ctx.store(&node.base);
378394
379 stack.append(State{ .ContainerDecl = node }) catch unreachable;395 stack.append(State{ .ContainerDecl = node }) catch unreachable;
380 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{396 try stack.append(State{
381 .id = Token.Id.LBrace,397 .ExpectTokenSave = ExpectTokenSave{
382 .ptr = &node.lbrace_token,398 .id = Token.Id.LBrace,
383 } });399 .ptr = &node.lbrace_token,
400 },
401 });
384 try stack.append(State{ .ContainerInitArgStart = node });402 try stack.append(State{ .ContainerInitArgStart = node });
385 continue;403 continue;
386 },404 },
...@@ -481,35 +499,41 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -481,35 +499,41 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
481 Token.Id.Keyword_pub => {499 Token.Id.Keyword_pub => {
482 switch (tree.tokens.at(container_decl.kind_token).id) {500 switch (tree.tokens.at(container_decl.kind_token).id) {
483 Token.Id.Keyword_struct => {501 Token.Id.Keyword_struct => {
484 try stack.append(State{ .TopLevelExternOrField = TopLevelExternOrFieldCtx{502 try stack.append(State{
485 .visib_token = token_index,503 .TopLevelExternOrField = TopLevelExternOrFieldCtx{
486 .container_decl = container_decl,504 .visib_token = token_index,
487 .comments = comments,505 .container_decl = container_decl,
488 } });506 .comments = comments,
507 },
508 });
489 continue;509 continue;
490 },510 },
491 else => {511 else => {
492 stack.append(State{ .ContainerDecl = container_decl }) catch unreachable;512 stack.append(State{ .ContainerDecl = container_decl }) catch unreachable;
493 try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{513 try stack.append(State{
494 .decls = &container_decl.fields_and_decls,514 .TopLevelExtern = TopLevelDeclCtx{
495 .visib_token = token_index,515 .decls = &container_decl.fields_and_decls,
496 .extern_export_inline_token = null,516 .visib_token = token_index,
497 .lib_name = null,517 .extern_export_inline_token = null,
498 .comments = comments,518 .lib_name = null,
499 } });519 .comments = comments,
520 },
521 });
500 continue;522 continue;
501 },523 },
502 }524 }
503 },525 },
504 Token.Id.Keyword_export => {526 Token.Id.Keyword_export => {
505 stack.append(State{ .ContainerDecl = container_decl }) catch unreachable;527 stack.append(State{ .ContainerDecl = container_decl }) catch unreachable;
506 try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{528 try stack.append(State{
507 .decls = &container_decl.fields_and_decls,529 .TopLevelExtern = TopLevelDeclCtx{
508 .visib_token = token_index,530 .decls = &container_decl.fields_and_decls,
509 .extern_export_inline_token = null,531 .visib_token = token_index,
510 .lib_name = null,532 .extern_export_inline_token = null,
511 .comments = comments,533 .lib_name = null,
512 } });534 .comments = comments,
535 },
536 });
513 continue;537 continue;
514 },538 },
515 Token.Id.RBrace => {539 Token.Id.RBrace => {
...@@ -523,13 +547,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -523,13 +547,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
523 else => {547 else => {
524 prevToken(&tok_it, &tree);548 prevToken(&tok_it, &tree);
525 stack.append(State{ .ContainerDecl = container_decl }) catch unreachable;549 stack.append(State{ .ContainerDecl = container_decl }) catch unreachable;
526 try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{550 try stack.append(State{
527 .decls = &container_decl.fields_and_decls,551 .TopLevelExtern = TopLevelDeclCtx{
528 .visib_token = null,552 .decls = &container_decl.fields_and_decls,
529 .extern_export_inline_token = null,553 .visib_token = null,
530 .lib_name = null,554 .extern_export_inline_token = null,
531 .comments = comments,555 .lib_name = null,
532 } });556 .comments = comments,
557 },
558 });
533 continue;559 continue;
534 },560 },
535 }561 }
...@@ -557,10 +583,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -557,10 +583,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
557 try stack.append(State{ .VarDeclAlign = var_decl });583 try stack.append(State{ .VarDeclAlign = var_decl });
558 try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &var_decl.type_node } });584 try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &var_decl.type_node } });
559 try stack.append(State{ .IfToken = Token.Id.Colon });585 try stack.append(State{ .IfToken = Token.Id.Colon });
560 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{586 try stack.append(State{
561 .id = Token.Id.Identifier,587 .ExpectTokenSave = ExpectTokenSave{
562 .ptr = &var_decl.name_token,588 .id = Token.Id.Identifier,
563 } });589 .ptr = &var_decl.name_token,
590 },
591 });
564 continue;592 continue;
565 },593 },
566 State.VarDeclAlign => |var_decl| {594 State.VarDeclAlign => |var_decl| {
...@@ -605,10 +633,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -605,10 +633,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
605 const semicolon_token = nextToken(&tok_it, &tree);633 const semicolon_token = nextToken(&tok_it, &tree);
606634
607 if (semicolon_token.ptr.id != Token.Id.Semicolon) {635 if (semicolon_token.ptr.id != Token.Id.Semicolon) {
608 ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{636 ((try tree.errors.addOne())).* = Error{
609 .token = semicolon_token.index,637 .ExpectedToken = Error.ExpectedToken{
610 .expected_id = Token.Id.Semicolon,638 .token = semicolon_token.index,
611 } };639 .expected_id = Token.Id.Semicolon,
640 },
641 };
612 return tree;642 return tree;
613 }643 }
614644
...@@ -713,10 +743,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -713,10 +743,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
713 });743 });
714 try fn_proto.params.push(&param_decl.base);744 try fn_proto.params.push(&param_decl.base);
715745
716 stack.append(State{ .ParamDeclEnd = ParamDeclEndCtx{746 stack.append(State{
717 .param_decl = param_decl,747 .ParamDeclEnd = ParamDeclEndCtx{
718 .fn_proto = fn_proto,748 .param_decl = param_decl,
719 } }) catch unreachable;749 .fn_proto = fn_proto,
750 },
751 }) catch unreachable;
720 try stack.append(State{ .ParamDeclName = param_decl });752 try stack.append(State{ .ParamDeclName = param_decl });
721 try stack.append(State{ .ParamDeclAliasOrComptime = param_decl });753 try stack.append(State{ .ParamDeclAliasOrComptime = param_decl });
722 continue;754 continue;
...@@ -769,10 +801,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -769,10 +801,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
769801
770 State.MaybeLabeledExpression => |ctx| {802 State.MaybeLabeledExpression => |ctx| {
771 if (eatToken(&tok_it, &tree, Token.Id.Colon)) |_| {803 if (eatToken(&tok_it, &tree, Token.Id.Colon)) |_| {
772 stack.append(State{ .LabeledExpression = LabelCtx{804 stack.append(State{
773 .label = ctx.label,805 .LabeledExpression = LabelCtx{
774 .opt_ctx = ctx.opt_ctx,806 .label = ctx.label,
775 } }) catch unreachable;807 .opt_ctx = ctx.opt_ctx,
808 },
809 }) catch unreachable;
776 continue;810 continue;
777 }811 }
778812
...@@ -797,21 +831,25 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -797,21 +831,25 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
797 continue;831 continue;
798 },832 },
799 Token.Id.Keyword_while => {833 Token.Id.Keyword_while => {
800 stack.append(State{ .While = LoopCtx{834 stack.append(State{
801 .label = ctx.label,835 .While = LoopCtx{
802 .inline_token = null,836 .label = ctx.label,
803 .loop_token = token_index,837 .inline_token = null,
804 .opt_ctx = ctx.opt_ctx.toRequired(),838 .loop_token = token_index,
805 } }) catch unreachable;839 .opt_ctx = ctx.opt_ctx.toRequired(),
840 },
841 }) catch unreachable;
806 continue;842 continue;
807 },843 },
808 Token.Id.Keyword_for => {844 Token.Id.Keyword_for => {
809 stack.append(State{ .For = LoopCtx{845 stack.append(State{
810 .label = ctx.label,846 .For = LoopCtx{
811 .inline_token = null,847 .label = ctx.label,
812 .loop_token = token_index,848 .inline_token = null,
813 .opt_ctx = ctx.opt_ctx.toRequired(),849 .loop_token = token_index,
814 } }) catch unreachable;850 .opt_ctx = ctx.opt_ctx.toRequired(),
851 },
852 }) catch unreachable;
815 continue;853 continue;
816 },854 },
817 Token.Id.Keyword_suspend => {855 Token.Id.Keyword_suspend => {
...@@ -828,11 +866,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -828,11 +866,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
828 continue;866 continue;
829 },867 },
830 Token.Id.Keyword_inline => {868 Token.Id.Keyword_inline => {
831 stack.append(State{ .Inline = InlineCtx{869 stack.append(State{
832 .label = ctx.label,870 .Inline = InlineCtx{
833 .inline_token = token_index,871 .label = ctx.label,
834 .opt_ctx = ctx.opt_ctx.toRequired(),872 .inline_token = token_index,
835 } }) catch unreachable;873 .opt_ctx = ctx.opt_ctx.toRequired(),
874 },
875 }) catch unreachable;
836 continue;876 continue;
837 },877 },
838 else => {878 else => {
...@@ -852,21 +892,25 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -852,21 +892,25 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
852 const token_ptr = token.ptr;892 const token_ptr = token.ptr;
853 switch (token_ptr.id) {893 switch (token_ptr.id) {
854 Token.Id.Keyword_while => {894 Token.Id.Keyword_while => {
855 stack.append(State{ .While = LoopCtx{895 stack.append(State{
856 .inline_token = ctx.inline_token,896 .While = LoopCtx{
857 .label = ctx.label,897 .inline_token = ctx.inline_token,
858 .loop_token = token_index,898 .label = ctx.label,
859 .opt_ctx = ctx.opt_ctx.toRequired(),899 .loop_token = token_index,
860 } }) catch unreachable;900 .opt_ctx = ctx.opt_ctx.toRequired(),
901 },
902 }) catch unreachable;
861 continue;903 continue;
862 },904 },
863 Token.Id.Keyword_for => {905 Token.Id.Keyword_for => {
864 stack.append(State{ .For = LoopCtx{906 stack.append(State{
865 .inline_token = ctx.inline_token,907 .For = LoopCtx{
866 .label = ctx.label,908 .inline_token = ctx.inline_token,
867 .loop_token = token_index,909 .label = ctx.label,
868 .opt_ctx = ctx.opt_ctx.toRequired(),910 .loop_token = token_index,
869 } }) catch unreachable;911 .opt_ctx = ctx.opt_ctx.toRequired(),
912 },
913 }) catch unreachable;
870 continue;914 continue;
871 },915 },
872 else => {916 else => {
...@@ -971,27 +1015,29 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -971,27 +1015,29 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
971 const token_ptr = token.ptr;1015 const token_ptr = token.ptr;
972 switch (token_ptr.id) {1016 switch (token_ptr.id) {
973 Token.Id.Keyword_comptime => {1017 Token.Id.Keyword_comptime => {
974 stack.append(State{ .ComptimeStatement = ComptimeStatementCtx{1018 stack.append(State{
975 .comptime_token = token_index,1019 .ComptimeStatement = ComptimeStatementCtx{
976 .block = block,1020 .comptime_token = token_index,
977 } }) catch unreachable;1021 .block = block,
978 continue;1022 },
979 },1023 }) catch unreachable;
980 Token.Id.Keyword_var,1024 continue;
981 Token.Id.Keyword_const => {1025 },
982 stack.append(State{ .VarDecl = VarDeclCtx{1026 Token.Id.Keyword_var, Token.Id.Keyword_const => {
983 .comments = null,1027 stack.append(State{
984 .visib_token = null,1028 .VarDecl = VarDeclCtx{
985 .comptime_token = null,1029 .comments = null,
986 .extern_export_token = null,1030 .visib_token = null,
987 .lib_name = null,1031 .comptime_token = null,
988 .mut_token = token_index,1032 .extern_export_token = null,
989 .list = &block.statements,1033 .lib_name = null,
990 } }) catch unreachable;1034 .mut_token = token_index,
1035 .list = &block.statements,
1036 },
1037 }) catch unreachable;
991 continue;1038 continue;
992 },1039 },
993 Token.Id.Keyword_defer,1040 Token.Id.Keyword_defer, Token.Id.Keyword_errdefer => {
994 Token.Id.Keyword_errdefer => {
995 const node = try arena.construct(ast.Node.Defer{1041 const node = try arena.construct(ast.Node.Defer{
996 .base = ast.Node{ .id = ast.Node.Id.Defer },1042 .base = ast.Node{ .id = ast.Node.Id.Defer },
997 .defer_token = token_index,1043 .defer_token = token_index,
...@@ -1036,17 +1082,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1036,17 +1082,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1036 const token_index = token.index;1082 const token_index = token.index;
1037 const token_ptr = token.ptr;1083 const token_ptr = token.ptr;
1038 switch (token_ptr.id) {1084 switch (token_ptr.id) {
1039 Token.Id.Keyword_var,1085 Token.Id.Keyword_var, Token.Id.Keyword_const => {
1040 Token.Id.Keyword_const => {1086 stack.append(State{
1041 stack.append(State{ .VarDecl = VarDeclCtx{1087 .VarDecl = VarDeclCtx{
1042 .comments = null,1088 .comments = null,
1043 .visib_token = null,1089 .visib_token = null,
1044 .comptime_token = ctx.comptime_token,1090 .comptime_token = ctx.comptime_token,
1045 .extern_export_token = null,1091 .extern_export_token = null,
1046 .lib_name = null,1092 .lib_name = null,
1047 .mut_token = token_index,1093 .mut_token = token_index,
1048 .list = &ctx.block.statements,1094 .list = &ctx.block.statements,
1049 } }) catch unreachable;1095 },
1096 }) catch unreachable;
1050 continue;1097 continue;
1051 },1098 },
1052 else => {1099 else => {
...@@ -1089,10 +1136,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1089,10 +1136,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
10891136
1090 stack.append(State{ .AsmOutputItems = items }) catch unreachable;1137 stack.append(State{ .AsmOutputItems = items }) catch unreachable;
1091 try stack.append(State{ .IfToken = Token.Id.Comma });1138 try stack.append(State{ .IfToken = Token.Id.Comma });
1092 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{1139 try stack.append(State{
1093 .id = Token.Id.RParen,1140 .ExpectTokenSave = ExpectTokenSave{
1094 .ptr = &node.rparen,1141 .id = Token.Id.RParen,
1095 } });1142 .ptr = &node.rparen,
1143 },
1144 });
1096 try stack.append(State{ .AsmOutputReturnOrType = node });1145 try stack.append(State{ .AsmOutputReturnOrType = node });
1097 try stack.append(State{ .ExpectToken = Token.Id.LParen });1146 try stack.append(State{ .ExpectToken = Token.Id.LParen });
1098 try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } });1147 try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } });
...@@ -1141,10 +1190,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1141,10 +1190,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
11411190
1142 stack.append(State{ .AsmInputItems = items }) catch unreachable;1191 stack.append(State{ .AsmInputItems = items }) catch unreachable;
1143 try stack.append(State{ .IfToken = Token.Id.Comma });1192 try stack.append(State{ .IfToken = Token.Id.Comma });
1144 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{1193 try stack.append(State{
1145 .id = Token.Id.RParen,1194 .ExpectTokenSave = ExpectTokenSave{
1146 .ptr = &node.rparen,1195 .id = Token.Id.RParen,
1147 } });1196 .ptr = &node.rparen,
1197 },
1198 });
1148 try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } });1199 try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } });
1149 try stack.append(State{ .ExpectToken = Token.Id.LParen });1200 try stack.append(State{ .ExpectToken = Token.Id.LParen });
1150 try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } });1201 try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } });
...@@ -1203,14 +1254,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1203,14 +1254,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1203 stack.append(State{ .FieldInitListCommaOrEnd = list_state }) catch unreachable;1254 stack.append(State{ .FieldInitListCommaOrEnd = list_state }) catch unreachable;
1204 try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } });1255 try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } });
1205 try stack.append(State{ .ExpectToken = Token.Id.Equal });1256 try stack.append(State{ .ExpectToken = Token.Id.Equal });
1206 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{1257 try stack.append(State{
1207 .id = Token.Id.Identifier,1258 .ExpectTokenSave = ExpectTokenSave{
1208 .ptr = &node.name_token,1259 .id = Token.Id.Identifier,
1209 } });1260 .ptr = &node.name_token,
1210 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{1261 },
1211 .id = Token.Id.Period,1262 });
1212 .ptr = &node.period_token,1263 try stack.append(State{
1213 } });1264 .ExpectTokenSave = ExpectTokenSave{
1265 .id = Token.Id.Period,
1266 .ptr = &node.period_token,
1267 },
1268 });
1214 continue;1269 continue;
1215 },1270 },
1216 State.FieldInitListCommaOrEnd => |list_state| {1271 State.FieldInitListCommaOrEnd => |list_state| {
...@@ -1320,10 +1375,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1320,10 +1375,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1320 });1375 });
1321 try switch_case.items.push(&else_node.base);1376 try switch_case.items.push(&else_node.base);
13221377
1323 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{1378 try stack.append(State{
1324 .id = Token.Id.EqualAngleBracketRight,1379 .ExpectTokenSave = ExpectTokenSave{
1325 .ptr = &switch_case.arrow_token,1380 .id = Token.Id.EqualAngleBracketRight,
1326 } });1381 .ptr = &switch_case.arrow_token,
1382 },
1383 });
1327 continue;1384 continue;
1328 } else {1385 } else {
1329 prevToken(&tok_it, &tree);1386 prevToken(&tok_it, &tree);
...@@ -1374,10 +1431,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1374,10 +1431,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1374 }1431 }
13751432
1376 async_node.rangle_bracket = TokenIndex(0);1433 async_node.rangle_bracket = TokenIndex(0);
1377 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{1434 try stack.append(State{
1378 .id = Token.Id.AngleBracketRight,1435 .ExpectTokenSave = ExpectTokenSave{
1379 .ptr = &??async_node.rangle_bracket,1436 .id = Token.Id.AngleBracketRight,
1380 } });1437 .ptr = &??async_node.rangle_bracket,
1438 },
1439 });
1381 try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &async_node.allocator_type } });1440 try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &async_node.allocator_type } });
1382 continue;1441 continue;
1383 },1442 },
...@@ -1430,10 +1489,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1430,10 +1489,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1430 continue;1489 continue;
1431 }1490 }
14321491
1433 stack.append(State{ .ContainerKind = ContainerKindCtx{1492 stack.append(State{
1434 .opt_ctx = ctx.opt_ctx,1493 .ContainerKind = ContainerKindCtx{
1435 .layout_token = ctx.extern_token,1494 .opt_ctx = ctx.opt_ctx,
1436 } }) catch unreachable;1495 .layout_token = ctx.extern_token,
1496 },
1497 }) catch unreachable;
1437 continue;1498 continue;
1438 },1499 },
1439 State.SliceOrArrayAccess => |node| {1500 State.SliceOrArrayAccess => |node| {
...@@ -1443,15 +1504,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1443,15 +1504,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1443 switch (token_ptr.id) {1504 switch (token_ptr.id) {
1444 Token.Id.Ellipsis2 => {1505 Token.Id.Ellipsis2 => {
1445 const start = node.op.ArrayAccess;1506 const start = node.op.ArrayAccess;
1446 node.op = ast.Node.SuffixOp.Op{ .Slice = ast.Node.SuffixOp.Op.Slice{1507 node.op = ast.Node.SuffixOp.Op{
1447 .start = start,1508 .Slice = ast.Node.SuffixOp.Op.Slice{
1448 .end = null,1509 .start = start,
1449 } };1510 .end = null,
1511 },
1512 };
14501513
1451 stack.append(State{ .ExpectTokenSave = ExpectTokenSave{1514 stack.append(State{
1452 .id = Token.Id.RBracket,1515 .ExpectTokenSave = ExpectTokenSave{
1453 .ptr = &node.rtoken,1516 .id = Token.Id.RBracket,
1454 } }) catch unreachable;1517 .ptr = &node.rtoken,
1518 },
1519 }) catch unreachable;
1455 try stack.append(State{ .Expression = OptionalCtx{ .Optional = &node.op.Slice.end } });1520 try stack.append(State{ .Expression = OptionalCtx{ .Optional = &node.op.Slice.end } });
1456 continue;1521 continue;
1457 },1522 },
...@@ -1467,13 +1532,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1467,13 +1532,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1467 },1532 },
1468 State.SliceOrArrayType => |node| {1533 State.SliceOrArrayType => |node| {
1469 if (eatToken(&tok_it, &tree, Token.Id.RBracket)) |_| {1534 if (eatToken(&tok_it, &tree, Token.Id.RBracket)) |_| {
1470 node.op = ast.Node.PrefixOp.Op{ .SliceType = ast.Node.PrefixOp.AddrOfInfo{1535 node.op = ast.Node.PrefixOp.Op{
1471 .align_info = null,1536 .SliceType = ast.Node.PrefixOp.PtrInfo{
1472 .const_token = null,1537 .align_info = null,
1473 .volatile_token = null,1538 .const_token = null,
1474 } };1539 .volatile_token = null,
1540 },
1541 };
1475 stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &node.rhs } }) catch unreachable;1542 stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &node.rhs } }) catch unreachable;
1476 try stack.append(State{ .AddrOfModifiers = &node.op.SliceType });1543 try stack.append(State{ .PtrTypeModifiers = &node.op.SliceType });
1477 continue;1544 continue;
1478 }1545 }
14791546
...@@ -1484,7 +1551,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1484,7 +1551,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1484 continue;1551 continue;
1485 },1552 },
14861553
1487 State.AddrOfModifiers => |addr_of_info| {1554 State.PtrTypeModifiers => |addr_of_info| {
1488 const token = nextToken(&tok_it, &tree);1555 const token = nextToken(&tok_it, &tree);
1489 const token_index = token.index;1556 const token_index = token.index;
1490 const token_ptr = token.ptr;1557 const token_ptr = token.ptr;
...@@ -1495,7 +1562,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1495,7 +1562,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1495 ((try tree.errors.addOne())).* = Error{ .ExtraAlignQualifier = Error.ExtraAlignQualifier{ .token = token_index } };1562 ((try tree.errors.addOne())).* = Error{ .ExtraAlignQualifier = Error.ExtraAlignQualifier{ .token = token_index } };
1496 return tree;1563 return tree;
1497 }1564 }
1498 addr_of_info.align_info = ast.Node.PrefixOp.AddrOfInfo.Align {1565 addr_of_info.align_info = ast.Node.PrefixOp.PtrInfo.Align{
1499 .node = undefined,1566 .node = undefined,
1500 .bit_range = null,1567 .bit_range = null,
1501 };1568 };
...@@ -1536,7 +1603,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1536,7 +1603,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1536 const token = nextToken(&tok_it, &tree);1603 const token = nextToken(&tok_it, &tree);
1537 switch (token.ptr.id) {1604 switch (token.ptr.id) {
1538 Token.Id.Colon => {1605 Token.Id.Colon => {
1539 align_info.bit_range = ast.Node.PrefixOp.AddrOfInfo.Align.BitRange(undefined);1606 align_info.bit_range = ast.Node.PrefixOp.PtrInfo.Align.BitRange(undefined);
1540 const bit_range = &??align_info.bit_range;1607 const bit_range = &??align_info.bit_range;
15411608
1542 try stack.append(State{ .ExpectToken = Token.Id.RParen });1609 try stack.append(State{ .ExpectToken = Token.Id.RParen });
...@@ -1548,9 +1615,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1548,9 +1615,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1548 Token.Id.RParen => continue,1615 Token.Id.RParen => continue,
1549 else => {1616 else => {
1550 (try tree.errors.addOne()).* = Error{1617 (try tree.errors.addOne()).* = Error{
1551 .ExpectedColonOrRParen = Error.ExpectedColonOrRParen{1618 .ExpectedColonOrRParen = Error.ExpectedColonOrRParen{ .token = token.index },
1552 .token = token.index,
1553 }
1554 };1619 };
1555 return tree;1620 return tree;
1556 },1621 },
...@@ -1563,10 +1628,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1563,10 +1628,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1563 const token_ptr = token.ptr;1628 const token_ptr = token.ptr;
1564 if (token_ptr.id != Token.Id.Pipe) {1629 if (token_ptr.id != Token.Id.Pipe) {
1565 if (opt_ctx != OptionalCtx.Optional) {1630 if (opt_ctx != OptionalCtx.Optional) {
1566 ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{1631 ((try tree.errors.addOne())).* = Error{
1567 .token = token_index,1632 .ExpectedToken = Error.ExpectedToken{
1568 .expected_id = Token.Id.Pipe,1633 .token = token_index,
1569 } };1634 .expected_id = Token.Id.Pipe,
1635 },
1636 };
1570 return tree;1637 return tree;
1571 }1638 }
15721639
...@@ -1582,10 +1649,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1582,10 +1649,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1582 });1649 });
1583 opt_ctx.store(&node.base);1650 opt_ctx.store(&node.base);
15841651
1585 stack.append(State{ .ExpectTokenSave = ExpectTokenSave{1652 stack.append(State{
1586 .id = Token.Id.Pipe,1653 .ExpectTokenSave = ExpectTokenSave{
1587 .ptr = &node.rpipe,1654 .id = Token.Id.Pipe,
1588 } }) catch unreachable;1655 .ptr = &node.rpipe,
1656 },
1657 }) catch unreachable;
1589 try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.error_symbol } });1658 try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.error_symbol } });
1590 continue;1659 continue;
1591 },1660 },
...@@ -1595,10 +1664,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1595,10 +1664,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1595 const token_ptr = token.ptr;1664 const token_ptr = token.ptr;
1596 if (token_ptr.id != Token.Id.Pipe) {1665 if (token_ptr.id != Token.Id.Pipe) {
1597 if (opt_ctx != OptionalCtx.Optional) {1666 if (opt_ctx != OptionalCtx.Optional) {
1598 ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{1667 ((try tree.errors.addOne())).* = Error{
1599 .token = token_index,1668 .ExpectedToken = Error.ExpectedToken{
1600 .expected_id = Token.Id.Pipe,1669 .token = token_index,
1601 } };1670 .expected_id = Token.Id.Pipe,
1671 },
1672 };
1602 return tree;1673 return tree;
1603 }1674 }
16041675
...@@ -1615,15 +1686,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1615,15 +1686,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1615 });1686 });
1616 opt_ctx.store(&node.base);1687 opt_ctx.store(&node.base);
16171688
1618 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{1689 try stack.append(State{
1619 .id = Token.Id.Pipe,1690 .ExpectTokenSave = ExpectTokenSave{
1620 .ptr = &node.rpipe,1691 .id = Token.Id.Pipe,
1621 } });1692 .ptr = &node.rpipe,
1693 },
1694 });
1622 try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.value_symbol } });1695 try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.value_symbol } });
1623 try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{1696 try stack.append(State{
1624 .id = Token.Id.Asterisk,1697 .OptionalTokenSave = OptionalTokenSave{
1625 .ptr = &node.ptr_token,1698 .id = Token.Id.Asterisk,
1626 } });1699 .ptr = &node.ptr_token,
1700 },
1701 });
1627 continue;1702 continue;
1628 },1703 },
1629 State.PointerIndexPayload => |opt_ctx| {1704 State.PointerIndexPayload => |opt_ctx| {
...@@ -1632,10 +1707,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1632,10 +1707,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1632 const token_ptr = token.ptr;1707 const token_ptr = token.ptr;
1633 if (token_ptr.id != Token.Id.Pipe) {1708 if (token_ptr.id != Token.Id.Pipe) {
1634 if (opt_ctx != OptionalCtx.Optional) {1709 if (opt_ctx != OptionalCtx.Optional) {
1635 ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{1710 ((try tree.errors.addOne())).* = Error{
1636 .token = token_index,1711 .ExpectedToken = Error.ExpectedToken{
1637 .expected_id = Token.Id.Pipe,1712 .token = token_index,
1638 } };1713 .expected_id = Token.Id.Pipe,
1714 },
1715 };
1639 return tree;1716 return tree;
1640 }1717 }
16411718
...@@ -1653,17 +1730,21 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1653,17 +1730,21 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1653 });1730 });
1654 opt_ctx.store(&node.base);1731 opt_ctx.store(&node.base);
16551732
1656 stack.append(State{ .ExpectTokenSave = ExpectTokenSave{1733 stack.append(State{
1657 .id = Token.Id.Pipe,1734 .ExpectTokenSave = ExpectTokenSave{
1658 .ptr = &node.rpipe,1735 .id = Token.Id.Pipe,
1659 } }) catch unreachable;1736 .ptr = &node.rpipe,
1737 },
1738 }) catch unreachable;
1660 try stack.append(State{ .Identifier = OptionalCtx{ .RequiredNull = &node.index_symbol } });1739 try stack.append(State{ .Identifier = OptionalCtx{ .RequiredNull = &node.index_symbol } });
1661 try stack.append(State{ .IfToken = Token.Id.Comma });1740 try stack.append(State{ .IfToken = Token.Id.Comma });
1662 try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.value_symbol } });1741 try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.value_symbol } });
1663 try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{1742 try stack.append(State{
1664 .id = Token.Id.Asterisk,1743 .OptionalTokenSave = OptionalTokenSave{
1665 .ptr = &node.ptr_token,1744 .id = Token.Id.Asterisk,
1666 } });1745 .ptr = &node.ptr_token,
1746 },
1747 });
1667 continue;1748 continue;
1668 },1749 },
16691750
...@@ -1672,9 +1753,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1672,9 +1753,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1672 const token_index = token.index;1753 const token_index = token.index;
1673 const token_ptr = token.ptr;1754 const token_ptr = token.ptr;
1674 switch (token_ptr.id) {1755 switch (token_ptr.id) {
1675 Token.Id.Keyword_return,1756 Token.Id.Keyword_return, Token.Id.Keyword_break, Token.Id.Keyword_continue => {
1676 Token.Id.Keyword_break,
1677 Token.Id.Keyword_continue => {
1678 const node = try arena.construct(ast.Node.ControlFlowExpression{1757 const node = try arena.construct(ast.Node.ControlFlowExpression{
1679 .base = ast.Node{ .id = ast.Node.Id.ControlFlowExpression },1758 .base = ast.Node{ .id = ast.Node.Id.ControlFlowExpression },
1680 .ltoken = token_index,1759 .ltoken = token_index,
...@@ -1703,9 +1782,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -1703,9 +1782,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
1703 }1782 }
1704 continue;1783 continue;
1705 },1784 },
1706 Token.Id.Keyword_try,1785 Token.Id.Keyword_try, Token.Id.Keyword_cancel, Token.Id.Keyword_resume => {
1707 Token.Id.Keyword_cancel,
1708 Token.Id.Keyword_resume => {
1709 const node = try arena.construct(ast.Node.PrefixOp{1786 const node = try arena.construct(ast.Node.PrefixOp{
1710 .base = ast.Node{ .id = ast.Node.Id.PrefixOp },1787 .base = ast.Node{ .id = ast.Node.Id.PrefixOp },
1711 .op_token = token_index,1788 .op_token = token_index,
...@@ -2078,10 +2155,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2078,10 +2155,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
20782155
2079 stack.append(State{ .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable;2156 stack.append(State{ .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable;
2080 try stack.append(State{ .IfToken = Token.Id.LBrace });2157 try stack.append(State{ .IfToken = Token.Id.LBrace });
2081 try stack.append(State{ .FieldInitListItemOrEnd = ListSave(@typeOf(node.op.StructInitializer)){2158 try stack.append(State{
2082 .list = &node.op.StructInitializer,2159 .FieldInitListItemOrEnd = ListSave(@typeOf(node.op.StructInitializer)){
2083 .ptr = &node.rtoken,2160 .list = &node.op.StructInitializer,
2084 } });2161 .ptr = &node.rtoken,
2162 },
2163 });
2085 continue;2164 continue;
2086 }2165 }
20872166
...@@ -2094,11 +2173,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2094,11 +2173,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2094 opt_ctx.store(&node.base);2173 opt_ctx.store(&node.base);
2095 stack.append(State{ .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable;2174 stack.append(State{ .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable;
2096 try stack.append(State{ .IfToken = Token.Id.LBrace });2175 try stack.append(State{ .IfToken = Token.Id.LBrace });
2097 try stack.append(State{ .ExprListItemOrEnd = ExprListCtx{2176 try stack.append(State{
2098 .list = &node.op.ArrayInitializer,2177 .ExprListItemOrEnd = ExprListCtx{
2099 .end = Token.Id.RBrace,2178 .list = &node.op.ArrayInitializer,
2100 .ptr = &node.rtoken,2179 .end = Token.Id.RBrace,
2101 } });2180 .ptr = &node.rtoken,
2181 },
2182 });
2102 continue;2183 continue;
2103 },2184 },
21042185
...@@ -2139,7 +2220,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2139,7 +2220,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2139 });2220 });
2140 opt_ctx.store(&node.base);2221 opt_ctx.store(&node.base);
21412222
2142 // Treat '**' token as two derefs2223 // Treat '**' token as two pointer types
2143 if (token_ptr.id == Token.Id.AsteriskAsterisk) {2224 if (token_ptr.id == Token.Id.AsteriskAsterisk) {
2144 const child = try arena.construct(ast.Node.PrefixOp{2225 const child = try arena.construct(ast.Node.PrefixOp{
2145 .base = ast.Node{ .id = ast.Node.Id.PrefixOp },2226 .base = ast.Node{ .id = ast.Node.Id.PrefixOp },
...@@ -2152,8 +2233,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2152,8 +2233,8 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2152 }2233 }
21532234
2154 stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &node.rhs } }) catch unreachable;2235 stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &node.rhs } }) catch unreachable;
2155 if (node.op == ast.Node.PrefixOp.Op.AddrOf) {2236 if (node.op == ast.Node.PrefixOp.Op.PtrType) {
2156 try stack.append(State{ .AddrOfModifiers = &node.op.AddrOf });2237 try stack.append(State{ .PtrTypeModifiers = &node.op.PtrType });
2157 }2238 }
2158 continue;2239 continue;
2159 } else {2240 } else {
...@@ -2171,10 +2252,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2171,10 +2252,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2171 .allocator_type = null,2252 .allocator_type = null,
2172 .rangle_bracket = null,2253 .rangle_bracket = null,
2173 });2254 });
2174 stack.append(State{ .AsyncEnd = AsyncEndCtx{2255 stack.append(State{
2175 .ctx = opt_ctx,2256 .AsyncEnd = AsyncEndCtx{
2176 .attribute = async_node,2257 .ctx = opt_ctx,
2177 } }) catch unreachable;2258 .attribute = async_node,
2259 },
2260 }) catch unreachable;
2178 try stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() });2261 try stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() });
2179 try stack.append(State{ .PrimaryExpression = opt_ctx.toRequired() });2262 try stack.append(State{ .PrimaryExpression = opt_ctx.toRequired() });
2180 try stack.append(State{ .AsyncAllocator = async_node });2263 try stack.append(State{ .AsyncAllocator = async_node });
...@@ -2197,20 +2280,24 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2197,20 +2280,24 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2197 const node = try arena.construct(ast.Node.SuffixOp{2280 const node = try arena.construct(ast.Node.SuffixOp{
2198 .base = ast.Node{ .id = ast.Node.Id.SuffixOp },2281 .base = ast.Node{ .id = ast.Node.Id.SuffixOp },
2199 .lhs = lhs,2282 .lhs = lhs,
2200 .op = ast.Node.SuffixOp.Op{ .Call = ast.Node.SuffixOp.Op.Call{2283 .op = ast.Node.SuffixOp.Op{
2201 .params = ast.Node.SuffixOp.Op.Call.ParamList.init(arena),2284 .Call = ast.Node.SuffixOp.Op.Call{
2202 .async_attr = null,2285 .params = ast.Node.SuffixOp.Op.Call.ParamList.init(arena),
2203 } },2286 .async_attr = null,
2287 },
2288 },
2204 .rtoken = undefined,2289 .rtoken = undefined,
2205 });2290 });
2206 opt_ctx.store(&node.base);2291 opt_ctx.store(&node.base);
22072292
2208 stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable;2293 stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable;
2209 try stack.append(State{ .ExprListItemOrEnd = ExprListCtx{2294 try stack.append(State{
2210 .list = &node.op.Call.params,2295 .ExprListItemOrEnd = ExprListCtx{
2211 .end = Token.Id.RParen,2296 .list = &node.op.Call.params,
2212 .ptr = &node.rtoken,2297 .end = Token.Id.RParen,
2213 } });2298 .ptr = &node.rtoken,
2299 },
2300 });
2214 continue;2301 continue;
2215 },2302 },
2216 Token.Id.LBracket => {2303 Token.Id.LBracket => {
...@@ -2278,8 +2365,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2278,8 +2365,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2278 _ = try createToCtxLiteral(arena, opt_ctx, ast.Node.UndefinedLiteral, token.index);2365 _ = try createToCtxLiteral(arena, opt_ctx, ast.Node.UndefinedLiteral, token.index);
2279 continue;2366 continue;
2280 },2367 },
2281 Token.Id.Keyword_true,2368 Token.Id.Keyword_true, Token.Id.Keyword_false => {
2282 Token.Id.Keyword_false => {
2283 _ = try createToCtxLiteral(arena, opt_ctx, ast.Node.BoolLiteral, token.index);2369 _ = try createToCtxLiteral(arena, opt_ctx, ast.Node.BoolLiteral, token.index);
2284 continue;2370 continue;
2285 },2371 },
...@@ -2321,8 +2407,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2321,8 +2407,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2321 try stack.append(State{ .Expression = OptionalCtx{ .Required = return_type_ptr } });2407 try stack.append(State{ .Expression = OptionalCtx{ .Required = return_type_ptr } });
2322 continue;2408 continue;
2323 },2409 },
2324 Token.Id.StringLiteral,2410 Token.Id.StringLiteral, Token.Id.MultilineStringLiteralLine => {
2325 Token.Id.MultilineStringLiteralLine => {
2326 opt_ctx.store((try parseStringLiteral(arena, &tok_it, token.ptr, token.index, &tree)) ?? unreachable);2411 opt_ctx.store((try parseStringLiteral(arena, &tok_it, token.ptr, token.index, &tree)) ?? unreachable);
2327 continue;2412 continue;
2328 },2413 },
...@@ -2335,10 +2420,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2335,10 +2420,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2335 });2420 });
2336 opt_ctx.store(&node.base);2421 opt_ctx.store(&node.base);
23372422
2338 stack.append(State{ .ExpectTokenSave = ExpectTokenSave{2423 stack.append(State{
2339 .id = Token.Id.RParen,2424 .ExpectTokenSave = ExpectTokenSave{
2340 .ptr = &node.rparen,2425 .id = Token.Id.RParen,
2341 } }) catch unreachable;2426 .ptr = &node.rparen,
2427 },
2428 }) catch unreachable;
2342 try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } });2429 try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } });
2343 continue;2430 continue;
2344 },2431 },
...@@ -2351,11 +2438,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2351,11 +2438,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2351 });2438 });
2352 opt_ctx.store(&node.base);2439 opt_ctx.store(&node.base);
23532440
2354 stack.append(State{ .ExprListItemOrEnd = ExprListCtx{2441 stack.append(State{
2355 .list = &node.params,2442 .ExprListItemOrEnd = ExprListCtx{
2356 .end = Token.Id.RParen,2443 .list = &node.params,
2357 .ptr = &node.rparen_token,2444 .end = Token.Id.RParen,
2358 } }) catch unreachable;2445 .ptr = &node.rparen_token,
2446 },
2447 }) catch unreachable;
2359 try stack.append(State{ .ExpectToken = Token.Id.LParen });2448 try stack.append(State{ .ExpectToken = Token.Id.LParen });
2360 continue;2449 continue;
2361 },2450 },
...@@ -2372,42 +2461,50 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2372,42 +2461,50 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2372 continue;2461 continue;
2373 },2462 },
2374 Token.Id.Keyword_error => {2463 Token.Id.Keyword_error => {
2375 stack.append(State{ .ErrorTypeOrSetDecl = ErrorTypeOrSetDeclCtx{2464 stack.append(State{
2376 .error_token = token.index,2465 .ErrorTypeOrSetDecl = ErrorTypeOrSetDeclCtx{
2377 .opt_ctx = opt_ctx,2466 .error_token = token.index,
2378 } }) catch unreachable;2467 .opt_ctx = opt_ctx,
2468 },
2469 }) catch unreachable;
2379 continue;2470 continue;
2380 },2471 },
2381 Token.Id.Keyword_packed => {2472 Token.Id.Keyword_packed => {
2382 stack.append(State{ .ContainerKind = ContainerKindCtx{2473 stack.append(State{
2383 .opt_ctx = opt_ctx,2474 .ContainerKind = ContainerKindCtx{
2384 .layout_token = token.index,2475 .opt_ctx = opt_ctx,
2385 } }) catch unreachable;2476 .layout_token = token.index,
2477 },
2478 }) catch unreachable;
2386 continue;2479 continue;
2387 },2480 },
2388 Token.Id.Keyword_extern => {2481 Token.Id.Keyword_extern => {
2389 stack.append(State{ .ExternType = ExternTypeCtx{2482 stack.append(State{
2390 .opt_ctx = opt_ctx,2483 .ExternType = ExternTypeCtx{
2391 .extern_token = token.index,2484 .opt_ctx = opt_ctx,
2392 .comments = null,2485 .extern_token = token.index,
2393 } }) catch unreachable;2486 .comments = null,
2487 },
2488 }) catch unreachable;
2394 continue;2489 continue;
2395 },2490 },
2396 Token.Id.Keyword_struct,2491 Token.Id.Keyword_struct, Token.Id.Keyword_union, Token.Id.Keyword_enum => {
2397 Token.Id.Keyword_union,
2398 Token.Id.Keyword_enum => {
2399 prevToken(&tok_it, &tree);2492 prevToken(&tok_it, &tree);
2400 stack.append(State{ .ContainerKind = ContainerKindCtx{2493 stack.append(State{
2401 .opt_ctx = opt_ctx,2494 .ContainerKind = ContainerKindCtx{
2402 .layout_token = null,2495 .opt_ctx = opt_ctx,
2403 } }) catch unreachable;2496 .layout_token = null,
2497 },
2498 }) catch unreachable;
2404 continue;2499 continue;
2405 },2500 },
2406 Token.Id.Identifier => {2501 Token.Id.Identifier => {
2407 stack.append(State{ .MaybeLabeledExpression = MaybeLabeledExpressionCtx{2502 stack.append(State{
2408 .label = token.index,2503 .MaybeLabeledExpression = MaybeLabeledExpressionCtx{
2409 .opt_ctx = opt_ctx,2504 .label = token.index,
2410 } }) catch unreachable;2505 .opt_ctx = opt_ctx,
2506 },
2507 }) catch unreachable;
2411 continue;2508 continue;
2412 },2509 },
2413 Token.Id.Keyword_fn => {2510 Token.Id.Keyword_fn => {
...@@ -2431,8 +2528,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2431,8 +2528,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2431 stack.append(State{ .FnProto = fn_proto }) catch unreachable;2528 stack.append(State{ .FnProto = fn_proto }) catch unreachable;
2432 continue;2529 continue;
2433 },2530 },
2434 Token.Id.Keyword_nakedcc,2531 Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc => {
2435 Token.Id.Keyword_stdcallcc => {
2436 const fn_proto = try arena.construct(ast.Node.FnProto{2532 const fn_proto = try arena.construct(ast.Node.FnProto{
2437 .base = ast.Node{ .id = ast.Node.Id.FnProto },2533 .base = ast.Node{ .id = ast.Node.Id.FnProto },
2438 .doc_comments = null,2534 .doc_comments = null,
...@@ -2451,10 +2547,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2451,10 +2547,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2451 });2547 });
2452 opt_ctx.store(&fn_proto.base);2548 opt_ctx.store(&fn_proto.base);
2453 stack.append(State{ .FnProto = fn_proto }) catch unreachable;2549 stack.append(State{ .FnProto = fn_proto }) catch unreachable;
2454 try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{2550 try stack.append(State{
2455 .id = Token.Id.Keyword_fn,2551 .ExpectTokenSave = ExpectTokenSave{
2456 .ptr = &fn_proto.fn_token,2552 .id = Token.Id.Keyword_fn,
2457 } });2553 .ptr = &fn_proto.fn_token,
2554 },
2555 });
2458 continue;2556 continue;
2459 },2557 },
2460 Token.Id.Keyword_asm => {2558 Token.Id.Keyword_asm => {
...@@ -2470,10 +2568,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2470,10 +2568,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2470 });2568 });
2471 opt_ctx.store(&node.base);2569 opt_ctx.store(&node.base);
24722570
2473 stack.append(State{ .ExpectTokenSave = ExpectTokenSave{2571 stack.append(State{
2474 .id = Token.Id.RParen,2572 .ExpectTokenSave = ExpectTokenSave{
2475 .ptr = &node.rparen,2573 .id = Token.Id.RParen,
2476 } }) catch unreachable;2574 .ptr = &node.rparen,
2575 },
2576 }) catch unreachable;
2477 try stack.append(State{ .AsmClobberItems = &node.clobbers });2577 try stack.append(State{ .AsmClobberItems = &node.clobbers });
2478 try stack.append(State{ .IfToken = Token.Id.Colon });2578 try stack.append(State{ .IfToken = Token.Id.Colon });
2479 try stack.append(State{ .AsmInputItems = &node.inputs });2579 try stack.append(State{ .AsmInputItems = &node.inputs });
...@@ -2482,17 +2582,21 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2482,17 +2582,21 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2482 try stack.append(State{ .IfToken = Token.Id.Colon });2582 try stack.append(State{ .IfToken = Token.Id.Colon });
2483 try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.template } });2583 try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.template } });
2484 try stack.append(State{ .ExpectToken = Token.Id.LParen });2584 try stack.append(State{ .ExpectToken = Token.Id.LParen });
2485 try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{2585 try stack.append(State{
2486 .id = Token.Id.Keyword_volatile,2586 .OptionalTokenSave = OptionalTokenSave{
2487 .ptr = &node.volatile_token,2587 .id = Token.Id.Keyword_volatile,
2488 } });2588 .ptr = &node.volatile_token,
2589 },
2590 });
2489 },2591 },
2490 Token.Id.Keyword_inline => {2592 Token.Id.Keyword_inline => {
2491 stack.append(State{ .Inline = InlineCtx{2593 stack.append(State{
2492 .label = null,2594 .Inline = InlineCtx{
2493 .inline_token = token.index,2595 .label = null,
2494 .opt_ctx = opt_ctx,2596 .inline_token = token.index,
2495 } }) catch unreachable;2597 .opt_ctx = opt_ctx,
2598 },
2599 }) catch unreachable;
2496 continue;2600 continue;
2497 },2601 },
2498 else => {2602 else => {
...@@ -2522,10 +2626,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2522,10 +2626,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2522 });2626 });
2523 ctx.opt_ctx.store(&node.base);2627 ctx.opt_ctx.store(&node.base);
25242628
2525 stack.append(State{ .ErrorTagListItemOrEnd = ListSave(@typeOf(node.decls)){2629 stack.append(State{
2526 .list = &node.decls,2630 .ErrorTagListItemOrEnd = ListSave(@typeOf(node.decls)){
2527 .ptr = &node.rbrace_token,2631 .list = &node.decls,
2528 } }) catch unreachable;2632 .ptr = &node.rbrace_token,
2633 },
2634 }) catch unreachable;
2529 continue;2635 continue;
2530 },2636 },
2531 State.StringLiteral => |opt_ctx| {2637 State.StringLiteral => |opt_ctx| {
...@@ -2553,10 +2659,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2553,10 +2659,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2553 const token = nextToken(&tok_it, &tree);2659 const token = nextToken(&tok_it, &tree);
2554 const token_index = token.index;2660 const token_index = token.index;
2555 const token_ptr = token.ptr;2661 const token_ptr = token.ptr;
2556 ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{2662 ((try tree.errors.addOne())).* = Error{
2557 .token = token_index,2663 .ExpectedToken = Error.ExpectedToken{
2558 .expected_id = Token.Id.Identifier,2664 .token = token_index,
2559 } };2665 .expected_id = Token.Id.Identifier,
2666 },
2667 };
2560 return tree;2668 return tree;
2561 }2669 }
2562 },2670 },
...@@ -2567,10 +2675,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2567,10 +2675,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2567 const ident_token_index = ident_token.index;2675 const ident_token_index = ident_token.index;
2568 const ident_token_ptr = ident_token.ptr;2676 const ident_token_ptr = ident_token.ptr;
2569 if (ident_token_ptr.id != Token.Id.Identifier) {2677 if (ident_token_ptr.id != Token.Id.Identifier) {
2570 ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{2678 ((try tree.errors.addOne())).* = Error{
2571 .token = ident_token_index,2679 .ExpectedToken = Error.ExpectedToken{
2572 .expected_id = Token.Id.Identifier,2680 .token = ident_token_index,
2573 } };2681 .expected_id = Token.Id.Identifier,
2682 },
2683 };
2574 return tree;2684 return tree;
2575 }2685 }
25762686
...@@ -2588,10 +2698,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2588,10 +2698,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2588 const token_index = token.index;2698 const token_index = token.index;
2589 const token_ptr = token.ptr;2699 const token_ptr = token.ptr;
2590 if (token_ptr.id != token_id) {2700 if (token_ptr.id != token_id) {
2591 ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{2701 ((try tree.errors.addOne())).* = Error{
2592 .token = token_index,2702 .ExpectedToken = Error.ExpectedToken{
2593 .expected_id = token_id,2703 .token = token_index,
2594 } };2704 .expected_id = token_id,
2705 },
2706 };
2595 return tree;2707 return tree;
2596 }2708 }
2597 continue;2709 continue;
...@@ -2601,10 +2713,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2601,10 +2713,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2601 const token_index = token.index;2713 const token_index = token.index;
2602 const token_ptr = token.ptr;2714 const token_ptr = token.ptr;
2603 if (token_ptr.id != expect_token_save.id) {2715 if (token_ptr.id != expect_token_save.id) {
2604 ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{2716 ((try tree.errors.addOne())).* = Error{
2605 .token = token_index,2717 .ExpectedToken = Error.ExpectedToken{
2606 .expected_id = expect_token_save.id,2718 .token = token_index,
2607 } };2719 .expected_id = expect_token_save.id,
2720 },
2721 };
2608 return tree;2722 return tree;
2609 }2723 }
2610 expect_token_save.ptr.* = token_index;2724 expect_token_save.ptr.* = token_index;
...@@ -2640,16 +2754,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {...@@ -2640,16 +2754,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
2640}2754}
26412755
2642const AnnotatedToken = struct {2756const AnnotatedToken = struct {
2643 ptr: &Token,2757 ptr: *Token,
2644 index: TokenIndex,2758 index: TokenIndex,
2645};2759};
26462760
2647const TopLevelDeclCtx = struct {2761const TopLevelDeclCtx = struct {
2648 decls: &ast.Node.Root.DeclList,2762 decls: *ast.Node.Root.DeclList,
2649 visib_token: ?TokenIndex,2763 visib_token: ?TokenIndex,
2650 extern_export_inline_token: ?AnnotatedToken,2764 extern_export_inline_token: ?AnnotatedToken,
2651 lib_name: ?&ast.Node,2765 lib_name: ?*ast.Node,
2652 comments: ?&ast.Node.DocComment,2766 comments: ?*ast.Node.DocComment,
2653};2767};
26542768
2655const VarDeclCtx = struct {2769const VarDeclCtx = struct {
...@@ -2657,21 +2771,21 @@ const VarDeclCtx = struct {...@@ -2657,21 +2771,21 @@ const VarDeclCtx = struct {
2657 visib_token: ?TokenIndex,2771 visib_token: ?TokenIndex,
2658 comptime_token: ?TokenIndex,2772 comptime_token: ?TokenIndex,
2659 extern_export_token: ?TokenIndex,2773 extern_export_token: ?TokenIndex,
2660 lib_name: ?&ast.Node,2774 lib_name: ?*ast.Node,
2661 list: &ast.Node.Root.DeclList,2775 list: *ast.Node.Root.DeclList,
2662 comments: ?&ast.Node.DocComment,2776 comments: ?*ast.Node.DocComment,
2663};2777};
26642778
2665const TopLevelExternOrFieldCtx = struct {2779const TopLevelExternOrFieldCtx = struct {
2666 visib_token: TokenIndex,2780 visib_token: TokenIndex,
2667 container_decl: &ast.Node.ContainerDecl,2781 container_decl: *ast.Node.ContainerDecl,
2668 comments: ?&ast.Node.DocComment,2782 comments: ?*ast.Node.DocComment,
2669};2783};
26702784
2671const ExternTypeCtx = struct {2785const ExternTypeCtx = struct {
2672 opt_ctx: OptionalCtx,2786 opt_ctx: OptionalCtx,
2673 extern_token: TokenIndex,2787 extern_token: TokenIndex,
2674 comments: ?&ast.Node.DocComment,2788 comments: ?*ast.Node.DocComment,
2675};2789};
26762790
2677const ContainerKindCtx = struct {2791const ContainerKindCtx = struct {
...@@ -2681,24 +2795,24 @@ const ContainerKindCtx = struct {...@@ -2681,24 +2795,24 @@ const ContainerKindCtx = struct {
26812795
2682const ExpectTokenSave = struct {2796const ExpectTokenSave = struct {
2683 id: @TagType(Token.Id),2797 id: @TagType(Token.Id),
2684 ptr: &TokenIndex,2798 ptr: *TokenIndex,
2685};2799};
26862800
2687const OptionalTokenSave = struct {2801const OptionalTokenSave = struct {
2688 id: @TagType(Token.Id),2802 id: @TagType(Token.Id),
2689 ptr: &?TokenIndex,2803 ptr: *?TokenIndex,
2690};2804};
26912805
2692const ExprListCtx = struct {2806const ExprListCtx = struct {
2693 list: &ast.Node.SuffixOp.Op.InitList,2807 list: *ast.Node.SuffixOp.Op.InitList,
2694 end: Token.Id,2808 end: Token.Id,
2695 ptr: &TokenIndex,2809 ptr: *TokenIndex,
2696};2810};
26972811
2698fn ListSave(comptime List: type) type {2812fn ListSave(comptime List: type) type {
2699 return struct {2813 return struct {
2700 list: &List,2814 list: *List,
2701 ptr: &TokenIndex,2815 ptr: *TokenIndex,
2702 };2816 };
2703}2817}
27042818
...@@ -2727,7 +2841,7 @@ const LoopCtx = struct {...@@ -2727,7 +2841,7 @@ const LoopCtx = struct {
27272841
2728const AsyncEndCtx = struct {2842const AsyncEndCtx = struct {
2729 ctx: OptionalCtx,2843 ctx: OptionalCtx,
2730 attribute: &ast.Node.AsyncAttribute,2844 attribute: *ast.Node.AsyncAttribute,
2731};2845};
27322846
2733const ErrorTypeOrSetDeclCtx = struct {2847const ErrorTypeOrSetDeclCtx = struct {
...@@ -2736,21 +2850,21 @@ const ErrorTypeOrSetDeclCtx = struct {...@@ -2736,21 +2850,21 @@ const ErrorTypeOrSetDeclCtx = struct {
2736};2850};
27372851
2738const ParamDeclEndCtx = struct {2852const ParamDeclEndCtx = struct {
2739 fn_proto: &ast.Node.FnProto,2853 fn_proto: *ast.Node.FnProto,
2740 param_decl: &ast.Node.ParamDecl,2854 param_decl: *ast.Node.ParamDecl,
2741};2855};
27422856
2743const ComptimeStatementCtx = struct {2857const ComptimeStatementCtx = struct {
2744 comptime_token: TokenIndex,2858 comptime_token: TokenIndex,
2745 block: &ast.Node.Block,2859 block: *ast.Node.Block,
2746};2860};
27472861
2748const OptionalCtx = union(enum) {2862const OptionalCtx = union(enum) {
2749 Optional: &?&ast.Node,2863 Optional: *?*ast.Node,
2750 RequiredNull: &?&ast.Node,2864 RequiredNull: *?*ast.Node,
2751 Required: &&ast.Node,2865 Required: **ast.Node,
27522866
2753 pub fn store(self: &const OptionalCtx, value: &ast.Node) void {2867 pub fn store(self: *const OptionalCtx, value: *ast.Node) void {
2754 switch (self.*) {2868 switch (self.*) {
2755 OptionalCtx.Optional => |ptr| ptr.* = value,2869 OptionalCtx.Optional => |ptr| ptr.* = value,
2756 OptionalCtx.RequiredNull => |ptr| ptr.* = value,2870 OptionalCtx.RequiredNull => |ptr| ptr.* = value,
...@@ -2758,7 +2872,7 @@ const OptionalCtx = union(enum) {...@@ -2758,7 +2872,7 @@ const OptionalCtx = union(enum) {
2758 }2872 }
2759 }2873 }
27602874
2761 pub fn get(self: &const OptionalCtx) ?&ast.Node {2875 pub fn get(self: *const OptionalCtx) ?*ast.Node {
2762 switch (self.*) {2876 switch (self.*) {
2763 OptionalCtx.Optional => |ptr| return ptr.*,2877 OptionalCtx.Optional => |ptr| return ptr.*,
2764 OptionalCtx.RequiredNull => |ptr| return ??ptr.*,2878 OptionalCtx.RequiredNull => |ptr| return ??ptr.*,
...@@ -2766,7 +2880,7 @@ const OptionalCtx = union(enum) {...@@ -2766,7 +2880,7 @@ const OptionalCtx = union(enum) {
2766 }2880 }
2767 }2881 }
27682882
2769 pub fn toRequired(self: &const OptionalCtx) OptionalCtx {2883 pub fn toRequired(self: *const OptionalCtx) OptionalCtx {
2770 switch (self.*) {2884 switch (self.*) {
2771 OptionalCtx.Optional => |ptr| {2885 OptionalCtx.Optional => |ptr| {
2772 return OptionalCtx{ .RequiredNull = ptr };2886 return OptionalCtx{ .RequiredNull = ptr };
...@@ -2778,8 +2892,8 @@ const OptionalCtx = union(enum) {...@@ -2778,8 +2892,8 @@ const OptionalCtx = union(enum) {
2778};2892};
27792893
2780const AddCommentsCtx = struct {2894const AddCommentsCtx = struct {
2781 node_ptr: &&ast.Node,2895 node_ptr: **ast.Node,
2782 comments: ?&ast.Node.DocComment,2896 comments: ?*ast.Node.DocComment,
2783};2897};
27842898
2785const State = union(enum) {2899const State = union(enum) {
...@@ -2790,67 +2904,67 @@ const State = union(enum) {...@@ -2790,67 +2904,67 @@ const State = union(enum) {
2790 TopLevelExternOrField: TopLevelExternOrFieldCtx,2904 TopLevelExternOrField: TopLevelExternOrFieldCtx,
27912905
2792 ContainerKind: ContainerKindCtx,2906 ContainerKind: ContainerKindCtx,
2793 ContainerInitArgStart: &ast.Node.ContainerDecl,2907 ContainerInitArgStart: *ast.Node.ContainerDecl,
2794 ContainerInitArg: &ast.Node.ContainerDecl,2908 ContainerInitArg: *ast.Node.ContainerDecl,
2795 ContainerDecl: &ast.Node.ContainerDecl,2909 ContainerDecl: *ast.Node.ContainerDecl,
27962910
2797 VarDecl: VarDeclCtx,2911 VarDecl: VarDeclCtx,
2798 VarDeclAlign: &ast.Node.VarDecl,2912 VarDeclAlign: *ast.Node.VarDecl,
2799 VarDeclEq: &ast.Node.VarDecl,2913 VarDeclEq: *ast.Node.VarDecl,
2800 VarDeclSemiColon: &ast.Node.VarDecl,2914 VarDeclSemiColon: *ast.Node.VarDecl,
28012915
2802 FnDef: &ast.Node.FnProto,2916 FnDef: *ast.Node.FnProto,
2803 FnProto: &ast.Node.FnProto,2917 FnProto: *ast.Node.FnProto,
2804 FnProtoAlign: &ast.Node.FnProto,2918 FnProtoAlign: *ast.Node.FnProto,
2805 FnProtoReturnType: &ast.Node.FnProto,2919 FnProtoReturnType: *ast.Node.FnProto,
28062920
2807 ParamDecl: &ast.Node.FnProto,2921 ParamDecl: *ast.Node.FnProto,
2808 ParamDeclAliasOrComptime: &ast.Node.ParamDecl,2922 ParamDeclAliasOrComptime: *ast.Node.ParamDecl,
2809 ParamDeclName: &ast.Node.ParamDecl,2923 ParamDeclName: *ast.Node.ParamDecl,
2810 ParamDeclEnd: ParamDeclEndCtx,2924 ParamDeclEnd: ParamDeclEndCtx,
2811 ParamDeclComma: &ast.Node.FnProto,2925 ParamDeclComma: *ast.Node.FnProto,
28122926
2813 MaybeLabeledExpression: MaybeLabeledExpressionCtx,2927 MaybeLabeledExpression: MaybeLabeledExpressionCtx,
2814 LabeledExpression: LabelCtx,2928 LabeledExpression: LabelCtx,
2815 Inline: InlineCtx,2929 Inline: InlineCtx,
2816 While: LoopCtx,2930 While: LoopCtx,
2817 WhileContinueExpr: &?&ast.Node,2931 WhileContinueExpr: *?*ast.Node,
2818 For: LoopCtx,2932 For: LoopCtx,
2819 Else: &?&ast.Node.Else,2933 Else: *?*ast.Node.Else,
28202934
2821 Block: &ast.Node.Block,2935 Block: *ast.Node.Block,
2822 Statement: &ast.Node.Block,2936 Statement: *ast.Node.Block,
2823 ComptimeStatement: ComptimeStatementCtx,2937 ComptimeStatement: ComptimeStatementCtx,
2824 Semicolon: &&ast.Node,2938 Semicolon: **ast.Node,
28252939
2826 AsmOutputItems: &ast.Node.Asm.OutputList,2940 AsmOutputItems: *ast.Node.Asm.OutputList,
2827 AsmOutputReturnOrType: &ast.Node.AsmOutput,2941 AsmOutputReturnOrType: *ast.Node.AsmOutput,
2828 AsmInputItems: &ast.Node.Asm.InputList,2942 AsmInputItems: *ast.Node.Asm.InputList,
2829 AsmClobberItems: &ast.Node.Asm.ClobberList,2943 AsmClobberItems: *ast.Node.Asm.ClobberList,
28302944
2831 ExprListItemOrEnd: ExprListCtx,2945 ExprListItemOrEnd: ExprListCtx,
2832 ExprListCommaOrEnd: ExprListCtx,2946 ExprListCommaOrEnd: ExprListCtx,
2833 FieldInitListItemOrEnd: ListSave(ast.Node.SuffixOp.Op.InitList),2947 FieldInitListItemOrEnd: ListSave(ast.Node.SuffixOp.Op.InitList),
2834 FieldInitListCommaOrEnd: ListSave(ast.Node.SuffixOp.Op.InitList),2948 FieldInitListCommaOrEnd: ListSave(ast.Node.SuffixOp.Op.InitList),
2835 FieldListCommaOrEnd: &ast.Node.ContainerDecl,2949 FieldListCommaOrEnd: *ast.Node.ContainerDecl,
2836 FieldInitValue: OptionalCtx,2950 FieldInitValue: OptionalCtx,
2837 ErrorTagListItemOrEnd: ListSave(ast.Node.ErrorSetDecl.DeclList),2951 ErrorTagListItemOrEnd: ListSave(ast.Node.ErrorSetDecl.DeclList),
2838 ErrorTagListCommaOrEnd: ListSave(ast.Node.ErrorSetDecl.DeclList),2952 ErrorTagListCommaOrEnd: ListSave(ast.Node.ErrorSetDecl.DeclList),
2839 SwitchCaseOrEnd: ListSave(ast.Node.Switch.CaseList),2953 SwitchCaseOrEnd: ListSave(ast.Node.Switch.CaseList),
2840 SwitchCaseCommaOrEnd: ListSave(ast.Node.Switch.CaseList),2954 SwitchCaseCommaOrEnd: ListSave(ast.Node.Switch.CaseList),
2841 SwitchCaseFirstItem: &ast.Node.SwitchCase,2955 SwitchCaseFirstItem: *ast.Node.SwitchCase,
2842 SwitchCaseItemCommaOrEnd: &ast.Node.SwitchCase,2956 SwitchCaseItemCommaOrEnd: *ast.Node.SwitchCase,
2843 SwitchCaseItemOrEnd: &ast.Node.SwitchCase,2957 SwitchCaseItemOrEnd: *ast.Node.SwitchCase,
28442958
2845 SuspendBody: &ast.Node.Suspend,2959 SuspendBody: *ast.Node.Suspend,
2846 AsyncAllocator: &ast.Node.AsyncAttribute,2960 AsyncAllocator: *ast.Node.AsyncAttribute,
2847 AsyncEnd: AsyncEndCtx,2961 AsyncEnd: AsyncEndCtx,
28482962
2849 ExternType: ExternTypeCtx,2963 ExternType: ExternTypeCtx,
2850 SliceOrArrayAccess: &ast.Node.SuffixOp,2964 SliceOrArrayAccess: *ast.Node.SuffixOp,
2851 SliceOrArrayType: &ast.Node.PrefixOp,2965 SliceOrArrayType: *ast.Node.PrefixOp,
2852 AddrOfModifiers: &ast.Node.PrefixOp.AddrOfInfo,2966 PtrTypeModifiers: *ast.Node.PrefixOp.PtrInfo,
2853 AlignBitRange: &ast.Node.PrefixOp.AddrOfInfo.Align,2967 AlignBitRange: *ast.Node.PrefixOp.PtrInfo.Align,
28542968
2855 Payload: OptionalCtx,2969 Payload: OptionalCtx,
2856 PointerPayload: OptionalCtx,2970 PointerPayload: OptionalCtx,
...@@ -2893,7 +3007,7 @@ const State = union(enum) {...@@ -2893,7 +3007,7 @@ const State = union(enum) {
2893 ErrorTypeOrSetDecl: ErrorTypeOrSetDeclCtx,3007 ErrorTypeOrSetDecl: ErrorTypeOrSetDeclCtx,
2894 StringLiteral: OptionalCtx,3008 StringLiteral: OptionalCtx,
2895 Identifier: OptionalCtx,3009 Identifier: OptionalCtx,
2896 ErrorTag: &&ast.Node,3010 ErrorTag: **ast.Node,
28973011
2898 IfToken: @TagType(Token.Id),3012 IfToken: @TagType(Token.Id),
2899 IfTokenSave: ExpectTokenSave,3013 IfTokenSave: ExpectTokenSave,
...@@ -2902,7 +3016,7 @@ const State = union(enum) {...@@ -2902,7 +3016,7 @@ const State = union(enum) {
2902 OptionalTokenSave: OptionalTokenSave,3016 OptionalTokenSave: OptionalTokenSave,
2903};3017};
29043018
2905fn pushDocComment(arena: &mem.Allocator, line_comment: TokenIndex, result: &?&ast.Node.DocComment) !void {3019fn pushDocComment(arena: *mem.Allocator, line_comment: TokenIndex, result: *?*ast.Node.DocComment) !void {
2906 const node = blk: {3020 const node = blk: {
2907 if (result.*) |comment_node| {3021 if (result.*) |comment_node| {
2908 break :blk comment_node;3022 break :blk comment_node;
...@@ -2918,8 +3032,8 @@ fn pushDocComment(arena: &mem.Allocator, line_comment: TokenIndex, result: &?&as...@@ -2918,8 +3032,8 @@ fn pushDocComment(arena: &mem.Allocator, line_comment: TokenIndex, result: &?&as
2918 try node.lines.push(line_comment);3032 try node.lines.push(line_comment);
2919}3033}
29203034
2921fn eatDocComments(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) !?&ast.Node.DocComment {3035fn eatDocComments(arena: *mem.Allocator, tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) !?*ast.Node.DocComment {
2922 var result: ?&ast.Node.DocComment = null;3036 var result: ?*ast.Node.DocComment = null;
2923 while (true) {3037 while (true) {
2924 if (eatToken(tok_it, tree, Token.Id.DocComment)) |line_comment| {3038 if (eatToken(tok_it, tree, Token.Id.DocComment)) |line_comment| {
2925 try pushDocComment(arena, line_comment, &result);3039 try pushDocComment(arena, line_comment, &result);
...@@ -2930,7 +3044,7 @@ fn eatDocComments(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, t...@@ -2930,7 +3044,7 @@ fn eatDocComments(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, t
2930 return result;3044 return result;
2931}3045}
29323046
2933fn parseStringLiteral(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, token_ptr: &const Token, token_index: TokenIndex, tree: &ast.Tree) !?&ast.Node {3047fn parseStringLiteral(arena: *mem.Allocator, tok_it: *ast.Tree.TokenList.Iterator, token_ptr: *const Token, token_index: TokenIndex, tree: *ast.Tree) !?*ast.Node {
2934 switch (token_ptr.id) {3048 switch (token_ptr.id) {
2935 Token.Id.StringLiteral => {3049 Token.Id.StringLiteral => {
2936 return &(try createLiteral(arena, ast.Node.StringLiteral, token_index)).base;3050 return &(try createLiteral(arena, ast.Node.StringLiteral, token_index)).base;
...@@ -2957,11 +3071,11 @@ fn parseStringLiteral(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterato...@@ -2957,11 +3071,11 @@ fn parseStringLiteral(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterato
2957 },3071 },
2958 // TODO: We shouldn't need a cast, but:3072 // TODO: We shouldn't need a cast, but:
2959 // zig: /home/jc/Documents/zig/src/ir.cpp:7962: TypeTableEntry* ir_resolve_peer_types(IrAnalyze*, AstNode*, IrInstruction**, size_t): Assertion `err_set_type != nullptr' failed.3073 // zig: /home/jc/Documents/zig/src/ir.cpp:7962: TypeTableEntry* ir_resolve_peer_types(IrAnalyze*, AstNode*, IrInstruction**, size_t): Assertion `err_set_type != nullptr' failed.
2960 else => return (?&ast.Node)(null),3074 else => return (?*ast.Node)(null),
2961 }3075 }
2962}3076}
29633077
2964fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &const OptionalCtx, token_ptr: &const Token, token_index: TokenIndex) !bool {3078fn parseBlockExpr(stack: *std.ArrayList(State), arena: *mem.Allocator, ctx: *const OptionalCtx, token_ptr: *const Token, token_index: TokenIndex) !bool {
2965 switch (token_ptr.id) {3079 switch (token_ptr.id) {
2966 Token.Id.Keyword_suspend => {3080 Token.Id.Keyword_suspend => {
2967 const node = try arena.construct(ast.Node.Suspend{3081 const node = try arena.construct(ast.Node.Suspend{
...@@ -2997,21 +3111,25 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con...@@ -2997,21 +3111,25 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con
2997 return true;3111 return true;
2998 },3112 },
2999 Token.Id.Keyword_while => {3113 Token.Id.Keyword_while => {
3000 stack.append(State{ .While = LoopCtx{3114 stack.append(State{
3001 .label = null,3115 .While = LoopCtx{
3002 .inline_token = null,3116 .label = null,
3003 .loop_token = token_index,3117 .inline_token = null,
3004 .opt_ctx = ctx.*,3118 .loop_token = token_index,
3005 } }) catch unreachable;3119 .opt_ctx = ctx.*,
3120 },
3121 }) catch unreachable;
3006 return true;3122 return true;
3007 },3123 },
3008 Token.Id.Keyword_for => {3124 Token.Id.Keyword_for => {
3009 stack.append(State{ .For = LoopCtx{3125 stack.append(State{
3010 .label = null,3126 .For = LoopCtx{
3011 .inline_token = null,3127 .label = null,
3012 .loop_token = token_index,3128 .inline_token = null,
3013 .opt_ctx = ctx.*,3129 .loop_token = token_index,
3014 } }) catch unreachable;3130 .opt_ctx = ctx.*,
3131 },
3132 }) catch unreachable;
3015 return true;3133 return true;
3016 },3134 },
3017 Token.Id.Keyword_switch => {3135 Token.Id.Keyword_switch => {
...@@ -3024,10 +3142,12 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con...@@ -3024,10 +3142,12 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con
3024 });3142 });
3025 ctx.store(&node.base);3143 ctx.store(&node.base);
30263144
3027 stack.append(State{ .SwitchCaseOrEnd = ListSave(@typeOf(node.cases)){3145 stack.append(State{
3028 .list = &node.cases,3146 .SwitchCaseOrEnd = ListSave(@typeOf(node.cases)){
3029 .ptr = &node.rbrace,3147 .list = &node.cases,
3030 } }) catch unreachable;3148 .ptr = &node.rbrace,
3149 },
3150 }) catch unreachable;
3031 try stack.append(State{ .ExpectToken = Token.Id.LBrace });3151 try stack.append(State{ .ExpectToken = Token.Id.LBrace });
3032 try stack.append(State{ .ExpectToken = Token.Id.RParen });3152 try stack.append(State{ .ExpectToken = Token.Id.RParen });
3033 try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } });3153 try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } });
...@@ -3069,7 +3189,7 @@ const ExpectCommaOrEndResult = union(enum) {...@@ -3069,7 +3189,7 @@ const ExpectCommaOrEndResult = union(enum) {
3069 parse_error: Error,3189 parse_error: Error,
3070};3190};
30713191
3072fn expectCommaOrEnd(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, end: @TagType(Token.Id)) ExpectCommaOrEndResult {3192fn expectCommaOrEnd(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree, end: @TagType(Token.Id)) ExpectCommaOrEndResult {
3073 const token = nextToken(tok_it, tree);3193 const token = nextToken(tok_it, tree);
3074 const token_index = token.index;3194 const token_index = token.index;
3075 const token_ptr = token.ptr;3195 const token_ptr = token.ptr;
...@@ -3080,15 +3200,19 @@ fn expectCommaOrEnd(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, end:...@@ -3080,15 +3200,19 @@ fn expectCommaOrEnd(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, end:
3080 return ExpectCommaOrEndResult{ .end_token = token_index };3200 return ExpectCommaOrEndResult{ .end_token = token_index };
3081 }3201 }
30823202
3083 return ExpectCommaOrEndResult{ .parse_error = Error{ .ExpectedCommaOrEnd = Error.ExpectedCommaOrEnd{3203 return ExpectCommaOrEndResult{
3084 .token = token_index,3204 .parse_error = Error{
3085 .end_id = end,3205 .ExpectedCommaOrEnd = Error.ExpectedCommaOrEnd{
3086 } } };3206 .token = token_index,
3207 .end_id = end,
3208 },
3209 },
3210 };
3087 },3211 },
3088 }3212 }
3089}3213}
30903214
3091fn tokenIdToAssignment(id: &const Token.Id) ?ast.Node.InfixOp.Op {3215fn tokenIdToAssignment(id: *const Token.Id) ?ast.Node.InfixOp.Op {
3092 // TODO: We have to cast all cases because of this:3216 // TODO: We have to cast all cases because of this:
3093 // error: expected type '?InfixOp', found '?@TagType(InfixOp)'3217 // error: expected type '?InfixOp', found '?@TagType(InfixOp)'
3094 return switch (id.*) {3218 return switch (id.*) {
...@@ -3167,13 +3291,14 @@ fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op {...@@ -3167,13 +3291,14 @@ fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op {
3167 Token.Id.Tilde => ast.Node.PrefixOp.Op{ .BitNot = void{} },3291 Token.Id.Tilde => ast.Node.PrefixOp.Op{ .BitNot = void{} },
3168 Token.Id.Minus => ast.Node.PrefixOp.Op{ .Negation = void{} },3292 Token.Id.Minus => ast.Node.PrefixOp.Op{ .Negation = void{} },
3169 Token.Id.MinusPercent => ast.Node.PrefixOp.Op{ .NegationWrap = void{} },3293 Token.Id.MinusPercent => ast.Node.PrefixOp.Op{ .NegationWrap = void{} },
3170 Token.Id.Asterisk,3294 Token.Id.Ampersand => ast.Node.PrefixOp.Op{ .AddressOf = void{} },
3171 Token.Id.AsteriskAsterisk => ast.Node.PrefixOp.Op{ .PointerType = void{} },3295 Token.Id.Asterisk, Token.Id.AsteriskAsterisk, Token.Id.BracketStarBracket => ast.Node.PrefixOp.Op{
3172 Token.Id.Ampersand => ast.Node.PrefixOp.Op{ .AddrOf = ast.Node.PrefixOp.AddrOfInfo{3296 .PtrType = ast.Node.PrefixOp.PtrInfo{
3173 .align_info = null,3297 .align_info = null,
3174 .const_token = null,3298 .const_token = null,
3175 .volatile_token = null,3299 .volatile_token = null,
3176 } },3300 },
3301 },
3177 Token.Id.QuestionMark => ast.Node.PrefixOp.Op{ .MaybeType = void{} },3302 Token.Id.QuestionMark => ast.Node.PrefixOp.Op{ .MaybeType = void{} },
3178 Token.Id.QuestionMarkQuestionMark => ast.Node.PrefixOp.Op{ .UnwrapMaybe = void{} },3303 Token.Id.QuestionMarkQuestionMark => ast.Node.PrefixOp.Op{ .UnwrapMaybe = void{} },
3179 Token.Id.Keyword_await => ast.Node.PrefixOp.Op{ .Await = void{} },3304 Token.Id.Keyword_await => ast.Node.PrefixOp.Op{ .Await = void{} },
...@@ -3182,21 +3307,21 @@ fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op {...@@ -3182,21 +3307,21 @@ fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op {
3182 };3307 };
3183}3308}
31843309
3185fn createLiteral(arena: &mem.Allocator, comptime T: type, token_index: TokenIndex) !&T {3310fn createLiteral(arena: *mem.Allocator, comptime T: type, token_index: TokenIndex) !*T {
3186 return arena.construct(T{3311 return arena.construct(T{
3187 .base = ast.Node{ .id = ast.Node.typeToId(T) },3312 .base = ast.Node{ .id = ast.Node.typeToId(T) },
3188 .token = token_index,3313 .token = token_index,
3189 });3314 });
3190}3315}
31913316
3192fn createToCtxLiteral(arena: &mem.Allocator, opt_ctx: &const OptionalCtx, comptime T: type, token_index: TokenIndex) !&T {3317fn createToCtxLiteral(arena: *mem.Allocator, opt_ctx: *const OptionalCtx, comptime T: type, token_index: TokenIndex) !*T {
3193 const node = try createLiteral(arena, T, token_index);3318 const node = try createLiteral(arena, T, token_index);
3194 opt_ctx.store(&node.base);3319 opt_ctx.store(&node.base);
31953320
3196 return node;3321 return node;
3197}3322}
31983323
3199fn eatToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, id: @TagType(Token.Id)) ?TokenIndex {3324fn eatToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree, id: @TagType(Token.Id)) ?TokenIndex {
3200 const token = ??tok_it.peek();3325 const token = ??tok_it.peek();
32013326
3202 if (token.id == id) {3327 if (token.id == id) {
...@@ -3206,7 +3331,7 @@ fn eatToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, id: @TagType(...@@ -3206,7 +3331,7 @@ fn eatToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, id: @TagType(
3206 return null;3331 return null;
3207}3332}
32083333
3209fn nextToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) AnnotatedToken {3334fn nextToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) AnnotatedToken {
3210 const result = AnnotatedToken{3335 const result = AnnotatedToken{
3211 .index = tok_it.index,3336 .index = tok_it.index,
3212 .ptr = ??tok_it.next(),3337 .ptr = ??tok_it.next(),
...@@ -3220,7 +3345,7 @@ fn nextToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) AnnotatedTok...@@ -3220,7 +3345,7 @@ fn nextToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) AnnotatedTok
3220 }3345 }
3221}3346}
32223347
3223fn prevToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) void {3348fn prevToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) void {
3224 while (true) {3349 while (true) {
3225 const prev_tok = tok_it.prev() ?? return;3350 const prev_tok = tok_it.prev() ?? return;
3226 if (prev_tok.id == Token.Id.LineComment) continue;3351 if (prev_tok.id == Token.Id.LineComment) continue;
std/zig/parser_test.zig+95-43
...@@ -1,3 +1,43 @@...@@ -1,3 +1,43 @@
1test "zig fmt: pointer of unknown length" {
2 try testCanonical(
3 \\fn foo(ptr: [*]u8) void {}
4 \\
5 );
6}
7
8test "zig fmt: spaces around slice operator" {
9 try testCanonical(
10 \\var a = b[c..d];
11 \\var a = b[c + 1 .. d];
12 \\var a = b[c + 1 ..];
13 \\var a = b[c .. d + 1];
14 \\var a = b[c.a..d.e];
15 \\
16 );
17}
18
19test "zig fmt: async call in if condition" {
20 try testCanonical(
21 \\comptime {
22 \\ if (async<a> b()) {
23 \\ a();
24 \\ }
25 \\}
26 \\
27 );
28}
29
30test "zig fmt: 2nd arg multiline string" {
31 try testCanonical(
32 \\comptime {
33 \\ cases.addAsm("hello world linux x86_64",
34 \\ \\.text
35 \\ , "Hello, world!\n");
36 \\}
37 \\
38 );
39}
40
1test "zig fmt: if condition wraps" {41test "zig fmt: if condition wraps" {
2 try testTransform(42 try testTransform(
3 \\comptime {43 \\comptime {
...@@ -496,7 +536,7 @@ test "zig fmt: line comment after doc comment" {...@@ -496,7 +536,7 @@ test "zig fmt: line comment after doc comment" {
496test "zig fmt: float literal with exponent" {536test "zig fmt: float literal with exponent" {
497 try testCanonical(537 try testCanonical(
498 \\test "bit field alignment" {538 \\test "bit field alignment" {
499 \\ assert(@typeOf(&blah.b) == &align(1:3:6) const u3);539 \\ assert(@typeOf(&blah.b) == *align(1:3:6) const u3);
500 \\}540 \\}
501 \\541 \\
502 );542 );
...@@ -774,7 +814,7 @@ test "zig fmt: doc comments before struct field" {...@@ -774,7 +814,7 @@ test "zig fmt: doc comments before struct field" {
774 \\pub const Allocator = struct {814 \\pub const Allocator = struct {
775 \\ /// Allocate byte_count bytes and return them in a slice, with the815 \\ /// Allocate byte_count bytes and return them in a slice, with the
776 \\ /// slice's pointer aligned at least to alignment bytes.816 \\ /// slice's pointer aligned at least to alignment bytes.
777 \\ allocFn: fn() void,817 \\ allocFn: fn () void,
778 \\};818 \\};
779 \\819 \\
780 );820 );
...@@ -999,7 +1039,7 @@ test "zig fmt: extern declaration" {...@@ -999,7 +1039,7 @@ test "zig fmt: extern declaration" {
999}1039}
10001040
1001test "zig fmt: alignment" {1041test "zig fmt: alignment" {
1002 try testCanonical(1042 try testCanonical(
1003 \\var foo: c_int align(1);1043 \\var foo: c_int align(1);
1004 \\1044 \\
1005 );1045 );
...@@ -1007,7 +1047,7 @@ test "zig fmt: alignment" {...@@ -1007,7 +1047,7 @@ test "zig fmt: alignment" {
10071047
1008test "zig fmt: C main" {1048test "zig fmt: C main" {
1009 try testCanonical(1049 try testCanonical(
1010 \\fn main(argc: c_int, argv: &&u8) c_int {1050 \\fn main(argc: c_int, argv: **u8) c_int {
1011 \\ const a = b;1051 \\ const a = b;
1012 \\}1052 \\}
1013 \\1053 \\
...@@ -1016,7 +1056,7 @@ test "zig fmt: C main" {...@@ -1016,7 +1056,7 @@ test "zig fmt: C main" {
10161056
1017test "zig fmt: return" {1057test "zig fmt: return" {
1018 try testCanonical(1058 try testCanonical(
1019 \\fn foo(argc: c_int, argv: &&u8) c_int {1059 \\fn foo(argc: c_int, argv: **u8) c_int {
1020 \\ return 0;1060 \\ return 0;
1021 \\}1061 \\}
1022 \\1062 \\
...@@ -1029,26 +1069,26 @@ test "zig fmt: return" {...@@ -1029,26 +1069,26 @@ test "zig fmt: return" {
10291069
1030test "zig fmt: pointer attributes" {1070test "zig fmt: pointer attributes" {
1031 try testCanonical(1071 try testCanonical(
1032 \\extern fn f1(s: &align(&u8) u8) c_int;1072 \\extern fn f1(s: *align(*u8) u8) c_int;
1033 \\extern fn f2(s: &&align(1) &const &volatile u8) c_int;1073 \\extern fn f2(s: **align(1) *const *volatile u8) c_int;
1034 \\extern fn f3(s: &align(1) const &align(1) volatile &const volatile u8) c_int;1074 \\extern fn f3(s: *align(1) const *align(1) volatile *const volatile u8) c_int;
1035 \\extern fn f4(s: &align(1) const volatile u8) c_int;1075 \\extern fn f4(s: *align(1) const volatile u8) c_int;
1036 \\1076 \\
1037 );1077 );
1038}1078}
10391079
1040test "zig fmt: slice attributes" {1080test "zig fmt: slice attributes" {
1041 try testCanonical(1081 try testCanonical(
1042 \\extern fn f1(s: &align(&u8) u8) c_int;1082 \\extern fn f1(s: *align(*u8) u8) c_int;
1043 \\extern fn f2(s: &&align(1) &const &volatile u8) c_int;1083 \\extern fn f2(s: **align(1) *const *volatile u8) c_int;
1044 \\extern fn f3(s: &align(1) const &align(1) volatile &const volatile u8) c_int;1084 \\extern fn f3(s: *align(1) const *align(1) volatile *const volatile u8) c_int;
1045 \\extern fn f4(s: &align(1) const volatile u8) c_int;1085 \\extern fn f4(s: *align(1) const volatile u8) c_int;
1046 \\1086 \\
1047 );1087 );
1048}1088}
10491089
1050test "zig fmt: test declaration" {1090test "zig fmt: test declaration" {
1051 try testCanonical(1091 try testCanonical(
1052 \\test "test name" {1092 \\test "test name" {
1053 \\ const a = 1;1093 \\ const a = 1;
1054 \\ var b = 1;1094 \\ var b = 1;
...@@ -1179,18 +1219,18 @@ test "zig fmt: var type" {...@@ -1179,18 +1219,18 @@ test "zig fmt: var type" {
11791219
1180test "zig fmt: functions" {1220test "zig fmt: functions" {
1181 try testCanonical(1221 try testCanonical(
1182 \\extern fn puts(s: &const u8) c_int;1222 \\extern fn puts(s: *const u8) c_int;
1183 \\extern "c" fn puts(s: &const u8) c_int;1223 \\extern "c" fn puts(s: *const u8) c_int;
1184 \\export fn puts(s: &const u8) c_int;1224 \\export fn puts(s: *const u8) c_int;
1185 \\inline fn puts(s: &const u8) c_int;1225 \\inline fn puts(s: *const u8) c_int;
1186 \\pub extern fn puts(s: &const u8) c_int;1226 \\pub extern fn puts(s: *const u8) c_int;
1187 \\pub extern "c" fn puts(s: &const u8) c_int;1227 \\pub extern "c" fn puts(s: *const u8) c_int;
1188 \\pub export fn puts(s: &const u8) c_int;1228 \\pub export fn puts(s: *const u8) c_int;
1189 \\pub inline fn puts(s: &const u8) c_int;1229 \\pub inline fn puts(s: *const u8) c_int;
1190 \\pub extern fn puts(s: &const u8) align(2 + 2) c_int;1230 \\pub extern fn puts(s: *const u8) align(2 + 2) c_int;
1191 \\pub extern "c" fn puts(s: &const u8) align(2 + 2) c_int;1231 \\pub extern "c" fn puts(s: *const u8) align(2 + 2) c_int;
1192 \\pub export fn puts(s: &const u8) align(2 + 2) c_int;1232 \\pub export fn puts(s: *const u8) align(2 + 2) c_int;
1193 \\pub inline fn puts(s: &const u8) align(2 + 2) c_int;1233 \\pub inline fn puts(s: *const u8) align(2 + 2) c_int;
1194 \\1234 \\
1195 );1235 );
1196}1236}
...@@ -1265,8 +1305,8 @@ test "zig fmt: struct declaration" {...@@ -1265,8 +1305,8 @@ test "zig fmt: struct declaration" {
1265 \\ f1: u8,1305 \\ f1: u8,
1266 \\ pub f3: u8,1306 \\ pub f3: u8,
1267 \\1307 \\
1268 \\ fn method(self: &Self) Self {1308 \\ fn method(self: *Self) Self {
1269 \\ return *self;1309 \\ return self.*;
1270 \\ }1310 \\ }
1271 \\1311 \\
1272 \\ f2: u8,1312 \\ f2: u8,
...@@ -1290,7 +1330,7 @@ test "zig fmt: struct declaration" {...@@ -1290,7 +1330,7 @@ test "zig fmt: struct declaration" {
1290}1330}
12911331
1292test "zig fmt: enum declaration" {1332test "zig fmt: enum declaration" {
1293 try testCanonical(1333 try testCanonical(
1294 \\const E = enum {1334 \\const E = enum {
1295 \\ Ok,1335 \\ Ok,
1296 \\ SomethingElse = 0,1336 \\ SomethingElse = 0,
...@@ -1318,7 +1358,7 @@ test "zig fmt: enum declaration" {...@@ -1318,7 +1358,7 @@ test "zig fmt: enum declaration" {
1318}1358}
13191359
1320test "zig fmt: union declaration" {1360test "zig fmt: union declaration" {
1321 try testCanonical(1361 try testCanonical(
1322 \\const U = union {1362 \\const U = union {
1323 \\ Int: u8,1363 \\ Int: u8,
1324 \\ Float: f32,1364 \\ Float: f32,
...@@ -1679,10 +1719,10 @@ test "zig fmt: fn type" {...@@ -1679,10 +1719,10 @@ test "zig fmt: fn type" {
1679 \\ return i + 1;1719 \\ return i + 1;
1680 \\}1720 \\}
1681 \\1721 \\
1682 \\const a: fn(u8) u8 = undefined;1722 \\const a: fn (u8) u8 = undefined;
1683 \\const b: extern fn(u8) u8 = undefined;1723 \\const b: extern fn (u8) u8 = undefined;
1684 \\const c: nakedcc fn(u8) u8 = undefined;1724 \\const c: nakedcc fn (u8) u8 = undefined;
1685 \\const ap: fn(u8) u8 = a;1725 \\const ap: fn (u8) u8 = a;
1686 \\1726 \\
1687 );1727 );
1688}1728}
...@@ -1770,7 +1810,7 @@ const io = std.io;...@@ -1770,7 +1810,7 @@ const io = std.io;
17701810
1771var fixed_buffer_mem: [100 * 1024]u8 = undefined;1811var fixed_buffer_mem: [100 * 1024]u8 = undefined;
17721812
1773fn testParse(source: []const u8, allocator: &mem.Allocator) ![]u8 {1813fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *bool) ![]u8 {
1774 var stderr_file = try io.getStdErr();1814 var stderr_file = try io.getStdErr();
1775 var stderr = &io.FileOutStream.init(&stderr_file).stream;1815 var stderr = &io.FileOutStream.init(&stderr_file).stream;
17761816
...@@ -1807,7 +1847,7 @@ fn testParse(source: []const u8, allocator: &mem.Allocator) ![]u8 {...@@ -1807,7 +1847,7 @@ fn testParse(source: []const u8, allocator: &mem.Allocator) ![]u8 {
1807 errdefer buffer.deinit();1847 errdefer buffer.deinit();
18081848
1809 var buffer_out_stream = io.BufferOutStream.init(&buffer);1849 var buffer_out_stream = io.BufferOutStream.init(&buffer);
1810 try std.zig.render(allocator, &buffer_out_stream.stream, &tree);1850 anything_changed.* = try std.zig.render(allocator, &buffer_out_stream.stream, &tree);
1811 return buffer.toOwnedSlice();1851 return buffer.toOwnedSlice();
1812}1852}
18131853
...@@ -1816,7 +1856,8 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void {...@@ -1816,7 +1856,8 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void {
1816 // Try it once with unlimited memory, make sure it works1856 // Try it once with unlimited memory, make sure it works
1817 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);1857 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
1818 var failing_allocator = std.debug.FailingAllocator.init(&fixed_allocator.allocator, @maxValue(usize));1858 var failing_allocator = std.debug.FailingAllocator.init(&fixed_allocator.allocator, @maxValue(usize));
1819 const result_source = try testParse(source, &failing_allocator.allocator);1859 var anything_changed: bool = undefined;
1860 const result_source = try testParse(source, &failing_allocator.allocator, &anything_changed);
1820 if (!mem.eql(u8, result_source, expected_source)) {1861 if (!mem.eql(u8, result_source, expected_source)) {
1821 warn("\n====== expected this output: =========\n");1862 warn("\n====== expected this output: =========\n");
1822 warn("{}", expected_source);1863 warn("{}", expected_source);
...@@ -1825,6 +1866,12 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void {...@@ -1825,6 +1866,12 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void {
1825 warn("\n======================================\n");1866 warn("\n======================================\n");
1826 return error.TestFailed;1867 return error.TestFailed;
1827 }1868 }
1869 const changes_expected = source.ptr != expected_source.ptr;
1870 if (anything_changed != changes_expected) {
1871 warn("std.zig.render returned {} instead of {}\n", anything_changed, changes_expected);
1872 return error.TestFailed;
1873 }
1874 std.debug.assert(anything_changed == changes_expected);
1828 failing_allocator.allocator.free(result_source);1875 failing_allocator.allocator.free(result_source);
1829 break :x failing_allocator.index;1876 break :x failing_allocator.index;
1830 };1877 };
...@@ -1833,15 +1880,21 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void {...@@ -1833,15 +1880,21 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void {
1833 while (fail_index < needed_alloc_count) : (fail_index += 1) {1880 while (fail_index < needed_alloc_count) : (fail_index += 1) {
1834 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);1881 var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
1835 var failing_allocator = std.debug.FailingAllocator.init(&fixed_allocator.allocator, fail_index);1882 var failing_allocator = std.debug.FailingAllocator.init(&fixed_allocator.allocator, fail_index);
1836 if (testParse(source, &failing_allocator.allocator)) |_| {1883 var anything_changed: bool = undefined;
1884 if (testParse(source, &failing_allocator.allocator, &anything_changed)) |_| {
1837 return error.NondeterministicMemoryUsage;1885 return error.NondeterministicMemoryUsage;
1838 } else |err| switch (err) {1886 } else |err| switch (err) {
1839 error.OutOfMemory => {1887 error.OutOfMemory => {
1840 if (failing_allocator.allocated_bytes != failing_allocator.freed_bytes) {1888 if (failing_allocator.allocated_bytes != failing_allocator.freed_bytes) {
1841 warn("\nfail_index: {}/{}\nallocated bytes: {}\nfreed bytes: {}\nallocations: {}\ndeallocations: {}\n",1889 warn(
1842 fail_index, needed_alloc_count,1890 "\nfail_index: {}/{}\nallocated bytes: {}\nfreed bytes: {}\nallocations: {}\ndeallocations: {}\n",
1843 failing_allocator.allocated_bytes, failing_allocator.freed_bytes,1891 fail_index,
1844 failing_allocator.index, failing_allocator.deallocations);1892 needed_alloc_count,
1893 failing_allocator.allocated_bytes,
1894 failing_allocator.freed_bytes,
1895 failing_allocator.index,
1896 failing_allocator.deallocations,
1897 );
1845 return error.MemoryLeakDetected;1898 return error.MemoryLeakDetected;
1846 }1899 }
1847 },1900 },
...@@ -1854,4 +1907,3 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void {...@@ -1854,4 +1907,3 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void {
1854fn testCanonical(source: []const u8) !void {1907fn testCanonical(source: []const u8) !void {
1855 return testTransform(source, source);1908 return testTransform(source, source);
1856}1909}
1857
std/zig/render.zig+161-35
...@@ -12,9 +12,61 @@ pub const Error = error{...@@ -12,9 +12,61 @@ pub const Error = error{
12 OutOfMemory,12 OutOfMemory,
13};13};
1414
15pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf(stream).Child.Error || Error)!void {15/// Returns whether anything changed
16pub fn render(allocator: *mem.Allocator, stream: var, tree: *ast.Tree) (@typeOf(stream).Child.Error || Error)!bool {
16 comptime assert(@typeId(@typeOf(stream)) == builtin.TypeId.Pointer);17 comptime assert(@typeId(@typeOf(stream)) == builtin.TypeId.Pointer);
1718
19 var anything_changed: bool = false;
20
21 // make a passthrough stream that checks whether something changed
22 const MyStream = struct {
23 const MyStream = this;
24 const StreamError = @typeOf(stream).Child.Error;
25 const Stream = std.io.OutStream(StreamError);
26
27 anything_changed_ptr: *bool,
28 child_stream: @typeOf(stream),
29 stream: Stream,
30 source_index: usize,
31 source: []const u8,
32
33 fn write(iface_stream: *Stream, bytes: []const u8) StreamError!void {
34 const self = @fieldParentPtr(MyStream, "stream", iface_stream);
35
36 if (!self.anything_changed_ptr.*) {
37 const end = self.source_index + bytes.len;
38 if (end > self.source.len) {
39 self.anything_changed_ptr.* = true;
40 } else {
41 const src_slice = self.source[self.source_index..end];
42 self.source_index += bytes.len;
43 if (!mem.eql(u8, bytes, src_slice)) {
44 self.anything_changed_ptr.* = true;
45 }
46 }
47 }
48
49 try self.child_stream.write(bytes);
50 }
51 };
52 var my_stream = MyStream{
53 .stream = MyStream.Stream{ .writeFn = MyStream.write },
54 .child_stream = stream,
55 .anything_changed_ptr = &anything_changed,
56 .source_index = 0,
57 .source = tree.source,
58 };
59
60 try renderRoot(allocator, &my_stream.stream, tree);
61
62 return anything_changed;
63}
64
65fn renderRoot(
66 allocator: *mem.Allocator,
67 stream: var,
68 tree: *ast.Tree,
69) (@typeOf(stream).Child.Error || Error)!void {
18 // render all the line comments at the beginning of the file70 // render all the line comments at the beginning of the file
19 var tok_it = tree.tokens.iterator(0);71 var tok_it = tree.tokens.iterator(0);
20 while (tok_it.next()) |token| {72 while (tok_it.next()) |token| {
...@@ -38,7 +90,7 @@ pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf(...@@ -38,7 +90,7 @@ pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf(
38 }90 }
39}91}
4092
41fn renderExtraNewline(tree: &ast.Tree, stream: var, start_col: &usize, node: &ast.Node) !void {93fn renderExtraNewline(tree: *ast.Tree, stream: var, start_col: *usize, node: *ast.Node) !void {
42 const first_token = node.firstToken();94 const first_token = node.firstToken();
43 var prev_token = first_token;95 var prev_token = first_token;
44 while (tree.tokens.at(prev_token - 1).id == Token.Id.DocComment) {96 while (tree.tokens.at(prev_token - 1).id == Token.Id.DocComment) {
...@@ -52,7 +104,7 @@ fn renderExtraNewline(tree: &ast.Tree, stream: var, start_col: &usize, node: &as...@@ -52,7 +104,7 @@ fn renderExtraNewline(tree: &ast.Tree, stream: var, start_col: &usize, node: &as
52 }104 }
53}105}
54106
55fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, decl: &ast.Node) (@typeOf(stream).Child.Error || Error)!void {107fn renderTopLevelDecl(allocator: *mem.Allocator, stream: var, tree: *ast.Tree, indent: usize, start_col: *usize, decl: *ast.Node) (@typeOf(stream).Child.Error || Error)!void {
56 switch (decl.id) {108 switch (decl.id) {
57 ast.Node.Id.FnProto => {109 ast.Node.Id.FnProto => {
58 const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl);110 const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl);
...@@ -161,7 +213,15 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i...@@ -161,7 +213,15 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i
161 }213 }
162}214}
163215
164fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, base: &ast.Node, space: Space,) (@typeOf(stream).Child.Error || Error)!void {216fn renderExpression(
217 allocator: *mem.Allocator,
218 stream: var,
219 tree: *ast.Tree,
220 indent: usize,
221 start_col: *usize,
222 base: *ast.Node,
223 space: Space,
224) (@typeOf(stream).Child.Error || Error)!void {
165 switch (base.id) {225 switch (base.id) {
166 ast.Node.Id.Identifier => {226 ast.Node.Id.Identifier => {
167 const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base);227 const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base);
...@@ -213,13 +273,13 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind...@@ -213,13 +273,13 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
213 const async_attr = @fieldParentPtr(ast.Node.AsyncAttribute, "base", base);273 const async_attr = @fieldParentPtr(ast.Node.AsyncAttribute, "base", base);
214274
215 if (async_attr.allocator_type) |allocator_type| {275 if (async_attr.allocator_type) |allocator_type| {
216 try renderToken(tree, stream, async_attr.async_token, indent, start_col, Space.None);276 try renderToken(tree, stream, async_attr.async_token, indent, start_col, Space.None); // async
217277
218 try renderToken(tree, stream, tree.nextToken(async_attr.async_token), indent, start_col, Space.None);278 try renderToken(tree, stream, tree.nextToken(async_attr.async_token), indent, start_col, Space.None); // <
219 try renderExpression(allocator, stream, tree, indent, start_col, allocator_type, Space.None);279 try renderExpression(allocator, stream, tree, indent, start_col, allocator_type, Space.None); // allocator
220 return renderToken(tree, stream, tree.nextToken(allocator_type.lastToken()), indent, start_col, space);280 return renderToken(tree, stream, tree.nextToken(allocator_type.lastToken()), indent, start_col, space); // >
221 } else {281 } else {
222 return renderToken(tree, stream, async_attr.async_token, indent, start_col, space);282 return renderToken(tree, stream, async_attr.async_token, indent, start_col, space); // async
223 }283 }
224 },284 },
225285
...@@ -259,8 +319,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind...@@ -259,8 +319,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
259 try renderExpression(allocator, stream, tree, indent, start_col, infix_op_node.lhs, op_space);319 try renderExpression(allocator, stream, tree, indent, start_col, infix_op_node.lhs, op_space);
260320
261 const after_op_space = blk: {321 const after_op_space = blk: {
262 const loc = tree.tokenLocation(tree.tokens.at(infix_op_node.op_token).end,322 const loc = tree.tokenLocation(tree.tokens.at(infix_op_node.op_token).end, tree.nextToken(infix_op_node.op_token));
263 tree.nextToken(infix_op_node.op_token));
264 break :blk if (loc.line == 0) op_space else Space.Newline;323 break :blk if (loc.line == 0) op_space else Space.Newline;
265 };324 };
266325
...@@ -284,9 +343,13 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind...@@ -284,9 +343,13 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
284 const prefix_op_node = @fieldParentPtr(ast.Node.PrefixOp, "base", base);343 const prefix_op_node = @fieldParentPtr(ast.Node.PrefixOp, "base", base);
285344
286 switch (prefix_op_node.op) {345 switch (prefix_op_node.op) {
287 ast.Node.PrefixOp.Op.AddrOf => |addr_of_info| {346 ast.Node.PrefixOp.Op.PtrType => |ptr_info| {
288 try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None); // &347 const star_offset = switch (tree.tokens.at(prefix_op_node.op_token).id) {
289 if (addr_of_info.align_info) |align_info| {348 Token.Id.AsteriskAsterisk => usize(1),
349 else => usize(0),
350 };
351 try renderTokenOffset(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None, star_offset); // *
352 if (ptr_info.align_info) |align_info| {
290 const lparen_token = tree.prevToken(align_info.node.firstToken());353 const lparen_token = tree.prevToken(align_info.node.firstToken());
291 const align_token = tree.prevToken(lparen_token);354 const align_token = tree.prevToken(lparen_token);
292355
...@@ -311,19 +374,19 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind...@@ -311,19 +374,19 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
311 try renderToken(tree, stream, rparen_token, indent, start_col, Space.Space); // )374 try renderToken(tree, stream, rparen_token, indent, start_col, Space.Space); // )
312 }375 }
313 }376 }
314 if (addr_of_info.const_token) |const_token| {377 if (ptr_info.const_token) |const_token| {
315 try renderToken(tree, stream, const_token, indent, start_col, Space.Space); // const378 try renderToken(tree, stream, const_token, indent, start_col, Space.Space); // const
316 }379 }
317 if (addr_of_info.volatile_token) |volatile_token| {380 if (ptr_info.volatile_token) |volatile_token| {
318 try renderToken(tree, stream, volatile_token, indent, start_col, Space.Space); // volatile381 try renderToken(tree, stream, volatile_token, indent, start_col, Space.Space); // volatile
319 }382 }
320 },383 },
321384
322 ast.Node.PrefixOp.Op.SliceType => |addr_of_info| {385 ast.Node.PrefixOp.Op.SliceType => |ptr_info| {
323 try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None); // [386 try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None); // [
324 try renderToken(tree, stream, tree.nextToken(prefix_op_node.op_token), indent, start_col, Space.None); // ]387 try renderToken(tree, stream, tree.nextToken(prefix_op_node.op_token), indent, start_col, Space.None); // ]
325388
326 if (addr_of_info.align_info) |align_info| {389 if (ptr_info.align_info) |align_info| {
327 const lparen_token = tree.prevToken(align_info.node.firstToken());390 const lparen_token = tree.prevToken(align_info.node.firstToken());
328 const align_token = tree.prevToken(lparen_token);391 const align_token = tree.prevToken(lparen_token);
329392
...@@ -348,10 +411,10 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind...@@ -348,10 +411,10 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
348 try renderToken(tree, stream, rparen_token, indent, start_col, Space.Space); // )411 try renderToken(tree, stream, rparen_token, indent, start_col, Space.Space); // )
349 }412 }
350 }413 }
351 if (addr_of_info.const_token) |const_token| {414 if (ptr_info.const_token) |const_token| {
352 try renderToken(tree, stream, const_token, indent, start_col, Space.Space);415 try renderToken(tree, stream, const_token, indent, start_col, Space.Space);
353 }416 }
354 if (addr_of_info.volatile_token) |volatile_token| {417 if (ptr_info.volatile_token) |volatile_token| {
355 try renderToken(tree, stream, volatile_token, indent, start_col, Space.Space);418 try renderToken(tree, stream, volatile_token, indent, start_col, Space.Space);
356 }419 }
357 },420 },
...@@ -367,14 +430,16 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind...@@ -367,14 +430,16 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
367 ast.Node.PrefixOp.Op.NegationWrap,430 ast.Node.PrefixOp.Op.NegationWrap,
368 ast.Node.PrefixOp.Op.UnwrapMaybe,431 ast.Node.PrefixOp.Op.UnwrapMaybe,
369 ast.Node.PrefixOp.Op.MaybeType,432 ast.Node.PrefixOp.Op.MaybeType,
370 ast.Node.PrefixOp.Op.PointerType => {433 ast.Node.PrefixOp.Op.AddressOf,
434 => {
371 try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None);435 try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None);
372 },436 },
373437
374 ast.Node.PrefixOp.Op.Try,438 ast.Node.PrefixOp.Op.Try,
375 ast.Node.PrefixOp.Op.Await,439 ast.Node.PrefixOp.Op.Await,
376 ast.Node.PrefixOp.Op.Cancel,440 ast.Node.PrefixOp.Op.Cancel,
377 ast.Node.PrefixOp.Op.Resume => {441 ast.Node.PrefixOp.Op.Resume,
442 => {
378 try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.Space);443 try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.Space);
379 },444 },
380 }445 }
...@@ -469,9 +534,14 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind...@@ -469,9 +534,14 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
469 const lbracket = tree.prevToken(range.start.firstToken());534 const lbracket = tree.prevToken(range.start.firstToken());
470 const dotdot = tree.nextToken(range.start.lastToken());535 const dotdot = tree.nextToken(range.start.lastToken());
471536
537 const after_start_space_bool = nodeCausesSliceOpSpace(range.start) or
538 (if (range.end) |end| nodeCausesSliceOpSpace(end) else false);
539 const after_start_space = if (after_start_space_bool) Space.Space else Space.None;
540 const after_op_space = if (range.end != null) after_start_space else Space.None;
541
472 try renderToken(tree, stream, lbracket, indent, start_col, Space.None); // [542 try renderToken(tree, stream, lbracket, indent, start_col, Space.None); // [
473 try renderExpression(allocator, stream, tree, indent, start_col, range.start, Space.None);543 try renderExpression(allocator, stream, tree, indent, start_col, range.start, after_start_space);
474 try renderToken(tree, stream, dotdot, indent, start_col, Space.None); // ..544 try renderToken(tree, stream, dotdot, indent, start_col, after_op_space); // ..
475 if (range.end) |end| {545 if (range.end) |end| {
476 try renderExpression(allocator, stream, tree, indent, start_col, end, Space.None);546 try renderExpression(allocator, stream, tree, indent, start_col, end, Space.None);
477 }547 }
...@@ -993,7 +1063,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind...@@ -993,7 +1063,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
993 try renderToken(tree, stream, name_token, indent, start_col, Space.None); // name1063 try renderToken(tree, stream, name_token, indent, start_col, Space.None); // name
994 break :blk tree.nextToken(name_token);1064 break :blk tree.nextToken(name_token);
995 } else blk: {1065 } else blk: {
996 try renderToken(tree, stream, fn_proto.fn_token, indent, start_col, Space.None); // fn1066 try renderToken(tree, stream, fn_proto.fn_token, indent, start_col, Space.Space); // fn
997 break :blk tree.nextToken(fn_proto.fn_token);1067 break :blk tree.nextToken(fn_proto.fn_token);
998 };1068 };
9991069
...@@ -1568,13 +1638,19 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind...@@ -1568,13 +1638,19 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
1568 ast.Node.Id.VarDecl,1638 ast.Node.Id.VarDecl,
1569 ast.Node.Id.Use,1639 ast.Node.Id.Use,
1570 ast.Node.Id.TestDecl,1640 ast.Node.Id.TestDecl,
1571 ast.Node.Id.ParamDecl => unreachable,1641 ast.Node.Id.ParamDecl,
1642 => unreachable,
1572 }1643 }
1573}1644}
15741645
1575fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize,1646fn renderVarDecl(
1576 var_decl: &ast.Node.VarDecl,) (@typeOf(stream).Child.Error || Error)!void1647 allocator: *mem.Allocator,
1577{1648 stream: var,
1649 tree: *ast.Tree,
1650 indent: usize,
1651 start_col: *usize,
1652 var_decl: *ast.Node.VarDecl,
1653) (@typeOf(stream).Child.Error || Error)!void {
1578 if (var_decl.visib_token) |visib_token| {1654 if (var_decl.visib_token) |visib_token| {
1579 try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub1655 try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub
1580 }1656 }
...@@ -1623,7 +1699,15 @@ fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent...@@ -1623,7 +1699,15 @@ fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent
1623 try renderToken(tree, stream, var_decl.semicolon_token, indent, start_col, Space.Newline);1699 try renderToken(tree, stream, var_decl.semicolon_token, indent, start_col, Space.Newline);
1624}1700}
16251701
1626fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, base: &ast.Node, space: Space,) (@typeOf(stream).Child.Error || Error)!void {1702fn renderParamDecl(
1703 allocator: *mem.Allocator,
1704 stream: var,
1705 tree: *ast.Tree,
1706 indent: usize,
1707 start_col: *usize,
1708 base: *ast.Node,
1709 space: Space,
1710) (@typeOf(stream).Child.Error || Error)!void {
1627 const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base);1711 const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base);
16281712
1629 if (param_decl.comptime_token) |comptime_token| {1713 if (param_decl.comptime_token) |comptime_token| {
...@@ -1643,7 +1727,14 @@ fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, inde...@@ -1643,7 +1727,14 @@ fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, inde
1643 }1727 }
1644}1728}
16451729
1646fn renderStatement(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, base: &ast.Node,) (@typeOf(stream).Child.Error || Error)!void {1730fn renderStatement(
1731 allocator: *mem.Allocator,
1732 stream: var,
1733 tree: *ast.Tree,
1734 indent: usize,
1735 start_col: *usize,
1736 base: *ast.Node,
1737) (@typeOf(stream).Child.Error || Error)!void {
1647 switch (base.id) {1738 switch (base.id) {
1648 ast.Node.Id.VarDecl => {1739 ast.Node.Id.VarDecl => {
1649 const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base);1740 const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base);
...@@ -1674,7 +1765,15 @@ const Space = enum {...@@ -1674,7 +1765,15 @@ const Space = enum {
1674 BlockStart,1765 BlockStart,
1675};1766};
16761767
1677fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, start_col: &usize, space: Space) (@typeOf(stream).Child.Error || Error)!void {1768fn renderTokenOffset(
1769 tree: *ast.Tree,
1770 stream: var,
1771 token_index: ast.TokenIndex,
1772 indent: usize,
1773 start_col: *usize,
1774 space: Space,
1775 token_skip_bytes: usize,
1776) (@typeOf(stream).Child.Error || Error)!void {
1678 if (space == Space.BlockStart) {1777 if (space == Space.BlockStart) {
1679 if (start_col.* < indent + indent_delta)1778 if (start_col.* < indent + indent_delta)
1680 return renderToken(tree, stream, token_index, indent, start_col, Space.Space);1779 return renderToken(tree, stream, token_index, indent, start_col, Space.Space);
...@@ -1685,7 +1784,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent...@@ -1685,7 +1784,7 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent
1685 }1784 }
16861785
1687 var token = tree.tokens.at(token_index);1786 var token = tree.tokens.at(token_index);
1688 try stream.write(mem.trimRight(u8, tree.tokenSlicePtr(token), " "));1787 try stream.write(mem.trimRight(u8, tree.tokenSlicePtr(token)[token_skip_bytes..], " "));
16891788
1690 if (space == Space.NoComment)1789 if (space == Space.NoComment)
1691 return;1790 return;
...@@ -1733,6 +1832,8 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent...@@ -1733,6 +1832,8 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent
1733 }1832 }
1734 },1833 },
1735 Space.Space, Space.SpaceOrOutdent => {1834 Space.Space, Space.SpaceOrOutdent => {
1835 if (next_token.id == Token.Id.MultilineStringLiteralLine)
1836 return;
1736 try stream.writeByte(' ');1837 try stream.writeByte(' ');
1737 return;1838 return;
1738 },1839 },
...@@ -1838,7 +1939,24 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent...@@ -1838,7 +1939,24 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent
1838 }1939 }
1839}1940}
18401941
1841fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize, start_col: &usize,) (@typeOf(stream).Child.Error || Error)!void {1942fn renderToken(
1943 tree: *ast.Tree,
1944 stream: var,
1945 token_index: ast.TokenIndex,
1946 indent: usize,
1947 start_col: *usize,
1948 space: Space,
1949) (@typeOf(stream).Child.Error || Error)!void {
1950 return renderTokenOffset(tree, stream, token_index, indent, start_col, space, 0);
1951}
1952
1953fn renderDocComments(
1954 tree: *ast.Tree,
1955 stream: var,
1956 node: var,
1957 indent: usize,
1958 start_col: *usize,
1959) (@typeOf(stream).Child.Error || Error)!void {
1842 const comment = node.doc_comments ?? return;1960 const comment = node.doc_comments ?? return;
1843 var it = comment.lines.iterator(0);1961 var it = comment.lines.iterator(0);
1844 const first_token = node.firstToken();1962 const first_token = node.firstToken();
...@@ -1854,7 +1972,7 @@ fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize, sta...@@ -1854,7 +1972,7 @@ fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize, sta
1854 }1972 }
1855}1973}
18561974
1857fn nodeIsBlock(base: &const ast.Node) bool {1975fn nodeIsBlock(base: *const ast.Node) bool {
1858 return switch (base.id) {1976 return switch (base.id) {
1859 ast.Node.Id.Block,1977 ast.Node.Id.Block,
1860 ast.Node.Id.If,1978 ast.Node.Id.If,
...@@ -1865,3 +1983,11 @@ fn nodeIsBlock(base: &const ast.Node) bool {...@@ -1865,3 +1983,11 @@ fn nodeIsBlock(base: &const ast.Node) bool {
1865 else => false,1983 else => false,
1866 };1984 };
1867}1985}
1986
1987fn nodeCausesSliceOpSpace(base: *ast.Node) bool {
1988 const infix_op = base.cast(ast.Node.InfixOp) ?? return false;
1989 return switch (infix_op.op) {
1990 ast.Node.InfixOp.Op.Period => false,
1991 else => true,
1992 };
1993}
std/zig/tokenizer.zig+144-108
...@@ -11,55 +11,55 @@ pub const Token = struct {...@@ -11,55 +11,55 @@ pub const Token = struct {
11 id: Id,11 id: Id,
12 };12 };
1313
14 pub const keywords = []Keyword {14 pub const keywords = []Keyword{
15 Keyword{.bytes="align", .id = Id.Keyword_align},15 Keyword{ .bytes = "align", .id = Id.Keyword_align },
16 Keyword{.bytes="and", .id = Id.Keyword_and},16 Keyword{ .bytes = "and", .id = Id.Keyword_and },
17 Keyword{.bytes="asm", .id = Id.Keyword_asm},17 Keyword{ .bytes = "asm", .id = Id.Keyword_asm },
18 Keyword{.bytes="async", .id = Id.Keyword_async},18 Keyword{ .bytes = "async", .id = Id.Keyword_async },
19 Keyword{.bytes="await", .id = Id.Keyword_await},19 Keyword{ .bytes = "await", .id = Id.Keyword_await },
20 Keyword{.bytes="break", .id = Id.Keyword_break},20 Keyword{ .bytes = "break", .id = Id.Keyword_break },
21 Keyword{.bytes="catch", .id = Id.Keyword_catch},21 Keyword{ .bytes = "catch", .id = Id.Keyword_catch },
22 Keyword{.bytes="cancel", .id = Id.Keyword_cancel},22 Keyword{ .bytes = "cancel", .id = Id.Keyword_cancel },
23 Keyword{.bytes="comptime", .id = Id.Keyword_comptime},23 Keyword{ .bytes = "comptime", .id = Id.Keyword_comptime },
24 Keyword{.bytes="const", .id = Id.Keyword_const},24 Keyword{ .bytes = "const", .id = Id.Keyword_const },
25 Keyword{.bytes="continue", .id = Id.Keyword_continue},25 Keyword{ .bytes = "continue", .id = Id.Keyword_continue },
26 Keyword{.bytes="defer", .id = Id.Keyword_defer},26 Keyword{ .bytes = "defer", .id = Id.Keyword_defer },
27 Keyword{.bytes="else", .id = Id.Keyword_else},27 Keyword{ .bytes = "else", .id = Id.Keyword_else },
28 Keyword{.bytes="enum", .id = Id.Keyword_enum},28 Keyword{ .bytes = "enum", .id = Id.Keyword_enum },
29 Keyword{.bytes="errdefer", .id = Id.Keyword_errdefer},29 Keyword{ .bytes = "errdefer", .id = Id.Keyword_errdefer },
30 Keyword{.bytes="error", .id = Id.Keyword_error},30 Keyword{ .bytes = "error", .id = Id.Keyword_error },
31 Keyword{.bytes="export", .id = Id.Keyword_export},31 Keyword{ .bytes = "export", .id = Id.Keyword_export },
32 Keyword{.bytes="extern", .id = Id.Keyword_extern},32 Keyword{ .bytes = "extern", .id = Id.Keyword_extern },
33 Keyword{.bytes="false", .id = Id.Keyword_false},33 Keyword{ .bytes = "false", .id = Id.Keyword_false },
34 Keyword{.bytes="fn", .id = Id.Keyword_fn},34 Keyword{ .bytes = "fn", .id = Id.Keyword_fn },
35 Keyword{.bytes="for", .id = Id.Keyword_for},35 Keyword{ .bytes = "for", .id = Id.Keyword_for },
36 Keyword{.bytes="if", .id = Id.Keyword_if},36 Keyword{ .bytes = "if", .id = Id.Keyword_if },
37 Keyword{.bytes="inline", .id = Id.Keyword_inline},37 Keyword{ .bytes = "inline", .id = Id.Keyword_inline },
38 Keyword{.bytes="nakedcc", .id = Id.Keyword_nakedcc},38 Keyword{ .bytes = "nakedcc", .id = Id.Keyword_nakedcc },
39 Keyword{.bytes="noalias", .id = Id.Keyword_noalias},39 Keyword{ .bytes = "noalias", .id = Id.Keyword_noalias },
40 Keyword{.bytes="null", .id = Id.Keyword_null},40 Keyword{ .bytes = "null", .id = Id.Keyword_null },
41 Keyword{.bytes="or", .id = Id.Keyword_or},41 Keyword{ .bytes = "or", .id = Id.Keyword_or },
42 Keyword{.bytes="packed", .id = Id.Keyword_packed},42 Keyword{ .bytes = "packed", .id = Id.Keyword_packed },
43 Keyword{.bytes="promise", .id = Id.Keyword_promise},43 Keyword{ .bytes = "promise", .id = Id.Keyword_promise },
44 Keyword{.bytes="pub", .id = Id.Keyword_pub},44 Keyword{ .bytes = "pub", .id = Id.Keyword_pub },
45 Keyword{.bytes="resume", .id = Id.Keyword_resume},45 Keyword{ .bytes = "resume", .id = Id.Keyword_resume },
46 Keyword{.bytes="return", .id = Id.Keyword_return},46 Keyword{ .bytes = "return", .id = Id.Keyword_return },
47 Keyword{.bytes="section", .id = Id.Keyword_section},47 Keyword{ .bytes = "section", .id = Id.Keyword_section },
48 Keyword{.bytes="stdcallcc", .id = Id.Keyword_stdcallcc},48 Keyword{ .bytes = "stdcallcc", .id = Id.Keyword_stdcallcc },
49 Keyword{.bytes="struct", .id = Id.Keyword_struct},49 Keyword{ .bytes = "struct", .id = Id.Keyword_struct },
50 Keyword{.bytes="suspend", .id = Id.Keyword_suspend},50 Keyword{ .bytes = "suspend", .id = Id.Keyword_suspend },
51 Keyword{.bytes="switch", .id = Id.Keyword_switch},51 Keyword{ .bytes = "switch", .id = Id.Keyword_switch },
52 Keyword{.bytes="test", .id = Id.Keyword_test},52 Keyword{ .bytes = "test", .id = Id.Keyword_test },
53 Keyword{.bytes="this", .id = Id.Keyword_this},53 Keyword{ .bytes = "this", .id = Id.Keyword_this },
54 Keyword{.bytes="true", .id = Id.Keyword_true},54 Keyword{ .bytes = "true", .id = Id.Keyword_true },
55 Keyword{.bytes="try", .id = Id.Keyword_try},55 Keyword{ .bytes = "try", .id = Id.Keyword_try },
56 Keyword{.bytes="undefined", .id = Id.Keyword_undefined},56 Keyword{ .bytes = "undefined", .id = Id.Keyword_undefined },
57 Keyword{.bytes="union", .id = Id.Keyword_union},57 Keyword{ .bytes = "union", .id = Id.Keyword_union },
58 Keyword{.bytes="unreachable", .id = Id.Keyword_unreachable},58 Keyword{ .bytes = "unreachable", .id = Id.Keyword_unreachable },
59 Keyword{.bytes="use", .id = Id.Keyword_use},59 Keyword{ .bytes = "use", .id = Id.Keyword_use },
60 Keyword{.bytes="var", .id = Id.Keyword_var},60 Keyword{ .bytes = "var", .id = Id.Keyword_var },
61 Keyword{.bytes="volatile", .id = Id.Keyword_volatile},61 Keyword{ .bytes = "volatile", .id = Id.Keyword_volatile },
62 Keyword{.bytes="while", .id = Id.Keyword_while},62 Keyword{ .bytes = "while", .id = Id.Keyword_while },
63 };63 };
6464
65 // TODO perfect hash at comptime65 // TODO perfect hash at comptime
...@@ -72,7 +72,10 @@ pub const Token = struct {...@@ -72,7 +72,10 @@ pub const Token = struct {
72 return null;72 return null;
73 }73 }
7474
75 const StrLitKind = enum {Normal, C};75 const StrLitKind = enum {
76 Normal,
77 C,
78 };
7679
77 pub const Id = union(enum) {80 pub const Id = union(enum) {
78 Invalid,81 Invalid,
...@@ -140,6 +143,7 @@ pub const Token = struct {...@@ -140,6 +143,7 @@ pub const Token = struct {
140 FloatLiteral,143 FloatLiteral,
141 LineComment,144 LineComment,
142 DocComment,145 DocComment,
146 BracketStarBracket,
143 Keyword_align,147 Keyword_align,
144 Keyword_and,148 Keyword_and,
145 Keyword_asm,149 Keyword_asm,
...@@ -197,12 +201,12 @@ pub const Tokenizer = struct {...@@ -197,12 +201,12 @@ pub const Tokenizer = struct {
197 pending_invalid_token: ?Token,201 pending_invalid_token: ?Token,
198202
199 /// For debugging purposes203 /// For debugging purposes
200 pub fn dump(self: &Tokenizer, token: &const Token) void {204 pub fn dump(self: *Tokenizer, token: *const Token) void {
201 std.debug.warn("{} \"{}\"\n", @tagName(token.id), self.buffer[token.start..token.end]);205 std.debug.warn("{} \"{}\"\n", @tagName(token.id), self.buffer[token.start..token.end]);
202 }206 }
203207
204 pub fn init(buffer: []const u8) Tokenizer {208 pub fn init(buffer: []const u8) Tokenizer {
205 return Tokenizer {209 return Tokenizer{
206 .buffer = buffer,210 .buffer = buffer,
207 .index = 0,211 .index = 0,
208 .pending_invalid_token = null,212 .pending_invalid_token = null,
...@@ -260,16 +264,18 @@ pub const Tokenizer = struct {...@@ -260,16 +264,18 @@ pub const Tokenizer = struct {
260 Period,264 Period,
261 Period2,265 Period2,
262 SawAtSign,266 SawAtSign,
267 LBracket,
268 LBracketStar,
263 };269 };
264270
265 pub fn next(self: &Tokenizer) Token {271 pub fn next(self: *Tokenizer) Token {
266 if (self.pending_invalid_token) |token| {272 if (self.pending_invalid_token) |token| {
267 self.pending_invalid_token = null;273 self.pending_invalid_token = null;
268 return token;274 return token;
269 }275 }
270 const start_index = self.index;276 const start_index = self.index;
271 var state = State.Start;277 var state = State.Start;
272 var result = Token {278 var result = Token{
273 .id = Token.Id.Eof,279 .id = Token.Id.Eof,
274 .start = self.index,280 .start = self.index,
275 .end = undefined,281 .end = undefined,
...@@ -290,7 +296,7 @@ pub const Tokenizer = struct {...@@ -290,7 +296,7 @@ pub const Tokenizer = struct {
290 },296 },
291 '"' => {297 '"' => {
292 state = State.StringLiteral;298 state = State.StringLiteral;
293 result.id = Token.Id { .StringLiteral = Token.StrLitKind.Normal };299 result.id = Token.Id{ .StringLiteral = Token.StrLitKind.Normal };
294 },300 },
295 '\'' => {301 '\'' => {
296 state = State.CharLiteral;302 state = State.CharLiteral;
...@@ -322,9 +328,7 @@ pub const Tokenizer = struct {...@@ -322,9 +328,7 @@ pub const Tokenizer = struct {
322 break;328 break;
323 },329 },
324 '[' => {330 '[' => {
325 result.id = Token.Id.LBracket;331 state = State.LBracket;
326 self.index += 1;
327 break;
328 },332 },
329 ']' => {333 ']' => {
330 result.id = Token.Id.RBracket;334 result.id = Token.Id.RBracket;
...@@ -369,7 +373,7 @@ pub const Tokenizer = struct {...@@ -369,7 +373,7 @@ pub const Tokenizer = struct {
369 },373 },
370 '\\' => {374 '\\' => {
371 state = State.Backslash;375 state = State.Backslash;
372 result.id = Token.Id { .MultilineStringLiteralLine = Token.StrLitKind.Normal };376 result.id = Token.Id{ .MultilineStringLiteralLine = Token.StrLitKind.Normal };
373 },377 },
374 '{' => {378 '{' => {
375 result.id = Token.Id.LBrace;379 result.id = Token.Id.LBrace;
...@@ -426,6 +430,28 @@ pub const Tokenizer = struct {...@@ -426,6 +430,28 @@ pub const Tokenizer = struct {
426 },430 },
427 },431 },
428432
433 State.LBracket => switch (c) {
434 '*' => {
435 state = State.LBracketStar;
436 },
437 else => {
438 result.id = Token.Id.LBracket;
439 break;
440 },
441 },
442
443 State.LBracketStar => switch (c) {
444 ']' => {
445 result.id = Token.Id.BracketStarBracket;
446 self.index += 1;
447 break;
448 },
449 else => {
450 result.id = Token.Id.Invalid;
451 break;
452 },
453 },
454
429 State.Ampersand => switch (c) {455 State.Ampersand => switch (c) {
430 '=' => {456 '=' => {
431 result.id = Token.Id.AmpersandEqual;457 result.id = Token.Id.AmpersandEqual;
...@@ -455,7 +481,7 @@ pub const Tokenizer = struct {...@@ -455,7 +481,7 @@ pub const Tokenizer = struct {
455 else => {481 else => {
456 result.id = Token.Id.Asterisk;482 result.id = Token.Id.Asterisk;
457 break;483 break;
458 }484 },
459 },485 },
460486
461 State.AsteriskPercent => switch (c) {487 State.AsteriskPercent => switch (c) {
...@@ -467,7 +493,7 @@ pub const Tokenizer = struct {...@@ -467,7 +493,7 @@ pub const Tokenizer = struct {
467 else => {493 else => {
468 result.id = Token.Id.AsteriskPercent;494 result.id = Token.Id.AsteriskPercent;
469 break;495 break;
470 }496 },
471 },497 },
472498
473 State.QuestionMark => switch (c) {499 State.QuestionMark => switch (c) {
...@@ -535,7 +561,7 @@ pub const Tokenizer = struct {...@@ -535,7 +561,7 @@ pub const Tokenizer = struct {
535 else => {561 else => {
536 result.id = Token.Id.Caret;562 result.id = Token.Id.Caret;
537 break;563 break;
538 }564 },
539 },565 },
540566
541 State.Identifier => switch (c) {567 State.Identifier => switch (c) {
...@@ -560,11 +586,11 @@ pub const Tokenizer = struct {...@@ -560,11 +586,11 @@ pub const Tokenizer = struct {
560 State.C => switch (c) {586 State.C => switch (c) {
561 '\\' => {587 '\\' => {
562 state = State.Backslash;588 state = State.Backslash;
563 result.id = Token.Id { .MultilineStringLiteralLine = Token.StrLitKind.C };589 result.id = Token.Id{ .MultilineStringLiteralLine = Token.StrLitKind.C };
564 },590 },
565 '"' => {591 '"' => {
566 state = State.StringLiteral;592 state = State.StringLiteral;
567 result.id = Token.Id { .StringLiteral = Token.StrLitKind.C };593 result.id = Token.Id{ .StringLiteral = Token.StrLitKind.C };
568 },594 },
569 'a'...'z', 'A'...'Z', '_', '0'...'9' => {595 'a'...'z', 'A'...'Z', '_', '0'...'9' => {
570 state = State.Identifier;596 state = State.Identifier;
...@@ -605,7 +631,7 @@ pub const Tokenizer = struct {...@@ -605,7 +631,7 @@ pub const Tokenizer = struct {
605 }631 }
606632
607 state = State.CharLiteralEnd;633 state = State.CharLiteralEnd;
608 }634 },
609 },635 },
610636
611 State.CharLiteralBackslash => switch (c) {637 State.CharLiteralBackslash => switch (c) {
...@@ -736,7 +762,7 @@ pub const Tokenizer = struct {...@@ -736,7 +762,7 @@ pub const Tokenizer = struct {
736 else => {762 else => {
737 result.id = Token.Id.MinusPercent;763 result.id = Token.Id.MinusPercent;
738 break;764 break;
739 }765 },
740 },766 },
741767
742 State.AngleBracketLeft => switch (c) {768 State.AngleBracketLeft => switch (c) {
...@@ -944,7 +970,7 @@ pub const Tokenizer = struct {...@@ -944,7 +970,7 @@ pub const Tokenizer = struct {
944 // reinterpret as a normal exponent number970 // reinterpret as a normal exponent number
945 self.index -= 1;971 self.index -= 1;
946 state = State.FloatExponentNumber;972 state = State.FloatExponentNumber;
947 }973 },
948 },974 },
949 State.FloatExponentUnsignedHex => switch (c) {975 State.FloatExponentUnsignedHex => switch (c) {
950 '+', '-' => {976 '+', '-' => {
...@@ -954,7 +980,7 @@ pub const Tokenizer = struct {...@@ -954,7 +980,7 @@ pub const Tokenizer = struct {
954 // reinterpret as a normal exponent number980 // reinterpret as a normal exponent number
955 self.index -= 1;981 self.index -= 1;
956 state = State.FloatExponentNumberHex;982 state = State.FloatExponentNumberHex;
957 }983 },
958 },984 },
959 State.FloatExponentNumber => switch (c) {985 State.FloatExponentNumber => switch (c) {
960 '0'...'9' => {},986 '0'...'9' => {},
...@@ -978,15 +1004,15 @@ pub const Tokenizer = struct {...@@ -978,15 +1004,15 @@ pub const Tokenizer = struct {
978 State.FloatExponentNumberHex,1004 State.FloatExponentNumberHex,
979 State.StringLiteral, // find this error later1005 State.StringLiteral, // find this error later
980 State.MultilineStringLiteralLine,1006 State.MultilineStringLiteralLine,
981 State.Builtin => {},1007 State.Builtin,
1008 => {},
9821009
983 State.Identifier => {1010 State.Identifier => {
984 if (Token.getKeyword(self.buffer[result.start..self.index])) |id| {1011 if (Token.getKeyword(self.buffer[result.start..self.index])) |id| {
985 result.id = id;1012 result.id = id;
986 }1013 }
987 },1014 },
988 State.LineCommentStart,1015 State.LineCommentStart, State.LineComment => {
989 State.LineComment => {
990 result.id = Token.Id.LineComment;1016 result.id = Token.Id.LineComment;
991 },1017 },
992 State.DocComment, State.DocCommentStart => {1018 State.DocComment, State.DocCommentStart => {
...@@ -1004,7 +1030,9 @@ pub const Tokenizer = struct {...@@ -1004,7 +1030,9 @@ pub const Tokenizer = struct {
1004 State.CharLiteralEscape1,1030 State.CharLiteralEscape1,
1005 State.CharLiteralEscape2,1031 State.CharLiteralEscape2,
1006 State.CharLiteralEnd,1032 State.CharLiteralEnd,
1007 State.StringLiteralBackslash => {1033 State.StringLiteralBackslash,
1034 State.LBracketStar,
1035 => {
1008 result.id = Token.Id.Invalid;1036 result.id = Token.Id.Invalid;
1009 },1037 },
10101038
...@@ -1020,6 +1048,9 @@ pub const Tokenizer = struct {...@@ -1020,6 +1048,9 @@ pub const Tokenizer = struct {
1020 State.Slash => {1048 State.Slash => {
1021 result.id = Token.Id.Slash;1049 result.id = Token.Id.Slash;
1022 },1050 },
1051 State.LBracket => {
1052 result.id = Token.Id.LBracket;
1053 },
1023 State.Zero => {1054 State.Zero => {
1024 result.id = Token.Id.IntegerLiteral;1055 result.id = Token.Id.IntegerLiteral;
1025 },1056 },
...@@ -1085,18 +1116,18 @@ pub const Tokenizer = struct {...@@ -1085,18 +1116,18 @@ pub const Tokenizer = struct {
1085 return result;1116 return result;
1086 }1117 }
10871118
1088 fn checkLiteralCharacter(self: &Tokenizer) void {1119 fn checkLiteralCharacter(self: *Tokenizer) void {
1089 if (self.pending_invalid_token != null) return;1120 if (self.pending_invalid_token != null) return;
1090 const invalid_length = self.getInvalidCharacterLength();1121 const invalid_length = self.getInvalidCharacterLength();
1091 if (invalid_length == 0) return;1122 if (invalid_length == 0) return;
1092 self.pending_invalid_token = Token {1123 self.pending_invalid_token = Token{
1093 .id = Token.Id.Invalid,1124 .id = Token.Id.Invalid,
1094 .start = self.index,1125 .start = self.index,
1095 .end = self.index + invalid_length,1126 .end = self.index + invalid_length,
1096 };1127 };
1097 }1128 }
10981129
1099 fn getInvalidCharacterLength(self: &Tokenizer) u3 {1130 fn getInvalidCharacterLength(self: *Tokenizer) u3 {
1100 const c0 = self.buffer[self.index];1131 const c0 = self.buffer[self.index];
1101 if (c0 < 0x80) {1132 if (c0 < 0x80) {
1102 if (c0 < 0x20 or c0 == 0x7f) {1133 if (c0 < 0x20 or c0 == 0x7f) {
...@@ -1112,7 +1143,7 @@ pub const Tokenizer = struct {...@@ -1112,7 +1143,7 @@ pub const Tokenizer = struct {
1112 if (self.index + length > self.buffer.len) {1143 if (self.index + length > self.buffer.len) {
1113 return u3(self.buffer.len - self.index);1144 return u3(self.buffer.len - self.index);
1114 }1145 }
1115 const bytes = self.buffer[self.index..self.index + length];1146 const bytes = self.buffer[self.index .. self.index + length];
1116 switch (length) {1147 switch (length) {
1117 2 => {1148 2 => {
1118 const value = std.unicode.utf8Decode2(bytes) catch return length;1149 const value = std.unicode.utf8Decode2(bytes) catch return length;
...@@ -1134,23 +1165,27 @@ pub const Tokenizer = struct {...@@ -1134,23 +1165,27 @@ pub const Tokenizer = struct {
1134 }1165 }
1135};1166};
11361167
1137
1138
1139test "tokenizer" {1168test "tokenizer" {
1140 testTokenize("test", []Token.Id {1169 testTokenize("test", []Token.Id{Token.Id.Keyword_test});
1141 Token.Id.Keyword_test,1170}
1171
1172test "tokenizer - unknown length pointer" {
1173 testTokenize(
1174 \\[*]u8
1175 , []Token.Id{
1176 Token.Id.BracketStarBracket,
1177 Token.Id.Identifier,
1142 });1178 });
1143}1179}
11441180
1145test "tokenizer - char literal with hex escape" {1181test "tokenizer - char literal with hex escape" {
1146 testTokenize( \\'\x1b'1182 testTokenize(
1147 , []Token.Id {1183 \\'\x1b'
1148 Token.Id.CharLiteral,1184 , []Token.Id{Token.Id.CharLiteral});
1149 });
1150}1185}
11511186
1152test "tokenizer - float literal e exponent" {1187test "tokenizer - float literal e exponent" {
1153 testTokenize("a = 4.94065645841246544177e-324;\n", []Token.Id {1188 testTokenize("a = 4.94065645841246544177e-324;\n", []Token.Id{
1154 Token.Id.Identifier,1189 Token.Id.Identifier,
1155 Token.Id.Equal,1190 Token.Id.Equal,
1156 Token.Id.FloatLiteral,1191 Token.Id.FloatLiteral,
...@@ -1159,7 +1194,7 @@ test "tokenizer - float literal e exponent" {...@@ -1159,7 +1194,7 @@ test "tokenizer - float literal e exponent" {
1159}1194}
11601195
1161test "tokenizer - float literal p exponent" {1196test "tokenizer - float literal p exponent" {
1162 testTokenize("a = 0x1.a827999fcef32p+1022;\n", []Token.Id {1197 testTokenize("a = 0x1.a827999fcef32p+1022;\n", []Token.Id{
1163 Token.Id.Identifier,1198 Token.Id.Identifier,
1164 Token.Id.Equal,1199 Token.Id.Equal,
1165 Token.Id.FloatLiteral,1200 Token.Id.FloatLiteral,
...@@ -1168,31 +1203,31 @@ test "tokenizer - float literal p exponent" {...@@ -1168,31 +1203,31 @@ test "tokenizer - float literal p exponent" {
1168}1203}
11691204
1170test "tokenizer - chars" {1205test "tokenizer - chars" {
1171 testTokenize("'c'", []Token.Id {Token.Id.CharLiteral});1206 testTokenize("'c'", []Token.Id{Token.Id.CharLiteral});
1172}1207}
11731208
1174test "tokenizer - invalid token characters" {1209test "tokenizer - invalid token characters" {
1175 testTokenize("#", []Token.Id{Token.Id.Invalid});1210 testTokenize("#", []Token.Id{Token.Id.Invalid});
1176 testTokenize("`", []Token.Id{Token.Id.Invalid});1211 testTokenize("`", []Token.Id{Token.Id.Invalid});
1177 testTokenize("'c", []Token.Id {Token.Id.Invalid});1212 testTokenize("'c", []Token.Id{Token.Id.Invalid});
1178 testTokenize("'", []Token.Id {Token.Id.Invalid});1213 testTokenize("'", []Token.Id{Token.Id.Invalid});
1179 testTokenize("''", []Token.Id {Token.Id.Invalid, Token.Id.Invalid});1214 testTokenize("''", []Token.Id{ Token.Id.Invalid, Token.Id.Invalid });
1180}1215}
11811216
1182test "tokenizer - invalid literal/comment characters" {1217test "tokenizer - invalid literal/comment characters" {
1183 testTokenize("\"\x00\"", []Token.Id {1218 testTokenize("\"\x00\"", []Token.Id{
1184 Token.Id { .StringLiteral = Token.StrLitKind.Normal },1219 Token.Id{ .StringLiteral = Token.StrLitKind.Normal },
1185 Token.Id.Invalid,1220 Token.Id.Invalid,
1186 });1221 });
1187 testTokenize("//\x00", []Token.Id {1222 testTokenize("//\x00", []Token.Id{
1188 Token.Id.LineComment,1223 Token.Id.LineComment,
1189 Token.Id.Invalid,1224 Token.Id.Invalid,
1190 });1225 });
1191 testTokenize("//\x1f", []Token.Id {1226 testTokenize("//\x1f", []Token.Id{
1192 Token.Id.LineComment,1227 Token.Id.LineComment,
1193 Token.Id.Invalid,1228 Token.Id.Invalid,
1194 });1229 });
1195 testTokenize("//\x7f", []Token.Id {1230 testTokenize("//\x7f", []Token.Id{
1196 Token.Id.LineComment,1231 Token.Id.LineComment,
1197 Token.Id.Invalid,1232 Token.Id.Invalid,
1198 });1233 });
...@@ -1261,18 +1296,16 @@ test "tokenizer - illegal unicode codepoints" {...@@ -1261,18 +1296,16 @@ test "tokenizer - illegal unicode codepoints" {
1261test "tokenizer - string identifier and builtin fns" {1296test "tokenizer - string identifier and builtin fns" {
1262 testTokenize(1297 testTokenize(
1263 \\const @"if" = @import("std");1298 \\const @"if" = @import("std");
1264 ,1299 , []Token.Id{
1265 []Token.Id{1300 Token.Id.Keyword_const,
1266 Token.Id.Keyword_const,1301 Token.Id.Identifier,
1267 Token.Id.Identifier,1302 Token.Id.Equal,
1268 Token.Id.Equal,1303 Token.Id.Builtin,
1269 Token.Id.Builtin,1304 Token.Id.LParen,
1270 Token.Id.LParen,1305 Token.Id{ .StringLiteral = Token.StrLitKind.Normal },
1271 Token.Id {.StringLiteral = Token.StrLitKind.Normal},1306 Token.Id.RParen,
1272 Token.Id.RParen,1307 Token.Id.Semicolon,
1273 Token.Id.Semicolon,1308 });
1274 }
1275 );
1276}1309}
12771310
1278test "tokenizer - pipe and then invalid" {1311test "tokenizer - pipe and then invalid" {
...@@ -1314,7 +1347,10 @@ fn testTokenize(source: []const u8, expected_tokens: []const Token.Id) void {...@@ -1314,7 +1347,10 @@ fn testTokenize(source: []const u8, expected_tokens: []const Token.Id) void {
1314 }1347 }
1315 switch (expected_token_id) {1348 switch (expected_token_id) {
1316 Token.Id.StringLiteral => |expected_kind| {1349 Token.Id.StringLiteral => |expected_kind| {
1317 std.debug.assert(expected_kind == switch (token.id) { Token.Id.StringLiteral => |kind| kind, else => unreachable });1350 std.debug.assert(expected_kind == switch (token.id) {
1351 Token.Id.StringLiteral => |kind| kind,
1352 else => unreachable,
1353 });
1318 },1354 },
1319 else => {},1355 else => {},
1320 }1356 }
test/assemble_and_link.zig+1-1
...@@ -1,7 +1,7 @@...@@ -1,7 +1,7 @@
1const builtin = @import("builtin");1const builtin = @import("builtin");
2const tests = @import("tests.zig");2const tests = @import("tests.zig");
33
4pub fn addCases(cases: &tests.CompareOutputContext) void {4pub fn addCases(cases: *tests.CompareOutputContext) void {
5 if (builtin.os == builtin.Os.linux and builtin.arch == builtin.Arch.x86_64) {5 if (builtin.os == builtin.Os.linux and builtin.arch == builtin.Arch.x86_64) {
6 cases.addAsm("hello world linux x86_64",6 cases.addAsm("hello world linux x86_64",
7 \\.text7 \\.text
test/build_examples.zig+1-1
...@@ -2,7 +2,7 @@ const tests = @import("tests.zig");...@@ -2,7 +2,7 @@ const tests = @import("tests.zig");
2const builtin = @import("builtin");2const builtin = @import("builtin");
3const is_windows = builtin.os == builtin.Os.windows;3const is_windows = builtin.os == builtin.Os.windows;
44
5pub fn addCases(cases: &tests.BuildExamplesContext) void {5pub fn addCases(cases: *tests.BuildExamplesContext) void {
6 cases.add("example/hello_world/hello.zig");6 cases.add("example/hello_world/hello.zig");
7 cases.addC("example/hello_world/hello_libc.zig");7 cases.addC("example/hello_world/hello_libc.zig");
8 cases.add("example/cat/main.zig");8 cases.add("example/cat/main.zig");
test/cases/align.zig+44-57
...@@ -5,7 +5,7 @@ var foo: u8 align(4) = 100;...@@ -5,7 +5,7 @@ var foo: u8 align(4) = 100;
55
6test "global variable alignment" {6test "global variable alignment" {
7 assert(@typeOf(&foo).alignment == 4);7 assert(@typeOf(&foo).alignment == 4);
8 assert(@typeOf(&foo) == &align(4) u8);8 assert(@typeOf(&foo) == *align(4) u8);
9 const slice = (&foo)[0..1];9 const slice = (&foo)[0..1];
10 assert(@typeOf(slice) == []align(4) u8);10 assert(@typeOf(slice) == []align(4) u8);
11}11}
...@@ -18,8 +18,8 @@ fn noop4() align(4) void {}...@@ -18,8 +18,8 @@ fn noop4() align(4) void {}
1818
19test "function alignment" {19test "function alignment" {
20 assert(derp() == 1234);20 assert(derp() == 1234);
21 assert(@typeOf(noop1) == fn() align(1) void);21 assert(@typeOf(noop1) == fn () align(1) void);
22 assert(@typeOf(noop4) == fn() align(4) void);22 assert(@typeOf(noop4) == fn () align(4) void);
23 noop1();23 noop1();
24 noop4();24 noop4();
25}25}
...@@ -30,7 +30,7 @@ var baz: packed struct {...@@ -30,7 +30,7 @@ var baz: packed struct {
30} = undefined;30} = undefined;
3131
32test "packed struct alignment" {32test "packed struct alignment" {
33 assert(@typeOf(&baz.b) == &align(1) u32);33 assert(@typeOf(&baz.b) == *align(1) u32);
34}34}
3535
36const blah: packed struct {36const blah: packed struct {
...@@ -40,11 +40,11 @@ const blah: packed struct {...@@ -40,11 +40,11 @@ const blah: packed struct {
40} = undefined;40} = undefined;
4141
42test "bit field alignment" {42test "bit field alignment" {
43 assert(@typeOf(&blah.b) == &align(1:3:6) const u3);43 assert(@typeOf(&blah.b) == *align(1:3:6) const u3);
44}44}
4545
46test "default alignment allows unspecified in type syntax" {46test "default alignment allows unspecified in type syntax" {
47 assert(&u32 == &align(@alignOf(u32)) u32);47 assert(*u32 == *align(@alignOf(u32)) u32);
48}48}
4949
50test "implicitly decreasing pointer alignment" {50test "implicitly decreasing pointer alignment" {
...@@ -53,7 +53,7 @@ test "implicitly decreasing pointer alignment" {...@@ -53,7 +53,7 @@ test "implicitly decreasing pointer alignment" {
53 assert(addUnaligned(&a, &b) == 7);53 assert(addUnaligned(&a, &b) == 7);
54}54}
5555
56fn addUnaligned(a: &align(1) const u32, b: &align(1) const u32) u32 {56fn addUnaligned(a: *align(1) const u32, b: *align(1) const u32) u32 {
57 return a.* + b.*;57 return a.* + b.*;
58}58}
5959
...@@ -70,13 +70,13 @@ test "specifying alignment allows pointer cast" {...@@ -70,13 +70,13 @@ test "specifying alignment allows pointer cast" {
70 testBytesAlign(0x33);70 testBytesAlign(0x33);
71}71}
72fn testBytesAlign(b: u8) void {72fn testBytesAlign(b: u8) void {
73 var bytes align(4) = []u8 {73 var bytes align(4) = []u8{
74 b,74 b,
75 b,75 b,
76 b,76 b,
77 b,77 b,
78 };78 };
79 const ptr = @ptrCast(&u32, &bytes[0]);79 const ptr = @ptrCast(*u32, &bytes[0]);
80 assert(ptr.* == 0x33333333);80 assert(ptr.* == 0x33333333);
81}81}
8282
...@@ -84,7 +84,7 @@ test "specifying alignment allows slice cast" {...@@ -84,7 +84,7 @@ test "specifying alignment allows slice cast" {
84 testBytesAlignSlice(0x33);84 testBytesAlignSlice(0x33);
85}85}
86fn testBytesAlignSlice(b: u8) void {86fn testBytesAlignSlice(b: u8) void {
87 var bytes align(4) = []u8 {87 var bytes align(4) = []u8{
88 b,88 b,
89 b,89 b,
90 b,90 b,
...@@ -99,15 +99,15 @@ test "@alignCast pointers" {...@@ -99,15 +99,15 @@ test "@alignCast pointers" {
99 expectsOnly1(&x);99 expectsOnly1(&x);
100 assert(x == 2);100 assert(x == 2);
101}101}
102fn expectsOnly1(x: &align(1) u32) void {102fn expectsOnly1(x: *align(1) u32) void {
103 expects4(@alignCast(4, x));103 expects4(@alignCast(4, x));
104}104}
105fn expects4(x: &align(4) u32) void {105fn expects4(x: *align(4) u32) void {
106 x.* += 1;106 x.* += 1;
107}107}
108108
109test "@alignCast slices" {109test "@alignCast slices" {
110 var array align(4) = []u32 {110 var array align(4) = []u32{
111 1,111 1,
112 1,112 1,
113 };113 };
...@@ -127,7 +127,7 @@ test "implicitly decreasing fn alignment" {...@@ -127,7 +127,7 @@ test "implicitly decreasing fn alignment" {
127 testImplicitlyDecreaseFnAlign(alignedBig, 5678);127 testImplicitlyDecreaseFnAlign(alignedBig, 5678);
128}128}
129129
130fn testImplicitlyDecreaseFnAlign(ptr: fn() align(1) i32, answer: i32) void {130fn testImplicitlyDecreaseFnAlign(ptr: fn () align(1) i32, answer: i32) void {
131 assert(ptr() == answer);131 assert(ptr() == answer);
132}132}
133133
...@@ -141,10 +141,10 @@ fn alignedBig() align(16) i32 {...@@ -141,10 +141,10 @@ fn alignedBig() align(16) i32 {
141test "@alignCast functions" {141test "@alignCast functions" {
142 assert(fnExpectsOnly1(simple4) == 0x19);142 assert(fnExpectsOnly1(simple4) == 0x19);
143}143}
144fn fnExpectsOnly1(ptr: fn() align(1) i32) i32 {144fn fnExpectsOnly1(ptr: fn () align(1) i32) i32 {
145 return fnExpects4(@alignCast(4, ptr));145 return fnExpects4(@alignCast(4, ptr));
146}146}
147fn fnExpects4(ptr: fn() align(4) i32) i32 {147fn fnExpects4(ptr: fn () align(4) i32) i32 {
148 return ptr();148 return ptr();
149}149}
150fn simple4() align(4) i32 {150fn simple4() align(4) i32 {
...@@ -163,58 +163,45 @@ fn whyWouldYouEverDoThis(comptime align_bytes: u8) align(align_bytes) u8 {...@@ -163,58 +163,45 @@ fn whyWouldYouEverDoThis(comptime align_bytes: u8) align(align_bytes) u8 {
163163
164test "@ptrCast preserves alignment of bigger source" {164test "@ptrCast preserves alignment of bigger source" {
165 var x: u32 align(16) = 1234;165 var x: u32 align(16) = 1234;
166 const ptr = @ptrCast(&u8, &x);166 const ptr = @ptrCast(*u8, &x);
167 assert(@typeOf(ptr) == &align(16) u8);167 assert(@typeOf(ptr) == *align(16) u8);
168}168}
169169
170test "compile-time known array index has best alignment possible" {170test "runtime known array index has best alignment possible" {
171 // take full advantage of over-alignment171 // take full advantage of over-alignment
172 var array align(4) = []u8 {172 var array align(4) = []u8{ 1, 2, 3, 4 };
173 1,173 assert(@typeOf(&array[0]) == *align(4) u8);
174 2,174 assert(@typeOf(&array[1]) == *u8);
175 3,175 assert(@typeOf(&array[2]) == *align(2) u8);
176 4,176 assert(@typeOf(&array[3]) == *u8);
177 };
178 assert(@typeOf(&array[0]) == &align(4) u8);
179 assert(@typeOf(&array[1]) == &u8);
180 assert(@typeOf(&array[2]) == &align(2) u8);
181 assert(@typeOf(&array[3]) == &u8);
182177
183 // because align is too small but we still figure out to use 2178 // because align is too small but we still figure out to use 2
184 var bigger align(2) = []u64 {179 var bigger align(2) = []u64{ 1, 2, 3, 4 };
185 1,180 assert(@typeOf(&bigger[0]) == *align(2) u64);
186 2,181 assert(@typeOf(&bigger[1]) == *align(2) u64);
187 3,182 assert(@typeOf(&bigger[2]) == *align(2) u64);
188 4,183 assert(@typeOf(&bigger[3]) == *align(2) u64);
189 };
190 assert(@typeOf(&bigger[0]) == &align(2) u64);
191 assert(@typeOf(&bigger[1]) == &align(2) u64);
192 assert(@typeOf(&bigger[2]) == &align(2) u64);
193 assert(@typeOf(&bigger[3]) == &align(2) u64);
194184
195 // because pointer is align 2 and u32 align % 2 == 0 we can assume align 2185 // because pointer is align 2 and u32 align % 2 == 0 we can assume align 2
196 var smaller align(2) = []u32 {186 var smaller align(2) = []u32{ 1, 2, 3, 4 };
197 1,187 comptime assert(@typeOf(smaller[0..]) == []align(2) u32);
198 2,188 comptime assert(@typeOf(smaller[0..].ptr) == [*]align(2) u32);
199 3,189 testIndex(smaller[0..].ptr, 0, *align(2) u32);
200 4,190 testIndex(smaller[0..].ptr, 1, *align(2) u32);
201 };191 testIndex(smaller[0..].ptr, 2, *align(2) u32);
202 testIndex(&smaller[0], 0, &align(2) u32);192 testIndex(smaller[0..].ptr, 3, *align(2) u32);
203 testIndex(&smaller[0], 1, &align(2) u32);
204 testIndex(&smaller[0], 2, &align(2) u32);
205 testIndex(&smaller[0], 3, &align(2) u32);
206193
207 // has to use ABI alignment because index known at runtime only194 // has to use ABI alignment because index known at runtime only
208 testIndex2(&array[0], 0, &u8);195 testIndex2(array[0..].ptr, 0, *u8);
209 testIndex2(&array[0], 1, &u8);196 testIndex2(array[0..].ptr, 1, *u8);
210 testIndex2(&array[0], 2, &u8);197 testIndex2(array[0..].ptr, 2, *u8);
211 testIndex2(&array[0], 3, &u8);198 testIndex2(array[0..].ptr, 3, *u8);
212}199}
213fn testIndex(smaller: &align(2) u32, index: usize, comptime T: type) void {200fn testIndex(smaller: [*]align(2) u32, index: usize, comptime T: type) void {
214 assert(@typeOf(&smaller[index]) == T);201 comptime assert(@typeOf(&smaller[index]) == T);
215}202}
216fn testIndex2(ptr: &align(4) u8, index: usize, comptime T: type) void {203fn testIndex2(ptr: [*]align(4) u8, index: usize, comptime T: type) void {
217 assert(@typeOf(&ptr[index]) == T);204 comptime assert(@typeOf(&ptr[index]) == T);
218}205}
219206
220test "alignstack" {207test "alignstack" {
test/cases/array.zig+5-7
...@@ -34,7 +34,7 @@ test "void arrays" {...@@ -34,7 +34,7 @@ test "void arrays" {
34}34}
3535
36test "array literal" {36test "array literal" {
37 const hex_mult = []u16 {37 const hex_mult = []u16{
38 4096,38 4096,
39 256,39 256,
40 16,40 16,
...@@ -54,7 +54,7 @@ test "array dot len const expr" {...@@ -54,7 +54,7 @@ test "array dot len const expr" {
54const ArrayDotLenConstExpr = struct {54const ArrayDotLenConstExpr = struct {
55 y: [some_array.len]u8,55 y: [some_array.len]u8,
56};56};
57const some_array = []u8 {57const some_array = []u8{
58 0,58 0,
59 1,59 1,
60 2,60 2,
...@@ -62,7 +62,7 @@ const some_array = []u8 {...@@ -62,7 +62,7 @@ const some_array = []u8 {
62};62};
6363
64test "nested arrays" {64test "nested arrays" {
65 const array_of_strings = [][]const u8 {65 const array_of_strings = [][]const u8{
66 "hello",66 "hello",
67 "this",67 "this",
68 "is",68 "is",
...@@ -86,9 +86,7 @@ const Str = struct {...@@ -86,9 +86,7 @@ const Str = struct {
86 a: []Sub,86 a: []Sub,
87};87};
88test "set global var array via slice embedded in struct" {88test "set global var array via slice embedded in struct" {
89 var s = Str {89 var s = Str{ .a = s_array[0..] };
90 .a = s_array[0..],
91 };
9290
93 s.a[0].b = 1;91 s.a[0].b = 1;
94 s.a[1].b = 2;92 s.a[1].b = 2;
...@@ -100,7 +98,7 @@ test "set global var array via slice embedded in struct" {...@@ -100,7 +98,7 @@ test "set global var array via slice embedded in struct" {
100}98}
10199
102test "array literal with specified size" {100test "array literal with specified size" {
103 var array = [2]u8 {101 var array = [2]u8{
104 1,102 1,
105 2,103 2,
106 };104 };
test/cases/atomics.zig+6-6
...@@ -34,7 +34,7 @@ test "atomicrmw and atomicload" {...@@ -34,7 +34,7 @@ test "atomicrmw and atomicload" {
34 testAtomicLoad(&data);34 testAtomicLoad(&data);
35}35}
3636
37fn testAtomicRmw(ptr: &u8) void {37fn testAtomicRmw(ptr: *u8) void {
38 const prev_value = @atomicRmw(u8, ptr, AtomicRmwOp.Xchg, 42, AtomicOrder.SeqCst);38 const prev_value = @atomicRmw(u8, ptr, AtomicRmwOp.Xchg, 42, AtomicOrder.SeqCst);
39 assert(prev_value == 200);39 assert(prev_value == 200);
40 comptime {40 comptime {
...@@ -45,7 +45,7 @@ fn testAtomicRmw(ptr: &u8) void {...@@ -45,7 +45,7 @@ fn testAtomicRmw(ptr: &u8) void {
45 }45 }
46}46}
4747
48fn testAtomicLoad(ptr: &u8) void {48fn testAtomicLoad(ptr: *u8) void {
49 const x = @atomicLoad(u8, ptr, AtomicOrder.SeqCst);49 const x = @atomicLoad(u8, ptr, AtomicOrder.SeqCst);
50 assert(x == 42);50 assert(x == 42);
51}51}
...@@ -54,18 +54,18 @@ test "cmpxchg with ptr" {...@@ -54,18 +54,18 @@ test "cmpxchg with ptr" {
54 var data1: i32 = 1234;54 var data1: i32 = 1234;
55 var data2: i32 = 5678;55 var data2: i32 = 5678;
56 var data3: i32 = 9101;56 var data3: i32 = 9101;
57 var x: &i32 = &data1;57 var x: *i32 = &data1;
58 if (@cmpxchgWeak(&i32, &x, &data2, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {58 if (@cmpxchgWeak(*i32, &x, &data2, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
59 assert(x1 == &data1);59 assert(x1 == &data1);
60 } else {60 } else {
61 @panic("cmpxchg should have failed");61 @panic("cmpxchg should have failed");
62 }62 }
6363
64 while (@cmpxchgWeak(&i32, &x, &data1, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {64 while (@cmpxchgWeak(*i32, &x, &data1, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
65 assert(x1 == &data1);65 assert(x1 == &data1);
66 }66 }
67 assert(x == &data3);67 assert(x == &data3);
6868
69 assert(@cmpxchgStrong(&i32, &x, &data3, &data2, AtomicOrder.SeqCst, AtomicOrder.SeqCst) == null);69 assert(@cmpxchgStrong(*i32, &x, &data3, &data2, AtomicOrder.SeqCst, AtomicOrder.SeqCst) == null);
70 assert(x == &data2);70 assert(x == &data2);
71}71}
test/cases/bugs/394.zig+2-4
...@@ -10,11 +10,9 @@ const S = struct {...@@ -10,11 +10,9 @@ const S = struct {
10const assert = @import("std").debug.assert;10const assert = @import("std").debug.assert;
1111
12test "bug 394 fixed" {12test "bug 394 fixed" {
13 const x = S {13 const x = S{
14 .x = 3,14 .x = 3,
15 .y = E {15 .y = E{ .B = 1 },
16 .B = 1,
17 },
18 };16 };
19 assert(x.x == 3);17 assert(x.x == 3);
20}18}
test/cases/bugs/655.zig+2-2
...@@ -3,10 +3,10 @@ const other_file = @import("655_other_file.zig");...@@ -3,10 +3,10 @@ const other_file = @import("655_other_file.zig");
33
4test "function with &const parameter with type dereferenced by namespace" {4test "function with &const parameter with type dereferenced by namespace" {
5 const x: other_file.Integer = 1234;5 const x: other_file.Integer = 1234;
6 comptime std.debug.assert(@typeOf(&x) == &const other_file.Integer);6 comptime std.debug.assert(@typeOf(&x) == *const other_file.Integer);
7 foo(x);7 foo(x);
8}8}
99
10fn foo(x: &const other_file.Integer) void {10fn foo(x: *const other_file.Integer) void {
11 std.debug.assert(x.* == 1234);11 std.debug.assert(x.* == 1234);
12}12}
test/cases/bugs/656.zig+2-4
...@@ -14,10 +14,8 @@ test "nullable if after an if in a switch prong of a switch with 2 prongs in an...@@ -14,10 +14,8 @@ test "nullable if after an if in a switch prong of a switch with 2 prongs in an
14}14}
1515
16fn foo(a: bool, b: bool) void {16fn foo(a: bool, b: bool) void {
17 var prefix_op = PrefixOp {17 var prefix_op = PrefixOp{
18 .AddrOf = Value {18 .AddrOf = Value{ .align_expr = 1234 },
19 .align_expr = 1234,
20 },
21 };19 };
22 if (a) {} else {20 if (a) {} else {
23 switch (prefix_op) {21 switch (prefix_op) {
test/cases/bugs/828.zig+5-9
...@@ -1,27 +1,23 @@...@@ -1,27 +1,23 @@
1const CountBy = struct {1const CountBy = struct {
2 a: usize,2 a: usize,
33
4 const One = CountBy {4 const One = CountBy{ .a = 1 };
5 .a = 1,
6 };
75
8 pub fn counter(self: &const CountBy) Counter {6 pub fn counter(self: *const CountBy) Counter {
9 return Counter {7 return Counter{ .i = 0 };
10 .i = 0,
11 };
12 }8 }
13};9};
1410
15const Counter = struct {11const Counter = struct {
16 i: usize,12 i: usize,
1713
18 pub fn count(self: &Counter) bool {14 pub fn count(self: *Counter) bool {
19 self.i += 1;15 self.i += 1;
20 return self.i <= 10;16 return self.i <= 10;
21 }17 }
22};18};
2319
24fn constCount(comptime cb: &const CountBy, comptime unused: u32) void {20fn constCount(comptime cb: *const CountBy, comptime unused: u32) void {
25 comptime {21 comptime {
26 var cnt = cb.counter();22 var cnt = cb.counter();
27 if (cnt.i != 0) @compileError("Counter instance reused!");23 if (cnt.i != 0) @compileError("Counter instance reused!");
test/cases/bugs/920.zig+4-4
...@@ -7,12 +7,12 @@ const ZigTable = struct {...@@ -7,12 +7,12 @@ const ZigTable = struct {
7 x: [257]f64,7 x: [257]f64,
8 f: [257]f64,8 f: [257]f64,
99
10 pdf: fn(f64) f64,10 pdf: fn (f64) f64,
11 is_symmetric: bool,11 is_symmetric: bool,
12 zero_case: fn(&Random, f64) f64,12 zero_case: fn (*Random, f64) f64,
13};13};
1414
15fn ZigTableGen(comptime is_symmetric: bool, comptime r: f64, comptime v: f64, comptime f: fn(f64) f64, comptime f_inv: fn(f64) f64, comptime zero_case: fn(&Random, f64) f64) ZigTable {15fn ZigTableGen(comptime is_symmetric: bool, comptime r: f64, comptime v: f64, comptime f: fn (f64) f64, comptime f_inv: fn (f64) f64, comptime zero_case: fn (*Random, f64) f64) ZigTable {
16 var tables: ZigTable = undefined;16 var tables: ZigTable = undefined;
1717
18 tables.is_symmetric = is_symmetric;18 tables.is_symmetric = is_symmetric;
...@@ -45,7 +45,7 @@ fn norm_f(x: f64) f64 {...@@ -45,7 +45,7 @@ fn norm_f(x: f64) f64 {
45fn norm_f_inv(y: f64) f64 {45fn norm_f_inv(y: f64) f64 {
46 return math.sqrt(-2.0 * math.ln(y));46 return math.sqrt(-2.0 * math.ln(y));
47}47}
48fn norm_zero_case(random: &Random, u: f64) f64 {48fn norm_zero_case(random: *Random, u: f64) f64 {
49 return 0.0;49 return 0.0;
50}50}
5151
test/cases/cast.zig+29-44
...@@ -3,20 +3,20 @@ const mem = @import("std").mem;...@@ -3,20 +3,20 @@ const mem = @import("std").mem;
33
4test "int to ptr cast" {4test "int to ptr cast" {
5 const x = usize(13);5 const x = usize(13);
6 const y = @intToPtr(&u8, x);6 const y = @intToPtr(*u8, x);
7 const z = @ptrToInt(y);7 const z = @ptrToInt(y);
8 assert(z == 13);8 assert(z == 13);
9}9}
1010
11test "integer literal to pointer cast" {11test "integer literal to pointer cast" {
12 const vga_mem = @intToPtr(&u16, 0xB8000);12 const vga_mem = @intToPtr(*u16, 0xB8000);
13 assert(@ptrToInt(vga_mem) == 0xB8000);13 assert(@ptrToInt(vga_mem) == 0xB8000);
14}14}
1515
16test "pointer reinterpret const float to int" {16test "pointer reinterpret const float to int" {
17 const float: f64 = 5.99999999999994648725e-01;17 const float: f64 = 5.99999999999994648725e-01;
18 const float_ptr = &float;18 const float_ptr = &float;
19 const int_ptr = @ptrCast(&const i32, float_ptr);19 const int_ptr = @ptrCast(*const i32, float_ptr);
20 const int_val = int_ptr.*;20 const int_val = int_ptr.*;
21 assert(int_val == 858993411);21 assert(int_val == 858993411);
22}22}
...@@ -28,32 +28,26 @@ test "implicitly cast a pointer to a const pointer of it" {...@@ -28,32 +28,26 @@ test "implicitly cast a pointer to a const pointer of it" {
28 assert(x == 2);28 assert(x == 2);
29}29}
3030
31fn funcWithConstPtrPtr(x: &const &i32) void {31fn funcWithConstPtrPtr(x: *const *i32) void {
32 x.*.* += 1;32 x.*.* += 1;
33}33}
3434
35test "implicitly cast a container to a const pointer of it" {35test "implicitly cast a container to a const pointer of it" {
36 const z = Struct(void) {36 const z = Struct(void){ .x = void{} };
37 .x = void{},
38 };
39 assert(0 == @sizeOf(@typeOf(z)));37 assert(0 == @sizeOf(@typeOf(z)));
40 assert(void{} == Struct(void).pointer(z).x);38 assert(void{} == Struct(void).pointer(z).x);
41 assert(void{} == Struct(void).pointer(&z).x);39 assert(void{} == Struct(void).pointer(&z).x);
42 assert(void{} == Struct(void).maybePointer(z).x);40 assert(void{} == Struct(void).maybePointer(z).x);
43 assert(void{} == Struct(void).maybePointer(&z).x);41 assert(void{} == Struct(void).maybePointer(&z).x);
44 assert(void{} == Struct(void).maybePointer(null).x);42 assert(void{} == Struct(void).maybePointer(null).x);
45 const s = Struct(u8) {43 const s = Struct(u8){ .x = 42 };
46 .x = 42,
47 };
48 assert(0 != @sizeOf(@typeOf(s)));44 assert(0 != @sizeOf(@typeOf(s)));
49 assert(42 == Struct(u8).pointer(s).x);45 assert(42 == Struct(u8).pointer(s).x);
50 assert(42 == Struct(u8).pointer(&s).x);46 assert(42 == Struct(u8).pointer(&s).x);
51 assert(42 == Struct(u8).maybePointer(s).x);47 assert(42 == Struct(u8).maybePointer(s).x);
52 assert(42 == Struct(u8).maybePointer(&s).x);48 assert(42 == Struct(u8).maybePointer(&s).x);
53 assert(0 == Struct(u8).maybePointer(null).x);49 assert(0 == Struct(u8).maybePointer(null).x);
54 const u = Union {50 const u = Union{ .x = 42 };
55 .x = 42,
56 };
57 assert(42 == Union.pointer(u).x);51 assert(42 == Union.pointer(u).x);
58 assert(42 == Union.pointer(&u).x);52 assert(42 == Union.pointer(&u).x);
59 assert(42 == Union.maybePointer(u).x);53 assert(42 == Union.maybePointer(u).x);
...@@ -72,14 +66,12 @@ fn Struct(comptime T: type) type {...@@ -72,14 +66,12 @@ fn Struct(comptime T: type) type {
72 const Self = this;66 const Self = this;
73 x: T,67 x: T,
7468
75 fn pointer(self: &const Self) Self {69 fn pointer(self: *const Self) Self {
76 return self.*;70 return self.*;
77 }71 }
7872
79 fn maybePointer(self: ?&const Self) Self {73 fn maybePointer(self: ?*const Self) Self {
80 const none = Self {74 const none = Self{ .x = if (T == void) void{} else 0 };
81 .x = if (T == void) void{} else 0,
82 };
83 return (self ?? &none).*;75 return (self ?? &none).*;
84 }76 }
85 };77 };
...@@ -88,14 +80,12 @@ fn Struct(comptime T: type) type {...@@ -88,14 +80,12 @@ fn Struct(comptime T: type) type {
88const Union = union {80const Union = union {
89 x: u8,81 x: u8,
9082
91 fn pointer(self: &const Union) Union {83 fn pointer(self: *const Union) Union {
92 return self.*;84 return self.*;
93 }85 }
9486
95 fn maybePointer(self: ?&const Union) Union {87 fn maybePointer(self: ?*const Union) Union {
96 const none = Union {88 const none = Union{ .x = 0 };
97 .x = 0,
98 };
99 return (self ?? &none).*;89 return (self ?? &none).*;
100 }90 }
101};91};
...@@ -104,11 +94,11 @@ const Enum = enum {...@@ -104,11 +94,11 @@ const Enum = enum {
104 None,94 None,
105 Some,95 Some,
10696
107 fn pointer(self: &const Enum) Enum {97 fn pointer(self: *const Enum) Enum {
108 return self.*;98 return self.*;
109 }99 }
110100
111 fn maybePointer(self: ?&const Enum) Enum {101 fn maybePointer(self: ?*const Enum) Enum {
112 return (self ?? &Enum.None).*;102 return (self ?? &Enum.None).*;
113 }103 }
114};104};
...@@ -117,22 +107,20 @@ test "implicitly cast indirect pointer to maybe-indirect pointer" {...@@ -117,22 +107,20 @@ test "implicitly cast indirect pointer to maybe-indirect pointer" {
117 const S = struct {107 const S = struct {
118 const Self = this;108 const Self = this;
119 x: u8,109 x: u8,
120 fn constConst(p: &const &const Self) u8 {110 fn constConst(p: *const *const Self) u8 {
121 return (p.*).x;111 return (p.*).x;
122 }112 }
123 fn maybeConstConst(p: ?&const &const Self) u8 {113 fn maybeConstConst(p: ?*const *const Self) u8 {
124 return ((??p).*).x;114 return ((??p).*).x;
125 }115 }
126 fn constConstConst(p: &const &const &const Self) u8 {116 fn constConstConst(p: *const *const *const Self) u8 {
127 return (p.*.*).x;117 return (p.*.*).x;
128 }118 }
129 fn maybeConstConstConst(p: ?&const &const &const Self) u8 {119 fn maybeConstConstConst(p: ?*const *const *const Self) u8 {
130 return ((??p).*.*).x;120 return ((??p).*.*).x;
131 }121 }
132 };122 };
133 const s = S {123 const s = S{ .x = 42 };
134 .x = 42,
135 };
136 const p = &s;124 const p = &s;
137 const q = &p;125 const q = &p;
138 const r = &q;126 const r = &q;
...@@ -178,12 +166,12 @@ fn testPeerResolveArrayConstSlice(b: bool) void {...@@ -178,12 +166,12 @@ fn testPeerResolveArrayConstSlice(b: bool) void {
178}166}
179167
180test "integer literal to &const int" {168test "integer literal to &const int" {
181 const x: &const i32 = 3;169 const x: *const i32 = 3;
182 assert(x.* == 3);170 assert(x.* == 3);
183}171}
184172
185test "string literal to &const []const u8" {173test "string literal to &const []const u8" {
186 const x: &const []const u8 = "hello";174 const x: *const []const u8 = "hello";
187 assert(mem.eql(u8, x.*, "hello"));175 assert(mem.eql(u8, x.*, "hello"));
188}176}
189177
...@@ -202,9 +190,7 @@ fn castToMaybeTypeError(z: i32) void {...@@ -202,9 +190,7 @@ fn castToMaybeTypeError(z: i32) void {
202 const f = z;190 const f = z;
203 const g: error!?i32 = f;191 const g: error!?i32 = f;
204192
205 const a = A {193 const a = A{ .a = z };
206 .a = z,
207 };
208 const b: error!?A = a;194 const b: error!?A = a;
209 assert((??(b catch unreachable)).a == 1);195 assert((??(b catch unreachable)).a == 1);
210}196}
...@@ -223,11 +209,11 @@ test "return null from fn() error!?&T" {...@@ -223,11 +209,11 @@ test "return null from fn() error!?&T" {
223 const b = returnNullLitFromMaybeTypeErrorRef();209 const b = returnNullLitFromMaybeTypeErrorRef();
224 assert((try a) == null and (try b) == null);210 assert((try a) == null and (try b) == null);
225}211}
226fn returnNullFromMaybeTypeErrorRef() error!?&A {212fn returnNullFromMaybeTypeErrorRef() error!?*A {
227 const a: ?&A = null;213 const a: ?*A = null;
228 return a;214 return a;
229}215}
230fn returnNullLitFromMaybeTypeErrorRef() error!?&A {216fn returnNullLitFromMaybeTypeErrorRef() error!?*A {
231 return null;217 return null;
232}218}
233219
...@@ -326,7 +312,7 @@ test "implicit cast from &const [N]T to []const T" {...@@ -326,7 +312,7 @@ test "implicit cast from &const [N]T to []const T" {
326fn testCastConstArrayRefToConstSlice() void {312fn testCastConstArrayRefToConstSlice() void {
327 const blah = "aoeu";313 const blah = "aoeu";
328 const const_array_ref = &blah;314 const const_array_ref = &blah;
329 assert(@typeOf(const_array_ref) == &const [4]u8);315 assert(@typeOf(const_array_ref) == *const [4]u8);
330 const slice: []const u8 = const_array_ref;316 const slice: []const u8 = const_array_ref;
331 assert(mem.eql(u8, slice, "aoeu"));317 assert(mem.eql(u8, slice, "aoeu"));
332}318}
...@@ -336,14 +322,13 @@ test "var args implicitly casts by value arg to const ref" {...@@ -336,14 +322,13 @@ test "var args implicitly casts by value arg to const ref" {
336}322}
337323
338fn foo(args: ...) void {324fn foo(args: ...) void {
339 assert(@typeOf(args[0]) == &const [5]u8);325 assert(@typeOf(args[0]) == *const [5]u8);
340}326}
341327
342test "peer type resolution: error and [N]T" {328test "peer type resolution: error and [N]T" {
343 // TODO: implicit error!T to error!U where T can implicitly cast to U329 // TODO: implicit error!T to error!U where T can implicitly cast to U
344 //assert(mem.eql(u8, try testPeerErrorAndArray(0), "OK"));330 //assert(mem.eql(u8, try testPeerErrorAndArray(0), "OK"));
345 //comptime assert(mem.eql(u8, try testPeerErrorAndArray(0), "OK"));331 //comptime assert(mem.eql(u8, try testPeerErrorAndArray(0), "OK"));
346
347 assert(mem.eql(u8, try testPeerErrorAndArray2(1), "OKK"));332 assert(mem.eql(u8, try testPeerErrorAndArray2(1), "OKK"));
348 comptime assert(mem.eql(u8, try testPeerErrorAndArray2(1), "OKK"));333 comptime assert(mem.eql(u8, try testPeerErrorAndArray2(1), "OKK"));
349}334}
...@@ -387,7 +372,7 @@ fn cast128Float(x: u128) f128 {...@@ -387,7 +372,7 @@ fn cast128Float(x: u128) f128 {
387}372}
388373
389test "const slice widen cast" {374test "const slice widen cast" {
390 const bytes align(4) = []u8 {375 const bytes align(4) = []u8{
391 0x12,376 0x12,
392 0x12,377 0x12,
393 0x12,378 0x12,
test/cases/const_slice_child.zig+5-4
...@@ -1,15 +1,16 @@...@@ -1,15 +1,16 @@
1const debug = @import("std").debug;1const debug = @import("std").debug;
2const assert = debug.assert;2const assert = debug.assert;
33
4var argv: &const &const u8 = undefined;4var argv: [*]const [*]const u8 = undefined;
55
6test "const slice child" {6test "const slice child" {
7 const strs = ([]&const u8) {7 const strs = ([][*]const u8){
8 c"one",8 c"one",
9 c"two",9 c"two",
10 c"three",10 c"three",
11 };11 };
12 argv = &strs[0];12 // TODO this should implicitly cast
13 argv = @ptrCast([*]const [*]const u8, &strs);
13 bar(strs.len);14 bar(strs.len);
14}15}
1516
...@@ -29,7 +30,7 @@ fn bar(argc: usize) void {...@@ -29,7 +30,7 @@ fn bar(argc: usize) void {
29 foo(args);30 foo(args);
30}31}
3132
32fn strlen(ptr: &const u8) usize {33fn strlen(ptr: [*]const u8) usize {
33 var count: usize = 0;34 var count: usize = 0;
34 while (ptr[count] != 0) : (count += 1) {}35 while (ptr[count] != 0) : (count += 1) {}
35 return count;36 return count;
test/cases/coroutines.zig+7-22
...@@ -10,7 +10,6 @@ test "create a coroutine and cancel it" {...@@ -10,7 +10,6 @@ test "create a coroutine and cancel it" {
10 cancel p;10 cancel p;
11 assert(x == 2);11 assert(x == 2);
12}12}
13
14async fn simpleAsyncFn() void {13async fn simpleAsyncFn() void {
15 x += 1;14 x += 1;
16 suspend;15 suspend;
...@@ -28,7 +27,6 @@ test "coroutine suspend, resume, cancel" {...@@ -28,7 +27,6 @@ test "coroutine suspend, resume, cancel" {
2827
29 assert(std.mem.eql(u8, points, "abcdefg"));28 assert(std.mem.eql(u8, points, "abcdefg"));
30}29}
31
32async fn testAsyncSeq() void {30async fn testAsyncSeq() void {
33 defer seq('e');31 defer seq('e');
3432
...@@ -36,7 +34,7 @@ async fn testAsyncSeq() void {...@@ -36,7 +34,7 @@ async fn testAsyncSeq() void {
36 suspend;34 suspend;
37 seq('d');35 seq('d');
38}36}
39var points = []u8 {0} ** "abcdefg".len;37var points = []u8{0} ** "abcdefg".len;
40var index: usize = 0;38var index: usize = 0;
4139
42fn seq(c: u8) void {40fn seq(c: u8) void {
...@@ -54,7 +52,6 @@ test "coroutine suspend with block" {...@@ -54,7 +52,6 @@ test "coroutine suspend with block" {
5452
55var a_promise: promise = undefined;53var a_promise: promise = undefined;
56var result = false;54var result = false;
57
58async fn testSuspendBlock() void {55async fn testSuspendBlock() void {
59 suspend |p| {56 suspend |p| {
60 comptime assert(@typeOf(p) == promise->void);57 comptime assert(@typeOf(p) == promise->void);
...@@ -75,7 +72,6 @@ test "coroutine await" {...@@ -75,7 +72,6 @@ test "coroutine await" {
75 assert(await_final_result == 1234);72 assert(await_final_result == 1234);
76 assert(std.mem.eql(u8, await_points, "abcdefghi"));73 assert(std.mem.eql(u8, await_points, "abcdefghi"));
77}74}
78
79async fn await_amain() void {75async fn await_amain() void {
80 await_seq('b');76 await_seq('b');
81 const p = async await_another() catch unreachable;77 const p = async await_another() catch unreachable;
...@@ -83,7 +79,6 @@ async fn await_amain() void {...@@ -83,7 +79,6 @@ async fn await_amain() void {
83 await_final_result = await p;79 await_final_result = await p;
84 await_seq('h');80 await_seq('h');
85}81}
86
87async fn await_another() i32 {82async fn await_another() i32 {
88 await_seq('c');83 await_seq('c');
89 suspend |p| {84 suspend |p| {
...@@ -94,7 +89,7 @@ async fn await_another() i32 {...@@ -94,7 +89,7 @@ async fn await_another() i32 {
94 return 1234;89 return 1234;
95}90}
9691
97var await_points = []u8 {0} ** "abcdefghi".len;92var await_points = []u8{0} ** "abcdefghi".len;
98var await_seq_index: usize = 0;93var await_seq_index: usize = 0;
9994
100fn await_seq(c: u8) void {95fn await_seq(c: u8) void {
...@@ -111,7 +106,6 @@ test "coroutine await early return" {...@@ -111,7 +106,6 @@ test "coroutine await early return" {
111 assert(early_final_result == 1234);106 assert(early_final_result == 1234);
112 assert(std.mem.eql(u8, early_points, "abcdef"));107 assert(std.mem.eql(u8, early_points, "abcdef"));
113}108}
114
115async fn early_amain() void {109async fn early_amain() void {
116 early_seq('b');110 early_seq('b');
117 const p = async early_another() catch unreachable;111 const p = async early_another() catch unreachable;
...@@ -119,13 +113,12 @@ async fn early_amain() void {...@@ -119,13 +113,12 @@ async fn early_amain() void {
119 early_final_result = await p;113 early_final_result = await p;
120 early_seq('e');114 early_seq('e');
121}115}
122
123async fn early_another() i32 {116async fn early_another() i32 {
124 early_seq('c');117 early_seq('c');
125 return 1234;118 return 1234;
126}119}
127120
128var early_points = []u8 {0} ** "abcdef".len;121var early_points = []u8{0} ** "abcdef".len;
129var early_seq_index: usize = 0;122var early_seq_index: usize = 0;
130123
131fn early_seq(c: u8) void {124fn early_seq(c: u8) void {
...@@ -141,7 +134,6 @@ test "coro allocation failure" {...@@ -141,7 +134,6 @@ test "coro allocation failure" {
141 error.OutOfMemory => {},134 error.OutOfMemory => {},
142 }135 }
143}136}
144
145async fn asyncFuncThatNeverGetsRun() void {137async fn asyncFuncThatNeverGetsRun() void {
146 @panic("coro frame allocation should fail");138 @panic("coro frame allocation should fail");
147}139}
...@@ -162,18 +154,15 @@ test "async function with dot syntax" {...@@ -162,18 +154,15 @@ test "async function with dot syntax" {
162test "async fn pointer in a struct field" {154test "async fn pointer in a struct field" {
163 var data: i32 = 1;155 var data: i32 = 1;
164 const Foo = struct {156 const Foo = struct {
165 bar: async<&std.mem.Allocator> fn(&i32) void,157 bar: async<*std.mem.Allocator> fn (*i32) void,
166 };
167 var foo = Foo {
168 .bar = simpleAsyncFn2,
169 };158 };
159 var foo = Foo{ .bar = simpleAsyncFn2 };
170 const p = (async<std.debug.global_allocator> foo.bar(&data)) catch unreachable;160 const p = (async<std.debug.global_allocator> foo.bar(&data)) catch unreachable;
171 assert(data == 2);161 assert(data == 2);
172 cancel p;162 cancel p;
173 assert(data == 4);163 assert(data == 4);
174}164}
175165async<*std.mem.Allocator> fn simpleAsyncFn2(y: *i32) void {
176async<&std.mem.Allocator> fn simpleAsyncFn2(y: &i32) void {
177 defer y.* += 2;166 defer y.* += 2;
178 y.* += 1;167 y.* += 1;
179 suspend;168 suspend;
...@@ -184,7 +173,6 @@ test "async fn with inferred error set" {...@@ -184,7 +173,6 @@ test "async fn with inferred error set" {
184 resume p;173 resume p;
185 cancel p;174 cancel p;
186}175}
187
188async fn failing() !void {176async fn failing() !void {
189 suspend;177 suspend;
190 return error.Fail;178 return error.Fail;
...@@ -208,12 +196,10 @@ test "error return trace across suspend points - async return" {...@@ -208,12 +196,10 @@ test "error return trace across suspend points - async return" {
208fn nonFailing() (promise->error!void) {196fn nonFailing() (promise->error!void) {
209 return async<std.debug.global_allocator> suspendThenFail() catch unreachable;197 return async<std.debug.global_allocator> suspendThenFail() catch unreachable;
210}198}
211
212async fn suspendThenFail() error!void {199async fn suspendThenFail() error!void {
213 suspend;200 suspend;
214 return error.Fail;201 return error.Fail;
215}202}
216
217async fn printTrace(p: promise->error!void) void {203async fn printTrace(p: promise->error!void) void {
218 (await p) catch |e| {204 (await p) catch |e| {
219 std.debug.assert(e == error.Fail);205 std.debug.assert(e == error.Fail);
...@@ -234,8 +220,7 @@ test "break from suspend" {...@@ -234,8 +220,7 @@ test "break from suspend" {
234 cancel p;220 cancel p;
235 std.debug.assert(my_result == 2);221 std.debug.assert(my_result == 2);
236}222}
237223async fn testBreakFromSuspend(my_result: *i32) void {
238async fn testBreakFromSuspend(my_result: &i32) void {
239 s: suspend |p| {224 s: suspend |p| {
240 break :s;225 break :s;
241 }226 }
test/cases/enum.zig+12-20
...@@ -2,11 +2,9 @@ const assert = @import("std").debug.assert;...@@ -2,11 +2,9 @@ const assert = @import("std").debug.assert;
2const mem = @import("std").mem;2const mem = @import("std").mem;
33
4test "enum type" {4test "enum type" {
5 const foo1 = Foo {5 const foo1 = Foo{ .One = 13 };
6 .One = 13,6 const foo2 = Foo{
7 };7 .Two = Point{
8 const foo2 = Foo {
9 .Two = Point {
10 .x = 1234,8 .x = 1234,
11 .y = 5678,9 .y = 5678,
12 },10 },
...@@ -48,30 +46,24 @@ const Bar = enum {...@@ -48,30 +46,24 @@ const Bar = enum {
48};46};
4947
50fn returnAnInt(x: i32) Foo {48fn returnAnInt(x: i32) Foo {
51 return Foo {49 return Foo{ .One = x };
52 .One = x,
53 };
54}50}
5551
56test "constant enum with payload" {52test "constant enum with payload" {
57 var empty = AnEnumWithPayload {53 var empty = AnEnumWithPayload{ .Empty = {} };
58 .Empty = {},54 var full = AnEnumWithPayload{ .Full = 13 };
59 };
60 var full = AnEnumWithPayload {
61 .Full = 13,
62 };
63 shouldBeEmpty(empty);55 shouldBeEmpty(empty);
64 shouldBeNotEmpty(full);56 shouldBeNotEmpty(full);
65}57}
6658
67fn shouldBeEmpty(x: &const AnEnumWithPayload) void {59fn shouldBeEmpty(x: *const AnEnumWithPayload) void {
68 switch (x.*) {60 switch (x.*) {
69 AnEnumWithPayload.Empty => {},61 AnEnumWithPayload.Empty => {},
70 else => unreachable,62 else => unreachable,
71 }63 }
72}64}
7365
74fn shouldBeNotEmpty(x: &const AnEnumWithPayload) void {66fn shouldBeNotEmpty(x: *const AnEnumWithPayload) void {
75 switch (x.*) {67 switch (x.*) {
76 AnEnumWithPayload.Empty => unreachable,68 AnEnumWithPayload.Empty => unreachable,
77 else => {},69 else => {},
...@@ -737,7 +729,7 @@ const BitFieldOfEnums = packed struct {...@@ -737,7 +729,7 @@ const BitFieldOfEnums = packed struct {
737 c: C,729 c: C,
738};730};
739731
740const bit_field_1 = BitFieldOfEnums {732const bit_field_1 = BitFieldOfEnums{
741 .a = A.Two,733 .a = A.Two,
742 .b = B.Three3,734 .b = B.Three3,
743 .c = C.Four4,735 .c = C.Four4,
...@@ -758,15 +750,15 @@ test "bit field access with enum fields" {...@@ -758,15 +750,15 @@ test "bit field access with enum fields" {
758 assert(data.b == B.Four3);750 assert(data.b == B.Four3);
759}751}
760752
761fn getA(data: &const BitFieldOfEnums) A {753fn getA(data: *const BitFieldOfEnums) A {
762 return data.a;754 return data.a;
763}755}
764756
765fn getB(data: &const BitFieldOfEnums) B {757fn getB(data: *const BitFieldOfEnums) B {
766 return data.b;758 return data.b;
767}759}
768760
769fn getC(data: &const BitFieldOfEnums) C {761fn getC(data: *const BitFieldOfEnums) C {
770 return data.c;762 return data.c;
771}763}
772764
test/cases/enum_with_members.zig+3-7
...@@ -6,7 +6,7 @@ const ET = union(enum) {...@@ -6,7 +6,7 @@ const ET = union(enum) {
6 SINT: i32,6 SINT: i32,
7 UINT: u32,7 UINT: u32,
88
9 pub fn print(a: &const ET, buf: []u8) error!usize {9 pub fn print(a: *const ET, buf: []u8) error!usize {
10 return switch (a.*) {10 return switch (a.*) {
11 ET.SINT => |x| fmt.formatIntBuf(buf, x, 10, false, 0),11 ET.SINT => |x| fmt.formatIntBuf(buf, x, 10, false, 0),
12 ET.UINT => |x| fmt.formatIntBuf(buf, x, 10, false, 0),12 ET.UINT => |x| fmt.formatIntBuf(buf, x, 10, false, 0),
...@@ -15,12 +15,8 @@ const ET = union(enum) {...@@ -15,12 +15,8 @@ const ET = union(enum) {
15};15};
1616
17test "enum with members" {17test "enum with members" {
18 const a = ET {18 const a = ET{ .SINT = -42 };
19 .SINT = -42,19 const b = ET{ .UINT = 42 };
20 };
21 const b = ET {
22 .UINT = 42,
23 };
24 var buf: [20]u8 = undefined;20 var buf: [20]u8 = undefined;
2521
26 assert((a.print(buf[0..]) catch unreachable) == 3);22 assert((a.print(buf[0..]) catch unreachable) == 3);
test/cases/error.zig+11-13
...@@ -92,7 +92,7 @@ test "error set type " {...@@ -92,7 +92,7 @@ test "error set type " {
92 comptime testErrorSetType();92 comptime testErrorSetType();
93}93}
9494
95const MyErrSet = error {95const MyErrSet = error{
96 OutOfMemory,96 OutOfMemory,
97 FileNotFound,97 FileNotFound,
98};98};
...@@ -114,11 +114,11 @@ test "explicit error set cast" {...@@ -114,11 +114,11 @@ test "explicit error set cast" {
114 comptime testExplicitErrorSetCast(Set1.A);114 comptime testExplicitErrorSetCast(Set1.A);
115}115}
116116
117const Set1 = error {117const Set1 = error{
118 A,118 A,
119 B,119 B,
120};120};
121const Set2 = error {121const Set2 = error{
122 A,122 A,
123 C,123 C,
124};124};
...@@ -134,8 +134,7 @@ test "comptime test error for empty error set" {...@@ -134,8 +134,7 @@ test "comptime test error for empty error set" {
134 comptime testComptimeTestErrorEmptySet(1234);134 comptime testComptimeTestErrorEmptySet(1234);
135}135}
136136
137const EmptyErrorSet = error {137const EmptyErrorSet = error{};
138};
139138
140fn testComptimeTestErrorEmptySet(x: EmptyErrorSet!i32) void {139fn testComptimeTestErrorEmptySet(x: EmptyErrorSet!i32) void {
141 if (x) |v| assert(v == 1234) else |err| @compileError("bad");140 if (x) |v| assert(v == 1234) else |err| @compileError("bad");
...@@ -151,9 +150,10 @@ test "comptime err to int of error set with only 1 possible value" {...@@ -151,9 +150,10 @@ test "comptime err to int of error set with only 1 possible value" {
151 testErrToIntWithOnePossibleValue(error.A, u32(error.A));150 testErrToIntWithOnePossibleValue(error.A, u32(error.A));
152 comptime testErrToIntWithOnePossibleValue(error.A, u32(error.A));151 comptime testErrToIntWithOnePossibleValue(error.A, u32(error.A));
153}152}
154fn testErrToIntWithOnePossibleValue(x: error {153fn testErrToIntWithOnePossibleValue(
155 A,154 x: error{A},
156}, comptime value: u32) void {155 comptime value: u32,
156) void {
157 if (u32(x) != value) {157 if (u32(x) != value) {
158 @compileError("bad");158 @compileError("bad");
159 }159 }
...@@ -193,20 +193,18 @@ fn entry() void {...@@ -193,20 +193,18 @@ fn entry() void {
193 foo2(bar2);193 foo2(bar2);
194}194}
195195
196fn foo2(f: fn() error!void) void {196fn foo2(f: fn () error!void) void {
197 const x = f();197 const x = f();
198}198}
199199
200fn bar2() (error {200fn bar2() (error{}!void) {}
201}!void) {}
202201
203test "error: Zero sized error set returned with value payload crash" {202test "error: Zero sized error set returned with value payload crash" {
204 _ = foo3(0);203 _ = foo3(0);
205 _ = comptime foo3(0);204 _ = comptime foo3(0);
206}205}
207206
208const Error = error {207const Error = error{};
209};
210fn foo3(b: usize) Error!usize {208fn foo3(b: usize) Error!usize {
211 return b;209 return b;
212}210}
test/cases/eval.zig+62-38
...@@ -72,12 +72,12 @@ const Point = struct {...@@ -72,12 +72,12 @@ const Point = struct {
72 x: i32,72 x: i32,
73 y: i32,73 y: i32,
74};74};
75const static_point_list = []Point {75const static_point_list = []Point{
76 makePoint(1, 2),76 makePoint(1, 2),
77 makePoint(3, 4),77 makePoint(3, 4),
78};78};
79fn makePoint(x: i32, y: i32) Point {79fn makePoint(x: i32, y: i32) Point {
80 return Point {80 return Point{
81 .x = x,81 .x = x,
82 .y = y,82 .y = y,
83 };83 };
...@@ -92,13 +92,11 @@ pub const Vec3 = struct {...@@ -92,13 +92,11 @@ pub const Vec3 = struct {
92 data: [3]f32,92 data: [3]f32,
93};93};
94pub fn vec3(x: f32, y: f32, z: f32) Vec3 {94pub fn vec3(x: f32, y: f32, z: f32) Vec3 {
95 return Vec3 {95 return Vec3{ .data = []f32{
96 .data = []f32 {96 x,
97 x,97 y,
98 y,98 z,
99 z,99 } };
100 },
101 };
102}100}
103101
104test "constant expressions" {102test "constant expressions" {
...@@ -117,22 +115,22 @@ const Vertex = struct {...@@ -117,22 +115,22 @@ const Vertex = struct {
117 g: f32,115 g: f32,
118 b: f32,116 b: f32,
119};117};
120const vertices = []Vertex {118const vertices = []Vertex{
121 Vertex {119 Vertex{
122 .x = -0.6,120 .x = -0.6,
123 .y = -0.4,121 .y = -0.4,
124 .r = 1.0,122 .r = 1.0,
125 .g = 0.0,123 .g = 0.0,
126 .b = 0.0,124 .b = 0.0,
127 },125 },
128 Vertex {126 Vertex{
129 .x = 0.6,127 .x = 0.6,
130 .y = -0.4,128 .y = -0.4,
131 .r = 0.0,129 .r = 0.0,
132 .g = 1.0,130 .g = 1.0,
133 .b = 0.0,131 .b = 0.0,
134 },132 },
135 Vertex {133 Vertex{
136 .x = 0.0,134 .x = 0.0,
137 .y = 0.6,135 .y = 0.6,
138 .r = 0.0,136 .r = 0.0,
...@@ -149,7 +147,7 @@ const StInitStrFoo = struct {...@@ -149,7 +147,7 @@ const StInitStrFoo = struct {
149 x: i32,147 x: i32,
150 y: bool,148 y: bool,
151};149};
152var st_init_str_foo = StInitStrFoo {150var st_init_str_foo = StInitStrFoo{
153 .x = 13,151 .x = 13,
154 .y = true,152 .y = true,
155};153};
...@@ -158,7 +156,7 @@ test "statically initalized array literal" {...@@ -158,7 +156,7 @@ test "statically initalized array literal" {
158 const y: [4]u8 = st_init_arr_lit_x;156 const y: [4]u8 = st_init_arr_lit_x;
159 assert(y[3] == 4);157 assert(y[3] == 4);
160}158}
161const st_init_arr_lit_x = []u8 {159const st_init_arr_lit_x = []u8{
162 1,160 1,
163 2,161 2,
164 3,162 3,
...@@ -217,19 +215,19 @@ test "inlined block and runtime block phi" {...@@ -217,19 +215,19 @@ test "inlined block and runtime block phi" {
217215
218const CmdFn = struct {216const CmdFn = struct {
219 name: []const u8,217 name: []const u8,
220 func: fn(i32) i32,218 func: fn (i32) i32,
221};219};
222220
223const cmd_fns = []CmdFn {221const cmd_fns = []CmdFn{
224 CmdFn {222 CmdFn{
225 .name = "one",223 .name = "one",
226 .func = one,224 .func = one,
227 },225 },
228 CmdFn {226 CmdFn{
229 .name = "two",227 .name = "two",
230 .func = two,228 .func = two,
231 },229 },
232 CmdFn {230 CmdFn{
233 .name = "three",231 .name = "three",
234 .func = three,232 .func = three,
235 },233 },
...@@ -284,14 +282,12 @@ fn fnWithFloatMode() f32 {...@@ -284,14 +282,12 @@ fn fnWithFloatMode() f32 {
284const SimpleStruct = struct {282const SimpleStruct = struct {
285 field: i32,283 field: i32,
286284
287 fn method(self: &const SimpleStruct) i32 {285 fn method(self: *const SimpleStruct) i32 {
288 return self.field + 3;286 return self.field + 3;
289 }287 }
290};288};
291289
292var simple_struct = SimpleStruct {290var simple_struct = SimpleStruct{ .field = 1234 };
293 .field = 1234,
294};
295291
296const bound_fn = simple_struct.method;292const bound_fn = simple_struct.method;
297293
...@@ -341,9 +337,7 @@ const Foo = struct {...@@ -341,9 +337,7 @@ const Foo = struct {
341 name: []const u8,337 name: []const u8,
342};338};
343339
344var foo_contents = Foo {340var foo_contents = Foo{ .name = "a" };
345 .name = "a",
346};
347const foo_ref = &foo_contents;341const foo_ref = &foo_contents;
348342
349test "create global array with for loop" {343test "create global array with for loop" {
...@@ -373,7 +367,7 @@ test "const global shares pointer with other same one" {...@@ -373,7 +367,7 @@ test "const global shares pointer with other same one" {
373 assertEqualPtrs(&hi1[0], &hi2[0]);367 assertEqualPtrs(&hi1[0], &hi2[0]);
374 comptime assert(&hi1[0] == &hi2[0]);368 comptime assert(&hi1[0] == &hi2[0]);
375}369}
376fn assertEqualPtrs(ptr1: &const u8, ptr2: &const u8) void {370fn assertEqualPtrs(ptr1: *const u8, ptr2: *const u8) void {
377 assert(ptr1 == ptr2);371 assert(ptr1 == ptr2);
378}372}
379373
...@@ -424,9 +418,9 @@ test "string literal used as comptime slice is memoized" {...@@ -424,9 +418,9 @@ test "string literal used as comptime slice is memoized" {
424}418}
425419
426test "comptime slice of undefined pointer of length 0" {420test "comptime slice of undefined pointer of length 0" {
427 const slice1 = (&i32)(undefined)[0..0];421 const slice1 = (*i32)(undefined)[0..0];
428 assert(slice1.len == 0);422 assert(slice1.len == 0);
429 const slice2 = (&i32)(undefined)[100..100];423 const slice2 = (*i32)(undefined)[100..100];
430 assert(slice2.len == 0);424 assert(slice2.len == 0);
431}425}
432426
...@@ -478,7 +472,7 @@ test "comptime function with mutable pointer is not memoized" {...@@ -478,7 +472,7 @@ test "comptime function with mutable pointer is not memoized" {
478 }472 }
479}473}
480474
481fn increment(value: &i32) void {475fn increment(value: *i32) void {
482 value.* += 1;476 value.* += 1;
483}477}
484478
...@@ -523,15 +517,13 @@ test "comptime slice of pointer preserves comptime var" {...@@ -523,15 +517,13 @@ test "comptime slice of pointer preserves comptime var" {
523const SingleFieldStruct = struct {517const SingleFieldStruct = struct {
524 x: i32,518 x: i32,
525519
526 fn read_x(self: &const SingleFieldStruct) i32 {520 fn read_x(self: *const SingleFieldStruct) i32 {
527 return self.x;521 return self.x;
528 }522 }
529};523};
530test "const ptr to comptime mutable data is not memoized" {524test "const ptr to comptime mutable data is not memoized" {
531 comptime {525 comptime {
532 var foo = SingleFieldStruct {526 var foo = SingleFieldStruct{ .x = 1 };
533 .x = 1,
534 };
535 assert(foo.read_x() == 1);527 assert(foo.read_x() == 1);
536 foo.x = 2;528 foo.x = 2;
537 assert(foo.read_x() == 2);529 assert(foo.read_x() == 2);
...@@ -574,9 +566,7 @@ pub const Info = struct {...@@ -574,9 +566,7 @@ pub const Info = struct {
574 version: u8,566 version: u8,
575};567};
576568
577pub const diamond_info = Info {569pub const diamond_info = Info{ .version = 0 };
578 .version = 0,
579};
580570
581test "comptime modification of const struct field" {571test "comptime modification of const struct field" {
582 comptime {572 comptime {
...@@ -586,3 +576,37 @@ test "comptime modification of const struct field" {...@@ -586,3 +576,37 @@ test "comptime modification of const struct field" {
586 assert(res.version == 1);576 assert(res.version == 1);
587 }577 }
588}578}
579
580test "pointer to type" {
581 comptime {
582 var T: type = i32;
583 assert(T == i32);
584 var ptr = &T;
585 assert(@typeOf(ptr) == *type);
586 ptr.* = f32;
587 assert(T == f32);
588 assert(*T == *f32);
589 }
590}
591
592test "slice of type" {
593 comptime {
594 var types_array = []type{ i32, f64, type };
595 for (types_array) |T, i| {
596 switch (i) {
597 0 => assert(T == i32),
598 1 => assert(T == f64),
599 2 => assert(T == type),
600 else => unreachable,
601 }
602 }
603 for (types_array[0..]) |T, i| {
604 switch (i) {
605 0 => assert(T == i32),
606 1 => assert(T == f64),
607 2 => assert(T == type),
608 else => unreachable,
609 }
610 }
611 }
612}
test/cases/field_parent_ptr.zig+3-3
...@@ -17,14 +17,14 @@ const Foo = struct {...@@ -17,14 +17,14 @@ const Foo = struct {
17 d: i32,17 d: i32,
18};18};
1919
20const foo = Foo {20const foo = Foo{
21 .a = true,21 .a = true,
22 .b = 0.123,22 .b = 0.123,
23 .c = 1234,23 .c = 1234,
24 .d = -10,24 .d = -10,
25};25};
2626
27fn testParentFieldPtr(c: &const i32) void {27fn testParentFieldPtr(c: *const i32) void {
28 assert(c == &foo.c);28 assert(c == &foo.c);
2929
30 const base = @fieldParentPtr(Foo, "c", c);30 const base = @fieldParentPtr(Foo, "c", c);
...@@ -32,7 +32,7 @@ fn testParentFieldPtr(c: &const i32) void {...@@ -32,7 +32,7 @@ fn testParentFieldPtr(c: &const i32) void {
32 assert(&base.c == c);32 assert(&base.c == c);
33}33}
3434
35fn testParentFieldPtrFirst(a: &const bool) void {35fn testParentFieldPtrFirst(a: *const bool) void {
36 assert(a == &foo.a);36 assert(a == &foo.a);
3737
38 const base = @fieldParentPtr(Foo, "a", a);38 const base = @fieldParentPtr(Foo, "a", a);
test/cases/fn.zig+2-2
...@@ -66,14 +66,14 @@ test "implicit cast function unreachable return" {...@@ -66,14 +66,14 @@ test "implicit cast function unreachable return" {
66 wantsFnWithVoid(fnWithUnreachable);66 wantsFnWithVoid(fnWithUnreachable);
67}67}
6868
69fn wantsFnWithVoid(f: fn() void) void {}69fn wantsFnWithVoid(f: fn () void) void {}
7070
71fn fnWithUnreachable() noreturn {71fn fnWithUnreachable() noreturn {
72 unreachable;72 unreachable;
73}73}
7474
75test "function pointers" {75test "function pointers" {
76 const fns = []@typeOf(fn1) {76 const fns = []@typeOf(fn1){
77 fn1,77 fn1,
78 fn2,78 fn2,
79 fn3,79 fn3,
test/cases/fn_in_struct_in_comptime.zig+3-3
...@@ -1,9 +1,9 @@...@@ -1,9 +1,9 @@
1const assert = @import("std").debug.assert;1const assert = @import("std").debug.assert;
22
3fn get_foo() fn(&u8)usize {3fn get_foo() fn (*u8) usize {
4 comptime {4 comptime {
5 return struct {5 return struct {
6 fn func(ptr: &u8) usize {6 fn func(ptr: *u8) usize {
7 var u = @ptrToInt(ptr);7 var u = @ptrToInt(ptr);
8 return u;8 return u;
9 }9 }
...@@ -13,5 +13,5 @@ fn get_foo() fn(&u8)usize {...@@ -13,5 +13,5 @@ fn get_foo() fn(&u8)usize {
1313
14test "define a function in an anonymous struct in comptime" {14test "define a function in an anonymous struct in comptime" {
15 const foo = get_foo();15 const foo = get_foo();
16 assert(foo(@intToPtr(&u8, 12345)) == 12345);16 assert(foo(@intToPtr(*u8, 12345)) == 12345);
17}17}
test/cases/for.zig+3-25
...@@ -3,7 +3,7 @@ const assert = std.debug.assert;...@@ -3,7 +3,7 @@ const assert = std.debug.assert;
3const mem = std.mem;3const mem = std.mem;
44
5test "continue in for loop" {5test "continue in for loop" {
6 const array = []i32 {6 const array = []i32{
7 1,7 1,
8 2,8 2,
9 3,9 3,
...@@ -35,34 +35,12 @@ fn mangleString(s: []u8) void {...@@ -35,34 +35,12 @@ fn mangleString(s: []u8) void {
35}35}
3636
37test "basic for loop" {37test "basic for loop" {
38 const expected_result = []u8 {38 const expected_result = []u8{ 9, 8, 7, 6, 0, 1, 2, 3, 9, 8, 7, 6, 0, 1, 2, 3 };
39 9,
40 8,
41 7,
42 6,
43 0,
44 1,
45 2,
46 3,
47 9,
48 8,
49 7,
50 6,
51 0,
52 1,
53 2,
54 3,
55 };
5639
57 var buffer: [expected_result.len]u8 = undefined;40 var buffer: [expected_result.len]u8 = undefined;
58 var buf_index: usize = 0;41 var buf_index: usize = 0;
5942
60 const array = []u8 {43 const array = []u8{ 9, 8, 7, 6 };
61 9,
62 8,
63 7,
64 6,
65 };
66 for (array) |item| {44 for (array) |item| {
67 buffer[buf_index] = item;45 buffer[buf_index] = item;
68 buf_index += 1;46 buf_index += 1;
test/cases/generics.zig+9-9
...@@ -81,11 +81,11 @@ test "function with return type type" {...@@ -81,11 +81,11 @@ test "function with return type type" {
81}81}
8282
83test "generic struct" {83test "generic struct" {
84 var a1 = GenNode(i32) {84 var a1 = GenNode(i32){
85 .value = 13,85 .value = 13,
86 .next = null,86 .next = null,
87 };87 };
88 var b1 = GenNode(bool) {88 var b1 = GenNode(bool){
89 .value = true,89 .value = true,
90 .next = null,90 .next = null,
91 };91 };
...@@ -96,8 +96,8 @@ test "generic struct" {...@@ -96,8 +96,8 @@ test "generic struct" {
96fn GenNode(comptime T: type) type {96fn GenNode(comptime T: type) type {
97 return struct {97 return struct {
98 value: T,98 value: T,
99 next: ?&GenNode(T),99 next: ?*GenNode(T),
100 fn getVal(n: &const GenNode(T)) T {100 fn getVal(n: *const GenNode(T)) T {
101 return n.value;101 return n.value;
102 }102 }
103 };103 };
...@@ -120,20 +120,20 @@ fn aGenericFn(comptime T: type, comptime a: T, b: T) T {...@@ -120,20 +120,20 @@ fn aGenericFn(comptime T: type, comptime a: T, b: T) T {
120}120}
121121
122test "generic fn with implicit cast" {122test "generic fn with implicit cast" {
123 assert(getFirstByte(u8, []u8 {13}) == 13);123 assert(getFirstByte(u8, []u8{13}) == 13);
124 assert(getFirstByte(u16, []u16 {124 assert(getFirstByte(u16, []u16{
125 0,125 0,
126 13,126 13,
127 }) == 0);127 }) == 0);
128}128}
129fn getByte(ptr: ?&const u8) u8 {129fn getByte(ptr: ?*const u8) u8 {
130 return (??ptr).*;130 return (??ptr).*;
131}131}
132fn getFirstByte(comptime T: type, mem: []const T) u8 {132fn getFirstByte(comptime T: type, mem: []const T) u8 {
133 return getByte(@ptrCast(&const u8, &mem[0]));133 return getByte(@ptrCast(*const u8, &mem[0]));
134}134}
135135
136const foos = []fn(var) bool {136const foos = []fn (var) bool{
137 foo1,137 foo1,
138 foo2,138 foo2,
139};139};
test/cases/incomplete_struct_param_tld.zig+5-7
...@@ -11,21 +11,19 @@ const B = struct {...@@ -11,21 +11,19 @@ const B = struct {
11const C = struct {11const C = struct {
12 x: i32,12 x: i32,
1313
14 fn d(c: &const C) i32 {14 fn d(c: *const C) i32 {
15 return c.x;15 return c.x;
16 }16 }
17};17};
1818
19fn foo(a: &const A) i32 {19fn foo(a: *const A) i32 {
20 return a.b.c.d();20 return a.b.c.d();
21}21}
2222
23test "incomplete struct param top level declaration" {23test "incomplete struct param top level declaration" {
24 const a = A {24 const a = A{
25 .b = B {25 .b = B{
26 .c = C {26 .c = C{ .x = 13 },
27 .x = 13,
28 },
29 },27 },
30 };28 };
31 assert(foo(a) == 13);29 assert(foo(a) == 13);
test/cases/math.zig+28-10
...@@ -28,13 +28,27 @@ fn testDivision() void {...@@ -28,13 +28,27 @@ fn testDivision() void {
28 assert(divTrunc(f32, -5.0, 3.0) == -1.0);28 assert(divTrunc(f32, -5.0, 3.0) == -1.0);
2929
30 comptime {30 comptime {
31 assert(1194735857077236777412821811143690633098347576 % 508740759824825164163191790951174292733114988 == 177254337427586449086438229241342047632117600);31 assert(
32 assert(@rem(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -177254337427586449086438229241342047632117600);32 1194735857077236777412821811143690633098347576 % 508740759824825164163191790951174292733114988 == 177254337427586449086438229241342047632117600,
33 assert(1194735857077236777412821811143690633098347576 / 508740759824825164163191790951174292733114988 == 2);33 );
34 assert(@divTrunc(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -2);34 assert(
35 assert(@divTrunc(1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == -2);35 @rem(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -177254337427586449086438229241342047632117600,
36 assert(@divTrunc(-1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == 2);36 );
37 assert(4126227191251978491697987544882340798050766755606969681711 % 10 == 1);37 assert(
38 1194735857077236777412821811143690633098347576 / 508740759824825164163191790951174292733114988 == 2,
39 );
40 assert(
41 @divTrunc(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -2,
42 );
43 assert(
44 @divTrunc(1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == -2,
45 );
46 assert(
47 @divTrunc(-1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == 2,
48 );
49 assert(
50 4126227191251978491697987544882340798050766755606969681711 % 10 == 1,
51 );
38 }52 }
39}53}
40fn div(comptime T: type, a: T, b: T) T {54fn div(comptime T: type, a: T, b: T) T {
...@@ -197,7 +211,7 @@ fn test_u64_div() void {...@@ -197,7 +211,7 @@ fn test_u64_div() void {
197 assert(result.remainder == 100663296);211 assert(result.remainder == 100663296);
198}212}
199fn divWithResult(a: u64, b: u64) DivResult {213fn divWithResult(a: u64, b: u64) DivResult {
200 return DivResult {214 return DivResult{
201 .quotient = a / b,215 .quotient = a / b,
202 .remainder = a % b,216 .remainder = a % b,
203 };217 };
...@@ -324,8 +338,12 @@ test "big number addition" {...@@ -324,8 +338,12 @@ test "big number addition" {
324338
325test "big number multiplication" {339test "big number multiplication" {
326 comptime {340 comptime {
327 assert(45960427431263824329884196484953148229 * 128339149605334697009938835852565949723 == 5898522172026096622534201617172456926982464453350084962781392314016180490567);341 assert(
328 assert(594491908217841670578297176641415611445982232488944558774612 * 390603545391089362063884922208143568023166603618446395589768 == 232210647056203049913662402532976186578842425262306016094292237500303028346593132411865381225871291702600263463125370016);342 45960427431263824329884196484953148229 * 128339149605334697009938835852565949723 == 5898522172026096622534201617172456926982464453350084962781392314016180490567,
343 );
344 assert(
345 594491908217841670578297176641415611445982232488944558774612 * 390603545391089362063884922208143568023166603618446395589768 == 232210647056203049913662402532976186578842425262306016094292237500303028346593132411865381225871291702600263463125370016,
346 );
329 }347 }
330}348}
331349
test/cases/misc.zig+47-56
...@@ -171,8 +171,8 @@ test "memcpy and memset intrinsics" {...@@ -171,8 +171,8 @@ test "memcpy and memset intrinsics" {
171 var foo: [20]u8 = undefined;171 var foo: [20]u8 = undefined;
172 var bar: [20]u8 = undefined;172 var bar: [20]u8 = undefined;
173173
174 @memset(&foo[0], 'A', foo.len);174 @memset(foo[0..].ptr, 'A', foo.len);
175 @memcpy(&bar[0], &foo[0], bar.len);175 @memcpy(bar[0..].ptr, foo[0..].ptr, bar.len);
176176
177 if (bar[11] != 'A') unreachable;177 if (bar[11] != 'A') unreachable;
178}178}
...@@ -194,7 +194,7 @@ test "slicing" {...@@ -194,7 +194,7 @@ test "slicing" {
194 if (slice.len != 5) unreachable;194 if (slice.len != 5) unreachable;
195195
196 const ptr = &slice[0];196 const ptr = &slice[0];
197 if (ptr[0] != 1234) unreachable;197 if (ptr.* != 1234) unreachable;
198198
199 var slice_rest = array[10..];199 var slice_rest = array[10..];
200 if (slice_rest.len != 10) unreachable;200 if (slice_rest.len != 10) unreachable;
...@@ -232,7 +232,7 @@ test "string escapes" {...@@ -232,7 +232,7 @@ test "string escapes" {
232}232}
233233
234test "multiline string" {234test "multiline string" {
235 const s1 = 235 const s1 =
236 \\one236 \\one
237 \\two)237 \\two)
238 \\three238 \\three
...@@ -242,7 +242,7 @@ test "multiline string" {...@@ -242,7 +242,7 @@ test "multiline string" {
242}242}
243243
244test "multiline C string" {244test "multiline C string" {
245 const s1 = 245 const s1 =
246 c\\one246 c\\one
247 c\\two)247 c\\two)
248 c\\three248 c\\three
...@@ -252,20 +252,20 @@ test "multiline C string" {...@@ -252,20 +252,20 @@ test "multiline C string" {
252}252}
253253
254test "type equality" {254test "type equality" {
255 assert(&const u8 != &u8);255 assert(*const u8 != *u8);
256}256}
257257
258const global_a: i32 = 1234;258const global_a: i32 = 1234;
259const global_b: &const i32 = &global_a;259const global_b: *const i32 = &global_a;
260const global_c: &const f32 = @ptrCast(&const f32, global_b);260const global_c: *const f32 = @ptrCast(*const f32, global_b);
261test "compile time global reinterpret" {261test "compile time global reinterpret" {
262 const d = @ptrCast(&const i32, global_c);262 const d = @ptrCast(*const i32, global_c);
263 assert(d.* == 1234);263 assert(d.* == 1234);
264}264}
265265
266test "explicit cast maybe pointers" {266test "explicit cast maybe pointers" {
267 const a: ?&i32 = undefined;267 const a: ?*i32 = undefined;
268 const b: ?&f32 = @ptrCast(?&f32, a);268 const b: ?*f32 = @ptrCast(?*f32, a);
269}269}
270270
271test "generic malloc free" {271test "generic malloc free" {
...@@ -274,7 +274,7 @@ test "generic malloc free" {...@@ -274,7 +274,7 @@ test "generic malloc free" {
274}274}
275var some_mem: [100]u8 = undefined;275var some_mem: [100]u8 = undefined;
276fn memAlloc(comptime T: type, n: usize) error![]T {276fn memAlloc(comptime T: type, n: usize) error![]T {
277 return @ptrCast(&T, &some_mem[0])[0..n];277 return @ptrCast(*T, &some_mem[0])[0..n];
278}278}
279fn memFree(comptime T: type, memory: []T) void {}279fn memFree(comptime T: type, memory: []T) void {}
280280
...@@ -350,16 +350,14 @@ const Test3Point = struct {...@@ -350,16 +350,14 @@ const Test3Point = struct {
350 x: i32,350 x: i32,
351 y: i32,351 y: i32,
352};352};
353const test3_foo = Test3Foo {353const test3_foo = Test3Foo{
354 .Three = Test3Point {354 .Three = Test3Point{
355 .x = 3,355 .x = 3,
356 .y = 4,356 .y = 4,
357 },357 },
358};358};
359const test3_bar = Test3Foo {359const test3_bar = Test3Foo{ .Two = 13 };
360 .Two = 13,360fn test3_1(f: *const Test3Foo) void {
361};
362fn test3_1(f: &const Test3Foo) void {
363 switch (f.*) {361 switch (f.*) {
364 Test3Foo.Three => |pt| {362 Test3Foo.Three => |pt| {
365 assert(pt.x == 3);363 assert(pt.x == 3);
...@@ -368,7 +366,7 @@ fn test3_1(f: &const Test3Foo) void {...@@ -368,7 +366,7 @@ fn test3_1(f: &const Test3Foo) void {
368 else => unreachable,366 else => unreachable,
369 }367 }
370}368}
371fn test3_2(f: &const Test3Foo) void {369fn test3_2(f: *const Test3Foo) void {
372 switch (f.*) {370 switch (f.*) {
373 Test3Foo.Two => |x| {371 Test3Foo.Two => |x| {
374 assert(x == 13);372 assert(x == 13);
...@@ -395,7 +393,7 @@ test "pointer comparison" {...@@ -395,7 +393,7 @@ test "pointer comparison" {
395 const b = &a;393 const b = &a;
396 assert(ptrEql(b, b));394 assert(ptrEql(b, b));
397}395}
398fn ptrEql(a: &const []const u8, b: &const []const u8) bool {396fn ptrEql(a: *const []const u8, b: *const []const u8) bool {
399 return a == b;397 return a == b;
400}398}
401399
...@@ -417,7 +415,7 @@ test "C string concatenation" {...@@ -417,7 +415,7 @@ test "C string concatenation" {
417415
418test "cast slice to u8 slice" {416test "cast slice to u8 slice" {
419 assert(@sizeOf(i32) == 4);417 assert(@sizeOf(i32) == 4);
420 var big_thing_array = []i32 {418 var big_thing_array = []i32{
421 1,419 1,
422 2,420 2,
423 3,421 3,
...@@ -448,26 +446,27 @@ fn testPointerToVoidReturnType() error!void {...@@ -448,26 +446,27 @@ fn testPointerToVoidReturnType() error!void {
448 return a.*;446 return a.*;
449}447}
450const test_pointer_to_void_return_type_x = void{};448const test_pointer_to_void_return_type_x = void{};
451fn testPointerToVoidReturnType2() &const void {449fn testPointerToVoidReturnType2() *const void {
452 return &test_pointer_to_void_return_type_x;450 return &test_pointer_to_void_return_type_x;
453}451}
454452
455test "non const ptr to aliased type" {453test "non const ptr to aliased type" {
456 const int = i32;454 const int = i32;
457 assert(?&int == ?&i32);455 assert(?*int == ?*i32);
458}456}
459457
460test "array 2D const double ptr" {458test "array 2D const double ptr" {
461 const rect_2d_vertexes = [][1]f32 {459 const rect_2d_vertexes = [][1]f32{
462 []f32 {1.0},460 []f32{1.0},
463 []f32 {2.0},461 []f32{2.0},
464 };462 };
465 testArray2DConstDoublePtr(&rect_2d_vertexes[0][0]);463 testArray2DConstDoublePtr(&rect_2d_vertexes[0][0]);
466}464}
467465
468fn testArray2DConstDoublePtr(ptr: &const f32) void {466fn testArray2DConstDoublePtr(ptr: *const f32) void {
469 assert(ptr[0] == 1.0);467 const ptr2 = @ptrCast([*]const f32, ptr);
470 assert(ptr[1] == 2.0);468 assert(ptr2[0] == 1.0);
469 assert(ptr2[1] == 2.0);
471}470}
472471
473const Tid = builtin.TypeId;472const Tid = builtin.TypeId;
...@@ -499,7 +498,7 @@ test "@typeId" {...@@ -499,7 +498,7 @@ test "@typeId" {
499 assert(@typeId(u64) == Tid.Int);498 assert(@typeId(u64) == Tid.Int);
500 assert(@typeId(f32) == Tid.Float);499 assert(@typeId(f32) == Tid.Float);
501 assert(@typeId(f64) == Tid.Float);500 assert(@typeId(f64) == Tid.Float);
502 assert(@typeId(&f32) == Tid.Pointer);501 assert(@typeId(*f32) == Tid.Pointer);
503 assert(@typeId([2]u8) == Tid.Array);502 assert(@typeId([2]u8) == Tid.Array);
504 assert(@typeId(AStruct) == Tid.Struct);503 assert(@typeId(AStruct) == Tid.Struct);
505 assert(@typeId(@typeOf(1)) == Tid.IntLiteral);504 assert(@typeId(@typeOf(1)) == Tid.IntLiteral);
...@@ -513,7 +512,7 @@ test "@typeId" {...@@ -513,7 +512,7 @@ test "@typeId" {
513 assert(@typeId(@typeOf(AUnionEnum.One)) == Tid.Enum);512 assert(@typeId(@typeOf(AUnionEnum.One)) == Tid.Enum);
514 assert(@typeId(AUnionEnum) == Tid.Union);513 assert(@typeId(AUnionEnum) == Tid.Union);
515 assert(@typeId(AUnion) == Tid.Union);514 assert(@typeId(AUnion) == Tid.Union);
516 assert(@typeId(fn() void) == Tid.Fn);515 assert(@typeId(fn () void) == Tid.Fn);
517 assert(@typeId(@typeOf(builtin)) == Tid.Namespace);516 assert(@typeId(@typeOf(builtin)) == Tid.Namespace);
518 assert(@typeId(@typeOf(x: {517 assert(@typeId(@typeOf(x: {
519 break :x this;518 break :x this;
...@@ -542,7 +541,7 @@ test "@typeName" {...@@ -542,7 +541,7 @@ test "@typeName" {
542 };541 };
543 comptime {542 comptime {
544 assert(mem.eql(u8, @typeName(i64), "i64"));543 assert(mem.eql(u8, @typeName(i64), "i64"));
545 assert(mem.eql(u8, @typeName(&usize), "&usize"));544 assert(mem.eql(u8, @typeName(*usize), "*usize"));
546 // https://github.com/ziglang/zig/issues/675545 // https://github.com/ziglang/zig/issues/675
547 assert(mem.eql(u8, @typeName(TypeFromFn(u8)), "TypeFromFn(u8)"));546 assert(mem.eql(u8, @typeName(TypeFromFn(u8)), "TypeFromFn(u8)"));
548 assert(mem.eql(u8, @typeName(Struct), "Struct"));547 assert(mem.eql(u8, @typeName(Struct), "Struct"));
...@@ -557,7 +556,7 @@ fn TypeFromFn(comptime T: type) type {...@@ -557,7 +556,7 @@ fn TypeFromFn(comptime T: type) type {
557556
558test "volatile load and store" {557test "volatile load and store" {
559 var number: i32 = 1234;558 var number: i32 = 1234;
560 const ptr = (&volatile i32)(&number);559 const ptr = (*volatile i32)(&number);
561 ptr.* += 1;560 ptr.* += 1;
562 assert(ptr.* == 1235);561 assert(ptr.* == 1235);
563}562}
...@@ -565,7 +564,7 @@ test "volatile load and store" {...@@ -565,7 +564,7 @@ test "volatile load and store" {
565test "slice string literal has type []const u8" {564test "slice string literal has type []const u8" {
566 comptime {565 comptime {
567 assert(@typeOf("aoeu"[0..]) == []const u8);566 assert(@typeOf("aoeu"[0..]) == []const u8);
568 const array = []i32 {567 const array = []i32{
569 1,568 1,
570 2,569 2,
571 3,570 3,
...@@ -581,40 +580,36 @@ test "global variable initialized to global variable array element" {...@@ -581,40 +580,36 @@ test "global variable initialized to global variable array element" {
581const GDTEntry = struct {580const GDTEntry = struct {
582 field: i32,581 field: i32,
583};582};
584var gdt = []GDTEntry {583var gdt = []GDTEntry{
585 GDTEntry {584 GDTEntry{ .field = 1 },
586 .field = 1,585 GDTEntry{ .field = 2 },
587 },
588 GDTEntry {
589 .field = 2,
590 },
591};586};
592var global_ptr = &gdt[0];587var global_ptr = &gdt[0];
593588
594// can't really run this test but we can make sure it has no compile error589// can't really run this test but we can make sure it has no compile error
595// and generates code590// and generates code
596const vram = @intToPtr(&volatile u8, 0x20000000)[0..0x8000];591const vram = @intToPtr(*volatile u8, 0x20000000)[0..0x8000];
597export fn writeToVRam() void {592export fn writeToVRam() void {
598 vram[0] = 'X';593 vram[0] = 'X';
599}594}
600595
601test "pointer child field" {596test "pointer child field" {
602 assert((&u32).Child == u32);597 assert((*u32).Child == u32);
603}598}
604599
605const OpaqueA = @OpaqueType();600const OpaqueA = @OpaqueType();
606const OpaqueB = @OpaqueType();601const OpaqueB = @OpaqueType();
607test "@OpaqueType" {602test "@OpaqueType" {
608 assert(&OpaqueA != &OpaqueB);603 assert(*OpaqueA != *OpaqueB);
609 assert(mem.eql(u8, @typeName(OpaqueA), "OpaqueA"));604 assert(mem.eql(u8, @typeName(OpaqueA), "OpaqueA"));
610 assert(mem.eql(u8, @typeName(OpaqueB), "OpaqueB"));605 assert(mem.eql(u8, @typeName(OpaqueB), "OpaqueB"));
611}606}
612607
613test "variable is allowed to be a pointer to an opaque type" {608test "variable is allowed to be a pointer to an opaque type" {
614 var x: i32 = 1234;609 var x: i32 = 1234;
615 _ = hereIsAnOpaqueType(@ptrCast(&OpaqueA, &x));610 _ = hereIsAnOpaqueType(@ptrCast(*OpaqueA, &x));
616}611}
617fn hereIsAnOpaqueType(ptr: &OpaqueA) &OpaqueA {612fn hereIsAnOpaqueType(ptr: *OpaqueA) *OpaqueA {
618 var a = ptr;613 var a = ptr;
619 return a;614 return a;
620}615}
...@@ -648,9 +643,7 @@ fn testStructInFn() void {...@@ -648,9 +643,7 @@ fn testStructInFn() void {
648 kind: BlockKind,643 kind: BlockKind,
649 };644 };
650645
651 var block = Block {646 var block = Block{ .kind = 1234 };
652 .kind = 1234,
653 };
654647
655 block.kind += 1;648 block.kind += 1;
656649
...@@ -694,15 +687,13 @@ const PackedEnum = packed enum {...@@ -694,15 +687,13 @@ const PackedEnum = packed enum {
694};687};
695688
696test "packed struct, enum, union parameters in extern function" {689test "packed struct, enum, union parameters in extern function" {
697 testPackedStuff(PackedStruct {690 testPackedStuff(PackedStruct{
698 .a = 1,691 .a = 1,
699 .b = 2,692 .b = 2,
700 }, PackedUnion {693 }, PackedUnion{ .a = 1 }, PackedEnum.A);
701 .a = 1,
702 }, PackedEnum.A);
703}694}
704695
705export fn testPackedStuff(a: &const PackedStruct, b: &const PackedUnion, c: PackedEnum) void {}696export fn testPackedStuff(a: *const PackedStruct, b: *const PackedUnion, c: PackedEnum) void {}
706697
707test "slicing zero length array" {698test "slicing zero length array" {
708 const s1 = ""[0..];699 const s1 = ""[0..];
...@@ -713,8 +704,8 @@ test "slicing zero length array" {...@@ -713,8 +704,8 @@ test "slicing zero length array" {
713 assert(mem.eql(u32, s2, []u32{}));704 assert(mem.eql(u32, s2, []u32{}));
714}705}
715706
716const addr1 = @ptrCast(&const u8, emptyFn);707const addr1 = @ptrCast(*const u8, emptyFn);
717test "comptime cast fn to ptr" {708test "comptime cast fn to ptr" {
718 const addr2 = @ptrCast(&const u8, emptyFn);709 const addr2 = @ptrCast(*const u8, emptyFn);
719 comptime assert(addr1 == addr2);710 comptime assert(addr1 == addr2);
720}711}
test/cases/null.zig+3-5
...@@ -58,14 +58,14 @@ fn foo(x: ?i32) ?bool {...@@ -58,14 +58,14 @@ fn foo(x: ?i32) ?bool {
58}58}
5959
60test "if var maybe pointer" {60test "if var maybe pointer" {
61 assert(shouldBeAPlus1(Particle {61 assert(shouldBeAPlus1(Particle{
62 .a = 14,62 .a = 14,
63 .b = 1,63 .b = 1,
64 .c = 1,64 .c = 1,
65 .d = 1,65 .d = 1,
66 }) == 15);66 }) == 15);
67}67}
68fn shouldBeAPlus1(p: &const Particle) u64 {68fn shouldBeAPlus1(p: *const Particle) u64 {
69 var maybe_particle: ?Particle = p.*;69 var maybe_particle: ?Particle = p.*;
70 if (maybe_particle) |*particle| {70 if (maybe_particle) |*particle| {
71 particle.a += 1;71 particle.a += 1;
...@@ -92,9 +92,7 @@ test "null literal outside function" {...@@ -92,9 +92,7 @@ test "null literal outside function" {
92const SillyStruct = struct {92const SillyStruct = struct {
93 context: ?i32,93 context: ?i32,
94};94};
95const here_is_a_null_literal = SillyStruct {95const here_is_a_null_literal = SillyStruct{ .context = null };
96 .context = null,
97};
9896
99test "test null runtime" {97test "test null runtime" {
100 testTestNullRuntime(null);98 testTestNullRuntime(null);
test/cases/pointers.zig+30
...@@ -12,3 +12,33 @@ fn testDerefPtr() void {...@@ -12,3 +12,33 @@ fn testDerefPtr() void {
12 y.* += 1;12 y.* += 1;
13 assert(x == 1235);13 assert(x == 1235);
14}14}
15
16test "pointer arithmetic" {
17 var ptr = c"abcd";
18
19 assert(ptr[0] == 'a');
20 ptr += 1;
21 assert(ptr[0] == 'b');
22 ptr += 1;
23 assert(ptr[0] == 'c');
24 ptr += 1;
25 assert(ptr[0] == 'd');
26 ptr += 1;
27 assert(ptr[0] == 0);
28 ptr -= 1;
29 assert(ptr[0] == 'd');
30 ptr -= 1;
31 assert(ptr[0] == 'c');
32 ptr -= 1;
33 assert(ptr[0] == 'b');
34 ptr -= 1;
35 assert(ptr[0] == 'a');
36}
37
38test "double pointer parsing" {
39 comptime assert(PtrOf(PtrOf(i32)) == **i32);
40}
41
42fn PtrOf(comptime T: type) type {
43 return *T;
44}
test/cases/reflection.zig+2-2
...@@ -5,7 +5,7 @@ const reflection = this;...@@ -5,7 +5,7 @@ const reflection = this;
5test "reflection: array, pointer, nullable, error union type child" {5test "reflection: array, pointer, nullable, error union type child" {
6 comptime {6 comptime {
7 assert(([10]u8).Child == u8);7 assert(([10]u8).Child == u8);
8 assert((&u8).Child == u8);8 assert((*u8).Child == u8);
9 assert((error!u8).Payload == u8);9 assert((error!u8).Payload == u8);
10 assert((?u8).Child == u8);10 assert((?u8).Child == u8);
11 }11 }
...@@ -59,7 +59,7 @@ test "reflection: enum member types and names" {...@@ -59,7 +59,7 @@ test "reflection: enum member types and names" {
59}59}
6060
61test "reflection: @field" {61test "reflection: @field" {
62 var f = Foo {62 var f = Foo{
63 .one = 42,63 .one = 42,
64 .two = true,64 .two = true,
65 .three = void{},65 .three = void{},
test/cases/slice.zig+2-2
...@@ -1,7 +1,7 @@...@@ -1,7 +1,7 @@
1const assert = @import("std").debug.assert;1const assert = @import("std").debug.assert;
2const mem = @import("std").mem;2const mem = @import("std").mem;
33
4const x = @intToPtr(&i32, 0x1000)[0..0x500];4const x = @intToPtr(*i32, 0x1000)[0..0x500];
5const y = x[0x100..];5const y = x[0x100..];
6test "compile time slice of pointer to hard coded address" {6test "compile time slice of pointer to hard coded address" {
7 assert(@ptrToInt(x.ptr) == 0x1000);7 assert(@ptrToInt(x.ptr) == 0x1000);
...@@ -18,7 +18,7 @@ test "slice child property" {...@@ -18,7 +18,7 @@ test "slice child property" {
18}18}
1919
20test "runtime safety lets us slice from len..len" {20test "runtime safety lets us slice from len..len" {
21 var an_array = []u8 {21 var an_array = []u8{
22 1,22 1,
23 2,23 2,
24 3,24 3,
test/cases/struct.zig+31-41
...@@ -27,7 +27,7 @@ test "invake static method in global scope" {...@@ -27,7 +27,7 @@ test "invake static method in global scope" {
27}27}
2828
29test "void struct fields" {29test "void struct fields" {
30 const foo = VoidStructFieldsFoo {30 const foo = VoidStructFieldsFoo{
31 .a = void{},31 .a = void{},
32 .b = 1,32 .b = 1,
33 .c = void{},33 .c = void{},
...@@ -43,7 +43,7 @@ const VoidStructFieldsFoo = struct {...@@ -43,7 +43,7 @@ const VoidStructFieldsFoo = struct {
4343
44test "structs" {44test "structs" {
45 var foo: StructFoo = undefined;45 var foo: StructFoo = undefined;
46 @memset(@ptrCast(&u8, &foo), 0, @sizeOf(StructFoo));46 @memset(@ptrCast([*]u8, &foo), 0, @sizeOf(StructFoo));
47 foo.a += 1;47 foo.a += 1;
48 foo.b = foo.a == 1;48 foo.b = foo.a == 1;
49 testFoo(foo);49 testFoo(foo);
...@@ -55,16 +55,16 @@ const StructFoo = struct {...@@ -55,16 +55,16 @@ const StructFoo = struct {
55 b: bool,55 b: bool,
56 c: f32,56 c: f32,
57};57};
58fn testFoo(foo: &const StructFoo) void {58fn testFoo(foo: *const StructFoo) void {
59 assert(foo.b);59 assert(foo.b);
60}60}
61fn testMutation(foo: &StructFoo) void {61fn testMutation(foo: *StructFoo) void {
62 foo.c = 100;62 foo.c = 100;
63}63}
6464
65const Node = struct {65const Node = struct {
66 val: Val,66 val: Val,
67 next: &Node,67 next: *Node,
68};68};
6969
70const Val = struct {70const Val = struct {
...@@ -96,62 +96,52 @@ test "struct byval assign" {...@@ -96,62 +96,52 @@ test "struct byval assign" {
96}96}
9797
98fn structInitializer() void {98fn structInitializer() void {
99 const val = Val {99 const val = Val{ .x = 42 };
100 .x = 42,
101 };
102 assert(val.x == 42);100 assert(val.x == 42);
103}101}
104102
105test "fn call of struct field" {103test "fn call of struct field" {
106 assert(callStructField(Foo {104 assert(callStructField(Foo{ .ptr = aFunc }) == 13);
107 .ptr = aFunc,
108 }) == 13);
109}105}
110106
111const Foo = struct {107const Foo = struct {
112 ptr: fn() i32,108 ptr: fn () i32,
113};109};
114110
115fn aFunc() i32 {111fn aFunc() i32 {
116 return 13;112 return 13;
117}113}
118114
119fn callStructField(foo: &const Foo) i32 {115fn callStructField(foo: *const Foo) i32 {
120 return foo.ptr();116 return foo.ptr();
121}117}
122118
123test "store member function in variable" {119test "store member function in variable" {
124 const instance = MemberFnTestFoo {120 const instance = MemberFnTestFoo{ .x = 1234 };
125 .x = 1234,
126 };
127 const memberFn = MemberFnTestFoo.member;121 const memberFn = MemberFnTestFoo.member;
128 const result = memberFn(instance);122 const result = memberFn(instance);
129 assert(result == 1234);123 assert(result == 1234);
130}124}
131const MemberFnTestFoo = struct {125const MemberFnTestFoo = struct {
132 x: i32,126 x: i32,
133 fn member(foo: &const MemberFnTestFoo) i32 {127 fn member(foo: *const MemberFnTestFoo) i32 {
134 return foo.x;128 return foo.x;
135 }129 }
136};130};
137131
138test "call member function directly" {132test "call member function directly" {
139 const instance = MemberFnTestFoo {133 const instance = MemberFnTestFoo{ .x = 1234 };
140 .x = 1234,
141 };
142 const result = MemberFnTestFoo.member(instance);134 const result = MemberFnTestFoo.member(instance);
143 assert(result == 1234);135 assert(result == 1234);
144}136}
145137
146test "member functions" {138test "member functions" {
147 const r = MemberFnRand {139 const r = MemberFnRand{ .seed = 1234 };
148 .seed = 1234,
149 };
150 assert(r.getSeed() == 1234);140 assert(r.getSeed() == 1234);
151}141}
152const MemberFnRand = struct {142const MemberFnRand = struct {
153 seed: u32,143 seed: u32,
154 pub fn getSeed(r: &const MemberFnRand) u32 {144 pub fn getSeed(r: *const MemberFnRand) u32 {
155 return r.seed;145 return r.seed;
156 }146 }
157};147};
...@@ -165,7 +155,7 @@ const Bar = struct {...@@ -165,7 +155,7 @@ const Bar = struct {
165 y: i32,155 y: i32,
166};156};
167fn makeBar(x: i32, y: i32) Bar {157fn makeBar(x: i32, y: i32) Bar {
168 return Bar {158 return Bar{
169 .x = x,159 .x = x,
170 .y = y,160 .y = y,
171 };161 };
...@@ -176,7 +166,7 @@ test "empty struct method call" {...@@ -176,7 +166,7 @@ test "empty struct method call" {
176 assert(es.method() == 1234);166 assert(es.method() == 1234);
177}167}
178const EmptyStruct = struct {168const EmptyStruct = struct {
179 fn method(es: &const EmptyStruct) i32 {169 fn method(es: *const EmptyStruct) i32 {
180 return 1234;170 return 1234;
181 }171 }
182};172};
...@@ -190,7 +180,7 @@ fn testReturnEmptyStructFromFn() EmptyStruct2 {...@@ -190,7 +180,7 @@ fn testReturnEmptyStructFromFn() EmptyStruct2 {
190}180}
191181
192test "pass slice of empty struct to fn" {182test "pass slice of empty struct to fn" {
193 assert(testPassSliceOfEmptyStructToFn([]EmptyStruct2 {EmptyStruct2{}}) == 1);183 assert(testPassSliceOfEmptyStructToFn([]EmptyStruct2{EmptyStruct2{}}) == 1);
194}184}
195fn testPassSliceOfEmptyStructToFn(slice: []const EmptyStruct2) usize {185fn testPassSliceOfEmptyStructToFn(slice: []const EmptyStruct2) usize {
196 return slice.len;186 return slice.len;
...@@ -202,7 +192,7 @@ const APackedStruct = packed struct {...@@ -202,7 +192,7 @@ const APackedStruct = packed struct {
202};192};
203193
204test "packed struct" {194test "packed struct" {
205 var foo = APackedStruct {195 var foo = APackedStruct{
206 .x = 1,196 .x = 1,
207 .y = 2,197 .y = 2,
208 };198 };
...@@ -217,7 +207,7 @@ const BitField1 = packed struct {...@@ -217,7 +207,7 @@ const BitField1 = packed struct {
217 c: u2,207 c: u2,
218};208};
219209
220const bit_field_1 = BitField1 {210const bit_field_1 = BitField1{
221 .a = 1,211 .a = 1,
222 .b = 2,212 .b = 2,
223 .c = 3,213 .c = 3,
...@@ -238,15 +228,15 @@ test "bit field access" {...@@ -238,15 +228,15 @@ test "bit field access" {
238 assert(data.b == 3);228 assert(data.b == 3);
239}229}
240230
241fn getA(data: &const BitField1) u3 {231fn getA(data: *const BitField1) u3 {
242 return data.a;232 return data.a;
243}233}
244234
245fn getB(data: &const BitField1) u3 {235fn getB(data: *const BitField1) u3 {
246 return data.b;236 return data.b;
247}237}
248238
249fn getC(data: &const BitField1) u2 {239fn getC(data: *const BitField1) u2 {
250 return data.c;240 return data.c;
251}241}
252242
...@@ -267,7 +257,7 @@ test "packed struct 24bits" {...@@ -267,7 +257,7 @@ test "packed struct 24bits" {
267 assert(@sizeOf(Foo96Bits) == 12);257 assert(@sizeOf(Foo96Bits) == 12);
268 }258 }
269259
270 var value = Foo96Bits {260 var value = Foo96Bits{
271 .a = 0,261 .a = 0,
272 .b = 0,262 .b = 0,
273 .c = 0,263 .c = 0,
...@@ -310,9 +300,9 @@ test "packed array 24bits" {...@@ -310,9 +300,9 @@ test "packed array 24bits" {
310 assert(@sizeOf(FooArray24Bits) == 2 + 2 * 3 + 2);300 assert(@sizeOf(FooArray24Bits) == 2 + 2 * 3 + 2);
311 }301 }
312302
313 var bytes = []u8 {0} ** (@sizeOf(FooArray24Bits) + 1);303 var bytes = []u8{0} ** (@sizeOf(FooArray24Bits) + 1);
314 bytes[bytes.len - 1] = 0xaa;304 bytes[bytes.len - 1] = 0xaa;
315 const ptr = &([]FooArray24Bits)(bytes[0..bytes.len - 1])[0];305 const ptr = &([]FooArray24Bits)(bytes[0 .. bytes.len - 1])[0];
316 assert(ptr.a == 0);306 assert(ptr.a == 0);
317 assert(ptr.b[0].field == 0);307 assert(ptr.b[0].field == 0);
318 assert(ptr.b[1].field == 0);308 assert(ptr.b[1].field == 0);
...@@ -360,7 +350,7 @@ test "aligned array of packed struct" {...@@ -360,7 +350,7 @@ test "aligned array of packed struct" {
360 assert(@sizeOf(FooArrayOfAligned) == 2 * 2);350 assert(@sizeOf(FooArrayOfAligned) == 2 * 2);
361 }351 }
362352
363 var bytes = []u8 {0xbb} ** @sizeOf(FooArrayOfAligned);353 var bytes = []u8{0xbb} ** @sizeOf(FooArrayOfAligned);
364 const ptr = &([]FooArrayOfAligned)(bytes[0..bytes.len])[0];354 const ptr = &([]FooArrayOfAligned)(bytes[0..bytes.len])[0];
365355
366 assert(ptr.a[0].a == 0xbb);356 assert(ptr.a[0].a == 0xbb);
...@@ -370,11 +360,11 @@ test "aligned array of packed struct" {...@@ -370,11 +360,11 @@ test "aligned array of packed struct" {
370}360}
371361
372test "runtime struct initialization of bitfield" {362test "runtime struct initialization of bitfield" {
373 const s1 = Nibbles {363 const s1 = Nibbles{
374 .x = x1,364 .x = x1,
375 .y = x1,365 .y = x1,
376 };366 };
377 const s2 = Nibbles {367 const s2 = Nibbles{
378 .x = u4(x2),368 .x = u4(x2),
379 .y = u4(x2),369 .y = u4(x2),
380 };370 };
...@@ -406,8 +396,8 @@ const Bitfields = packed struct {...@@ -406,8 +396,8 @@ const Bitfields = packed struct {
406test "native bit field understands endianness" {396test "native bit field understands endianness" {
407 var all: u64 = 0x7765443322221111;397 var all: u64 = 0x7765443322221111;
408 var bytes: [8]u8 = undefined;398 var bytes: [8]u8 = undefined;
409 @memcpy(&bytes[0], @ptrCast(&u8, &all), 8);399 @memcpy(bytes[0..].ptr, @ptrCast([*]u8, &all), 8);
410 var bitfields = @ptrCast(&Bitfields, &bytes[0]).*;400 var bitfields = @ptrCast(*Bitfields, bytes[0..].ptr).*;
411401
412 assert(bitfields.f1 == 0x1111);402 assert(bitfields.f1 == 0x1111);
413 assert(bitfields.f2 == 0x2222);403 assert(bitfields.f2 == 0x2222);
...@@ -425,7 +415,7 @@ test "align 1 field before self referential align 8 field as slice return type"...@@ -425,7 +415,7 @@ test "align 1 field before self referential align 8 field as slice return type"
425415
426const Expr = union(enum) {416const Expr = union(enum) {
427 Literal: u8,417 Literal: u8,
428 Question: &Expr,418 Question: *Expr,
429};419};
430420
431fn alloc(comptime T: type) []T {421fn alloc(comptime T: type) []T {
test/cases/struct_contains_null_ptr_itself.zig+2-2
...@@ -2,13 +2,13 @@ const std = @import("std");...@@ -2,13 +2,13 @@ const std = @import("std");
2const assert = std.debug.assert;2const assert = std.debug.assert;
33
4test "struct contains null pointer which contains original struct" {4test "struct contains null pointer which contains original struct" {
5 var x: ?&NodeLineComment = null;5 var x: ?*NodeLineComment = null;
6 assert(x == null);6 assert(x == null);
7}7}
88
9pub const Node = struct {9pub const Node = struct {
10 id: Id,10 id: Id,
11 comment: ?&NodeLineComment,11 comment: ?*NodeLineComment,
1212
13 pub const Id = enum {13 pub const Id = enum {
14 Root,14 Root,
test/cases/struct_contains_slice_of_itself.zig+8-8
...@@ -6,31 +6,31 @@ const Node = struct {...@@ -6,31 +6,31 @@ const Node = struct {
6};6};
77
8test "struct contains slice of itself" {8test "struct contains slice of itself" {
9 var other_nodes = []Node {9 var other_nodes = []Node{
10 Node {10 Node{
11 .payload = 31,11 .payload = 31,
12 .children = []Node{},12 .children = []Node{},
13 },13 },
14 Node {14 Node{
15 .payload = 32,15 .payload = 32,
16 .children = []Node{},16 .children = []Node{},
17 },17 },
18 };18 };
19 var nodes = []Node {19 var nodes = []Node{
20 Node {20 Node{
21 .payload = 1,21 .payload = 1,
22 .children = []Node{},22 .children = []Node{},
23 },23 },
24 Node {24 Node{
25 .payload = 2,25 .payload = 2,
26 .children = []Node{},26 .children = []Node{},
27 },27 },
28 Node {28 Node{
29 .payload = 3,29 .payload = 3,
30 .children = other_nodes[0..],30 .children = other_nodes[0..],
31 },31 },
32 };32 };
33 const root = Node {33 const root = Node{
34 .payload = 1234,34 .payload = 1234,
35 .children = nodes[0..],35 .children = nodes[0..],
36 };36 };
test/cases/switch.zig+18-38
...@@ -6,10 +6,7 @@ test "switch with numbers" {...@@ -6,10 +6,7 @@ test "switch with numbers" {
66
7fn testSwitchWithNumbers(x: u32) void {7fn testSwitchWithNumbers(x: u32) void {
8 const result = switch (x) {8 const result = switch (x) {
9 1,9 1, 2, 3, 4...8 => false,
10 2,
11 3,
12 4 ... 8 => false,
13 13 => true,10 13 => true,
14 else => false,11 else => false,
15 };12 };
...@@ -25,9 +22,9 @@ test "switch with all ranges" {...@@ -25,9 +22,9 @@ test "switch with all ranges" {
2522
26fn testSwitchWithAllRanges(x: u32, y: u32) u32 {23fn testSwitchWithAllRanges(x: u32, y: u32) u32 {
27 return switch (x) {24 return switch (x) {
28 0 ... 100 => 1,25 0...100 => 1,
29 101 ... 200 => 2,26 101...200 => 2,
30 201 ... 300 => 3,27 201...300 => 3,
31 else => y,28 else => y,
32 };29 };
33}30}
...@@ -37,10 +34,8 @@ test "implicit comptime switch" {...@@ -37,10 +34,8 @@ test "implicit comptime switch" {
37 const result = switch (x) {34 const result = switch (x) {
38 3 => 10,35 3 => 10,
39 4 => 11,36 4 => 11,
40 5,37 5, 6 => 12,
41 6 => 12,38 7, 8 => 13,
42 7,
43 8 => 13,
44 else => 14,39 else => 14,
45 };40 };
4641
...@@ -86,22 +81,16 @@ const SwitchStatmentFoo = enum {...@@ -86,22 +81,16 @@ const SwitchStatmentFoo = enum {
86};81};
8782
88test "switch prong with variable" {83test "switch prong with variable" {
89 switchProngWithVarFn(SwitchProngWithVarEnum {84 switchProngWithVarFn(SwitchProngWithVarEnum{ .One = 13 });
90 .One = 13,85 switchProngWithVarFn(SwitchProngWithVarEnum{ .Two = 13.0 });
91 });86 switchProngWithVarFn(SwitchProngWithVarEnum{ .Meh = {} });
92 switchProngWithVarFn(SwitchProngWithVarEnum {
93 .Two = 13.0,
94 });
95 switchProngWithVarFn(SwitchProngWithVarEnum {
96 .Meh = {},
97 });
98}87}
99const SwitchProngWithVarEnum = union(enum) {88const SwitchProngWithVarEnum = union(enum) {
100 One: i32,89 One: i32,
101 Two: f32,90 Two: f32,
102 Meh: void,91 Meh: void,
103};92};
104fn switchProngWithVarFn(a: &const SwitchProngWithVarEnum) void {93fn switchProngWithVarFn(a: *const SwitchProngWithVarEnum) void {
105 switch (a.*) {94 switch (a.*) {
106 SwitchProngWithVarEnum.One => |x| {95 SwitchProngWithVarEnum.One => |x| {
107 assert(x == 13);96 assert(x == 13);
...@@ -121,9 +110,7 @@ test "switch on enum using pointer capture" {...@@ -121,9 +110,7 @@ test "switch on enum using pointer capture" {
121}110}
122111
123fn testSwitchEnumPtrCapture() void {112fn testSwitchEnumPtrCapture() void {
124 var value = SwitchProngWithVarEnum {113 var value = SwitchProngWithVarEnum{ .One = 1234 };
125 .One = 1234,
126 };
127 switch (value) {114 switch (value) {
128 SwitchProngWithVarEnum.One => |*x| x.* += 1,115 SwitchProngWithVarEnum.One => |*x| x.* += 1,
129 else => unreachable,116 else => unreachable,
...@@ -136,12 +123,8 @@ fn testSwitchEnumPtrCapture() void {...@@ -136,12 +123,8 @@ fn testSwitchEnumPtrCapture() void {
136123
137test "switch with multiple expressions" {124test "switch with multiple expressions" {
138 const x = switch (returnsFive()) {125 const x = switch (returnsFive()) {
139 1,126 1, 2, 3 => 1,
140 2,127 4, 5, 6 => 2,
141 3 => 1,
142 4,
143 5,
144 6 => 2,
145 else => i32(3),128 else => i32(3),
146 };129 };
147 assert(x == 2);130 assert(x == 2);
...@@ -156,9 +139,7 @@ const Number = union(enum) {...@@ -156,9 +139,7 @@ const Number = union(enum) {
156 Three: f32,139 Three: f32,
157};140};
158141
159const number = Number {142const number = Number{ .Three = 1.23 };
160 .Three = 1.23,
161};
162143
163fn returnsFalse() bool {144fn returnsFalse() bool {
164 switch (number) {145 switch (number) {
...@@ -212,12 +193,11 @@ fn testSwitchHandleAllCasesExhaustive(x: u2) u2 {...@@ -212,12 +193,11 @@ fn testSwitchHandleAllCasesExhaustive(x: u2) u2 {
212193
213fn testSwitchHandleAllCasesRange(x: u8) u8 {194fn testSwitchHandleAllCasesRange(x: u8) u8 {
214 return switch (x) {195 return switch (x) {
215 0 ... 100 => u8(0),196 0...100 => u8(0),
216 101 ... 200 => 1,197 101...200 => 1,
217 201,198 201, 203 => 2,
218 203 => 2,
219 202 => 4,199 202 => 4,
220 204 ... 255 => 3,200 204...255 => 3,
221 };201 };
222}202}
223203
test/cases/switch_prong_err_enum.zig+1-3
...@@ -14,9 +14,7 @@ const FormValue = union(enum) {...@@ -14,9 +14,7 @@ const FormValue = union(enum) {
1414
15fn doThing(form_id: u64) error!FormValue {15fn doThing(form_id: u64) error!FormValue {
16 return switch (form_id) {16 return switch (form_id) {
17 17 => FormValue {17 17 => FormValue{ .Address = try readOnce() },
18 .Address = try readOnce(),
19 },
20 else => error.InvalidDebugInfo,18 else => error.InvalidDebugInfo,
21 };19 };
22}20}
test/cases/switch_prong_implicit_cast.zig+2-6
...@@ -7,12 +7,8 @@ const FormValue = union(enum) {...@@ -7,12 +7,8 @@ const FormValue = union(enum) {
77
8fn foo(id: u64) !FormValue {8fn foo(id: u64) !FormValue {
9 return switch (id) {9 return switch (id) {
10 2 => FormValue {10 2 => FormValue{ .Two = true },
11 .Two = true,11 1 => FormValue{ .One = {} },
12 },
13 1 => FormValue {
14 .One = {},
15 },
16 else => return error.Whatever,12 else => return error.Whatever,
17 };13 };
18}14}
test/cases/this.zig+2-2
...@@ -8,7 +8,7 @@ fn Point(comptime T: type) type {...@@ -8,7 +8,7 @@ fn Point(comptime T: type) type {
8 x: T,8 x: T,
9 y: T,9 y: T,
1010
11 fn addOne(self: &Self) void {11 fn addOne(self: *Self) void {
12 self.x += 1;12 self.x += 1;
13 self.y += 1;13 self.y += 1;
14 }14 }
...@@ -29,7 +29,7 @@ test "this refer to module call private fn" {...@@ -29,7 +29,7 @@ test "this refer to module call private fn" {
29}29}
3030
31test "this refer to container" {31test "this refer to container" {
32 var pt = Point(i32) {32 var pt = Point(i32){
33 .x = 12,33 .x = 12,
34 .y = 34,34 .y = 34,
35 };35 };
test/cases/try.zig+1-2
...@@ -7,8 +7,7 @@ test "try on error union" {...@@ -7,8 +7,7 @@ test "try on error union" {
77
8fn tryOnErrorUnionImpl() void {8fn tryOnErrorUnionImpl() void {
9 const x = if (returnsTen()) |val| val + 1 else |err| switch (err) {9 const x = if (returnsTen()) |val| val + 1 else |err| switch (err) {
10 error.ItBroke,10 error.ItBroke, error.NoMem => 1,
11 error.NoMem => 1,
12 error.CrappedOut => i32(2),11 error.CrappedOut => i32(2),
13 else => unreachable,12 else => unreachable,
14 };13 };
test/cases/type_info.zig+16-9
...@@ -37,7 +37,7 @@ test "type info: pointer type info" {...@@ -37,7 +37,7 @@ test "type info: pointer type info" {
37}37}
3838
39fn testPointer() void {39fn testPointer() void {
40 const u32_ptr_info = @typeInfo(&u32);40 const u32_ptr_info = @typeInfo(*u32);
41 assert(TypeId(u32_ptr_info) == TypeId.Pointer);41 assert(TypeId(u32_ptr_info) == TypeId.Pointer);
42 assert(u32_ptr_info.Pointer.is_const == false);42 assert(u32_ptr_info.Pointer.is_const == false);
43 assert(u32_ptr_info.Pointer.is_volatile == false);43 assert(u32_ptr_info.Pointer.is_volatile == false);
...@@ -103,7 +103,7 @@ test "type info: error set, error union info" {...@@ -103,7 +103,7 @@ test "type info: error set, error union info" {
103}103}
104104
105fn testErrorSet() void {105fn testErrorSet() void {
106 const TestErrorSet = error {106 const TestErrorSet = error{
107 First,107 First,
108 Second,108 Second,
109 Third,109 Third,
...@@ -169,14 +169,14 @@ fn testUnion() void {...@@ -169,14 +169,14 @@ fn testUnion() void {
169 assert(notag_union_info.Union.fields[1].field_type == u32);169 assert(notag_union_info.Union.fields[1].field_type == u32);
170170
171 const TestExternUnion = extern union {171 const TestExternUnion = extern union {
172 foo: &c_void,172 foo: *c_void,
173 };173 };
174174
175 const extern_union_info = @typeInfo(TestExternUnion);175 const extern_union_info = @typeInfo(TestExternUnion);
176 assert(extern_union_info.Union.layout == TypeInfo.ContainerLayout.Extern);176 assert(extern_union_info.Union.layout == TypeInfo.ContainerLayout.Extern);
177 assert(extern_union_info.Union.tag_type == @typeOf(undefined));177 assert(extern_union_info.Union.tag_type == @typeOf(undefined));
178 assert(extern_union_info.Union.fields[0].enum_field == null);178 assert(extern_union_info.Union.fields[0].enum_field == null);
179 assert(extern_union_info.Union.fields[0].field_type == &c_void);179 assert(extern_union_info.Union.fields[0].field_type == *c_void);
180}180}
181181
182test "type info: struct info" {182test "type info: struct info" {
...@@ -190,13 +190,13 @@ fn testStruct() void {...@@ -190,13 +190,13 @@ fn testStruct() void {
190 assert(struct_info.Struct.layout == TypeInfo.ContainerLayout.Packed);190 assert(struct_info.Struct.layout == TypeInfo.ContainerLayout.Packed);
191 assert(struct_info.Struct.fields.len == 3);191 assert(struct_info.Struct.fields.len == 3);
192 assert(struct_info.Struct.fields[1].offset == null);192 assert(struct_info.Struct.fields[1].offset == null);
193 assert(struct_info.Struct.fields[2].field_type == &TestStruct);193 assert(struct_info.Struct.fields[2].field_type == *TestStruct);
194 assert(struct_info.Struct.defs.len == 2);194 assert(struct_info.Struct.defs.len == 2);
195 assert(struct_info.Struct.defs[0].is_pub);195 assert(struct_info.Struct.defs[0].is_pub);
196 assert(!struct_info.Struct.defs[0].data.Fn.is_extern);196 assert(!struct_info.Struct.defs[0].data.Fn.is_extern);
197 assert(struct_info.Struct.defs[0].data.Fn.lib_name == null);197 assert(struct_info.Struct.defs[0].data.Fn.lib_name == null);
198 assert(struct_info.Struct.defs[0].data.Fn.return_type == void);198 assert(struct_info.Struct.defs[0].data.Fn.return_type == void);
199 assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn(&const TestStruct)void);199 assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn (*const TestStruct) void);
200}200}
201201
202const TestStruct = packed struct {202const TestStruct = packed struct {
...@@ -204,9 +204,9 @@ const TestStruct = packed struct {...@@ -204,9 +204,9 @@ const TestStruct = packed struct {
204204
205 fieldA: usize,205 fieldA: usize,
206 fieldB: void,206 fieldB: void,
207 fieldC: &Self,207 fieldC: *Self,
208208
209 pub fn foo(self: &const Self) void {}209 pub fn foo(self: *const Self) void {}
210};210};
211211
212test "type info: function type info" {212test "type info: function type info" {
...@@ -227,9 +227,16 @@ fn testFunction() void {...@@ -227,9 +227,16 @@ fn testFunction() void {
227 const test_instance: TestStruct = undefined;227 const test_instance: TestStruct = undefined;
228 const bound_fn_info = @typeInfo(@typeOf(test_instance.foo));228 const bound_fn_info = @typeInfo(@typeOf(test_instance.foo));
229 assert(TypeId(bound_fn_info) == TypeId.BoundFn);229 assert(TypeId(bound_fn_info) == TypeId.BoundFn);
230 assert(bound_fn_info.BoundFn.args[0].arg_type == &const TestStruct);230 assert(bound_fn_info.BoundFn.args[0].arg_type == *const TestStruct);
231}231}
232232
233fn foo(comptime a: usize, b: bool, args: ...) usize {233fn foo(comptime a: usize, b: bool, args: ...) usize {
234 return 0;234 return 0;
235}235}
236
237test "typeInfo with comptime parameter in struct fn def" {
238 const S = struct {
239 pub fn func(comptime x: f32) void {}
240 };
241 comptime var info = @typeInfo(S);
242}
test/cases/undefined.zig+2-2
...@@ -27,12 +27,12 @@ test "init static array to undefined" {...@@ -27,12 +27,12 @@ test "init static array to undefined" {
27const Foo = struct {27const Foo = struct {
28 x: i32,28 x: i32,
2929
30 fn setFooXMethod(foo: &Foo) void {30 fn setFooXMethod(foo: *Foo) void {
31 foo.x = 3;31 foo.x = 3;
32 }32 }
33};33};
3434
35fn setFooX(foo: &Foo) void {35fn setFooX(foo: *Foo) void {
36 foo.x = 2;36 foo.x = 2;
37}37}
3838
test/cases/union.zig+10-11
...@@ -50,10 +50,10 @@ test "basic unions" {...@@ -50,10 +50,10 @@ test "basic unions" {
5050
51test "comptime union field access" {51test "comptime union field access" {
52 comptime {52 comptime {
53 var foo = Foo { .int = 0 };53 var foo = Foo{ .int = 0 };
54 assert(foo.int == 0);54 assert(foo.int == 0);
5555
56 foo = Foo { .float = 42.42 };56 foo = Foo{ .float = 42.42 };
57 assert(foo.float == 42.42);57 assert(foo.float == 42.42);
58 }58 }
59}59}
...@@ -68,11 +68,11 @@ test "init union with runtime value" {...@@ -68,11 +68,11 @@ test "init union with runtime value" {
68 assert(foo.int == 42);68 assert(foo.int == 42);
69}69}
7070
71fn setFloat(foo: &Foo, x: f64) void {71fn setFloat(foo: *Foo, x: f64) void {
72 foo.* = Foo{ .float = x };72 foo.* = Foo{ .float = x };
73}73}
7474
75fn setInt(foo: &Foo, x: i32) void {75fn setInt(foo: *Foo, x: i32) void {
76 foo.* = Foo{ .int = x };76 foo.* = Foo{ .int = x };
77}77}
7878
...@@ -108,7 +108,7 @@ fn doTest() void {...@@ -108,7 +108,7 @@ fn doTest() void {
108 assert(bar(Payload{ .A = 1234 }) == -10);108 assert(bar(Payload{ .A = 1234 }) == -10);
109}109}
110110
111fn bar(value: &const Payload) i32 {111fn bar(value: *const Payload) i32 {
112 assert(Letter(value.*) == Letter.A);112 assert(Letter(value.*) == Letter.A);
113 return switch (value.*) {113 return switch (value.*) {
114 Payload.A => |x| return x - 1244,114 Payload.A => |x| return x - 1244,
...@@ -147,7 +147,7 @@ test "union(enum(u32)) with specified and unspecified tag values" {...@@ -147,7 +147,7 @@ test "union(enum(u32)) with specified and unspecified tag values" {
147 comptime testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2{ .C = 123 });147 comptime testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2{ .C = 123 });
148}148}
149149
150fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: &const MultipleChoice2) void {150fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: *const MultipleChoice2) void {
151 assert(u32(@TagType(MultipleChoice2)(x.*)) == 60);151 assert(u32(@TagType(MultipleChoice2)(x.*)) == 60);
152 assert(1123 == switch (x.*) {152 assert(1123 == switch (x.*) {
153 MultipleChoice2.A => 1,153 MultipleChoice2.A => 1,
...@@ -163,7 +163,7 @@ fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: &const MultipleChoice2) void...@@ -163,7 +163,7 @@ fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: &const MultipleChoice2) void
163}163}
164164
165const ExternPtrOrInt = extern union {165const ExternPtrOrInt = extern union {
166 ptr: &u8,166 ptr: *u8,
167 int: u64,167 int: u64,
168};168};
169test "extern union size" {169test "extern union size" {
...@@ -171,7 +171,7 @@ test "extern union size" {...@@ -171,7 +171,7 @@ test "extern union size" {
171}171}
172172
173const PackedPtrOrInt = packed union {173const PackedPtrOrInt = packed union {
174 ptr: &u8,174 ptr: *u8,
175 int: u64,175 int: u64,
176};176};
177test "extern union size" {177test "extern union size" {
...@@ -206,7 +206,7 @@ test "cast union to tag type of union" {...@@ -206,7 +206,7 @@ test "cast union to tag type of union" {
206 comptime testCastUnionToTagType(TheUnion{ .B = 1234 });206 comptime testCastUnionToTagType(TheUnion{ .B = 1234 });
207}207}
208208
209fn testCastUnionToTagType(x: &const TheUnion) void {209fn testCastUnionToTagType(x: *const TheUnion) void {
210 assert(TheTag(x.*) == TheTag.B);210 assert(TheTag(x.*) == TheTag.B);
211}211}
212212
...@@ -243,7 +243,7 @@ const TheUnion2 = union(enum) {...@@ -243,7 +243,7 @@ const TheUnion2 = union(enum) {
243 Item2: i32,243 Item2: i32,
244};244};
245245
246fn assertIsTheUnion2Item1(value: &const TheUnion2) void {246fn assertIsTheUnion2Item1(value: *const TheUnion2) void {
247 assert(value.* == TheUnion2.Item1);247 assert(value.* == TheUnion2.Item1);
248}248}
249249
...@@ -286,7 +286,6 @@ const PartialInstWithPayload = union(enum) {...@@ -286,7 +286,6 @@ const PartialInstWithPayload = union(enum) {
286 Compiled: i32,286 Compiled: i32,
287};287};
288288
289
290test "access a member of tagged union with conflicting enum tag name" {289test "access a member of tagged union with conflicting enum tag name" {
291 const Bar = union(enum) {290 const Bar = union(enum) {
292 A: A,291 A: A,
test/cases/var_args.zig+1-1
...@@ -58,7 +58,7 @@ fn extraFn(extra: u32, args: ...) usize {...@@ -58,7 +58,7 @@ fn extraFn(extra: u32, args: ...) usize {
58 return args.len;58 return args.len;
59}59}
6060
61const foos = []fn(...) bool {61const foos = []fn (...) bool{
62 foo1,62 foo1,
63 foo2,63 foo2,
64};64};
test/cases/void.zig+1-1
...@@ -8,7 +8,7 @@ const Foo = struct {...@@ -8,7 +8,7 @@ const Foo = struct {
88
9test "compare void with void compile time known" {9test "compare void with void compile time known" {
10 comptime {10 comptime {
11 const foo = Foo {11 const foo = Foo{
12 .a = {},12 .a = {},
13 .b = 1,13 .b = 1,
14 .c = {},14 .c = {},
test/cases/while.zig+2-2
...@@ -151,7 +151,7 @@ test "while on nullable with else result follow break prong" {...@@ -151,7 +151,7 @@ test "while on nullable with else result follow break prong" {
151test "while on error union with else result follow else prong" {151test "while on error union with else result follow else prong" {
152 const result = while (returnError()) |value| {152 const result = while (returnError()) |value| {
153 break value;153 break value;
154 } else|err| 154 } else |err|
155 i32(2);155 i32(2);
156 assert(result == 2);156 assert(result == 2);
157}157}
...@@ -159,7 +159,7 @@ test "while on error union with else result follow else prong" {...@@ -159,7 +159,7 @@ test "while on error union with else result follow else prong" {
159test "while on error union with else result follow break prong" {159test "while on error union with else result follow break prong" {
160 const result = while (returnSuccess(10)) |value| {160 const result = while (returnSuccess(10)) |value| {
161 break value;161 break value;
162 } else|err| 162 } else |err|
163 i32(2);163 i32(2);
164 assert(result == 10);164 assert(result == 10);
165}165}
test/compare_output.zig+13-13
...@@ -3,10 +3,10 @@ const std = @import("std");...@@ -3,10 +3,10 @@ const std = @import("std");
3const os = std.os;3const os = std.os;
4const tests = @import("tests.zig");4const tests = @import("tests.zig");
55
6pub fn addCases(cases: &tests.CompareOutputContext) void {6pub fn addCases(cases: *tests.CompareOutputContext) void {
7 cases.addC("hello world with libc",7 cases.addC("hello world with libc",
8 \\const c = @cImport(@cInclude("stdio.h"));8 \\const c = @cImport(@cInclude("stdio.h"));
9 \\export fn main(argc: c_int, argv: &&u8) c_int {9 \\export fn main(argc: c_int, argv: [*][*]u8) c_int {
10 \\ _ = c.puts(c"Hello, world!");10 \\ _ = c.puts(c"Hello, world!");
11 \\ return 0;11 \\ return 0;
12 \\}12 \\}
...@@ -139,7 +139,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -139,7 +139,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
139 \\ @cInclude("stdio.h");139 \\ @cInclude("stdio.h");
140 \\});140 \\});
141 \\141 \\
142 \\export fn main(argc: c_int, argv: &&u8) c_int {142 \\export fn main(argc: c_int, argv: [*][*]u8) c_int {
143 \\ if (is_windows) {143 \\ if (is_windows) {
144 \\ // we want actual \n, not \r\n144 \\ // we want actual \n, not \r\n
145 \\ _ = c._setmode(1, c._O_BINARY);145 \\ _ = c._setmode(1, c._O_BINARY);
...@@ -284,9 +284,9 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -284,9 +284,9 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
284 cases.addC("expose function pointer to C land",284 cases.addC("expose function pointer to C land",
285 \\const c = @cImport(@cInclude("stdlib.h"));285 \\const c = @cImport(@cInclude("stdlib.h"));
286 \\286 \\
287 \\export fn compare_fn(a: ?&const c_void, b: ?&const c_void) c_int {287 \\export fn compare_fn(a: ?[*]const c_void, b: ?[*]const c_void) c_int {
288 \\ const a_int = @ptrCast(&align(1) const i32, a ?? unreachable);288 \\ const a_int = @ptrCast(*const i32, @alignCast(@alignOf(i32), a));
289 \\ const b_int = @ptrCast(&align(1) const i32, b ?? unreachable);289 \\ const b_int = @ptrCast(*const i32, @alignCast(@alignOf(i32), b));
290 \\ if (a_int.* < b_int.*) {290 \\ if (a_int.* < b_int.*) {
291 \\ return -1;291 \\ return -1;
292 \\ } else if (a_int.* > b_int.*) {292 \\ } else if (a_int.* > b_int.*) {
...@@ -297,9 +297,9 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -297,9 +297,9 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
297 \\}297 \\}
298 \\298 \\
299 \\export fn main() c_int {299 \\export fn main() c_int {
300 \\ var array = []u32 { 1, 7, 3, 2, 0, 9, 4, 8, 6, 5 };300 \\ var array = []u32{ 1, 7, 3, 2, 0, 9, 4, 8, 6, 5 };
301 \\301 \\
302 \\ c.qsort(@ptrCast(&c_void, &array[0]), c_ulong(array.len), @sizeOf(i32), compare_fn);302 \\ c.qsort(@ptrCast(?[*]c_void, array[0..].ptr), c_ulong(array.len), @sizeOf(i32), compare_fn);
303 \\303 \\
304 \\ for (array) |item, i| {304 \\ for (array) |item, i| {
305 \\ if (item != i) {305 \\ if (item != i) {
...@@ -324,7 +324,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -324,7 +324,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
324 \\ @cInclude("stdio.h");324 \\ @cInclude("stdio.h");
325 \\});325 \\});
326 \\326 \\
327 \\export fn main(argc: c_int, argv: &&u8) c_int {327 \\export fn main(argc: c_int, argv: [*][*]u8) c_int {
328 \\ if (is_windows) {328 \\ if (is_windows) {
329 \\ // we want actual \n, not \r\n329 \\ // we want actual \n, not \r\n
330 \\ _ = c._setmode(1, c._O_BINARY);330 \\ _ = c._setmode(1, c._O_BINARY);
...@@ -344,13 +344,13 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -344,13 +344,13 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
344 \\const Foo = struct {344 \\const Foo = struct {
345 \\ field1: Bar,345 \\ field1: Bar,
346 \\346 \\
347 \\ fn method(a: &const Foo) bool { return true; }347 \\ fn method(a: *const Foo) bool { return true; }
348 \\};348 \\};
349 \\349 \\
350 \\const Bar = struct {350 \\const Bar = struct {
351 \\ field2: i32,351 \\ field2: i32,
352 \\352 \\
353 \\ fn method(b: &const Bar) bool { return true; }353 \\ fn method(b: *const Bar) bool { return true; }
354 \\};354 \\};
355 \\355 \\
356 \\pub fn main() void {356 \\pub fn main() void {
...@@ -475,7 +475,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -475,7 +475,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
475 \\475 \\
476 );476 );
477477
478 tc.setCommandLineArgs([][]const u8 {478 tc.setCommandLineArgs([][]const u8{
479 "first arg",479 "first arg",
480 "'a' 'b' \\",480 "'a' 'b' \\",
481 "bare",481 "bare",
...@@ -516,7 +516,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -516,7 +516,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
516 \\516 \\
517 );517 );
518518
519 tc.setCommandLineArgs([][]const u8 {519 tc.setCommandLineArgs([][]const u8{
520 "first arg",520 "first arg",
521 "'a' 'b' \\",521 "'a' 'b' \\",
522 "bare",522 "bare",
test/compile_errors.zig+1572-762
...@@ -1,7 +1,34 @@...@@ -1,7 +1,34 @@
1const tests = @import("tests.zig");1const tests = @import("tests.zig");
22
3pub fn addCases(cases: &tests.CompileErrorContext) void {3pub fn addCases(cases: *tests.CompileErrorContext) void {
4 cases.add("invalid deref on switch target",4 cases.add(
5 "indexing single-item pointer",
6 \\export fn entry(ptr: *i32) i32 {
7 \\ return ptr[1];
8 \\}
9 ,
10 ".tmp_source.zig:2:15: error: indexing not allowed on pointer to single item",
11 );
12
13 cases.add(
14 "invalid deref on switch target",
15 \\const NextError = error{NextError};
16 \\const OtherError = error{OutOfMemory};
17 \\
18 \\export fn entry() void {
19 \\ const a: ?NextError!i32 = foo();
20 \\}
21 \\
22 \\fn foo() ?OtherError!i32 {
23 \\ return null;
24 \\}
25 ,
26 ".tmp_source.zig:5:34: error: expected 'NextError!i32', found 'OtherError!i32'",
27 ".tmp_source.zig:2:26: note: 'error.OutOfMemory' not a member of destination error set",
28 );
29
30 cases.add(
31 "invalid deref on switch target",
5 \\comptime {32 \\comptime {
6 \\ var tile = Tile.Empty;33 \\ var tile = Tile.Empty;
7 \\ switch (tile.*) {34 \\ switch (tile.*) {
...@@ -14,15 +41,19 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -14,15 +41,19 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
14 \\ Filled,41 \\ Filled,
15 \\};42 \\};
16 ,43 ,
17 ".tmp_source.zig:3:17: error: invalid deref on switch target");44 ".tmp_source.zig:3:17: error: invalid deref on switch target",
45 );
1846
19 cases.add("invalid field access in comptime",47 cases.add(
48 "invalid field access in comptime",
20 \\comptime { var x = doesnt_exist.whatever; }49 \\comptime { var x = doesnt_exist.whatever; }
21 ,50 ,
22 ".tmp_source.zig:1:20: error: use of undeclared identifier 'doesnt_exist'");51 ".tmp_source.zig:1:20: error: use of undeclared identifier 'doesnt_exist'",
52 );
2353
24 cases.add("suspend inside suspend block",54 cases.add(
25 \\const std = @import("std");55 "suspend inside suspend block",
56 \\const std = @import("std",);
26 \\57 \\
27 \\export fn entry() void {58 \\export fn entry() void {
28 \\ var buf: [500]u8 = undefined;59 \\ var buf: [500]u8 = undefined;
...@@ -39,27 +70,32 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -39,27 +70,32 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
39 \\}70 \\}
40 ,71 ,
41 ".tmp_source.zig:12:9: error: cannot suspend inside suspend block",72 ".tmp_source.zig:12:9: error: cannot suspend inside suspend block",
42 ".tmp_source.zig:11:5: note: other suspend block here");73 ".tmp_source.zig:11:5: note: other suspend block here",
74 );
4375
44 cases.add("assign inline fn to non-comptime var",76 cases.add(
77 "assign inline fn to non-comptime var",
45 \\export fn entry() void {78 \\export fn entry() void {
46 \\ var a = b;79 \\ var a = b;
47 \\}80 \\}
48 \\inline fn b() void { }81 \\inline fn b() void { }
49 ,82 ,
50 ".tmp_source.zig:2:5: error: functions marked inline must be stored in const or comptime var",83 ".tmp_source.zig:2:5: error: functions marked inline must be stored in const or comptime var",
51 ".tmp_source.zig:4:8: note: declared here");84 ".tmp_source.zig:4:8: note: declared here",
85 );
5286
53 cases.add("wrong type passed to @panic",87 cases.add(
88 "wrong type passed to @panic",
54 \\export fn entry() void {89 \\export fn entry() void {
55 \\ var e = error.Foo;90 \\ var e = error.Foo;
56 \\ @panic(e);91 \\ @panic(e);
57 \\}92 \\}
58 ,93 ,
59 ".tmp_source.zig:3:12: error: expected type '[]const u8', found 'error{Foo}'");94 ".tmp_source.zig:3:12: error: expected type '[]const u8', found 'error{Foo}'",
6095 );
6196
62 cases.add("@tagName used on union with no associated enum tag",97 cases.add(
98 "@tagName used on union with no associated enum tag",
63 \\const FloatInt = extern union {99 \\const FloatInt = extern union {
64 \\ Float: f32,100 \\ Float: f32,
65 \\ Int: i32,101 \\ Int: i32,
...@@ -70,10 +106,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -70,10 +106,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
70 \\}106 \\}
71 ,107 ,
72 ".tmp_source.zig:7:19: error: union has no associated enum",108 ".tmp_source.zig:7:19: error: union has no associated enum",
73 ".tmp_source.zig:1:18: note: declared here");109 ".tmp_source.zig:1:18: note: declared here",
110 );
74111
75 cases.add("returning error from void async function",112 cases.add(
76 \\const std = @import("std");113 "returning error from void async function",
114 \\const std = @import("std",);
77 \\export fn entry() void {115 \\export fn entry() void {
78 \\ const p = async<std.debug.global_allocator> amain() catch unreachable;116 \\ const p = async<std.debug.global_allocator> amain() catch unreachable;
79 \\}117 \\}
...@@ -81,32 +119,40 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -81,32 +119,40 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
81 \\ return error.ShouldBeCompileError;119 \\ return error.ShouldBeCompileError;
82 \\}120 \\}
83 ,121 ,
84 ".tmp_source.zig:6:17: error: expected type 'void', found 'error{ShouldBeCompileError}'");122 ".tmp_source.zig:6:17: error: expected type 'void', found 'error{ShouldBeCompileError}'",
123 );
85124
86 cases.add("var not allowed in structs",125 cases.add(
126 "var not allowed in structs",
87 \\export fn entry() void {127 \\export fn entry() void {
88 \\ var s = (struct{v: var}){.v=i32(10)};128 \\ var s = (struct{v: var}){.v=i32(10)};
89 \\}129 \\}
90 ,130 ,
91 ".tmp_source.zig:2:23: error: invalid token: 'var'");131 ".tmp_source.zig:2:23: error: invalid token: 'var'",
132 );
92133
93 cases.add("@ptrCast discards const qualifier",134 cases.add(
135 "@ptrCast discards const qualifier",
94 \\export fn entry() void {136 \\export fn entry() void {
95 \\ const x: i32 = 1234;137 \\ const x: i32 = 1234;
96 \\ const y = @ptrCast(&i32, &x);138 \\ const y = @ptrCast(*i32, &x);
97 \\}139 \\}
98 ,140 ,
99 ".tmp_source.zig:3:15: error: cast discards const qualifier");141 ".tmp_source.zig:3:15: error: cast discards const qualifier",
142 );
100143
101 cases.add("comptime slice of undefined pointer non-zero len",144 cases.add(
145 "comptime slice of undefined pointer non-zero len",
102 \\export fn entry() void {146 \\export fn entry() void {
103 \\ const slice = (&i32)(undefined)[0..1];147 \\ const slice = (*i32)(undefined)[0..1];
104 \\}148 \\}
105 ,149 ,
106 ".tmp_source.zig:2:36: error: non-zero length slice of undefined pointer");150 ".tmp_source.zig:2:36: error: non-zero length slice of undefined pointer",
151 );
107152
108 cases.add("type checking function pointers",153 cases.add(
109 \\fn a(b: fn (&const u8) void) void {154 "type checking function pointers",
155 \\fn a(b: fn (*const u8) void) void {
110 \\ b('a');156 \\ b('a');
111 \\}157 \\}
112 \\fn c(d: u8) void {158 \\fn c(d: u8) void {
...@@ -116,9 +162,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -116,9 +162,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
116 \\ a(c);162 \\ a(c);
117 \\}163 \\}
118 ,164 ,
119 ".tmp_source.zig:8:7: error: expected type 'fn(&const u8) void', found 'fn(u8) void'");165 ".tmp_source.zig:8:7: error: expected type 'fn(*const u8) void', found 'fn(u8) void'",
166 );
120167
121 cases.add("no else prong on switch on global error set",168 cases.add(
169 "no else prong on switch on global error set",
122 \\export fn entry() void {170 \\export fn entry() void {
123 \\ foo(error.A);171 \\ foo(error.A);
124 \\}172 \\}
...@@ -128,18 +176,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -128,18 +176,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
128 \\ }176 \\ }
129 \\}177 \\}
130 ,178 ,
131 ".tmp_source.zig:5:5: error: else prong required when switching on type 'error'");179 ".tmp_source.zig:5:5: error: else prong required when switching on type 'error'",
180 );
132181
133 cases.add("inferred error set with no returned error",182 cases.add(
183 "inferred error set with no returned error",
134 \\export fn entry() void {184 \\export fn entry() void {
135 \\ foo() catch unreachable;185 \\ foo() catch unreachable;
136 \\}186 \\}
137 \\fn foo() !void {187 \\fn foo() !void {
138 \\}188 \\}
139 ,189 ,
140 ".tmp_source.zig:4:11: error: function with inferred error set must return at least one possible error");190 ".tmp_source.zig:4:11: error: function with inferred error set must return at least one possible error",
191 );
141192
142 cases.add("error not handled in switch",193 cases.add(
194 "error not handled in switch",
143 \\export fn entry() void {195 \\export fn entry() void {
144 \\ foo(452) catch |err| switch (err) {196 \\ foo(452) catch |err| switch (err) {
145 \\ error.Foo => {},197 \\ error.Foo => {},
...@@ -155,9 +207,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -155,9 +207,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
155 \\}207 \\}
156 ,208 ,
157 ".tmp_source.zig:2:26: error: error.Baz not handled in switch",209 ".tmp_source.zig:2:26: error: error.Baz not handled in switch",
158 ".tmp_source.zig:2:26: error: error.Bar not handled in switch");210 ".tmp_source.zig:2:26: error: error.Bar not handled in switch",
211 );
159212
160 cases.add("duplicate error in switch",213 cases.add(
214 "duplicate error in switch",
161 \\export fn entry() void {215 \\export fn entry() void {
162 \\ foo(452) catch |err| switch (err) {216 \\ foo(452) catch |err| switch (err) {
163 \\ error.Foo => {},217 \\ error.Foo => {},
...@@ -175,9 +229,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -175,9 +229,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
175 \\}229 \\}
176 ,230 ,
177 ".tmp_source.zig:5:14: error: duplicate switch value: '@typeOf(foo).ReturnType.ErrorSet.Foo'",231 ".tmp_source.zig:5:14: error: duplicate switch value: '@typeOf(foo).ReturnType.ErrorSet.Foo'",
178 ".tmp_source.zig:3:14: note: other value is here");232 ".tmp_source.zig:3:14: note: other value is here",
233 );
179234
180 cases.add("range operator in switch used on error set",235 cases.add(
236 "range operator in switch used on error set",
181 \\export fn entry() void {237 \\export fn entry() void {
182 \\ try foo(452) catch |err| switch (err) {238 \\ try foo(452) catch |err| switch (err) {
183 \\ error.A ... error.B => {},239 \\ error.A ... error.B => {},
...@@ -192,31 +248,39 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -192,31 +248,39 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
192 \\ }248 \\ }
193 \\}249 \\}
194 ,250 ,
195 ".tmp_source.zig:3:17: error: operator not allowed for errors");251 ".tmp_source.zig:3:17: error: operator not allowed for errors",
252 );
196253
197 cases.add("inferring error set of function pointer",254 cases.add(
255 "inferring error set of function pointer",
198 \\comptime {256 \\comptime {
199 \\ const z: ?fn()!void = null;257 \\ const z: ?fn()!void = null;
200 \\}258 \\}
201 ,259 ,
202 ".tmp_source.zig:2:15: error: inferring error set of return type valid only for function definitions");260 ".tmp_source.zig:2:15: error: inferring error set of return type valid only for function definitions",
261 );
203262
204 cases.add("access non-existent member of error set",263 cases.add(
264 "access non-existent member of error set",
205 \\const Foo = error{A};265 \\const Foo = error{A};
206 \\comptime {266 \\comptime {
207 \\ const z = Foo.Bar;267 \\ const z = Foo.Bar;
208 \\}268 \\}
209 ,269 ,
210 ".tmp_source.zig:3:18: error: no error named 'Bar' in 'Foo'");270 ".tmp_source.zig:3:18: error: no error named 'Bar' in 'Foo'",
271 );
211272
212 cases.add("error union operator with non error set LHS",273 cases.add(
274 "error union operator with non error set LHS",
213 \\comptime {275 \\comptime {
214 \\ const z = i32!i32;276 \\ const z = i32!i32;
215 \\}277 \\}
216 ,278 ,
217 ".tmp_source.zig:2:15: error: expected error set type, found type 'i32'");279 ".tmp_source.zig:2:15: error: expected error set type, found type 'i32'",
280 );
218281
219 cases.add("error equality but sets have no common members",282 cases.add(
283 "error equality but sets have no common members",
220 \\const Set1 = error{A, C};284 \\const Set1 = error{A, C};
221 \\const Set2 = error{B, D};285 \\const Set2 = error{B, D};
222 \\export fn entry() void {286 \\export fn entry() void {
...@@ -228,16 +292,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -228,16 +292,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
228 \\ }292 \\ }
229 \\}293 \\}
230 ,294 ,
231 ".tmp_source.zig:7:11: error: error sets 'Set1' and 'Set2' have no common errors");295 ".tmp_source.zig:7:11: error: error sets 'Set1' and 'Set2' have no common errors",
296 );
232297
233 cases.add("only equality binary operator allowed for error sets",298 cases.add(
299 "only equality binary operator allowed for error sets",
234 \\comptime {300 \\comptime {
235 \\ const z = error.A > error.B;301 \\ const z = error.A > error.B;
236 \\}302 \\}
237 ,303 ,
238 ".tmp_source.zig:2:23: error: operator not allowed for errors");304 ".tmp_source.zig:2:23: error: operator not allowed for errors",
305 );
239306
240 cases.add("explicit error set cast known at comptime violates error sets",307 cases.add(
308 "explicit error set cast known at comptime violates error sets",
241 \\const Set1 = error {A, B};309 \\const Set1 = error {A, B};
242 \\const Set2 = error {A, C};310 \\const Set2 = error {A, C};
243 \\comptime {311 \\comptime {
...@@ -245,9 +313,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -245,9 +313,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
245 \\ var y = Set2(x);313 \\ var y = Set2(x);
246 \\}314 \\}
247 ,315 ,
248 ".tmp_source.zig:5:17: error: error.B not a member of error set 'Set2'");316 ".tmp_source.zig:5:17: error: error.B not a member of error set 'Set2'",
317 );
249318
250 cases.add("cast error union of global error set to error union of smaller error set",319 cases.add(
320 "cast error union of global error set to error union of smaller error set",
251 \\const SmallErrorSet = error{A};321 \\const SmallErrorSet = error{A};
252 \\export fn entry() void {322 \\export fn entry() void {
253 \\ var x: SmallErrorSet!i32 = foo();323 \\ var x: SmallErrorSet!i32 = foo();
...@@ -257,9 +327,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -257,9 +327,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
257 \\}327 \\}
258 ,328 ,
259 ".tmp_source.zig:3:35: error: expected 'SmallErrorSet!i32', found 'error!i32'",329 ".tmp_source.zig:3:35: error: expected 'SmallErrorSet!i32', found 'error!i32'",
260 ".tmp_source.zig:3:35: note: unable to cast global error set into smaller set");330 ".tmp_source.zig:3:35: note: unable to cast global error set into smaller set",
331 );
261332
262 cases.add("cast global error set to error set",333 cases.add(
334 "cast global error set to error set",
263 \\const SmallErrorSet = error{A};335 \\const SmallErrorSet = error{A};
264 \\export fn entry() void {336 \\export fn entry() void {
265 \\ var x: SmallErrorSet = foo();337 \\ var x: SmallErrorSet = foo();
...@@ -269,9 +341,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -269,9 +341,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
269 \\}341 \\}
270 ,342 ,
271 ".tmp_source.zig:3:31: error: expected 'SmallErrorSet', found 'error'",343 ".tmp_source.zig:3:31: error: expected 'SmallErrorSet', found 'error'",
272 ".tmp_source.zig:3:31: note: unable to cast global error set into smaller set");344 ".tmp_source.zig:3:31: note: unable to cast global error set into smaller set",
345 );
273346
274 cases.add("recursive inferred error set",347 cases.add(
348 "recursive inferred error set",
275 \\export fn entry() void {349 \\export fn entry() void {
276 \\ foo() catch unreachable;350 \\ foo() catch unreachable;
277 \\}351 \\}
...@@ -279,9 +353,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -279,9 +353,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
279 \\ try foo();353 \\ try foo();
280 \\}354 \\}
281 ,355 ,
282 ".tmp_source.zig:5:5: error: cannot resolve inferred error set '@typeOf(foo).ReturnType.ErrorSet': function 'foo' not fully analyzed yet");356 ".tmp_source.zig:5:5: error: cannot resolve inferred error set '@typeOf(foo).ReturnType.ErrorSet': function 'foo' not fully analyzed yet",
357 );
283358
284 cases.add("implicit cast of error set not a subset",359 cases.add(
360 "implicit cast of error set not a subset",
285 \\const Set1 = error{A, B};361 \\const Set1 = error{A, B};
286 \\const Set2 = error{A, C};362 \\const Set2 = error{A, C};
287 \\export fn entry() void {363 \\export fn entry() void {
...@@ -292,18 +368,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -292,18 +368,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
292 \\}368 \\}
293 ,369 ,
294 ".tmp_source.zig:7:19: error: expected 'Set2', found 'Set1'",370 ".tmp_source.zig:7:19: error: expected 'Set2', found 'Set1'",
295 ".tmp_source.zig:1:23: note: 'error.B' not a member of destination error set");371 ".tmp_source.zig:1:23: note: 'error.B' not a member of destination error set",
372 );
296373
297 cases.add("int to err global invalid number",374 cases.add(
375 "int to err global invalid number",
298 \\const Set1 = error{A, B};376 \\const Set1 = error{A, B};
299 \\comptime {377 \\comptime {
300 \\ var x: usize = 3;378 \\ var x: usize = 3;
301 \\ var y = error(x);379 \\ var y = error(x);
302 \\}380 \\}
303 ,381 ,
304 ".tmp_source.zig:4:18: error: integer value 3 represents no error");382 ".tmp_source.zig:4:18: error: integer value 3 represents no error",
383 );
305384
306 cases.add("int to err non global invalid number",385 cases.add(
386 "int to err non global invalid number",
307 \\const Set1 = error{A, B};387 \\const Set1 = error{A, B};
308 \\const Set2 = error{A, C};388 \\const Set2 = error{A, C};
309 \\comptime {389 \\comptime {
...@@ -311,16 +391,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -311,16 +391,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
311 \\ var y = Set2(x);391 \\ var y = Set2(x);
312 \\}392 \\}
313 ,393 ,
314 ".tmp_source.zig:5:17: error: integer value 2 represents no error in 'Set2'");394 ".tmp_source.zig:5:17: error: integer value 2 represents no error in 'Set2'",
395 );
315396
316 cases.add("@memberCount of error",397 cases.add(
398 "@memberCount of error",
317 \\comptime {399 \\comptime {
318 \\ _ = @memberCount(error);400 \\ _ = @memberCount(error);
319 \\}401 \\}
320 ,402 ,
321 ".tmp_source.zig:2:9: error: global error set member count not available at comptime");403 ".tmp_source.zig:2:9: error: global error set member count not available at comptime",
404 );
322405
323 cases.add("duplicate error value in error set",406 cases.add(
407 "duplicate error value in error set",
324 \\const Foo = error {408 \\const Foo = error {
325 \\ Bar,409 \\ Bar,
326 \\ Bar,410 \\ Bar,
...@@ -330,22 +414,30 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -330,22 +414,30 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
330 \\}414 \\}
331 ,415 ,
332 ".tmp_source.zig:3:5: error: duplicate error: 'Bar'",416 ".tmp_source.zig:3:5: error: duplicate error: 'Bar'",
333 ".tmp_source.zig:2:5: note: other error here");417 ".tmp_source.zig:2:5: note: other error here",
418 );
334419
335 cases.add("cast negative integer literal to usize",420 cases.add(
421 "cast negative integer literal to usize",
336 \\export fn entry() void {422 \\export fn entry() void {
337 \\ const x = usize(-10);423 \\ const x = usize(-10);
338 \\}424 \\}
339 , ".tmp_source.zig:2:21: error: cannot cast negative value -10 to unsigned integer type 'usize'");425 ,
426 ".tmp_source.zig:2:21: error: cannot cast negative value -10 to unsigned integer type 'usize'",
427 );
340428
341 cases.add("use invalid number literal as array index",429 cases.add(
430 "use invalid number literal as array index",
342 \\var v = 25;431 \\var v = 25;
343 \\export fn entry() void {432 \\export fn entry() void {
344 \\ var arr: [v]u8 = undefined;433 \\ var arr: [v]u8 = undefined;
345 \\}434 \\}
346 , ".tmp_source.zig:1:1: error: unable to infer variable type");435 ,
436 ".tmp_source.zig:1:1: error: unable to infer variable type",
437 );
347438
348 cases.add("duplicate struct field",439 cases.add(
440 "duplicate struct field",
349 \\const Foo = struct {441 \\const Foo = struct {
350 \\ Bar: i32,442 \\ Bar: i32,
351 \\ Bar: usize,443 \\ Bar: usize,
...@@ -355,9 +447,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -355,9 +447,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
355 \\}447 \\}
356 ,448 ,
357 ".tmp_source.zig:3:5: error: duplicate struct field: 'Bar'",449 ".tmp_source.zig:3:5: error: duplicate struct field: 'Bar'",
358 ".tmp_source.zig:2:5: note: other field here");450 ".tmp_source.zig:2:5: note: other field here",
451 );
359452
360 cases.add("duplicate union field",453 cases.add(
454 "duplicate union field",
361 \\const Foo = union {455 \\const Foo = union {
362 \\ Bar: i32,456 \\ Bar: i32,
363 \\ Bar: usize,457 \\ Bar: usize,
...@@ -367,9 +461,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -367,9 +461,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
367 \\}461 \\}
368 ,462 ,
369 ".tmp_source.zig:3:5: error: duplicate union field: 'Bar'",463 ".tmp_source.zig:3:5: error: duplicate union field: 'Bar'",
370 ".tmp_source.zig:2:5: note: other field here");464 ".tmp_source.zig:2:5: note: other field here",
465 );
371466
372 cases.add("duplicate enum field",467 cases.add(
468 "duplicate enum field",
373 \\const Foo = enum {469 \\const Foo = enum {
374 \\ Bar,470 \\ Bar,
375 \\ Bar,471 \\ Bar,
...@@ -380,77 +476,108 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -380,77 +476,108 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
380 \\}476 \\}
381 ,477 ,
382 ".tmp_source.zig:3:5: error: duplicate enum field: 'Bar'",478 ".tmp_source.zig:3:5: error: duplicate enum field: 'Bar'",
383 ".tmp_source.zig:2:5: note: other field here");479 ".tmp_source.zig:2:5: note: other field here",
480 );
384481
385 cases.add("calling function with naked calling convention",482 cases.add(
483 "calling function with naked calling convention",
386 \\export fn entry() void {484 \\export fn entry() void {
387 \\ foo();485 \\ foo();
388 \\}486 \\}
389 \\nakedcc fn foo() void { }487 \\nakedcc fn foo() void { }
390 ,488 ,
391 ".tmp_source.zig:2:5: error: unable to call function with naked calling convention",489 ".tmp_source.zig:2:5: error: unable to call function with naked calling convention",
392 ".tmp_source.zig:4:9: note: declared here");490 ".tmp_source.zig:4:9: note: declared here",
491 );
393492
394 cases.add("function with invalid return type",493 cases.add(
494 "function with invalid return type",
395 \\export fn foo() boid {}495 \\export fn foo() boid {}
396 , ".tmp_source.zig:1:17: error: use of undeclared identifier 'boid'");496 ,
497 ".tmp_source.zig:1:17: error: use of undeclared identifier 'boid'",
498 );
397499
398 cases.add("function with non-extern non-packed enum parameter",500 cases.add(
501 "function with non-extern non-packed enum parameter",
399 \\const Foo = enum { A, B, C };502 \\const Foo = enum { A, B, C };
400 \\export fn entry(foo: Foo) void { }503 \\export fn entry(foo: Foo) void { }
401 , ".tmp_source.zig:2:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'");504 ,
505 ".tmp_source.zig:2:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'",
506 );
402507
403 cases.add("function with non-extern non-packed struct parameter",508 cases.add(
509 "function with non-extern non-packed struct parameter",
404 \\const Foo = struct {510 \\const Foo = struct {
405 \\ A: i32,511 \\ A: i32,
406 \\ B: f32,512 \\ B: f32,
407 \\ C: bool,513 \\ C: bool,
408 \\};514 \\};
409 \\export fn entry(foo: Foo) void { }515 \\export fn entry(foo: Foo) void { }
410 , ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'");516 ,
517 ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'",
518 );
411519
412 cases.add("function with non-extern non-packed union parameter",520 cases.add(
521 "function with non-extern non-packed union parameter",
413 \\const Foo = union {522 \\const Foo = union {
414 \\ A: i32,523 \\ A: i32,
415 \\ B: f32,524 \\ B: f32,
416 \\ C: bool,525 \\ C: bool,
417 \\};526 \\};
418 \\export fn entry(foo: Foo) void { }527 \\export fn entry(foo: Foo) void { }
419 , ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'");528 ,
529 ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'",
530 );
420531
421 cases.add("switch on enum with 1 field with no prongs",532 cases.add(
533 "switch on enum with 1 field with no prongs",
422 \\const Foo = enum { M };534 \\const Foo = enum { M };
423 \\535 \\
424 \\export fn entry() void {536 \\export fn entry() void {
425 \\ var f = Foo.M;537 \\ var f = Foo.M;
426 \\ switch (f) {}538 \\ switch (f) {}
427 \\}539 \\}
428 , ".tmp_source.zig:5:5: error: enumeration value 'Foo.M' not handled in switch");540 ,
541 ".tmp_source.zig:5:5: error: enumeration value 'Foo.M' not handled in switch",
542 );
429543
430 cases.add("shift by negative comptime integer",544 cases.add(
545 "shift by negative comptime integer",
431 \\comptime {546 \\comptime {
432 \\ var a = 1 >> -1;547 \\ var a = 1 >> -1;
433 \\}548 \\}
434 , ".tmp_source.zig:2:18: error: shift by negative value -1");549 ,
550 ".tmp_source.zig:2:18: error: shift by negative value -1",
551 );
435552
436 cases.add("@panic called at compile time",553 cases.add(
554 "@panic called at compile time",
437 \\export fn entry() void {555 \\export fn entry() void {
438 \\ comptime {556 \\ comptime {
439 \\ @panic("aoeu");557 \\ @panic("aoeu",);
440 \\ }558 \\ }
441 \\}559 \\}
442 , ".tmp_source.zig:3:9: error: encountered @panic at compile-time");560 ,
561 ".tmp_source.zig:3:9: error: encountered @panic at compile-time",
562 );
443563
444 cases.add("wrong return type for main",564 cases.add(
565 "wrong return type for main",
445 \\pub fn main() f32 { }566 \\pub fn main() f32 { }
446 , "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'");567 ,
568 "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'",
569 );
447570
448 cases.add("double ?? on main return value",571 cases.add(
572 "double ?? on main return value",
449 \\pub fn main() ??void {573 \\pub fn main() ??void {
450 \\}574 \\}
451 , "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'");575 ,
576 "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'",
577 );
452578
453 cases.add("bad identifier in function with struct defined inside function which references local const",579 cases.add(
580 "bad identifier in function with struct defined inside function which references local const",
454 \\export fn entry() void {581 \\export fn entry() void {
455 \\ const BlockKind = u32;582 \\ const BlockKind = u32;
456 \\583 \\
...@@ -460,9 +587,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -460,9 +587,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
460 \\587 \\
461 \\ bogus;588 \\ bogus;
462 \\}589 \\}
463 , ".tmp_source.zig:8:5: error: use of undeclared identifier 'bogus'");590 ,
591 ".tmp_source.zig:8:5: error: use of undeclared identifier 'bogus'",
592 );
464593
465 cases.add("labeled break not found",594 cases.add(
595 "labeled break not found",
466 \\export fn entry() void {596 \\export fn entry() void {
467 \\ blah: while (true) {597 \\ blah: while (true) {
468 \\ while (true) {598 \\ while (true) {
...@@ -470,9 +600,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -470,9 +600,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
470 \\ }600 \\ }
471 \\ }601 \\ }
472 \\}602 \\}
473 , ".tmp_source.zig:4:13: error: label not found: 'outer'");603 ,
604 ".tmp_source.zig:4:13: error: label not found: 'outer'",
605 );
474606
475 cases.add("labeled continue not found",607 cases.add(
608 "labeled continue not found",
476 \\export fn entry() void {609 \\export fn entry() void {
477 \\ var i: usize = 0;610 \\ var i: usize = 0;
478 \\ blah: while (i < 10) : (i += 1) {611 \\ blah: while (i < 10) : (i += 1) {
...@@ -481,400 +614,554 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -481,400 +614,554 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
481 \\ }614 \\ }
482 \\ }615 \\ }
483 \\}616 \\}
484 , ".tmp_source.zig:5:13: error: labeled loop not found: 'outer'");617 ,
618 ".tmp_source.zig:5:13: error: labeled loop not found: 'outer'",
619 );
485620
486 cases.add("attempt to use 0 bit type in extern fn",621 cases.add(
487 \\extern fn foo(ptr: extern fn(&void) void) void;622 "attempt to use 0 bit type in extern fn",
623 \\extern fn foo(ptr: extern fn(*void) void) void;
488 \\624 \\
489 \\export fn entry() void {625 \\export fn entry() void {
490 \\ foo(bar);626 \\ foo(bar);
491 \\}627 \\}
492 \\628 \\
493 \\extern fn bar(x: &void) void { }629 \\extern fn bar(x: *void) void { }
494 , ".tmp_source.zig:7:18: error: parameter of type '&void' has 0 bits; not allowed in function with calling convention 'ccc'");630 ,
631 ".tmp_source.zig:7:18: error: parameter of type '*void' has 0 bits; not allowed in function with calling convention 'ccc'",
632 );
495633
496 cases.add("implicit semicolon - block statement",634 cases.add(
635 "implicit semicolon - block statement",
497 \\export fn entry() void {636 \\export fn entry() void {
498 \\ {}637 \\ {}
499 \\ var good = {};638 \\ var good = {};
500 \\ ({})639 \\ ({})
501 \\ var bad = {};640 \\ var bad = {};
502 \\}641 \\}
503 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");642 ,
643 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
644 );
504645
505 cases.add("implicit semicolon - block expr",646 cases.add(
647 "implicit semicolon - block expr",
506 \\export fn entry() void {648 \\export fn entry() void {
507 \\ _ = {};649 \\ _ = {};
508 \\ var good = {};650 \\ var good = {};
509 \\ _ = {}651 \\ _ = {}
510 \\ var bad = {};652 \\ var bad = {};
511 \\}653 \\}
512 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");654 ,
655 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
656 );
513657
514 cases.add("implicit semicolon - comptime statement",658 cases.add(
659 "implicit semicolon - comptime statement",
515 \\export fn entry() void {660 \\export fn entry() void {
516 \\ comptime {}661 \\ comptime {}
517 \\ var good = {};662 \\ var good = {};
518 \\ comptime ({})663 \\ comptime ({})
519 \\ var bad = {};664 \\ var bad = {};
520 \\}665 \\}
521 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");666 ,
667 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
668 );
522669
523 cases.add("implicit semicolon - comptime expression",670 cases.add(
671 "implicit semicolon - comptime expression",
524 \\export fn entry() void {672 \\export fn entry() void {
525 \\ _ = comptime {};673 \\ _ = comptime {};
526 \\ var good = {};674 \\ var good = {};
527 \\ _ = comptime {}675 \\ _ = comptime {}
528 \\ var bad = {};676 \\ var bad = {};
529 \\}677 \\}
530 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");678 ,
679 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
680 );
531681
532 cases.add("implicit semicolon - defer",682 cases.add(
683 "implicit semicolon - defer",
533 \\export fn entry() void {684 \\export fn entry() void {
534 \\ defer {}685 \\ defer {}
535 \\ var good = {};686 \\ var good = {};
536 \\ defer ({})687 \\ defer ({})
537 \\ var bad = {};688 \\ var bad = {};
538 \\}689 \\}
539 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");690 ,
691 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
692 );
540693
541 cases.add("implicit semicolon - if statement",694 cases.add(
695 "implicit semicolon - if statement",
542 \\export fn entry() void {696 \\export fn entry() void {
543 \\ if(true) {}697 \\ if(true) {}
544 \\ var good = {};698 \\ var good = {};
545 \\ if(true) ({})699 \\ if(true) ({})
546 \\ var bad = {};700 \\ var bad = {};
547 \\}701 \\}
548 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");702 ,
703 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
704 );
549705
550 cases.add("implicit semicolon - if expression",706 cases.add(
707 "implicit semicolon - if expression",
551 \\export fn entry() void {708 \\export fn entry() void {
552 \\ _ = if(true) {};709 \\ _ = if(true) {};
553 \\ var good = {};710 \\ var good = {};
554 \\ _ = if(true) {}711 \\ _ = if(true) {}
555 \\ var bad = {};712 \\ var bad = {};
556 \\}713 \\}
557 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");714 ,
715 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
716 );
558717
559 cases.add("implicit semicolon - if-else statement",718 cases.add(
719 "implicit semicolon - if-else statement",
560 \\export fn entry() void {720 \\export fn entry() void {
561 \\ if(true) {} else {}721 \\ if(true) {} else {}
562 \\ var good = {};722 \\ var good = {};
563 \\ if(true) ({}) else ({})723 \\ if(true) ({}) else ({})
564 \\ var bad = {};724 \\ var bad = {};
565 \\}725 \\}
566 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");726 ,
727 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
728 );
567729
568 cases.add("implicit semicolon - if-else expression",730 cases.add(
731 "implicit semicolon - if-else expression",
569 \\export fn entry() void {732 \\export fn entry() void {
570 \\ _ = if(true) {} else {};733 \\ _ = if(true) {} else {};
571 \\ var good = {};734 \\ var good = {};
572 \\ _ = if(true) {} else {}735 \\ _ = if(true) {} else {}
573 \\ var bad = {};736 \\ var bad = {};
574 \\}737 \\}
575 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");738 ,
739 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
740 );
576741
577 cases.add("implicit semicolon - if-else-if statement",742 cases.add(
743 "implicit semicolon - if-else-if statement",
578 \\export fn entry() void {744 \\export fn entry() void {
579 \\ if(true) {} else if(true) {}745 \\ if(true) {} else if(true) {}
580 \\ var good = {};746 \\ var good = {};
581 \\ if(true) ({}) else if(true) ({})747 \\ if(true) ({}) else if(true) ({})
582 \\ var bad = {};748 \\ var bad = {};
583 \\}749 \\}
584 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");750 ,
751 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
752 );
585753
586 cases.add("implicit semicolon - if-else-if expression",754 cases.add(
755 "implicit semicolon - if-else-if expression",
587 \\export fn entry() void {756 \\export fn entry() void {
588 \\ _ = if(true) {} else if(true) {};757 \\ _ = if(true) {} else if(true) {};
589 \\ var good = {};758 \\ var good = {};
590 \\ _ = if(true) {} else if(true) {}759 \\ _ = if(true) {} else if(true) {}
591 \\ var bad = {};760 \\ var bad = {};
592 \\}761 \\}
593 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");762 ,
763 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
764 );
594765
595 cases.add("implicit semicolon - if-else-if-else statement",766 cases.add(
767 "implicit semicolon - if-else-if-else statement",
596 \\export fn entry() void {768 \\export fn entry() void {
597 \\ if(true) {} else if(true) {} else {}769 \\ if(true) {} else if(true) {} else {}
598 \\ var good = {};770 \\ var good = {};
599 \\ if(true) ({}) else if(true) ({}) else ({})771 \\ if(true) ({}) else if(true) ({}) else ({})
600 \\ var bad = {};772 \\ var bad = {};
601 \\}773 \\}
602 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");774 ,
775 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
776 );
603777
604 cases.add("implicit semicolon - if-else-if-else expression",778 cases.add(
779 "implicit semicolon - if-else-if-else expression",
605 \\export fn entry() void {780 \\export fn entry() void {
606 \\ _ = if(true) {} else if(true) {} else {};781 \\ _ = if(true) {} else if(true) {} else {};
607 \\ var good = {};782 \\ var good = {};
608 \\ _ = if(true) {} else if(true) {} else {}783 \\ _ = if(true) {} else if(true) {} else {}
609 \\ var bad = {};784 \\ var bad = {};
610 \\}785 \\}
611 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");786 ,
787 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
788 );
612789
613 cases.add("implicit semicolon - test statement",790 cases.add(
791 "implicit semicolon - test statement",
614 \\export fn entry() void {792 \\export fn entry() void {
615 \\ if (foo()) |_| {}793 \\ if (foo()) |_| {}
616 \\ var good = {};794 \\ var good = {};
617 \\ if (foo()) |_| ({})795 \\ if (foo()) |_| ({})
618 \\ var bad = {};796 \\ var bad = {};
619 \\}797 \\}
620 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");798 ,
799 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
800 );
621801
622 cases.add("implicit semicolon - test expression",802 cases.add(
803 "implicit semicolon - test expression",
623 \\export fn entry() void {804 \\export fn entry() void {
624 \\ _ = if (foo()) |_| {};805 \\ _ = if (foo()) |_| {};
625 \\ var good = {};806 \\ var good = {};
626 \\ _ = if (foo()) |_| {}807 \\ _ = if (foo()) |_| {}
627 \\ var bad = {};808 \\ var bad = {};
628 \\}809 \\}
629 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");810 ,
811 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
812 );
630813
631 cases.add("implicit semicolon - while statement",814 cases.add(
815 "implicit semicolon - while statement",
632 \\export fn entry() void {816 \\export fn entry() void {
633 \\ while(true) {}817 \\ while(true) {}
634 \\ var good = {};818 \\ var good = {};
635 \\ while(true) ({})819 \\ while(true) ({})
636 \\ var bad = {};820 \\ var bad = {};
637 \\}821 \\}
638 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");822 ,
823 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
824 );
639825
640 cases.add("implicit semicolon - while expression",826 cases.add(
827 "implicit semicolon - while expression",
641 \\export fn entry() void {828 \\export fn entry() void {
642 \\ _ = while(true) {};829 \\ _ = while(true) {};
643 \\ var good = {};830 \\ var good = {};
644 \\ _ = while(true) {}831 \\ _ = while(true) {}
645 \\ var bad = {};832 \\ var bad = {};
646 \\}833 \\}
647 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");834 ,
835 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
836 );
648837
649 cases.add("implicit semicolon - while-continue statement",838 cases.add(
839 "implicit semicolon - while-continue statement",
650 \\export fn entry() void {840 \\export fn entry() void {
651 \\ while(true):({}) {}841 \\ while(true):({}) {}
652 \\ var good = {};842 \\ var good = {};
653 \\ while(true):({}) ({})843 \\ while(true):({}) ({})
654 \\ var bad = {};844 \\ var bad = {};
655 \\}845 \\}
656 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");846 ,
847 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
848 );
657849
658 cases.add("implicit semicolon - while-continue expression",850 cases.add(
851 "implicit semicolon - while-continue expression",
659 \\export fn entry() void {852 \\export fn entry() void {
660 \\ _ = while(true):({}) {};853 \\ _ = while(true):({}) {};
661 \\ var good = {};854 \\ var good = {};
662 \\ _ = while(true):({}) {}855 \\ _ = while(true):({}) {}
663 \\ var bad = {};856 \\ var bad = {};
664 \\}857 \\}
665 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");858 ,
859 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
860 );
666861
667 cases.add("implicit semicolon - for statement",862 cases.add(
863 "implicit semicolon - for statement",
668 \\export fn entry() void {864 \\export fn entry() void {
669 \\ for(foo()) {}865 \\ for(foo()) {}
670 \\ var good = {};866 \\ var good = {};
671 \\ for(foo()) ({})867 \\ for(foo()) ({})
672 \\ var bad = {};868 \\ var bad = {};
673 \\}869 \\}
674 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");870 ,
871 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
872 );
675873
676 cases.add("implicit semicolon - for expression",874 cases.add(
875 "implicit semicolon - for expression",
677 \\export fn entry() void {876 \\export fn entry() void {
678 \\ _ = for(foo()) {};877 \\ _ = for(foo()) {};
679 \\ var good = {};878 \\ var good = {};
680 \\ _ = for(foo()) {}879 \\ _ = for(foo()) {}
681 \\ var bad = {};880 \\ var bad = {};
682 \\}881 \\}
683 , ".tmp_source.zig:5:5: error: expected token ';', found 'var'");882 ,
883 ".tmp_source.zig:5:5: error: expected token ';', found 'var'",
884 );
684885
685 cases.add("multiple function definitions",886 cases.add(
887 "multiple function definitions",
686 \\fn a() void {}888 \\fn a() void {}
687 \\fn a() void {}889 \\fn a() void {}
688 \\export fn entry() void { a(); }890 \\export fn entry() void { a(); }
689 , ".tmp_source.zig:2:1: error: redefinition of 'a'");891 ,
892 ".tmp_source.zig:2:1: error: redefinition of 'a'",
893 );
690894
691 cases.add("unreachable with return",895 cases.add(
896 "unreachable with return",
692 \\fn a() noreturn {return;}897 \\fn a() noreturn {return;}
693 \\export fn entry() void { a(); }898 \\export fn entry() void { a(); }
694 , ".tmp_source.zig:1:18: error: expected type 'noreturn', found 'void'");899 ,
900 ".tmp_source.zig:1:18: error: expected type 'noreturn', found 'void'",
901 );
695902
696 cases.add("control reaches end of non-void function",903 cases.add(
904 "control reaches end of non-void function",
697 \\fn a() i32 {}905 \\fn a() i32 {}
698 \\export fn entry() void { _ = a(); }906 \\export fn entry() void { _ = a(); }
699 , ".tmp_source.zig:1:12: error: expected type 'i32', found 'void'");907 ,
908 ".tmp_source.zig:1:12: error: expected type 'i32', found 'void'",
909 );
700910
701 cases.add("undefined function call",911 cases.add(
912 "undefined function call",
702 \\export fn a() void {913 \\export fn a() void {
703 \\ b();914 \\ b();
704 \\}915 \\}
705 , ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'");916 ,
917 ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'",
918 );
706919
707 cases.add("wrong number of arguments",920 cases.add(
921 "wrong number of arguments",
708 \\export fn a() void {922 \\export fn a() void {
709 \\ b(1);923 \\ b(1);
710 \\}924 \\}
711 \\fn b(a: i32, b: i32, c: i32) void { }925 \\fn b(a: i32, b: i32, c: i32) void { }
712 , ".tmp_source.zig:2:6: error: expected 3 arguments, found 1");926 ,
927 ".tmp_source.zig:2:6: error: expected 3 arguments, found 1",
928 );
713929
714 cases.add("invalid type",930 cases.add(
931 "invalid type",
715 \\fn a() bogus {}932 \\fn a() bogus {}
716 \\export fn entry() void { _ = a(); }933 \\export fn entry() void { _ = a(); }
717 , ".tmp_source.zig:1:8: error: use of undeclared identifier 'bogus'");934 ,
935 ".tmp_source.zig:1:8: error: use of undeclared identifier 'bogus'",
936 );
718937
719 cases.add("pointer to noreturn",938 cases.add(
720 \\fn a() &noreturn {}939 "pointer to noreturn",
940 \\fn a() *noreturn {}
721 \\export fn entry() void { _ = a(); }941 \\export fn entry() void { _ = a(); }
722 , ".tmp_source.zig:1:9: error: pointer to noreturn not allowed");942 ,
943 ".tmp_source.zig:1:8: error: pointer to noreturn not allowed",
944 );
723945
724 cases.add("unreachable code",946 cases.add(
947 "unreachable code",
725 \\export fn a() void {948 \\export fn a() void {
726 \\ return;949 \\ return;
727 \\ b();950 \\ b();
728 \\}951 \\}
729 \\952 \\
730 \\fn b() void {}953 \\fn b() void {}
731 , ".tmp_source.zig:3:5: error: unreachable code");954 ,
955 ".tmp_source.zig:3:5: error: unreachable code",
956 );
732957
733 cases.add("bad import",958 cases.add(
734 \\const bogus = @import("bogus-does-not-exist.zig");959 "bad import",
960 \\const bogus = @import("bogus-does-not-exist.zig",);
735 \\export fn entry() void { bogus.bogo(); }961 \\export fn entry() void { bogus.bogo(); }
736 , ".tmp_source.zig:1:15: error: unable to find 'bogus-does-not-exist.zig'");962 ,
963 ".tmp_source.zig:1:15: error: unable to find 'bogus-does-not-exist.zig'",
964 );
737965
738 cases.add("undeclared identifier",966 cases.add(
967 "undeclared identifier",
739 \\export fn a() void {968 \\export fn a() void {
740 \\ return969 \\ return
741 \\ b +970 \\ b +
742 \\ c;971 \\ c;
743 \\}972 \\}
744 ,973 ,
745 ".tmp_source.zig:3:5: error: use of undeclared identifier 'b'",974 ".tmp_source.zig:3:5: error: use of undeclared identifier 'b'",
746 ".tmp_source.zig:4:5: error: use of undeclared identifier 'c'");975 ".tmp_source.zig:4:5: error: use of undeclared identifier 'c'",
976 );
747977
748 cases.add("parameter redeclaration",978 cases.add(
979 "parameter redeclaration",
749 \\fn f(a : i32, a : i32) void {980 \\fn f(a : i32, a : i32) void {
750 \\}981 \\}
751 \\export fn entry() void { f(1, 2); }982 \\export fn entry() void { f(1, 2); }
752 , ".tmp_source.zig:1:15: error: redeclaration of variable 'a'");983 ,
984 ".tmp_source.zig:1:15: error: redeclaration of variable 'a'",
985 );
753986
754 cases.add("local variable redeclaration",987 cases.add(
988 "local variable redeclaration",
755 \\export fn f() void {989 \\export fn f() void {
756 \\ const a : i32 = 0;990 \\ const a : i32 = 0;
757 \\ const a = 0;991 \\ const a = 0;
758 \\}992 \\}
759 , ".tmp_source.zig:3:5: error: redeclaration of variable 'a'");993 ,
994 ".tmp_source.zig:3:5: error: redeclaration of variable 'a'",
995 );
760996
761 cases.add("local variable redeclares parameter",997 cases.add(
998 "local variable redeclares parameter",
762 \\fn f(a : i32) void {999 \\fn f(a : i32) void {
763 \\ const a = 0;1000 \\ const a = 0;
764 \\}1001 \\}
765 \\export fn entry() void { f(1); }1002 \\export fn entry() void { f(1); }
766 , ".tmp_source.zig:2:5: error: redeclaration of variable 'a'");1003 ,
1004 ".tmp_source.zig:2:5: error: redeclaration of variable 'a'",
1005 );
7671006
768 cases.add("variable has wrong type",1007 cases.add(
1008 "variable has wrong type",
769 \\export fn f() i32 {1009 \\export fn f() i32 {
770 \\ const a = c"a";1010 \\ const a = c"a";
771 \\ return a;1011 \\ return a;
772 \\}1012 \\}
773 , ".tmp_source.zig:3:12: error: expected type 'i32', found '&const u8'");1013 ,
1014 ".tmp_source.zig:3:12: error: expected type 'i32', found '[*]const u8'",
1015 );
7741016
775 cases.add("if condition is bool, not int",1017 cases.add(
1018 "if condition is bool, not int",
776 \\export fn f() void {1019 \\export fn f() void {
777 \\ if (0) {}1020 \\ if (0) {}
778 \\}1021 \\}
779 , ".tmp_source.zig:2:9: error: integer value 0 cannot be implicitly casted to type 'bool'");1022 ,
1023 ".tmp_source.zig:2:9: error: integer value 0 cannot be implicitly casted to type 'bool'",
1024 );
7801025
781 cases.add("assign unreachable",1026 cases.add(
1027 "assign unreachable",
782 \\export fn f() void {1028 \\export fn f() void {
783 \\ const a = return;1029 \\ const a = return;
784 \\}1030 \\}
785 , ".tmp_source.zig:2:5: error: unreachable code");1031 ,
1032 ".tmp_source.zig:2:5: error: unreachable code",
1033 );
7861034
787 cases.add("unreachable variable",1035 cases.add(
1036 "unreachable variable",
788 \\export fn f() void {1037 \\export fn f() void {
789 \\ const a: noreturn = {};1038 \\ const a: noreturn = {};
790 \\}1039 \\}
791 , ".tmp_source.zig:2:14: error: variable of type 'noreturn' not allowed");1040 ,
1041 ".tmp_source.zig:2:14: error: variable of type 'noreturn' not allowed",
1042 );
7921043
793 cases.add("unreachable parameter",1044 cases.add(
1045 "unreachable parameter",
794 \\fn f(a: noreturn) void {}1046 \\fn f(a: noreturn) void {}
795 \\export fn entry() void { f(); }1047 \\export fn entry() void { f(); }
796 , ".tmp_source.zig:1:9: error: parameter of type 'noreturn' not allowed");1048 ,
1049 ".tmp_source.zig:1:9: error: parameter of type 'noreturn' not allowed",
1050 );
7971051
798 cases.add("bad assignment target",1052 cases.add(
1053 "bad assignment target",
799 \\export fn f() void {1054 \\export fn f() void {
800 \\ 3 = 3;1055 \\ 3 = 3;
801 \\}1056 \\}
802 , ".tmp_source.zig:2:7: error: cannot assign to constant");1057 ,
1058 ".tmp_source.zig:2:7: error: cannot assign to constant",
1059 );
8031060
804 cases.add("assign to constant variable",1061 cases.add(
1062 "assign to constant variable",
805 \\export fn f() void {1063 \\export fn f() void {
806 \\ const a = 3;1064 \\ const a = 3;
807 \\ a = 4;1065 \\ a = 4;
808 \\}1066 \\}
809 , ".tmp_source.zig:3:7: error: cannot assign to constant");1067 ,
1068 ".tmp_source.zig:3:7: error: cannot assign to constant",
1069 );
8101070
811 cases.add("use of undeclared identifier",1071 cases.add(
1072 "use of undeclared identifier",
812 \\export fn f() void {1073 \\export fn f() void {
813 \\ b = 3;1074 \\ b = 3;
814 \\}1075 \\}
815 , ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'");1076 ,
1077 ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'",
1078 );
8161079
817 cases.add("const is a statement, not an expression",1080 cases.add(
1081 "const is a statement, not an expression",
818 \\export fn f() void {1082 \\export fn f() void {
819 \\ (const a = 0);1083 \\ (const a = 0);
820 \\}1084 \\}
821 , ".tmp_source.zig:2:6: error: invalid token: 'const'");1085 ,
1086 ".tmp_source.zig:2:6: error: invalid token: 'const'",
1087 );
8221088
823 cases.add("array access of undeclared identifier",1089 cases.add(
1090 "array access of undeclared identifier",
824 \\export fn f() void {1091 \\export fn f() void {
825 \\ i[i] = i[i];1092 \\ i[i] = i[i];
826 \\}1093 \\}
827 , ".tmp_source.zig:2:5: error: use of undeclared identifier 'i'",1094 ,
828 ".tmp_source.zig:2:12: error: use of undeclared identifier 'i'");1095 ".tmp_source.zig:2:5: error: use of undeclared identifier 'i'",
1096 ".tmp_source.zig:2:12: error: use of undeclared identifier 'i'",
1097 );
8291098
830 cases.add("array access of non array",1099 cases.add(
1100 "array access of non array",
831 \\export fn f() void {1101 \\export fn f() void {
832 \\ var bad : bool = undefined;1102 \\ var bad : bool = undefined;
833 \\ bad[bad] = bad[bad];1103 \\ bad[bad] = bad[bad];
834 \\}1104 \\}
835 , ".tmp_source.zig:3:8: error: array access of non-array type 'bool'",1105 ,
836 ".tmp_source.zig:3:19: error: array access of non-array type 'bool'");1106 ".tmp_source.zig:3:8: error: array access of non-array type 'bool'",
1107 ".tmp_source.zig:3:19: error: array access of non-array type 'bool'",
1108 );
8371109
838 cases.add("array access with non integer index",1110 cases.add(
1111 "array access with non integer index",
839 \\export fn f() void {1112 \\export fn f() void {
840 \\ var array = "aoeu";1113 \\ var array = "aoeu";
841 \\ var bad = false;1114 \\ var bad = false;
842 \\ array[bad] = array[bad];1115 \\ array[bad] = array[bad];
843 \\}1116 \\}
844 , ".tmp_source.zig:4:11: error: expected type 'usize', found 'bool'",1117 ,
845 ".tmp_source.zig:4:24: error: expected type 'usize', found 'bool'");1118 ".tmp_source.zig:4:11: error: expected type 'usize', found 'bool'",
1119 ".tmp_source.zig:4:24: error: expected type 'usize', found 'bool'",
1120 );
8461121
847 cases.add("write to const global variable",1122 cases.add(
1123 "write to const global variable",
848 \\const x : i32 = 99;1124 \\const x : i32 = 99;
849 \\fn f() void {1125 \\fn f() void {
850 \\ x = 1;1126 \\ x = 1;
851 \\}1127 \\}
852 \\export fn entry() void { f(); }1128 \\export fn entry() void { f(); }
853 , ".tmp_source.zig:3:7: error: cannot assign to constant");1129 ,
8541130 ".tmp_source.zig:3:7: error: cannot assign to constant",
1131 );
8551132
856 cases.add("missing else clause",1133 cases.add(
1134 "missing else clause",
857 \\fn f(b: bool) void {1135 \\fn f(b: bool) void {
858 \\ const x : i32 = if (b) h: { break :h 1; };1136 \\ const x : i32 = if (b) h: { break :h 1; };
859 \\ const y = if (b) h: { break :h i32(1); };1137 \\ const y = if (b) h: { break :h i32(1); };
860 \\}1138 \\}
861 \\export fn entry() void { f(true); }1139 \\export fn entry() void { f(true); }
862 , ".tmp_source.zig:2:42: error: integer value 1 cannot be implicitly casted to type 'void'",1140 ,
863 ".tmp_source.zig:3:15: error: incompatible types: 'i32' and 'void'");1141 ".tmp_source.zig:2:42: error: integer value 1 cannot be implicitly casted to type 'void'",
1142 ".tmp_source.zig:3:15: error: incompatible types: 'i32' and 'void'",
1143 );
8641144
865 cases.add("direct struct loop",1145 cases.add(
1146 "direct struct loop",
866 \\const A = struct { a : A, };1147 \\const A = struct { a : A, };
867 \\export fn entry() usize { return @sizeOf(A); }1148 \\export fn entry() usize { return @sizeOf(A); }
868 , ".tmp_source.zig:1:11: error: struct 'A' contains itself");1149 ,
1150 ".tmp_source.zig:1:11: error: struct 'A' contains itself",
1151 );
8691152
870 cases.add("indirect struct loop",1153 cases.add(
1154 "indirect struct loop",
871 \\const A = struct { b : B, };1155 \\const A = struct { b : B, };
872 \\const B = struct { c : C, };1156 \\const B = struct { c : C, };
873 \\const C = struct { a : A, };1157 \\const C = struct { a : A, };
874 \\export fn entry() usize { return @sizeOf(A); }1158 \\export fn entry() usize { return @sizeOf(A); }
875 , ".tmp_source.zig:1:11: error: struct 'A' contains itself");1159 ,
1160 ".tmp_source.zig:1:11: error: struct 'A' contains itself",
1161 );
8761162
877 cases.add("invalid struct field",1163 cases.add(
1164 "invalid struct field",
878 \\const A = struct { x : i32, };1165 \\const A = struct { x : i32, };
879 \\export fn f() void {1166 \\export fn f() void {
880 \\ var a : A = undefined;1167 \\ var a : A = undefined;
...@@ -882,27 +1169,37 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -882,27 +1169,37 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
882 \\ const y = a.bar;1169 \\ const y = a.bar;
883 \\}1170 \\}
884 ,1171 ,
885 ".tmp_source.zig:4:6: error: no member named 'foo' in struct 'A'",1172 ".tmp_source.zig:4:6: error: no member named 'foo' in struct 'A'",
886 ".tmp_source.zig:5:16: error: no member named 'bar' in struct 'A'");1173 ".tmp_source.zig:5:16: error: no member named 'bar' in struct 'A'",
1174 );
8871175
888 cases.add("redefinition of struct",1176 cases.add(
1177 "redefinition of struct",
889 \\const A = struct { x : i32, };1178 \\const A = struct { x : i32, };
890 \\const A = struct { y : i32, };1179 \\const A = struct { y : i32, };
891 , ".tmp_source.zig:2:1: error: redefinition of 'A'");1180 ,
1181 ".tmp_source.zig:2:1: error: redefinition of 'A'",
1182 );
8921183
893 cases.add("redefinition of enums",1184 cases.add(
1185 "redefinition of enums",
894 \\const A = enum {};1186 \\const A = enum {};
895 \\const A = enum {};1187 \\const A = enum {};
896 , ".tmp_source.zig:2:1: error: redefinition of 'A'");1188 ,
1189 ".tmp_source.zig:2:1: error: redefinition of 'A'",
1190 );
8971191
898 cases.add("redefinition of global variables",1192 cases.add(
1193 "redefinition of global variables",
899 \\var a : i32 = 1;1194 \\var a : i32 = 1;
900 \\var a : i32 = 2;1195 \\var a : i32 = 2;
901 ,1196 ,
902 ".tmp_source.zig:2:1: error: redefinition of 'a'",1197 ".tmp_source.zig:2:1: error: redefinition of 'a'",
903 ".tmp_source.zig:1:1: note: previous definition is here");1198 ".tmp_source.zig:1:1: note: previous definition is here",
1199 );
9041200
905 cases.add("duplicate field in struct value expression",1201 cases.add(
1202 "duplicate field in struct value expression",
906 \\const A = struct {1203 \\const A = struct {
907 \\ x : i32,1204 \\ x : i32,
908 \\ y : i32,1205 \\ y : i32,
...@@ -916,9 +1213,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -916,9 +1213,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
916 \\ .z = 4,1213 \\ .z = 4,
917 \\ };1214 \\ };
918 \\}1215 \\}
919 , ".tmp_source.zig:11:9: error: duplicate field");1216 ,
1217 ".tmp_source.zig:11:9: error: duplicate field",
1218 );
9201219
921 cases.add("missing field in struct value expression",1220 cases.add(
1221 "missing field in struct value expression",
922 \\const A = struct {1222 \\const A = struct {
923 \\ x : i32,1223 \\ x : i32,
924 \\ y : i32,1224 \\ y : i32,
...@@ -932,9 +1232,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -932,9 +1232,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
932 \\ .y = 2,1232 \\ .y = 2,
933 \\ };1233 \\ };
934 \\}1234 \\}
935 , ".tmp_source.zig:9:17: error: missing field: 'x'");1235 ,
1236 ".tmp_source.zig:9:17: error: missing field: 'x'",
1237 );
9361238
937 cases.add("invalid field in struct value expression",1239 cases.add(
1240 "invalid field in struct value expression",
938 \\const A = struct {1241 \\const A = struct {
939 \\ x : i32,1242 \\ x : i32,
940 \\ y : i32,1243 \\ y : i32,
...@@ -947,66 +1250,95 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -947,66 +1250,95 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
947 \\ .foo = 42,1250 \\ .foo = 42,
948 \\ };1251 \\ };
949 \\}1252 \\}
950 , ".tmp_source.zig:10:9: error: no member named 'foo' in struct 'A'");1253 ,
1254 ".tmp_source.zig:10:9: error: no member named 'foo' in struct 'A'",
1255 );
9511256
952 cases.add("invalid break expression",1257 cases.add(
1258 "invalid break expression",
953 \\export fn f() void {1259 \\export fn f() void {
954 \\ break;1260 \\ break;
955 \\}1261 \\}
956 , ".tmp_source.zig:2:5: error: break expression outside loop");1262 ,
1263 ".tmp_source.zig:2:5: error: break expression outside loop",
1264 );
9571265
958 cases.add("invalid continue expression",1266 cases.add(
1267 "invalid continue expression",
959 \\export fn f() void {1268 \\export fn f() void {
960 \\ continue;1269 \\ continue;
961 \\}1270 \\}
962 , ".tmp_source.zig:2:5: error: continue expression outside loop");1271 ,
1272 ".tmp_source.zig:2:5: error: continue expression outside loop",
1273 );
9631274
964 cases.add("invalid maybe type",1275 cases.add(
1276 "invalid maybe type",
965 \\export fn f() void {1277 \\export fn f() void {
966 \\ if (true) |x| { }1278 \\ if (true) |x| { }
967 \\}1279 \\}
968 , ".tmp_source.zig:2:9: error: expected nullable type, found 'bool'");1280 ,
1281 ".tmp_source.zig:2:9: error: expected nullable type, found 'bool'",
1282 );
9691283
970 cases.add("cast unreachable",1284 cases.add(
1285 "cast unreachable",
971 \\fn f() i32 {1286 \\fn f() i32 {
972 \\ return i32(return 1);1287 \\ return i32(return 1);
973 \\}1288 \\}
974 \\export fn entry() void { _ = f(); }1289 \\export fn entry() void { _ = f(); }
975 , ".tmp_source.zig:2:15: error: unreachable code");1290 ,
1291 ".tmp_source.zig:2:15: error: unreachable code",
1292 );
9761293
977 cases.add("invalid builtin fn",1294 cases.add(
1295 "invalid builtin fn",
978 \\fn f() @bogus(foo) {1296 \\fn f() @bogus(foo) {
979 \\}1297 \\}
980 \\export fn entry() void { _ = f(); }1298 \\export fn entry() void { _ = f(); }
981 , ".tmp_source.zig:1:8: error: invalid builtin function: 'bogus'");1299 ,
1300 ".tmp_source.zig:1:8: error: invalid builtin function: 'bogus'",
1301 );
9821302
983 cases.add("top level decl dependency loop",1303 cases.add(
1304 "top level decl dependency loop",
984 \\const a : @typeOf(b) = 0;1305 \\const a : @typeOf(b) = 0;
985 \\const b : @typeOf(a) = 0;1306 \\const b : @typeOf(a) = 0;
986 \\export fn entry() void {1307 \\export fn entry() void {
987 \\ const c = a + b;1308 \\ const c = a + b;
988 \\}1309 \\}
989 , ".tmp_source.zig:1:1: error: 'a' depends on itself");1310 ,
1311 ".tmp_source.zig:1:1: error: 'a' depends on itself",
1312 );
9901313
991 cases.add("noalias on non pointer param",1314 cases.add(
1315 "noalias on non pointer param",
992 \\fn f(noalias x: i32) void {}1316 \\fn f(noalias x: i32) void {}
993 \\export fn entry() void { f(1234); }1317 \\export fn entry() void { f(1234); }
994 , ".tmp_source.zig:1:6: error: noalias on non-pointer parameter");1318 ,
1319 ".tmp_source.zig:1:6: error: noalias on non-pointer parameter",
1320 );
9951321
996 cases.add("struct init syntax for array",1322 cases.add(
1323 "struct init syntax for array",
997 \\const foo = []u16{.x = 1024,};1324 \\const foo = []u16{.x = 1024,};
998 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }1325 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
999 , ".tmp_source.zig:1:18: error: type '[]u16' does not support struct initialization syntax");1326 ,
1327 ".tmp_source.zig:1:18: error: type '[]u16' does not support struct initialization syntax",
1328 );
10001329
1001 cases.add("type variables must be constant",1330 cases.add(
1331 "type variables must be constant",
1002 \\var foo = u8;1332 \\var foo = u8;
1003 \\export fn entry() foo {1333 \\export fn entry() foo {
1004 \\ return 1;1334 \\ return 1;
1005 \\}1335 \\}
1006 , ".tmp_source.zig:1:1: error: variable of type 'type' must be constant");1336 ,
10071337 ".tmp_source.zig:1:1: error: variable of type 'type' must be constant",
1338 );
10081339
1009 cases.add("variables shadowing types",1340 cases.add(
1341 "variables shadowing types",
1010 \\const Foo = struct {};1342 \\const Foo = struct {};
1011 \\const Bar = struct {};1343 \\const Bar = struct {};
1012 \\1344 \\
...@@ -1018,12 +1350,14 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1018,12 +1350,14 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1018 \\ f(1234);1350 \\ f(1234);
1019 \\}1351 \\}
1020 ,1352 ,
1021 ".tmp_source.zig:4:6: error: redefinition of 'Foo'",1353 ".tmp_source.zig:4:6: error: redefinition of 'Foo'",
1022 ".tmp_source.zig:1:1: note: previous definition is here",1354 ".tmp_source.zig:1:1: note: previous definition is here",
1023 ".tmp_source.zig:5:5: error: redefinition of 'Bar'",1355 ".tmp_source.zig:5:5: error: redefinition of 'Bar'",
1024 ".tmp_source.zig:2:1: note: previous definition is here");1356 ".tmp_source.zig:2:1: note: previous definition is here",
1357 );
10251358
1026 cases.add("switch expression - missing enumeration prong",1359 cases.add(
1360 "switch expression - missing enumeration prong",
1027 \\const Number = enum {1361 \\const Number = enum {
1028 \\ One,1362 \\ One,
1029 \\ Two,1363 \\ Two,
...@@ -1039,9 +1373,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1039,9 +1373,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1039 \\}1373 \\}
1040 \\1374 \\
1041 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }1375 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }
1042 , ".tmp_source.zig:8:5: error: enumeration value 'Number.Four' not handled in switch");1376 ,
1377 ".tmp_source.zig:8:5: error: enumeration value 'Number.Four' not handled in switch",
1378 );
10431379
1044 cases.add("switch expression - duplicate enumeration prong",1380 cases.add(
1381 "switch expression - duplicate enumeration prong",
1045 \\const Number = enum {1382 \\const Number = enum {
1046 \\ One,1383 \\ One,
1047 \\ Two,1384 \\ Two,
...@@ -1059,10 +1396,13 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1059,10 +1396,13 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1059 \\}1396 \\}
1060 \\1397 \\
1061 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }1398 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }
1062 , ".tmp_source.zig:13:15: error: duplicate switch value",1399 ,
1063 ".tmp_source.zig:10:15: note: other value is here");1400 ".tmp_source.zig:13:15: error: duplicate switch value",
1401 ".tmp_source.zig:10:15: note: other value is here",
1402 );
10641403
1065 cases.add("switch expression - duplicate enumeration prong when else present",1404 cases.add(
1405 "switch expression - duplicate enumeration prong when else present",
1066 \\const Number = enum {1406 \\const Number = enum {
1067 \\ One,1407 \\ One,
1068 \\ Two,1408 \\ Two,
...@@ -1081,10 +1421,13 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1081,10 +1421,13 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1081 \\}1421 \\}
1082 \\1422 \\
1083 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }1423 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }
1084 , ".tmp_source.zig:13:15: error: duplicate switch value",1424 ,
1085 ".tmp_source.zig:10:15: note: other value is here");1425 ".tmp_source.zig:13:15: error: duplicate switch value",
1426 ".tmp_source.zig:10:15: note: other value is here",
1427 );
10861428
1087 cases.add("switch expression - multiple else prongs",1429 cases.add(
1430 "switch expression - multiple else prongs",
1088 \\fn f(x: u32) void {1431 \\fn f(x: u32) void {
1089 \\ const value: bool = switch (x) {1432 \\ const value: bool = switch (x) {
1090 \\ 1234 => false,1433 \\ 1234 => false,
...@@ -1095,9 +1438,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1095,9 +1438,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1095 \\export fn entry() void {1438 \\export fn entry() void {
1096 \\ f(1234);1439 \\ f(1234);
1097 \\}1440 \\}
1098 , ".tmp_source.zig:5:9: error: multiple else prongs in switch expression");1441 ,
1442 ".tmp_source.zig:5:9: error: multiple else prongs in switch expression",
1443 );
10991444
1100 cases.add("switch expression - non exhaustive integer prongs",1445 cases.add(
1446 "switch expression - non exhaustive integer prongs",
1101 \\fn foo(x: u8) void {1447 \\fn foo(x: u8) void {
1102 \\ switch (x) {1448 \\ switch (x) {
1103 \\ 0 => {},1449 \\ 0 => {},
...@@ -1105,9 +1451,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1105,9 +1451,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1105 \\}1451 \\}
1106 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }1452 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1107 ,1453 ,
1108 ".tmp_source.zig:2:5: error: switch must handle all possibilities");1454 ".tmp_source.zig:2:5: error: switch must handle all possibilities",
1455 );
11091456
1110 cases.add("switch expression - duplicate or overlapping integer value",1457 cases.add(
1458 "switch expression - duplicate or overlapping integer value",
1111 \\fn foo(x: u8) u8 {1459 \\fn foo(x: u8) u8 {
1112 \\ return switch (x) {1460 \\ return switch (x) {
1113 \\ 0 ... 100 => u8(0),1461 \\ 0 ... 100 => u8(0),
...@@ -1119,10 +1467,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1119,10 +1467,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1119 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }1467 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1120 ,1468 ,
1121 ".tmp_source.zig:6:9: error: duplicate switch value",1469 ".tmp_source.zig:6:9: error: duplicate switch value",
1122 ".tmp_source.zig:5:14: note: previous value is here");1470 ".tmp_source.zig:5:14: note: previous value is here",
1471 );
11231472
1124 cases.add("switch expression - switch on pointer type with no else",1473 cases.add(
1125 \\fn foo(x: &u8) void {1474 "switch expression - switch on pointer type with no else",
1475 \\fn foo(x: *u8) void {
1126 \\ switch (x) {1476 \\ switch (x) {
1127 \\ &y => {},1477 \\ &y => {},
1128 \\ }1478 \\ }
...@@ -1130,62 +1480,85 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1130,62 +1480,85 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1130 \\const y: u8 = 100;1480 \\const y: u8 = 100;
1131 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }1481 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1132 ,1482 ,
1133 ".tmp_source.zig:2:5: error: else prong required when switching on type '&u8'");1483 ".tmp_source.zig:2:5: error: else prong required when switching on type '*u8'",
1484 );
11341485
1135 cases.add("global variable initializer must be constant expression",1486 cases.add(
1487 "global variable initializer must be constant expression",
1136 \\extern fn foo() i32;1488 \\extern fn foo() i32;
1137 \\const x = foo();1489 \\const x = foo();
1138 \\export fn entry() i32 { return x; }1490 \\export fn entry() i32 { return x; }
1139 , ".tmp_source.zig:2:11: error: unable to evaluate constant expression");1491 ,
1492 ".tmp_source.zig:2:11: error: unable to evaluate constant expression",
1493 );
11401494
1141 cases.add("array concatenation with wrong type",1495 cases.add(
1496 "array concatenation with wrong type",
1142 \\const src = "aoeu";1497 \\const src = "aoeu";
1143 \\const derp = usize(1234);1498 \\const derp = usize(1234);
1144 \\const a = derp ++ "foo";1499 \\const a = derp ++ "foo";
1145 \\1500 \\
1146 \\export fn entry() usize { return @sizeOf(@typeOf(a)); }1501 \\export fn entry() usize { return @sizeOf(@typeOf(a)); }
1147 , ".tmp_source.zig:3:11: error: expected array or C string literal, found 'usize'");1502 ,
1503 ".tmp_source.zig:3:11: error: expected array or C string literal, found 'usize'",
1504 );
11481505
1149 cases.add("non compile time array concatenation",1506 cases.add(
1507 "non compile time array concatenation",
1150 \\fn f() []u8 {1508 \\fn f() []u8 {
1151 \\ return s ++ "foo";1509 \\ return s ++ "foo";
1152 \\}1510 \\}
1153 \\var s: [10]u8 = undefined;1511 \\var s: [10]u8 = undefined;
1154 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }1512 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }
1155 , ".tmp_source.zig:2:12: error: unable to evaluate constant expression");1513 ,
1514 ".tmp_source.zig:2:12: error: unable to evaluate constant expression",
1515 );
11561516
1157 cases.add("@cImport with bogus include",1517 cases.add(
1518 "@cImport with bogus include",
1158 \\const c = @cImport(@cInclude("bogus.h"));1519 \\const c = @cImport(@cInclude("bogus.h"));
1159 \\export fn entry() usize { return @sizeOf(@typeOf(c.bogo)); }1520 \\export fn entry() usize { return @sizeOf(@typeOf(c.bogo)); }
1160 , ".tmp_source.zig:1:11: error: C import failed",1521 ,
1161 ".h:1:10: note: 'bogus.h' file not found");1522 ".tmp_source.zig:1:11: error: C import failed",
1523 ".h:1:10: note: 'bogus.h' file not found",
1524 );
11621525
1163 cases.add("address of number literal",1526 cases.add(
1527 "address of number literal",
1164 \\const x = 3;1528 \\const x = 3;
1165 \\const y = &x;1529 \\const y = &x;
1166 \\fn foo() &const i32 { return y; }1530 \\fn foo() *const i32 { return y; }
1167 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }1531 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1168 , ".tmp_source.zig:3:30: error: expected type '&const i32', found '&const (integer literal)'");1532 ,
1533 ".tmp_source.zig:3:30: error: expected type '*const i32', found '*const (integer literal)'",
1534 );
11691535
1170 cases.add("integer overflow error",1536 cases.add(
1537 "integer overflow error",
1171 \\const x : u8 = 300;1538 \\const x : u8 = 300;
1172 \\export fn entry() usize { return @sizeOf(@typeOf(x)); }1539 \\export fn entry() usize { return @sizeOf(@typeOf(x)); }
1173 , ".tmp_source.zig:1:16: error: integer value 300 cannot be implicitly casted to type 'u8'");1540 ,
1541 ".tmp_source.zig:1:16: error: integer value 300 cannot be implicitly casted to type 'u8'",
1542 );
11741543
1175 cases.add("incompatible number literals",1544 cases.add(
1545 "incompatible number literals",
1176 \\const x = 2 == 2.0;1546 \\const x = 2 == 2.0;
1177 \\export fn entry() usize { return @sizeOf(@typeOf(x)); }1547 \\export fn entry() usize { return @sizeOf(@typeOf(x)); }
1178 , ".tmp_source.zig:1:11: error: integer value 2 cannot be implicitly casted to type '(float literal)'");1548 ,
1549 ".tmp_source.zig:1:11: error: integer value 2 cannot be implicitly casted to type '(float literal)'",
1550 );
11791551
1180 cases.add("missing function call param",1552 cases.add(
1553 "missing function call param",
1181 \\const Foo = struct {1554 \\const Foo = struct {
1182 \\ a: i32,1555 \\ a: i32,
1183 \\ b: i32,1556 \\ b: i32,
1184 \\1557 \\
1185 \\ fn member_a(foo: &const Foo) i32 {1558 \\ fn member_a(foo: *const Foo) i32 {
1186 \\ return foo.a;1559 \\ return foo.a;
1187 \\ }1560 \\ }
1188 \\ fn member_b(foo: &const Foo) i32 {1561 \\ fn member_b(foo: *const Foo) i32 {
1189 \\ return foo.b;1562 \\ return foo.b;
1190 \\ }1563 \\ }
1191 \\};1564 \\};
...@@ -1196,63 +1569,78 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1196,63 +1569,78 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1196 \\ Foo.member_b,1569 \\ Foo.member_b,
1197 \\};1570 \\};
1198 \\1571 \\
1199 \\fn f(foo: &const Foo, index: usize) void {1572 \\fn f(foo: *const Foo, index: usize) void {
1200 \\ const result = members[index]();1573 \\ const result = members[index]();
1201 \\}1574 \\}
1202 \\1575 \\
1203 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }1576 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }
1204 , ".tmp_source.zig:20:34: error: expected 1 arguments, found 0");1577 ,
1578 ".tmp_source.zig:20:34: error: expected 1 arguments, found 0",
1579 );
12051580
1206 cases.add("missing function name and param name",1581 cases.add(
1582 "missing function name and param name",
1207 \\fn () void {}1583 \\fn () void {}
1208 \\fn f(i32) void {}1584 \\fn f(i32) void {}
1209 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }1585 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }
1210 ,1586 ,
1211 ".tmp_source.zig:1:1: error: missing function name",1587 ".tmp_source.zig:1:1: error: missing function name",
1212 ".tmp_source.zig:2:6: error: missing parameter name");1588 ".tmp_source.zig:2:6: error: missing parameter name",
1589 );
12131590
1214 cases.add("wrong function type",1591 cases.add(
1592 "wrong function type",
1215 \\const fns = []fn() void { a, b, c };1593 \\const fns = []fn() void { a, b, c };
1216 \\fn a() i32 {return 0;}1594 \\fn a() i32 {return 0;}
1217 \\fn b() i32 {return 1;}1595 \\fn b() i32 {return 1;}
1218 \\fn c() i32 {return 2;}1596 \\fn c() i32 {return 2;}
1219 \\export fn entry() usize { return @sizeOf(@typeOf(fns)); }1597 \\export fn entry() usize { return @sizeOf(@typeOf(fns)); }
1220 , ".tmp_source.zig:1:27: error: expected type 'fn() void', found 'fn() i32'");1598 ,
1599 ".tmp_source.zig:1:27: error: expected type 'fn() void', found 'fn() i32'",
1600 );
12211601
1222 cases.add("extern function pointer mismatch",1602 cases.add(
1603 "extern function pointer mismatch",
1223 \\const fns = [](fn(i32)i32) { a, b, c };1604 \\const fns = [](fn(i32)i32) { a, b, c };
1224 \\pub fn a(x: i32) i32 {return x + 0;}1605 \\pub fn a(x: i32) i32 {return x + 0;}
1225 \\pub fn b(x: i32) i32 {return x + 1;}1606 \\pub fn b(x: i32) i32 {return x + 1;}
1226 \\export fn c(x: i32) i32 {return x + 2;}1607 \\export fn c(x: i32) i32 {return x + 2;}
1227 \\1608 \\
1228 \\export fn entry() usize { return @sizeOf(@typeOf(fns)); }1609 \\export fn entry() usize { return @sizeOf(@typeOf(fns)); }
1229 , ".tmp_source.zig:1:36: error: expected type 'fn(i32) i32', found 'extern fn(i32) i32'");1610 ,
12301611 ".tmp_source.zig:1:36: error: expected type 'fn(i32) i32', found 'extern fn(i32) i32'",
1612 );
12311613
1232 cases.add("implicit cast from f64 to f32",1614 cases.add(
1615 "implicit cast from f64 to f32",
1233 \\const x : f64 = 1.0;1616 \\const x : f64 = 1.0;
1234 \\const y : f32 = x;1617 \\const y : f32 = x;
1235 \\1618 \\
1236 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }1619 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }
1237 , ".tmp_source.zig:2:17: error: expected type 'f32', found 'f64'");1620 ,
12381621 ".tmp_source.zig:2:17: error: expected type 'f32', found 'f64'",
1622 );
12391623
1240 cases.add("colliding invalid top level functions",1624 cases.add(
1625 "colliding invalid top level functions",
1241 \\fn func() bogus {}1626 \\fn func() bogus {}
1242 \\fn func() bogus {}1627 \\fn func() bogus {}
1243 \\export fn entry() usize { return @sizeOf(@typeOf(func)); }1628 \\export fn entry() usize { return @sizeOf(@typeOf(func)); }
1244 ,1629 ,
1245 ".tmp_source.zig:2:1: error: redefinition of 'func'",1630 ".tmp_source.zig:2:1: error: redefinition of 'func'",
1246 ".tmp_source.zig:1:11: error: use of undeclared identifier 'bogus'");1631 ".tmp_source.zig:1:11: error: use of undeclared identifier 'bogus'",
12471632 );
12481633
1249 cases.add("bogus compile var",1634 cases.add(
1635 "bogus compile var",
1250 \\const x = @import("builtin").bogus;1636 \\const x = @import("builtin").bogus;
1251 \\export fn entry() usize { return @sizeOf(@typeOf(x)); }1637 \\export fn entry() usize { return @sizeOf(@typeOf(x)); }
1252 , ".tmp_source.zig:1:29: error: no member named 'bogus' in '");1638 ,
12531639 ".tmp_source.zig:1:29: error: no member named 'bogus' in '",
1640 );
12541641
1255 cases.add("non constant expression in array size outside function",1642 cases.add(
1643 "non constant expression in array size outside function",
1256 \\const Foo = struct {1644 \\const Foo = struct {
1257 \\ y: [get()]u8,1645 \\ y: [get()]u8,
1258 \\};1646 \\};
...@@ -1261,22 +1649,25 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1261,22 +1649,25 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1261 \\1649 \\
1262 \\export fn entry() usize { return @sizeOf(@typeOf(Foo)); }1650 \\export fn entry() usize { return @sizeOf(@typeOf(Foo)); }
1263 ,1651 ,
1264 ".tmp_source.zig:5:25: error: unable to evaluate constant expression",1652 ".tmp_source.zig:5:25: error: unable to evaluate constant expression",
1265 ".tmp_source.zig:2:12: note: called from here",1653 ".tmp_source.zig:2:12: note: called from here",
1266 ".tmp_source.zig:2:8: note: called from here");1654 ".tmp_source.zig:2:8: note: called from here",
12671655 );
12681656
1269 cases.add("addition with non numbers",1657 cases.add(
1658 "addition with non numbers",
1270 \\const Foo = struct {1659 \\const Foo = struct {
1271 \\ field: i32,1660 \\ field: i32,
1272 \\};1661 \\};
1273 \\const x = Foo {.field = 1} + Foo {.field = 2};1662 \\const x = Foo {.field = 1} + Foo {.field = 2};
1274 \\1663 \\
1275 \\export fn entry() usize { return @sizeOf(@typeOf(x)); }1664 \\export fn entry() usize { return @sizeOf(@typeOf(x)); }
1276 , ".tmp_source.zig:4:28: error: invalid operands to binary expression: 'Foo' and 'Foo'");1665 ,
12771666 ".tmp_source.zig:4:28: error: invalid operands to binary expression: 'Foo' and 'Foo'",
1667 );
12781668
1279 cases.add("division by zero",1669 cases.add(
1670 "division by zero",
1280 \\const lit_int_x = 1 / 0;1671 \\const lit_int_x = 1 / 0;
1281 \\const lit_float_x = 1.0 / 0.0;1672 \\const lit_float_x = 1.0 / 0.0;
1282 \\const int_x = u32(1) / u32(0);1673 \\const int_x = u32(1) / u32(0);
...@@ -1287,49 +1678,65 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1287,49 +1678,65 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1287 \\export fn entry3() usize { return @sizeOf(@typeOf(int_x)); }1678 \\export fn entry3() usize { return @sizeOf(@typeOf(int_x)); }
1288 \\export fn entry4() usize { return @sizeOf(@typeOf(float_x)); }1679 \\export fn entry4() usize { return @sizeOf(@typeOf(float_x)); }
1289 ,1680 ,
1290 ".tmp_source.zig:1:21: error: division by zero",1681 ".tmp_source.zig:1:21: error: division by zero",
1291 ".tmp_source.zig:2:25: error: division by zero",1682 ".tmp_source.zig:2:25: error: division by zero",
1292 ".tmp_source.zig:3:22: error: division by zero",1683 ".tmp_source.zig:3:22: error: division by zero",
1293 ".tmp_source.zig:4:26: error: division by zero");1684 ".tmp_source.zig:4:26: error: division by zero",
1685 );
12941686
12951687 cases.add(
1296 cases.add("normal string with newline",1688 "normal string with newline",
1297 \\const foo = "a1689 \\const foo = "a
1298 \\b";1690 \\b";
1299 \\1691 \\
1300 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }1692 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1301 , ".tmp_source.zig:1:13: error: newline not allowed in string literal");1693 ,
1694 ".tmp_source.zig:1:13: error: newline not allowed in string literal",
1695 );
13021696
1303 cases.add("invalid comparison for function pointers",1697 cases.add(
1698 "invalid comparison for function pointers",
1304 \\fn foo() void {}1699 \\fn foo() void {}
1305 \\const invalid = foo > foo;1700 \\const invalid = foo > foo;
1306 \\1701 \\
1307 \\export fn entry() usize { return @sizeOf(@typeOf(invalid)); }1702 \\export fn entry() usize { return @sizeOf(@typeOf(invalid)); }
1308 , ".tmp_source.zig:2:21: error: operator not allowed for type 'fn() void'");1703 ,
1704 ".tmp_source.zig:2:21: error: operator not allowed for type 'fn() void'",
1705 );
13091706
1310 cases.add("generic function instance with non-constant expression",1707 cases.add(
1708 "generic function instance with non-constant expression",
1311 \\fn foo(comptime x: i32, y: i32) i32 { return x + y; }1709 \\fn foo(comptime x: i32, y: i32) i32 { return x + y; }
1312 \\fn test1(a: i32, b: i32) i32 {1710 \\fn test1(a: i32, b: i32) i32 {
1313 \\ return foo(a, b);1711 \\ return foo(a, b);
1314 \\}1712 \\}
1315 \\1713 \\
1316 \\export fn entry() usize { return @sizeOf(@typeOf(test1)); }1714 \\export fn entry() usize { return @sizeOf(@typeOf(test1)); }
1317 , ".tmp_source.zig:3:16: error: unable to evaluate constant expression");1715 ,
1716 ".tmp_source.zig:3:16: error: unable to evaluate constant expression",
1717 );
13181718
1319 cases.add("assign null to non-nullable pointer",1719 cases.add(
1320 \\const a: &u8 = null;1720 "assign null to non-nullable pointer",
1721 \\const a: *u8 = null;
1321 \\1722 \\
1322 \\export fn entry() usize { return @sizeOf(@typeOf(a)); }1723 \\export fn entry() usize { return @sizeOf(@typeOf(a)); }
1323 , ".tmp_source.zig:1:16: error: expected type '&u8', found '(null)'");1724 ,
1725 ".tmp_source.zig:1:16: error: expected type '*u8', found '(null)'",
1726 );
13241727
1325 cases.add("indexing an array of size zero",1728 cases.add(
1729 "indexing an array of size zero",
1326 \\const array = []u8{};1730 \\const array = []u8{};
1327 \\export fn foo() void {1731 \\export fn foo() void {
1328 \\ const pointer = &array[0];1732 \\ const pointer = &array[0];
1329 \\}1733 \\}
1330 , ".tmp_source.zig:3:27: error: index 0 outside array of size 0");1734 ,
1735 ".tmp_source.zig:3:27: error: index 0 outside array of size 0",
1736 );
13311737
1332 cases.add("compile time division by zero",1738 cases.add(
1739 "compile time division by zero",
1333 \\const y = foo(0);1740 \\const y = foo(0);
1334 \\fn foo(x: u32) u32 {1741 \\fn foo(x: u32) u32 {
1335 \\ return 1 / x;1742 \\ return 1 / x;
...@@ -1337,17 +1744,21 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1337,17 +1744,21 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1337 \\1744 \\
1338 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }1745 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }
1339 ,1746 ,
1340 ".tmp_source.zig:3:14: error: division by zero",1747 ".tmp_source.zig:3:14: error: division by zero",
1341 ".tmp_source.zig:1:14: note: called from here");1748 ".tmp_source.zig:1:14: note: called from here",
1749 );
13421750
1343 cases.add("branch on undefined value",1751 cases.add(
1752 "branch on undefined value",
1344 \\const x = if (undefined) true else false;1753 \\const x = if (undefined) true else false;
1345 \\1754 \\
1346 \\export fn entry() usize { return @sizeOf(@typeOf(x)); }1755 \\export fn entry() usize { return @sizeOf(@typeOf(x)); }
1347 , ".tmp_source.zig:1:15: error: use of undefined value");1756 ,
13481757 ".tmp_source.zig:1:15: error: use of undefined value",
1758 );
13491759
1350 cases.add("endless loop in function evaluation",1760 cases.add(
1761 "endless loop in function evaluation",
1351 \\const seventh_fib_number = fibbonaci(7);1762 \\const seventh_fib_number = fibbonaci(7);
1352 \\fn fibbonaci(x: i32) i32 {1763 \\fn fibbonaci(x: i32) i32 {
1353 \\ return fibbonaci(x - 1) + fibbonaci(x - 2);1764 \\ return fibbonaci(x - 1) + fibbonaci(x - 2);
...@@ -1355,16 +1766,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1355,16 +1766,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1355 \\1766 \\
1356 \\export fn entry() usize { return @sizeOf(@typeOf(seventh_fib_number)); }1767 \\export fn entry() usize { return @sizeOf(@typeOf(seventh_fib_number)); }
1357 ,1768 ,
1358 ".tmp_source.zig:3:21: error: evaluation exceeded 1000 backwards branches",1769 ".tmp_source.zig:3:21: error: evaluation exceeded 1000 backwards branches",
1359 ".tmp_source.zig:3:21: note: called from here");1770 ".tmp_source.zig:3:21: note: called from here",
1771 );
13601772
1361 cases.add("@embedFile with bogus file",1773 cases.add(
1362 \\const resource = @embedFile("bogus.txt");1774 "@embedFile with bogus file",
1775 \\const resource = @embedFile("bogus.txt",);
1363 \\1776 \\
1364 \\export fn entry() usize { return @sizeOf(@typeOf(resource)); }1777 \\export fn entry() usize { return @sizeOf(@typeOf(resource)); }
1365 , ".tmp_source.zig:1:29: error: unable to find '", "bogus.txt'");1778 ,
1779 ".tmp_source.zig:1:29: error: unable to find '",
1780 "bogus.txt'",
1781 );
13661782
1367 cases.add("non-const expression in struct literal outside function",1783 cases.add(
1784 "non-const expression in struct literal outside function",
1368 \\const Foo = struct {1785 \\const Foo = struct {
1369 \\ x: i32,1786 \\ x: i32,
1370 \\};1787 \\};
...@@ -1372,9 +1789,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1372,9 +1789,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1372 \\extern fn get_it() i32;1789 \\extern fn get_it() i32;
1373 \\1790 \\
1374 \\export fn entry() usize { return @sizeOf(@typeOf(a)); }1791 \\export fn entry() usize { return @sizeOf(@typeOf(a)); }
1375 , ".tmp_source.zig:4:21: error: unable to evaluate constant expression");1792 ,
1793 ".tmp_source.zig:4:21: error: unable to evaluate constant expression",
1794 );
13761795
1377 cases.add("non-const expression function call with struct return value outside function",1796 cases.add(
1797 "non-const expression function call with struct return value outside function",
1378 \\const Foo = struct {1798 \\const Foo = struct {
1379 \\ x: i32,1799 \\ x: i32,
1380 \\};1800 \\};
...@@ -1387,19 +1807,24 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1387,19 +1807,24 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1387 \\1807 \\
1388 \\export fn entry() usize { return @sizeOf(@typeOf(a)); }1808 \\export fn entry() usize { return @sizeOf(@typeOf(a)); }
1389 ,1809 ,
1390 ".tmp_source.zig:6:24: error: unable to evaluate constant expression",1810 ".tmp_source.zig:6:24: error: unable to evaluate constant expression",
1391 ".tmp_source.zig:4:17: note: called from here");1811 ".tmp_source.zig:4:17: note: called from here",
1812 );
13921813
1393 cases.add("undeclared identifier error should mark fn as impure",1814 cases.add(
1815 "undeclared identifier error should mark fn as impure",
1394 \\export fn foo() void {1816 \\export fn foo() void {
1395 \\ test_a_thing();1817 \\ test_a_thing();
1396 \\}1818 \\}
1397 \\fn test_a_thing() void {1819 \\fn test_a_thing() void {
1398 \\ bad_fn_call();1820 \\ bad_fn_call();
1399 \\}1821 \\}
1400 , ".tmp_source.zig:5:5: error: use of undeclared identifier 'bad_fn_call'");1822 ,
1823 ".tmp_source.zig:5:5: error: use of undeclared identifier 'bad_fn_call'",
1824 );
14011825
1402 cases.add("illegal comparison of types",1826 cases.add(
1827 "illegal comparison of types",
1403 \\fn bad_eql_1(a: []u8, b: []u8) bool {1828 \\fn bad_eql_1(a: []u8, b: []u8) bool {
1404 \\ return a == b;1829 \\ return a == b;
1405 \\}1830 \\}
...@@ -1407,17 +1832,19 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1407,17 +1832,19 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1407 \\ One: void,1832 \\ One: void,
1408 \\ Two: i32,1833 \\ Two: i32,
1409 \\};1834 \\};
1410 \\fn bad_eql_2(a: &const EnumWithData, b: &const EnumWithData) bool {1835 \\fn bad_eql_2(a: *const EnumWithData, b: *const EnumWithData) bool {
1411 \\ return a.* == b.*;1836 \\ return a.* == b.*;
1412 \\}1837 \\}
1413 \\1838 \\
1414 \\export fn entry1() usize { return @sizeOf(@typeOf(bad_eql_1)); }1839 \\export fn entry1() usize { return @sizeOf(@typeOf(bad_eql_1)); }
1415 \\export fn entry2() usize { return @sizeOf(@typeOf(bad_eql_2)); }1840 \\export fn entry2() usize { return @sizeOf(@typeOf(bad_eql_2)); }
1416 ,1841 ,
1417 ".tmp_source.zig:2:14: error: operator not allowed for type '[]u8'",1842 ".tmp_source.zig:2:14: error: operator not allowed for type '[]u8'",
1418 ".tmp_source.zig:9:16: error: operator not allowed for type 'EnumWithData'");1843 ".tmp_source.zig:9:16: error: operator not allowed for type 'EnumWithData'",
1844 );
14191845
1420 cases.add("non-const switch number literal",1846 cases.add(
1847 "non-const switch number literal",
1421 \\export fn foo() void {1848 \\export fn foo() void {
1422 \\ const x = switch (bar()) {1849 \\ const x = switch (bar()) {
1423 \\ 1, 2 => 1,1850 \\ 1, 2 => 1,
...@@ -1428,25 +1855,34 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1428,25 +1855,34 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1428 \\fn bar() i32 {1855 \\fn bar() i32 {
1429 \\ return 2;1856 \\ return 2;
1430 \\}1857 \\}
1431 , ".tmp_source.zig:2:15: error: unable to infer expression type");1858 ,
1859 ".tmp_source.zig:2:15: error: unable to infer expression type",
1860 );
14321861
1433 cases.add("atomic orderings of cmpxchg - failure stricter than success",1862 cases.add(
1863 "atomic orderings of cmpxchg - failure stricter than success",
1434 \\const AtomicOrder = @import("builtin").AtomicOrder;1864 \\const AtomicOrder = @import("builtin").AtomicOrder;
1435 \\export fn f() void {1865 \\export fn f() void {
1436 \\ var x: i32 = 1234;1866 \\ var x: i32 = 1234;
1437 \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.Monotonic, AtomicOrder.SeqCst)) {}1867 \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.Monotonic, AtomicOrder.SeqCst)) {}
1438 \\}1868 \\}
1439 , ".tmp_source.zig:4:81: error: failure atomic ordering must be no stricter than success");1869 ,
1870 ".tmp_source.zig:4:81: error: failure atomic ordering must be no stricter than success",
1871 );
14401872
1441 cases.add("atomic orderings of cmpxchg - success Monotonic or stricter",1873 cases.add(
1874 "atomic orderings of cmpxchg - success Monotonic or stricter",
1442 \\const AtomicOrder = @import("builtin").AtomicOrder;1875 \\const AtomicOrder = @import("builtin").AtomicOrder;
1443 \\export fn f() void {1876 \\export fn f() void {
1444 \\ var x: i32 = 1234;1877 \\ var x: i32 = 1234;
1445 \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.Unordered, AtomicOrder.Unordered)) {}1878 \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.Unordered, AtomicOrder.Unordered)) {}
1446 \\}1879 \\}
1447 , ".tmp_source.zig:4:58: error: success atomic ordering must be Monotonic or stricter");1880 ,
1881 ".tmp_source.zig:4:58: error: success atomic ordering must be Monotonic or stricter",
1882 );
14481883
1449 cases.add("negation overflow in function evaluation",1884 cases.add(
1885 "negation overflow in function evaluation",
1450 \\const y = neg(-128);1886 \\const y = neg(-128);
1451 \\fn neg(x: i8) i8 {1887 \\fn neg(x: i8) i8 {
1452 \\ return -x;1888 \\ return -x;
...@@ -1454,10 +1890,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1454,10 +1890,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1454 \\1890 \\
1455 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }1891 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }
1456 ,1892 ,
1457 ".tmp_source.zig:3:12: error: negation caused overflow",1893 ".tmp_source.zig:3:12: error: negation caused overflow",
1458 ".tmp_source.zig:1:14: note: called from here");1894 ".tmp_source.zig:1:14: note: called from here",
1895 );
14591896
1460 cases.add("add overflow in function evaluation",1897 cases.add(
1898 "add overflow in function evaluation",
1461 \\const y = add(65530, 10);1899 \\const y = add(65530, 10);
1462 \\fn add(a: u16, b: u16) u16 {1900 \\fn add(a: u16, b: u16) u16 {
1463 \\ return a + b;1901 \\ return a + b;
...@@ -1465,11 +1903,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1465,11 +1903,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1465 \\1903 \\
1466 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }1904 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }
1467 ,1905 ,
1468 ".tmp_source.zig:3:14: error: operation caused overflow",1906 ".tmp_source.zig:3:14: error: operation caused overflow",
1469 ".tmp_source.zig:1:14: note: called from here");1907 ".tmp_source.zig:1:14: note: called from here",
14701908 );
14711909
1472 cases.add("sub overflow in function evaluation",1910 cases.add(
1911 "sub overflow in function evaluation",
1473 \\const y = sub(10, 20);1912 \\const y = sub(10, 20);
1474 \\fn sub(a: u16, b: u16) u16 {1913 \\fn sub(a: u16, b: u16) u16 {
1475 \\ return a - b;1914 \\ return a - b;
...@@ -1477,10 +1916,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1477,10 +1916,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1477 \\1916 \\
1478 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }1917 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }
1479 ,1918 ,
1480 ".tmp_source.zig:3:14: error: operation caused overflow",1919 ".tmp_source.zig:3:14: error: operation caused overflow",
1481 ".tmp_source.zig:1:14: note: called from here");1920 ".tmp_source.zig:1:14: note: called from here",
1921 );
14821922
1483 cases.add("mul overflow in function evaluation",1923 cases.add(
1924 "mul overflow in function evaluation",
1484 \\const y = mul(300, 6000);1925 \\const y = mul(300, 6000);
1485 \\fn mul(a: u16, b: u16) u16 {1926 \\fn mul(a: u16, b: u16) u16 {
1486 \\ return a * b;1927 \\ return a * b;
...@@ -1488,27 +1929,34 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1488,27 +1929,34 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1488 \\1929 \\
1489 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }1930 \\export fn entry() usize { return @sizeOf(@typeOf(y)); }
1490 ,1931 ,
1491 ".tmp_source.zig:3:14: error: operation caused overflow",1932 ".tmp_source.zig:3:14: error: operation caused overflow",
1492 ".tmp_source.zig:1:14: note: called from here");1933 ".tmp_source.zig:1:14: note: called from here",
1934 );
14931935
1494 cases.add("truncate sign mismatch",1936 cases.add(
1937 "truncate sign mismatch",
1495 \\fn f() i8 {1938 \\fn f() i8 {
1496 \\ const x: u32 = 10;1939 \\ const x: u32 = 10;
1497 \\ return @truncate(i8, x);1940 \\ return @truncate(i8, x);
1498 \\}1941 \\}
1499 \\1942 \\
1500 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }1943 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }
1501 , ".tmp_source.zig:3:26: error: expected signed integer type, found 'u32'");1944 ,
1945 ".tmp_source.zig:3:26: error: expected signed integer type, found 'u32'",
1946 );
15021947
1503 cases.add("try in function with non error return type",1948 cases.add(
1949 "try in function with non error return type",
1504 \\export fn f() void {1950 \\export fn f() void {
1505 \\ try something();1951 \\ try something();
1506 \\}1952 \\}
1507 \\fn something() error!void { }1953 \\fn something() error!void { }
1508 ,1954 ,
1509 ".tmp_source.zig:2:5: error: expected type 'void', found 'error'");1955 ".tmp_source.zig:2:5: error: expected type 'void', found 'error'",
1956 );
15101957
1511 cases.add("invalid pointer for var type",1958 cases.add(
1959 "invalid pointer for var type",
1512 \\extern fn ext() usize;1960 \\extern fn ext() usize;
1513 \\var bytes: [ext()]u8 = undefined;1961 \\var bytes: [ext()]u8 = undefined;
1514 \\export fn f() void {1962 \\export fn f() void {
...@@ -1516,30 +1964,42 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1516,30 +1964,42 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1516 \\ b.* = u8(i);1964 \\ b.* = u8(i);
1517 \\ }1965 \\ }
1518 \\}1966 \\}
1519 , ".tmp_source.zig:2:13: error: unable to evaluate constant expression");1967 ,
1968 ".tmp_source.zig:2:13: error: unable to evaluate constant expression",
1969 );
15201970
1521 cases.add("export function with comptime parameter",1971 cases.add(
1972 "export function with comptime parameter",
1522 \\export fn foo(comptime x: i32, y: i32) i32{1973 \\export fn foo(comptime x: i32, y: i32) i32{
1523 \\ return x + y;1974 \\ return x + y;
1524 \\}1975 \\}
1525 , ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'");1976 ,
1977 ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'",
1978 );
15261979
1527 cases.add("extern function with comptime parameter",1980 cases.add(
1981 "extern function with comptime parameter",
1528 \\extern fn foo(comptime x: i32, y: i32) i32;1982 \\extern fn foo(comptime x: i32, y: i32) i32;
1529 \\fn f() i32 {1983 \\fn f() i32 {
1530 \\ return foo(1, 2);1984 \\ return foo(1, 2);
1531 \\}1985 \\}
1532 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }1986 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }
1533 , ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'");1987 ,
1988 ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'",
1989 );
15341990
1535 cases.add("convert fixed size array to slice with invalid size",1991 cases.add(
1992 "convert fixed size array to slice with invalid size",
1536 \\export fn f() void {1993 \\export fn f() void {
1537 \\ var array: [5]u8 = undefined;1994 \\ var array: [5]u8 = undefined;
1538 \\ var foo = ([]const u32)(array)[0];1995 \\ var foo = ([]const u32)(array)[0];
1539 \\}1996 \\}
1540 , ".tmp_source.zig:3:28: error: unable to convert [5]u8 to []const u32: size mismatch");1997 ,
1998 ".tmp_source.zig:3:28: error: unable to convert [5]u8 to []const u32: size mismatch",
1999 );
15412000
1542 cases.add("non-pure function returns type",2001 cases.add(
2002 "non-pure function returns type",
1543 \\var a: u32 = 0;2003 \\var a: u32 = 0;
1544 \\pub fn List(comptime T: type) type {2004 \\pub fn List(comptime T: type) type {
1545 \\ a += 1;2005 \\ a += 1;
...@@ -1558,56 +2018,77 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1558,56 +2018,77 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1558 \\ var list: List(i32) = undefined;2018 \\ var list: List(i32) = undefined;
1559 \\ list.length = 10;2019 \\ list.length = 10;
1560 \\}2020 \\}
1561 , ".tmp_source.zig:3:7: error: unable to evaluate constant expression",2021 ,
1562 ".tmp_source.zig:16:19: note: called from here");2022 ".tmp_source.zig:3:7: error: unable to evaluate constant expression",
2023 ".tmp_source.zig:16:19: note: called from here",
2024 );
15632025
1564 cases.add("bogus method call on slice",2026 cases.add(
2027 "bogus method call on slice",
1565 \\var self = "aoeu";2028 \\var self = "aoeu";
1566 \\fn f(m: []const u8) void {2029 \\fn f(m: []const u8) void {
1567 \\ m.copy(u8, self[0..], m);2030 \\ m.copy(u8, self[0..], m);
1568 \\}2031 \\}
1569 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }2032 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }
1570 , ".tmp_source.zig:3:6: error: no member named 'copy' in '[]const u8'");2033 ,
2034 ".tmp_source.zig:3:6: error: no member named 'copy' in '[]const u8'",
2035 );
15712036
1572 cases.add("wrong number of arguments for method fn call",2037 cases.add(
2038 "wrong number of arguments for method fn call",
1573 \\const Foo = struct {2039 \\const Foo = struct {
1574 \\ fn method(self: &const Foo, a: i32) void {}2040 \\ fn method(self: *const Foo, a: i32) void {}
1575 \\};2041 \\};
1576 \\fn f(foo: &const Foo) void {2042 \\fn f(foo: *const Foo) void {
1577 \\2043 \\
1578 \\ foo.method(1, 2);2044 \\ foo.method(1, 2);
1579 \\}2045 \\}
1580 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }2046 \\export fn entry() usize { return @sizeOf(@typeOf(f)); }
1581 , ".tmp_source.zig:6:15: error: expected 2 arguments, found 3");2047 ,
2048 ".tmp_source.zig:6:15: error: expected 2 arguments, found 3",
2049 );
15822050
1583 cases.add("assign through constant pointer",2051 cases.add(
2052 "assign through constant pointer",
1584 \\export fn f() void {2053 \\export fn f() void {
1585 \\ var cstr = c"Hat";2054 \\ var cstr = c"Hat";
1586 \\ cstr[0] = 'W';2055 \\ cstr[0] = 'W';
1587 \\}2056 \\}
1588 , ".tmp_source.zig:3:11: error: cannot assign to constant");2057 ,
2058 ".tmp_source.zig:3:11: error: cannot assign to constant",
2059 );
15892060
1590 cases.add("assign through constant slice",2061 cases.add(
2062 "assign through constant slice",
1591 \\export fn f() void {2063 \\export fn f() void {
1592 \\ var cstr: []const u8 = "Hat";2064 \\ var cstr: []const u8 = "Hat";
1593 \\ cstr[0] = 'W';2065 \\ cstr[0] = 'W';
1594 \\}2066 \\}
1595 , ".tmp_source.zig:3:11: error: cannot assign to constant");2067 ,
2068 ".tmp_source.zig:3:11: error: cannot assign to constant",
2069 );
15962070
1597 cases.add("main function with bogus args type",2071 cases.add(
2072 "main function with bogus args type",
1598 \\pub fn main(args: [][]bogus) !void {}2073 \\pub fn main(args: [][]bogus) !void {}
1599 , ".tmp_source.zig:1:23: error: use of undeclared identifier 'bogus'");2074 ,
2075 ".tmp_source.zig:1:23: error: use of undeclared identifier 'bogus'",
2076 );
16002077
1601 cases.add("for loop missing element param",2078 cases.add(
2079 "for loop missing element param",
1602 \\fn foo(blah: []u8) void {2080 \\fn foo(blah: []u8) void {
1603 \\ for (blah) { }2081 \\ for (blah) { }
1604 \\}2082 \\}
1605 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }2083 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1606 , ".tmp_source.zig:2:5: error: for loop expression missing element parameter");2084 ,
2085 ".tmp_source.zig:2:5: error: for loop expression missing element parameter",
2086 );
16072087
1608 cases.add("misspelled type with pointer only reference",2088 cases.add(
2089 "misspelled type with pointer only reference",
1609 \\const JasonHM = u8;2090 \\const JasonHM = u8;
1610 \\const JasonList = &JsonNode;2091 \\const JasonList = *JsonNode;
1611 \\2092 \\
1612 \\const JsonOA = union(enum) {2093 \\const JsonOA = union(enum) {
1613 \\ JSONArray: JsonList,2094 \\ JSONArray: JsonList,
...@@ -1636,9 +2117,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1636,9 +2117,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1636 \\}2117 \\}
1637 \\2118 \\
1638 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }2119 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1639 , ".tmp_source.zig:5:16: error: use of undeclared identifier 'JsonList'");2120 ,
2121 ".tmp_source.zig:5:16: error: use of undeclared identifier 'JsonList'",
2122 );
16402123
1641 cases.add("method call with first arg type primitive",2124 cases.add(
2125 "method call with first arg type primitive",
1642 \\const Foo = struct {2126 \\const Foo = struct {
1643 \\ x: i32,2127 \\ x: i32,
1644 \\2128 \\
...@@ -1654,14 +2138,17 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1654,14 +2138,17 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1654 \\2138 \\
1655 \\ derp.init();2139 \\ derp.init();
1656 \\}2140 \\}
1657 , ".tmp_source.zig:14:5: error: expected type 'i32', found '&const Foo'");2141 ,
2142 ".tmp_source.zig:14:5: error: expected type 'i32', found '*const Foo'",
2143 );
16582144
1659 cases.add("method call with first arg type wrong container",2145 cases.add(
2146 "method call with first arg type wrong container",
1660 \\pub const List = struct {2147 \\pub const List = struct {
1661 \\ len: usize,2148 \\ len: usize,
1662 \\ allocator: &Allocator,2149 \\ allocator: *Allocator,
1663 \\2150 \\
1664 \\ pub fn init(allocator: &Allocator) List {2151 \\ pub fn init(allocator: *Allocator) List {
1665 \\ return List {2152 \\ return List {
1666 \\ .len = 0,2153 \\ .len = 0,
1667 \\ .allocator = allocator,2154 \\ .allocator = allocator,
...@@ -1681,26 +2168,33 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1681,26 +2168,33 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1681 \\ var x = List.init(&global_allocator);2168 \\ var x = List.init(&global_allocator);
1682 \\ x.init();2169 \\ x.init();
1683 \\}2170 \\}
1684 , ".tmp_source.zig:23:5: error: expected type '&Allocator', found '&List'");2171 ,
2172 ".tmp_source.zig:23:5: error: expected type '*Allocator', found '*List'",
2173 );
16852174
1686 cases.add("binary not on number literal",2175 cases.add(
2176 "binary not on number literal",
1687 \\const TINY_QUANTUM_SHIFT = 4;2177 \\const TINY_QUANTUM_SHIFT = 4;
1688 \\const TINY_QUANTUM_SIZE = 1 << TINY_QUANTUM_SHIFT;2178 \\const TINY_QUANTUM_SIZE = 1 << TINY_QUANTUM_SHIFT;
1689 \\var block_aligned_stuff: usize = (4 + TINY_QUANTUM_SIZE) & ~(TINY_QUANTUM_SIZE - 1);2179 \\var block_aligned_stuff: usize = (4 + TINY_QUANTUM_SIZE) & ~(TINY_QUANTUM_SIZE - 1);
1690 \\2180 \\
1691 \\export fn entry() usize { return @sizeOf(@typeOf(block_aligned_stuff)); }2181 \\export fn entry() usize { return @sizeOf(@typeOf(block_aligned_stuff)); }
1692 , ".tmp_source.zig:3:60: error: unable to perform binary not operation on type '(integer literal)'");2182 ,
2183 ".tmp_source.zig:3:60: error: unable to perform binary not operation on type '(integer literal)'",
2184 );
16932185
1694 cases.addCase(x: {2186 cases.addCase(x: {
1695 const tc = cases.create("multiple files with private function error",2187 const tc = cases.create(
1696 \\const foo = @import("foo.zig");2188 "multiple files with private function error",
2189 \\const foo = @import("foo.zig",);
1697 \\2190 \\
1698 \\export fn callPrivFunction() void {2191 \\export fn callPrivFunction() void {
1699 \\ foo.privateFunction();2192 \\ foo.privateFunction();
1700 \\}2193 \\}
1701 ,2194 ,
1702 ".tmp_source.zig:4:8: error: 'privateFunction' is private",2195 ".tmp_source.zig:4:8: error: 'privateFunction' is private",
1703 "foo.zig:1:1: note: declared here");2196 "foo.zig:1:1: note: declared here",
2197 );
17042198
1705 tc.addSourceFile("foo.zig",2199 tc.addSourceFile("foo.zig",
1706 \\fn privateFunction() void { }2200 \\fn privateFunction() void { }
...@@ -1709,14 +2203,18 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1709,14 +2203,18 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1709 break :x tc;2203 break :x tc;
1710 });2204 });
17112205
1712 cases.add("container init with non-type",2206 cases.add(
2207 "container init with non-type",
1713 \\const zero: i32 = 0;2208 \\const zero: i32 = 0;
1714 \\const a = zero{1};2209 \\const a = zero{1};
1715 \\2210 \\
1716 \\export fn entry() usize { return @sizeOf(@typeOf(a)); }2211 \\export fn entry() usize { return @sizeOf(@typeOf(a)); }
1717 , ".tmp_source.zig:2:11: error: expected type, found 'i32'");2212 ,
2213 ".tmp_source.zig:2:11: error: expected type, found 'i32'",
2214 );
17182215
1719 cases.add("assign to constant field",2216 cases.add(
2217 "assign to constant field",
1720 \\const Foo = struct {2218 \\const Foo = struct {
1721 \\ field: i32,2219 \\ field: i32,
1722 \\};2220 \\};
...@@ -1724,9 +2222,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1724,9 +2222,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1724 \\ const f = Foo {.field = 1234,};2222 \\ const f = Foo {.field = 1234,};
1725 \\ f.field = 0;2223 \\ f.field = 0;
1726 \\}2224 \\}
1727 , ".tmp_source.zig:6:13: error: cannot assign to constant");2225 ,
2226 ".tmp_source.zig:6:13: error: cannot assign to constant",
2227 );
17282228
1729 cases.add("return from defer expression",2229 cases.add(
2230 "return from defer expression",
1730 \\pub fn testTrickyDefer() !void {2231 \\pub fn testTrickyDefer() !void {
1731 \\ defer canFail() catch {};2232 \\ defer canFail() catch {};
1732 \\2233 \\
...@@ -1742,9 +2243,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1742,9 +2243,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1742 \\}2243 \\}
1743 \\2244 \\
1744 \\export fn entry() usize { return @sizeOf(@typeOf(testTrickyDefer)); }2245 \\export fn entry() usize { return @sizeOf(@typeOf(testTrickyDefer)); }
1745 , ".tmp_source.zig:4:11: error: cannot return from defer expression");2246 ,
2247 ".tmp_source.zig:4:11: error: cannot return from defer expression",
2248 );
17462249
1747 cases.add("attempt to access var args out of bounds",2250 cases.add(
2251 "attempt to access var args out of bounds",
1748 \\fn add(args: ...) i32 {2252 \\fn add(args: ...) i32 {
1749 \\ return args[0] + args[1];2253 \\ return args[0] + args[1];
1750 \\}2254 \\}
...@@ -1755,10 +2259,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1755,10 +2259,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1755 \\2259 \\
1756 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }2260 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1757 ,2261 ,
1758 ".tmp_source.zig:2:26: error: index 1 outside argument list of size 1",2262 ".tmp_source.zig:2:26: error: index 1 outside argument list of size 1",
1759 ".tmp_source.zig:6:15: note: called from here");2263 ".tmp_source.zig:6:15: note: called from here",
2264 );
17602265
1761 cases.add("pass integer literal to var args",2266 cases.add(
2267 "pass integer literal to var args",
1762 \\fn add(args: ...) i32 {2268 \\fn add(args: ...) i32 {
1763 \\ var sum = i32(0);2269 \\ var sum = i32(0);
1764 \\ {comptime var i: usize = 0; inline while (i < args.len) : (i += 1) {2270 \\ {comptime var i: usize = 0; inline while (i < args.len) : (i += 1) {
...@@ -1772,32 +2278,44 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1772,32 +2278,44 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1772 \\}2278 \\}
1773 \\2279 \\
1774 \\export fn entry() usize { return @sizeOf(@typeOf(bar)); }2280 \\export fn entry() usize { return @sizeOf(@typeOf(bar)); }
1775 , ".tmp_source.zig:10:16: error: compiler bug: integer and float literals in var args function must be casted");2281 ,
2282 ".tmp_source.zig:10:16: error: compiler bug: integer and float literals in var args function must be casted",
2283 );
17762284
1777 cases.add("assign too big number to u16",2285 cases.add(
2286 "assign too big number to u16",
1778 \\export fn foo() void {2287 \\export fn foo() void {
1779 \\ var vga_mem: u16 = 0xB8000;2288 \\ var vga_mem: u16 = 0xB8000;
1780 \\}2289 \\}
1781 , ".tmp_source.zig:2:24: error: integer value 753664 cannot be implicitly casted to type 'u16'");2290 ,
2291 ".tmp_source.zig:2:24: error: integer value 753664 cannot be implicitly casted to type 'u16'",
2292 );
17822293
1783 cases.add("global variable alignment non power of 2",2294 cases.add(
2295 "global variable alignment non power of 2",
1784 \\const some_data: [100]u8 align(3) = undefined;2296 \\const some_data: [100]u8 align(3) = undefined;
1785 \\export fn entry() usize { return @sizeOf(@typeOf(some_data)); }2297 \\export fn entry() usize { return @sizeOf(@typeOf(some_data)); }
1786 , ".tmp_source.zig:1:32: error: alignment value 3 is not a power of 2");2298 ,
2299 ".tmp_source.zig:1:32: error: alignment value 3 is not a power of 2",
2300 );
17872301
1788 cases.add("function alignment non power of 2",2302 cases.add(
2303 "function alignment non power of 2",
1789 \\extern fn foo() align(3) void;2304 \\extern fn foo() align(3) void;
1790 \\export fn entry() void { return foo(); }2305 \\export fn entry() void { return foo(); }
1791 , ".tmp_source.zig:1:23: error: alignment value 3 is not a power of 2");2306 ,
2307 ".tmp_source.zig:1:23: error: alignment value 3 is not a power of 2",
2308 );
17922309
1793 cases.add("compile log",2310 cases.add(
2311 "compile log",
1794 \\export fn foo() void {2312 \\export fn foo() void {
1795 \\ comptime bar(12, "hi");2313 \\ comptime bar(12, "hi",);
1796 \\}2314 \\}
1797 \\fn bar(a: i32, b: []const u8) void {2315 \\fn bar(a: i32, b: []const u8) void {
1798 \\ @compileLog("begin");2316 \\ @compileLog("begin",);
1799 \\ @compileLog("a", a, "b", b);2317 \\ @compileLog("a", a, "b", b);
1800 \\ @compileLog("end");2318 \\ @compileLog("end",);
1801 \\}2319 \\}
1802 ,2320 ,
1803 ".tmp_source.zig:5:5: error: found compile log statement",2321 ".tmp_source.zig:5:5: error: found compile log statement",
...@@ -1805,27 +2323,32 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1805,27 +2323,32 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1805 ".tmp_source.zig:6:5: error: found compile log statement",2323 ".tmp_source.zig:6:5: error: found compile log statement",
1806 ".tmp_source.zig:2:17: note: called from here",2324 ".tmp_source.zig:2:17: note: called from here",
1807 ".tmp_source.zig:7:5: error: found compile log statement",2325 ".tmp_source.zig:7:5: error: found compile log statement",
1808 ".tmp_source.zig:2:17: note: called from here");2326 ".tmp_source.zig:2:17: note: called from here",
2327 );
18092328
1810 cases.add("casting bit offset pointer to regular pointer",2329 cases.add(
2330 "casting bit offset pointer to regular pointer",
1811 \\const BitField = packed struct {2331 \\const BitField = packed struct {
1812 \\ a: u3,2332 \\ a: u3,
1813 \\ b: u3,2333 \\ b: u3,
1814 \\ c: u2,2334 \\ c: u2,
1815 \\};2335 \\};
1816 \\2336 \\
1817 \\fn foo(bit_field: &const BitField) u3 {2337 \\fn foo(bit_field: *const BitField) u3 {
1818 \\ return bar(&bit_field.b);2338 \\ return bar(&bit_field.b);
1819 \\}2339 \\}
1820 \\2340 \\
1821 \\fn bar(x: &const u3) u3 {2341 \\fn bar(x: *const u3) u3 {
1822 \\ return x.*;2342 \\ return x.*;
1823 \\}2343 \\}
1824 \\2344 \\
1825 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }2345 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1826 , ".tmp_source.zig:8:26: error: expected type '&const u3', found '&align(1:3:6) const u3'");2346 ,
2347 ".tmp_source.zig:8:26: error: expected type '*const u3', found '*align(1:3:6) const u3'",
2348 );
18272349
1828 cases.add("referring to a struct that is invalid",2350 cases.add(
2351 "referring to a struct that is invalid",
1829 \\const UsbDeviceRequest = struct {2352 \\const UsbDeviceRequest = struct {
1830 \\ Type: u8,2353 \\ Type: u8,
1831 \\};2354 \\};
...@@ -1838,10 +2361,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1838,10 +2361,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1838 \\ if (!ok) unreachable;2361 \\ if (!ok) unreachable;
1839 \\}2362 \\}
1840 ,2363 ,
1841 ".tmp_source.zig:10:14: error: unable to evaluate constant expression",2364 ".tmp_source.zig:10:14: error: unable to evaluate constant expression",
1842 ".tmp_source.zig:6:20: note: called from here");2365 ".tmp_source.zig:6:20: note: called from here",
2366 );
18432367
1844 cases.add("control flow uses comptime var at runtime",2368 cases.add(
2369 "control flow uses comptime var at runtime",
1845 \\export fn foo() void {2370 \\export fn foo() void {
1846 \\ comptime var i = 0;2371 \\ comptime var i = 0;
1847 \\ while (i < 5) : (i += 1) {2372 \\ while (i < 5) : (i += 1) {
...@@ -1851,88 +2376,118 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1851,88 +2376,118 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1851 \\2376 \\
1852 \\fn bar() void { }2377 \\fn bar() void { }
1853 ,2378 ,
1854 ".tmp_source.zig:3:5: error: control flow attempts to use compile-time variable at runtime",2379 ".tmp_source.zig:3:5: error: control flow attempts to use compile-time variable at runtime",
1855 ".tmp_source.zig:3:24: note: compile-time variable assigned here");2380 ".tmp_source.zig:3:24: note: compile-time variable assigned here",
2381 );
18562382
1857 cases.add("ignored return value",2383 cases.add(
2384 "ignored return value",
1858 \\export fn foo() void {2385 \\export fn foo() void {
1859 \\ bar();2386 \\ bar();
1860 \\}2387 \\}
1861 \\fn bar() i32 { return 0; }2388 \\fn bar() i32 { return 0; }
1862 , ".tmp_source.zig:2:8: error: expression value is ignored");2389 ,
2390 ".tmp_source.zig:2:8: error: expression value is ignored",
2391 );
18632392
1864 cases.add("ignored assert-err-ok return value",2393 cases.add(
2394 "ignored assert-err-ok return value",
1865 \\export fn foo() void {2395 \\export fn foo() void {
1866 \\ bar() catch unreachable;2396 \\ bar() catch unreachable;
1867 \\}2397 \\}
1868 \\fn bar() error!i32 { return 0; }2398 \\fn bar() error!i32 { return 0; }
1869 , ".tmp_source.zig:2:11: error: expression value is ignored");2399 ,
2400 ".tmp_source.zig:2:11: error: expression value is ignored",
2401 );
18702402
1871 cases.add("ignored statement value",2403 cases.add(
2404 "ignored statement value",
1872 \\export fn foo() void {2405 \\export fn foo() void {
1873 \\ 1;2406 \\ 1;
1874 \\}2407 \\}
1875 , ".tmp_source.zig:2:5: error: expression value is ignored");2408 ,
2409 ".tmp_source.zig:2:5: error: expression value is ignored",
2410 );
18762411
1877 cases.add("ignored comptime statement value",2412 cases.add(
2413 "ignored comptime statement value",
1878 \\export fn foo() void {2414 \\export fn foo() void {
1879 \\ comptime {1;}2415 \\ comptime {1;}
1880 \\}2416 \\}
1881 , ".tmp_source.zig:2:15: error: expression value is ignored");2417 ,
2418 ".tmp_source.zig:2:15: error: expression value is ignored",
2419 );
18822420
1883 cases.add("ignored comptime value",2421 cases.add(
2422 "ignored comptime value",
1884 \\export fn foo() void {2423 \\export fn foo() void {
1885 \\ comptime 1;2424 \\ comptime 1;
1886 \\}2425 \\}
1887 , ".tmp_source.zig:2:5: error: expression value is ignored");2426 ,
2427 ".tmp_source.zig:2:5: error: expression value is ignored",
2428 );
18882429
1889 cases.add("ignored defered statement value",2430 cases.add(
2431 "ignored defered statement value",
1890 \\export fn foo() void {2432 \\export fn foo() void {
1891 \\ defer {1;}2433 \\ defer {1;}
1892 \\}2434 \\}
1893 , ".tmp_source.zig:2:12: error: expression value is ignored");2435 ,
2436 ".tmp_source.zig:2:12: error: expression value is ignored",
2437 );
18942438
1895 cases.add("ignored defered function call",2439 cases.add(
2440 "ignored defered function call",
1896 \\export fn foo() void {2441 \\export fn foo() void {
1897 \\ defer bar();2442 \\ defer bar();
1898 \\}2443 \\}
1899 \\fn bar() error!i32 { return 0; }2444 \\fn bar() error!i32 { return 0; }
1900 , ".tmp_source.zig:2:14: error: expression value is ignored");2445 ,
2446 ".tmp_source.zig:2:14: error: expression value is ignored",
2447 );
19012448
1902 cases.add("dereference an array",2449 cases.add(
2450 "dereference an array",
1903 \\var s_buffer: [10]u8 = undefined;2451 \\var s_buffer: [10]u8 = undefined;
1904 \\pub fn pass(in: []u8) []u8 {2452 \\pub fn pass(in: []u8) []u8 {
1905 \\ var out = &s_buffer;2453 \\ var out = &s_buffer;
1906 \\ out[0].* = in[0];2454 \\ out.*.* = in[0];
1907 \\ return out.*[0..1];2455 \\ return out.*[0..1];
1908 \\}2456 \\}
1909 \\2457 \\
1910 \\export fn entry() usize { return @sizeOf(@typeOf(pass)); }2458 \\export fn entry() usize { return @sizeOf(@typeOf(pass)); }
1911 , ".tmp_source.zig:4:11: error: attempt to dereference non pointer type '[10]u8'");2459 ,
2460 ".tmp_source.zig:4:10: error: attempt to dereference non pointer type '[10]u8'",
2461 );
19122462
1913 cases.add("pass const ptr to mutable ptr fn",2463 cases.add(
2464 "pass const ptr to mutable ptr fn",
1914 \\fn foo() bool {2465 \\fn foo() bool {
1915 \\ const a = ([]const u8)("a");2466 \\ const a = ([]const u8)("a",);
1916 \\ const b = &a;2467 \\ const b = &a;
1917 \\ return ptrEql(b, b);2468 \\ return ptrEql(b, b);
1918 \\}2469 \\}
1919 \\fn ptrEql(a: &[]const u8, b: &[]const u8) bool {2470 \\fn ptrEql(a: *[]const u8, b: *[]const u8) bool {
1920 \\ return true;2471 \\ return true;
1921 \\}2472 \\}
1922 \\2473 \\
1923 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }2474 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1924 , ".tmp_source.zig:4:19: error: expected type '&[]const u8', found '&const []const u8'");2475 ,
2476 ".tmp_source.zig:4:19: error: expected type '*[]const u8', found '*const []const u8'",
2477 );
19252478
1926 cases.addCase(x: {2479 cases.addCase(x: {
1927 const tc = cases.create("export collision",2480 const tc = cases.create(
1928 \\const foo = @import("foo.zig");2481 "export collision",
2482 \\const foo = @import("foo.zig",);
1929 \\2483 \\
1930 \\export fn bar() usize {2484 \\export fn bar() usize {
1931 \\ return foo.baz;2485 \\ return foo.baz;
1932 \\}2486 \\}
1933 ,2487 ,
1934 "foo.zig:1:8: error: exported symbol collision: 'bar'",2488 "foo.zig:1:8: error: exported symbol collision: 'bar'",
1935 ".tmp_source.zig:3:8: note: other symbol here");2489 ".tmp_source.zig:3:8: note: other symbol here",
2490 );
19362491
1937 tc.addSourceFile("foo.zig",2492 tc.addSourceFile("foo.zig",
1938 \\export fn bar() void {}2493 \\export fn bar() void {}
...@@ -1942,35 +2497,48 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1942,35 +2497,48 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1942 break :x tc;2497 break :x tc;
1943 });2498 });
19442499
1945 cases.add("pass non-copyable type by value to function",2500 cases.add(
2501 "pass non-copyable type by value to function",
1946 \\const Point = struct { x: i32, y: i32, };2502 \\const Point = struct { x: i32, y: i32, };
1947 \\fn foo(p: Point) void { }2503 \\fn foo(p: Point) void { }
1948 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }2504 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1949 , ".tmp_source.zig:2:11: error: type 'Point' is not copyable; cannot pass by value");2505 ,
2506 ".tmp_source.zig:2:11: error: type 'Point' is not copyable; cannot pass by value",
2507 );
19502508
1951 cases.add("implicit cast from array to mutable slice",2509 cases.add(
2510 "implicit cast from array to mutable slice",
1952 \\var global_array: [10]i32 = undefined;2511 \\var global_array: [10]i32 = undefined;
1953 \\fn foo(param: []i32) void {}2512 \\fn foo(param: []i32) void {}
1954 \\export fn entry() void {2513 \\export fn entry() void {
1955 \\ foo(global_array);2514 \\ foo(global_array);
1956 \\}2515 \\}
1957 , ".tmp_source.zig:4:9: error: expected type '[]i32', found '[10]i32'");2516 ,
2517 ".tmp_source.zig:4:9: error: expected type '[]i32', found '[10]i32'",
2518 );
19582519
1959 cases.add("ptrcast to non-pointer",2520 cases.add(
1960 \\export fn entry(a: &i32) usize {2521 "ptrcast to non-pointer",
2522 \\export fn entry(a: *i32) usize {
1961 \\ return @ptrCast(usize, a);2523 \\ return @ptrCast(usize, a);
1962 \\}2524 \\}
1963 , ".tmp_source.zig:2:21: error: expected pointer, found 'usize'");2525 ,
2526 ".tmp_source.zig:2:21: error: expected pointer, found 'usize'",
2527 );
19642528
1965 cases.add("too many error values to cast to small integer",2529 cases.add(
2530 "too many error values to cast to small integer",
1966 \\const Error = error { A, B, C, D, E, F, G, H };2531 \\const Error = error { A, B, C, D, E, F, G, H };
1967 \\fn foo(e: Error) u2 {2532 \\fn foo(e: Error) u2 {
1968 \\ return u2(e);2533 \\ return u2(e);
1969 \\}2534 \\}
1970 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }2535 \\export fn entry() usize { return @sizeOf(@typeOf(foo)); }
1971 , ".tmp_source.zig:3:14: error: too many error values to fit in 'u2'");2536 ,
2537 ".tmp_source.zig:3:14: error: too many error values to fit in 'u2'",
2538 );
19722539
1973 cases.add("asm at compile time",2540 cases.add(
2541 "asm at compile time",
1974 \\comptime {2542 \\comptime {
1975 \\ doSomeAsm();2543 \\ doSomeAsm();
1976 \\}2544 \\}
...@@ -1982,48 +2550,66 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -1982,48 +2550,66 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
1982 \\ \\.set aoeu, derp;2550 \\ \\.set aoeu, derp;
1983 \\ );2551 \\ );
1984 \\}2552 \\}
1985 , ".tmp_source.zig:6:5: error: unable to evaluate constant expression");2553 ,
2554 ".tmp_source.zig:6:5: error: unable to evaluate constant expression",
2555 );
19862556
1987 cases.add("invalid member of builtin enum",2557 cases.add(
1988 \\const builtin = @import("builtin");2558 "invalid member of builtin enum",
2559 \\const builtin = @import("builtin",);
1989 \\export fn entry() void {2560 \\export fn entry() void {
1990 \\ const foo = builtin.Arch.x86;2561 \\ const foo = builtin.Arch.x86;
1991 \\}2562 \\}
1992 , ".tmp_source.zig:3:29: error: container 'Arch' has no member called 'x86'");2563 ,
2564 ".tmp_source.zig:3:29: error: container 'Arch' has no member called 'x86'",
2565 );
19932566
1994 cases.add("int to ptr of 0 bits",2567 cases.add(
2568 "int to ptr of 0 bits",
1995 \\export fn foo() void {2569 \\export fn foo() void {
1996 \\ var x: usize = 0x1000;2570 \\ var x: usize = 0x1000;
1997 \\ var y: &void = @intToPtr(&void, x);2571 \\ var y: *void = @intToPtr(*void, x);
1998 \\}2572 \\}
1999 , ".tmp_source.zig:3:31: error: type '&void' has 0 bits and cannot store information");2573 ,
2574 ".tmp_source.zig:3:30: error: type '*void' has 0 bits and cannot store information",
2575 );
20002576
2001 cases.add("@fieldParentPtr - non struct",2577 cases.add(
2578 "@fieldParentPtr - non struct",
2002 \\const Foo = i32;2579 \\const Foo = i32;
2003 \\export fn foo(a: &i32) &Foo {2580 \\export fn foo(a: *i32) *Foo {
2004 \\ return @fieldParentPtr(Foo, "a", a);2581 \\ return @fieldParentPtr(Foo, "a", a);
2005 \\}2582 \\}
2006 , ".tmp_source.zig:3:28: error: expected struct type, found 'i32'");2583 ,
2584 ".tmp_source.zig:3:28: error: expected struct type, found 'i32'",
2585 );
20072586
2008 cases.add("@fieldParentPtr - bad field name",2587 cases.add(
2588 "@fieldParentPtr - bad field name",
2009 \\const Foo = extern struct {2589 \\const Foo = extern struct {
2010 \\ derp: i32,2590 \\ derp: i32,
2011 \\};2591 \\};
2012 \\export fn foo(a: &i32) &Foo {2592 \\export fn foo(a: *i32) *Foo {
2013 \\ return @fieldParentPtr(Foo, "a", a);2593 \\ return @fieldParentPtr(Foo, "a", a);
2014 \\}2594 \\}
2015 , ".tmp_source.zig:5:33: error: struct 'Foo' has no field 'a'");2595 ,
2596 ".tmp_source.zig:5:33: error: struct 'Foo' has no field 'a'",
2597 );
20162598
2017 cases.add("@fieldParentPtr - field pointer is not pointer",2599 cases.add(
2600 "@fieldParentPtr - field pointer is not pointer",
2018 \\const Foo = extern struct {2601 \\const Foo = extern struct {
2019 \\ a: i32,2602 \\ a: i32,
2020 \\};2603 \\};
2021 \\export fn foo(a: i32) &Foo {2604 \\export fn foo(a: i32) *Foo {
2022 \\ return @fieldParentPtr(Foo, "a", a);2605 \\ return @fieldParentPtr(Foo, "a", a);
2023 \\}2606 \\}
2024 , ".tmp_source.zig:5:38: error: expected pointer, found 'i32'");2607 ,
2608 ".tmp_source.zig:5:38: error: expected pointer, found 'i32'",
2609 );
20252610
2026 cases.add("@fieldParentPtr - comptime field ptr not based on struct",2611 cases.add(
2612 "@fieldParentPtr - comptime field ptr not based on struct",
2027 \\const Foo = struct {2613 \\const Foo = struct {
2028 \\ a: i32,2614 \\ a: i32,
2029 \\ b: i32,2615 \\ b: i32,
...@@ -2031,12 +2617,15 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2031,12 +2617,15 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2031 \\const foo = Foo { .a = 1, .b = 2, };2617 \\const foo = Foo { .a = 1, .b = 2, };
2032 \\2618 \\
2033 \\comptime {2619 \\comptime {
2034 \\ const field_ptr = @intToPtr(&i32, 0x1234);2620 \\ const field_ptr = @intToPtr(*i32, 0x1234);
2035 \\ const another_foo_ptr = @fieldParentPtr(Foo, "b", field_ptr);2621 \\ const another_foo_ptr = @fieldParentPtr(Foo, "b", field_ptr);
2036 \\}2622 \\}
2037 , ".tmp_source.zig:9:55: error: pointer value not based on parent struct");2623 ,
2624 ".tmp_source.zig:9:55: error: pointer value not based on parent struct",
2625 );
20382626
2039 cases.add("@fieldParentPtr - comptime wrong field index",2627 cases.add(
2628 "@fieldParentPtr - comptime wrong field index",
2040 \\const Foo = struct {2629 \\const Foo = struct {
2041 \\ a: i32,2630 \\ a: i32,
2042 \\ b: i32,2631 \\ b: i32,
...@@ -2046,76 +2635,100 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2046,76 +2635,100 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2046 \\comptime {2635 \\comptime {
2047 \\ const another_foo_ptr = @fieldParentPtr(Foo, "b", &foo.a);2636 \\ const another_foo_ptr = @fieldParentPtr(Foo, "b", &foo.a);
2048 \\}2637 \\}
2049 , ".tmp_source.zig:8:29: error: field 'b' has index 1 but pointer value is index 0 of struct 'Foo'");2638 ,
2639 ".tmp_source.zig:8:29: error: field 'b' has index 1 but pointer value is index 0 of struct 'Foo'",
2640 );
20502641
2051 cases.add("@offsetOf - non struct",2642 cases.add(
2643 "@offsetOf - non struct",
2052 \\const Foo = i32;2644 \\const Foo = i32;
2053 \\export fn foo() usize {2645 \\export fn foo() usize {
2054 \\ return @offsetOf(Foo, "a");2646 \\ return @offsetOf(Foo, "a",);
2055 \\}2647 \\}
2056 , ".tmp_source.zig:3:22: error: expected struct type, found 'i32'");2648 ,
2649 ".tmp_source.zig:3:22: error: expected struct type, found 'i32'",
2650 );
20572651
2058 cases.add("@offsetOf - bad field name",2652 cases.add(
2653 "@offsetOf - bad field name",
2059 \\const Foo = struct {2654 \\const Foo = struct {
2060 \\ derp: i32,2655 \\ derp: i32,
2061 \\};2656 \\};
2062 \\export fn foo() usize {2657 \\export fn foo() usize {
2063 \\ return @offsetOf(Foo, "a");2658 \\ return @offsetOf(Foo, "a",);
2064 \\}2659 \\}
2065 , ".tmp_source.zig:5:27: error: struct 'Foo' has no field 'a'");2660 ,
2661 ".tmp_source.zig:5:27: error: struct 'Foo' has no field 'a'",
2662 );
20662663
2067 cases.addExe("missing main fn in executable",2664 cases.addExe(
2665 "missing main fn in executable",
2068 \\2666 \\
2069 , "error: no member named 'main' in '");2667 ,
2668 "error: no member named 'main' in '",
2669 );
20702670
2071 cases.addExe("private main fn",2671 cases.addExe(
2672 "private main fn",
2072 \\fn main() void {}2673 \\fn main() void {}
2073 ,2674 ,
2074 "error: 'main' is private",2675 "error: 'main' is private",
2075 ".tmp_source.zig:1:1: note: declared here");2676 ".tmp_source.zig:1:1: note: declared here",
2677 );
20762678
2077 cases.add("setting a section on an extern variable",2679 cases.add(
2680 "setting a section on an extern variable",
2078 \\extern var foo: i32 section(".text2");2681 \\extern var foo: i32 section(".text2");
2079 \\export fn entry() i32 {2682 \\export fn entry() i32 {
2080 \\ return foo;2683 \\ return foo;
2081 \\}2684 \\}
2082 ,2685 ,
2083 ".tmp_source.zig:1:29: error: cannot set section of external variable 'foo'");2686 ".tmp_source.zig:1:29: error: cannot set section of external variable 'foo'",
2687 );
20842688
2085 cases.add("setting a section on a local variable",2689 cases.add(
2690 "setting a section on a local variable",
2086 \\export fn entry() i32 {2691 \\export fn entry() i32 {
2087 \\ var foo: i32 section(".text2") = 1234;2692 \\ var foo: i32 section(".text2") = 1234;
2088 \\ return foo;2693 \\ return foo;
2089 \\}2694 \\}
2090 ,2695 ,
2091 ".tmp_source.zig:2:26: error: cannot set section of local variable 'foo'");2696 ".tmp_source.zig:2:26: error: cannot set section of local variable 'foo'",
2697 );
20922698
2093 cases.add("setting a section on an extern fn",2699 cases.add(
2700 "setting a section on an extern fn",
2094 \\extern fn foo() section(".text2") void;2701 \\extern fn foo() section(".text2") void;
2095 \\export fn entry() void {2702 \\export fn entry() void {
2096 \\ foo();2703 \\ foo();
2097 \\}2704 \\}
2098 ,2705 ,
2099 ".tmp_source.zig:1:25: error: cannot set section of external function 'foo'");2706 ".tmp_source.zig:1:25: error: cannot set section of external function 'foo'",
2707 );
21002708
2101 cases.add("returning address of local variable - simple",2709 cases.add(
2102 \\export fn foo() &i32 {2710 "returning address of local variable - simple",
2711 \\export fn foo() *i32 {
2103 \\ var a: i32 = undefined;2712 \\ var a: i32 = undefined;
2104 \\ return &a;2713 \\ return &a;
2105 \\}2714 \\}
2106 ,2715 ,
2107 ".tmp_source.zig:3:13: error: function returns address of local variable");2716 ".tmp_source.zig:3:13: error: function returns address of local variable",
2717 );
21082718
2109 cases.add("returning address of local variable - phi",2719 cases.add(
2110 \\export fn foo(c: bool) &i32 {2720 "returning address of local variable - phi",
2721 \\export fn foo(c: bool) *i32 {
2111 \\ var a: i32 = undefined;2722 \\ var a: i32 = undefined;
2112 \\ var b: i32 = undefined;2723 \\ var b: i32 = undefined;
2113 \\ return if (c) &a else &b;2724 \\ return if (c) &a else &b;
2114 \\}2725 \\}
2115 ,2726 ,
2116 ".tmp_source.zig:4:12: error: function returns address of local variable");2727 ".tmp_source.zig:4:12: error: function returns address of local variable",
2728 );
21172729
2118 cases.add("inner struct member shadowing outer struct member",2730 cases.add(
2731 "inner struct member shadowing outer struct member",
2119 \\fn A() type {2732 \\fn A() type {
2120 \\ return struct {2733 \\ return struct {
2121 \\ b: B(),2734 \\ b: B(),
...@@ -2137,57 +2750,71 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2137,57 +2750,71 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2137 \\}2750 \\}
2138 ,2751 ,
2139 ".tmp_source.zig:9:17: error: redefinition of 'Self'",2752 ".tmp_source.zig:9:17: error: redefinition of 'Self'",
2140 ".tmp_source.zig:5:9: note: previous definition is here");2753 ".tmp_source.zig:5:9: note: previous definition is here",
2754 );
21412755
2142 cases.add("while expected bool, got nullable",2756 cases.add(
2757 "while expected bool, got nullable",
2143 \\export fn foo() void {2758 \\export fn foo() void {
2144 \\ while (bar()) {}2759 \\ while (bar()) {}
2145 \\}2760 \\}
2146 \\fn bar() ?i32 { return 1; }2761 \\fn bar() ?i32 { return 1; }
2147 ,2762 ,
2148 ".tmp_source.zig:2:15: error: expected type 'bool', found '?i32'");2763 ".tmp_source.zig:2:15: error: expected type 'bool', found '?i32'",
2764 );
21492765
2150 cases.add("while expected bool, got error union",2766 cases.add(
2767 "while expected bool, got error union",
2151 \\export fn foo() void {2768 \\export fn foo() void {
2152 \\ while (bar()) {}2769 \\ while (bar()) {}
2153 \\}2770 \\}
2154 \\fn bar() error!i32 { return 1; }2771 \\fn bar() error!i32 { return 1; }
2155 ,2772 ,
2156 ".tmp_source.zig:2:15: error: expected type 'bool', found 'error!i32'");2773 ".tmp_source.zig:2:15: error: expected type 'bool', found 'error!i32'",
2774 );
21572775
2158 cases.add("while expected nullable, got bool",2776 cases.add(
2777 "while expected nullable, got bool",
2159 \\export fn foo() void {2778 \\export fn foo() void {
2160 \\ while (bar()) |x| {}2779 \\ while (bar()) |x| {}
2161 \\}2780 \\}
2162 \\fn bar() bool { return true; }2781 \\fn bar() bool { return true; }
2163 ,2782 ,
2164 ".tmp_source.zig:2:15: error: expected nullable type, found 'bool'");2783 ".tmp_source.zig:2:15: error: expected nullable type, found 'bool'",
2784 );
21652785
2166 cases.add("while expected nullable, got error union",2786 cases.add(
2787 "while expected nullable, got error union",
2167 \\export fn foo() void {2788 \\export fn foo() void {
2168 \\ while (bar()) |x| {}2789 \\ while (bar()) |x| {}
2169 \\}2790 \\}
2170 \\fn bar() error!i32 { return 1; }2791 \\fn bar() error!i32 { return 1; }
2171 ,2792 ,
2172 ".tmp_source.zig:2:15: error: expected nullable type, found 'error!i32'");2793 ".tmp_source.zig:2:15: error: expected nullable type, found 'error!i32'",
2794 );
21732795
2174 cases.add("while expected error union, got bool",2796 cases.add(
2797 "while expected error union, got bool",
2175 \\export fn foo() void {2798 \\export fn foo() void {
2176 \\ while (bar()) |x| {} else |err| {}2799 \\ while (bar()) |x| {} else |err| {}
2177 \\}2800 \\}
2178 \\fn bar() bool { return true; }2801 \\fn bar() bool { return true; }
2179 ,2802 ,
2180 ".tmp_source.zig:2:15: error: expected error union type, found 'bool'");2803 ".tmp_source.zig:2:15: error: expected error union type, found 'bool'",
2804 );
21812805
2182 cases.add("while expected error union, got nullable",2806 cases.add(
2807 "while expected error union, got nullable",
2183 \\export fn foo() void {2808 \\export fn foo() void {
2184 \\ while (bar()) |x| {} else |err| {}2809 \\ while (bar()) |x| {} else |err| {}
2185 \\}2810 \\}
2186 \\fn bar() ?i32 { return 1; }2811 \\fn bar() ?i32 { return 1; }
2187 ,2812 ,
2188 ".tmp_source.zig:2:15: error: expected error union type, found '?i32'");2813 ".tmp_source.zig:2:15: error: expected error union type, found '?i32'",
2814 );
21892815
2190 cases.add("inline fn calls itself indirectly",2816 cases.add(
2817 "inline fn calls itself indirectly",
2191 \\export fn foo() void {2818 \\export fn foo() void {
2192 \\ bar();2819 \\ bar();
2193 \\}2820 \\}
...@@ -2201,91 +2828,113 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2201,91 +2828,113 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2201 \\}2828 \\}
2202 \\extern fn quux() void;2829 \\extern fn quux() void;
2203 ,2830 ,
2204 ".tmp_source.zig:4:8: error: unable to inline function");2831 ".tmp_source.zig:4:8: error: unable to inline function",
2832 );
22052833
2206 cases.add("save reference to inline function",2834 cases.add(
2835 "save reference to inline function",
2207 \\export fn foo() void {2836 \\export fn foo() void {
2208 \\ quux(@ptrToInt(bar));2837 \\ quux(@ptrToInt(bar));
2209 \\}2838 \\}
2210 \\inline fn bar() void { }2839 \\inline fn bar() void { }
2211 \\extern fn quux(usize) void;2840 \\extern fn quux(usize) void;
2212 ,2841 ,
2213 ".tmp_source.zig:4:8: error: unable to inline function");2842 ".tmp_source.zig:4:8: error: unable to inline function",
2843 );
22142844
2215 cases.add("signed integer division",2845 cases.add(
2846 "signed integer division",
2216 \\export fn foo(a: i32, b: i32) i32 {2847 \\export fn foo(a: i32, b: i32) i32 {
2217 \\ return a / b;2848 \\ return a / b;
2218 \\}2849 \\}
2219 ,2850 ,
2220 ".tmp_source.zig:2:14: error: division with 'i32' and 'i32': signed integers must use @divTrunc, @divFloor, or @divExact");2851 ".tmp_source.zig:2:14: error: division with 'i32' and 'i32': signed integers must use @divTrunc, @divFloor, or @divExact",
2852 );
22212853
2222 cases.add("signed integer remainder division",2854 cases.add(
2855 "signed integer remainder division",
2223 \\export fn foo(a: i32, b: i32) i32 {2856 \\export fn foo(a: i32, b: i32) i32 {
2224 \\ return a % b;2857 \\ return a % b;
2225 \\}2858 \\}
2226 ,2859 ,
2227 ".tmp_source.zig:2:14: error: remainder division with 'i32' and 'i32': signed integers and floats must use @rem or @mod");2860 ".tmp_source.zig:2:14: error: remainder division with 'i32' and 'i32': signed integers and floats must use @rem or @mod",
2861 );
22282862
2229 cases.add("cast negative value to unsigned integer",2863 cases.add(
2864 "cast negative value to unsigned integer",
2230 \\comptime {2865 \\comptime {
2231 \\ const value: i32 = -1;2866 \\ const value: i32 = -1;
2232 \\ const unsigned = u32(value);2867 \\ const unsigned = u32(value);
2233 \\}2868 \\}
2234 ,2869 ,
2235 ".tmp_source.zig:3:25: error: attempt to cast negative value to unsigned integer");2870 ".tmp_source.zig:3:25: error: attempt to cast negative value to unsigned integer",
2871 );
22362872
2237 cases.add("compile-time division by zero",2873 cases.add(
2874 "compile-time division by zero",
2238 \\comptime {2875 \\comptime {
2239 \\ const a: i32 = 1;2876 \\ const a: i32 = 1;
2240 \\ const b: i32 = 0;2877 \\ const b: i32 = 0;
2241 \\ const c = a / b;2878 \\ const c = a / b;
2242 \\}2879 \\}
2243 ,2880 ,
2244 ".tmp_source.zig:4:17: error: division by zero");2881 ".tmp_source.zig:4:17: error: division by zero",
2882 );
22452883
2246 cases.add("compile-time remainder division by zero",2884 cases.add(
2885 "compile-time remainder division by zero",
2247 \\comptime {2886 \\comptime {
2248 \\ const a: i32 = 1;2887 \\ const a: i32 = 1;
2249 \\ const b: i32 = 0;2888 \\ const b: i32 = 0;
2250 \\ const c = a % b;2889 \\ const c = a % b;
2251 \\}2890 \\}
2252 ,2891 ,
2253 ".tmp_source.zig:4:17: error: division by zero");2892 ".tmp_source.zig:4:17: error: division by zero",
2893 );
22542894
2255 cases.add("compile-time integer cast truncates bits",2895 cases.add(
2896 "compile-time integer cast truncates bits",
2256 \\comptime {2897 \\comptime {
2257 \\ const spartan_count: u16 = 300;2898 \\ const spartan_count: u16 = 300;
2258 \\ const byte = u8(spartan_count);2899 \\ const byte = u8(spartan_count);
2259 \\}2900 \\}
2260 ,2901 ,
2261 ".tmp_source.zig:3:20: error: cast from 'u16' to 'u8' truncates bits");2902 ".tmp_source.zig:3:20: error: cast from 'u16' to 'u8' truncates bits",
2903 );
22622904
2263 cases.add("@setRuntimeSafety twice for same scope",2905 cases.add(
2906 "@setRuntimeSafety twice for same scope",
2264 \\export fn foo() void {2907 \\export fn foo() void {
2265 \\ @setRuntimeSafety(false);2908 \\ @setRuntimeSafety(false);
2266 \\ @setRuntimeSafety(false);2909 \\ @setRuntimeSafety(false);
2267 \\}2910 \\}
2268 ,2911 ,
2269 ".tmp_source.zig:3:5: error: runtime safety set twice for same scope",2912 ".tmp_source.zig:3:5: error: runtime safety set twice for same scope",
2270 ".tmp_source.zig:2:5: note: first set here");2913 ".tmp_source.zig:2:5: note: first set here",
2914 );
22712915
2272 cases.add("@setFloatMode twice for same scope",2916 cases.add(
2917 "@setFloatMode twice for same scope",
2273 \\export fn foo() void {2918 \\export fn foo() void {
2274 \\ @setFloatMode(this, @import("builtin").FloatMode.Optimized);2919 \\ @setFloatMode(this, @import("builtin").FloatMode.Optimized);
2275 \\ @setFloatMode(this, @import("builtin").FloatMode.Optimized);2920 \\ @setFloatMode(this, @import("builtin").FloatMode.Optimized);
2276 \\}2921 \\}
2277 ,2922 ,
2278 ".tmp_source.zig:3:5: error: float mode set twice for same scope",2923 ".tmp_source.zig:3:5: error: float mode set twice for same scope",
2279 ".tmp_source.zig:2:5: note: first set here");2924 ".tmp_source.zig:2:5: note: first set here",
2925 );
22802926
2281 cases.add("array access of type",2927 cases.add(
2928 "array access of type",
2282 \\export fn foo() void {2929 \\export fn foo() void {
2283 \\ var b: u8[40] = undefined;2930 \\ var b: u8[40] = undefined;
2284 \\}2931 \\}
2285 ,2932 ,
2286 ".tmp_source.zig:2:14: error: array access of non-array type 'type'");2933 ".tmp_source.zig:2:14: error: array access of non-array type 'type'",
2934 );
22872935
2288 cases.add("cannot break out of defer expression",2936 cases.add(
2937 "cannot break out of defer expression",
2289 \\export fn foo() void {2938 \\export fn foo() void {
2290 \\ while (true) {2939 \\ while (true) {
2291 \\ defer {2940 \\ defer {
...@@ -2294,9 +2943,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2294,9 +2943,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2294 \\ }2943 \\ }
2295 \\}2944 \\}
2296 ,2945 ,
2297 ".tmp_source.zig:4:13: error: cannot break out of defer expression");2946 ".tmp_source.zig:4:13: error: cannot break out of defer expression",
2947 );
22982948
2299 cases.add("cannot continue out of defer expression",2949 cases.add(
2950 "cannot continue out of defer expression",
2300 \\export fn foo() void {2951 \\export fn foo() void {
2301 \\ while (true) {2952 \\ while (true) {
2302 \\ defer {2953 \\ defer {
...@@ -2305,9 +2956,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2305,9 +2956,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2305 \\ }2956 \\ }
2306 \\}2957 \\}
2307 ,2958 ,
2308 ".tmp_source.zig:4:13: error: cannot continue out of defer expression");2959 ".tmp_source.zig:4:13: error: cannot continue out of defer expression",
2960 );
23092961
2310 cases.add("calling a var args function only known at runtime",2962 cases.add(
2963 "calling a var args function only known at runtime",
2311 \\var foos = []fn(...) void { foo1, foo2 };2964 \\var foos = []fn(...) void { foo1, foo2 };
2312 \\2965 \\
2313 \\fn foo1(args: ...) void {}2966 \\fn foo1(args: ...) void {}
...@@ -2317,9 +2970,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2317,9 +2970,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2317 \\ foos[0]();2970 \\ foos[0]();
2318 \\}2971 \\}
2319 ,2972 ,
2320 ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value");2973 ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value",
2974 );
23212975
2322 cases.add("calling a generic function only known at runtime",2976 cases.add(
2977 "calling a generic function only known at runtime",
2323 \\var foos = []fn(var) void { foo1, foo2 };2978 \\var foos = []fn(var) void { foo1, foo2 };
2324 \\2979 \\
2325 \\fn foo1(arg: var) void {}2980 \\fn foo1(arg: var) void {}
...@@ -2329,10 +2984,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2329,10 +2984,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2329 \\ foos[0](true);2984 \\ foos[0](true);
2330 \\}2985 \\}
2331 ,2986 ,
2332 ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value");2987 ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value",
2988 );
23332989
2334 cases.add("@compileError shows traceback of references that caused it",2990 cases.add(
2335 \\const foo = @compileError("aoeu");2991 "@compileError shows traceback of references that caused it",
2992 \\const foo = @compileError("aoeu",);
2336 \\2993 \\
2337 \\const bar = baz + foo;2994 \\const bar = baz + foo;
2338 \\const baz = 1;2995 \\const baz = 1;
...@@ -2343,9 +3000,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2343,9 +3000,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2343 ,3000 ,
2344 ".tmp_source.zig:1:13: error: aoeu",3001 ".tmp_source.zig:1:13: error: aoeu",
2345 ".tmp_source.zig:3:19: note: referenced here",3002 ".tmp_source.zig:3:19: note: referenced here",
2346 ".tmp_source.zig:7:12: note: referenced here");3003 ".tmp_source.zig:7:12: note: referenced here",
3004 );
23473005
2348 cases.add("instantiating an undefined value for an invalid struct that contains itself",3006 cases.add(
3007 "instantiating an undefined value for an invalid struct that contains itself",
2349 \\const Foo = struct {3008 \\const Foo = struct {
2350 \\ x: Foo,3009 \\ x: Foo,
2351 \\};3010 \\};
...@@ -2356,73 +3015,93 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2356,73 +3015,93 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2356 \\ return @sizeOf(@typeOf(foo.x));3015 \\ return @sizeOf(@typeOf(foo.x));
2357 \\}3016 \\}
2358 ,3017 ,
2359 ".tmp_source.zig:1:13: error: struct 'Foo' contains itself");3018 ".tmp_source.zig:1:13: error: struct 'Foo' contains itself",
3019 );
23603020
2361 cases.add("float literal too large error",3021 cases.add(
3022 "float literal too large error",
2362 \\comptime {3023 \\comptime {
2363 \\ const a = 0x1.0p16384;3024 \\ const a = 0x1.0p16384;
2364 \\}3025 \\}
2365 ,3026 ,
2366 ".tmp_source.zig:2:15: error: float literal out of range of any type");3027 ".tmp_source.zig:2:15: error: float literal out of range of any type",
3028 );
23673029
2368 cases.add("float literal too small error (denormal)",3030 cases.add(
3031 "float literal too small error (denormal)",
2369 \\comptime {3032 \\comptime {
2370 \\ const a = 0x1.0p-16384;3033 \\ const a = 0x1.0p-16384;
2371 \\}3034 \\}
2372 ,3035 ,
2373 ".tmp_source.zig:2:15: error: float literal out of range of any type");3036 ".tmp_source.zig:2:15: error: float literal out of range of any type",
3037 );
23743038
2375 cases.add("explicit cast float literal to integer when there is a fraction component",3039 cases.add(
3040 "explicit cast float literal to integer when there is a fraction component",
2376 \\export fn entry() i32 {3041 \\export fn entry() i32 {
2377 \\ return i32(12.34);3042 \\ return i32(12.34);
2378 \\}3043 \\}
2379 ,3044 ,
2380 ".tmp_source.zig:2:16: error: fractional component prevents float value 12.340000 from being casted to type 'i32'");3045 ".tmp_source.zig:2:16: error: fractional component prevents float value 12.340000 from being casted to type 'i32'",
3046 );
23813047
2382 cases.add("non pointer given to @ptrToInt",3048 cases.add(
3049 "non pointer given to @ptrToInt",
2383 \\export fn entry(x: i32) usize {3050 \\export fn entry(x: i32) usize {
2384 \\ return @ptrToInt(x);3051 \\ return @ptrToInt(x);
2385 \\}3052 \\}
2386 ,3053 ,
2387 ".tmp_source.zig:2:22: error: expected pointer, found 'i32'");3054 ".tmp_source.zig:2:22: error: expected pointer, found 'i32'",
3055 );
23883056
2389 cases.add("@shlExact shifts out 1 bits",3057 cases.add(
3058 "@shlExact shifts out 1 bits",
2390 \\comptime {3059 \\comptime {
2391 \\ const x = @shlExact(u8(0b01010101), 2);3060 \\ const x = @shlExact(u8(0b01010101), 2);
2392 \\}3061 \\}
2393 ,3062 ,
2394 ".tmp_source.zig:2:15: error: operation caused overflow");3063 ".tmp_source.zig:2:15: error: operation caused overflow",
3064 );
23953065
2396 cases.add("@shrExact shifts out 1 bits",3066 cases.add(
3067 "@shrExact shifts out 1 bits",
2397 \\comptime {3068 \\comptime {
2398 \\ const x = @shrExact(u8(0b10101010), 2);3069 \\ const x = @shrExact(u8(0b10101010), 2);
2399 \\}3070 \\}
2400 ,3071 ,
2401 ".tmp_source.zig:2:15: error: exact shift shifted out 1 bits");3072 ".tmp_source.zig:2:15: error: exact shift shifted out 1 bits",
3073 );
24023074
2403 cases.add("shifting without int type or comptime known",3075 cases.add(
3076 "shifting without int type or comptime known",
2404 \\export fn entry(x: u8) u8 {3077 \\export fn entry(x: u8) u8 {
2405 \\ return 0x11 << x;3078 \\ return 0x11 << x;
2406 \\}3079 \\}
2407 ,3080 ,
2408 ".tmp_source.zig:2:17: error: LHS of shift must be an integer type, or RHS must be compile-time known");3081 ".tmp_source.zig:2:17: error: LHS of shift must be an integer type, or RHS must be compile-time known",
3082 );
24093083
2410 cases.add("shifting RHS is log2 of LHS int bit width",3084 cases.add(
3085 "shifting RHS is log2 of LHS int bit width",
2411 \\export fn entry(x: u8, y: u8) u8 {3086 \\export fn entry(x: u8, y: u8) u8 {
2412 \\ return x << y;3087 \\ return x << y;
2413 \\}3088 \\}
2414 ,3089 ,
2415 ".tmp_source.zig:2:17: error: expected type 'u3', found 'u8'");3090 ".tmp_source.zig:2:17: error: expected type 'u3', found 'u8'",
3091 );
24163092
2417 cases.add("globally shadowing a primitive type",3093 cases.add(
3094 "globally shadowing a primitive type",
2418 \\const u16 = @intType(false, 8);3095 \\const u16 = @intType(false, 8);
2419 \\export fn entry() void {3096 \\export fn entry() void {
2420 \\ const a: u16 = 300;3097 \\ const a: u16 = 300;
2421 \\}3098 \\}
2422 ,3099 ,
2423 ".tmp_source.zig:1:1: error: declaration shadows type 'u16'");3100 ".tmp_source.zig:1:1: error: declaration shadows type 'u16'",
3101 );
24243102
2425 cases.add("implicitly increasing pointer alignment",3103 cases.add(
3104 "implicitly increasing pointer alignment",
2426 \\const Foo = packed struct {3105 \\const Foo = packed struct {
2427 \\ a: u8,3106 \\ a: u8,
2428 \\ b: u32,3107 \\ b: u32,
...@@ -2433,13 +3112,15 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2433,13 +3112,15 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2433 \\ bar(&foo.b);3112 \\ bar(&foo.b);
2434 \\}3113 \\}
2435 \\3114 \\
2436 \\fn bar(x: &u32) void {3115 \\fn bar(x: *u32) void {
2437 \\ x.* += 1;3116 \\ x.* += 1;
2438 \\}3117 \\}
2439 ,3118 ,
2440 ".tmp_source.zig:8:13: error: expected type '&u32', found '&align(1) u32'");3119 ".tmp_source.zig:8:13: error: expected type '*u32', found '*align(1) u32'",
3120 );
24413121
2442 cases.add("implicitly increasing slice alignment",3122 cases.add(
3123 "implicitly increasing slice alignment",
2443 \\const Foo = packed struct {3124 \\const Foo = packed struct {
2444 \\ a: u8,3125 \\ a: u8,
2445 \\ b: u32,3126 \\ b: u32,
...@@ -2455,20 +3136,24 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2455,20 +3136,24 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2455 \\ x[0] += 1;3136 \\ x[0] += 1;
2456 \\}3137 \\}
2457 ,3138 ,
2458 ".tmp_source.zig:9:17: error: expected type '[]u32', found '[]align(1) u32'");3139 ".tmp_source.zig:9:17: error: expected type '[]u32', found '[]align(1) u32'",
3140 );
24593141
2460 cases.add("increase pointer alignment in @ptrCast",3142 cases.add(
3143 "increase pointer alignment in @ptrCast",
2461 \\export fn entry() u32 {3144 \\export fn entry() u32 {
2462 \\ var bytes: [4]u8 = []u8{0x01, 0x02, 0x03, 0x04};3145 \\ var bytes: [4]u8 = []u8{0x01, 0x02, 0x03, 0x04};
2463 \\ const ptr = @ptrCast(&u32, &bytes[0]);3146 \\ const ptr = @ptrCast(*u32, &bytes[0]);
2464 \\ return ptr.*;3147 \\ return ptr.*;
2465 \\}3148 \\}
2466 ,3149 ,
2467 ".tmp_source.zig:3:17: error: cast increases pointer alignment",3150 ".tmp_source.zig:3:17: error: cast increases pointer alignment",
2468 ".tmp_source.zig:3:38: note: '&u8' has alignment 1",3151 ".tmp_source.zig:3:38: note: '*u8' has alignment 1",
2469 ".tmp_source.zig:3:27: note: '&u32' has alignment 4");3152 ".tmp_source.zig:3:26: note: '*u32' has alignment 4",
3153 );
24703154
2471 cases.add("increase pointer alignment in slice resize",3155 cases.add(
3156 "increase pointer alignment in slice resize",
2472 \\export fn entry() u32 {3157 \\export fn entry() u32 {
2473 \\ var bytes = []u8{0x01, 0x02, 0x03, 0x04};3158 \\ var bytes = []u8{0x01, 0x02, 0x03, 0x04};
2474 \\ return ([]u32)(bytes[0..])[0];3159 \\ return ([]u32)(bytes[0..])[0];
...@@ -2476,16 +3161,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2476,16 +3161,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2476 ,3161 ,
2477 ".tmp_source.zig:3:19: error: cast increases pointer alignment",3162 ".tmp_source.zig:3:19: error: cast increases pointer alignment",
2478 ".tmp_source.zig:3:19: note: '[]u8' has alignment 1",3163 ".tmp_source.zig:3:19: note: '[]u8' has alignment 1",
2479 ".tmp_source.zig:3:19: note: '[]u32' has alignment 4");3164 ".tmp_source.zig:3:19: note: '[]u32' has alignment 4",
3165 );
24803166
2481 cases.add("@alignCast expects pointer or slice",3167 cases.add(
3168 "@alignCast expects pointer or slice",
2482 \\export fn entry() void {3169 \\export fn entry() void {
2483 \\ @alignCast(4, u32(3));3170 \\ @alignCast(4, u32(3));
2484 \\}3171 \\}
2485 ,3172 ,
2486 ".tmp_source.zig:2:22: error: expected pointer or slice, found 'u32'");3173 ".tmp_source.zig:2:22: error: expected pointer or slice, found 'u32'",
3174 );
24873175
2488 cases.add("passing an under-aligned function pointer",3176 cases.add(
3177 "passing an under-aligned function pointer",
2489 \\export fn entry() void {3178 \\export fn entry() void {
2490 \\ testImplicitlyDecreaseFnAlign(alignedSmall, 1234);3179 \\ testImplicitlyDecreaseFnAlign(alignedSmall, 1234);
2491 \\}3180 \\}
...@@ -2494,9 +3183,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2494,9 +3183,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2494 \\}3183 \\}
2495 \\fn alignedSmall() align(4) i32 { return 1234; }3184 \\fn alignedSmall() align(4) i32 { return 1234; }
2496 ,3185 ,
2497 ".tmp_source.zig:2:35: error: expected type 'fn() align(8) i32', found 'fn() align(4) i32'");3186 ".tmp_source.zig:2:35: error: expected type 'fn() align(8) i32', found 'fn() align(4) i32'",
3187 );
24983188
2499 cases.add("passing a not-aligned-enough pointer to cmpxchg",3189 cases.add(
3190 "passing a not-aligned-enough pointer to cmpxchg",
2500 \\const AtomicOrder = @import("builtin").AtomicOrder;3191 \\const AtomicOrder = @import("builtin").AtomicOrder;
2501 \\export fn entry() bool {3192 \\export fn entry() bool {
2502 \\ var x: i32 align(1) = 1234;3193 \\ var x: i32 align(1) = 1234;
...@@ -2504,16 +3195,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2504,16 +3195,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2504 \\ return x == 5678;3195 \\ return x == 5678;
2505 \\}3196 \\}
2506 ,3197 ,
2507 ".tmp_source.zig:4:32: error: expected type '&i32', found '&align(1) i32'");3198 ".tmp_source.zig:4:32: error: expected type '*i32', found '*align(1) i32'",
3199 );
25083200
2509 cases.add("wrong size to an array literal",3201 cases.add(
3202 "wrong size to an array literal",
2510 \\comptime {3203 \\comptime {
2511 \\ const array = [2]u8{1, 2, 3};3204 \\ const array = [2]u8{1, 2, 3};
2512 \\}3205 \\}
2513 ,3206 ,
2514 ".tmp_source.zig:2:24: error: expected [2]u8 literal, found [3]u8 literal");3207 ".tmp_source.zig:2:24: error: expected [2]u8 literal, found [3]u8 literal",
3208 );
25153209
2516 cases.add("@setEvalBranchQuota in non-root comptime execution context",3210 cases.add(
3211 "@setEvalBranchQuota in non-root comptime execution context",
2517 \\comptime {3212 \\comptime {
2518 \\ foo();3213 \\ foo();
2519 \\}3214 \\}
...@@ -2523,22 +3218,26 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2523,22 +3218,26 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2523 ,3218 ,
2524 ".tmp_source.zig:5:5: error: @setEvalBranchQuota must be called from the top of the comptime stack",3219 ".tmp_source.zig:5:5: error: @setEvalBranchQuota must be called from the top of the comptime stack",
2525 ".tmp_source.zig:2:8: note: called from here",3220 ".tmp_source.zig:2:8: note: called from here",
2526 ".tmp_source.zig:1:10: note: called from here");3221 ".tmp_source.zig:1:10: note: called from here",
3222 );
25273223
2528 cases.add("wrong pointer implicitly casted to pointer to @OpaqueType()",3224 cases.add(
3225 "wrong pointer implicitly casted to pointer to @OpaqueType()",
2529 \\const Derp = @OpaqueType();3226 \\const Derp = @OpaqueType();
2530 \\extern fn bar(d: &Derp) void;3227 \\extern fn bar(d: *Derp) void;
2531 \\export fn foo() void {3228 \\export fn foo() void {
2532 \\ var x = u8(1);3229 \\ var x = u8(1);
2533 \\ bar(@ptrCast(&c_void, &x));3230 \\ bar(@ptrCast(*c_void, &x));
2534 \\}3231 \\}
2535 ,3232 ,
2536 ".tmp_source.zig:5:9: error: expected type '&Derp', found '&c_void'");3233 ".tmp_source.zig:5:9: error: expected type '*Derp', found '*c_void'",
3234 );
25373235
2538 cases.add("non-const variables of things that require const variables",3236 cases.add(
3237 "non-const variables of things that require const variables",
2539 \\const Opaque = @OpaqueType();3238 \\const Opaque = @OpaqueType();
2540 \\3239 \\
2541 \\export fn entry(opaque: &Opaque) void {3240 \\export fn entry(opaque: *Opaque) void {
2542 \\ var m2 = &2;3241 \\ var m2 = &2;
2543 \\ const y: u32 = m2.*;3242 \\ const y: u32 = m2.*;
2544 \\3243 \\
...@@ -2549,17 +3248,17 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2549,17 +3248,17 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2549 \\ var e = null;3248 \\ var e = null;
2550 \\ var f = opaque.*;3249 \\ var f = opaque.*;
2551 \\ var g = i32;3250 \\ var g = i32;
2552 \\ var h = @import("std");3251 \\ var h = @import("std",);
2553 \\ var i = (Foo {}).bar;3252 \\ var i = (Foo {}).bar;
2554 \\3253 \\
2555 \\ var z: noreturn = return;3254 \\ var z: noreturn = return;
2556 \\}3255 \\}
2557 \\3256 \\
2558 \\const Foo = struct {3257 \\const Foo = struct {
2559 \\ fn bar(self: &const Foo) void {}3258 \\ fn bar(self: *const Foo) void {}
2560 \\};3259 \\};
2561 ,3260 ,
2562 ".tmp_source.zig:4:4: error: variable of type '&const (integer literal)' must be const or comptime",3261 ".tmp_source.zig:4:4: error: variable of type '*(integer literal)' must be const or comptime",
2563 ".tmp_source.zig:7:4: error: variable of type '(undefined)' must be const or comptime",3262 ".tmp_source.zig:7:4: error: variable of type '(undefined)' must be const or comptime",
2564 ".tmp_source.zig:8:4: error: variable of type '(integer literal)' must be const or comptime",3263 ".tmp_source.zig:8:4: error: variable of type '(integer literal)' must be const or comptime",
2565 ".tmp_source.zig:9:4: error: variable of type '(float literal)' must be const or comptime",3264 ".tmp_source.zig:9:4: error: variable of type '(float literal)' must be const or comptime",
...@@ -2568,27 +3267,33 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2568,27 +3267,33 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2568 ".tmp_source.zig:12:4: error: variable of type 'Opaque' must be const or comptime",3267 ".tmp_source.zig:12:4: error: variable of type 'Opaque' must be const or comptime",
2569 ".tmp_source.zig:13:4: error: variable of type 'type' must be const or comptime",3268 ".tmp_source.zig:13:4: error: variable of type 'type' must be const or comptime",
2570 ".tmp_source.zig:14:4: error: variable of type '(namespace)' must be const or comptime",3269 ".tmp_source.zig:14:4: error: variable of type '(namespace)' must be const or comptime",
2571 ".tmp_source.zig:15:4: error: variable of type '(bound fn(&const Foo) void)' must be const or comptime",3270 ".tmp_source.zig:15:4: error: variable of type '(bound fn(*const Foo) void)' must be const or comptime",
2572 ".tmp_source.zig:17:4: error: unreachable code");3271 ".tmp_source.zig:17:4: error: unreachable code",
3272 );
25733273
2574 cases.add("wrong types given to atomic order args in cmpxchg",3274 cases.add(
3275 "wrong types given to atomic order args in cmpxchg",
2575 \\export fn entry() void {3276 \\export fn entry() void {
2576 \\ var x: i32 = 1234;3277 \\ var x: i32 = 1234;
2577 \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, u32(1234), u32(1234))) {}3278 \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, u32(1234), u32(1234))) {}
2578 \\}3279 \\}
2579 ,3280 ,
2580 ".tmp_source.zig:3:50: error: expected type 'AtomicOrder', found 'u32'");3281 ".tmp_source.zig:3:50: error: expected type 'AtomicOrder', found 'u32'",
3282 );
25813283
2582 cases.add("wrong types given to @export",3284 cases.add(
3285 "wrong types given to @export",
2583 \\extern fn entry() void { }3286 \\extern fn entry() void { }
2584 \\comptime {3287 \\comptime {
2585 \\ @export("entry", entry, u32(1234));3288 \\ @export("entry", entry, u32(1234));
2586 \\}3289 \\}
2587 ,3290 ,
2588 ".tmp_source.zig:3:32: error: expected type 'GlobalLinkage', found 'u32'");3291 ".tmp_source.zig:3:32: error: expected type 'GlobalLinkage', found 'u32'",
3292 );
25893293
2590 cases.add("struct with invalid field",3294 cases.add(
2591 \\const std = @import("std");3295 "struct with invalid field",
3296 \\const std = @import("std",);
2592 \\const Allocator = std.mem.Allocator;3297 \\const Allocator = std.mem.Allocator;
2593 \\const ArrayList = std.ArrayList;3298 \\const ArrayList = std.ArrayList;
2594 \\3299 \\
...@@ -2612,23 +3317,29 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2612,23 +3317,29 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2612 \\ };3317 \\ };
2613 \\}3318 \\}
2614 ,3319 ,
2615 ".tmp_source.zig:14:17: error: use of undeclared identifier 'HeaderValue'");3320 ".tmp_source.zig:14:17: error: use of undeclared identifier 'HeaderValue'",
3321 );
26163322
2617 cases.add("@setAlignStack outside function",3323 cases.add(
3324 "@setAlignStack outside function",
2618 \\comptime {3325 \\comptime {
2619 \\ @setAlignStack(16);3326 \\ @setAlignStack(16);
2620 \\}3327 \\}
2621 ,3328 ,
2622 ".tmp_source.zig:2:5: error: @setAlignStack outside function");3329 ".tmp_source.zig:2:5: error: @setAlignStack outside function",
3330 );
26233331
2624 cases.add("@setAlignStack in naked function",3332 cases.add(
3333 "@setAlignStack in naked function",
2625 \\export nakedcc fn entry() void {3334 \\export nakedcc fn entry() void {
2626 \\ @setAlignStack(16);3335 \\ @setAlignStack(16);
2627 \\}3336 \\}
2628 ,3337 ,
2629 ".tmp_source.zig:2:5: error: @setAlignStack in naked function");3338 ".tmp_source.zig:2:5: error: @setAlignStack in naked function",
3339 );
26303340
2631 cases.add("@setAlignStack in inline function",3341 cases.add(
3342 "@setAlignStack in inline function",
2632 \\export fn entry() void {3343 \\export fn entry() void {
2633 \\ foo();3344 \\ foo();
2634 \\}3345 \\}
...@@ -2636,25 +3347,31 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2636,25 +3347,31 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2636 \\ @setAlignStack(16);3347 \\ @setAlignStack(16);
2637 \\}3348 \\}
2638 ,3349 ,
2639 ".tmp_source.zig:5:5: error: @setAlignStack in inline function");3350 ".tmp_source.zig:5:5: error: @setAlignStack in inline function",
3351 );
26403352
2641 cases.add("@setAlignStack set twice",3353 cases.add(
3354 "@setAlignStack set twice",
2642 \\export fn entry() void {3355 \\export fn entry() void {
2643 \\ @setAlignStack(16);3356 \\ @setAlignStack(16);
2644 \\ @setAlignStack(16);3357 \\ @setAlignStack(16);
2645 \\}3358 \\}
2646 ,3359 ,
2647 ".tmp_source.zig:3:5: error: alignstack set twice",3360 ".tmp_source.zig:3:5: error: alignstack set twice",
2648 ".tmp_source.zig:2:5: note: first set here");3361 ".tmp_source.zig:2:5: note: first set here",
3362 );
26493363
2650 cases.add("@setAlignStack too big",3364 cases.add(
3365 "@setAlignStack too big",
2651 \\export fn entry() void {3366 \\export fn entry() void {
2652 \\ @setAlignStack(511 + 1);3367 \\ @setAlignStack(511 + 1);
2653 \\}3368 \\}
2654 ,3369 ,
2655 ".tmp_source.zig:2:5: error: attempt to @setAlignStack(512); maximum is 256");3370 ".tmp_source.zig:2:5: error: attempt to @setAlignStack(512); maximum is 256",
3371 );
26563372
2657 cases.add("storing runtime value in compile time variable then using it",3373 cases.add(
3374 "storing runtime value in compile time variable then using it",
2658 \\const Mode = @import("builtin").Mode;3375 \\const Mode = @import("builtin").Mode;
2659 \\3376 \\
2660 \\fn Free(comptime filename: []const u8) TestCase {3377 \\fn Free(comptime filename: []const u8) TestCase {
...@@ -2697,134 +3414,164 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2697,134 +3414,164 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2697 \\ }3414 \\ }
2698 \\}3415 \\}
2699 ,3416 ,
2700 ".tmp_source.zig:37:16: error: cannot store runtime value in compile time variable");3417 ".tmp_source.zig:37:16: error: cannot store runtime value in compile time variable",
3418 );
27013419
2702 cases.add("field access of opaque type",3420 cases.add(
3421 "field access of opaque type",
2703 \\const MyType = @OpaqueType();3422 \\const MyType = @OpaqueType();
2704 \\3423 \\
2705 \\export fn entry() bool {3424 \\export fn entry() bool {
2706 \\ var x: i32 = 1;3425 \\ var x: i32 = 1;
2707 \\ return bar(@ptrCast(&MyType, &x));3426 \\ return bar(@ptrCast(*MyType, &x));
2708 \\}3427 \\}
2709 \\3428 \\
2710 \\fn bar(x: &MyType) bool {3429 \\fn bar(x: *MyType) bool {
2711 \\ return x.blah;3430 \\ return x.blah;
2712 \\}3431 \\}
2713 ,3432 ,
2714 ".tmp_source.zig:9:13: error: type '&MyType' does not support field access");3433 ".tmp_source.zig:9:13: error: type '*MyType' does not support field access",
3434 );
27153435
2716 cases.add("carriage return special case",3436 cases.add(
3437 "carriage return special case",
2717 "fn test() bool {\r\n" ++3438 "fn test() bool {\r\n" ++
2718 " true\r\n" ++3439 " true\r\n" ++
2719 "}\r\n"3440 "}\r\n",
2720 ,3441 ".tmp_source.zig:1:17: error: invalid carriage return, only '\\n' line endings are supported",
2721 ".tmp_source.zig:1:17: error: invalid carriage return, only '\\n' line endings are supported");3442 );
27223443
2723 cases.add("non-printable invalid character",3444 cases.add(
2724 "\xff\xfe" ++3445 "non-printable invalid character",
2725 \\fn test() bool {\r3446 "\xff\xfe" ++
2726 \\ true\r3447 \\fn test() bool {\r
2727 \\}3448 \\ true\r
2728 ,3449 \\}
2729 ".tmp_source.zig:1:1: error: invalid character: '\\xff'");3450 ,
3451 ".tmp_source.zig:1:1: error: invalid character: '\\xff'",
3452 );
27303453
2731 cases.add("non-printable invalid character with escape alternative",3454 cases.add(
3455 "non-printable invalid character with escape alternative",
2732 "fn test() bool {\n" ++3456 "fn test() bool {\n" ++
2733 "\ttrue\n" ++3457 "\ttrue\n" ++
2734 "}\n"3458 "}\n",
2735 ,3459 ".tmp_source.zig:2:1: error: invalid character: '\\t'",
2736 ".tmp_source.zig:2:1: error: invalid character: '\\t'");3460 );
27373461
2738 cases.add("@ArgType given non function parameter",3462 cases.add(
3463 "@ArgType given non function parameter",
2739 \\comptime {3464 \\comptime {
2740 \\ _ = @ArgType(i32, 3);3465 \\ _ = @ArgType(i32, 3);
2741 \\}3466 \\}
2742 ,3467 ,
2743 ".tmp_source.zig:2:18: error: expected function, found 'i32'");3468 ".tmp_source.zig:2:18: error: expected function, found 'i32'",
3469 );
27443470
2745 cases.add("@ArgType arg index out of bounds",3471 cases.add(
3472 "@ArgType arg index out of bounds",
2746 \\comptime {3473 \\comptime {
2747 \\ _ = @ArgType(@typeOf(add), 2);3474 \\ _ = @ArgType(@typeOf(add), 2);
2748 \\}3475 \\}
2749 \\fn add(a: i32, b: i32) i32 { return a + b; }3476 \\fn add(a: i32, b: i32) i32 { return a + b; }
2750 ,3477 ,
2751 ".tmp_source.zig:2:32: error: arg index 2 out of bounds; 'fn(i32, i32) i32' has 2 arguments");3478 ".tmp_source.zig:2:32: error: arg index 2 out of bounds; 'fn(i32, i32) i32' has 2 arguments",
3479 );
27523480
2753 cases.add("@memberType on unsupported type",3481 cases.add(
3482 "@memberType on unsupported type",
2754 \\comptime {3483 \\comptime {
2755 \\ _ = @memberType(i32, 0);3484 \\ _ = @memberType(i32, 0);
2756 \\}3485 \\}
2757 ,3486 ,
2758 ".tmp_source.zig:2:21: error: type 'i32' does not support @memberType");3487 ".tmp_source.zig:2:21: error: type 'i32' does not support @memberType",
3488 );
27593489
2760 cases.add("@memberType on enum",3490 cases.add(
3491 "@memberType on enum",
2761 \\comptime {3492 \\comptime {
2762 \\ _ = @memberType(Foo, 0);3493 \\ _ = @memberType(Foo, 0);
2763 \\}3494 \\}
2764 \\const Foo = enum {A,};3495 \\const Foo = enum {A,};
2765 ,3496 ,
2766 ".tmp_source.zig:2:21: error: type 'Foo' does not support @memberType");3497 ".tmp_source.zig:2:21: error: type 'Foo' does not support @memberType",
3498 );
27673499
2768 cases.add("@memberType struct out of bounds",3500 cases.add(
3501 "@memberType struct out of bounds",
2769 \\comptime {3502 \\comptime {
2770 \\ _ = @memberType(Foo, 0);3503 \\ _ = @memberType(Foo, 0);
2771 \\}3504 \\}
2772 \\const Foo = struct {};3505 \\const Foo = struct {};
2773 ,3506 ,
2774 ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members");3507 ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members",
3508 );
27753509
2776 cases.add("@memberType union out of bounds",3510 cases.add(
3511 "@memberType union out of bounds",
2777 \\comptime {3512 \\comptime {
2778 \\ _ = @memberType(Foo, 1);3513 \\ _ = @memberType(Foo, 1);
2779 \\}3514 \\}
2780 \\const Foo = union {A: void,};3515 \\const Foo = union {A: void,};
2781 ,3516 ,
2782 ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members");3517 ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members",
3518 );
27833519
2784 cases.add("@memberName on unsupported type",3520 cases.add(
3521 "@memberName on unsupported type",
2785 \\comptime {3522 \\comptime {
2786 \\ _ = @memberName(i32, 0);3523 \\ _ = @memberName(i32, 0);
2787 \\}3524 \\}
2788 ,3525 ,
2789 ".tmp_source.zig:2:21: error: type 'i32' does not support @memberName");3526 ".tmp_source.zig:2:21: error: type 'i32' does not support @memberName",
3527 );
27903528
2791 cases.add("@memberName struct out of bounds",3529 cases.add(
3530 "@memberName struct out of bounds",
2792 \\comptime {3531 \\comptime {
2793 \\ _ = @memberName(Foo, 0);3532 \\ _ = @memberName(Foo, 0);
2794 \\}3533 \\}
2795 \\const Foo = struct {};3534 \\const Foo = struct {};
2796 ,3535 ,
2797 ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members");3536 ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members",
3537 );
27983538
2799 cases.add("@memberName enum out of bounds",3539 cases.add(
3540 "@memberName enum out of bounds",
2800 \\comptime {3541 \\comptime {
2801 \\ _ = @memberName(Foo, 1);3542 \\ _ = @memberName(Foo, 1);
2802 \\}3543 \\}
2803 \\const Foo = enum {A,};3544 \\const Foo = enum {A,};
2804 ,3545 ,
2805 ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members");3546 ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members",
3547 );
28063548
2807 cases.add("@memberName union out of bounds",3549 cases.add(
3550 "@memberName union out of bounds",
2808 \\comptime {3551 \\comptime {
2809 \\ _ = @memberName(Foo, 1);3552 \\ _ = @memberName(Foo, 1);
2810 \\}3553 \\}
2811 \\const Foo = union {A:i32,};3554 \\const Foo = union {A:i32,};
2812 ,3555 ,
2813 ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members");3556 ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members",
3557 );
28143558
2815 cases.add("calling var args extern function, passing array instead of pointer",3559 cases.add(
3560 "calling var args extern function, passing array instead of pointer",
2816 \\export fn entry() void {3561 \\export fn entry() void {
2817 \\ foo("hello");3562 \\ foo("hello",);
2818 \\}3563 \\}
2819 \\pub extern fn foo(format: &const u8, ...) void;3564 \\pub extern fn foo(format: *const u8, ...) void;
2820 ,3565 ,
2821 ".tmp_source.zig:2:9: error: expected type '&const u8', found '[5]u8'");3566 ".tmp_source.zig:2:9: error: expected type '*const u8', found '[5]u8'",
3567 );
28223568
2823 cases.add("constant inside comptime function has compile error",3569 cases.add(
3570 "constant inside comptime function has compile error",
2824 \\const ContextAllocator = MemoryPool(usize);3571 \\const ContextAllocator = MemoryPool(usize);
2825 \\3572 \\
2826 \\pub fn MemoryPool(comptime T: type) type {3573 \\pub fn MemoryPool(comptime T: type) type {
2827 \\ const free_list_t = @compileError("aoeu");3574 \\ const free_list_t = @compileError("aoeu",);
2828 \\3575 \\
2829 \\ return struct {3576 \\ return struct {
2830 \\ free_list: free_list_t,3577 \\ free_list: free_list_t,
...@@ -2837,9 +3584,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2837,9 +3584,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2837 ,3584 ,
2838 ".tmp_source.zig:4:25: error: aoeu",3585 ".tmp_source.zig:4:25: error: aoeu",
2839 ".tmp_source.zig:1:36: note: called from here",3586 ".tmp_source.zig:1:36: note: called from here",
2840 ".tmp_source.zig:12:20: note: referenced here");3587 ".tmp_source.zig:12:20: note: referenced here",
3588 );
28413589
2842 cases.add("specify enum tag type that is too small",3590 cases.add(
3591 "specify enum tag type that is too small",
2843 \\const Small = enum (u2) {3592 \\const Small = enum (u2) {
2844 \\ One,3593 \\ One,
2845 \\ Two,3594 \\ Two,
...@@ -2852,9 +3601,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2852,9 +3601,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2852 \\ var x = Small.One;3601 \\ var x = Small.One;
2853 \\}3602 \\}
2854 ,3603 ,
2855 ".tmp_source.zig:1:20: error: 'u2' too small to hold all bits; must be at least 'u3'");3604 ".tmp_source.zig:1:20: error: 'u2' too small to hold all bits; must be at least 'u3'",
3605 );
28563606
2857 cases.add("specify non-integer enum tag type",3607 cases.add(
3608 "specify non-integer enum tag type",
2858 \\const Small = enum (f32) {3609 \\const Small = enum (f32) {
2859 \\ One,3610 \\ One,
2860 \\ Two,3611 \\ Two,
...@@ -2865,9 +3616,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2865,9 +3616,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2865 \\ var x = Small.One;3616 \\ var x = Small.One;
2866 \\}3617 \\}
2867 ,3618 ,
2868 ".tmp_source.zig:1:20: error: expected integer, found 'f32'");3619 ".tmp_source.zig:1:20: error: expected integer, found 'f32'",
3620 );
28693621
2870 cases.add("implicitly casting enum to tag type",3622 cases.add(
3623 "implicitly casting enum to tag type",
2871 \\const Small = enum(u2) {3624 \\const Small = enum(u2) {
2872 \\ One,3625 \\ One,
2873 \\ Two,3626 \\ Two,
...@@ -2879,9 +3632,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2879,9 +3632,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2879 \\ var x: u2 = Small.Two;3632 \\ var x: u2 = Small.Two;
2880 \\}3633 \\}
2881 ,3634 ,
2882 ".tmp_source.zig:9:22: error: expected type 'u2', found 'Small'");3635 ".tmp_source.zig:9:22: error: expected type 'u2', found 'Small'",
3636 );
28833637
2884 cases.add("explicitly casting enum to non tag type",3638 cases.add(
3639 "explicitly casting enum to non tag type",
2885 \\const Small = enum(u2) {3640 \\const Small = enum(u2) {
2886 \\ One,3641 \\ One,
2887 \\ Two,3642 \\ Two,
...@@ -2893,9 +3648,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2893,9 +3648,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2893 \\ var x = u3(Small.Two);3648 \\ var x = u3(Small.Two);
2894 \\}3649 \\}
2895 ,3650 ,
2896 ".tmp_source.zig:9:15: error: enum to integer cast to 'u3' instead of its tag type, 'u2'");3651 ".tmp_source.zig:9:15: error: enum to integer cast to 'u3' instead of its tag type, 'u2'",
3652 );
28973653
2898 cases.add("explicitly casting non tag type to enum",3654 cases.add(
3655 "explicitly casting non tag type to enum",
2899 \\const Small = enum(u2) {3656 \\const Small = enum(u2) {
2900 \\ One,3657 \\ One,
2901 \\ Two,3658 \\ Two,
...@@ -2908,9 +3665,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2908,9 +3665,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2908 \\ var x = Small(y);3665 \\ var x = Small(y);
2909 \\}3666 \\}
2910 ,3667 ,
2911 ".tmp_source.zig:10:18: error: integer to enum cast from 'u3' instead of its tag type, 'u2'");3668 ".tmp_source.zig:10:18: error: integer to enum cast from 'u3' instead of its tag type, 'u2'",
3669 );
29123670
2913 cases.add("non unsigned integer enum tag type",3671 cases.add(
3672 "non unsigned integer enum tag type",
2914 \\const Small = enum(i2) {3673 \\const Small = enum(i2) {
2915 \\ One,3674 \\ One,
2916 \\ Two,3675 \\ Two,
...@@ -2922,9 +3681,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2922,9 +3681,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2922 \\ var y = Small.Two;3681 \\ var y = Small.Two;
2923 \\}3682 \\}
2924 ,3683 ,
2925 ".tmp_source.zig:1:19: error: expected unsigned integer, found 'i2'");3684 ".tmp_source.zig:1:19: error: expected unsigned integer, found 'i2'",
3685 );
29263686
2927 cases.add("struct fields with value assignments",3687 cases.add(
3688 "struct fields with value assignments",
2928 \\const MultipleChoice = struct {3689 \\const MultipleChoice = struct {
2929 \\ A: i32 = 20,3690 \\ A: i32 = 20,
2930 \\};3691 \\};
...@@ -2932,9 +3693,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2932,9 +3693,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2932 \\ var x: MultipleChoice = undefined;3693 \\ var x: MultipleChoice = undefined;
2933 \\}3694 \\}
2934 ,3695 ,
2935 ".tmp_source.zig:2:14: error: enums, not structs, support field assignment");3696 ".tmp_source.zig:2:14: error: enums, not structs, support field assignment",
3697 );
29363698
2937 cases.add("union fields with value assignments",3699 cases.add(
3700 "union fields with value assignments",
2938 \\const MultipleChoice = union {3701 \\const MultipleChoice = union {
2939 \\ A: i32 = 20,3702 \\ A: i32 = 20,
2940 \\};3703 \\};
...@@ -2943,25 +3706,31 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2943,25 +3706,31 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2943 \\}3706 \\}
2944 ,3707 ,
2945 ".tmp_source.zig:2:14: error: non-enum union field assignment",3708 ".tmp_source.zig:2:14: error: non-enum union field assignment",
2946 ".tmp_source.zig:1:24: note: consider 'union(enum)' here");3709 ".tmp_source.zig:1:24: note: consider 'union(enum)' here",
3710 );
29473711
2948 cases.add("enum with 0 fields",3712 cases.add(
3713 "enum with 0 fields",
2949 \\const Foo = enum {};3714 \\const Foo = enum {};
2950 \\export fn entry() usize {3715 \\export fn entry() usize {
2951 \\ return @sizeOf(Foo);3716 \\ return @sizeOf(Foo);
2952 \\}3717 \\}
2953 ,3718 ,
2954 ".tmp_source.zig:1:13: error: enums must have 1 or more fields");3719 ".tmp_source.zig:1:13: error: enums must have 1 or more fields",
3720 );
29553721
2956 cases.add("union with 0 fields",3722 cases.add(
3723 "union with 0 fields",
2957 \\const Foo = union {};3724 \\const Foo = union {};
2958 \\export fn entry() usize {3725 \\export fn entry() usize {
2959 \\ return @sizeOf(Foo);3726 \\ return @sizeOf(Foo);
2960 \\}3727 \\}
2961 ,3728 ,
2962 ".tmp_source.zig:1:13: error: unions must have 1 or more fields");3729 ".tmp_source.zig:1:13: error: unions must have 1 or more fields",
3730 );
29633731
2964 cases.add("enum value already taken",3732 cases.add(
3733 "enum value already taken",
2965 \\const MultipleChoice = enum(u32) {3734 \\const MultipleChoice = enum(u32) {
2966 \\ A = 20,3735 \\ A = 20,
2967 \\ B = 40,3736 \\ B = 40,
...@@ -2974,9 +3743,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2974,9 +3743,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2974 \\}3743 \\}
2975 ,3744 ,
2976 ".tmp_source.zig:6:9: error: enum tag value 60 already taken",3745 ".tmp_source.zig:6:9: error: enum tag value 60 already taken",
2977 ".tmp_source.zig:4:9: note: other occurrence here");3746 ".tmp_source.zig:4:9: note: other occurrence here",
3747 );
29783748
2979 cases.add("union with specified enum omits field",3749 cases.add(
3750 "union with specified enum omits field",
2980 \\const Letter = enum {3751 \\const Letter = enum {
2981 \\ A,3752 \\ A,
2982 \\ B,3753 \\ B,
...@@ -2991,9 +3762,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -2991,9 +3762,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
2991 \\}3762 \\}
2992 ,3763 ,
2993 ".tmp_source.zig:6:17: error: enum field missing: 'C'",3764 ".tmp_source.zig:6:17: error: enum field missing: 'C'",
2994 ".tmp_source.zig:4:5: note: declared here");3765 ".tmp_source.zig:4:5: note: declared here",
3766 );
29953767
2996 cases.add("@TagType when union has no attached enum",3768 cases.add(
3769 "@TagType when union has no attached enum",
2997 \\const Foo = union {3770 \\const Foo = union {
2998 \\ A: i32,3771 \\ A: i32,
2999 \\};3772 \\};
...@@ -3002,9 +3775,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3002,9 +3775,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3002 \\}3775 \\}
3003 ,3776 ,
3004 ".tmp_source.zig:5:24: error: union 'Foo' has no tag",3777 ".tmp_source.zig:5:24: error: union 'Foo' has no tag",
3005 ".tmp_source.zig:1:13: note: consider 'union(enum)' here");3778 ".tmp_source.zig:1:13: note: consider 'union(enum)' here",
3779 );
30063780
3007 cases.add("non-integer tag type to automatic union enum",3781 cases.add(
3782 "non-integer tag type to automatic union enum",
3008 \\const Foo = union(enum(f32)) {3783 \\const Foo = union(enum(f32)) {
3009 \\ A: i32,3784 \\ A: i32,
3010 \\};3785 \\};
...@@ -3012,9 +3787,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3012,9 +3787,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3012 \\ const x = @TagType(Foo);3787 \\ const x = @TagType(Foo);
3013 \\}3788 \\}
3014 ,3789 ,
3015 ".tmp_source.zig:1:23: error: expected integer tag type, found 'f32'");3790 ".tmp_source.zig:1:23: error: expected integer tag type, found 'f32'",
3791 );
30163792
3017 cases.add("non-enum tag type passed to union",3793 cases.add(
3794 "non-enum tag type passed to union",
3018 \\const Foo = union(u32) {3795 \\const Foo = union(u32) {
3019 \\ A: i32,3796 \\ A: i32,
3020 \\};3797 \\};
...@@ -3022,9 +3799,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3022,9 +3799,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3022 \\ const x = @TagType(Foo);3799 \\ const x = @TagType(Foo);
3023 \\}3800 \\}
3024 ,3801 ,
3025 ".tmp_source.zig:1:18: error: expected enum tag type, found 'u32'");3802 ".tmp_source.zig:1:18: error: expected enum tag type, found 'u32'",
3803 );
30263804
3027 cases.add("union auto-enum value already taken",3805 cases.add(
3806 "union auto-enum value already taken",
3028 \\const MultipleChoice = union(enum(u32)) {3807 \\const MultipleChoice = union(enum(u32)) {
3029 \\ A = 20,3808 \\ A = 20,
3030 \\ B = 40,3809 \\ B = 40,
...@@ -3037,9 +3816,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3037,9 +3816,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3037 \\}3816 \\}
3038 ,3817 ,
3039 ".tmp_source.zig:6:9: error: enum tag value 60 already taken",3818 ".tmp_source.zig:6:9: error: enum tag value 60 already taken",
3040 ".tmp_source.zig:4:9: note: other occurrence here");3819 ".tmp_source.zig:4:9: note: other occurrence here",
3820 );
30413821
3042 cases.add("union enum field does not match enum",3822 cases.add(
3823 "union enum field does not match enum",
3043 \\const Letter = enum {3824 \\const Letter = enum {
3044 \\ A,3825 \\ A,
3045 \\ B,3826 \\ B,
...@@ -3056,9 +3837,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3056,9 +3837,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3056 \\}3837 \\}
3057 ,3838 ,
3058 ".tmp_source.zig:10:5: error: enum field not found: 'D'",3839 ".tmp_source.zig:10:5: error: enum field not found: 'D'",
3059 ".tmp_source.zig:1:16: note: enum declared here");3840 ".tmp_source.zig:1:16: note: enum declared here",
3841 );
30603842
3061 cases.add("field type supplied in an enum",3843 cases.add(
3844 "field type supplied in an enum",
3062 \\const Letter = enum {3845 \\const Letter = enum {
3063 \\ A: void,3846 \\ A: void,
3064 \\ B,3847 \\ B,
...@@ -3069,9 +3852,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3069,9 +3852,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3069 \\}3852 \\}
3070 ,3853 ,
3071 ".tmp_source.zig:2:8: error: structs and unions, not enums, support field types",3854 ".tmp_source.zig:2:8: error: structs and unions, not enums, support field types",
3072 ".tmp_source.zig:1:16: note: consider 'union(enum)' here");3855 ".tmp_source.zig:1:16: note: consider 'union(enum)' here",
3856 );
30733857
3074 cases.add("struct field missing type",3858 cases.add(
3859 "struct field missing type",
3075 \\const Letter = struct {3860 \\const Letter = struct {
3076 \\ A,3861 \\ A,
3077 \\};3862 \\};
...@@ -3079,9 +3864,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3079,9 +3864,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3079 \\ var a = Letter { .A = {} };3864 \\ var a = Letter { .A = {} };
3080 \\}3865 \\}
3081 ,3866 ,
3082 ".tmp_source.zig:2:5: error: struct field missing type");3867 ".tmp_source.zig:2:5: error: struct field missing type",
3868 );
30833869
3084 cases.add("extern union field missing type",3870 cases.add(
3871 "extern union field missing type",
3085 \\const Letter = extern union {3872 \\const Letter = extern union {
3086 \\ A,3873 \\ A,
3087 \\};3874 \\};
...@@ -3089,9 +3876,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3089,9 +3876,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3089 \\ var a = Letter { .A = {} };3876 \\ var a = Letter { .A = {} };
3090 \\}3877 \\}
3091 ,3878 ,
3092 ".tmp_source.zig:2:5: error: union field missing type");3879 ".tmp_source.zig:2:5: error: union field missing type",
3880 );
30933881
3094 cases.add("extern union given enum tag type",3882 cases.add(
3883 "extern union given enum tag type",
3095 \\const Letter = enum {3884 \\const Letter = enum {
3096 \\ A,3885 \\ A,
3097 \\ B,3886 \\ B,
...@@ -3106,9 +3895,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3106,9 +3895,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3106 \\ var a = Payload { .A = 1234 };3895 \\ var a = Payload { .A = 1234 };
3107 \\}3896 \\}
3108 ,3897 ,
3109 ".tmp_source.zig:6:29: error: extern union does not support enum tag type");3898 ".tmp_source.zig:6:29: error: extern union does not support enum tag type",
3899 );
31103900
3111 cases.add("packed union given enum tag type",3901 cases.add(
3902 "packed union given enum tag type",
3112 \\const Letter = enum {3903 \\const Letter = enum {
3113 \\ A,3904 \\ A,
3114 \\ B,3905 \\ B,
...@@ -3123,9 +3914,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3123,9 +3914,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3123 \\ var a = Payload { .A = 1234 };3914 \\ var a = Payload { .A = 1234 };
3124 \\}3915 \\}
3125 ,3916 ,
3126 ".tmp_source.zig:6:29: error: packed union does not support enum tag type");3917 ".tmp_source.zig:6:29: error: packed union does not support enum tag type",
3918 );
31273919
3128 cases.add("switch on union with no attached enum",3920 cases.add(
3921 "switch on union with no attached enum",
3129 \\const Payload = union {3922 \\const Payload = union {
3130 \\ A: i32,3923 \\ A: i32,
3131 \\ B: f64,3924 \\ B: f64,
...@@ -3135,7 +3928,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3135,7 +3928,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3135 \\ const a = Payload { .A = 1234 };3928 \\ const a = Payload { .A = 1234 };
3136 \\ foo(a);3929 \\ foo(a);
3137 \\}3930 \\}
3138 \\fn foo(a: &const Payload) void {3931 \\fn foo(a: *const Payload) void {
3139 \\ switch (a.*) {3932 \\ switch (a.*) {
3140 \\ Payload.A => {},3933 \\ Payload.A => {},
3141 \\ else => unreachable,3934 \\ else => unreachable,
...@@ -3143,9 +3936,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3143,9 +3936,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3143 \\}3936 \\}
3144 ,3937 ,
3145 ".tmp_source.zig:11:14: error: switch on union which has no attached enum",3938 ".tmp_source.zig:11:14: error: switch on union which has no attached enum",
3146 ".tmp_source.zig:1:17: note: consider 'union(enum)' here");3939 ".tmp_source.zig:1:17: note: consider 'union(enum)' here",
3940 );
31473941
3148 cases.add("enum in field count range but not matching tag",3942 cases.add(
3943 "enum in field count range but not matching tag",
3149 \\const Foo = enum(u32) {3944 \\const Foo = enum(u32) {
3150 \\ A = 10,3945 \\ A = 10,
3151 \\ B = 11,3946 \\ B = 11,
...@@ -3155,9 +3950,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3155,9 +3950,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3155 \\}3950 \\}
3156 ,3951 ,
3157 ".tmp_source.zig:6:16: error: enum 'Foo' has no tag matching integer value 0",3952 ".tmp_source.zig:6:16: error: enum 'Foo' has no tag matching integer value 0",
3158 ".tmp_source.zig:1:13: note: 'Foo' declared here");3953 ".tmp_source.zig:1:13: note: 'Foo' declared here",
3954 );
31593955
3160 cases.add("comptime cast enum to union but field has payload",3956 cases.add(
3957 "comptime cast enum to union but field has payload",
3161 \\const Letter = enum { A, B, C };3958 \\const Letter = enum { A, B, C };
3162 \\const Value = union(Letter) {3959 \\const Value = union(Letter) {
3163 \\ A: i32,3960 \\ A: i32,
...@@ -3169,9 +3966,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3169,9 +3966,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3169 \\}3966 \\}
3170 ,3967 ,
3171 ".tmp_source.zig:8:26: error: cast to union 'Value' must initialize 'i32' field 'A'",3968 ".tmp_source.zig:8:26: error: cast to union 'Value' must initialize 'i32' field 'A'",
3172 ".tmp_source.zig:3:5: note: field 'A' declared here");3969 ".tmp_source.zig:3:5: note: field 'A' declared here",
3970 );
31733971
3174 cases.add("runtime cast to union which has non-void fields",3972 cases.add(
3973 "runtime cast to union which has non-void fields",
3175 \\const Letter = enum { A, B, C };3974 \\const Letter = enum { A, B, C };
3176 \\const Value = union(Letter) {3975 \\const Value = union(Letter) {
3177 \\ A: i32,3976 \\ A: i32,
...@@ -3186,9 +3985,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3186,9 +3985,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3186 \\}3985 \\}
3187 ,3986 ,
3188 ".tmp_source.zig:11:20: error: runtime cast to union 'Value' which has non-void fields",3987 ".tmp_source.zig:11:20: error: runtime cast to union 'Value' which has non-void fields",
3189 ".tmp_source.zig:3:5: note: field 'A' has type 'i32'");3988 ".tmp_source.zig:3:5: note: field 'A' has type 'i32'",
3989 );
31903990
3191 cases.add("self-referencing function pointer field",3991 cases.add(
3992 "self-referencing function pointer field",
3192 \\const S = struct {3993 \\const S = struct {
3193 \\ f: fn(_: S) void,3994 \\ f: fn(_: S) void,
3194 \\};3995 \\};
...@@ -3198,19 +3999,23 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3198,19 +3999,23 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3198 \\ var _ = S { .f = f };3999 \\ var _ = S { .f = f };
3199 \\}4000 \\}
3200 ,4001 ,
3201 ".tmp_source.zig:4:9: error: type 'S' is not copyable; cannot pass by value");4002 ".tmp_source.zig:4:9: error: type 'S' is not copyable; cannot pass by value",
4003 );
32024004
3203 cases.add("taking offset of void field in struct",4005 cases.add(
4006 "taking offset of void field in struct",
3204 \\const Empty = struct {4007 \\const Empty = struct {
3205 \\ val: void,4008 \\ val: void,
3206 \\};4009 \\};
3207 \\export fn foo() void {4010 \\export fn foo() void {
3208 \\ const fieldOffset = @offsetOf(Empty, "val");4011 \\ const fieldOffset = @offsetOf(Empty, "val",);
3209 \\}4012 \\}
3210 ,4013 ,
3211 ".tmp_source.zig:5:42: error: zero-bit field 'val' in struct 'Empty' has no offset");4014 ".tmp_source.zig:5:42: error: zero-bit field 'val' in struct 'Empty' has no offset",
4015 );
32124016
3213 cases.add("invalid union field access in comptime",4017 cases.add(
4018 "invalid union field access in comptime",
3214 \\const Foo = union {4019 \\const Foo = union {
3215 \\ Bar: u8,4020 \\ Bar: u8,
3216 \\ Baz: void,4021 \\ Baz: void,
...@@ -3220,21 +4025,26 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {...@@ -3220,21 +4025,26 @@ pub fn addCases(cases: &tests.CompileErrorContext) void {
3220 \\ const bar_val = foo.Bar;4025 \\ const bar_val = foo.Bar;
3221 \\}4026 \\}
3222 ,4027 ,
3223 ".tmp_source.zig:7:24: error: accessing union field 'Bar' while field 'Baz' is set");4028 ".tmp_source.zig:7:24: error: accessing union field 'Bar' while field 'Baz' is set",
4029 );
32244030
3225 cases.add("getting return type of generic function",4031 cases.add(
4032 "getting return type of generic function",
3226 \\fn generic(a: var) void {}4033 \\fn generic(a: var) void {}
3227 \\comptime {4034 \\comptime {
3228 \\ _ = @typeOf(generic).ReturnType;4035 \\ _ = @typeOf(generic).ReturnType;
3229 \\}4036 \\}
3230 ,4037 ,
3231 ".tmp_source.zig:3:25: error: ReturnType has not been resolved because 'fn(var)var' is generic");4038 ".tmp_source.zig:3:25: error: ReturnType has not been resolved because 'fn(var)var' is generic",
4039 );
32324040
3233 cases.add("getting @ArgType of generic function",4041 cases.add(
4042 "getting @ArgType of generic function",
3234 \\fn generic(a: var) void {}4043 \\fn generic(a: var) void {}
3235 \\comptime {4044 \\comptime {
3236 \\ _ = @ArgType(@typeOf(generic), 0);4045 \\ _ = @ArgType(@typeOf(generic), 0);
3237 \\}4046 \\}
3238 ,4047 ,
3239 ".tmp_source.zig:3:36: error: @ArgType could not resolve the type of arg 0 because 'fn(var)var' is generic");4048 ".tmp_source.zig:3:36: error: @ArgType could not resolve the type of arg 0 because 'fn(var)var' is generic",
4049 );
3240}4050}
test/gen_h.zig+3-4
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const tests = @import("tests.zig");1const tests = @import("tests.zig");
22
3pub fn addCases(cases: &tests.GenHContext) void {3pub fn addCases(cases: *tests.GenHContext) void {
4 cases.add("declare enum",4 cases.add("declare enum",
5 \\const Foo = extern enum { A, B, C };5 \\const Foo = extern enum { A, B, C };
6 \\export fn entry(foo: Foo) void { }6 \\export fn entry(foo: Foo) void { }
...@@ -54,7 +54,7 @@ pub fn addCases(cases: &tests.GenHContext) void {...@@ -54,7 +54,7 @@ pub fn addCases(cases: &tests.GenHContext) void {
54 cases.add("declare opaque type",54 cases.add("declare opaque type",
55 \\export const Foo = @OpaqueType();55 \\export const Foo = @OpaqueType();
56 \\56 \\
57 \\export fn entry(foo: ?&Foo) void { }57 \\export fn entry(foo: ?*Foo) void { }
58 ,58 ,
59 \\struct Foo;59 \\struct Foo;
60 \\60 \\
...@@ -64,7 +64,7 @@ pub fn addCases(cases: &tests.GenHContext) void {...@@ -64,7 +64,7 @@ pub fn addCases(cases: &tests.GenHContext) void {
64 cases.add("array field-type",64 cases.add("array field-type",
65 \\const Foo = extern struct {65 \\const Foo = extern struct {
66 \\ A: [2]i32,66 \\ A: [2]i32,
67 \\ B: [4]&u32,67 \\ B: [4]*u32,
68 \\};68 \\};
69 \\export fn entry(foo: Foo, bar: [3]u8) void { }69 \\export fn entry(foo: Foo, bar: [3]u8) void { }
70 ,70 ,
...@@ -76,5 +76,4 @@ pub fn addCases(cases: &tests.GenHContext) void {...@@ -76,5 +76,4 @@ pub fn addCases(cases: &tests.GenHContext) void {
76 \\TEST_EXPORT void entry(struct Foo foo, uint8_t bar[]);76 \\TEST_EXPORT void entry(struct Foo foo, uint8_t bar[]);
77 \\77 \\
78 );78 );
79
80}79}
test/runtime_safety.zig+24-24
...@@ -1,8 +1,8 @@...@@ -1,8 +1,8 @@
1const tests = @import("tests.zig");1const tests = @import("tests.zig");
22
3pub fn addCases(cases: &tests.CompareOutputContext) void {3pub fn addCases(cases: *tests.CompareOutputContext) void {
4 cases.addRuntimeSafety("calling panic",4 cases.addRuntimeSafety("calling panic",
5 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {5 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
6 \\ @import("std").os.exit(126);6 \\ @import("std").os.exit(126);
7 \\}7 \\}
8 \\pub fn main() void {8 \\pub fn main() void {
...@@ -11,7 +11,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -11,7 +11,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
11 );11 );
1212
13 cases.addRuntimeSafety("out of bounds slice access",13 cases.addRuntimeSafety("out of bounds slice access",
14 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {14 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
15 \\ @import("std").os.exit(126);15 \\ @import("std").os.exit(126);
16 \\}16 \\}
17 \\pub fn main() void {17 \\pub fn main() void {
...@@ -25,7 +25,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -25,7 +25,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
25 );25 );
2626
27 cases.addRuntimeSafety("integer addition overflow",27 cases.addRuntimeSafety("integer addition overflow",
28 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {28 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
29 \\ @import("std").os.exit(126);29 \\ @import("std").os.exit(126);
30 \\}30 \\}
31 \\pub fn main() !void {31 \\pub fn main() !void {
...@@ -38,7 +38,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -38,7 +38,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
38 );38 );
3939
40 cases.addRuntimeSafety("integer subtraction overflow",40 cases.addRuntimeSafety("integer subtraction overflow",
41 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {41 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
42 \\ @import("std").os.exit(126);42 \\ @import("std").os.exit(126);
43 \\}43 \\}
44 \\pub fn main() !void {44 \\pub fn main() !void {
...@@ -51,7 +51,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -51,7 +51,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
51 );51 );
5252
53 cases.addRuntimeSafety("integer multiplication overflow",53 cases.addRuntimeSafety("integer multiplication overflow",
54 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {54 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
55 \\ @import("std").os.exit(126);55 \\ @import("std").os.exit(126);
56 \\}56 \\}
57 \\pub fn main() !void {57 \\pub fn main() !void {
...@@ -64,7 +64,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -64,7 +64,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
64 );64 );
6565
66 cases.addRuntimeSafety("integer negation overflow",66 cases.addRuntimeSafety("integer negation overflow",
67 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {67 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
68 \\ @import("std").os.exit(126);68 \\ @import("std").os.exit(126);
69 \\}69 \\}
70 \\pub fn main() !void {70 \\pub fn main() !void {
...@@ -77,7 +77,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -77,7 +77,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
77 );77 );
7878
79 cases.addRuntimeSafety("signed integer division overflow",79 cases.addRuntimeSafety("signed integer division overflow",
80 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {80 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
81 \\ @import("std").os.exit(126);81 \\ @import("std").os.exit(126);
82 \\}82 \\}
83 \\pub fn main() !void {83 \\pub fn main() !void {
...@@ -90,7 +90,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -90,7 +90,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
90 );90 );
9191
92 cases.addRuntimeSafety("signed shift left overflow",92 cases.addRuntimeSafety("signed shift left overflow",
93 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {93 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
94 \\ @import("std").os.exit(126);94 \\ @import("std").os.exit(126);
95 \\}95 \\}
96 \\pub fn main() !void {96 \\pub fn main() !void {
...@@ -103,7 +103,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -103,7 +103,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
103 );103 );
104104
105 cases.addRuntimeSafety("unsigned shift left overflow",105 cases.addRuntimeSafety("unsigned shift left overflow",
106 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {106 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
107 \\ @import("std").os.exit(126);107 \\ @import("std").os.exit(126);
108 \\}108 \\}
109 \\pub fn main() !void {109 \\pub fn main() !void {
...@@ -116,7 +116,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -116,7 +116,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
116 );116 );
117117
118 cases.addRuntimeSafety("signed shift right overflow",118 cases.addRuntimeSafety("signed shift right overflow",
119 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {119 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
120 \\ @import("std").os.exit(126);120 \\ @import("std").os.exit(126);
121 \\}121 \\}
122 \\pub fn main() !void {122 \\pub fn main() !void {
...@@ -129,7 +129,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -129,7 +129,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
129 );129 );
130130
131 cases.addRuntimeSafety("unsigned shift right overflow",131 cases.addRuntimeSafety("unsigned shift right overflow",
132 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {132 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
133 \\ @import("std").os.exit(126);133 \\ @import("std").os.exit(126);
134 \\}134 \\}
135 \\pub fn main() !void {135 \\pub fn main() !void {
...@@ -142,7 +142,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -142,7 +142,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
142 );142 );
143143
144 cases.addRuntimeSafety("integer division by zero",144 cases.addRuntimeSafety("integer division by zero",
145 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {145 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
146 \\ @import("std").os.exit(126);146 \\ @import("std").os.exit(126);
147 \\}147 \\}
148 \\pub fn main() void {148 \\pub fn main() void {
...@@ -154,7 +154,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -154,7 +154,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
154 );154 );
155155
156 cases.addRuntimeSafety("exact division failure",156 cases.addRuntimeSafety("exact division failure",
157 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {157 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
158 \\ @import("std").os.exit(126);158 \\ @import("std").os.exit(126);
159 \\}159 \\}
160 \\pub fn main() !void {160 \\pub fn main() !void {
...@@ -167,7 +167,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -167,7 +167,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
167 );167 );
168168
169 cases.addRuntimeSafety("cast []u8 to bigger slice of wrong size",169 cases.addRuntimeSafety("cast []u8 to bigger slice of wrong size",
170 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {170 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
171 \\ @import("std").os.exit(126);171 \\ @import("std").os.exit(126);
172 \\}172 \\}
173 \\pub fn main() !void {173 \\pub fn main() !void {
...@@ -180,7 +180,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -180,7 +180,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
180 );180 );
181181
182 cases.addRuntimeSafety("value does not fit in shortening cast",182 cases.addRuntimeSafety("value does not fit in shortening cast",
183 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {183 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
184 \\ @import("std").os.exit(126);184 \\ @import("std").os.exit(126);
185 \\}185 \\}
186 \\pub fn main() !void {186 \\pub fn main() !void {
...@@ -193,7 +193,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -193,7 +193,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
193 );193 );
194194
195 cases.addRuntimeSafety("signed integer not fitting in cast to unsigned integer",195 cases.addRuntimeSafety("signed integer not fitting in cast to unsigned integer",
196 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {196 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
197 \\ @import("std").os.exit(126);197 \\ @import("std").os.exit(126);
198 \\}198 \\}
199 \\pub fn main() !void {199 \\pub fn main() !void {
...@@ -206,7 +206,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -206,7 +206,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
206 );206 );
207207
208 cases.addRuntimeSafety("unwrap error",208 cases.addRuntimeSafety("unwrap error",
209 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {209 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
210 \\ if (@import("std").mem.eql(u8, message, "attempt to unwrap error: Whatever")) {210 \\ if (@import("std").mem.eql(u8, message, "attempt to unwrap error: Whatever")) {
211 \\ @import("std").os.exit(126); // good211 \\ @import("std").os.exit(126); // good
212 \\ }212 \\ }
...@@ -221,7 +221,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -221,7 +221,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
221 );221 );
222222
223 cases.addRuntimeSafety("cast integer to global error and no code matches",223 cases.addRuntimeSafety("cast integer to global error and no code matches",
224 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {224 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
225 \\ @import("std").os.exit(126);225 \\ @import("std").os.exit(126);
226 \\}226 \\}
227 \\pub fn main() void {227 \\pub fn main() void {
...@@ -233,7 +233,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -233,7 +233,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
233 );233 );
234234
235 cases.addRuntimeSafety("cast integer to non-global error set and no match",235 cases.addRuntimeSafety("cast integer to non-global error set and no match",
236 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {236 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
237 \\ @import("std").os.exit(126);237 \\ @import("std").os.exit(126);
238 \\}238 \\}
239 \\const Set1 = error{A, B};239 \\const Set1 = error{A, B};
...@@ -247,7 +247,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -247,7 +247,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
247 );247 );
248248
249 cases.addRuntimeSafety("@alignCast misaligned",249 cases.addRuntimeSafety("@alignCast misaligned",
250 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {250 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
251 \\ @import("std").os.exit(126);251 \\ @import("std").os.exit(126);
252 \\}252 \\}
253 \\pub fn main() !void {253 \\pub fn main() !void {
...@@ -263,7 +263,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -263,7 +263,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
263 );263 );
264264
265 cases.addRuntimeSafety("bad union field access",265 cases.addRuntimeSafety("bad union field access",
266 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {266 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
267 \\ @import("std").os.exit(126);267 \\ @import("std").os.exit(126);
268 \\}268 \\}
269 \\269 \\
...@@ -277,7 +277,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -277,7 +277,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
277 \\ bar(&f);277 \\ bar(&f);
278 \\}278 \\}
279 \\279 \\
280 \\fn bar(f: &Foo) void {280 \\fn bar(f: *Foo) void {
281 \\ f.float = 12.34;281 \\ f.float = 12.34;
282 \\}282 \\}
283 );283 );
...@@ -287,7 +287,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {...@@ -287,7 +287,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void {
287 cases.addRuntimeSafety("error return trace across suspend points",287 cases.addRuntimeSafety("error return trace across suspend points",
288 \\const std = @import("std");288 \\const std = @import("std");
289 \\289 \\
290 \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn {290 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
291 \\ std.os.exit(126);291 \\ std.os.exit(126);
292 \\}292 \\}
293 \\293 \\
test/standalone/brace_expansion/build.zig+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const Builder = @import("std").build.Builder;1const Builder = @import("std").build.Builder;
22
3pub fn build(b: &Builder) void {3pub fn build(b: *Builder) void {
4 const main = b.addTest("main.zig");4 const main = b.addTest("main.zig");
5 main.setBuildMode(b.standardReleaseOptions());5 main.setBuildMode(b.standardReleaseOptions());
66
test/standalone/brace_expansion/main.zig+8-13
...@@ -14,7 +14,7 @@ const Token = union(enum) {...@@ -14,7 +14,7 @@ const Token = union(enum) {
14 Eof,14 Eof,
15};15};
1616
17var global_allocator: &mem.Allocator = undefined;17var global_allocator: *mem.Allocator = undefined;
1818
19fn tokenize(input: []const u8) !ArrayList(Token) {19fn tokenize(input: []const u8) !ArrayList(Token) {
20 const State = enum {20 const State = enum {
...@@ -29,8 +29,7 @@ fn tokenize(input: []const u8) !ArrayList(Token) {...@@ -29,8 +29,7 @@ fn tokenize(input: []const u8) !ArrayList(Token) {
29 for (input) |b, i| {29 for (input) |b, i| {
30 switch (state) {30 switch (state) {
31 State.Start => switch (b) {31 State.Start => switch (b) {
32 'a' ... 'z',32 'a'...'z', 'A'...'Z' => {
33 'A' ... 'Z' => {
34 state = State.Word;33 state = State.Word;
35 tok_begin = i;34 tok_begin = i;
36 },35 },
...@@ -40,11 +39,8 @@ fn tokenize(input: []const u8) !ArrayList(Token) {...@@ -40,11 +39,8 @@ fn tokenize(input: []const u8) !ArrayList(Token) {
40 else => return error.InvalidInput,39 else => return error.InvalidInput,
41 },40 },
42 State.Word => switch (b) {41 State.Word => switch (b) {
43 'a' ... 'z',42 'a'...'z', 'A'...'Z' => {},
44 'A' ... 'Z' => {},43 '{', '}', ',' => {
45 '{',
46 '}',
47 ',' => {
48 try token_list.append(Token{ .Word = input[tok_begin..i] });44 try token_list.append(Token{ .Word = input[tok_begin..i] });
49 switch (b) {45 switch (b) {
50 '{' => try token_list.append(Token.OpenBrace),46 '{' => try token_list.append(Token.OpenBrace),
...@@ -77,7 +73,7 @@ const ParseError = error{...@@ -77,7 +73,7 @@ const ParseError = error{
77 OutOfMemory,73 OutOfMemory,
78};74};
7975
80fn parse(tokens: &const ArrayList(Token), token_index: &usize) ParseError!Node {76fn parse(tokens: *const ArrayList(Token), token_index: *usize) ParseError!Node {
81 const first_token = tokens.items[token_index.*];77 const first_token = tokens.items[token_index.*];
82 token_index.* += 1;78 token_index.* += 1;
8379
...@@ -103,8 +99,7 @@ fn parse(tokens: &const ArrayList(Token), token_index: &usize) ParseError!Node {...@@ -103,8 +99,7 @@ fn parse(tokens: &const ArrayList(Token), token_index: &usize) ParseError!Node {
103 };99 };
104100
105 switch (tokens.items[token_index.*]) {101 switch (tokens.items[token_index.*]) {
106 Token.Word,102 Token.Word, Token.OpenBrace => {
107 Token.OpenBrace => {
108 const pair = try global_allocator.alloc(Node, 2);103 const pair = try global_allocator.alloc(Node, 2);
109 pair[0] = result_node;104 pair[0] = result_node;
110 pair[1] = try parse(tokens, token_index);105 pair[1] = try parse(tokens, token_index);
...@@ -114,7 +109,7 @@ fn parse(tokens: &const ArrayList(Token), token_index: &usize) ParseError!Node {...@@ -114,7 +109,7 @@ fn parse(tokens: &const ArrayList(Token), token_index: &usize) ParseError!Node {
114 }109 }
115}110}
116111
117fn expandString(input: []const u8, output: &Buffer) !void {112fn expandString(input: []const u8, output: *Buffer) !void {
118 const tokens = try tokenize(input);113 const tokens = try tokenize(input);
119 if (tokens.len == 1) {114 if (tokens.len == 1) {
120 return output.resize(0);115 return output.resize(0);
...@@ -144,7 +139,7 @@ fn expandString(input: []const u8, output: &Buffer) !void {...@@ -144,7 +139,7 @@ fn expandString(input: []const u8, output: &Buffer) !void {
144139
145const ExpandNodeError = error{OutOfMemory};140const ExpandNodeError = error{OutOfMemory};
146141
147fn expandNode(node: &const Node, output: &ArrayList(Buffer)) ExpandNodeError!void {142fn expandNode(node: *const Node, output: *ArrayList(Buffer)) ExpandNodeError!void {
148 assert(output.len == 0);143 assert(output.len == 0);
149 switch (node.*) {144 switch (node.*) {
150 Node.Scalar => |scalar| {145 Node.Scalar => |scalar| {
test/standalone/issue_339/build.zig+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const Builder = @import("std").build.Builder;1const Builder = @import("std").build.Builder;
22
3pub fn build(b: &Builder) void {3pub fn build(b: *Builder) void {
4 const obj = b.addObject("test", "test.zig");4 const obj = b.addObject("test", "test.zig");
55
6 const test_step = b.step("test", "Test the program");6 const test_step = b.step("test", "Test the program");
test/standalone/issue_339/test.zig+4-1
...@@ -1,5 +1,8 @@...@@ -1,5 +1,8 @@
1const StackTrace = @import("builtin").StackTrace;1const StackTrace = @import("builtin").StackTrace;
2pub fn panic(msg: []const u8, stack_trace: ?&StackTrace) noreturn { @breakpoint(); while (true) {} }2pub fn panic(msg: []const u8, stack_trace: ?*StackTrace) noreturn {
3 @breakpoint();
4 while (true) {}
5}
36
4fn bar() error!void {}7fn bar() error!void {}
58
test/standalone/issue_794/build.zig+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const Builder = @import("std").build.Builder;1const Builder = @import("std").build.Builder;
22
3pub fn build(b: &Builder) void {3pub fn build(b: *Builder) void {
4 const test_artifact = b.addTest("main.zig");4 const test_artifact = b.addTest("main.zig");
5 test_artifact.addIncludeDir("a_directory");5 test_artifact.addIncludeDir("a_directory");
66
test/standalone/pkg_import/build.zig+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const Builder = @import("std").build.Builder;1const Builder = @import("std").build.Builder;
22
3pub fn build(b: &Builder) void {3pub fn build(b: *Builder) void {
4 const exe = b.addExecutable("test", "test.zig");4 const exe = b.addExecutable("test", "test.zig");
5 exe.addPackagePath("my_pkg", "pkg.zig");5 exe.addPackagePath("my_pkg", "pkg.zig");
66
test/standalone/pkg_import/pkg.zig+3-1
...@@ -1 +1,3 @@...@@ -1 +1,3 @@
1pub fn add(a: i32, b: i32) i32 { return a + b; }1pub fn add(a: i32, b: i32) i32 {
2 return a + b;
3}
test/standalone/use_alias/build.zig+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const Builder = @import("std").build.Builder;1const Builder = @import("std").build.Builder;
22
3pub fn build(b: &Builder) void {3pub fn build(b: *Builder) void {
4 b.addCIncludePath(".");4 b.addCIncludePath(".");
55
6 const main = b.addTest("main.zig");6 const main = b.addTest("main.zig");
test/standalone/use_alias/main.zig+1-1
...@@ -2,7 +2,7 @@ const c = @import("c.zig");...@@ -2,7 +2,7 @@ const c = @import("c.zig");
2const assert = @import("std").debug.assert;2const assert = @import("std").debug.assert;
33
4test "symbol exists" {4test "symbol exists" {
5 var foo = c.Foo {5 var foo = c.Foo{
6 .a = 1,6 .a = 1,
7 .b = 1,7 .b = 1,
8 };8 };
test/tests.zig+68-68
...@@ -47,7 +47,7 @@ const test_targets = []TestTarget{...@@ -47,7 +47,7 @@ const test_targets = []TestTarget{
4747
48const max_stdout_size = 1 * 1024 * 1024; // 1 MB48const max_stdout_size = 1 * 1024 * 1024; // 1 MB
4949
50pub fn addCompareOutputTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step {50pub fn addCompareOutputTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step {
51 const cases = b.allocator.create(CompareOutputContext) catch unreachable;51 const cases = b.allocator.create(CompareOutputContext) catch unreachable;
52 cases.* = CompareOutputContext{52 cases.* = CompareOutputContext{
53 .b = b,53 .b = b,
...@@ -61,7 +61,7 @@ pub fn addCompareOutputTests(b: &build.Builder, test_filter: ?[]const u8) &build...@@ -61,7 +61,7 @@ pub fn addCompareOutputTests(b: &build.Builder, test_filter: ?[]const u8) &build
61 return cases.step;61 return cases.step;
62}62}
6363
64pub fn addRuntimeSafetyTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step {64pub fn addRuntimeSafetyTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step {
65 const cases = b.allocator.create(CompareOutputContext) catch unreachable;65 const cases = b.allocator.create(CompareOutputContext) catch unreachable;
66 cases.* = CompareOutputContext{66 cases.* = CompareOutputContext{
67 .b = b,67 .b = b,
...@@ -75,7 +75,7 @@ pub fn addRuntimeSafetyTests(b: &build.Builder, test_filter: ?[]const u8) &build...@@ -75,7 +75,7 @@ pub fn addRuntimeSafetyTests(b: &build.Builder, test_filter: ?[]const u8) &build
75 return cases.step;75 return cases.step;
76}76}
7777
78pub fn addCompileErrorTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step {78pub fn addCompileErrorTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step {
79 const cases = b.allocator.create(CompileErrorContext) catch unreachable;79 const cases = b.allocator.create(CompileErrorContext) catch unreachable;
80 cases.* = CompileErrorContext{80 cases.* = CompileErrorContext{
81 .b = b,81 .b = b,
...@@ -89,7 +89,7 @@ pub fn addCompileErrorTests(b: &build.Builder, test_filter: ?[]const u8) &build....@@ -89,7 +89,7 @@ pub fn addCompileErrorTests(b: &build.Builder, test_filter: ?[]const u8) &build.
89 return cases.step;89 return cases.step;
90}90}
9191
92pub fn addBuildExampleTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step {92pub fn addBuildExampleTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step {
93 const cases = b.allocator.create(BuildExamplesContext) catch unreachable;93 const cases = b.allocator.create(BuildExamplesContext) catch unreachable;
94 cases.* = BuildExamplesContext{94 cases.* = BuildExamplesContext{
95 .b = b,95 .b = b,
...@@ -103,7 +103,7 @@ pub fn addBuildExampleTests(b: &build.Builder, test_filter: ?[]const u8) &build....@@ -103,7 +103,7 @@ pub fn addBuildExampleTests(b: &build.Builder, test_filter: ?[]const u8) &build.
103 return cases.step;103 return cases.step;
104}104}
105105
106pub fn addAssembleAndLinkTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step {106pub fn addAssembleAndLinkTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step {
107 const cases = b.allocator.create(CompareOutputContext) catch unreachable;107 const cases = b.allocator.create(CompareOutputContext) catch unreachable;
108 cases.* = CompareOutputContext{108 cases.* = CompareOutputContext{
109 .b = b,109 .b = b,
...@@ -117,7 +117,7 @@ pub fn addAssembleAndLinkTests(b: &build.Builder, test_filter: ?[]const u8) &bui...@@ -117,7 +117,7 @@ pub fn addAssembleAndLinkTests(b: &build.Builder, test_filter: ?[]const u8) &bui
117 return cases.step;117 return cases.step;
118}118}
119119
120pub fn addTranslateCTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step {120pub fn addTranslateCTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step {
121 const cases = b.allocator.create(TranslateCContext) catch unreachable;121 const cases = b.allocator.create(TranslateCContext) catch unreachable;
122 cases.* = TranslateCContext{122 cases.* = TranslateCContext{
123 .b = b,123 .b = b,
...@@ -131,7 +131,7 @@ pub fn addTranslateCTests(b: &build.Builder, test_filter: ?[]const u8) &build.St...@@ -131,7 +131,7 @@ pub fn addTranslateCTests(b: &build.Builder, test_filter: ?[]const u8) &build.St
131 return cases.step;131 return cases.step;
132}132}
133133
134pub fn addGenHTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step {134pub fn addGenHTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step {
135 const cases = b.allocator.create(GenHContext) catch unreachable;135 const cases = b.allocator.create(GenHContext) catch unreachable;
136 cases.* = GenHContext{136 cases.* = GenHContext{
137 .b = b,137 .b = b,
...@@ -145,7 +145,7 @@ pub fn addGenHTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step {...@@ -145,7 +145,7 @@ pub fn addGenHTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step {
145 return cases.step;145 return cases.step;
146}146}
147147
148pub fn addPkgTests(b: &build.Builder, test_filter: ?[]const u8, root_src: []const u8, name: []const u8, desc: []const u8, with_lldb: bool) &build.Step {148pub fn addPkgTests(b: *build.Builder, test_filter: ?[]const u8, root_src: []const u8, name: []const u8, desc: []const u8, with_lldb: bool) *build.Step {
149 const step = b.step(b.fmt("test-{}", name), desc);149 const step = b.step(b.fmt("test-{}", name), desc);
150 for (test_targets) |test_target| {150 for (test_targets) |test_target| {
151 const is_native = (test_target.os == builtin.os and test_target.arch == builtin.arch);151 const is_native = (test_target.os == builtin.os and test_target.arch == builtin.arch);
...@@ -193,8 +193,8 @@ pub fn addPkgTests(b: &build.Builder, test_filter: ?[]const u8, root_src: []cons...@@ -193,8 +193,8 @@ pub fn addPkgTests(b: &build.Builder, test_filter: ?[]const u8, root_src: []cons
193}193}
194194
195pub const CompareOutputContext = struct {195pub const CompareOutputContext = struct {
196 b: &build.Builder,196 b: *build.Builder,
197 step: &build.Step,197 step: *build.Step,
198 test_index: usize,198 test_index: usize,
199 test_filter: ?[]const u8,199 test_filter: ?[]const u8,
200200
...@@ -217,28 +217,28 @@ pub const CompareOutputContext = struct {...@@ -217,28 +217,28 @@ pub const CompareOutputContext = struct {
217 source: []const u8,217 source: []const u8,
218 };218 };
219219
220 pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void {220 pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void {
221 self.sources.append(SourceFile{221 self.sources.append(SourceFile{
222 .filename = filename,222 .filename = filename,
223 .source = source,223 .source = source,
224 }) catch unreachable;224 }) catch unreachable;
225 }225 }
226226
227 pub fn setCommandLineArgs(self: &TestCase, args: []const []const u8) void {227 pub fn setCommandLineArgs(self: *TestCase, args: []const []const u8) void {
228 self.cli_args = args;228 self.cli_args = args;
229 }229 }
230 };230 };
231231
232 const RunCompareOutputStep = struct {232 const RunCompareOutputStep = struct {
233 step: build.Step,233 step: build.Step,
234 context: &CompareOutputContext,234 context: *CompareOutputContext,
235 exe_path: []const u8,235 exe_path: []const u8,
236 name: []const u8,236 name: []const u8,
237 expected_output: []const u8,237 expected_output: []const u8,
238 test_index: usize,238 test_index: usize,
239 cli_args: []const []const u8,239 cli_args: []const []const u8,
240240
241 pub fn create(context: &CompareOutputContext, exe_path: []const u8, name: []const u8, expected_output: []const u8, cli_args: []const []const u8) &RunCompareOutputStep {241 pub fn create(context: *CompareOutputContext, exe_path: []const u8, name: []const u8, expected_output: []const u8, cli_args: []const []const u8) *RunCompareOutputStep {
242 const allocator = context.b.allocator;242 const allocator = context.b.allocator;
243 const ptr = allocator.create(RunCompareOutputStep) catch unreachable;243 const ptr = allocator.create(RunCompareOutputStep) catch unreachable;
244 ptr.* = RunCompareOutputStep{244 ptr.* = RunCompareOutputStep{
...@@ -254,7 +254,7 @@ pub const CompareOutputContext = struct {...@@ -254,7 +254,7 @@ pub const CompareOutputContext = struct {
254 return ptr;254 return ptr;
255 }255 }
256256
257 fn make(step: &build.Step) !void {257 fn make(step: *build.Step) !void {
258 const self = @fieldParentPtr(RunCompareOutputStep, "step", step);258 const self = @fieldParentPtr(RunCompareOutputStep, "step", step);
259 const b = self.context.b;259 const b = self.context.b;
260260
...@@ -321,12 +321,12 @@ pub const CompareOutputContext = struct {...@@ -321,12 +321,12 @@ pub const CompareOutputContext = struct {
321321
322 const RuntimeSafetyRunStep = struct {322 const RuntimeSafetyRunStep = struct {
323 step: build.Step,323 step: build.Step,
324 context: &CompareOutputContext,324 context: *CompareOutputContext,
325 exe_path: []const u8,325 exe_path: []const u8,
326 name: []const u8,326 name: []const u8,
327 test_index: usize,327 test_index: usize,
328328
329 pub fn create(context: &CompareOutputContext, exe_path: []const u8, name: []const u8) &RuntimeSafetyRunStep {329 pub fn create(context: *CompareOutputContext, exe_path: []const u8, name: []const u8) *RuntimeSafetyRunStep {
330 const allocator = context.b.allocator;330 const allocator = context.b.allocator;
331 const ptr = allocator.create(RuntimeSafetyRunStep) catch unreachable;331 const ptr = allocator.create(RuntimeSafetyRunStep) catch unreachable;
332 ptr.* = RuntimeSafetyRunStep{332 ptr.* = RuntimeSafetyRunStep{
...@@ -340,7 +340,7 @@ pub const CompareOutputContext = struct {...@@ -340,7 +340,7 @@ pub const CompareOutputContext = struct {
340 return ptr;340 return ptr;
341 }341 }
342342
343 fn make(step: &build.Step) !void {343 fn make(step: *build.Step) !void {
344 const self = @fieldParentPtr(RuntimeSafetyRunStep, "step", step);344 const self = @fieldParentPtr(RuntimeSafetyRunStep, "step", step);
345 const b = self.context.b;345 const b = self.context.b;
346346
...@@ -382,7 +382,7 @@ pub const CompareOutputContext = struct {...@@ -382,7 +382,7 @@ pub const CompareOutputContext = struct {
382 }382 }
383 };383 };
384384
385 pub fn createExtra(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8, special: Special) TestCase {385 pub fn createExtra(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8, special: Special) TestCase {
386 var tc = TestCase{386 var tc = TestCase{
387 .name = name,387 .name = name,
388 .sources = ArrayList(TestCase.SourceFile).init(self.b.allocator),388 .sources = ArrayList(TestCase.SourceFile).init(self.b.allocator),
...@@ -396,32 +396,32 @@ pub const CompareOutputContext = struct {...@@ -396,32 +396,32 @@ pub const CompareOutputContext = struct {
396 return tc;396 return tc;
397 }397 }
398398
399 pub fn create(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) TestCase {399 pub fn create(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) TestCase {
400 return createExtra(self, name, source, expected_output, Special.None);400 return createExtra(self, name, source, expected_output, Special.None);
401 }401 }
402402
403 pub fn addC(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void {403 pub fn addC(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void {
404 var tc = self.create(name, source, expected_output);404 var tc = self.create(name, source, expected_output);
405 tc.link_libc = true;405 tc.link_libc = true;
406 self.addCase(tc);406 self.addCase(tc);
407 }407 }
408408
409 pub fn add(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void {409 pub fn add(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void {
410 const tc = self.create(name, source, expected_output);410 const tc = self.create(name, source, expected_output);
411 self.addCase(tc);411 self.addCase(tc);
412 }412 }
413413
414 pub fn addAsm(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void {414 pub fn addAsm(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void {
415 const tc = self.createExtra(name, source, expected_output, Special.Asm);415 const tc = self.createExtra(name, source, expected_output, Special.Asm);
416 self.addCase(tc);416 self.addCase(tc);
417 }417 }
418418
419 pub fn addRuntimeSafety(self: &CompareOutputContext, name: []const u8, source: []const u8) void {419 pub fn addRuntimeSafety(self: *CompareOutputContext, name: []const u8, source: []const u8) void {
420 const tc = self.createExtra(name, source, undefined, Special.RuntimeSafety);420 const tc = self.createExtra(name, source, undefined, Special.RuntimeSafety);
421 self.addCase(tc);421 self.addCase(tc);
422 }422 }
423423
424 pub fn addCase(self: &CompareOutputContext, case: &const TestCase) void {424 pub fn addCase(self: *CompareOutputContext, case: *const TestCase) void {
425 const b = self.b;425 const b = self.b;
426426
427 const root_src = os.path.join(b.allocator, b.cache_root, case.sources.items[0].filename) catch unreachable;427 const root_src = os.path.join(b.allocator, b.cache_root, case.sources.items[0].filename) catch unreachable;
...@@ -504,8 +504,8 @@ pub const CompareOutputContext = struct {...@@ -504,8 +504,8 @@ pub const CompareOutputContext = struct {
504};504};
505505
506pub const CompileErrorContext = struct {506pub const CompileErrorContext = struct {
507 b: &build.Builder,507 b: *build.Builder,
508 step: &build.Step,508 step: *build.Step,
509 test_index: usize,509 test_index: usize,
510 test_filter: ?[]const u8,510 test_filter: ?[]const u8,
511511
...@@ -521,27 +521,27 @@ pub const CompileErrorContext = struct {...@@ -521,27 +521,27 @@ pub const CompileErrorContext = struct {
521 source: []const u8,521 source: []const u8,
522 };522 };
523523
524 pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void {524 pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void {
525 self.sources.append(SourceFile{525 self.sources.append(SourceFile{
526 .filename = filename,526 .filename = filename,
527 .source = source,527 .source = source,
528 }) catch unreachable;528 }) catch unreachable;
529 }529 }
530530
531 pub fn addExpectedError(self: &TestCase, text: []const u8) void {531 pub fn addExpectedError(self: *TestCase, text: []const u8) void {
532 self.expected_errors.append(text) catch unreachable;532 self.expected_errors.append(text) catch unreachable;
533 }533 }
534 };534 };
535535
536 const CompileCmpOutputStep = struct {536 const CompileCmpOutputStep = struct {
537 step: build.Step,537 step: build.Step,
538 context: &CompileErrorContext,538 context: *CompileErrorContext,
539 name: []const u8,539 name: []const u8,
540 test_index: usize,540 test_index: usize,
541 case: &const TestCase,541 case: *const TestCase,
542 build_mode: Mode,542 build_mode: Mode,
543543
544 pub fn create(context: &CompileErrorContext, name: []const u8, case: &const TestCase, build_mode: Mode) &CompileCmpOutputStep {544 pub fn create(context: *CompileErrorContext, name: []const u8, case: *const TestCase, build_mode: Mode) *CompileCmpOutputStep {
545 const allocator = context.b.allocator;545 const allocator = context.b.allocator;
546 const ptr = allocator.create(CompileCmpOutputStep) catch unreachable;546 const ptr = allocator.create(CompileCmpOutputStep) catch unreachable;
547 ptr.* = CompileCmpOutputStep{547 ptr.* = CompileCmpOutputStep{
...@@ -556,7 +556,7 @@ pub const CompileErrorContext = struct {...@@ -556,7 +556,7 @@ pub const CompileErrorContext = struct {
556 return ptr;556 return ptr;
557 }557 }
558558
559 fn make(step: &build.Step) !void {559 fn make(step: *build.Step) !void {
560 const self = @fieldParentPtr(CompileCmpOutputStep, "step", step);560 const self = @fieldParentPtr(CompileCmpOutputStep, "step", step);
561 const b = self.context.b;561 const b = self.context.b;
562562
...@@ -661,7 +661,7 @@ pub const CompileErrorContext = struct {...@@ -661,7 +661,7 @@ pub const CompileErrorContext = struct {
661 warn("\n");661 warn("\n");
662 }662 }
663663
664 pub fn create(self: &CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) &TestCase {664 pub fn create(self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) *TestCase {
665 const tc = self.b.allocator.create(TestCase) catch unreachable;665 const tc = self.b.allocator.create(TestCase) catch unreachable;
666 tc.* = TestCase{666 tc.* = TestCase{
667 .name = name,667 .name = name,
...@@ -678,24 +678,24 @@ pub const CompileErrorContext = struct {...@@ -678,24 +678,24 @@ pub const CompileErrorContext = struct {
678 return tc;678 return tc;
679 }679 }
680680
681 pub fn addC(self: &CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void {681 pub fn addC(self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void {
682 var tc = self.create(name, source, expected_lines);682 var tc = self.create(name, source, expected_lines);
683 tc.link_libc = true;683 tc.link_libc = true;
684 self.addCase(tc);684 self.addCase(tc);
685 }685 }
686686
687 pub fn addExe(self: &CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void {687 pub fn addExe(self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void {
688 var tc = self.create(name, source, expected_lines);688 var tc = self.create(name, source, expected_lines);
689 tc.is_exe = true;689 tc.is_exe = true;
690 self.addCase(tc);690 self.addCase(tc);
691 }691 }
692692
693 pub fn add(self: &CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void {693 pub fn add(self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void {
694 const tc = self.create(name, source, expected_lines);694 const tc = self.create(name, source, expected_lines);
695 self.addCase(tc);695 self.addCase(tc);
696 }696 }
697697
698 pub fn addCase(self: &CompileErrorContext, case: &const TestCase) void {698 pub fn addCase(self: *CompileErrorContext, case: *const TestCase) void {
699 const b = self.b;699 const b = self.b;
700700
701 for ([]Mode{701 for ([]Mode{
...@@ -720,20 +720,20 @@ pub const CompileErrorContext = struct {...@@ -720,20 +720,20 @@ pub const CompileErrorContext = struct {
720};720};
721721
722pub const BuildExamplesContext = struct {722pub const BuildExamplesContext = struct {
723 b: &build.Builder,723 b: *build.Builder,
724 step: &build.Step,724 step: *build.Step,
725 test_index: usize,725 test_index: usize,
726 test_filter: ?[]const u8,726 test_filter: ?[]const u8,
727727
728 pub fn addC(self: &BuildExamplesContext, root_src: []const u8) void {728 pub fn addC(self: *BuildExamplesContext, root_src: []const u8) void {
729 self.addAllArgs(root_src, true);729 self.addAllArgs(root_src, true);
730 }730 }
731731
732 pub fn add(self: &BuildExamplesContext, root_src: []const u8) void {732 pub fn add(self: *BuildExamplesContext, root_src: []const u8) void {
733 self.addAllArgs(root_src, false);733 self.addAllArgs(root_src, false);
734 }734 }
735735
736 pub fn addBuildFile(self: &BuildExamplesContext, build_file: []const u8) void {736 pub fn addBuildFile(self: *BuildExamplesContext, build_file: []const u8) void {
737 const b = self.b;737 const b = self.b;
738738
739 const annotated_case_name = b.fmt("build {} (Debug)", build_file);739 const annotated_case_name = b.fmt("build {} (Debug)", build_file);
...@@ -763,7 +763,7 @@ pub const BuildExamplesContext = struct {...@@ -763,7 +763,7 @@ pub const BuildExamplesContext = struct {
763 self.step.dependOn(&log_step.step);763 self.step.dependOn(&log_step.step);
764 }764 }
765765
766 pub fn addAllArgs(self: &BuildExamplesContext, root_src: []const u8, link_libc: bool) void {766 pub fn addAllArgs(self: *BuildExamplesContext, root_src: []const u8, link_libc: bool) void {
767 const b = self.b;767 const b = self.b;
768768
769 for ([]Mode{769 for ([]Mode{
...@@ -792,8 +792,8 @@ pub const BuildExamplesContext = struct {...@@ -792,8 +792,8 @@ pub const BuildExamplesContext = struct {
792};792};
793793
794pub const TranslateCContext = struct {794pub const TranslateCContext = struct {
795 b: &build.Builder,795 b: *build.Builder,
796 step: &build.Step,796 step: *build.Step,
797 test_index: usize,797 test_index: usize,
798 test_filter: ?[]const u8,798 test_filter: ?[]const u8,
799799
...@@ -808,26 +808,26 @@ pub const TranslateCContext = struct {...@@ -808,26 +808,26 @@ pub const TranslateCContext = struct {
808 source: []const u8,808 source: []const u8,
809 };809 };
810810
811 pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void {811 pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void {
812 self.sources.append(SourceFile{812 self.sources.append(SourceFile{
813 .filename = filename,813 .filename = filename,
814 .source = source,814 .source = source,
815 }) catch unreachable;815 }) catch unreachable;
816 }816 }
817817
818 pub fn addExpectedLine(self: &TestCase, text: []const u8) void {818 pub fn addExpectedLine(self: *TestCase, text: []const u8) void {
819 self.expected_lines.append(text) catch unreachable;819 self.expected_lines.append(text) catch unreachable;
820 }820 }
821 };821 };
822822
823 const TranslateCCmpOutputStep = struct {823 const TranslateCCmpOutputStep = struct {
824 step: build.Step,824 step: build.Step,
825 context: &TranslateCContext,825 context: *TranslateCContext,
826 name: []const u8,826 name: []const u8,
827 test_index: usize,827 test_index: usize,
828 case: &const TestCase,828 case: *const TestCase,
829829
830 pub fn create(context: &TranslateCContext, name: []const u8, case: &const TestCase) &TranslateCCmpOutputStep {830 pub fn create(context: *TranslateCContext, name: []const u8, case: *const TestCase) *TranslateCCmpOutputStep {
831 const allocator = context.b.allocator;831 const allocator = context.b.allocator;
832 const ptr = allocator.create(TranslateCCmpOutputStep) catch unreachable;832 const ptr = allocator.create(TranslateCCmpOutputStep) catch unreachable;
833 ptr.* = TranslateCCmpOutputStep{833 ptr.* = TranslateCCmpOutputStep{
...@@ -841,7 +841,7 @@ pub const TranslateCContext = struct {...@@ -841,7 +841,7 @@ pub const TranslateCContext = struct {
841 return ptr;841 return ptr;
842 }842 }
843843
844 fn make(step: &build.Step) !void {844 fn make(step: *build.Step) !void {
845 const self = @fieldParentPtr(TranslateCCmpOutputStep, "step", step);845 const self = @fieldParentPtr(TranslateCCmpOutputStep, "step", step);
846 const b = self.context.b;846 const b = self.context.b;
847847
...@@ -935,7 +935,7 @@ pub const TranslateCContext = struct {...@@ -935,7 +935,7 @@ pub const TranslateCContext = struct {
935 warn("\n");935 warn("\n");
936 }936 }
937937
938 pub fn create(self: &TranslateCContext, allow_warnings: bool, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) &TestCase {938 pub fn create(self: *TranslateCContext, allow_warnings: bool, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) *TestCase {
939 const tc = self.b.allocator.create(TestCase) catch unreachable;939 const tc = self.b.allocator.create(TestCase) catch unreachable;
940 tc.* = TestCase{940 tc.* = TestCase{
941 .name = name,941 .name = name,
...@@ -951,22 +951,22 @@ pub const TranslateCContext = struct {...@@ -951,22 +951,22 @@ pub const TranslateCContext = struct {
951 return tc;951 return tc;
952 }952 }
953953
954 pub fn add(self: &TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void {954 pub fn add(self: *TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void {
955 const tc = self.create(false, "source.h", name, source, expected_lines);955 const tc = self.create(false, "source.h", name, source, expected_lines);
956 self.addCase(tc);956 self.addCase(tc);
957 }957 }
958958
959 pub fn addC(self: &TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void {959 pub fn addC(self: *TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void {
960 const tc = self.create(false, "source.c", name, source, expected_lines);960 const tc = self.create(false, "source.c", name, source, expected_lines);
961 self.addCase(tc);961 self.addCase(tc);
962 }962 }
963963
964 pub fn addAllowWarnings(self: &TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void {964 pub fn addAllowWarnings(self: *TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void {
965 const tc = self.create(true, "source.h", name, source, expected_lines);965 const tc = self.create(true, "source.h", name, source, expected_lines);
966 self.addCase(tc);966 self.addCase(tc);
967 }967 }
968968
969 pub fn addCase(self: &TranslateCContext, case: &const TestCase) void {969 pub fn addCase(self: *TranslateCContext, case: *const TestCase) void {
970 const b = self.b;970 const b = self.b;
971971
972 const annotated_case_name = fmt.allocPrint(self.b.allocator, "translate-c {}", case.name) catch unreachable;972 const annotated_case_name = fmt.allocPrint(self.b.allocator, "translate-c {}", case.name) catch unreachable;
...@@ -986,8 +986,8 @@ pub const TranslateCContext = struct {...@@ -986,8 +986,8 @@ pub const TranslateCContext = struct {
986};986};
987987
988pub const GenHContext = struct {988pub const GenHContext = struct {
989 b: &build.Builder,989 b: *build.Builder,
990 step: &build.Step,990 step: *build.Step,
991 test_index: usize,991 test_index: usize,
992 test_filter: ?[]const u8,992 test_filter: ?[]const u8,
993993
...@@ -1001,27 +1001,27 @@ pub const GenHContext = struct {...@@ -1001,27 +1001,27 @@ pub const GenHContext = struct {
1001 source: []const u8,1001 source: []const u8,
1002 };1002 };
10031003
1004 pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void {1004 pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void {
1005 self.sources.append(SourceFile{1005 self.sources.append(SourceFile{
1006 .filename = filename,1006 .filename = filename,
1007 .source = source,1007 .source = source,
1008 }) catch unreachable;1008 }) catch unreachable;
1009 }1009 }
10101010
1011 pub fn addExpectedLine(self: &TestCase, text: []const u8) void {1011 pub fn addExpectedLine(self: *TestCase, text: []const u8) void {
1012 self.expected_lines.append(text) catch unreachable;1012 self.expected_lines.append(text) catch unreachable;
1013 }1013 }
1014 };1014 };
10151015
1016 const GenHCmpOutputStep = struct {1016 const GenHCmpOutputStep = struct {
1017 step: build.Step,1017 step: build.Step,
1018 context: &GenHContext,1018 context: *GenHContext,
1019 h_path: []const u8,1019 h_path: []const u8,
1020 name: []const u8,1020 name: []const u8,
1021 test_index: usize,1021 test_index: usize,
1022 case: &const TestCase,1022 case: *const TestCase,
10231023
1024 pub fn create(context: &GenHContext, h_path: []const u8, name: []const u8, case: &const TestCase) &GenHCmpOutputStep {1024 pub fn create(context: *GenHContext, h_path: []const u8, name: []const u8, case: *const TestCase) *GenHCmpOutputStep {
1025 const allocator = context.b.allocator;1025 const allocator = context.b.allocator;
1026 const ptr = allocator.create(GenHCmpOutputStep) catch unreachable;1026 const ptr = allocator.create(GenHCmpOutputStep) catch unreachable;
1027 ptr.* = GenHCmpOutputStep{1027 ptr.* = GenHCmpOutputStep{
...@@ -1036,7 +1036,7 @@ pub const GenHContext = struct {...@@ -1036,7 +1036,7 @@ pub const GenHContext = struct {
1036 return ptr;1036 return ptr;
1037 }1037 }
10381038
1039 fn make(step: &build.Step) !void {1039 fn make(step: *build.Step) !void {
1040 const self = @fieldParentPtr(GenHCmpOutputStep, "step", step);1040 const self = @fieldParentPtr(GenHCmpOutputStep, "step", step);
1041 const b = self.context.b;1041 const b = self.context.b;
10421042
...@@ -1069,7 +1069,7 @@ pub const GenHContext = struct {...@@ -1069,7 +1069,7 @@ pub const GenHContext = struct {
1069 warn("\n");1069 warn("\n");
1070 }1070 }
10711071
1072 pub fn create(self: &GenHContext, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) &TestCase {1072 pub fn create(self: *GenHContext, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) *TestCase {
1073 const tc = self.b.allocator.create(TestCase) catch unreachable;1073 const tc = self.b.allocator.create(TestCase) catch unreachable;
1074 tc.* = TestCase{1074 tc.* = TestCase{
1075 .name = name,1075 .name = name,
...@@ -1084,12 +1084,12 @@ pub const GenHContext = struct {...@@ -1084,12 +1084,12 @@ pub const GenHContext = struct {
1084 return tc;1084 return tc;
1085 }1085 }
10861086
1087 pub fn add(self: &GenHContext, name: []const u8, source: []const u8, expected_lines: ...) void {1087 pub fn add(self: *GenHContext, name: []const u8, source: []const u8, expected_lines: ...) void {
1088 const tc = self.create("test.zig", name, source, expected_lines);1088 const tc = self.create("test.zig", name, source, expected_lines);
1089 self.addCase(tc);1089 self.addCase(tc);
1090 }1090 }
10911091
1092 pub fn addCase(self: &GenHContext, case: &const TestCase) void {1092 pub fn addCase(self: *GenHContext, case: *const TestCase) void {
1093 const b = self.b;1093 const b = self.b;
1094 const root_src = os.path.join(b.allocator, b.cache_root, case.sources.items[0].filename) catch unreachable;1094 const root_src = os.path.join(b.allocator, b.cache_root, case.sources.items[0].filename) catch unreachable;
10951095
test/translate_c.zig+53-54
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const tests = @import("tests.zig");1const tests = @import("tests.zig");
22
3pub fn addCases(cases: &tests.TranslateCContext) void {3pub fn addCases(cases: *tests.TranslateCContext) void {
4 cases.add("double define struct",4 cases.add("double define struct",
5 \\typedef struct Bar Bar;5 \\typedef struct Bar Bar;
6 \\typedef struct Foo Foo;6 \\typedef struct Foo Foo;
...@@ -14,11 +14,11 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -14,11 +14,11 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
14 \\};14 \\};
15 ,15 ,
16 \\pub const struct_Foo = extern struct {16 \\pub const struct_Foo = extern struct {
17 \\ a: ?&Foo,17 \\ a: ?[*]Foo,
18 \\};18 \\};
19 \\pub const Foo = struct_Foo;19 \\pub const Foo = struct_Foo;
20 \\pub const struct_Bar = extern struct {20 \\pub const struct_Bar = extern struct {
21 \\ a: ?&Foo,21 \\ a: ?[*]Foo,
22 \\};22 \\};
23 );23 );
2424
...@@ -99,7 +99,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -99,7 +99,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
99 cases.add("restrict -> noalias",99 cases.add("restrict -> noalias",
100 \\void foo(void *restrict bar, void *restrict);100 \\void foo(void *restrict bar, void *restrict);
101 ,101 ,
102 \\pub extern fn foo(noalias bar: ?&c_void, noalias arg1: ?&c_void) void;102 \\pub extern fn foo(noalias bar: ?[*]c_void, noalias arg1: ?[*]c_void) void;
103 );103 );
104104
105 cases.add("simple struct",105 cases.add("simple struct",
...@@ -110,7 +110,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -110,7 +110,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
110 ,110 ,
111 \\const struct_Foo = extern struct {111 \\const struct_Foo = extern struct {
112 \\ x: c_int,112 \\ x: c_int,
113 \\ y: ?&u8,113 \\ y: ?[*]u8,
114 \\};114 \\};
115 ,115 ,
116 \\pub const Foo = struct_Foo;116 \\pub const Foo = struct_Foo;
...@@ -141,7 +141,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -141,7 +141,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
141 ,141 ,
142 \\pub const BarB = enum_Bar.B;142 \\pub const BarB = enum_Bar.B;
143 ,143 ,
144 \\pub extern fn func(a: ?&struct_Foo, b: ?&(?&enum_Bar)) void;144 \\pub extern fn func(a: ?[*]struct_Foo, b: ?[*](?[*]enum_Bar)) void;
145 ,145 ,
146 \\pub const Foo = struct_Foo;146 \\pub const Foo = struct_Foo;
147 ,147 ,
...@@ -151,7 +151,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -151,7 +151,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
151 cases.add("constant size array",151 cases.add("constant size array",
152 \\void func(int array[20]);152 \\void func(int array[20]);
153 ,153 ,
154 \\pub extern fn func(array: ?&c_int) void;154 \\pub extern fn func(array: ?[*]c_int) void;
155 );155 );
156156
157 cases.add("self referential struct with function pointer",157 cases.add("self referential struct with function pointer",
...@@ -160,7 +160,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -160,7 +160,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
160 \\};160 \\};
161 ,161 ,
162 \\pub const struct_Foo = extern struct {162 \\pub const struct_Foo = extern struct {
163 \\ derp: ?extern fn(?&struct_Foo) void,163 \\ derp: ?extern fn(?[*]struct_Foo) void,
164 \\};164 \\};
165 ,165 ,
166 \\pub const Foo = struct_Foo;166 \\pub const Foo = struct_Foo;
...@@ -172,7 +172,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -172,7 +172,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
172 ,172 ,
173 \\pub const struct_Foo = @OpaqueType();173 \\pub const struct_Foo = @OpaqueType();
174 ,174 ,
175 \\pub extern fn some_func(foo: ?&struct_Foo, x: c_int) ?&struct_Foo;175 \\pub extern fn some_func(foo: ?[*]struct_Foo, x: c_int) ?[*]struct_Foo;
176 ,176 ,
177 \\pub const Foo = struct_Foo;177 \\pub const Foo = struct_Foo;
178 );178 );
...@@ -219,11 +219,11 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -219,11 +219,11 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
219 \\};219 \\};
220 ,220 ,
221 \\pub const struct_Bar = extern struct {221 \\pub const struct_Bar = extern struct {
222 \\ next: ?&struct_Foo,222 \\ next: ?[*]struct_Foo,
223 \\};223 \\};
224 ,224 ,
225 \\pub const struct_Foo = extern struct {225 \\pub const struct_Foo = extern struct {
226 \\ next: ?&struct_Bar,226 \\ next: ?[*]struct_Bar,
227 \\};227 \\};
228 );228 );
229229
...@@ -233,7 +233,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -233,7 +233,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
233 ,233 ,
234 \\pub const Foo = c_void;234 \\pub const Foo = c_void;
235 ,235 ,
236 \\pub extern fn fun(a: ?&Foo) Foo;236 \\pub extern fn fun(a: ?[*]Foo) Foo;
237 );237 );
238238
239 cases.add("generate inline func for #define global extern fn",239 cases.add("generate inline func for #define global extern fn",
...@@ -505,7 +505,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -505,7 +505,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
505 \\ return 6;505 \\ return 6;
506 \\}506 \\}
507 ,507 ,
508 \\pub export fn and_or_none_bool(a: c_int, b: f32, c: ?&c_void) c_int {508 \\pub export fn and_or_none_bool(a: c_int, b: f32, c: ?[*]c_void) c_int {
509 \\ if ((a != 0) and (b != 0)) return 0;509 \\ if ((a != 0) and (b != 0)) return 0;
510 \\ if ((b != 0) and (c != null)) return 1;510 \\ if ((b != 0) and (c != null)) return 1;
511 \\ if ((a != 0) and (c != null)) return 2;511 \\ if ((a != 0) and (c != null)) return 2;
...@@ -607,7 +607,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -607,7 +607,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
607 \\pub const struct_Foo = extern struct {607 \\pub const struct_Foo = extern struct {
608 \\ field: c_int,608 \\ field: c_int,
609 \\};609 \\};
610 \\pub export fn read_field(foo: ?&struct_Foo) c_int {610 \\pub export fn read_field(foo: ?[*]struct_Foo) c_int {
611 \\ return (??foo).field;611 \\ return (??foo).field;
612 \\}612 \\}
613 );613 );
...@@ -638,7 +638,6 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -638,7 +638,6 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
638 \\}638 \\}
639 );639 );
640640
641
642 cases.addC("c style cast",641 cases.addC("c style cast",
643 \\int float_to_int(float a) {642 \\int float_to_int(float a) {
644 \\ return (int)a;643 \\ return (int)a;
...@@ -654,8 +653,8 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -654,8 +653,8 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
654 \\ return x;653 \\ return x;
655 \\}654 \\}
656 ,655 ,
657 \\pub export fn foo(x: ?&c_ushort) ?&c_void {656 \\pub export fn foo(x: ?[*]c_ushort) ?[*]c_void {
658 \\ return @ptrCast(?&c_void, x);657 \\ return @ptrCast(?[*]c_void, x);
659 \\}658 \\}
660 );659 );
661660
...@@ -675,7 +674,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -675,7 +674,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
675 \\ return 0;674 \\ return 0;
676 \\}675 \\}
677 ,676 ,
678 \\pub export fn foo() ?&c_int {677 \\pub export fn foo() ?[*]c_int {
679 \\ return null;678 \\ return null;
680 \\}679 \\}
681 );680 );
...@@ -984,7 +983,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -984,7 +983,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
984 \\ *x = 1;983 \\ *x = 1;
985 \\}984 \\}
986 ,985 ,
987 \\pub export fn foo(x: ?&c_int) void {986 \\pub export fn foo(x: ?[*]c_int) void {
988 \\ (??x).* = 1;987 \\ (??x).* = 1;
989 \\}988 \\}
990 );989 );
...@@ -1012,7 +1011,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -1012,7 +1011,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
1012 ,1011 ,
1013 \\pub fn foo() c_int {1012 \\pub fn foo() c_int {
1014 \\ var x: c_int = 1234;1013 \\ var x: c_int = 1234;
1015 \\ var ptr: ?&c_int = &x;1014 \\ var ptr: ?[*]c_int = &x;
1016 \\ return (??ptr).*;1015 \\ return (??ptr).*;
1017 \\}1016 \\}
1018 );1017 );
...@@ -1022,7 +1021,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -1022,7 +1021,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
1022 \\ return "bar";1021 \\ return "bar";
1023 \\}1022 \\}
1024 ,1023 ,
1025 \\pub fn foo() ?&const u8 {1024 \\pub fn foo() ?[*]const u8 {
1026 \\ return c"bar";1025 \\ return c"bar";
1027 \\}1026 \\}
1028 );1027 );
...@@ -1151,8 +1150,8 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -1151,8 +1150,8 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
1151 \\ return (float *)a;1150 \\ return (float *)a;
1152 \\}1151 \\}
1153 ,1152 ,
1154 \\fn ptrcast(a: ?&c_int) ?&f32 {1153 \\fn ptrcast(a: ?[*]c_int) ?[*]f32 {
1155 \\ return @ptrCast(?&f32, a);1154 \\ return @ptrCast(?[*]f32, a);
1156 \\}1155 \\}
1157 );1156 );
11581157
...@@ -1174,7 +1173,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -1174,7 +1173,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
1174 \\ return !c;1173 \\ return !c;
1175 \\}1174 \\}
1176 ,1175 ,
1177 \\pub fn foo(a: c_int, b: f32, c: ?&c_void) c_int {1176 \\pub fn foo(a: c_int, b: f32, c: ?[*]c_void) c_int {
1178 \\ return !(a == 0);1177 \\ return !(a == 0);
1179 \\ return !(a != 0);1178 \\ return !(a != 0);
1180 \\ return !(b != 0);1179 \\ return !(b != 0);
...@@ -1195,7 +1194,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -1195,7 +1194,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
1195 cases.add("const ptr initializer",1194 cases.add("const ptr initializer",
1196 \\static const char *v0 = "0.0.0";1195 \\static const char *v0 = "0.0.0";
1197 ,1196 ,
1198 \\pub var v0: ?&const u8 = c"0.0.0";1197 \\pub var v0: ?[*]const u8 = c"0.0.0";
1199 );1198 );
12001199
1201 cases.add("static incomplete array inside function",1200 cases.add("static incomplete array inside function",
...@@ -1204,14 +1203,14 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -1204,14 +1203,14 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
1204 \\}1203 \\}
1205 ,1204 ,
1206 \\pub fn foo() void {1205 \\pub fn foo() void {
1207 \\ const v2: &const u8 = c"2.2.2";1206 \\ const v2: [*]const u8 = c"2.2.2";
1208 \\}1207 \\}
1209 );1208 );
12101209
1211 cases.add("macro pointer cast",1210 cases.add("macro pointer cast",
1212 \\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE)1211 \\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE)
1213 ,1212 ,
1214 \\pub const NRF_GPIO = if (@typeId(@typeOf(NRF_GPIO_BASE)) == @import("builtin").TypeId.Pointer) @ptrCast(&NRF_GPIO_Type, NRF_GPIO_BASE) else if (@typeId(@typeOf(NRF_GPIO_BASE)) == @import("builtin").TypeId.Int) @intToPtr(&NRF_GPIO_Type, NRF_GPIO_BASE) else (&NRF_GPIO_Type)(NRF_GPIO_BASE);1213 \\pub const NRF_GPIO = if (@typeId(@typeOf(NRF_GPIO_BASE)) == @import("builtin").TypeId.Pointer) @ptrCast([*]NRF_GPIO_Type, NRF_GPIO_BASE) else if (@typeId(@typeOf(NRF_GPIO_BASE)) == @import("builtin").TypeId.Int) @intToPtr([*]NRF_GPIO_Type, NRF_GPIO_BASE) else ([*]NRF_GPIO_Type)(NRF_GPIO_BASE);
1215 );1214 );
12161215
1217 cases.add("if on none bool",1216 cases.add("if on none bool",
...@@ -1232,7 +1231,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -1232,7 +1231,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
1232 \\ B,1231 \\ B,
1233 \\ C,1232 \\ C,
1234 \\};1233 \\};
1235 \\pub fn if_none_bool(a: c_int, b: f32, c: ?&c_void, d: enum_SomeEnum) c_int {1234 \\pub fn if_none_bool(a: c_int, b: f32, c: ?[*]c_void, d: enum_SomeEnum) c_int {
1236 \\ if (a != 0) return 0;1235 \\ if (a != 0) return 0;
1237 \\ if (b != 0) return 1;1236 \\ if (b != 0) return 1;
1238 \\ if (c != null) return 2;1237 \\ if (c != null) return 2;
...@@ -1249,7 +1248,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -1249,7 +1248,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
1249 \\ return 3;1248 \\ return 3;
1250 \\}1249 \\}
1251 ,1250 ,
1252 \\pub fn while_none_bool(a: c_int, b: f32, c: ?&c_void) c_int {1251 \\pub fn while_none_bool(a: c_int, b: f32, c: ?[*]c_void) c_int {
1253 \\ while (a != 0) return 0;1252 \\ while (a != 0) return 0;
1254 \\ while (b != 0) return 1;1253 \\ while (b != 0) return 1;
1255 \\ while (c != null) return 2;1254 \\ while (c != null) return 2;
...@@ -1265,7 +1264,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -1265,7 +1264,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
1265 \\ return 3;1264 \\ return 3;
1266 \\}1265 \\}
1267 ,1266 ,
1268 \\pub fn for_none_bool(a: c_int, b: f32, c: ?&c_void) c_int {1267 \\pub fn for_none_bool(a: c_int, b: f32, c: ?[*]c_void) c_int {
1269 \\ while (a != 0) return 0;1268 \\ while (a != 0) return 0;
1270 \\ while (b != 0) return 1;1269 \\ while (b != 0) return 1;
1271 \\ while (c != null) return 2;1270 \\ while (c != null) return 2;
...@@ -1289,29 +1288,29 @@ pub fn addCases(cases: &tests.TranslateCContext) void {...@@ -1289,29 +1288,29 @@ pub fn addCases(cases: &tests.TranslateCContext) void {
1289 \\ }1288 \\ }
1290 \\}1289 \\}
1291 ,1290 ,
1292 \\pub fn switch_fn(i: c_int) c_int {1291 \\pub fn switch_fn(i: c_int) c_int {
1293 \\ var res: c_int = 0;1292 \\ var res: c_int = 0;
1294 \\ __switch: {1293 \\ __switch: {
1295 \\ __case_2: {1294 \\ __case_2: {
1296 \\ __default: {1295 \\ __default: {
1297 \\ __case_1: {1296 \\ __case_1: {
1298 \\ __case_0: {1297 \\ __case_0: {
1299 \\ switch (i) {1298 \\ switch (i) {
1300 \\ 0 => break :__case_0,1299 \\ 0 => break :__case_0,
1301 \\ 1 => break :__case_1,1300 \\ 1 => break :__case_1,
1302 \\ else => break :__default,1301 \\ else => break :__default,
1303 \\ 2 => break :__case_2,1302 \\ 2 => break :__case_2,
1304 \\ }1303 \\ }
1305 \\ }1304 \\ }
1306 \\ res = 1;1305 \\ res = 1;
1307 \\ }1306 \\ }
1308 \\ res = 2;1307 \\ res = 2;
1309 \\ }1308 \\ }
1310 \\ res = (3 * i);1309 \\ res = (3 * i);
1311 \\ break :__switch;1310 \\ break :__switch;
1312 \\ }1311 \\ }
1313 \\ res = 5;1312 \\ res = 5;
1314 \\ }1313 \\ }
1315 \\}1314 \\}
1316 );1315 );
1317}1316}