From b7af9edb8a8802c35f1a460f8dafff8643b34639 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 14 Apr 2018 02:12:19 -0400 Subject: add std.os.createThread this adds kernel thread support to the standard library for linux. See #174 --- std/os/linux/index.zig | 30 ++++++++++++++++++++++++++++++ std/os/linux/x86_64.zig | 3 +++ 2 files changed, 33 insertions(+) (limited to 'std/os/linux') diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index e100af7733..6eb2d74bb7 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -14,6 +14,22 @@ pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; +pub const FUTEX_WAIT = 0; +pub const FUTEX_WAKE = 1; +pub const FUTEX_FD = 2; +pub const FUTEX_REQUEUE = 3; +pub const FUTEX_CMP_REQUEUE = 4; +pub const FUTEX_WAKE_OP = 5; +pub const FUTEX_LOCK_PI = 6; +pub const FUTEX_UNLOCK_PI = 7; +pub const FUTEX_TRYLOCK_PI = 8; +pub const FUTEX_WAIT_BITSET = 9; + +pub const FUTEX_PRIVATE_FLAG = 128; + +pub const FUTEX_CLOCK_REALTIME = 256; + + pub const PROT_NONE = 0; pub const PROT_READ = 1; pub const PROT_WRITE = 2; @@ -652,6 +668,10 @@ pub fn fork() usize { return syscall0(SYS_fork); } +pub fn futex_wait(uaddr: usize, futex_op: u32, val: i32, timeout: ?×pec) usize { + return syscall4(SYS_futex, uaddr, futex_op, @bitCast(u32, val), @ptrToInt(timeout)); +} + pub fn getcwd(buf: &u8, size: usize) usize { return syscall2(SYS_getcwd, @ptrToInt(buf), size); } @@ -746,6 +766,16 @@ pub fn openat(dirfd: i32, path: &const u8, flags: usize, mode: usize) usize { return syscall4(SYS_openat, usize(dirfd), @ptrToInt(path), flags, mode); } +/// See also `clone` (from the arch-specific include) +pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: &i32, child_tid: &i32, newtls: usize) usize { + return syscall5(SYS_clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls); +} + +/// See also `clone` (from the arch-specific include) +pub fn clone2(flags: usize, child_stack_ptr: usize) usize { + return syscall2(SYS_clone, flags, child_stack_ptr); +} + pub fn close(fd: i32) usize { return syscall1(SYS_close, usize(fd)); } diff --git a/std/os/linux/x86_64.zig b/std/os/linux/x86_64.zig index cfb2231df9..d3d2c702fc 100644 --- a/std/os/linux/x86_64.zig +++ b/std/os/linux/x86_64.zig @@ -443,6 +443,9 @@ pub fn syscall6(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz : "rcx", "r11"); } +/// This matches the libc clone function. +pub extern fn clone(func: extern fn(arg: usize) u8, stack: usize, flags: usize, arg: usize, ptid: &i32, tls: usize, ctid: &i32) usize; + pub nakedcc fn restore_rt() void { return asm volatile ("syscall" : -- cgit v1.2.3 From 8b66dd8c7d2809c3ec86f1eec8acc0a1c184c8c2 Mon Sep 17 00:00:00 2001 From: tgschultz Date: Wed, 18 Apr 2018 13:55:42 -0500 Subject: Added unstaged changes. --- CMakeLists.txt | 2 ++ std/c/darwin.zig | 18 ++++++++++++++++++ std/c/index.zig | 1 + std/fmt/index.zig | 3 ++- std/os/darwin.zig | 4 ++++ std/os/index.zig | 45 +-------------------------------------------- std/os/linux/index.zig | 20 ++++++++++++++++++++ std/os/linux/x86_64.zig | 10 ++++++++++ std/os/windows/index.zig | 7 +++++++ 9 files changed, 65 insertions(+), 45 deletions(-) (limited to 'std/os/linux') diff --git a/CMakeLists.txt b/CMakeLists.txt index 2bb9bf517c..42bc71fd97 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -507,6 +507,8 @@ set(ZIG_STD_FILES "os/linux/index.zig" "os/linux/x86_64.zig" "os/path.zig" + "os/time.zig" + "os/epoch.zig" "os/windows/error.zig" "os/windows/index.zig" "os/windows/util.zig" diff --git a/std/c/darwin.zig b/std/c/darwin.zig index aa49dfa3df..14b0ea0086 100644 --- a/std/c/darwin.zig +++ b/std/c/darwin.zig @@ -3,10 +3,28 @@ pub extern "c" fn _NSGetExecutablePath(buf: &u8, bufsize: &u32) c_int; pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: &u8, buf_len: usize, basep: &i64) usize; +pub extern "c" fn mach_absolute_time() u64; +pub extern "c" fn mach_timebase_info(&mach_timebase_info_data) void; + pub use @import("../os/darwin_errno.zig"); pub const _errno = __error; +pub const timeval = extern struct { + tv_sec: isize, + tv_usec: isize, +}; + +pub const timezone = extern struct { + tz_minuteswest: i32, + tz_dsttime: i32, +}; + +pub const mach_timebase_info_data = struct { + numer: u32, + denom: u32, +}; + /// Renamed to Stat to not conflict with the stat function. pub const Stat = extern struct { dev: i32, diff --git a/std/c/index.zig b/std/c/index.zig index 369ea2b358..223d6026ce 100644 --- a/std/c/index.zig +++ b/std/c/index.zig @@ -40,6 +40,7 @@ pub extern "c" fn dup2(old_fd: c_int, new_fd: c_int) c_int; pub extern "c" fn readlink(noalias path: &const u8, noalias buf: &u8, bufsize: usize) isize; pub extern "c" fn realpath(noalias file_name: &const u8, noalias resolved_name: &u8) ?&u8; pub extern "c" fn sigprocmask(how: c_int, noalias set: &const sigset_t, noalias oset: ?&sigset_t) c_int; +pub extern "c" fn gettimeofday(&timeval, ?&timezone) c_int; pub extern "c" fn sigaction(sig: c_int, noalias act: &const Sigaction, noalias oact: ?&Sigaction) c_int; pub extern "c" fn nanosleep(rqtp: &const timespec, rmtp: ?×pec) c_int; pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int; diff --git a/std/fmt/index.zig b/std/fmt/index.zig index bd5b5710e0..56395a0bd4 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -86,7 +86,8 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), }, 's' => { state = State.Buf; - },'.' => { + }, + '.' => { state = State.Float; }, else => @compileError("Unknown format character: " ++ []u8{c}), diff --git a/std/os/darwin.zig b/std/os/darwin.zig index f8b1fbed3b..3cf08199b2 100644 --- a/std/os/darwin.zig +++ b/std/os/darwin.zig @@ -251,6 +251,10 @@ pub fn readlink(noalias path: &const u8, noalias buf_ptr: &u8, buf_len: usize) u return errnoWrap(c.readlink(path, buf_ptr, buf_len)); } +pub fn gettimeofday(&timeval, ?&timezone) usize { + return errnoWrap(c.gettimeofday(timeval, timezone)); +} + pub fn nanosleep(req: &const timespec, rem: ?×pec) usize { return errnoWrap(c.nanosleep(req, rem)); } diff --git a/std/os/index.zig b/std/os/index.zig index 4b74af035e..5f76c4732a 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -18,6 +18,7 @@ pub const posix = switch(builtin.os) { pub const ChildProcess = @import("child_process.zig").ChildProcess; pub const path = @import("path.zig"); pub const File = @import("file.zig").File; +pub const time = @import("time.zig"); pub const FileMode = switch (builtin.os) { Os.windows => void, @@ -1356,50 +1357,6 @@ pub fn readLink(allocator: &Allocator, pathname: []const u8) ![]u8 { } } -pub fn sleep(seconds: usize, nanoseconds: usize) void { - switch(builtin.os) { - Os.linux, Os.macosx, Os.ios => { - posixSleep(u63(seconds), u63(nanoseconds)); - }, - Os.windows => { - const milliseconds = seconds * 1000 + nanoseconds / 1000000; - windows.Sleep(windows.DWORD(milliseconds)); - }, - else => @compileError("Unsupported OS"), - } -} - -const u63 = @IntType(false, 63); -pub fn posixSleep(seconds: u63, nanoseconds: u63) void { - var req = posix.timespec { - .tv_sec = seconds, - .tv_nsec = nanoseconds, - }; - var rem: posix.timespec = undefined; - while (true) { - const ret_val = posix.nanosleep(&req, &rem); - const err = posix.getErrno(ret_val); - if (err == 0) return; - switch (err) { - posix.EFAULT => unreachable, - posix.EINVAL => { - // Sometimes Darwin returns EINVAL for no reason. - // We treat it as a spurious wakeup. - return; - }, - posix.EINTR => { - req = rem; - continue; - }, - else => return, - } - } -} - -test "os.sleep" { - sleep(0, 1); -} - pub fn posix_setuid(uid: u32) !void { const err = posix.getErrno(posix.setuid(uid)); if (err == 0) return; diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 8fd8bcbe78..dff91a500d 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -495,6 +495,26 @@ pub fn waitpid(pid: i32, status: &i32, options: i32) usize { return syscall4(SYS_wait4, @bitCast(usize, isize(pid)), @ptrToInt(status), @bitCast(usize, isize(options)), 0); } +pub fn clock_gettime(clk_id: i32, tp: ×pec) usize { + return syscall2(SYS_clock_gettime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp)); +} + +pub fn clock_getres(clk_id: i32, tp: ×pec) usize { + return syscall2(SYS_clock_getres, @bitCast(usize, isize(clk_id)), @ptrToInt(tp)); +} + +pub fn clock_settime(clk_id: i32, tp: &const timespec) usize { + return syscall2(SYS_clock_settime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp)); +} + +pub fn gettimeofday(tv: &timeval, tz: &timezone) usize { + return syscall2(SYS_gettimeofday, @ptrToInt(tv), @ptrToInt(tz)); +} + +pub fn settimeofdat(tv: &const timeval, tz: &const timezone) usize { + return syscall2(SYS_settimeofday, @ptrToInt(tv), @ptrToInt(tz)); +} + pub fn nanosleep(req: &const timespec, rem: ?×pec) usize { return syscall2(SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem)); } diff --git a/std/os/linux/x86_64.zig b/std/os/linux/x86_64.zig index cfb2231df9..0a50c67d88 100644 --- a/std/os/linux/x86_64.zig +++ b/std/os/linux/x86_64.zig @@ -489,6 +489,16 @@ pub const timespec = extern struct { tv_nsec: isize, }; +pub const timeval = extern struct { + tv_sec: isize, + tv_usec: isize, +}; + +pub const timezone = extern struct { + tz_minuteswest: i32, + tz_dsttime: i32, +}; + pub const dirent = extern struct { d_ino: usize, d_off: usize, diff --git a/std/os/windows/index.zig b/std/os/windows/index.zig index 2709cf2a78..d944af9575 100644 --- a/std/os/windows/index.zig +++ b/std/os/windows/index.zig @@ -61,6 +61,8 @@ pub extern "kernel32" stdcallcc fn GetFinalPathNameByHandleA(hFile: HANDLE, lpsz pub extern "kernel32" stdcallcc fn GetProcessHeap() ?HANDLE; +pub extern "kernel32" stdcallcc fn GetSystemTimeAsFileTime(?&FILETIME) void; + pub extern "kernel32" stdcallcc fn HeapCreate(flOptions: DWORD, dwInitialSize: SIZE_T, dwMaximumSize: SIZE_T) ?HANDLE; pub extern "kernel32" stdcallcc fn HeapDestroy(hHeap: HANDLE) BOOL; pub extern "kernel32" stdcallcc fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: &c_void, dwBytes: SIZE_T) ?&c_void; @@ -77,6 +79,10 @@ pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem pub extern "kernel32" stdcallcc fn MoveFileExA(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, dwFlags: DWORD) BOOL; + +pub extern "kernel32" stdcallcc fn QueryPerformanceCounter(lpPerformanceCount: &LARGE_INTEGER) BOOL; + +pub extern "kernel32" stdcallcc fn QueryPerformanceFrequency(lpFrequency: &LARGE_INTEGER) BOOL; pub extern "kernel32" stdcallcc fn ReadFile(in_hFile: HANDLE, out_lpBuffer: &c_void, in_nNumberOfBytesToRead: DWORD, out_lpNumberOfBytesRead: &DWORD, @@ -137,6 +143,7 @@ pub const UNICODE = false; pub const WCHAR = u16; pub const WORD = u16; pub const LARGE_INTEGER = i64; +pub const FILETIME = i64; pub const TRUE = 1; pub const FALSE = 0; -- cgit v1.2.3 From 7cfe328a16ef0d1436d8eb37980d6ebf6908a0d8 Mon Sep 17 00:00:00 2001 From: tgschultz Date: Wed, 18 Apr 2018 17:43:35 -0500 Subject: fixed typos. --- std/os/linux/index.zig | 2 +- std/os/time.zig | 20 ++++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) (limited to 'std/os/linux') diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index dff91a500d..d37cfdcf91 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -511,7 +511,7 @@ pub fn gettimeofday(tv: &timeval, tz: &timezone) usize { return syscall2(SYS_gettimeofday, @ptrToInt(tv), @ptrToInt(tz)); } -pub fn settimeofdat(tv: &const timeval, tz: &const timezone) usize { +pub fn settimeofday(tv: &const timeval, tz: &const timezone) usize { return syscall2(SYS_settimeofday, @ptrToInt(tv), @ptrToInt(tz)); } diff --git a/std/os/time.zig b/std/os/time.zig index e6b614d433..d8a432f1a3 100644 --- a/std/os/time.zig +++ b/std/os/time.zig @@ -52,18 +52,18 @@ pub fn posixSleep(seconds: u63, nanoseconds: u63) void { /// Get the posix timestamp, UTC, in seconds pub fn timestamp() u64 { - return @divFloor(miliTimestamp(), ms_per_s); + return @divFloor(milliTimestamp(), ms_per_s); } /// Get the posix timestamp, UTC, in nanoseconds -pub const miliTimestamp = switch(builtin.os) { - Os.windows => miliTimestampWindows, - Os.linux => miliTimestampPosix, - Os.macosx, Os.ios => miliTimestampDarwin, +pub const milliTimestamp = switch(builtin.os) { + Os.windows => milliTimestampWindows, + Os.linux => milliTimestampPosix, + Os.macosx, Os.ios => milliTimestampDarwin, else => @compileError("Unsupported OS"), }; -fn miliTimestampWindows() u64 { +fn milliTimestampWindows() u64 { //FileTime has a granularity of 100 nanoseconds // and uses the NTFS/Windows epoch var ft: i64 = undefined; @@ -73,7 +73,7 @@ fn miliTimestampWindows() u64 { return u64(@divFloor(ft, hns_per_ms) + epoch_adj); } -fn miliTimestampDarwin() u64 { +fn milliTimestampDarwin() u64 { //Sources suggest MacOS 10.12 has support for // posix clock_gettime. var tv: darwin.timeval = undefined; @@ -84,7 +84,7 @@ fn miliTimestampDarwin() u64 { return u64(sec_ms) + u64(usec_ms); } -fn miliTimestampPosix() u64 { +fn milliTimestampPosix() u64 { //From what I can tell there's no reason clock_gettime // should ever fail for us with CLOCK_REALTIME var ts: posix.timespec = undefined; @@ -238,9 +238,9 @@ test "os.time.timestamp" { const ns_per_ms = (ns_per_s / ms_per_s); const margin = 50; - const time_0 = miliTimestamp(); + const time_0 = milliTimestamp(); sleep(0, ns_per_ms); - const time_1 = miliTimestamp(); + const time_1 = milliTimestamp(); const interval = time_1 - time_0; debug.assert(interval > 0 and interval < margin); } -- cgit v1.2.3 From da2af9c613841552e9e47b6c9f0e9e4ee74894fb Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 22 Apr 2018 13:36:26 -0400 Subject: fixups --- std/os/index.zig | 3 +-- std/os/linux/index.zig | 7 ++++--- std/os/linux/test.zig | 2 -- std/os/windows/index.zig | 11 ++++------- 4 files changed, 9 insertions(+), 14 deletions(-) (limited to 'std/os/linux') diff --git a/std/os/index.zig b/std/os/index.zig index 8da5c05f06..1916e23db0 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -4,8 +4,7 @@ const Os = builtin.Os; const is_windows = builtin.os == Os.windows; const os = this; -comptime { - if (!builtin.is_test) return; +test "std.os" { _ = @import("child_process.zig"); _ = @import("darwin.zig"); _ = @import("darwin_errno.zig"); diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 42c19e91e6..d7924f7159 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -1309,7 +1309,8 @@ pub fn capset(hdrp: &cap_user_header_t, datap: &const cap_user_data_t) usize { return syscall2(SYS_capset, @ptrToInt(hdrp), @ptrToInt(datap)); } -comptime { - if (!builtin.is_test) return; - _ = @import("test.zig"); +test "import" { + if (builtin.os == builtin.Os.linux) { + _ = @import("test.zig"); + } } diff --git a/std/os/linux/test.zig b/std/os/linux/test.zig index f6dc6c2a52..18a6e5f19f 100644 --- a/std/os/linux/test.zig +++ b/std/os/linux/test.zig @@ -4,8 +4,6 @@ const linux = std.os.linux; const assert = std.debug.assert; test "timer" { - if (builtin.os != builtin.Os.linux) return; - const epoll_fd = linux.epoll_create(); var err = linux.getErrno(epoll_fd); assert(err == 0); diff --git a/std/os/windows/index.zig b/std/os/windows/index.zig index 4c127aba04..d6ef7205e8 100644 --- a/std/os/windows/index.zig +++ b/std/os/windows/index.zig @@ -1,10 +1,3 @@ -const builtin = @import("builtin"); -comptime { - if (!builtin.is_test) return; - _ = @import("util.zig"); -} - - pub const ERROR = @import("error.zig"); pub extern "advapi32" stdcallcc fn CryptAcquireContextA(phProv: &HCRYPTPROV, pszContainer: ?LPCSTR, @@ -324,3 +317,7 @@ pub const FILE_END = 2; pub const HEAP_CREATE_ENABLE_EXECUTE = 0x00040000; pub const HEAP_GENERATE_EXCEPTIONS = 0x00000004; pub const HEAP_NO_SERIALIZE = 0x00000001; + +test "import" { + _ = @import("util.zig"); +} -- cgit v1.2.3 From 21767144fc1a8627a109e81a164c55171c279d82 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 22 Apr 2018 18:11:50 -0400 Subject: linux: support VDSO for clock_gettime also fix a compiler crash when using cmpxchg with nullable pointer --- CMakeLists.txt | 1 + src/codegen.cpp | 10 + std/elf.zig | 611 ++++++++++++++++++++++++++++++++++++++++++++++ std/os/index.zig | 1 + std/os/linux/index.zig | 20 ++ std/os/linux/vdso.zig | 89 +++++++ std/os/linux/x86_64.zig | 8 + std/os/time.zig | 8 +- std/special/bootstrap.zig | 27 +- test/cases/atomics.zig | 20 ++ 10 files changed, 783 insertions(+), 12 deletions(-) create mode 100644 std/os/linux/vdso.zig (limited to 'std/os/linux') diff --git a/CMakeLists.txt b/CMakeLists.txt index 07e722f7b8..e692974719 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -508,6 +508,7 @@ set(ZIG_STD_FILES "os/index.zig" "os/linux/errno.zig" "os/linux/index.zig" + "os/linux/vdso.zig" "os/linux/x86_64.zig" "os/path.zig" "os/time.zig" diff --git a/src/codegen.cpp b/src/codegen.cpp index b5c8fdecac..4581c3e2b3 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -3561,6 +3561,16 @@ static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutable *executable, IrIn LLVMValueRef result_val = ZigLLVMBuildCmpXchg(g->builder, ptr_val, cmp_val, new_val, success_order, failure_order, instruction->is_weak); + TypeTableEntry *maybe_type = instruction->base.value.type; + assert(maybe_type->id == TypeTableEntryIdMaybe); + TypeTableEntry *child_type = maybe_type->data.maybe.child_type; + + if (type_is_codegen_pointer(child_type)) { + LLVMValueRef payload_val = LLVMBuildExtractValue(g->builder, result_val, 0, ""); + LLVMValueRef success_bit = LLVMBuildExtractValue(g->builder, result_val, 1, ""); + return LLVMBuildSelect(g->builder, success_bit, LLVMConstNull(child_type->type_ref), payload_val, ""); + } + assert(instruction->tmp_ptr != nullptr); assert(type_has_bits(instruction->type)); diff --git a/std/elf.zig b/std/elf.zig index 7e20fa000f..1764829bc8 100644 --- a/std/elf.zig +++ b/std/elf.zig @@ -7,6 +7,246 @@ const mem = std.mem; const debug = std.debug; const InStream = std.stream.InStream; +pub const AT_NULL = 0; +pub const AT_IGNORE = 1; +pub const AT_EXECFD = 2; +pub const AT_PHDR = 3; +pub const AT_PHENT = 4; +pub const AT_PHNUM = 5; +pub const AT_PAGESZ = 6; +pub const AT_BASE = 7; +pub const AT_FLAGS = 8; +pub const AT_ENTRY = 9; +pub const AT_NOTELF = 10; +pub const AT_UID = 11; +pub const AT_EUID = 12; +pub const AT_GID = 13; +pub const AT_EGID = 14; +pub const AT_CLKTCK = 17; +pub const AT_PLATFORM = 15; +pub const AT_HWCAP = 16; +pub const AT_FPUCW = 18; +pub const AT_DCACHEBSIZE = 19; +pub const AT_ICACHEBSIZE = 20; +pub const AT_UCACHEBSIZE = 21; +pub const AT_IGNOREPPC = 22; +pub const AT_SECURE = 23; +pub const AT_BASE_PLATFORM = 24; +pub const AT_RANDOM = 25; +pub const AT_HWCAP2 = 26; +pub const AT_EXECFN = 31; +pub const AT_SYSINFO = 32; +pub const AT_SYSINFO_EHDR = 33; +pub const AT_L1I_CACHESHAPE = 34; +pub const AT_L1D_CACHESHAPE = 35; +pub const AT_L2_CACHESHAPE = 36; +pub const AT_L3_CACHESHAPE = 37; +pub const AT_L1I_CACHESIZE = 40; +pub const AT_L1I_CACHEGEOMETRY = 41; +pub const AT_L1D_CACHESIZE = 42; +pub const AT_L1D_CACHEGEOMETRY = 43; +pub const AT_L2_CACHESIZE = 44; +pub const AT_L2_CACHEGEOMETRY = 45; +pub const AT_L3_CACHESIZE = 46; +pub const AT_L3_CACHEGEOMETRY = 47; + +pub const DT_NULL = 0; +pub const DT_NEEDED = 1; +pub const DT_PLTRELSZ = 2; +pub const DT_PLTGOT = 3; +pub const DT_HASH = 4; +pub const DT_STRTAB = 5; +pub const DT_SYMTAB = 6; +pub const DT_RELA = 7; +pub const DT_RELASZ = 8; +pub const DT_RELAENT = 9; +pub const DT_STRSZ = 10; +pub const DT_SYMENT = 11; +pub const DT_INIT = 12; +pub const DT_FINI = 13; +pub const DT_SONAME = 14; +pub const DT_RPATH = 15; +pub const DT_SYMBOLIC = 16; +pub const DT_REL = 17; +pub const DT_RELSZ = 18; +pub const DT_RELENT = 19; +pub const DT_PLTREL = 20; +pub const DT_DEBUG = 21; +pub const DT_TEXTREL = 22; +pub const DT_JMPREL = 23; +pub const DT_BIND_NOW = 24; +pub const DT_INIT_ARRAY = 25; +pub const DT_FINI_ARRAY = 26; +pub const DT_INIT_ARRAYSZ = 27; +pub const DT_FINI_ARRAYSZ = 28; +pub const DT_RUNPATH = 29; +pub const DT_FLAGS = 30; +pub const DT_ENCODING = 32; +pub const DT_PREINIT_ARRAY = 32; +pub const DT_PREINIT_ARRAYSZ = 33; +pub const DT_SYMTAB_SHNDX = 34; +pub const DT_NUM = 35; +pub const DT_LOOS = 0x6000000d; +pub const DT_HIOS = 0x6ffff000; +pub const DT_LOPROC = 0x70000000; +pub const DT_HIPROC = 0x7fffffff; +pub const DT_PROCNUM = DT_MIPS_NUM; + +pub const DT_VALRNGLO = 0x6ffffd00; +pub const DT_GNU_PRELINKED = 0x6ffffdf5; +pub const DT_GNU_CONFLICTSZ = 0x6ffffdf6; +pub const DT_GNU_LIBLISTSZ = 0x6ffffdf7; +pub const DT_CHECKSUM = 0x6ffffdf8; +pub const DT_PLTPADSZ = 0x6ffffdf9; +pub const DT_MOVEENT = 0x6ffffdfa; +pub const DT_MOVESZ = 0x6ffffdfb; +pub const DT_FEATURE_1 = 0x6ffffdfc; +pub const DT_POSFLAG_1 = 0x6ffffdfd; + +pub const DT_SYMINSZ = 0x6ffffdfe; +pub const DT_SYMINENT = 0x6ffffdff; +pub const DT_VALRNGHI = 0x6ffffdff; +pub const DT_VALNUM = 12; + +pub const DT_ADDRRNGLO = 0x6ffffe00; +pub const DT_GNU_HASH = 0x6ffffef5; +pub const DT_TLSDESC_PLT = 0x6ffffef6; +pub const DT_TLSDESC_GOT = 0x6ffffef7; +pub const DT_GNU_CONFLICT = 0x6ffffef8; +pub const DT_GNU_LIBLIST = 0x6ffffef9; +pub const DT_CONFIG = 0x6ffffefa; +pub const DT_DEPAUDIT = 0x6ffffefb; +pub const DT_AUDIT = 0x6ffffefc; +pub const DT_PLTPAD = 0x6ffffefd; +pub const DT_MOVETAB = 0x6ffffefe; +pub const DT_SYMINFO = 0x6ffffeff; +pub const DT_ADDRRNGHI = 0x6ffffeff; +pub const DT_ADDRNUM = 11; + + +pub const DT_VERSYM = 0x6ffffff0; + +pub const DT_RELACOUNT = 0x6ffffff9; +pub const DT_RELCOUNT = 0x6ffffffa; + + +pub const DT_FLAGS_1 = 0x6ffffffb; +pub const DT_VERDEF = 0x6ffffffc; + +pub const DT_VERDEFNUM = 0x6ffffffd; +pub const DT_VERNEED = 0x6ffffffe; + +pub const DT_VERNEEDNUM = 0x6fffffff; +pub const DT_VERSIONTAGNUM = 16; + + + +pub const DT_AUXILIARY = 0x7ffffffd; +pub const DT_FILTER = 0x7fffffff; +pub const DT_EXTRANUM = 3; + + +pub const DT_SPARC_REGISTER = 0x70000001; +pub const DT_SPARC_NUM = 2; + +pub const DT_MIPS_RLD_VERSION = 0x70000001; +pub const DT_MIPS_TIME_STAMP = 0x70000002; +pub const DT_MIPS_ICHECKSUM = 0x70000003; +pub const DT_MIPS_IVERSION = 0x70000004; +pub const DT_MIPS_FLAGS = 0x70000005; +pub const DT_MIPS_BASE_ADDRESS = 0x70000006; +pub const DT_MIPS_MSYM = 0x70000007; +pub const DT_MIPS_CONFLICT = 0x70000008; +pub const DT_MIPS_LIBLIST = 0x70000009; +pub const DT_MIPS_LOCAL_GOTNO = 0x7000000a; +pub const DT_MIPS_CONFLICTNO = 0x7000000b; +pub const DT_MIPS_LIBLISTNO = 0x70000010; +pub const DT_MIPS_SYMTABNO = 0x70000011; +pub const DT_MIPS_UNREFEXTNO = 0x70000012; +pub const DT_MIPS_GOTSYM = 0x70000013; +pub const DT_MIPS_HIPAGENO = 0x70000014; +pub const DT_MIPS_RLD_MAP = 0x70000016; +pub const DT_MIPS_DELTA_CLASS = 0x70000017; +pub const DT_MIPS_DELTA_CLASS_NO = 0x70000018; + +pub const DT_MIPS_DELTA_INSTANCE = 0x70000019; +pub const DT_MIPS_DELTA_INSTANCE_NO = 0x7000001a; + +pub const DT_MIPS_DELTA_RELOC = 0x7000001b; +pub const DT_MIPS_DELTA_RELOC_NO = 0x7000001c; + +pub const DT_MIPS_DELTA_SYM = 0x7000001d; + +pub const DT_MIPS_DELTA_SYM_NO = 0x7000001e; + +pub const DT_MIPS_DELTA_CLASSSYM = 0x70000020; + +pub const DT_MIPS_DELTA_CLASSSYM_NO = 0x70000021; + +pub const DT_MIPS_CXX_FLAGS = 0x70000022; +pub const DT_MIPS_PIXIE_INIT = 0x70000023; +pub const DT_MIPS_SYMBOL_LIB = 0x70000024; +pub const DT_MIPS_LOCALPAGE_GOTIDX = 0x70000025; +pub const DT_MIPS_LOCAL_GOTIDX = 0x70000026; +pub const DT_MIPS_HIDDEN_GOTIDX = 0x70000027; +pub const DT_MIPS_PROTECTED_GOTIDX = 0x70000028; +pub const DT_MIPS_OPTIONS = 0x70000029; +pub const DT_MIPS_INTERFACE = 0x7000002a; +pub const DT_MIPS_DYNSTR_ALIGN = 0x7000002b; +pub const DT_MIPS_INTERFACE_SIZE = 0x7000002c; +pub const DT_MIPS_RLD_TEXT_RESOLVE_ADDR = 0x7000002d; + +pub const DT_MIPS_PERF_SUFFIX = 0x7000002e; + +pub const DT_MIPS_COMPACT_SIZE = 0x7000002f; +pub const DT_MIPS_GP_VALUE = 0x70000030; +pub const DT_MIPS_AUX_DYNAMIC = 0x70000031; + +pub const DT_MIPS_PLTGOT = 0x70000032; + +pub const DT_MIPS_RWPLT = 0x70000034; +pub const DT_MIPS_RLD_MAP_REL = 0x70000035; +pub const DT_MIPS_NUM = 0x36; + +pub const DT_ALPHA_PLTRO = (DT_LOPROC + 0); +pub const DT_ALPHA_NUM = 1; + +pub const DT_PPC_GOT = (DT_LOPROC + 0); +pub const DT_PPC_OPT = (DT_LOPROC + 1); +pub const DT_PPC_NUM = 2; + +pub const DT_PPC64_GLINK = (DT_LOPROC + 0); +pub const DT_PPC64_OPD = (DT_LOPROC + 1); +pub const DT_PPC64_OPDSZ = (DT_LOPROC + 2); +pub const DT_PPC64_OPT = (DT_LOPROC + 3); +pub const DT_PPC64_NUM = 4; + +pub const DT_IA_64_PLT_RESERVE = (DT_LOPROC + 0); +pub const DT_IA_64_NUM = 1; + +pub const DT_NIOS2_GP = 0x70000002; + +pub const PT_NULL = 0; +pub const PT_LOAD = 1; +pub const PT_DYNAMIC = 2; +pub const PT_INTERP = 3; +pub const PT_NOTE = 4; +pub const PT_SHLIB = 5; +pub const PT_PHDR = 6; +pub const PT_TLS = 7; +pub const PT_NUM = 8; +pub const PT_LOOS = 0x60000000; +pub const PT_GNU_EH_FRAME = 0x6474e550; +pub const PT_GNU_STACK = 0x6474e551; +pub const PT_GNU_RELRO = 0x6474e552; +pub const PT_LOSUNW = 0x6ffffffa; +pub const PT_SUNWBSS = 0x6ffffffa; +pub const PT_SUNWSTACK = 0x6ffffffb; +pub const PT_HISUNW = 0x6fffffff; +pub const PT_HIOS = 0x6fffffff; +pub const PT_LOPROC = 0x70000000; +pub const PT_HIPROC = 0x7fffffff; + pub const SHT_NULL = 0; pub const SHT_PROGBITS = 1; pub const SHT_SYMTAB = 2; @@ -31,6 +271,45 @@ pub const SHT_HIPROC = 0x7fffffff; pub const SHT_LOUSER = 0x80000000; pub const SHT_HIUSER = 0xffffffff; +pub const STB_LOCAL = 0; +pub const STB_GLOBAL = 1; +pub const STB_WEAK = 2; +pub const STB_NUM = 3; +pub const STB_LOOS = 10; +pub const STB_GNU_UNIQUE = 10; +pub const STB_HIOS = 12; +pub const STB_LOPROC = 13; +pub const STB_HIPROC = 15; + +pub const STB_MIPS_SPLIT_COMMON = 13; + +pub const STT_NOTYPE = 0; +pub const STT_OBJECT = 1; +pub const STT_FUNC = 2; +pub const STT_SECTION = 3; +pub const STT_FILE = 4; +pub const STT_COMMON = 5; +pub const STT_TLS = 6; +pub const STT_NUM = 7; +pub const STT_LOOS = 10; +pub const STT_GNU_IFUNC = 10; +pub const STT_HIOS = 12; +pub const STT_LOPROC = 13; +pub const STT_HIPROC = 15; + +pub const STT_SPARC_REGISTER = 13; + +pub const STT_PARISC_MILLICODE = 13; + +pub const STT_HP_OPAQUE = (STT_LOOS + 0x1); +pub const STT_HP_STUB = (STT_LOOS + 0x2); + +pub const STT_ARM_TFUNC = STT_LOPROC; +pub const STT_ARM_16BIT = STT_HIPROC; + +pub const VER_FLG_BASE = 0x1; +pub const VER_FLG_WEAK = 0x2; + pub const FileType = enum { Relocatable, Executable, @@ -266,3 +545,335 @@ pub const Elf = struct { try elf.in_file.seekTo(elf_section.offset); } }; + +pub const EI_NIDENT = 16; +pub const Elf32_Half = u16; +pub const Elf64_Half = u16; +pub const Elf32_Word = u32; +pub const Elf32_Sword = i32; +pub const Elf64_Word = u32; +pub const Elf64_Sword = i32; +pub const Elf32_Xword = u64; +pub const Elf32_Sxword = i64; +pub const Elf64_Xword = u64; +pub const Elf64_Sxword = i64; +pub const Elf32_Addr = u32; +pub const Elf64_Addr = u64; +pub const Elf32_Off = u32; +pub const Elf64_Off = u64; +pub const Elf32_Section = u16; +pub const Elf64_Section = u16; +pub const Elf32_Versym = Elf32_Half; +pub const Elf64_Versym = Elf64_Half; +pub const Elf32_Ehdr = extern struct { + e_ident: [EI_NIDENT]u8, + e_type: Elf32_Half, + e_machine: Elf32_Half, + e_version: Elf32_Word, + e_entry: Elf32_Addr, + e_phoff: Elf32_Off, + e_shoff: Elf32_Off, + e_flags: Elf32_Word, + e_ehsize: Elf32_Half, + e_phentsize: Elf32_Half, + e_phnum: Elf32_Half, + e_shentsize: Elf32_Half, + e_shnum: Elf32_Half, + e_shstrndx: Elf32_Half, +}; +pub const Elf64_Ehdr = extern struct { + e_ident: [EI_NIDENT]u8, + e_type: Elf64_Half, + e_machine: Elf64_Half, + e_version: Elf64_Word, + e_entry: Elf64_Addr, + e_phoff: Elf64_Off, + e_shoff: Elf64_Off, + e_flags: Elf64_Word, + e_ehsize: Elf64_Half, + e_phentsize: Elf64_Half, + e_phnum: Elf64_Half, + e_shentsize: Elf64_Half, + e_shnum: Elf64_Half, + e_shstrndx: Elf64_Half, +}; +pub const Elf32_Shdr = extern struct { + sh_name: Elf32_Word, + sh_type: Elf32_Word, + sh_flags: Elf32_Word, + sh_addr: Elf32_Addr, + sh_offset: Elf32_Off, + sh_size: Elf32_Word, + sh_link: Elf32_Word, + sh_info: Elf32_Word, + sh_addralign: Elf32_Word, + sh_entsize: Elf32_Word, +}; +pub const Elf64_Shdr = extern struct { + sh_name: Elf64_Word, + sh_type: Elf64_Word, + sh_flags: Elf64_Xword, + sh_addr: Elf64_Addr, + sh_offset: Elf64_Off, + sh_size: Elf64_Xword, + sh_link: Elf64_Word, + sh_info: Elf64_Word, + sh_addralign: Elf64_Xword, + sh_entsize: Elf64_Xword, +}; +pub const Elf32_Chdr = extern struct { + ch_type: Elf32_Word, + ch_size: Elf32_Word, + ch_addralign: Elf32_Word, +}; +pub const Elf64_Chdr = extern struct { + ch_type: Elf64_Word, + ch_reserved: Elf64_Word, + ch_size: Elf64_Xword, + ch_addralign: Elf64_Xword, +}; +pub const Elf32_Sym = extern struct { + st_name: Elf32_Word, + st_value: Elf32_Addr, + st_size: Elf32_Word, + st_info: u8, + st_other: u8, + st_shndx: Elf32_Section, +}; +pub const Elf64_Sym = extern struct { + st_name: Elf64_Word, + st_info: u8, + st_other: u8, + st_shndx: Elf64_Section, + st_value: Elf64_Addr, + st_size: Elf64_Xword, +}; +pub const Elf32_Syminfo = extern struct { + si_boundto: Elf32_Half, + si_flags: Elf32_Half, +}; +pub const Elf64_Syminfo = extern struct { + si_boundto: Elf64_Half, + si_flags: Elf64_Half, +}; +pub const Elf32_Rel = extern struct { + r_offset: Elf32_Addr, + r_info: Elf32_Word, +}; +pub const Elf64_Rel = extern struct { + r_offset: Elf64_Addr, + r_info: Elf64_Xword, +}; +pub const Elf32_Rela = extern struct { + r_offset: Elf32_Addr, + r_info: Elf32_Word, + r_addend: Elf32_Sword, +}; +pub const Elf64_Rela = extern struct { + r_offset: Elf64_Addr, + r_info: Elf64_Xword, + r_addend: Elf64_Sxword, +}; +pub const Elf32_Phdr = extern struct { + p_type: Elf32_Word, + p_offset: Elf32_Off, + p_vaddr: Elf32_Addr, + p_paddr: Elf32_Addr, + p_filesz: Elf32_Word, + p_memsz: Elf32_Word, + p_flags: Elf32_Word, + p_align: Elf32_Word, +}; +pub const Elf64_Phdr = extern struct { + p_type: Elf64_Word, + p_flags: Elf64_Word, + p_offset: Elf64_Off, + p_vaddr: Elf64_Addr, + p_paddr: Elf64_Addr, + p_filesz: Elf64_Xword, + p_memsz: Elf64_Xword, + p_align: Elf64_Xword, +}; +pub const Elf32_Dyn = extern struct { + d_tag: Elf32_Sword, + d_un: extern union { + d_val: Elf32_Word, + d_ptr: Elf32_Addr, + }, +}; +pub const Elf64_Dyn = extern struct { + d_tag: Elf64_Sxword, + d_un: extern union { + d_val: Elf64_Xword, + d_ptr: Elf64_Addr, + }, +}; +pub const Elf32_Verdef = extern struct { + vd_version: Elf32_Half, + vd_flags: Elf32_Half, + vd_ndx: Elf32_Half, + vd_cnt: Elf32_Half, + vd_hash: Elf32_Word, + vd_aux: Elf32_Word, + vd_next: Elf32_Word, +}; +pub const Elf64_Verdef = extern struct { + vd_version: Elf64_Half, + vd_flags: Elf64_Half, + vd_ndx: Elf64_Half, + vd_cnt: Elf64_Half, + vd_hash: Elf64_Word, + vd_aux: Elf64_Word, + vd_next: Elf64_Word, +}; +pub const Elf32_Verdaux = extern struct { + vda_name: Elf32_Word, + vda_next: Elf32_Word, +}; +pub const Elf64_Verdaux = extern struct { + vda_name: Elf64_Word, + vda_next: Elf64_Word, +}; +pub const Elf32_Verneed = extern struct { + vn_version: Elf32_Half, + vn_cnt: Elf32_Half, + vn_file: Elf32_Word, + vn_aux: Elf32_Word, + vn_next: Elf32_Word, +}; +pub const Elf64_Verneed = extern struct { + vn_version: Elf64_Half, + vn_cnt: Elf64_Half, + vn_file: Elf64_Word, + vn_aux: Elf64_Word, + vn_next: Elf64_Word, +}; +pub const Elf32_Vernaux = extern struct { + vna_hash: Elf32_Word, + vna_flags: Elf32_Half, + vna_other: Elf32_Half, + vna_name: Elf32_Word, + vna_next: Elf32_Word, +}; +pub const Elf64_Vernaux = extern struct { + vna_hash: Elf64_Word, + vna_flags: Elf64_Half, + vna_other: Elf64_Half, + vna_name: Elf64_Word, + vna_next: Elf64_Word, +}; +pub const Elf32_auxv_t = extern struct { + a_type: u32, + a_un: extern union { + a_val: u32, + }, +}; +pub const Elf64_auxv_t = extern struct { + a_type: u64, + a_un: extern union { + a_val: u64, + }, +}; +pub const Elf32_Nhdr = extern struct { + n_namesz: Elf32_Word, + n_descsz: Elf32_Word, + n_type: Elf32_Word, +}; +pub const Elf64_Nhdr = extern struct { + n_namesz: Elf64_Word, + n_descsz: Elf64_Word, + n_type: Elf64_Word, +}; +pub const Elf32_Move = extern struct { + m_value: Elf32_Xword, + m_info: Elf32_Word, + m_poffset: Elf32_Word, + m_repeat: Elf32_Half, + m_stride: Elf32_Half, +}; +pub const Elf64_Move = extern struct { + m_value: Elf64_Xword, + m_info: Elf64_Xword, + m_poffset: Elf64_Xword, + m_repeat: Elf64_Half, + m_stride: Elf64_Half, +}; +pub const Elf32_gptab = extern union { + gt_header: extern struct { + gt_current_g_value: Elf32_Word, + gt_unused: Elf32_Word, + }, + gt_entry: extern struct { + gt_g_value: Elf32_Word, + gt_bytes: Elf32_Word, + }, +}; +pub const Elf32_RegInfo = extern struct { + ri_gprmask: Elf32_Word, + ri_cprmask: [4]Elf32_Word, + ri_gp_value: Elf32_Sword, +}; +pub const Elf_Options = extern struct { + kind: u8, + size: u8, + @"section": Elf32_Section, + info: Elf32_Word, +}; +pub const Elf_Options_Hw = extern struct { + hwp_flags1: Elf32_Word, + hwp_flags2: Elf32_Word, +}; +pub const Elf32_Lib = extern struct { + l_name: Elf32_Word, + l_time_stamp: Elf32_Word, + l_checksum: Elf32_Word, + l_version: Elf32_Word, + l_flags: Elf32_Word, +}; +pub const Elf64_Lib = extern struct { + l_name: Elf64_Word, + l_time_stamp: Elf64_Word, + l_checksum: Elf64_Word, + l_version: Elf64_Word, + l_flags: Elf64_Word, +}; +pub const Elf32_Conflict = Elf32_Addr; +pub const Elf_MIPS_ABIFlags_v0 = extern struct { + version: Elf32_Half, + isa_level: u8, + isa_rev: u8, + gpr_size: u8, + cpr1_size: u8, + cpr2_size: u8, + fp_abi: u8, + isa_ext: Elf32_Word, + ases: Elf32_Word, + flags1: Elf32_Word, + flags2: Elf32_Word, +}; + +pub const Ehdr = switch(@sizeOf(usize)) { + 4 => Elf32_Ehdr, + 8 => Elf64_Ehdr, + else => @compileError("expected pointer size of 32 or 64"), +}; +pub const Phdr = switch(@sizeOf(usize)) { + 4 => Elf32_Phdr, + 8 => Elf64_Phdr, + else => @compileError("expected pointer size of 32 or 64"), +}; +pub const Sym = switch(@sizeOf(usize)) { + 4 => Elf32_Sym, + 8 => Elf64_Sym, + else => @compileError("expected pointer size of 32 or 64"), +}; +pub const Verdef = switch(@sizeOf(usize)) { + 4 => Elf32_Verdef, + 8 => Elf64_Verdef, + else => @compileError("expected pointer size of 32 or 64"), +}; +pub const Verdaux = switch(@sizeOf(usize)) { + 4 => Elf32_Verdaux, + 8 => Elf64_Verdaux, + else => @compileError("expected pointer size of 32 or 64"), +}; diff --git a/std/os/index.zig b/std/os/index.zig index 1916e23db0..0639490725 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -478,6 +478,7 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError { }; } +pub var linux_aux_raw = []usize{0} ** 38; pub var posix_environ_raw: []&u8 = undefined; /// Caller must free result when done. diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index d7924f7159..dcd9532d1d 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -1,6 +1,7 @@ const std = @import("../../index.zig"); const assert = std.debug.assert; const builtin = @import("builtin"); +const vdso = @import("vdso.zig"); pub use switch (builtin.arch) { builtin.Arch.x86_64 => @import("x86_64.zig"), builtin.Arch.i386 => @import("i386.zig"), @@ -806,8 +807,27 @@ pub fn waitpid(pid: i32, status: &i32, options: i32) usize { } pub fn clock_gettime(clk_id: i32, tp: ×pec) usize { + if (VDSO_CGT_SYM.len != 0) { + const f = @atomicLoad(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, builtin.AtomicOrder.Unordered); + if (@ptrToInt(f) != 0) { + const rc = f(clk_id, tp); + switch (rc) { + 0, @bitCast(usize, isize(-EINVAL)) => return rc, + else => {}, + } + } + } return syscall2(SYS_clock_gettime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp)); } +var vdso_clock_gettime = init_vdso_clock_gettime; +extern fn init_vdso_clock_gettime(clk: i32, ts: ×pec) usize { + const addr = vdso.lookup(VDSO_CGT_VER, VDSO_CGT_SYM); + var f = @intToPtr(@typeOf(init_vdso_clock_gettime), addr); + _ = @cmpxchgStrong(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, init_vdso_clock_gettime, f, + builtin.AtomicOrder.Monotonic, builtin.AtomicOrder.Monotonic); + if (@ptrToInt(f) == 0) return @bitCast(usize, isize(-ENOSYS)); + return f(clk, ts); +} pub fn clock_getres(clk_id: i32, tp: ×pec) usize { return syscall2(SYS_clock_getres, @bitCast(usize, isize(clk_id)), @ptrToInt(tp)); diff --git a/std/os/linux/vdso.zig b/std/os/linux/vdso.zig new file mode 100644 index 0000000000..f4fb513af9 --- /dev/null +++ b/std/os/linux/vdso.zig @@ -0,0 +1,89 @@ +const std = @import("../../index.zig"); +const elf = std.elf; +const linux = std.os.linux; +const cstr = std.cstr; +const mem = std.mem; + +pub fn lookup(vername: []const u8, name: []const u8) usize { + const vdso_addr = std.os.linux_aux_raw[std.elf.AT_SYSINFO_EHDR]; + if (vdso_addr == 0) return 0; + + const eh = @intToPtr(&elf.Ehdr, vdso_addr); + var ph_addr: usize = vdso_addr + eh.e_phoff; + const ph = @intToPtr(&elf.Phdr, ph_addr); + + var maybe_dynv: ?&usize = null; + var base: usize = @maxValue(usize); + { + var i: usize = 0; + while (i < eh.e_phnum) : ({i += 1; ph_addr += eh.e_phentsize;}) { + const this_ph = @intToPtr(&elf.Phdr, ph_addr); + switch (this_ph.p_type) { + elf.PT_LOAD => base = vdso_addr + this_ph.p_offset - this_ph.p_vaddr, + elf.PT_DYNAMIC => maybe_dynv = @intToPtr(&usize, vdso_addr + this_ph.p_offset), + else => {}, + } + } + } + const dynv = maybe_dynv ?? return 0; + if (base == @maxValue(usize)) return 0; + + var maybe_strings: ?&u8 = null; + var maybe_syms: ?&elf.Sym = null; + var maybe_hashtab: ?&linux.Elf_Symndx = null; + var maybe_versym: ?&u16 = null; + var maybe_verdef: ?&elf.Verdef = null; + + { + var i: usize = 0; + while (dynv[i] != 0) : (i += 2) { + const p = base + dynv[i + 1]; + switch (dynv[i]) { + elf.DT_STRTAB => maybe_strings = @intToPtr(&u8, p), + elf.DT_SYMTAB => maybe_syms = @intToPtr(&elf.Sym, p), + elf.DT_HASH => maybe_hashtab = @intToPtr(&linux.Elf_Symndx, p), + elf.DT_VERSYM => maybe_versym = @intToPtr(&u16, p), + elf.DT_VERDEF => maybe_verdef = @intToPtr(&elf.Verdef, p), + else => {}, + } + } + } + + const strings = maybe_strings ?? return 0; + const syms = maybe_syms ?? return 0; + const hashtab = maybe_hashtab ?? return 0; + if (maybe_verdef == null) maybe_versym = null; + + + const OK_TYPES = (1<>4) & OK_BINDS)) continue; + if (0==syms[i].st_shndx) continue; + if (!mem.eql(u8, name, cstr.toSliceConst(&strings[syms[i].st_name]))) continue; + if (maybe_versym) |versym| { + if (!checkver(??maybe_verdef, versym[i], vername, strings)) + continue; + } + return base + syms[i].st_value; + } + + return 0; +} + +fn checkver(def_arg: &elf.Verdef, vsym_arg: i32, vername: []const u8, strings: &u8) bool { + var def = def_arg; + const vsym = @bitCast(u32, vsym_arg) & 0x7fff; + while (true) { + if (0==(def.vd_flags & elf.VER_FLG_BASE) and (def.vd_ndx & 0x7fff) == vsym) + break; + if (def.vd_next == 0) + return false; + def = @intToPtr(&elf.Verdef, @ptrToInt(def) + def.vd_next); + } + const aux = @intToPtr(&elf.Verdaux, @ptrToInt(def ) + def.vd_aux); + return mem.eql(u8, vername, cstr.toSliceConst(&strings[aux.vda_name])); +} diff --git a/std/os/linux/x86_64.zig b/std/os/linux/x86_64.zig index bfc27b0f38..544b2365ce 100644 --- a/std/os/linux/x86_64.zig +++ b/std/os/linux/x86_64.zig @@ -371,6 +371,13 @@ pub const F_GETOWN_EX = 16; pub const F_GETOWNER_UIDS = 17; + +pub const VDSO_USEFUL = true; +pub const VDSO_CGT_SYM = "__vdso_clock_gettime"; +pub const VDSO_CGT_VER = "LINUX_2.6"; +pub const VDSO_GETCPU_SYM = "__vdso_getcpu"; +pub const VDSO_GETCPU_VER = "LINUX_2.6"; + pub fn syscall0(number: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) @@ -509,3 +516,4 @@ pub const dirent = extern struct { d_name: u8, // field address is the address of first byte of name }; +pub const Elf_Symndx = u32; diff --git a/std/os/time.zig b/std/os/time.zig index 8a906d7954..e9fbf9798c 100644 --- a/std/os/time.zig +++ b/std/os/time.zig @@ -160,13 +160,13 @@ pub const Timer = struct { Os.windows => { var freq: i64 = undefined; var err = windows.QueryPerformanceFrequency(&freq); - if (err == 0) return error.TimerUnsupported; + if (err == windows.FALSE) return error.TimerUnsupported; self.frequency = u64(freq); self.resolution = @divFloor(ns_per_s, self.frequency); var start_time: i64 = undefined; err = windows.QueryPerformanceCounter(&start_time); - debug.assert(err != 0); + debug.assert(err != windows.FALSE); self.start_time = u64(start_time); }, Os.linux => { @@ -236,7 +236,7 @@ pub const Timer = struct { fn clockWindows() u64 { var result: i64 = undefined; var err = windows.QueryPerformanceCounter(&result); - debug.assert(err != 0); + debug.assert(err != windows.FALSE); return u64(result); } @@ -285,4 +285,4 @@ test "os.time.Timer" { timer.reset(); debug.assert(timer.read() < time_1); -} \ No newline at end of file +} diff --git a/std/special/bootstrap.zig b/std/special/bootstrap.zig index d2c22c13e1..1dc7e24869 100644 --- a/std/special/bootstrap.zig +++ b/std/special/bootstrap.zig @@ -48,22 +48,33 @@ extern fn WinMainCRTStartup() noreturn { fn posixCallMainAndExit() noreturn { const argc = *argc_ptr; const argv = @ptrCast(&&u8, &argc_ptr[1]); - const envp = @ptrCast(&?&u8, &argv[argc + 1]); + const envp_nullable = @ptrCast(&?&u8, &argv[argc + 1]); + var envp_count: usize = 0; + while (envp_nullable[envp_count]) |_| : (envp_count += 1) {} + const envp = @ptrCast(&&u8, envp_nullable)[0..envp_count]; + if (builtin.os == builtin.Os.linux) { + const auxv = &@ptrCast(&usize, envp.ptr)[envp_count + 1]; + var i: usize = 0; + while (auxv[i] != 0) : (i += 2) { + if (auxv[i] < std.os.linux_aux_raw.len) std.os.linux_aux_raw[auxv[i]] = auxv[i+1]; + } + std.debug.assert(std.os.linux_aux_raw[std.elf.AT_PAGESZ] == std.os.page_size); + } + std.os.posix.exit(callMainWithArgs(argc, argv, envp)); } -fn callMainWithArgs(argc: usize, argv: &&u8, envp: &?&u8) u8 { +fn callMainWithArgs(argc: usize, argv: &&u8, envp: []&u8) u8 { std.os.ArgIteratorPosix.raw = argv[0..argc]; - - var env_count: usize = 0; - while (envp[env_count] != null) : (env_count += 1) {} - std.os.posix_environ_raw = @ptrCast(&&u8, envp)[0..env_count]; - + std.os.posix_environ_raw = envp; return callMain(); } extern fn main(c_argc: i32, c_argv: &&u8, c_envp: &?&u8) i32 { - return callMainWithArgs(usize(c_argc), c_argv, c_envp); + var env_count: usize = 0; + while (c_envp[env_count] != null) : (env_count += 1) {} + const envp = @ptrCast(&&u8, c_envp)[0..env_count]; + return callMainWithArgs(usize(c_argc), c_argv, envp); } fn callMain() u8 { diff --git a/test/cases/atomics.zig b/test/cases/atomics.zig index 4cadabb728..d406285d29 100644 --- a/test/cases/atomics.zig +++ b/test/cases/atomics.zig @@ -49,3 +49,23 @@ fn testAtomicLoad(ptr: &u8) void { const x = @atomicLoad(u8, ptr, AtomicOrder.SeqCst); assert(x == 42); } + +test "cmpxchg with ptr" { + var data1: i32 = 1234; + var data2: i32 = 5678; + var data3: i32 = 9101; + var x: &i32 = &data1; + if (@cmpxchgWeak(&i32, &x, &data2, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| { + assert(x1 == &data1); + } else { + @panic("cmpxchg should have failed"); + } + + while (@cmpxchgWeak(&i32, &x, &data1, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| { + assert(x1 == &data1); + } + assert(x == &data3); + + assert(@cmpxchgStrong(&i32, &x, &data3, &data2, AtomicOrder.SeqCst, AtomicOrder.SeqCst) == null); + assert(x == &data2); +} -- cgit v1.2.3 From b21bcbd7755d236a313c06e6ff167f5395ab8ed4 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 29 Apr 2018 02:52:04 -0400 Subject: fix std threads for macos --- std/heap.zig | 6 +++--- std/os/darwin.zig | 8 ++++---- std/os/index.zig | 6 ++++-- std/os/linux/index.zig | 6 +++--- 4 files changed, 14 insertions(+), 12 deletions(-) (limited to 'std/os/linux') diff --git a/std/heap.zig b/std/heap.zig index d632b44cd1..bfdf62f658 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -91,7 +91,7 @@ pub const DirectAllocator = struct { const unused_start = addr; const unused_len = aligned_addr - 1 - unused_start; - var err = p.munmap(@intToPtr(&u8, unused_start), unused_len); + var err = p.munmap(unused_start, unused_len); debug.assert(p.getErrno(err) == 0); //It is impossible that there is an unoccupied page at the top of our @@ -132,7 +132,7 @@ pub const DirectAllocator = struct { const rem = @rem(new_addr_end, os.page_size); const new_addr_end_rounded = new_addr_end + if (rem == 0) 0 else (os.page_size - rem); if (old_addr_end > new_addr_end_rounded) { - _ = os.posix.munmap(@intToPtr(&u8, new_addr_end_rounded), old_addr_end - new_addr_end_rounded); + _ = os.posix.munmap(new_addr_end_rounded, old_addr_end - new_addr_end_rounded); } return old_mem[0..new_size]; } @@ -170,7 +170,7 @@ pub const DirectAllocator = struct { switch (builtin.os) { Os.linux, Os.macosx, Os.ios => { - _ = os.posix.munmap(bytes.ptr, bytes.len); + _ = os.posix.munmap(@ptrToInt(bytes.ptr), bytes.len); }, Os.windows => { const record_addr = @ptrToInt(bytes.ptr) + bytes.len; diff --git a/std/os/darwin.zig b/std/os/darwin.zig index 44418649ab..0a62b03ab2 100644 --- a/std/os/darwin.zig +++ b/std/os/darwin.zig @@ -184,7 +184,7 @@ pub fn write(fd: i32, buf: &const u8, nbyte: usize) usize { return errnoWrap(c.write(fd, @ptrCast(&const c_void, buf), nbyte)); } -pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: usize, fd: i32, +pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { const ptr_result = c.mmap(@ptrCast(&c_void, address), length, @@ -193,8 +193,8 @@ pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: usize, fd: i32, return errnoWrap(isize_result); } -pub fn munmap(address: &u8, length: usize) usize { - return errnoWrap(c.munmap(@ptrCast(&c_void, address), length)); +pub fn munmap(address: usize, length: usize) usize { + return errnoWrap(c.munmap(@intToPtr(&c_void, address), length)); } pub fn unlink(path: &const u8) usize { @@ -341,4 +341,4 @@ pub const timeval = c.timeval; pub const mach_timebase_info_data = c.mach_timebase_info_data; pub const mach_absolute_time = c.mach_absolute_time; -pub const mach_timebase_info = c.mach_timebase_info; \ No newline at end of file +pub const mach_timebase_info = c.mach_timebase_info; diff --git a/std/os/index.zig b/std/os/index.zig index 6842fd0fb3..5053a1b016 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -2497,11 +2497,13 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread } }; + const MAP_GROWSDOWN = if (builtin.os == builtin.Os.linux) linux.MAP_GROWSDOWN else 0; + const stack_len = default_stack_size; const stack_addr = posix.mmap(null, stack_len, posix.PROT_READ|posix.PROT_WRITE, - posix.MAP_PRIVATE|posix.MAP_ANONYMOUS|posix.MAP_GROWSDOWN, -1, 0); + posix.MAP_PRIVATE|posix.MAP_ANONYMOUS|MAP_GROWSDOWN, -1, 0); if (stack_addr == posix.MAP_FAILED) return error.OutOfMemory; - errdefer _ = posix.munmap(stack_addr, stack_len); + errdefer assert(posix.munmap(stack_addr, stack_len) == 0); var stack_end: usize = stack_addr + stack_len; var arg: usize = undefined; diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index dcd9532d1d..368f074b9b 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -706,13 +706,13 @@ pub fn umount2(special: &const u8, flags: u32) usize { return syscall2(SYS_umount2, @ptrToInt(special), flags); } -pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: usize, fd: i32, offset: isize) usize { +pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), @bitCast(usize, offset)); } -pub fn munmap(address: &u8, length: usize) usize { - return syscall2(SYS_munmap, @ptrToInt(address), length); +pub fn munmap(address: usize, length: usize) usize { + return syscall2(SYS_munmap, address, length); } pub fn read(fd: i32, buf: &u8, count: usize) usize { -- cgit v1.2.3 From ac4d55dec1e32ddef945bfa246eb78f20f31ec44 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 1 May 2018 01:53:04 -0400 Subject: behavior tests passing with new pointer deref syntax --- std/array_list.zig | 54 ++- std/fmt/index.zig | 93 ++-- std/heap.zig | 106 +++-- std/io.zig | 65 +-- std/linked_list.zig | 95 ++-- std/os/index.zig | 80 ++-- std/os/linux/index.zig | 379 ++++++++------- std/special/bootstrap.zig | 8 +- std/special/compiler_rt/fixuint.zig | 6 +- std/special/compiler_rt/fixunsdfdi.zig | 1 - std/special/compiler_rt/fixunsdfsi.zig | 1 - std/special/compiler_rt/fixunssfti.zig | 1 - std/special/compiler_rt/fixunstfti.zig | 1 - std/special/compiler_rt/index.zig | 818 +++++++++++++++++++++++++++------ std/special/compiler_rt/udivmod.zig | 43 +- std/special/compiler_rt/udivmodti4.zig | 2 +- std/special/compiler_rt/umodti3.zig | 2 +- test/cases/cast.zig | 6 +- test/cases/generics.zig | 2 +- 19 files changed, 1132 insertions(+), 631 deletions(-) (limited to 'std/os/linux') diff --git a/std/array_list.zig b/std/array_list.zig index 2a44b66518..8c8426e1e5 100644 --- a/std/array_list.zig +++ b/std/array_list.zig @@ -8,7 +8,7 @@ pub fn ArrayList(comptime T: type) type { return AlignedArrayList(T, @alignOf(T)); } -pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ +pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { return struct { const Self = this; @@ -21,7 +21,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ /// Deinitialize with `deinit` or use `toOwnedSlice`. pub fn init(allocator: &Allocator) Self { - return Self { + return Self{ .items = []align(A) T{}, .len = 0, .allocator = allocator, @@ -48,7 +48,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ /// allocated with `allocator`. /// Deinitialize with `deinit` or use `toOwnedSlice`. pub fn fromOwnedSlice(allocator: &Allocator, slice: []align(A) T) Self { - return Self { + return Self{ .items = slice, .len = slice.len, .allocator = allocator, @@ -59,7 +59,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ pub fn toOwnedSlice(self: &Self) []align(A) T { const allocator = self.allocator; const result = allocator.alignedShrink(T, A, self.items, self.len); - *self = init(allocator); + self.* = init(allocator); return result; } @@ -67,21 +67,21 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ try l.ensureCapacity(l.len + 1); l.len += 1; - mem.copy(T, l.items[n+1..l.len], l.items[n..l.len-1]); - l.items[n] = *item; + mem.copy(T, l.items[n + 1..l.len], l.items[n..l.len - 1]); + l.items[n] = item.*; } pub fn insertSlice(l: &Self, n: usize, items: []align(A) const T) !void { try l.ensureCapacity(l.len + items.len); l.len += items.len; - mem.copy(T, l.items[n+items.len..l.len], l.items[n..l.len-items.len]); - mem.copy(T, l.items[n..n+items.len], items); + mem.copy(T, l.items[n + items.len..l.len], l.items[n..l.len - items.len]); + mem.copy(T, l.items[n..n + items.len], items); } pub fn append(l: &Self, item: &const T) !void { const new_item_ptr = try l.addOne(); - *new_item_ptr = *item; + new_item_ptr.* = item.*; } pub fn appendSlice(l: &Self, items: []align(A) const T) !void { @@ -124,8 +124,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ } pub fn popOrNull(self: &Self) ?T { - if (self.len == 0) - return null; + if (self.len == 0) return null; return self.pop(); } }; @@ -135,25 +134,35 @@ test "basic ArrayList test" { var list = ArrayList(i32).init(debug.global_allocator); defer list.deinit(); - {var i: usize = 0; while (i < 10) : (i += 1) { - list.append(i32(i + 1)) catch unreachable; - }} + { + var i: usize = 0; + while (i < 10) : (i += 1) { + list.append(i32(i + 1)) catch unreachable; + } + } - {var i: usize = 0; while (i < 10) : (i += 1) { - assert(list.items[i] == i32(i + 1)); - }} + { + var i: usize = 0; + while (i < 10) : (i += 1) { + assert(list.items[i] == i32(i + 1)); + } + } assert(list.pop() == 10); assert(list.len == 9); - list.appendSlice([]const i32 { 1, 2, 3 }) catch unreachable; + list.appendSlice([]const i32{ + 1, + 2, + 3, + }) catch unreachable; assert(list.len == 12); assert(list.pop() == 3); assert(list.pop() == 2); assert(list.pop() == 1); assert(list.len == 9); - list.appendSlice([]const i32 {}) catch unreachable; + list.appendSlice([]const i32{}) catch unreachable; assert(list.len == 9); } @@ -166,12 +175,15 @@ test "insert ArrayList test" { assert(list.items[0] == 5); assert(list.items[1] == 1); - try list.insertSlice(1, []const i32 { 9, 8 }); + try list.insertSlice(1, []const i32{ + 9, + 8, + }); assert(list.items[0] == 5); assert(list.items[1] == 9); assert(list.items[2] == 8); - const items = []const i32 { 1 }; + const items = []const i32{1}; try list.insertSlice(0, items[0..0]); assert(list.items[0] == 5); } diff --git a/std/fmt/index.zig b/std/fmt/index.zig index 43e758038f..804fd802f1 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -11,9 +11,7 @@ const max_int_digits = 65; /// Renders fmt string with args, calling output with slices of bytes. /// If `output` returns an error, the error is returned from `format` and /// `output` is not called again. -pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void, - comptime fmt: []const u8, args: ...) Errors!void -{ +pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void, comptime fmt: []const u8, args: ...) Errors!void { const State = enum { Start, OpenBrace, @@ -221,7 +219,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), } } -pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void { +pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { const T = @typeOf(value); switch (@typeId(T)) { builtin.TypeId.Int => { @@ -256,7 +254,7 @@ pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@ }, builtin.TypeId.Pointer => { if (@typeId(T.Child) == builtin.TypeId.Array and T.Child.Child == u8) { - return output(context, (*value)[0..]); + return output(context, (value.*)[0..]); } else { return format(context, Errors, output, "{}@{x}", @typeName(T.Child), @ptrToInt(value)); } @@ -270,13 +268,11 @@ pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@ } } -pub fn formatAsciiChar(c: u8, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void { +pub fn formatAsciiChar(c: u8, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { return output(context, (&c)[0..1]); } -pub fn formatBuf(buf: []const u8, width: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +pub fn formatBuf(buf: []const u8, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { try output(context, buf); var leftover_padding = if (width > buf.len) (width - buf.len) else return; @@ -289,7 +285,7 @@ pub fn formatBuf(buf: []const u8, width: usize, // Print a float in scientific notation to the specified precision. Null uses full precision. // It should be the case that every full precision, printed value can be re-parsed back to the // same type unambiguously. -pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void { +pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { var x = f64(value); // Errol doesn't handle these special cases. @@ -338,7 +334,7 @@ pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, var printed: usize = 0; if (float_decimal.digits.len > 1) { const num_digits = math.min(float_decimal.digits.len, precision + 1); - try output(context, float_decimal.digits[1 .. num_digits]); + try output(context, float_decimal.digits[1..num_digits]); printed += num_digits - 1; } @@ -350,12 +346,9 @@ pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, try output(context, float_decimal.digits[0..1]); try output(context, "."); if (float_decimal.digits.len > 1) { - const num_digits = if (@typeOf(value) == f32) - math.min(usize(9), float_decimal.digits.len) - else - float_decimal.digits.len; + const num_digits = if (@typeOf(value) == f32) math.min(usize(9), float_decimal.digits.len) else float_decimal.digits.len; - try output(context, float_decimal.digits[1 .. num_digits]); + try output(context, float_decimal.digits[1..num_digits]); } else { try output(context, "0"); } @@ -381,7 +374,7 @@ pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, // Print a float of the format x.yyyyy where the number of y is specified by the precision argument. // By default floats are printed at full precision (no rounding). -pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void { +pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { var x = f64(value); // Errol doesn't handle these special cases. @@ -431,14 +424,14 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com if (num_digits_whole > 0) { // We may have to zero pad, for instance 1e4 requires zero padding. - try output(context, float_decimal.digits[0 .. num_digits_whole_no_pad]); + try output(context, float_decimal.digits[0..num_digits_whole_no_pad]); var i = num_digits_whole_no_pad; while (i < num_digits_whole) : (i += 1) { try output(context, "0"); } } else { - try output(context , "0"); + try output(context, "0"); } // {.0} special case doesn't want a trailing '.' @@ -470,10 +463,10 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com // Remaining fractional portion, zero-padding if insufficient. debug.assert(precision >= printed); if (num_digits_whole_no_pad + precision - printed < float_decimal.digits.len) { - try output(context, float_decimal.digits[num_digits_whole_no_pad .. num_digits_whole_no_pad + precision - printed]); + try output(context, float_decimal.digits[num_digits_whole_no_pad..num_digits_whole_no_pad + precision - printed]); return; } else { - try output(context, float_decimal.digits[num_digits_whole_no_pad ..]); + try output(context, float_decimal.digits[num_digits_whole_no_pad..]); printed += float_decimal.digits.len - num_digits_whole_no_pad; while (printed < precision) : (printed += 1) { @@ -489,14 +482,14 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com if (num_digits_whole > 0) { // We may have to zero pad, for instance 1e4 requires zero padding. - try output(context, float_decimal.digits[0 .. num_digits_whole_no_pad]); + try output(context, float_decimal.digits[0..num_digits_whole_no_pad]); var i = num_digits_whole_no_pad; while (i < num_digits_whole) : (i += 1) { try output(context, "0"); } } else { - try output(context , "0"); + try output(context, "0"); } // Omit `.` if no fractional portion @@ -516,14 +509,11 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com } } - try output(context, float_decimal.digits[num_digits_whole_no_pad ..]); + try output(context, float_decimal.digits[num_digits_whole_no_pad..]); } } - -pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { if (@typeOf(value).is_signed) { return formatIntSigned(value, base, uppercase, width, context, Errors, output); } else { @@ -531,9 +521,7 @@ pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize, } } -fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { const uint = @IntType(false, @typeOf(value).bit_count); if (value < 0) { const minus_sign: u8 = '-'; @@ -552,9 +540,7 @@ fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, } } -fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { // max_int_digits accounts for the minus sign. when printing an unsigned // number we don't need to do that. var buf: [max_int_digits - 1]u8 = undefined; @@ -566,8 +552,7 @@ fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, index -= 1; buf[index] = digitToChar(u8(digit), uppercase); a /= base; - if (a == 0) - break; + if (a == 0) break; } const digits_buf = buf[index..]; @@ -579,8 +564,7 @@ fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, while (true) { try output(context, (&zero_byte)[0..1]); leftover_padding -= 1; - if (leftover_padding == 0) - break; + if (leftover_padding == 0) break; } mem.set(u8, buf[0..index], '0'); return output(context, buf); @@ -592,7 +576,7 @@ fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, } pub fn formatIntBuf(out_buf: []u8, value: var, base: u8, uppercase: bool, width: usize) usize { - var context = FormatIntBuf { + var context = FormatIntBuf{ .out_buf = out_buf, .index = 0, }; @@ -609,10 +593,8 @@ fn formatIntCallback(context: &FormatIntBuf, bytes: []const u8) (error{}!void) { } pub fn parseInt(comptime T: type, buf: []const u8, radix: u8) !T { - if (!T.is_signed) - return parseUnsigned(T, buf, radix); - if (buf.len == 0) - return T(0); + if (!T.is_signed) return parseUnsigned(T, buf, radix); + if (buf.len == 0) return T(0); if (buf[0] == '-') { return math.negate(try parseUnsigned(T, buf[1..], radix)); } else if (buf[0] == '+') { @@ -632,9 +614,10 @@ test "fmt.parseInt" { assert(if (parseInt(u8, "256", 10)) |_| false else |err| err == error.Overflow); } -const ParseUnsignedError = error { +const ParseUnsignedError = error{ /// The result cannot fit in the type specified Overflow, + /// The input had a byte that was not a digit InvalidCharacter, }; @@ -659,8 +642,7 @@ pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) { else => return error.InvalidCharacter, }; - if (value >= radix) - return error.InvalidCharacter; + if (value >= radix) return error.InvalidCharacter; return value; } @@ -684,20 +666,21 @@ fn bufPrintWrite(context: &BufPrintContext, bytes: []const u8) !void { } pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: ...) ![]u8 { - var context = BufPrintContext { .remaining = buf, }; + var context = BufPrintContext{ .remaining = buf }; try format(&context, error{BufferTooSmall}, bufPrintWrite, fmt, args); return buf[0..buf.len - context.remaining.len]; } pub fn allocPrint(allocator: &mem.Allocator, comptime fmt: []const u8, args: ...) ![]u8 { var size: usize = 0; - format(&size, error{}, countSize, fmt, args) catch |err| switch (err) {}; + format(&size, error{}, countSize, fmt, args) catch |err| switch (err) { + }; const buf = try allocator.alloc(u8, size); return bufPrint(buf, fmt, args); } fn countSize(size: &usize, bytes: []const u8) (error{}!void) { - *size += bytes.len; + size.* += bytes.len; } test "buf print int" { @@ -773,9 +756,7 @@ test "fmt.format" { unused: u8, }; var buf1: [32]u8 = undefined; - const value = Struct { - .unused = 42, - }; + const value = Struct{ .unused = 42 }; const result = try bufPrint(buf1[0..], "pointer: {}\n", &value); assert(mem.startsWith(u8, result, "pointer: Struct@")); } @@ -988,7 +969,7 @@ test "fmt.format" { pub fn trim(buf: []const u8) []const u8 { var start: usize = 0; - while (start < buf.len and isWhiteSpace(buf[start])) : (start += 1) { } + while (start < buf.len and isWhiteSpace(buf[start])) : (start += 1) {} var end: usize = buf.len; while (true) { @@ -1000,7 +981,6 @@ pub fn trim(buf: []const u8) []const u8 { } } break; - } return buf[start..end]; } @@ -1015,7 +995,10 @@ test "fmt.trim" { pub fn isWhiteSpace(byte: u8) bool { return switch (byte) { - ' ', '\t', '\n', '\r' => true, + ' ', + '\t', + '\n', + '\r' => true, else => false, }; } diff --git a/std/heap.zig b/std/heap.zig index bfdf62f658..7b753524a6 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -10,7 +10,7 @@ const c = std.c; const Allocator = mem.Allocator; pub const c_allocator = &c_allocator_state; -var c_allocator_state = Allocator { +var c_allocator_state = Allocator{ .allocFn = cAlloc, .reallocFn = cRealloc, .freeFn = cFree, @@ -18,10 +18,7 @@ var c_allocator_state = Allocator { fn cAlloc(self: &Allocator, n: usize, alignment: u29) ![]u8 { assert(alignment <= @alignOf(c_longdouble)); - return if (c.malloc(n)) |buf| - @ptrCast(&u8, buf)[0..n] - else - error.OutOfMemory; + return if (c.malloc(n)) |buf| @ptrCast(&u8, buf)[0..n] else error.OutOfMemory; } fn cRealloc(self: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { @@ -48,8 +45,8 @@ pub const DirectAllocator = struct { const HeapHandle = if (builtin.os == Os.windows) os.windows.HANDLE else void; pub fn init() DirectAllocator { - return DirectAllocator { - .allocator = Allocator { + return DirectAllocator{ + .allocator = Allocator{ .allocFn = alloc, .reallocFn = realloc, .freeFn = free, @@ -71,39 +68,39 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, Os.macosx, Os.ios => { + Os.linux, + Os.macosx, + Os.ios => { const p = os.posix; - const alloc_size = if(alignment <= os.page_size) n else n + alignment; - const addr = p.mmap(null, alloc_size, p.PROT_READ|p.PROT_WRITE, - p.MAP_PRIVATE|p.MAP_ANONYMOUS, -1, 0); - if(addr == p.MAP_FAILED) return error.OutOfMemory; - - if(alloc_size == n) return @intToPtr(&u8, addr)[0..n]; - + const alloc_size = if (alignment <= os.page_size) n else n + alignment; + const addr = p.mmap(null, alloc_size, p.PROT_READ | p.PROT_WRITE, p.MAP_PRIVATE | p.MAP_ANONYMOUS, -1, 0); + if (addr == p.MAP_FAILED) return error.OutOfMemory; + + if (alloc_size == n) return @intToPtr(&u8, addr)[0..n]; + var aligned_addr = addr & ~usize(alignment - 1); aligned_addr += alignment; - + //We can unmap the unused portions of our mmap, but we must only // pass munmap bytes that exist outside our allocated pages or it // will happily eat us too - + //Since alignment > page_size, we are by definition on a page boundry const unused_start = addr; const unused_len = aligned_addr - 1 - unused_start; var err = p.munmap(unused_start, unused_len); debug.assert(p.getErrno(err) == 0); - + //It is impossible that there is an unoccupied page at the top of our // mmap. - + return @intToPtr(&u8, aligned_addr)[0..n]; }, Os.windows => { const amt = n + alignment + @sizeOf(usize); const heap_handle = self.heap_handle ?? blk: { - const hh = os.windows.HeapCreate(os.windows.HEAP_NO_SERIALIZE, amt, 0) - ?? return error.OutOfMemory; + const hh = os.windows.HeapCreate(os.windows.HEAP_NO_SERIALIZE, amt, 0) ?? return error.OutOfMemory; self.heap_handle = hh; break :blk hh; }; @@ -113,7 +110,7 @@ pub const DirectAllocator = struct { const march_forward_bytes = if (rem == 0) 0 else (alignment - rem); const adjusted_addr = root_addr + march_forward_bytes; const record_addr = adjusted_addr + n; - *@intToPtr(&align(1) usize, record_addr) = root_addr; + @intToPtr(&align(1) usize, record_addr).* = root_addr; return @intToPtr(&u8, adjusted_addr)[0..n]; }, else => @compileError("Unsupported OS"), @@ -124,7 +121,9 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, Os.macosx, Os.ios => { + Os.linux, + Os.macosx, + Os.ios => { if (new_size <= old_mem.len) { const base_addr = @ptrToInt(old_mem.ptr); const old_addr_end = base_addr + old_mem.len; @@ -144,13 +143,13 @@ pub const DirectAllocator = struct { Os.windows => { const old_adjusted_addr = @ptrToInt(old_mem.ptr); const old_record_addr = old_adjusted_addr + old_mem.len; - const root_addr = *@intToPtr(&align(1) usize, old_record_addr); + const root_addr = @intToPtr(&align(1) usize, old_record_addr).*; const old_ptr = @intToPtr(os.windows.LPVOID, root_addr); const amt = new_size + alignment + @sizeOf(usize); const new_ptr = os.windows.HeapReAlloc(??self.heap_handle, 0, old_ptr, amt) ?? blk: { if (new_size > old_mem.len) return error.OutOfMemory; const new_record_addr = old_record_addr - new_size + old_mem.len; - *@intToPtr(&align(1) usize, new_record_addr) = root_addr; + @intToPtr(&align(1) usize, new_record_addr).* = root_addr; return old_mem[0..new_size]; }; const offset = old_adjusted_addr - root_addr; @@ -158,7 +157,7 @@ pub const DirectAllocator = struct { const new_adjusted_addr = new_root_addr + offset; assert(new_adjusted_addr % alignment == 0); const new_record_addr = new_adjusted_addr + new_size; - *@intToPtr(&align(1) usize, new_record_addr) = new_root_addr; + @intToPtr(&align(1) usize, new_record_addr).* = new_root_addr; return @intToPtr(&u8, new_adjusted_addr)[0..new_size]; }, else => @compileError("Unsupported OS"), @@ -169,12 +168,14 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, Os.macosx, Os.ios => { + Os.linux, + Os.macosx, + Os.ios => { _ = os.posix.munmap(@ptrToInt(bytes.ptr), bytes.len); }, Os.windows => { const record_addr = @ptrToInt(bytes.ptr) + bytes.len; - const root_addr = *@intToPtr(&align(1) usize, record_addr); + const root_addr = @intToPtr(&align(1) usize, record_addr).*; const ptr = @intToPtr(os.windows.LPVOID, root_addr); _ = os.windows.HeapFree(??self.heap_handle, 0, ptr); }, @@ -195,8 +196,8 @@ pub const ArenaAllocator = struct { const BufNode = std.LinkedList([]u8).Node; pub fn init(child_allocator: &Allocator) ArenaAllocator { - return ArenaAllocator { - .allocator = Allocator { + return ArenaAllocator{ + .allocator = Allocator{ .allocFn = alloc, .reallocFn = realloc, .freeFn = free, @@ -228,7 +229,7 @@ pub const ArenaAllocator = struct { const buf = try self.child_allocator.alignedAlloc(u8, @alignOf(BufNode), len); const buf_node_slice = ([]BufNode)(buf[0..@sizeOf(BufNode)]); const buf_node = &buf_node_slice[0]; - *buf_node = BufNode { + buf_node.* = BufNode{ .data = buf, .prev = null, .next = null, @@ -253,7 +254,7 @@ pub const ArenaAllocator = struct { cur_node = try self.createNode(cur_buf.len, n + alignment); continue; } - const result = cur_buf[adjusted_index .. new_end_index]; + const result = cur_buf[adjusted_index..new_end_index]; self.end_index = new_end_index; return result; } @@ -269,7 +270,7 @@ pub const ArenaAllocator = struct { } } - fn free(allocator: &Allocator, bytes: []u8) void { } + fn free(allocator: &Allocator, bytes: []u8) void {} }; pub const FixedBufferAllocator = struct { @@ -278,8 +279,8 @@ pub const FixedBufferAllocator = struct { buffer: []u8, pub fn init(buffer: []u8) FixedBufferAllocator { - return FixedBufferAllocator { - .allocator = Allocator { + return FixedBufferAllocator{ + .allocator = Allocator{ .allocFn = alloc, .reallocFn = realloc, .freeFn = free, @@ -299,7 +300,7 @@ pub const FixedBufferAllocator = struct { if (new_end_index > self.buffer.len) { return error.OutOfMemory; } - const result = self.buffer[adjusted_index .. new_end_index]; + const result = self.buffer[adjusted_index..new_end_index]; self.end_index = new_end_index; return result; @@ -315,7 +316,7 @@ pub const FixedBufferAllocator = struct { } } - fn free(allocator: &Allocator, bytes: []u8) void { } + fn free(allocator: &Allocator, bytes: []u8) void {} }; /// lock free @@ -325,8 +326,8 @@ pub const ThreadSafeFixedBufferAllocator = struct { buffer: []u8, pub fn init(buffer: []u8) ThreadSafeFixedBufferAllocator { - return ThreadSafeFixedBufferAllocator { - .allocator = Allocator { + return ThreadSafeFixedBufferAllocator{ + .allocator = Allocator{ .allocFn = alloc, .reallocFn = realloc, .freeFn = free, @@ -348,8 +349,7 @@ pub const ThreadSafeFixedBufferAllocator = struct { if (new_end_index > self.buffer.len) { return error.OutOfMemory; } - end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, - builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst) ?? return self.buffer[adjusted_index .. new_end_index]; + end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst) ?? return self.buffer[adjusted_index..new_end_index]; } } @@ -363,11 +363,9 @@ pub const ThreadSafeFixedBufferAllocator = struct { } } - fn free(allocator: &Allocator, bytes: []u8) void { } + fn free(allocator: &Allocator, bytes: []u8) void {} }; - - test "c_allocator" { if (builtin.link_libc) { var slice = c_allocator.alloc(u8, 50) catch return; @@ -415,8 +413,8 @@ fn testAllocator(allocator: &mem.Allocator) !void { var slice = try allocator.alloc(&i32, 100); for (slice) |*item, i| { - *item = try allocator.create(i32); - **item = i32(i); + item.* = try allocator.create(i32); + item.*.* = i32(i); } for (slice) |item, i| { @@ -434,26 +432,26 @@ fn testAllocator(allocator: &mem.Allocator) !void { fn testAllocatorLargeAlignment(allocator: &mem.Allocator) mem.Allocator.Error!void { //Maybe a platform's page_size is actually the same as or // very near usize? - if(os.page_size << 2 > @maxValue(usize)) return; - + if (os.page_size << 2 > @maxValue(usize)) return; + const USizeShift = @IntType(false, std.math.log2(usize.bit_count)); const large_align = u29(os.page_size << 2); - + var align_mask: usize = undefined; _ = @shlWithOverflow(usize, ~usize(0), USizeShift(@ctz(large_align)), &align_mask); - + var slice = try allocator.allocFn(allocator, 500, large_align); debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr)); - + slice = try allocator.reallocFn(allocator, slice, 100, large_align); debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr)); - + slice = try allocator.reallocFn(allocator, slice, 5000, large_align); debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr)); - + slice = try allocator.reallocFn(allocator, slice, 10, large_align); debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr)); - + slice = try allocator.reallocFn(allocator, slice, 20000, large_align); debug.assert(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr)); diff --git a/std/io.zig b/std/io.zig index 7b72af15e4..7c997fdf42 100644 --- a/std/io.zig +++ b/std/io.zig @@ -18,32 +18,17 @@ const is_windows = builtin.os == builtin.Os.windows; const GetStdIoErrs = os.WindowsGetStdHandleErrs; pub fn getStdErr() GetStdIoErrs!File { - const handle = if (is_windows) - try os.windowsGetStdHandle(os.windows.STD_ERROR_HANDLE) - else if (is_posix) - os.posix.STDERR_FILENO - else - unreachable; + const handle = if (is_windows) try os.windowsGetStdHandle(os.windows.STD_ERROR_HANDLE) else if (is_posix) os.posix.STDERR_FILENO else unreachable; return File.openHandle(handle); } pub fn getStdOut() GetStdIoErrs!File { - const handle = if (is_windows) - try os.windowsGetStdHandle(os.windows.STD_OUTPUT_HANDLE) - else if (is_posix) - os.posix.STDOUT_FILENO - else - unreachable; + const handle = if (is_windows) try os.windowsGetStdHandle(os.windows.STD_OUTPUT_HANDLE) else if (is_posix) os.posix.STDOUT_FILENO else unreachable; return File.openHandle(handle); } pub fn getStdIn() GetStdIoErrs!File { - const handle = if (is_windows) - try os.windowsGetStdHandle(os.windows.STD_INPUT_HANDLE) - else if (is_posix) - os.posix.STDIN_FILENO - else - unreachable; + const handle = if (is_windows) try os.windowsGetStdHandle(os.windows.STD_INPUT_HANDLE) else if (is_posix) os.posix.STDIN_FILENO else unreachable; return File.openHandle(handle); } @@ -56,11 +41,9 @@ pub const FileInStream = struct { pub const Stream = InStream(Error); pub fn init(file: &File) FileInStream { - return FileInStream { + return FileInStream{ .file = file, - .stream = Stream { - .readFn = readFn, - }, + .stream = Stream{ .readFn = readFn }, }; } @@ -79,11 +62,9 @@ pub const FileOutStream = struct { pub const Stream = OutStream(Error); pub fn init(file: &File) FileOutStream { - return FileOutStream { + return FileOutStream{ .file = file, - .stream = Stream { - .writeFn = writeFn, - }, + .stream = Stream{ .writeFn = writeFn }, }; } @@ -121,8 +102,7 @@ pub fn InStream(comptime ReadError: type) type { } const new_buf_size = math.min(max_size, actual_buf_len + os.page_size); - if (new_buf_size == actual_buf_len) - return error.StreamTooLong; + if (new_buf_size == actual_buf_len) return error.StreamTooLong; try buffer.resize(new_buf_size); } } @@ -165,9 +145,7 @@ pub fn InStream(comptime ReadError: type) type { /// memory would be greater than `max_size`, returns `error.StreamTooLong`. /// Caller owns returned memory. /// If this function returns an error, the contents from the stream read so far are lost. - pub fn readUntilDelimiterAlloc(self: &Self, allocator: &mem.Allocator, - delimiter: u8, max_size: usize) ![]u8 - { + pub fn readUntilDelimiterAlloc(self: &Self, allocator: &mem.Allocator, delimiter: u8, max_size: usize) ![]u8 { var buf = Buffer.initNull(allocator); defer buf.deinit(); @@ -283,7 +261,7 @@ pub fn BufferedInStream(comptime Error: type) type { pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type) type { return struct { const Self = this; - const Stream = InStream(Error); + const Stream = InStream(Error); pub stream: Stream, @@ -294,7 +272,7 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type) end_index: usize, pub fn init(unbuffered_in_stream: &Stream) Self { - return Self { + return Self{ .unbuffered_in_stream = unbuffered_in_stream, .buffer = undefined, @@ -305,9 +283,7 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type) .start_index = buffer_size, .end_index = buffer_size, - .stream = Stream { - .readFn = readFn, - }, + .stream = Stream{ .readFn = readFn }, }; } @@ -368,13 +344,11 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr index: usize, pub fn init(unbuffered_out_stream: &Stream) Self { - return Self { + return Self{ .unbuffered_out_stream = unbuffered_out_stream, .buffer = undefined, .index = 0, - .stream = Stream { - .writeFn = writeFn, - }, + .stream = Stream{ .writeFn = writeFn }, }; } @@ -416,11 +390,9 @@ pub const BufferOutStream = struct { pub const Stream = OutStream(Error); pub fn init(buffer: &Buffer) BufferOutStream { - return BufferOutStream { + return BufferOutStream{ .buffer = buffer, - .stream = Stream { - .writeFn = writeFn, - }, + .stream = Stream{ .writeFn = writeFn }, }; } @@ -430,7 +402,6 @@ pub const BufferOutStream = struct { } }; - pub const BufferedAtomicFile = struct { atomic_file: os.AtomicFile, file_stream: FileOutStream, @@ -441,7 +412,7 @@ pub const BufferedAtomicFile = struct { var self = try allocator.create(BufferedAtomicFile); errdefer allocator.destroy(self); - *self = BufferedAtomicFile { + self.* = BufferedAtomicFile{ .atomic_file = undefined, .file_stream = undefined, .buffered_stream = undefined, @@ -489,7 +460,7 @@ pub fn readLine(buf: []u8) !usize { '\r' => { // trash the following \n _ = stream.readByte() catch return error.EndOfFile; - return index; + return index; }, '\n' => return index, else => { diff --git a/std/linked_list.zig b/std/linked_list.zig index 45595f3efb..c6be08171e 100644 --- a/std/linked_list.zig +++ b/std/linked_list.zig @@ -26,10 +26,10 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na data: T, pub fn init(value: &const T) Node { - return Node { + return Node{ .prev = null, .next = null, - .data = *value, + .data = value.*, }; } @@ -45,18 +45,18 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na }; first: ?&Node, - last: ?&Node, - len: usize, + last: ?&Node, + len: usize, /// Initialize a linked list. /// /// Returns: /// An empty linked list. pub fn init() Self { - return Self { + return Self{ .first = null, - .last = null, - .len = 0, + .last = null, + .len = 0, }; } @@ -131,7 +131,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na } else { // Empty list. list.first = new_node; - list.last = new_node; + list.last = new_node; new_node.prev = null; new_node.next = null; @@ -217,7 +217,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na pub fn createNode(list: &Self, data: &const T, allocator: &Allocator) !&Node { comptime assert(!isIntrusive()); var node = try list.allocateNode(allocator); - *node = Node.init(data); + node.* = Node.init(data); return node; } }; @@ -227,11 +227,11 @@ test "basic linked list test" { const allocator = debug.global_allocator; var list = LinkedList(u32).init(); - var one = try list.createNode(1, allocator); - var two = try list.createNode(2, allocator); + var one = try list.createNode(1, allocator); + var two = try list.createNode(2, allocator); var three = try list.createNode(3, allocator); - var four = try list.createNode(4, allocator); - var five = try list.createNode(5, allocator); + var four = try list.createNode(4, allocator); + var five = try list.createNode(5, allocator); defer { list.destroyNode(one, allocator); list.destroyNode(two, allocator); @@ -240,11 +240,11 @@ test "basic linked list test" { list.destroyNode(five, allocator); } - list.append(two); // {2} - list.append(five); // {2, 5} - list.prepend(one); // {1, 2, 5} - list.insertBefore(five, four); // {1, 2, 4, 5} - list.insertAfter(two, three); // {1, 2, 3, 4, 5} + list.append(two); // {2} + list.append(five); // {2, 5} + list.prepend(one); // {1, 2, 5} + list.insertBefore(five, four); // {1, 2, 4, 5} + list.insertAfter(two, three); // {1, 2, 3, 4, 5} // Traverse forwards. { @@ -266,13 +266,13 @@ test "basic linked list test" { } } - var first = list.popFirst(); // {2, 3, 4, 5} - var last = list.pop(); // {2, 3, 4} - list.remove(three); // {2, 4} + var first = list.popFirst(); // {2, 3, 4, 5} + var last = list.pop(); // {2, 3, 4} + list.remove(three); // {2, 4} - assert ((??list.first).data == 2); - assert ((??list.last ).data == 4); - assert (list.len == 2); + assert((??list.first).data == 2); + assert((??list.last).data == 4); + assert(list.len == 2); } const ElementList = IntrusiveLinkedList(Element, "link"); @@ -285,17 +285,32 @@ test "basic intrusive linked list test" { const allocator = debug.global_allocator; var list = ElementList.init(); - var one = Element { .value = 1, .link = ElementList.Node.initIntrusive() }; - var two = Element { .value = 2, .link = ElementList.Node.initIntrusive() }; - var three = Element { .value = 3, .link = ElementList.Node.initIntrusive() }; - var four = Element { .value = 4, .link = ElementList.Node.initIntrusive() }; - var five = Element { .value = 5, .link = ElementList.Node.initIntrusive() }; + var one = Element{ + .value = 1, + .link = ElementList.Node.initIntrusive(), + }; + var two = Element{ + .value = 2, + .link = ElementList.Node.initIntrusive(), + }; + var three = Element{ + .value = 3, + .link = ElementList.Node.initIntrusive(), + }; + var four = Element{ + .value = 4, + .link = ElementList.Node.initIntrusive(), + }; + var five = Element{ + .value = 5, + .link = ElementList.Node.initIntrusive(), + }; - list.append(&two.link); // {2} - list.append(&five.link); // {2, 5} - list.prepend(&one.link); // {1, 2, 5} - list.insertBefore(&five.link, &four.link); // {1, 2, 4, 5} - list.insertAfter(&two.link, &three.link); // {1, 2, 3, 4, 5} + list.append(&two.link); // {2} + list.append(&five.link); // {2, 5} + list.prepend(&one.link); // {1, 2, 5} + list.insertBefore(&five.link, &four.link); // {1, 2, 4, 5} + list.insertAfter(&two.link, &three.link); // {1, 2, 3, 4, 5} // Traverse forwards. { @@ -317,11 +332,11 @@ test "basic intrusive linked list test" { } } - var first = list.popFirst(); // {2, 3, 4, 5} - var last = list.pop(); // {2, 3, 4} - list.remove(&three.link); // {2, 4} + var first = list.popFirst(); // {2, 3, 4, 5} + var last = list.pop(); // {2, 3, 4} + list.remove(&three.link); // {2, 4} - assert ((??list.first).toData().value == 2); - assert ((??list.last ).toData().value == 4); - assert (list.len == 2); + assert((??list.first).toData().value == 2); + assert((??list.last).toData().value == 4); + assert(list.len == 2); } diff --git a/std/os/index.zig b/std/os/index.zig index 4f1826021f..8728f4a6f6 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -137,7 +137,7 @@ pub fn getRandomBytes(buf: []u8) !void { } }, Os.zen => { - const randomness = []u8 { + const randomness = []u8{ 42, 1, 7, @@ -265,7 +265,7 @@ pub fn posixRead(fd: i32, buf: []u8) !void { } } -pub const PosixWriteError = error { +pub const PosixWriteError = error{ WouldBlock, FileClosed, DestinationAddressRequired, @@ -310,7 +310,7 @@ pub fn posixWrite(fd: i32, bytes: []const u8) !void { } } -pub const PosixOpenError = error { +pub const PosixOpenError = error{ OutOfMemory, AccessDenied, FileTooBig, @@ -477,7 +477,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap, allocator: return posixExecveErrnoToErr(err); } -pub const PosixExecveError = error { +pub const PosixExecveError = error{ SystemResources, AccessDenied, InvalidExe, @@ -512,7 +512,7 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError { }; } -pub var linux_aux_raw = []usize {0} ** 38; +pub var linux_aux_raw = []usize{0} ** 38; pub var posix_environ_raw: []&u8 = undefined; /// Caller must free result when done. @@ -667,7 +667,7 @@ pub fn symLink(allocator: &Allocator, existing_path: []const u8, new_path: []con } } -pub const WindowsSymLinkError = error { +pub const WindowsSymLinkError = error{ OutOfMemory, Unexpected, }; @@ -686,7 +686,7 @@ pub fn symLinkWindows(allocator: &Allocator, existing_path: []const u8, new_path } } -pub const PosixSymLinkError = error { +pub const PosixSymLinkError = error{ OutOfMemory, AccessDenied, DiskQuota, @@ -895,7 +895,7 @@ pub const AtomicFile = struct { else => return err, }; - return AtomicFile { + return AtomicFile{ .allocator = allocator, .file = file, .tmp_path = tmp_path, @@ -1087,7 +1087,7 @@ pub fn deleteDir(allocator: &Allocator, dir_path: []const u8) !void { /// removes it. If it cannot be removed because it is a non-empty directory, /// this function recursively removes its entries and then tries again. /// TODO non-recursive implementation -const DeleteTreeError = error { +const DeleteTreeError = error{ OutOfMemory, AccessDenied, FileTooBig, @@ -1217,7 +1217,7 @@ pub const Dir = struct { Os.ios => 0, else => {}, }; - return Dir { + return Dir{ .allocator = allocator, .fd = fd, .darwin_seek = darwin_seek_init, @@ -1294,7 +1294,7 @@ pub const Dir = struct { posix.DT_WHT => Entry.Kind.Whiteout, else => Entry.Kind.Unknown, }; - return Entry { + return Entry{ .name = name, .kind = entry_kind, }; @@ -1355,7 +1355,7 @@ pub const Dir = struct { posix.DT_SOCK => Entry.Kind.UnixDomainSocket, else => Entry.Kind.Unknown, }; - return Entry { + return Entry{ .name = name, .kind = entry_kind, }; @@ -1465,7 +1465,7 @@ pub fn posix_setregid(rgid: u32, egid: u32) !void { }; } -pub const WindowsGetStdHandleErrs = error { +pub const WindowsGetStdHandleErrs = error{ NoStdHandles, Unexpected, }; @@ -1489,7 +1489,7 @@ pub const ArgIteratorPosix = struct { count: usize, pub fn init() ArgIteratorPosix { - return ArgIteratorPosix { + return ArgIteratorPosix{ .index = 0, .count = raw.len, }; @@ -1522,16 +1522,14 @@ pub const ArgIteratorWindows = struct { quote_count: usize, seen_quote_count: usize, - pub const NextError = error { - OutOfMemory, - }; + pub const NextError = error{OutOfMemory}; pub fn init() ArgIteratorWindows { return initWithCmdLine(windows.GetCommandLineA()); } pub fn initWithCmdLine(cmd_line: &const u8) ArgIteratorWindows { - return ArgIteratorWindows { + return ArgIteratorWindows{ .index = 0, .cmd_line = cmd_line, .in_quote = false, @@ -1676,9 +1674,7 @@ pub const ArgIterator = struct { inner: InnerType, pub fn init() ArgIterator { - return ArgIterator { - .inner = InnerType.init(), - }; + return ArgIterator{ .inner = InnerType.init() }; } pub const NextError = ArgIteratorWindows.NextError; @@ -1757,33 +1753,33 @@ pub fn argsFree(allocator: &mem.Allocator, args_alloc: []const []u8) void { } test "windows arg parsing" { - testWindowsCmdLine(c"a b\tc d", [][]const u8 { + testWindowsCmdLine(c"a b\tc d", [][]const u8{ "a", "b", "c", "d", }); - testWindowsCmdLine(c"\"abc\" d e", [][]const u8 { + testWindowsCmdLine(c"\"abc\" d e", [][]const u8{ "abc", "d", "e", }); - testWindowsCmdLine(c"a\\\\\\b d\"e f\"g h", [][]const u8 { + testWindowsCmdLine(c"a\\\\\\b d\"e f\"g h", [][]const u8{ "a\\\\\\b", "de fg", "h", }); - testWindowsCmdLine(c"a\\\\\\\"b c d", [][]const u8 { + testWindowsCmdLine(c"a\\\\\\\"b c d", [][]const u8{ "a\\\"b", "c", "d", }); - testWindowsCmdLine(c"a\\\\\\\\\"b c\" d e", [][]const u8 { + testWindowsCmdLine(c"a\\\\\\\\\"b c\" d e", [][]const u8{ "a\\\\b c", "d", "e", }); - testWindowsCmdLine(c"a b\tc \"d f", [][]const u8 { + testWindowsCmdLine(c"a b\tc \"d f", [][]const u8{ "a", "b", "c", @@ -1791,7 +1787,7 @@ test "windows arg parsing" { "f", }); - testWindowsCmdLine(c"\".\\..\\zig-cache\\build\" \"bin\\zig.exe\" \".\\..\" \".\\..\\zig-cache\" \"--help\"", [][]const u8 { + testWindowsCmdLine(c"\".\\..\\zig-cache\\build\" \"bin\\zig.exe\" \".\\..\" \".\\..\\zig-cache\" \"--help\"", [][]const u8{ ".\\..\\zig-cache\\build", "bin\\zig.exe", ".\\..", @@ -1811,7 +1807,7 @@ fn testWindowsCmdLine(input_cmd_line: &const u8, expected_args: []const []const // TODO make this a build variable that you can set const unexpected_error_tracing = false; -const UnexpectedError = error { +const UnexpectedError = error{ /// The Operating System returned an undocumented error code. Unexpected, }; @@ -1950,7 +1946,7 @@ pub fn isTty(handle: FileHandle) bool { } } -pub const PosixSocketError = error { +pub const PosixSocketError = error{ /// Permission to create a socket of the specified type and/or /// pro‐tocol is denied. PermissionDenied, @@ -1992,7 +1988,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 { } } -pub const PosixBindError = error { +pub const PosixBindError = error{ /// The address is protected, and the user is not the superuser. /// For UNIX domain sockets: Search permission is denied on a component /// of the path prefix. @@ -2065,7 +2061,7 @@ pub fn posixBind(fd: i32, addr: &const posix.sockaddr) PosixBindError!void { } } -const PosixListenError = error { +const PosixListenError = error{ /// Another socket is already listening on the same port. /// For Internet domain sockets, the socket referred to by sockfd had not previously /// been bound to an address and, upon attempting to bind it to an ephemeral port, it @@ -2098,7 +2094,7 @@ pub fn posixListen(sockfd: i32, backlog: u32) PosixListenError!void { } } -pub const PosixAcceptError = error { +pub const PosixAcceptError = error{ /// The socket is marked nonblocking and no connections are present to be accepted. WouldBlock, @@ -2165,7 +2161,7 @@ pub fn posixAccept(fd: i32, addr: &posix.sockaddr, flags: u32) PosixAcceptError! } } -pub const LinuxEpollCreateError = error { +pub const LinuxEpollCreateError = error{ /// Invalid value specified in flags. InvalidSyscall, @@ -2198,7 +2194,7 @@ pub fn linuxEpollCreate(flags: u32) LinuxEpollCreateError!i32 { } } -pub const LinuxEpollCtlError = error { +pub const LinuxEpollCtlError = error{ /// epfd or fd is not a valid file descriptor. InvalidFileDescriptor, @@ -2271,7 +2267,7 @@ pub fn linuxEpollWait(epfd: i32, events: []linux.epoll_event, timeout: i32) usiz } } -pub const PosixGetSockNameError = error { +pub const PosixGetSockNameError = error{ /// Insufficient resources were available in the system to perform the operation. SystemResources, @@ -2295,7 +2291,7 @@ pub fn posixGetSockName(sockfd: i32) PosixGetSockNameError!posix.sockaddr { } } -pub const PosixConnectError = error { +pub const PosixConnectError = error{ /// For UNIX domain sockets, which are identified by pathname: Write permission is denied on the socket /// file, or search permission is denied for one of the directories in the path prefix. /// or @@ -2484,7 +2480,7 @@ pub const Thread = struct { } }; -pub const SpawnThreadError = error { +pub const SpawnThreadError = error{ /// A system-imposed limit on the number of threads was encountered. /// There are a number of limits that may trigger this error: /// * the RLIMIT_NPROC soft resource limit (set via setrlimit(2)), @@ -2532,7 +2528,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread if (@sizeOf(Context) == 0) { return startFn({}); } else { - return startFn(*@ptrCast(&Context, @alignCast(@alignOf(Context), arg))); + return startFn(@ptrCast(&Context, @alignCast(@alignOf(Context), arg)).*); } } }; @@ -2562,7 +2558,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread if (@sizeOf(Context) == 0) { return startFn({}); } else { - return startFn(*@intToPtr(&const Context, ctx_addr)); + return startFn(@intToPtr(&const Context, ctx_addr).*); } } extern fn posixThreadMain(ctx: ?&c_void) ?&c_void { @@ -2570,7 +2566,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread _ = startFn({}); return null; } else { - _ = startFn(*@ptrCast(&const Context, @alignCast(@alignOf(Context), ctx))); + _ = startFn(@ptrCast(&const Context, @alignCast(@alignOf(Context), ctx)).*); return null; } } @@ -2590,7 +2586,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread stack_end -= stack_end % @alignOf(Context); assert(stack_end >= stack_addr); const context_ptr = @alignCast(@alignOf(Context), @intToPtr(&Context, stack_end)); - *context_ptr = context; + context_ptr.* = context; arg = stack_end; } diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 368f074b9b..4e0e9ee5d5 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -30,96 +30,95 @@ pub const FUTEX_PRIVATE_FLAG = 128; pub const FUTEX_CLOCK_REALTIME = 256; - -pub const PROT_NONE = 0; -pub const PROT_READ = 1; -pub const PROT_WRITE = 2; -pub const PROT_EXEC = 4; +pub const PROT_NONE = 0; +pub const PROT_READ = 1; +pub const PROT_WRITE = 2; +pub const PROT_EXEC = 4; pub const PROT_GROWSDOWN = 0x01000000; -pub const PROT_GROWSUP = 0x02000000; - -pub const MAP_FAILED = @maxValue(usize); -pub const MAP_SHARED = 0x01; -pub const MAP_PRIVATE = 0x02; -pub const MAP_TYPE = 0x0f; -pub const MAP_FIXED = 0x10; -pub const MAP_ANONYMOUS = 0x20; -pub const MAP_NORESERVE = 0x4000; -pub const MAP_GROWSDOWN = 0x0100; -pub const MAP_DENYWRITE = 0x0800; +pub const PROT_GROWSUP = 0x02000000; + +pub const MAP_FAILED = @maxValue(usize); +pub const MAP_SHARED = 0x01; +pub const MAP_PRIVATE = 0x02; +pub const MAP_TYPE = 0x0f; +pub const MAP_FIXED = 0x10; +pub const MAP_ANONYMOUS = 0x20; +pub const MAP_NORESERVE = 0x4000; +pub const MAP_GROWSDOWN = 0x0100; +pub const MAP_DENYWRITE = 0x0800; pub const MAP_EXECUTABLE = 0x1000; -pub const MAP_LOCKED = 0x2000; -pub const MAP_POPULATE = 0x8000; -pub const MAP_NONBLOCK = 0x10000; -pub const MAP_STACK = 0x20000; -pub const MAP_HUGETLB = 0x40000; -pub const MAP_FILE = 0; +pub const MAP_LOCKED = 0x2000; +pub const MAP_POPULATE = 0x8000; +pub const MAP_NONBLOCK = 0x10000; +pub const MAP_STACK = 0x20000; +pub const MAP_HUGETLB = 0x40000; +pub const MAP_FILE = 0; pub const F_OK = 0; pub const X_OK = 1; pub const W_OK = 2; pub const R_OK = 4; -pub const WNOHANG = 1; -pub const WUNTRACED = 2; -pub const WSTOPPED = 2; -pub const WEXITED = 4; +pub const WNOHANG = 1; +pub const WUNTRACED = 2; +pub const WSTOPPED = 2; +pub const WEXITED = 4; pub const WCONTINUED = 8; -pub const WNOWAIT = 0x1000000; - -pub const SA_NOCLDSTOP = 1; -pub const SA_NOCLDWAIT = 2; -pub const SA_SIGINFO = 4; -pub const SA_ONSTACK = 0x08000000; -pub const SA_RESTART = 0x10000000; -pub const SA_NODEFER = 0x40000000; -pub const SA_RESETHAND = 0x80000000; -pub const SA_RESTORER = 0x04000000; - -pub const SIGHUP = 1; -pub const SIGINT = 2; -pub const SIGQUIT = 3; -pub const SIGILL = 4; -pub const SIGTRAP = 5; -pub const SIGABRT = 6; -pub const SIGIOT = SIGABRT; -pub const SIGBUS = 7; -pub const SIGFPE = 8; -pub const SIGKILL = 9; -pub const SIGUSR1 = 10; -pub const SIGSEGV = 11; -pub const SIGUSR2 = 12; -pub const SIGPIPE = 13; -pub const SIGALRM = 14; -pub const SIGTERM = 15; +pub const WNOWAIT = 0x1000000; + +pub const SA_NOCLDSTOP = 1; +pub const SA_NOCLDWAIT = 2; +pub const SA_SIGINFO = 4; +pub const SA_ONSTACK = 0x08000000; +pub const SA_RESTART = 0x10000000; +pub const SA_NODEFER = 0x40000000; +pub const SA_RESETHAND = 0x80000000; +pub const SA_RESTORER = 0x04000000; + +pub const SIGHUP = 1; +pub const SIGINT = 2; +pub const SIGQUIT = 3; +pub const SIGILL = 4; +pub const SIGTRAP = 5; +pub const SIGABRT = 6; +pub const SIGIOT = SIGABRT; +pub const SIGBUS = 7; +pub const SIGFPE = 8; +pub const SIGKILL = 9; +pub const SIGUSR1 = 10; +pub const SIGSEGV = 11; +pub const SIGUSR2 = 12; +pub const SIGPIPE = 13; +pub const SIGALRM = 14; +pub const SIGTERM = 15; pub const SIGSTKFLT = 16; -pub const SIGCHLD = 17; -pub const SIGCONT = 18; -pub const SIGSTOP = 19; -pub const SIGTSTP = 20; -pub const SIGTTIN = 21; -pub const SIGTTOU = 22; -pub const SIGURG = 23; -pub const SIGXCPU = 24; -pub const SIGXFSZ = 25; +pub const SIGCHLD = 17; +pub const SIGCONT = 18; +pub const SIGSTOP = 19; +pub const SIGTSTP = 20; +pub const SIGTTIN = 21; +pub const SIGTTOU = 22; +pub const SIGURG = 23; +pub const SIGXCPU = 24; +pub const SIGXFSZ = 25; pub const SIGVTALRM = 26; -pub const SIGPROF = 27; -pub const SIGWINCH = 28; -pub const SIGIO = 29; -pub const SIGPOLL = 29; -pub const SIGPWR = 30; -pub const SIGSYS = 31; +pub const SIGPROF = 27; +pub const SIGWINCH = 28; +pub const SIGIO = 29; +pub const SIGPOLL = 29; +pub const SIGPWR = 30; +pub const SIGSYS = 31; pub const SIGUNUSED = SIGSYS; pub const O_RDONLY = 0o0; pub const O_WRONLY = 0o1; -pub const O_RDWR = 0o2; +pub const O_RDWR = 0o2; pub const SEEK_SET = 0; pub const SEEK_CUR = 1; pub const SEEK_END = 2; -pub const SIG_BLOCK = 0; +pub const SIG_BLOCK = 0; pub const SIG_UNBLOCK = 1; pub const SIG_SETMASK = 2; @@ -408,7 +407,6 @@ pub const DT_LNK = 10; pub const DT_SOCK = 12; pub const DT_WHT = 14; - pub const TCGETS = 0x5401; pub const TCSETS = 0x5402; pub const TCSETSW = 0x5403; @@ -539,23 +537,23 @@ pub const MS_BIND = 4096; pub const MS_MOVE = 8192; pub const MS_REC = 16384; pub const MS_SILENT = 32768; -pub const MS_POSIXACL = (1<<16); -pub const MS_UNBINDABLE = (1<<17); -pub const MS_PRIVATE = (1<<18); -pub const MS_SLAVE = (1<<19); -pub const MS_SHARED = (1<<20); -pub const MS_RELATIME = (1<<21); -pub const MS_KERNMOUNT = (1<<22); -pub const MS_I_VERSION = (1<<23); -pub const MS_STRICTATIME = (1<<24); -pub const MS_LAZYTIME = (1<<25); -pub const MS_NOREMOTELOCK = (1<<27); -pub const MS_NOSEC = (1<<28); -pub const MS_BORN = (1<<29); -pub const MS_ACTIVE = (1<<30); -pub const MS_NOUSER = (1<<31); - -pub const MS_RMT_MASK = (MS_RDONLY|MS_SYNCHRONOUS|MS_MANDLOCK|MS_I_VERSION|MS_LAZYTIME); +pub const MS_POSIXACL = (1 << 16); +pub const MS_UNBINDABLE = (1 << 17); +pub const MS_PRIVATE = (1 << 18); +pub const MS_SLAVE = (1 << 19); +pub const MS_SHARED = (1 << 20); +pub const MS_RELATIME = (1 << 21); +pub const MS_KERNMOUNT = (1 << 22); +pub const MS_I_VERSION = (1 << 23); +pub const MS_STRICTATIME = (1 << 24); +pub const MS_LAZYTIME = (1 << 25); +pub const MS_NOREMOTELOCK = (1 << 27); +pub const MS_NOSEC = (1 << 28); +pub const MS_BORN = (1 << 29); +pub const MS_ACTIVE = (1 << 30); +pub const MS_NOUSER = (1 << 31); + +pub const MS_RMT_MASK = (MS_RDONLY | MS_SYNCHRONOUS | MS_MANDLOCK | MS_I_VERSION | MS_LAZYTIME); pub const MS_MGC_VAL = 0xc0ed0000; pub const MS_MGC_MSK = 0xffff0000; @@ -565,7 +563,6 @@ pub const MNT_DETACH = 2; pub const MNT_EXPIRE = 4; pub const UMOUNT_NOFOLLOW = 8; - pub const S_IFMT = 0o170000; pub const S_IFDIR = 0o040000; @@ -626,15 +623,30 @@ pub const TFD_CLOEXEC = O_CLOEXEC; pub const TFD_TIMER_ABSTIME = 1; pub const TFD_TIMER_CANCEL_ON_SET = (1 << 1); -fn unsigned(s: i32) u32 { return @bitCast(u32, s); } -fn signed(s: u32) i32 { return @bitCast(i32, s); } -pub fn WEXITSTATUS(s: i32) i32 { return signed((unsigned(s) & 0xff00) >> 8); } -pub fn WTERMSIG(s: i32) i32 { return signed(unsigned(s) & 0x7f); } -pub fn WSTOPSIG(s: i32) i32 { return WEXITSTATUS(s); } -pub fn WIFEXITED(s: i32) bool { return WTERMSIG(s) == 0; } -pub fn WIFSTOPPED(s: i32) bool { return (u16)(((unsigned(s)&0xffff)*%0x10001)>>8) > 0x7f00; } -pub fn WIFSIGNALED(s: i32) bool { return (unsigned(s)&0xffff)-%1 < 0xff; } - +fn unsigned(s: i32) u32 { + return @bitCast(u32, s); +} +fn signed(s: u32) i32 { + return @bitCast(i32, s); +} +pub fn WEXITSTATUS(s: i32) i32 { + return signed((unsigned(s) & 0xff00) >> 8); +} +pub fn WTERMSIG(s: i32) i32 { + return signed(unsigned(s) & 0x7f); +} +pub fn WSTOPSIG(s: i32) i32 { + return WEXITSTATUS(s); +} +pub fn WIFEXITED(s: i32) bool { + return WTERMSIG(s) == 0; +} +pub fn WIFSTOPPED(s: i32) bool { + return (u16)(((unsigned(s) & 0xffff) *% 0x10001) >> 8) > 0x7f00; +} +pub fn WIFSIGNALED(s: i32) bool { + return (unsigned(s) & 0xffff) -% 1 < 0xff; +} pub const winsize = extern struct { ws_row: u16, @@ -707,8 +719,7 @@ pub fn umount2(special: &const u8, flags: u32) usize { } pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { - return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), - @bitCast(usize, offset)); + return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), @bitCast(usize, offset)); } pub fn munmap(address: usize, length: usize) usize { @@ -812,7 +823,8 @@ pub fn clock_gettime(clk_id: i32, tp: ×pec) usize { if (@ptrToInt(f) != 0) { const rc = f(clk_id, tp); switch (rc) { - 0, @bitCast(usize, isize(-EINVAL)) => return rc, + 0, + @bitCast(usize, isize(-EINVAL)) => return rc, else => {}, } } @@ -823,8 +835,7 @@ var vdso_clock_gettime = init_vdso_clock_gettime; extern fn init_vdso_clock_gettime(clk: i32, ts: ×pec) usize { const addr = vdso.lookup(VDSO_CGT_VER, VDSO_CGT_SYM); var f = @intToPtr(@typeOf(init_vdso_clock_gettime), addr); - _ = @cmpxchgStrong(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, init_vdso_clock_gettime, f, - builtin.AtomicOrder.Monotonic, builtin.AtomicOrder.Monotonic); + _ = @cmpxchgStrong(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, init_vdso_clock_gettime, f, builtin.AtomicOrder.Monotonic, builtin.AtomicOrder.Monotonic); if (@ptrToInt(f) == 0) return @bitCast(usize, isize(-ENOSYS)); return f(clk, ts); } @@ -918,18 +929,18 @@ pub fn getpid() i32 { } pub fn sigprocmask(flags: u32, noalias set: &const sigset_t, noalias oldset: ?&sigset_t) usize { - return syscall4(SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG/8); + return syscall4(SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8); } pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigaction) usize { assert(sig >= 1); assert(sig != SIGKILL); assert(sig != SIGSTOP); - var ksa = k_sigaction { + var ksa = k_sigaction{ .handler = act.handler, .flags = act.flags | SA_RESTORER, .mask = undefined, - .restorer = @ptrCast(extern fn()void, restore_rt), + .restorer = @ptrCast(extern fn() void, restore_rt), }; var ksa_old: k_sigaction = undefined; @memcpy(@ptrCast(&u8, &ksa.mask), @ptrCast(&const u8, &act.mask), 8); @@ -952,22 +963,22 @@ const all_mask = []usize{@maxValue(usize)}; const app_mask = []usize{0xfffffffc7fffffff}; const k_sigaction = extern struct { - handler: extern fn(i32)void, + handler: extern fn(i32) void, flags: usize, - restorer: extern fn()void, + restorer: extern fn() void, mask: [2]u32, }; /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = struct { - handler: extern fn(i32)void, + handler: extern fn(i32) void, mask: sigset_t, flags: u32, }; -pub const SIG_ERR = @intToPtr(extern fn(i32)void, @maxValue(usize)); -pub const SIG_DFL = @intToPtr(extern fn(i32)void, 0); -pub const SIG_IGN = @intToPtr(extern fn(i32)void, 1); +pub const SIG_ERR = @intToPtr(extern fn(i32) void, @maxValue(usize)); +pub const SIG_DFL = @intToPtr(extern fn(i32) void, 0); +pub const SIG_IGN = @intToPtr(extern fn(i32) void, 1); pub const empty_sigset = []usize{0} ** sigset_t.len; pub fn raise(sig: i32) usize { @@ -980,25 +991,25 @@ pub fn raise(sig: i32) usize { } fn blockAllSignals(set: &sigset_t) void { - _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&all_mask), @ptrToInt(set), NSIG/8); + _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&all_mask), @ptrToInt(set), NSIG / 8); } fn blockAppSignals(set: &sigset_t) void { - _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&app_mask), @ptrToInt(set), NSIG/8); + _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&app_mask), @ptrToInt(set), NSIG / 8); } fn restoreSignals(set: &sigset_t) void { - _ = syscall4(SYS_rt_sigprocmask, SIG_SETMASK, @ptrToInt(set), 0, NSIG/8); + _ = syscall4(SYS_rt_sigprocmask, SIG_SETMASK, @ptrToInt(set), 0, NSIG / 8); } pub fn sigaddset(set: &sigset_t, sig: u6) void { const s = sig - 1; - (*set)[usize(s) / usize.bit_count] |= usize(1) << (s & (usize.bit_count - 1)); + (set.*)[usize(s) / usize.bit_count] |= usize(1) << (s & (usize.bit_count - 1)); } pub fn sigismember(set: &const sigset_t, sig: u6) bool { const s = sig - 1; - return ((*set)[usize(s) / usize.bit_count] & (usize(1) << (s & (usize.bit_count - 1)))) != 0; + return ((set.*)[usize(s) / usize.bit_count] & (usize(1) << (s & (usize.bit_count - 1)))) != 0; } pub const in_port_t = u16; @@ -1062,9 +1073,7 @@ pub fn recvmsg(fd: i32, msg: &msghdr, flags: u32) usize { return syscall3(SYS_recvmsg, usize(fd), @ptrToInt(msg), flags); } -pub fn recvfrom(fd: i32, noalias buf: &u8, len: usize, flags: u32, - noalias addr: ?&sockaddr, noalias alen: ?&socklen_t) usize -{ +pub fn recvfrom(fd: i32, noalias buf: &u8, len: usize, flags: u32, noalias addr: ?&sockaddr, noalias alen: ?&socklen_t) usize { return syscall6(SYS_recvfrom, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); } @@ -1132,25 +1141,16 @@ pub fn fgetxattr(fd: usize, name: &const u8, value: &void, size: usize) usize { return syscall4(SYS_lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size); } -pub fn setxattr(path: &const u8, name: &const u8, value: &const void, - size: usize, flags: usize) usize { - - return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), - size, flags); +pub fn setxattr(path: &const u8, name: &const u8, value: &const void, size: usize, flags: usize) usize { + return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } -pub fn lsetxattr(path: &const u8, name: &const u8, value: &const void, - size: usize, flags: usize) usize { - - return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), - size, flags); +pub fn lsetxattr(path: &const u8, name: &const u8, value: &const void, size: usize, flags: usize) usize { + return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } -pub fn fsetxattr(fd: usize, name: &const u8, value: &const void, - size: usize, flags: usize) usize { - - return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), - size, flags); +pub fn fsetxattr(fd: usize, name: &const u8, value: &const void, size: usize, flags: usize) usize { + return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags); } pub fn removexattr(path: &const u8, name: &const u8) usize { @@ -1199,7 +1199,7 @@ pub fn timerfd_create(clockid: i32, flags: u32) usize { pub const itimerspec = extern struct { it_interval: timespec, - it_value: timespec + it_value: timespec, }; pub fn timerfd_gettime(fd: i32, curr_value: &itimerspec) usize { @@ -1211,30 +1211,30 @@ pub fn timerfd_settime(fd: i32, flags: u32, new_value: &const itimerspec, old_va } pub const _LINUX_CAPABILITY_VERSION_1 = 0x19980330; -pub const _LINUX_CAPABILITY_U32S_1 = 1; +pub const _LINUX_CAPABILITY_U32S_1 = 1; pub const _LINUX_CAPABILITY_VERSION_2 = 0x20071026; -pub const _LINUX_CAPABILITY_U32S_2 = 2; +pub const _LINUX_CAPABILITY_U32S_2 = 2; pub const _LINUX_CAPABILITY_VERSION_3 = 0x20080522; -pub const _LINUX_CAPABILITY_U32S_3 = 2; +pub const _LINUX_CAPABILITY_U32S_3 = 2; -pub const VFS_CAP_REVISION_MASK = 0xFF000000; -pub const VFS_CAP_REVISION_SHIFT = 24; -pub const VFS_CAP_FLAGS_MASK = ~VFS_CAP_REVISION_MASK; +pub const VFS_CAP_REVISION_MASK = 0xFF000000; +pub const VFS_CAP_REVISION_SHIFT = 24; +pub const VFS_CAP_FLAGS_MASK = ~VFS_CAP_REVISION_MASK; pub const VFS_CAP_FLAGS_EFFECTIVE = 0x000001; pub const VFS_CAP_REVISION_1 = 0x01000000; -pub const VFS_CAP_U32_1 = 1; -pub const XATTR_CAPS_SZ_1 = @sizeOf(u32)*(1 + 2*VFS_CAP_U32_1); +pub const VFS_CAP_U32_1 = 1; +pub const XATTR_CAPS_SZ_1 = @sizeOf(u32) * (1 + 2 * VFS_CAP_U32_1); pub const VFS_CAP_REVISION_2 = 0x02000000; -pub const VFS_CAP_U32_2 = 2; -pub const XATTR_CAPS_SZ_2 = @sizeOf(u32)*(1 + 2*VFS_CAP_U32_2); +pub const VFS_CAP_U32_2 = 2; +pub const XATTR_CAPS_SZ_2 = @sizeOf(u32) * (1 + 2 * VFS_CAP_U32_2); -pub const XATTR_CAPS_SZ = XATTR_CAPS_SZ_2; -pub const VFS_CAP_U32 = VFS_CAP_U32_2; -pub const VFS_CAP_REVISION = VFS_CAP_REVISION_2; +pub const XATTR_CAPS_SZ = XATTR_CAPS_SZ_2; +pub const VFS_CAP_U32 = VFS_CAP_U32_2; +pub const VFS_CAP_REVISION = VFS_CAP_REVISION_2; pub const vfs_cap_data = extern struct { //all of these are mandated as little endian @@ -1245,49 +1245,48 @@ pub const vfs_cap_data = extern struct { }; magic_etc: u32, - data: [VFS_CAP_U32]Data, + data: [VFS_CAP_U32]Data, }; - -pub const CAP_CHOWN = 0; -pub const CAP_DAC_OVERRIDE = 1; -pub const CAP_DAC_READ_SEARCH = 2; -pub const CAP_FOWNER = 3; -pub const CAP_FSETID = 4; -pub const CAP_KILL = 5; -pub const CAP_SETGID = 6; -pub const CAP_SETUID = 7; -pub const CAP_SETPCAP = 8; -pub const CAP_LINUX_IMMUTABLE = 9; -pub const CAP_NET_BIND_SERVICE = 10; -pub const CAP_NET_BROADCAST = 11; -pub const CAP_NET_ADMIN = 12; -pub const CAP_NET_RAW = 13; -pub const CAP_IPC_LOCK = 14; -pub const CAP_IPC_OWNER = 15; -pub const CAP_SYS_MODULE = 16; -pub const CAP_SYS_RAWIO = 17; -pub const CAP_SYS_CHROOT = 18; -pub const CAP_SYS_PTRACE = 19; -pub const CAP_SYS_PACCT = 20; -pub const CAP_SYS_ADMIN = 21; -pub const CAP_SYS_BOOT = 22; -pub const CAP_SYS_NICE = 23; -pub const CAP_SYS_RESOURCE = 24; -pub const CAP_SYS_TIME = 25; -pub const CAP_SYS_TTY_CONFIG = 26; -pub const CAP_MKNOD = 27; -pub const CAP_LEASE = 28; -pub const CAP_AUDIT_WRITE = 29; -pub const CAP_AUDIT_CONTROL = 30; -pub const CAP_SETFCAP = 31; -pub const CAP_MAC_OVERRIDE = 32; -pub const CAP_MAC_ADMIN = 33; -pub const CAP_SYSLOG = 34; -pub const CAP_WAKE_ALARM = 35; -pub const CAP_BLOCK_SUSPEND = 36; -pub const CAP_AUDIT_READ = 37; -pub const CAP_LAST_CAP = CAP_AUDIT_READ; +pub const CAP_CHOWN = 0; +pub const CAP_DAC_OVERRIDE = 1; +pub const CAP_DAC_READ_SEARCH = 2; +pub const CAP_FOWNER = 3; +pub const CAP_FSETID = 4; +pub const CAP_KILL = 5; +pub const CAP_SETGID = 6; +pub const CAP_SETUID = 7; +pub const CAP_SETPCAP = 8; +pub const CAP_LINUX_IMMUTABLE = 9; +pub const CAP_NET_BIND_SERVICE = 10; +pub const CAP_NET_BROADCAST = 11; +pub const CAP_NET_ADMIN = 12; +pub const CAP_NET_RAW = 13; +pub const CAP_IPC_LOCK = 14; +pub const CAP_IPC_OWNER = 15; +pub const CAP_SYS_MODULE = 16; +pub const CAP_SYS_RAWIO = 17; +pub const CAP_SYS_CHROOT = 18; +pub const CAP_SYS_PTRACE = 19; +pub const CAP_SYS_PACCT = 20; +pub const CAP_SYS_ADMIN = 21; +pub const CAP_SYS_BOOT = 22; +pub const CAP_SYS_NICE = 23; +pub const CAP_SYS_RESOURCE = 24; +pub const CAP_SYS_TIME = 25; +pub const CAP_SYS_TTY_CONFIG = 26; +pub const CAP_MKNOD = 27; +pub const CAP_LEASE = 28; +pub const CAP_AUDIT_WRITE = 29; +pub const CAP_AUDIT_CONTROL = 30; +pub const CAP_SETFCAP = 31; +pub const CAP_MAC_OVERRIDE = 32; +pub const CAP_MAC_ADMIN = 33; +pub const CAP_SYSLOG = 34; +pub const CAP_WAKE_ALARM = 35; +pub const CAP_BLOCK_SUSPEND = 36; +pub const CAP_AUDIT_READ = 37; +pub const CAP_LAST_CAP = CAP_AUDIT_READ; pub fn cap_valid(u8: x) bool { return x >= 0 and x <= CAP_LAST_CAP; diff --git a/std/special/bootstrap.zig b/std/special/bootstrap.zig index 1dc7e24869..056ab35003 100644 --- a/std/special/bootstrap.zig +++ b/std/special/bootstrap.zig @@ -27,10 +27,10 @@ extern fn zen_start() noreturn { nakedcc fn _start() noreturn { switch (builtin.arch) { builtin.Arch.x86_64 => { - argc_ptr = asm("lea (%%rsp), %[argc]": [argc] "=r" (-> &usize)); + argc_ptr = asm ("lea (%%rsp), %[argc]" : [argc] "=r" (-> &usize)); }, builtin.Arch.i386 => { - argc_ptr = asm("lea (%%esp), %[argc]": [argc] "=r" (-> &usize)); + argc_ptr = asm ("lea (%%esp), %[argc]" : [argc] "=r" (-> &usize)); }, else => @compileError("unsupported arch"), } @@ -46,7 +46,7 @@ extern fn WinMainCRTStartup() noreturn { } fn posixCallMainAndExit() noreturn { - const argc = *argc_ptr; + const argc = argc_ptr.*; const argv = @ptrCast(&&u8, &argc_ptr[1]); const envp_nullable = @ptrCast(&?&u8, &argv[argc + 1]); var envp_count: usize = 0; @@ -56,7 +56,7 @@ fn posixCallMainAndExit() noreturn { const auxv = &@ptrCast(&usize, envp.ptr)[envp_count + 1]; var i: usize = 0; while (auxv[i] != 0) : (i += 2) { - if (auxv[i] < std.os.linux_aux_raw.len) std.os.linux_aux_raw[auxv[i]] = auxv[i+1]; + if (auxv[i] < std.os.linux_aux_raw.len) std.os.linux_aux_raw[auxv[i]] = auxv[i + 1]; } std.debug.assert(std.os.linux_aux_raw[std.elf.AT_PAGESZ] == std.os.page_size); } diff --git a/std/special/compiler_rt/fixuint.zig b/std/special/compiler_rt/fixuint.zig index b01bc48118..d9a7393fe4 100644 --- a/std/special/compiler_rt/fixuint.zig +++ b/std/special/compiler_rt/fixuint.zig @@ -36,12 +36,10 @@ pub fn fixuint(comptime fp_t: type, comptime fixuint_t: type, a: fp_t) fixuint_t const significand: rep_t = (aAbs & significandMask) | implicitBit; // If either the value or the exponent is negative, the result is zero. - if (sign == -1 or exponent < 0) - return 0; + if (sign == -1 or exponent < 0) return 0; // If the value is too large for the integer type, saturate. - if (c_uint(exponent) >= fixuint_t.bit_count) - return ~fixuint_t(0); + if (c_uint(exponent) >= fixuint_t.bit_count) return ~fixuint_t(0); // If 0 <= exponent < significandBits, right shift to get the result. // Otherwise, shift left. diff --git a/std/special/compiler_rt/fixunsdfdi.zig b/std/special/compiler_rt/fixunsdfdi.zig index 37a8a01a50..1fa7ed758e 100644 --- a/std/special/compiler_rt/fixunsdfdi.zig +++ b/std/special/compiler_rt/fixunsdfdi.zig @@ -9,4 +9,3 @@ pub extern fn __fixunsdfdi(a: f64) u64 { test "import fixunsdfdi" { _ = @import("fixunsdfdi_test.zig"); } - diff --git a/std/special/compiler_rt/fixunsdfsi.zig b/std/special/compiler_rt/fixunsdfsi.zig index 0b5aebb7f6..a77cb8df89 100644 --- a/std/special/compiler_rt/fixunsdfsi.zig +++ b/std/special/compiler_rt/fixunsdfsi.zig @@ -9,4 +9,3 @@ pub extern fn __fixunsdfsi(a: f64) u32 { test "import fixunsdfsi" { _ = @import("fixunsdfsi_test.zig"); } - diff --git a/std/special/compiler_rt/fixunssfti.zig b/std/special/compiler_rt/fixunssfti.zig index 0abd73fe76..f0cd788d2e 100644 --- a/std/special/compiler_rt/fixunssfti.zig +++ b/std/special/compiler_rt/fixunssfti.zig @@ -9,4 +9,3 @@ pub extern fn __fixunssfti(a: f32) u128 { test "import fixunssfti" { _ = @import("fixunssfti_test.zig"); } - diff --git a/std/special/compiler_rt/fixunstfti.zig b/std/special/compiler_rt/fixunstfti.zig index fea99eb6e8..cd6178164a 100644 --- a/std/special/compiler_rt/fixunstfti.zig +++ b/std/special/compiler_rt/fixunstfti.zig @@ -9,4 +9,3 @@ pub extern fn __fixunstfti(a: f128) u128 { test "import fixunstfti" { _ = @import("fixunstfti_test.zig"); } - diff --git a/std/special/compiler_rt/index.zig b/std/special/compiler_rt/index.zig index 6ef43c4fed..44466a407d 100644 --- a/std/special/compiler_rt/index.zig +++ b/std/special/compiler_rt/index.zig @@ -91,9 +91,10 @@ pub fn setXmm0(comptime T: type, value: T) void { const aligned_value: T align(16) = value; asm volatile ( \\movaps (%[ptr]), %%xmm0 - : - : [ptr] "r" (&aligned_value) - : "xmm0"); + + : + : [ptr] "r" (&aligned_value) + : "xmm0"); } extern fn __udivdi3(a: u64, b: u64) u64 { @@ -282,26 +283,27 @@ extern fn __udivmodsi4(a: u32, b: u32, rem: &u32) u32 { @setRuntimeSafety(is_test); const d = __udivsi3(a, b); - *rem = u32(i32(a) -% (i32(d) * i32(b))); + rem.* = u32(i32(a) -% (i32(d) * i32(b))); return d; } - extern fn __udivsi3(n: u32, d: u32) u32 { @setRuntimeSafety(is_test); const n_uword_bits: c_uint = u32.bit_count; // special cases - if (d == 0) - return 0; // ?! - if (n == 0) - return 0; + if (d == 0) return 0; // ?! + if (n == 0) return 0; var sr = @bitCast(c_uint, c_int(@clz(d)) - c_int(@clz(n))); // 0 <= sr <= n_uword_bits - 1 or sr large - if (sr > n_uword_bits - 1) // d > r + if (sr > n_uword_bits - 1) { + // d > r return 0; - if (sr == n_uword_bits - 1) // d == 1 + } + if (sr == n_uword_bits - 1) { + // d == 1 return n; + } sr += 1; // 1 <= sr <= n_uword_bits - 1 // Not a special case @@ -340,139 +342,667 @@ fn test_one_umoddi3(a: u64, b: u64, expected_r: u64) void { } test "test_udivsi3" { - const cases = [][3]u32 { - []u32{0x00000000, 0x00000001, 0x00000000}, - []u32{0x00000000, 0x00000002, 0x00000000}, - []u32{0x00000000, 0x00000003, 0x00000000}, - []u32{0x00000000, 0x00000010, 0x00000000}, - []u32{0x00000000, 0x078644FA, 0x00000000}, - []u32{0x00000000, 0x0747AE14, 0x00000000}, - []u32{0x00000000, 0x7FFFFFFF, 0x00000000}, - []u32{0x00000000, 0x80000000, 0x00000000}, - []u32{0x00000000, 0xFFFFFFFD, 0x00000000}, - []u32{0x00000000, 0xFFFFFFFE, 0x00000000}, - []u32{0x00000000, 0xFFFFFFFF, 0x00000000}, - []u32{0x00000001, 0x00000001, 0x00000001}, - []u32{0x00000001, 0x00000002, 0x00000000}, - []u32{0x00000001, 0x00000003, 0x00000000}, - []u32{0x00000001, 0x00000010, 0x00000000}, - []u32{0x00000001, 0x078644FA, 0x00000000}, - []u32{0x00000001, 0x0747AE14, 0x00000000}, - []u32{0x00000001, 0x7FFFFFFF, 0x00000000}, - []u32{0x00000001, 0x80000000, 0x00000000}, - []u32{0x00000001, 0xFFFFFFFD, 0x00000000}, - []u32{0x00000001, 0xFFFFFFFE, 0x00000000}, - []u32{0x00000001, 0xFFFFFFFF, 0x00000000}, - []u32{0x00000002, 0x00000001, 0x00000002}, - []u32{0x00000002, 0x00000002, 0x00000001}, - []u32{0x00000002, 0x00000003, 0x00000000}, - []u32{0x00000002, 0x00000010, 0x00000000}, - []u32{0x00000002, 0x078644FA, 0x00000000}, - []u32{0x00000002, 0x0747AE14, 0x00000000}, - []u32{0x00000002, 0x7FFFFFFF, 0x00000000}, - []u32{0x00000002, 0x80000000, 0x00000000}, - []u32{0x00000002, 0xFFFFFFFD, 0x00000000}, - []u32{0x00000002, 0xFFFFFFFE, 0x00000000}, - []u32{0x00000002, 0xFFFFFFFF, 0x00000000}, - []u32{0x00000003, 0x00000001, 0x00000003}, - []u32{0x00000003, 0x00000002, 0x00000001}, - []u32{0x00000003, 0x00000003, 0x00000001}, - []u32{0x00000003, 0x00000010, 0x00000000}, - []u32{0x00000003, 0x078644FA, 0x00000000}, - []u32{0x00000003, 0x0747AE14, 0x00000000}, - []u32{0x00000003, 0x7FFFFFFF, 0x00000000}, - []u32{0x00000003, 0x80000000, 0x00000000}, - []u32{0x00000003, 0xFFFFFFFD, 0x00000000}, - []u32{0x00000003, 0xFFFFFFFE, 0x00000000}, - []u32{0x00000003, 0xFFFFFFFF, 0x00000000}, - []u32{0x00000010, 0x00000001, 0x00000010}, - []u32{0x00000010, 0x00000002, 0x00000008}, - []u32{0x00000010, 0x00000003, 0x00000005}, - []u32{0x00000010, 0x00000010, 0x00000001}, - []u32{0x00000010, 0x078644FA, 0x00000000}, - []u32{0x00000010, 0x0747AE14, 0x00000000}, - []u32{0x00000010, 0x7FFFFFFF, 0x00000000}, - []u32{0x00000010, 0x80000000, 0x00000000}, - []u32{0x00000010, 0xFFFFFFFD, 0x00000000}, - []u32{0x00000010, 0xFFFFFFFE, 0x00000000}, - []u32{0x00000010, 0xFFFFFFFF, 0x00000000}, - []u32{0x078644FA, 0x00000001, 0x078644FA}, - []u32{0x078644FA, 0x00000002, 0x03C3227D}, - []u32{0x078644FA, 0x00000003, 0x028216FE}, - []u32{0x078644FA, 0x00000010, 0x0078644F}, - []u32{0x078644FA, 0x078644FA, 0x00000001}, - []u32{0x078644FA, 0x0747AE14, 0x00000001}, - []u32{0x078644FA, 0x7FFFFFFF, 0x00000000}, - []u32{0x078644FA, 0x80000000, 0x00000000}, - []u32{0x078644FA, 0xFFFFFFFD, 0x00000000}, - []u32{0x078644FA, 0xFFFFFFFE, 0x00000000}, - []u32{0x078644FA, 0xFFFFFFFF, 0x00000000}, - []u32{0x0747AE14, 0x00000001, 0x0747AE14}, - []u32{0x0747AE14, 0x00000002, 0x03A3D70A}, - []u32{0x0747AE14, 0x00000003, 0x026D3A06}, - []u32{0x0747AE14, 0x00000010, 0x00747AE1}, - []u32{0x0747AE14, 0x078644FA, 0x00000000}, - []u32{0x0747AE14, 0x0747AE14, 0x00000001}, - []u32{0x0747AE14, 0x7FFFFFFF, 0x00000000}, - []u32{0x0747AE14, 0x80000000, 0x00000000}, - []u32{0x0747AE14, 0xFFFFFFFD, 0x00000000}, - []u32{0x0747AE14, 0xFFFFFFFE, 0x00000000}, - []u32{0x0747AE14, 0xFFFFFFFF, 0x00000000}, - []u32{0x7FFFFFFF, 0x00000001, 0x7FFFFFFF}, - []u32{0x7FFFFFFF, 0x00000002, 0x3FFFFFFF}, - []u32{0x7FFFFFFF, 0x00000003, 0x2AAAAAAA}, - []u32{0x7FFFFFFF, 0x00000010, 0x07FFFFFF}, - []u32{0x7FFFFFFF, 0x078644FA, 0x00000011}, - []u32{0x7FFFFFFF, 0x0747AE14, 0x00000011}, - []u32{0x7FFFFFFF, 0x7FFFFFFF, 0x00000001}, - []u32{0x7FFFFFFF, 0x80000000, 0x00000000}, - []u32{0x7FFFFFFF, 0xFFFFFFFD, 0x00000000}, - []u32{0x7FFFFFFF, 0xFFFFFFFE, 0x00000000}, - []u32{0x7FFFFFFF, 0xFFFFFFFF, 0x00000000}, - []u32{0x80000000, 0x00000001, 0x80000000}, - []u32{0x80000000, 0x00000002, 0x40000000}, - []u32{0x80000000, 0x00000003, 0x2AAAAAAA}, - []u32{0x80000000, 0x00000010, 0x08000000}, - []u32{0x80000000, 0x078644FA, 0x00000011}, - []u32{0x80000000, 0x0747AE14, 0x00000011}, - []u32{0x80000000, 0x7FFFFFFF, 0x00000001}, - []u32{0x80000000, 0x80000000, 0x00000001}, - []u32{0x80000000, 0xFFFFFFFD, 0x00000000}, - []u32{0x80000000, 0xFFFFFFFE, 0x00000000}, - []u32{0x80000000, 0xFFFFFFFF, 0x00000000}, - []u32{0xFFFFFFFD, 0x00000001, 0xFFFFFFFD}, - []u32{0xFFFFFFFD, 0x00000002, 0x7FFFFFFE}, - []u32{0xFFFFFFFD, 0x00000003, 0x55555554}, - []u32{0xFFFFFFFD, 0x00000010, 0x0FFFFFFF}, - []u32{0xFFFFFFFD, 0x078644FA, 0x00000022}, - []u32{0xFFFFFFFD, 0x0747AE14, 0x00000023}, - []u32{0xFFFFFFFD, 0x7FFFFFFF, 0x00000001}, - []u32{0xFFFFFFFD, 0x80000000, 0x00000001}, - []u32{0xFFFFFFFD, 0xFFFFFFFD, 0x00000001}, - []u32{0xFFFFFFFD, 0xFFFFFFFE, 0x00000000}, - []u32{0xFFFFFFFD, 0xFFFFFFFF, 0x00000000}, - []u32{0xFFFFFFFE, 0x00000001, 0xFFFFFFFE}, - []u32{0xFFFFFFFE, 0x00000002, 0x7FFFFFFF}, - []u32{0xFFFFFFFE, 0x00000003, 0x55555554}, - []u32{0xFFFFFFFE, 0x00000010, 0x0FFFFFFF}, - []u32{0xFFFFFFFE, 0x078644FA, 0x00000022}, - []u32{0xFFFFFFFE, 0x0747AE14, 0x00000023}, - []u32{0xFFFFFFFE, 0x7FFFFFFF, 0x00000002}, - []u32{0xFFFFFFFE, 0x80000000, 0x00000001}, - []u32{0xFFFFFFFE, 0xFFFFFFFD, 0x00000001}, - []u32{0xFFFFFFFE, 0xFFFFFFFE, 0x00000001}, - []u32{0xFFFFFFFE, 0xFFFFFFFF, 0x00000000}, - []u32{0xFFFFFFFF, 0x00000001, 0xFFFFFFFF}, - []u32{0xFFFFFFFF, 0x00000002, 0x7FFFFFFF}, - []u32{0xFFFFFFFF, 0x00000003, 0x55555555}, - []u32{0xFFFFFFFF, 0x00000010, 0x0FFFFFFF}, - []u32{0xFFFFFFFF, 0x078644FA, 0x00000022}, - []u32{0xFFFFFFFF, 0x0747AE14, 0x00000023}, - []u32{0xFFFFFFFF, 0x7FFFFFFF, 0x00000002}, - []u32{0xFFFFFFFF, 0x80000000, 0x00000001}, - []u32{0xFFFFFFFF, 0xFFFFFFFD, 0x00000001}, - []u32{0xFFFFFFFF, 0xFFFFFFFE, 0x00000001}, - []u32{0xFFFFFFFF, 0xFFFFFFFF, 0x00000001}, + const cases = [][3]u32{ + []u32{ + 0x00000000, + 0x00000001, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x00000002, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x00000003, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x00000010, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x0747AE14, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000000, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x00000000, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x00000000, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x00000001, + 0x00000001, + }, + []u32{ + 0x00000001, + 0x00000002, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x00000003, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x00000010, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x0747AE14, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000001, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x00000001, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x00000001, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x00000001, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x00000001, + 0x00000002, + }, + []u32{ + 0x00000002, + 0x00000002, + 0x00000001, + }, + []u32{ + 0x00000002, + 0x00000003, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x00000010, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x0747AE14, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000002, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x00000002, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x00000002, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x00000002, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000003, + 0x00000001, + 0x00000003, + }, + []u32{ + 0x00000003, + 0x00000002, + 0x00000001, + }, + []u32{ + 0x00000003, + 0x00000003, + 0x00000001, + }, + []u32{ + 0x00000003, + 0x00000010, + 0x00000000, + }, + []u32{ + 0x00000003, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x00000003, + 0x0747AE14, + 0x00000000, + }, + []u32{ + 0x00000003, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000003, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x00000003, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x00000003, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x00000003, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000010, + 0x00000001, + 0x00000010, + }, + []u32{ + 0x00000010, + 0x00000002, + 0x00000008, + }, + []u32{ + 0x00000010, + 0x00000003, + 0x00000005, + }, + []u32{ + 0x00000010, + 0x00000010, + 0x00000001, + }, + []u32{ + 0x00000010, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x00000010, + 0x0747AE14, + 0x00000000, + }, + []u32{ + 0x00000010, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x00000010, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x00000010, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x00000010, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x00000010, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x078644FA, + 0x00000001, + 0x078644FA, + }, + []u32{ + 0x078644FA, + 0x00000002, + 0x03C3227D, + }, + []u32{ + 0x078644FA, + 0x00000003, + 0x028216FE, + }, + []u32{ + 0x078644FA, + 0x00000010, + 0x0078644F, + }, + []u32{ + 0x078644FA, + 0x078644FA, + 0x00000001, + }, + []u32{ + 0x078644FA, + 0x0747AE14, + 0x00000001, + }, + []u32{ + 0x078644FA, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x078644FA, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x078644FA, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x078644FA, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x078644FA, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0x00000001, + 0x0747AE14, + }, + []u32{ + 0x0747AE14, + 0x00000002, + 0x03A3D70A, + }, + []u32{ + 0x0747AE14, + 0x00000003, + 0x026D3A06, + }, + []u32{ + 0x0747AE14, + 0x00000010, + 0x00747AE1, + }, + []u32{ + 0x0747AE14, + 0x078644FA, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0x0747AE14, + 0x00000001, + }, + []u32{ + 0x0747AE14, + 0x7FFFFFFF, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x0747AE14, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x7FFFFFFF, + 0x00000001, + 0x7FFFFFFF, + }, + []u32{ + 0x7FFFFFFF, + 0x00000002, + 0x3FFFFFFF, + }, + []u32{ + 0x7FFFFFFF, + 0x00000003, + 0x2AAAAAAA, + }, + []u32{ + 0x7FFFFFFF, + 0x00000010, + 0x07FFFFFF, + }, + []u32{ + 0x7FFFFFFF, + 0x078644FA, + 0x00000011, + }, + []u32{ + 0x7FFFFFFF, + 0x0747AE14, + 0x00000011, + }, + []u32{ + 0x7FFFFFFF, + 0x7FFFFFFF, + 0x00000001, + }, + []u32{ + 0x7FFFFFFF, + 0x80000000, + 0x00000000, + }, + []u32{ + 0x7FFFFFFF, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x7FFFFFFF, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x7FFFFFFF, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0x80000000, + 0x00000001, + 0x80000000, + }, + []u32{ + 0x80000000, + 0x00000002, + 0x40000000, + }, + []u32{ + 0x80000000, + 0x00000003, + 0x2AAAAAAA, + }, + []u32{ + 0x80000000, + 0x00000010, + 0x08000000, + }, + []u32{ + 0x80000000, + 0x078644FA, + 0x00000011, + }, + []u32{ + 0x80000000, + 0x0747AE14, + 0x00000011, + }, + []u32{ + 0x80000000, + 0x7FFFFFFF, + 0x00000001, + }, + []u32{ + 0x80000000, + 0x80000000, + 0x00000001, + }, + []u32{ + 0x80000000, + 0xFFFFFFFD, + 0x00000000, + }, + []u32{ + 0x80000000, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0x80000000, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0xFFFFFFFD, + 0x00000001, + 0xFFFFFFFD, + }, + []u32{ + 0xFFFFFFFD, + 0x00000002, + 0x7FFFFFFE, + }, + []u32{ + 0xFFFFFFFD, + 0x00000003, + 0x55555554, + }, + []u32{ + 0xFFFFFFFD, + 0x00000010, + 0x0FFFFFFF, + }, + []u32{ + 0xFFFFFFFD, + 0x078644FA, + 0x00000022, + }, + []u32{ + 0xFFFFFFFD, + 0x0747AE14, + 0x00000023, + }, + []u32{ + 0xFFFFFFFD, + 0x7FFFFFFF, + 0x00000001, + }, + []u32{ + 0xFFFFFFFD, + 0x80000000, + 0x00000001, + }, + []u32{ + 0xFFFFFFFD, + 0xFFFFFFFD, + 0x00000001, + }, + []u32{ + 0xFFFFFFFD, + 0xFFFFFFFE, + 0x00000000, + }, + []u32{ + 0xFFFFFFFD, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0xFFFFFFFE, + 0x00000001, + 0xFFFFFFFE, + }, + []u32{ + 0xFFFFFFFE, + 0x00000002, + 0x7FFFFFFF, + }, + []u32{ + 0xFFFFFFFE, + 0x00000003, + 0x55555554, + }, + []u32{ + 0xFFFFFFFE, + 0x00000010, + 0x0FFFFFFF, + }, + []u32{ + 0xFFFFFFFE, + 0x078644FA, + 0x00000022, + }, + []u32{ + 0xFFFFFFFE, + 0x0747AE14, + 0x00000023, + }, + []u32{ + 0xFFFFFFFE, + 0x7FFFFFFF, + 0x00000002, + }, + []u32{ + 0xFFFFFFFE, + 0x80000000, + 0x00000001, + }, + []u32{ + 0xFFFFFFFE, + 0xFFFFFFFD, + 0x00000001, + }, + []u32{ + 0xFFFFFFFE, + 0xFFFFFFFE, + 0x00000001, + }, + []u32{ + 0xFFFFFFFE, + 0xFFFFFFFF, + 0x00000000, + }, + []u32{ + 0xFFFFFFFF, + 0x00000001, + 0xFFFFFFFF, + }, + []u32{ + 0xFFFFFFFF, + 0x00000002, + 0x7FFFFFFF, + }, + []u32{ + 0xFFFFFFFF, + 0x00000003, + 0x55555555, + }, + []u32{ + 0xFFFFFFFF, + 0x00000010, + 0x0FFFFFFF, + }, + []u32{ + 0xFFFFFFFF, + 0x078644FA, + 0x00000022, + }, + []u32{ + 0xFFFFFFFF, + 0x0747AE14, + 0x00000023, + }, + []u32{ + 0xFFFFFFFF, + 0x7FFFFFFF, + 0x00000002, + }, + []u32{ + 0xFFFFFFFF, + 0x80000000, + 0x00000001, + }, + []u32{ + 0xFFFFFFFF, + 0xFFFFFFFD, + 0x00000001, + }, + []u32{ + 0xFFFFFFFF, + 0xFFFFFFFE, + 0x00000001, + }, + []u32{ + 0xFFFFFFFF, + 0xFFFFFFFF, + 0x00000001, + }, }; for (cases) |case| { diff --git a/std/special/compiler_rt/udivmod.zig b/std/special/compiler_rt/udivmod.zig index 07eaef583c..e8a86c5c44 100644 --- a/std/special/compiler_rt/udivmod.zig +++ b/std/special/compiler_rt/udivmod.zig @@ -1,7 +1,10 @@ const builtin = @import("builtin"); const is_test = builtin.is_test; -const low = switch (builtin.endian) { builtin.Endian.Big => 1, builtin.Endian.Little => 0 }; +const low = switch (builtin.endian) { + builtin.Endian.Big => 1, + builtin.Endian.Little => 0, +}; const high = 1 - low; pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: ?&DoubleInt) DoubleInt { @@ -11,8 +14,8 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: const SignedDoubleInt = @IntType(true, DoubleInt.bit_count); const Log2SingleInt = @import("../../math/index.zig").Log2Int(SingleInt); - const n = *@ptrCast(&const [2]SingleInt, &a); // TODO issue #421 - const d = *@ptrCast(&const [2]SingleInt, &b); // TODO issue #421 + const n = @ptrCast(&const [2]SingleInt, &a).*; // TODO issue #421 + const d = @ptrCast(&const [2]SingleInt, &b).*; // TODO issue #421 var q: [2]SingleInt = undefined; var r: [2]SingleInt = undefined; var sr: c_uint = undefined; @@ -23,7 +26,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // --- // 0 X if (maybe_rem) |rem| { - *rem = n[low] % d[low]; + rem.* = n[low] % d[low]; } return n[low] / d[low]; } @@ -31,7 +34,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // --- // K X if (maybe_rem) |rem| { - *rem = n[low]; + rem.* = n[low]; } return 0; } @@ -42,7 +45,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // --- // 0 0 if (maybe_rem) |rem| { - *rem = n[high] % d[low]; + rem.* = n[high] % d[low]; } return n[high] / d[low]; } @@ -54,7 +57,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: if (maybe_rem) |rem| { r[high] = n[high] % d[high]; r[low] = 0; - *rem = *@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]); // TODO issue #421 + rem.* = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 } return n[high] / d[high]; } @@ -66,7 +69,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: if (maybe_rem) |rem| { r[low] = n[low]; r[high] = n[high] & (d[high] - 1); - *rem = *@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]); // TODO issue #421 + rem.* = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 } return n[high] >> Log2SingleInt(@ctz(d[high])); } @@ -77,7 +80,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // 0 <= sr <= SingleInt.bit_count - 2 or sr large if (sr > SingleInt.bit_count - 2) { if (maybe_rem) |rem| { - *rem = a; + rem.* = a; } return 0; } @@ -98,7 +101,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: if ((d[low] & (d[low] - 1)) == 0) { // d is a power of 2 if (maybe_rem) |rem| { - *rem = n[low] & (d[low] - 1); + rem.* = n[low] & (d[low] - 1); } if (d[low] == 1) { return a; @@ -106,7 +109,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: sr = @ctz(d[low]); q[high] = n[high] >> Log2SingleInt(sr); q[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr)); - return *@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0]); // TODO issue #421 + return @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0]).*; // TODO issue #421 } // K X // --- @@ -141,7 +144,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // 0 <= sr <= SingleInt.bit_count - 1 or sr large if (sr > SingleInt.bit_count - 1) { if (maybe_rem) |rem| { - *rem = a; + rem.* = a; } return 0; } @@ -170,25 +173,25 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: var r_all: DoubleInt = undefined; while (sr > 0) : (sr -= 1) { // r:q = ((r:q) << 1) | carry - r[high] = (r[high] << 1) | (r[low] >> (SingleInt.bit_count - 1)); - r[low] = (r[low] << 1) | (q[high] >> (SingleInt.bit_count - 1)); - q[high] = (q[high] << 1) | (q[low] >> (SingleInt.bit_count - 1)); - q[low] = (q[low] << 1) | carry; + r[high] = (r[high] << 1) | (r[low] >> (SingleInt.bit_count - 1)); + r[low] = (r[low] << 1) | (q[high] >> (SingleInt.bit_count - 1)); + q[high] = (q[high] << 1) | (q[low] >> (SingleInt.bit_count - 1)); + q[low] = (q[low] << 1) | carry; // carry = 0; // if (r.all >= b) // { // r.all -= b; // carry = 1; // } - r_all = *@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]); // TODO issue #421 + r_all = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 const s: SignedDoubleInt = SignedDoubleInt(b -% r_all -% 1) >> (DoubleInt.bit_count - 1); carry = u32(s & 1); r_all -= b & @bitCast(DoubleInt, s); - r = *@ptrCast(&[2]SingleInt, &r_all); // TODO issue #421 + r = @ptrCast(&[2]SingleInt, &r_all).*; // TODO issue #421 } - const q_all = ((*@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0])) << 1) | carry; // TODO issue #421 + const q_all = ((@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0]).*) << 1) | carry; // TODO issue #421 if (maybe_rem) |rem| { - *rem = r_all; + rem.* = r_all; } return q_all; } diff --git a/std/special/compiler_rt/udivmodti4.zig b/std/special/compiler_rt/udivmodti4.zig index f8fdebe4db..816f82b900 100644 --- a/std/special/compiler_rt/udivmodti4.zig +++ b/std/special/compiler_rt/udivmodti4.zig @@ -9,7 +9,7 @@ pub extern fn __udivmodti4(a: u128, b: u128, maybe_rem: ?&u128) u128 { pub extern fn __udivmodti4_windows_x86_64(a: &const u128, b: &const u128, maybe_rem: ?&u128) void { @setRuntimeSafety(builtin.is_test); - compiler_rt.setXmm0(u128, udivmod(u128, *a, *b, maybe_rem)); + compiler_rt.setXmm0(u128, udivmod(u128, a.*, b.*, maybe_rem)); } test "import udivmodti4" { diff --git a/std/special/compiler_rt/umodti3.zig b/std/special/compiler_rt/umodti3.zig index 3e8b80058e..11e2955bb3 100644 --- a/std/special/compiler_rt/umodti3.zig +++ b/std/special/compiler_rt/umodti3.zig @@ -11,5 +11,5 @@ pub extern fn __umodti3(a: u128, b: u128) u128 { pub extern fn __umodti3_windows_x86_64(a: &const u128, b: &const u128) void { @setRuntimeSafety(builtin.is_test); - compiler_rt.setXmm0(u128, __umodti3(*a, *b)); + compiler_rt.setXmm0(u128, __umodti3(a.*, b.*)); } diff --git a/test/cases/cast.zig b/test/cases/cast.zig index 547cca5797..8b6afb4310 100644 --- a/test/cases/cast.zig +++ b/test/cases/cast.zig @@ -14,7 +14,7 @@ test "integer literal to pointer cast" { } test "pointer reinterpret const float to int" { - const float: f64 = 5.99999999999994648725e - 01; + const float: f64 = 5.99999999999994648725e-01; const float_ptr = &float; const int_ptr = @ptrCast(&const i32, float_ptr); const int_val = int_ptr.*; @@ -121,13 +121,13 @@ test "implicitly cast indirect pointer to maybe-indirect pointer" { return (p.*).x; } fn maybeConstConst(p: ?&const &const Self) u8 { - return (??p.*).x; + return ((??p).*).x; } fn constConstConst(p: &const &const &const Self) u8 { return (p.*.*).x; } fn maybeConstConstConst(p: ?&const &const &const Self) u8 { - return (??p.*.*).x; + return ((??p).*.*).x; } }; const s = S { diff --git a/test/cases/generics.zig b/test/cases/generics.zig index da8a7dcad6..3fb33d0495 100644 --- a/test/cases/generics.zig +++ b/test/cases/generics.zig @@ -127,7 +127,7 @@ test "generic fn with implicit cast" { }) == 0); } fn getByte(ptr: ?&const u8) u8 { - return ??ptr.*; + return (??ptr).*; } fn getFirstByte(comptime T: type, mem: []const T) u8 { return getByte(@ptrCast(&const u8, &mem[0])); -- cgit v1.2.3 From 0c16cd2d0ed78be2d160f9c865cd0a8703348232 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 20:23:55 -0400 Subject: run zig fmt on the codebase See #1003 --- std/base64.zig | 1 + std/crypto/blake2.zig | 248 +-- std/fmt/errol/index.zig | 3 +- std/fmt/errol/lookup.zig | 1200 ++++++------- std/fmt/index.zig | 70 +- std/hash/adler.zig | 17 +- std/hash/crc.zig | 5 +- std/hash/fnv.zig | 6 +- std/hash/siphash.zig | 6 +- std/heap.zig | 14 +- std/io_test.zig | 2 +- std/json.zig | 106 +- std/macho.zig | 20 +- std/math/atan.zig | 32 +- std/math/atan2.zig | 6 +- std/math/complex/index.zig | 22 +- std/math/complex/tanh.zig | 4 +- std/math/exp.zig | 30 +- std/math/exp2.zig | 280 +-- std/math/expm1.zig | 24 +- std/math/index.zig | 2 +- std/math/log1p.zig | 3 +- std/math/pow.zig | 1 - std/net.zig | 32 +- std/os/child_process.zig | 11 +- std/os/darwin.zig | 66 + std/os/darwin_errno.zig | 402 +++-- std/os/epoch.zig | 46 +- std/os/file.zig | 59 +- std/os/get_user_id.zig | 6 +- std/os/index.zig | 168 +- std/os/linux/errno.zig | 569 ++++-- std/os/linux/index.zig | 3 +- std/os/linux/test.zig | 12 +- std/os/linux/vdso.zig | 20 +- std/os/linux/x86_64.zig | 114 +- std/os/path.zig | 93 +- std/os/time.zig | 69 +- std/os/windows/error.zig | 1188 +++++++++++++ std/os/windows/index.zig | 178 +- std/os/windows/util.zig | 37 +- std/os/zen.zig | 138 +- std/rand/index.zig | 92 +- std/rand/ziggurat.zig | 30 +- std/segmented_list.zig | 6 +- std/sort.zig | 1 - std/special/bootstrap.zig | 8 +- std/special/bootstrap_lib.zig | 8 +- std/special/build_runner.zig | 6 +- std/special/builtin.zig | 60 +- std/special/compiler_rt/comparetf2.zig | 57 +- std/special/compiler_rt/fixunsdfti_test.zig | 1 - std/special/compiler_rt/index.zig | 14 +- std/unicode.zig | 22 +- std/zig/ast.zig | 9 +- std/zig/parse.zig | 927 +++++----- std/zig/parser_test.zig | 22 +- std/zig/render.zig | 60 +- std/zig/tokenizer.zig | 202 +-- test/cases/align.zig | 12 +- test/cases/array.zig | 12 +- test/cases/bugs/394.zig | 6 +- test/cases/bugs/656.zig | 6 +- test/cases/bugs/828.zig | 8 +- test/cases/cast.zig | 31 +- test/cases/const_slice_child.zig | 2 +- test/cases/coroutines.zig | 23 +- test/cases/enum.zig | 22 +- test/cases/enum_with_members.zig | 8 +- test/cases/error.zig | 22 +- test/cases/eval.zig | 52 +- test/cases/field_parent_ptr.zig | 2 +- test/cases/fn.zig | 2 +- test/cases/fn_in_struct_in_comptime.zig | 2 +- test/cases/for.zig | 6 +- test/cases/generics.zig | 10 +- test/cases/incomplete_struct_param_tld.zig | 8 +- test/cases/math.zig | 2 +- test/cases/misc.zig | 42 +- test/cases/null.zig | 6 +- test/cases/reflection.zig | 2 +- test/cases/slice.zig | 2 +- test/cases/struct.zig | 40 +- test/cases/struct_contains_slice_of_itself.zig | 16 +- test/cases/switch.zig | 54 +- test/cases/switch_prong_err_enum.zig | 4 +- test/cases/switch_prong_implicit_cast.zig | 8 +- test/cases/this.zig | 2 +- test/cases/try.zig | 3 +- test/cases/type_info.zig | 4 +- test/cases/union.zig | 5 +- test/cases/var_args.zig | 2 +- test/cases/void.zig | 2 +- test/cases/while.zig | 4 +- test/compare_output.zig | 4 +- test/compile_errors.zig | 2220 ++++++++++++++++-------- test/gen_h.zig | 1 - test/standalone/brace_expansion/main.zig | 13 +- test/standalone/issue_339/test.zig | 5 +- test/standalone/pkg_import/pkg.zig | 4 +- test/standalone/use_alias/main.zig | 2 +- test/translate_c.zig | 49 +- 102 files changed, 5969 insertions(+), 3599 deletions(-) (limited to 'std/os/linux') diff --git a/std/base64.zig b/std/base64.zig index 515738a99e..b714250992 100644 --- a/std/base64.zig +++ b/std/base64.zig @@ -81,6 +81,7 @@ pub const Base64Decoder = struct { /// e.g. 'A' => 0. /// undefined for any value not in the 64 alphabet chars. char_to_index: [256]u8, + /// true only for the 64 chars in the alphabet, not the pad char. char_in_alphabet: [256]bool, pad_char: u8, diff --git a/std/crypto/blake2.zig b/std/crypto/blake2.zig index 18025d08eb..b48e2fb4ba 100644 --- a/std/crypto/blake2.zig +++ b/std/crypto/blake2.zig @@ -49,16 +49,16 @@ fn Blake2s(comptime out_len: usize) type { }; const sigma = [10][16]u8{ - []const u8 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - []const u8 { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, - []const u8 { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, - []const u8 { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, - []const u8 { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, - []const u8 { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, - []const u8 { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, - []const u8 { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, - []const u8 { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, - []const u8 { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, + []const u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + []const u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + []const u8{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + []const u8{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + []const u8{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + []const u8{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + []const u8{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + []const u8{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + []const u8{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + []const u8{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, }; h: [8]u32, @@ -282,222 +282,18 @@ fn Blake2b(comptime out_len: usize) type { }; const sigma = [12][16]u8{ - []const u8{ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - }, - []const u8{ - 14, - 10, - 4, - 8, - 9, - 15, - 13, - 6, - 1, - 12, - 0, - 2, - 11, - 7, - 5, - 3, - }, - []const u8{ - 11, - 8, - 12, - 0, - 5, - 2, - 15, - 13, - 10, - 14, - 3, - 6, - 7, - 1, - 9, - 4, - }, - []const u8{ - 7, - 9, - 3, - 1, - 13, - 12, - 11, - 14, - 2, - 6, - 5, - 10, - 4, - 0, - 15, - 8, - }, - []const u8{ - 9, - 0, - 5, - 7, - 2, - 4, - 10, - 15, - 14, - 1, - 11, - 12, - 6, - 8, - 3, - 13, - }, - []const u8{ - 2, - 12, - 6, - 10, - 0, - 11, - 8, - 3, - 4, - 13, - 7, - 5, - 15, - 14, - 1, - 9, - }, - []const u8{ - 12, - 5, - 1, - 15, - 14, - 13, - 4, - 10, - 0, - 7, - 6, - 3, - 9, - 2, - 8, - 11, - }, - []const u8{ - 13, - 11, - 7, - 14, - 12, - 1, - 3, - 9, - 5, - 0, - 15, - 4, - 8, - 6, - 2, - 10, - }, - []const u8{ - 6, - 15, - 14, - 9, - 11, - 3, - 0, - 8, - 12, - 2, - 13, - 7, - 1, - 4, - 10, - 5, - }, - []const u8{ - 10, - 2, - 8, - 4, - 7, - 6, - 1, - 5, - 15, - 11, - 9, - 14, - 3, - 12, - 13, - 0, - }, - []const u8{ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - }, - []const u8{ - 14, - 10, - 4, - 8, - 9, - 15, - 13, - 6, - 1, - 12, - 0, - 2, - 11, - 7, - 5, - 3, - }, + []const u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + []const u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + []const u8{ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + []const u8{ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + []const u8{ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + []const u8{ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + []const u8{ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + []const u8{ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + []const u8{ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + []const u8{ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, + []const u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + []const u8{ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, }; h: [8]u64, diff --git a/std/fmt/errol/index.zig b/std/fmt/errol/index.zig index f4ec251b77..9c8fe343b5 100644 --- a/std/fmt/errol/index.zig +++ b/std/fmt/errol/index.zig @@ -98,7 +98,6 @@ pub fn errol3(value: f64, buffer: []u8) FloatDecimal { /// Uncorrected Errol3 double to ASCII conversion. fn errol3u(val: f64, buffer: []u8) FloatDecimal { // check if in integer or fixed range - if (val > 9.007199254740992e15 and val < 3.40282366920938e+38) { return errolInt(val, buffer); } else if (val >= 16.0 and val < 9.007199254740992e15) { @@ -420,7 +419,7 @@ fn fpprev(val: f64) f64 { return @bitCast(f64, @bitCast(u64, val) -% 1); } -pub const c_digits_lut = []u8 { +pub const c_digits_lut = []u8{ '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6', '0', '7', '0', '8', '0', '9', '1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '2', '0', diff --git a/std/fmt/errol/lookup.zig b/std/fmt/errol/lookup.zig index b7b89ba732..bd0a4ac8d1 100644 --- a/std/fmt/errol/lookup.zig +++ b/std/fmt/errol/lookup.zig @@ -3,604 +3,604 @@ pub const HP = struct { off: f64, }; pub const lookup_table = []HP{ - HP{.val=1.000000e+308, .off= -1.097906362944045488e+291 }, - HP{.val=1.000000e+307, .off= 1.396894023974354241e+290 }, - HP{.val=1.000000e+306, .off= -1.721606459673645508e+289 }, - HP{.val=1.000000e+305, .off= 6.074644749446353973e+288 }, - HP{.val=1.000000e+304, .off= 6.074644749446353567e+287 }, - HP{.val=1.000000e+303, .off= -1.617650767864564452e+284 }, - HP{.val=1.000000e+302, .off= -7.629703079084895055e+285 }, - HP{.val=1.000000e+301, .off= -5.250476025520442286e+284 }, - HP{.val=1.000000e+300, .off= -5.250476025520441956e+283 }, - HP{.val=1.000000e+299, .off= -5.250476025520441750e+282 }, - HP{.val=1.000000e+298, .off= 4.043379652465702264e+281 }, - HP{.val=1.000000e+297, .off= -1.765280146275637946e+280 }, - HP{.val=1.000000e+296, .off= 1.865132227937699609e+279 }, - HP{.val=1.000000e+295, .off= 1.865132227937699609e+278 }, - HP{.val=1.000000e+294, .off= -6.643646774124810287e+277 }, - HP{.val=1.000000e+293, .off= 7.537651562646039934e+276 }, - HP{.val=1.000000e+292, .off= -1.325659897835741608e+275 }, - HP{.val=1.000000e+291, .off= 4.213909764965371606e+274 }, - HP{.val=1.000000e+290, .off= -6.172783352786715670e+273 }, - HP{.val=1.000000e+289, .off= -6.172783352786715670e+272 }, - HP{.val=1.000000e+288, .off= -7.630473539575035471e+270 }, - HP{.val=1.000000e+287, .off= -7.525217352494018700e+270 }, - HP{.val=1.000000e+286, .off= -3.298861103408696612e+269 }, - HP{.val=1.000000e+285, .off= 1.984084207947955778e+268 }, - HP{.val=1.000000e+284, .off= -7.921438250845767591e+267 }, - HP{.val=1.000000e+283, .off= 4.460464822646386735e+266 }, - HP{.val=1.000000e+282, .off= -3.278224598286209647e+265 }, - HP{.val=1.000000e+281, .off= -3.278224598286209737e+264 }, - HP{.val=1.000000e+280, .off= -3.278224598286209961e+263 }, - HP{.val=1.000000e+279, .off= -5.797329227496039232e+262 }, - HP{.val=1.000000e+278, .off= 3.649313132040821498e+261 }, - HP{.val=1.000000e+277, .off= -2.867878510995372374e+259 }, - HP{.val=1.000000e+276, .off= -5.206914080024985409e+259 }, - HP{.val=1.000000e+275, .off= 4.018322599210230404e+258 }, - HP{.val=1.000000e+274, .off= 7.862171215558236495e+257 }, - HP{.val=1.000000e+273, .off= 5.459765830340732821e+256 }, - HP{.val=1.000000e+272, .off= -6.552261095746788047e+255 }, - HP{.val=1.000000e+271, .off= 4.709014147460262298e+254 }, - HP{.val=1.000000e+270, .off= -4.675381888545612729e+253 }, - HP{.val=1.000000e+269, .off= -4.675381888545612892e+252 }, - HP{.val=1.000000e+268, .off= 2.656177514583977380e+251 }, - HP{.val=1.000000e+267, .off= 2.656177514583977190e+250 }, - HP{.val=1.000000e+266, .off= -3.071603269111014892e+249 }, - HP{.val=1.000000e+265, .off= -6.651466258920385440e+248 }, - HP{.val=1.000000e+264, .off= -4.414051890289528972e+247 }, - HP{.val=1.000000e+263, .off= -1.617283929500958387e+246 }, - HP{.val=1.000000e+262, .off= -1.617283929500958241e+245 }, - HP{.val=1.000000e+261, .off= 7.122615947963323868e+244 }, - HP{.val=1.000000e+260, .off= -6.533477610574617382e+243 }, - HP{.val=1.000000e+259, .off= 7.122615947963323982e+242 }, - HP{.val=1.000000e+258, .off= -5.679971763165996225e+241 }, - HP{.val=1.000000e+257, .off= -3.012765990014054219e+240 }, - HP{.val=1.000000e+256, .off= -3.012765990014054219e+239 }, - HP{.val=1.000000e+255, .off= 1.154743030535854616e+238 }, - HP{.val=1.000000e+254, .off= 6.364129306223240767e+237 }, - HP{.val=1.000000e+253, .off= 6.364129306223241129e+236 }, - HP{.val=1.000000e+252, .off= -9.915202805299840595e+235 }, - HP{.val=1.000000e+251, .off= -4.827911520448877980e+234 }, - HP{.val=1.000000e+250, .off= 7.890316691678530146e+233 }, - HP{.val=1.000000e+249, .off= 7.890316691678529484e+232 }, - HP{.val=1.000000e+248, .off= -4.529828046727141859e+231 }, - HP{.val=1.000000e+247, .off= 4.785280507077111924e+230 }, - HP{.val=1.000000e+246, .off= -6.858605185178205305e+229 }, - HP{.val=1.000000e+245, .off= -4.432795665958347728e+228 }, - HP{.val=1.000000e+244, .off= -7.465057564983169531e+227 }, - HP{.val=1.000000e+243, .off= -7.465057564983169741e+226 }, - HP{.val=1.000000e+242, .off= -5.096102956370027445e+225 }, - HP{.val=1.000000e+241, .off= -5.096102956370026952e+224 }, - HP{.val=1.000000e+240, .off= -1.394611380411992474e+223 }, - HP{.val=1.000000e+239, .off= 9.188208545617793960e+221 }, - HP{.val=1.000000e+238, .off= -4.864759732872650359e+221 }, - HP{.val=1.000000e+237, .off= 5.979453868566904629e+220 }, - HP{.val=1.000000e+236, .off= -5.316601966265964857e+219 }, - HP{.val=1.000000e+235, .off= -5.316601966265964701e+218 }, - HP{.val=1.000000e+234, .off= -1.786584517880693123e+217 }, - HP{.val=1.000000e+233, .off= 2.625937292600896716e+216 }, - HP{.val=1.000000e+232, .off= -5.647541102052084079e+215 }, - HP{.val=1.000000e+231, .off= -5.647541102052083888e+214 }, - HP{.val=1.000000e+230, .off= -9.956644432600511943e+213 }, - HP{.val=1.000000e+229, .off= 8.161138937705571862e+211 }, - HP{.val=1.000000e+228, .off= 7.549087847752475275e+211 }, - HP{.val=1.000000e+227, .off= -9.283347037202319948e+210 }, - HP{.val=1.000000e+226, .off= 3.866992716668613820e+209 }, - HP{.val=1.000000e+225, .off= 7.154577655136347262e+208 }, - HP{.val=1.000000e+224, .off= 3.045096482051680688e+207 }, - HP{.val=1.000000e+223, .off= -4.660180717482069567e+206 }, - HP{.val=1.000000e+222, .off= -4.660180717482070101e+205 }, - HP{.val=1.000000e+221, .off= -4.660180717482069544e+204 }, - HP{.val=1.000000e+220, .off= 3.562757926310489022e+202 }, - HP{.val=1.000000e+219, .off= 3.491561111451748149e+202 }, - HP{.val=1.000000e+218, .off= -8.265758834125874135e+201 }, - HP{.val=1.000000e+217, .off= 3.981449442517482365e+200 }, - HP{.val=1.000000e+216, .off= -2.142154695804195936e+199 }, - HP{.val=1.000000e+215, .off= 9.339603063548950188e+198 }, - HP{.val=1.000000e+214, .off= 4.555537330485139746e+197 }, - HP{.val=1.000000e+213, .off= 1.565496247320257804e+196 }, - HP{.val=1.000000e+212, .off= 9.040598955232462036e+195 }, - HP{.val=1.000000e+211, .off= 4.368659762787334780e+194 }, - HP{.val=1.000000e+210, .off= 7.288621758065539072e+193 }, - HP{.val=1.000000e+209, .off= -7.311188218325485628e+192 }, - HP{.val=1.000000e+208, .off= 1.813693016918905189e+191 }, - HP{.val=1.000000e+207, .off= -3.889357755108838992e+190 }, - HP{.val=1.000000e+206, .off= -3.889357755108838992e+189 }, - HP{.val=1.000000e+205, .off= -1.661603547285501360e+188 }, - HP{.val=1.000000e+204, .off= 1.123089212493670643e+187 }, - HP{.val=1.000000e+203, .off= 1.123089212493670643e+186 }, - HP{.val=1.000000e+202, .off= 9.825254086803583029e+185 }, - HP{.val=1.000000e+201, .off= -3.771878529305654999e+184 }, - HP{.val=1.000000e+200, .off= 3.026687778748963675e+183 }, - HP{.val=1.000000e+199, .off= -9.720624048853446693e+182 }, - HP{.val=1.000000e+198, .off= -1.753554156601940139e+181 }, - HP{.val=1.000000e+197, .off= 4.885670753607648963e+180 }, - HP{.val=1.000000e+196, .off= 4.885670753607648963e+179 }, - HP{.val=1.000000e+195, .off= 2.292223523057028076e+178 }, - HP{.val=1.000000e+194, .off= 5.534032561245303825e+177 }, - HP{.val=1.000000e+193, .off= -6.622751331960730683e+176 }, - HP{.val=1.000000e+192, .off= -4.090088020876139692e+175 }, - HP{.val=1.000000e+191, .off= -7.255917159731877552e+174 }, - HP{.val=1.000000e+190, .off= -7.255917159731877992e+173 }, - HP{.val=1.000000e+189, .off= -2.309309130269787104e+172 }, - HP{.val=1.000000e+188, .off= -2.309309130269787019e+171 }, - HP{.val=1.000000e+187, .off= 9.284303438781988230e+170 }, - HP{.val=1.000000e+186, .off= 2.038295583124628364e+169 }, - HP{.val=1.000000e+185, .off= 2.038295583124628532e+168 }, - HP{.val=1.000000e+184, .off= -1.735666841696912925e+167 }, - HP{.val=1.000000e+183, .off= 5.340512704843477241e+166 }, - HP{.val=1.000000e+182, .off= -6.453119872723839321e+165 }, - HP{.val=1.000000e+181, .off= 8.288920849235306587e+164 }, - HP{.val=1.000000e+180, .off= -9.248546019891598293e+162 }, - HP{.val=1.000000e+179, .off= 1.954450226518486016e+162 }, - HP{.val=1.000000e+178, .off= -5.243811844750628197e+161 }, - HP{.val=1.000000e+177, .off= -7.448980502074320639e+159 }, - HP{.val=1.000000e+176, .off= -7.448980502074319858e+158 }, - HP{.val=1.000000e+175, .off= 6.284654753766312753e+158 }, - HP{.val=1.000000e+174, .off= -6.895756753684458388e+157 }, - HP{.val=1.000000e+173, .off= -1.403918625579970616e+156 }, - HP{.val=1.000000e+172, .off= -8.268716285710580522e+155 }, - HP{.val=1.000000e+171, .off= 4.602779327034313170e+154 }, - HP{.val=1.000000e+170, .off= -3.441905430931244940e+153 }, - HP{.val=1.000000e+169, .off= 6.613950516525702884e+152 }, - HP{.val=1.000000e+168, .off= 6.613950516525702652e+151 }, - HP{.val=1.000000e+167, .off= -3.860899428741951187e+150 }, - HP{.val=1.000000e+166, .off= 5.959272394946474605e+149 }, - HP{.val=1.000000e+165, .off= 1.005101065481665103e+149 }, - HP{.val=1.000000e+164, .off= -1.783349948587918355e+146 }, - HP{.val=1.000000e+163, .off= 6.215006036188360099e+146 }, - HP{.val=1.000000e+162, .off= 6.215006036188360099e+145 }, - HP{.val=1.000000e+161, .off= -3.774589324822814903e+144 }, - HP{.val=1.000000e+160, .off= -6.528407745068226929e+142 }, - HP{.val=1.000000e+159, .off= 7.151530601283157561e+142 }, - HP{.val=1.000000e+158, .off= 4.712664546348788765e+141 }, - HP{.val=1.000000e+157, .off= 1.664081977680827856e+140 }, - HP{.val=1.000000e+156, .off= 1.664081977680827750e+139 }, - HP{.val=1.000000e+155, .off= -7.176231540910168265e+137 }, - HP{.val=1.000000e+154, .off= -3.694754568805822650e+137 }, - HP{.val=1.000000e+153, .off= 2.665969958768462622e+134 }, - HP{.val=1.000000e+152, .off= -4.625108135904199522e+135 }, - HP{.val=1.000000e+151, .off= -1.717753238721771919e+134 }, - HP{.val=1.000000e+150, .off= 1.916440382756262433e+133 }, - HP{.val=1.000000e+149, .off= -4.897672657515052040e+132 }, - HP{.val=1.000000e+148, .off= -4.897672657515052198e+131 }, - HP{.val=1.000000e+147, .off= 2.200361759434233991e+130 }, - HP{.val=1.000000e+146, .off= 6.636633270027537273e+129 }, - HP{.val=1.000000e+145, .off= 1.091293881785907977e+128 }, - HP{.val=1.000000e+144, .off= -2.374543235865110597e+127 }, - HP{.val=1.000000e+143, .off= -2.374543235865110537e+126 }, - HP{.val=1.000000e+142, .off= -5.082228484029969099e+125 }, - HP{.val=1.000000e+141, .off= -1.697621923823895943e+124 }, - HP{.val=1.000000e+140, .off= -5.928380124081487212e+123 }, - HP{.val=1.000000e+139, .off= -3.284156248920492522e+122 }, - HP{.val=1.000000e+138, .off= -3.284156248920492706e+121 }, - HP{.val=1.000000e+137, .off= -3.284156248920492476e+120 }, - HP{.val=1.000000e+136, .off= -5.866406127007401066e+119 }, - HP{.val=1.000000e+135, .off= 3.817030915818506056e+118 }, - HP{.val=1.000000e+134, .off= 7.851796350329300951e+117 }, - HP{.val=1.000000e+133, .off= -2.235117235947686077e+116 }, - HP{.val=1.000000e+132, .off= 9.170432597638723691e+114 }, - HP{.val=1.000000e+131, .off= 8.797444499042767883e+114 }, - HP{.val=1.000000e+130, .off= -5.978307824605161274e+113 }, - HP{.val=1.000000e+129, .off= 1.782556435814758516e+111 }, - HP{.val=1.000000e+128, .off= -7.517448691651820362e+111 }, - HP{.val=1.000000e+127, .off= 4.507089332150205498e+110 }, - HP{.val=1.000000e+126, .off= 7.513223838100711695e+109 }, - HP{.val=1.000000e+125, .off= 7.513223838100712113e+108 }, - HP{.val=1.000000e+124, .off= 5.164681255326878494e+107 }, - HP{.val=1.000000e+123, .off= 2.229003026859587122e+106 }, - HP{.val=1.000000e+122, .off= -1.440594758724527399e+105 }, - HP{.val=1.000000e+121, .off= -3.734093374714598783e+104 }, - HP{.val=1.000000e+120, .off= 1.999653165260579757e+103 }, - HP{.val=1.000000e+119, .off= 5.583244752745066693e+102 }, - HP{.val=1.000000e+118, .off= 3.343500010567262234e+101 }, - HP{.val=1.000000e+117, .off= -5.055542772599503556e+100 }, - HP{.val=1.000000e+116, .off= -1.555941612946684331e+99 }, - HP{.val=1.000000e+115, .off= -1.555941612946684331e+98 }, - HP{.val=1.000000e+114, .off= -1.555941612946684293e+97 }, - HP{.val=1.000000e+113, .off= -1.555941612946684246e+96 }, - HP{.val=1.000000e+112, .off= 6.988006530736955847e+95 }, - HP{.val=1.000000e+111, .off= 4.318022735835818244e+94 }, - HP{.val=1.000000e+110, .off= -2.356936751417025578e+93 }, - HP{.val=1.000000e+109, .off= 1.814912928116001926e+92 }, - HP{.val=1.000000e+108, .off= -3.399899171300282744e+91 }, - HP{.val=1.000000e+107, .off= 3.118615952970072913e+90 }, - HP{.val=1.000000e+106, .off= -9.103599905036843605e+89 }, - HP{.val=1.000000e+105, .off= 6.174169917471802325e+88 }, - HP{.val=1.000000e+104, .off= -1.915675085734668657e+86 }, - HP{.val=1.000000e+103, .off= -1.915675085734668864e+85 }, - HP{.val=1.000000e+102, .off= 2.295048673475466221e+85 }, - HP{.val=1.000000e+101, .off= 2.295048673475466135e+84 }, - HP{.val=1.000000e+100, .off= -1.590289110975991792e+83 }, - HP{.val=1.000000e+99, .off= 3.266383119588331155e+82 }, - HP{.val=1.000000e+98, .off= 2.309629754856292029e+80 }, - HP{.val=1.000000e+97, .off= -7.357587384771124533e+80 }, - HP{.val=1.000000e+96, .off= -4.986165397190889509e+79 }, - HP{.val=1.000000e+95, .off= -2.021887912715594741e+78 }, - HP{.val=1.000000e+94, .off= -2.021887912715594638e+77 }, - HP{.val=1.000000e+93, .off= -4.337729697461918675e+76 }, - HP{.val=1.000000e+92, .off= -4.337729697461918997e+75 }, - HP{.val=1.000000e+91, .off= -7.956232486128049702e+74 }, - HP{.val=1.000000e+90, .off= 3.351588728453609882e+73 }, - HP{.val=1.000000e+89, .off= 5.246334248081951113e+71 }, - HP{.val=1.000000e+88, .off= 4.058327554364963672e+71 }, - HP{.val=1.000000e+87, .off= 4.058327554364963918e+70 }, - HP{.val=1.000000e+86, .off= -1.463069523067487266e+69 }, - HP{.val=1.000000e+85, .off= -1.463069523067487314e+68 }, - HP{.val=1.000000e+84, .off= -5.776660989811589441e+67 }, - HP{.val=1.000000e+83, .off= -3.080666323096525761e+66 }, - HP{.val=1.000000e+82, .off= 3.659320343691134468e+65 }, - HP{.val=1.000000e+81, .off= 7.871812010433421235e+64 }, - HP{.val=1.000000e+80, .off= -2.660986470836727449e+61 }, - HP{.val=1.000000e+79, .off= 3.264399249934044627e+62 }, - HP{.val=1.000000e+78, .off= -8.493621433689703070e+60 }, - HP{.val=1.000000e+77, .off= 1.721738727445414063e+60 }, - HP{.val=1.000000e+76, .off= -4.706013449590547218e+59 }, - HP{.val=1.000000e+75, .off= 7.346021882351880518e+58 }, - HP{.val=1.000000e+74, .off= 4.835181188197207515e+57 }, - HP{.val=1.000000e+73, .off= 1.696630320503867482e+56 }, - HP{.val=1.000000e+72, .off= 5.619818905120542959e+55 }, - HP{.val=1.000000e+71, .off= -4.188152556421145598e+54 }, - HP{.val=1.000000e+70, .off= -7.253143638152923145e+53 }, - HP{.val=1.000000e+69, .off= -7.253143638152923145e+52 }, - HP{.val=1.000000e+68, .off= 4.719477774861832896e+51 }, - HP{.val=1.000000e+67, .off= 1.726322421608144052e+50 }, - HP{.val=1.000000e+66, .off= 5.467766613175255107e+49 }, - HP{.val=1.000000e+65, .off= 7.909613737163661911e+47 }, - HP{.val=1.000000e+64, .off= -2.132041900945439564e+47 }, - HP{.val=1.000000e+63, .off= -5.785795994272697265e+46 }, - HP{.val=1.000000e+62, .off= -3.502199685943161329e+45 }, - HP{.val=1.000000e+61, .off= 5.061286470292598274e+44 }, - HP{.val=1.000000e+60, .off= 5.061286470292598472e+43 }, - HP{.val=1.000000e+59, .off= 2.831211950439536034e+42 }, - HP{.val=1.000000e+58, .off= 5.618805100255863927e+41 }, - HP{.val=1.000000e+57, .off= -4.834669211555366251e+40 }, - HP{.val=1.000000e+56, .off= -9.190283508143378583e+39 }, - HP{.val=1.000000e+55, .off= -1.023506702040855158e+38 }, - HP{.val=1.000000e+54, .off= -7.829154040459624616e+37 }, - HP{.val=1.000000e+53, .off= 6.779051325638372659e+35 }, - HP{.val=1.000000e+52, .off= 6.779051325638372290e+34 }, - HP{.val=1.000000e+51, .off= 6.779051325638371598e+33 }, - HP{.val=1.000000e+50, .off= -7.629769841091887392e+33 }, - HP{.val=1.000000e+49, .off= 5.350972305245182400e+32 }, - HP{.val=1.000000e+48, .off= -4.384584304507619764e+31 }, - HP{.val=1.000000e+47, .off= -4.384584304507619876e+30 }, - HP{.val=1.000000e+46, .off= 6.860180964052978705e+28 }, - HP{.val=1.000000e+45, .off= 7.024271097546444878e+28 }, - HP{.val=1.000000e+44, .off= -8.821361405306422641e+27 }, - HP{.val=1.000000e+43, .off= -1.393721169594140991e+26 }, - HP{.val=1.000000e+42, .off= -4.488571267807591679e+25 }, - HP{.val=1.000000e+41, .off= -6.200086450407783195e+23 }, - HP{.val=1.000000e+40, .off= -3.037860284270036669e+23 }, - HP{.val=1.000000e+39, .off= 6.029083362839682141e+22 }, - HP{.val=1.000000e+38, .off= 2.251190176543965970e+21 }, - HP{.val=1.000000e+37, .off= 4.612373417978788577e+20 }, - HP{.val=1.000000e+36, .off= -4.242063737401796198e+19 }, - HP{.val=1.000000e+35, .off= 3.136633892082024448e+18 }, - HP{.val=1.000000e+34, .off= 5.442476901295718400e+17 }, - HP{.val=1.000000e+33, .off= 5.442476901295718400e+16 }, - HP{.val=1.000000e+32, .off= -5.366162204393472000e+15 }, - HP{.val=1.000000e+31, .off= 3.641037050347520000e+14 }, - HP{.val=1.000000e+30, .off= -1.988462483865600000e+13 }, - HP{.val=1.000000e+29, .off= 8.566849142784000000e+12 }, - HP{.val=1.000000e+28, .off= 4.168802631680000000e+11 }, - HP{.val=1.000000e+27, .off= -1.328755507200000000e+10 }, - HP{.val=1.000000e+26, .off= -4.764729344000000000e+09 }, - HP{.val=1.000000e+25, .off= -9.059696640000000000e+08 }, - HP{.val=1.000000e+24, .off= 1.677721600000000000e+07 }, - HP{.val=1.000000e+23, .off= 8.388608000000000000e+06 }, - HP{.val=1.000000e+22, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+21, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+20, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+19, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+18, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+17, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+16, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+15, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+14, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+13, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+12, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+11, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+10, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+09, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+08, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+07, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+06, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+05, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+04, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+03, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+02, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+01, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e+00, .off= 0.000000000000000000e+00 }, - HP{.val=1.000000e-01, .off= -5.551115123125783010e-18 }, - HP{.val=1.000000e-02, .off= -2.081668171172168436e-19 }, - HP{.val=1.000000e-03, .off= -2.081668171172168557e-20 }, - HP{.val=1.000000e-04, .off= -4.792173602385929943e-21 }, - HP{.val=1.000000e-05, .off= -8.180305391403130547e-22 }, - HP{.val=1.000000e-06, .off= 4.525188817411374069e-23 }, - HP{.val=1.000000e-07, .off= 4.525188817411373922e-24 }, - HP{.val=1.000000e-08, .off= -2.092256083012847109e-25 }, - HP{.val=1.000000e-09, .off= -6.228159145777985254e-26 }, - HP{.val=1.000000e-10, .off= -3.643219731549774344e-27 }, - HP{.val=1.000000e-11, .off= 6.050303071806019080e-28 }, - HP{.val=1.000000e-12, .off= 2.011335237074438524e-29 }, - HP{.val=1.000000e-13, .off= -3.037374556340037101e-30 }, - HP{.val=1.000000e-14, .off= 1.180690645440101289e-32 }, - HP{.val=1.000000e-15, .off= -7.770539987666107583e-32 }, - HP{.val=1.000000e-16, .off= 2.090221327596539779e-33 }, - HP{.val=1.000000e-17, .off= -7.154242405462192144e-34 }, - HP{.val=1.000000e-18, .off= -7.154242405462192572e-35 }, - HP{.val=1.000000e-19, .off= 2.475407316473986894e-36 }, - HP{.val=1.000000e-20, .off= 5.484672854579042914e-37 }, - HP{.val=1.000000e-21, .off= 9.246254777210362522e-38 }, - HP{.val=1.000000e-22, .off= -4.859677432657087182e-39 }, - HP{.val=1.000000e-23, .off= 3.956530198510069291e-40 }, - HP{.val=1.000000e-24, .off= 7.629950044829717753e-41 }, - HP{.val=1.000000e-25, .off= -3.849486974919183692e-42 }, - HP{.val=1.000000e-26, .off= -3.849486974919184170e-43 }, - HP{.val=1.000000e-27, .off= -3.849486974919184070e-44 }, - HP{.val=1.000000e-28, .off= 2.876745653839937870e-45 }, - HP{.val=1.000000e-29, .off= 5.679342582489572168e-46 }, - HP{.val=1.000000e-30, .off= -8.333642060758598930e-47 }, - HP{.val=1.000000e-31, .off= -8.333642060758597958e-48 }, - HP{.val=1.000000e-32, .off= -5.596730997624190224e-49 }, - HP{.val=1.000000e-33, .off= -5.596730997624190604e-50 }, - HP{.val=1.000000e-34, .off= 7.232539610818348498e-51 }, - HP{.val=1.000000e-35, .off= -7.857545194582380514e-53 }, - HP{.val=1.000000e-36, .off= 5.896157255772251528e-53 }, - HP{.val=1.000000e-37, .off= -6.632427322784915796e-54 }, - HP{.val=1.000000e-38, .off= 3.808059826012723592e-55 }, - HP{.val=1.000000e-39, .off= 7.070712060011985131e-56 }, - HP{.val=1.000000e-40, .off= 7.070712060011985584e-57 }, - HP{.val=1.000000e-41, .off= -5.761291134237854167e-59 }, - HP{.val=1.000000e-42, .off= -3.762312935688689794e-59 }, - HP{.val=1.000000e-43, .off= -7.745042713519821150e-60 }, - HP{.val=1.000000e-44, .off= 4.700987842202462817e-61 }, - HP{.val=1.000000e-45, .off= 1.589480203271891964e-62 }, - HP{.val=1.000000e-46, .off= -2.299904345391321765e-63 }, - HP{.val=1.000000e-47, .off= 2.561826340437695261e-64 }, - HP{.val=1.000000e-48, .off= 2.561826340437695345e-65 }, - HP{.val=1.000000e-49, .off= 6.360053438741614633e-66 }, - HP{.val=1.000000e-50, .off= -7.616223705782342295e-68 }, - HP{.val=1.000000e-51, .off= -7.616223705782343324e-69 }, - HP{.val=1.000000e-52, .off= -7.616223705782342295e-70 }, - HP{.val=1.000000e-53, .off= -3.079876214757872338e-70 }, - HP{.val=1.000000e-54, .off= -3.079876214757872821e-71 }, - HP{.val=1.000000e-55, .off= 5.423954167728123147e-73 }, - HP{.val=1.000000e-56, .off= -3.985444122640543680e-73 }, - HP{.val=1.000000e-57, .off= 4.504255013759498850e-74 }, - HP{.val=1.000000e-58, .off= -2.570494266573869991e-75 }, - HP{.val=1.000000e-59, .off= -2.570494266573869930e-76 }, - HP{.val=1.000000e-60, .off= 2.956653608686574324e-77 }, - HP{.val=1.000000e-61, .off= -3.952281235388981376e-78 }, - HP{.val=1.000000e-62, .off= -3.952281235388981376e-79 }, - HP{.val=1.000000e-63, .off= -6.651083908855995172e-80 }, - HP{.val=1.000000e-64, .off= 3.469426116645307030e-81 }, - HP{.val=1.000000e-65, .off= 7.686305293937516319e-82 }, - HP{.val=1.000000e-66, .off= 2.415206322322254927e-83 }, - HP{.val=1.000000e-67, .off= 5.709643179581793251e-84 }, - HP{.val=1.000000e-68, .off= -6.644495035141475923e-85 }, - HP{.val=1.000000e-69, .off= 3.650620143794581913e-86 }, - HP{.val=1.000000e-70, .off= 4.333966503770636492e-88 }, - HP{.val=1.000000e-71, .off= 8.476455383920859113e-88 }, - HP{.val=1.000000e-72, .off= 3.449543675455986564e-89 }, - HP{.val=1.000000e-73, .off= 3.077238576654418974e-91 }, - HP{.val=1.000000e-74, .off= 4.234998629903623140e-91 }, - HP{.val=1.000000e-75, .off= 4.234998629903623412e-92 }, - HP{.val=1.000000e-76, .off= 7.303182045714702338e-93 }, - HP{.val=1.000000e-77, .off= 7.303182045714701699e-94 }, - HP{.val=1.000000e-78, .off= 1.121271649074855759e-96 }, - HP{.val=1.000000e-79, .off= 1.121271649074855863e-97 }, - HP{.val=1.000000e-80, .off= 3.857468248661243988e-97 }, - HP{.val=1.000000e-81, .off= 3.857468248661244248e-98 }, - HP{.val=1.000000e-82, .off= 3.857468248661244410e-99 }, - HP{.val=1.000000e-83, .off= -3.457651055545315679e-100 }, - HP{.val=1.000000e-84, .off= -3.457651055545315933e-101 }, - HP{.val=1.000000e-85, .off= 2.257285900866059216e-102 }, - HP{.val=1.000000e-86, .off= -8.458220892405268345e-103 }, - HP{.val=1.000000e-87, .off= -1.761029146610688867e-104 }, - HP{.val=1.000000e-88, .off= 6.610460535632536565e-105 }, - HP{.val=1.000000e-89, .off= -3.853901567171494935e-106 }, - HP{.val=1.000000e-90, .off= 5.062493089968513723e-108 }, - HP{.val=1.000000e-91, .off= -2.218844988608365240e-108 }, - HP{.val=1.000000e-92, .off= 1.187522883398155383e-109 }, - HP{.val=1.000000e-93, .off= 9.703442563414457296e-110 }, - HP{.val=1.000000e-94, .off= 4.380992763404268896e-111 }, - HP{.val=1.000000e-95, .off= 1.054461638397900823e-112 }, - HP{.val=1.000000e-96, .off= 9.370789450913819736e-113 }, - HP{.val=1.000000e-97, .off= -3.623472756142303998e-114 }, - HP{.val=1.000000e-98, .off= 6.122223899149788839e-115 }, - HP{.val=1.000000e-99, .off= -1.999189980260288281e-116 }, - HP{.val=1.000000e-100, .off= -1.999189980260288281e-117 }, - HP{.val=1.000000e-101, .off= -5.171617276904849634e-118 }, - HP{.val=1.000000e-102, .off= 6.724985085512256320e-119 }, - HP{.val=1.000000e-103, .off= 4.246526260008692213e-120 }, - HP{.val=1.000000e-104, .off= 7.344599791888147003e-121 }, - HP{.val=1.000000e-105, .off= 3.472007877038828407e-122 }, - HP{.val=1.000000e-106, .off= 5.892377823819652194e-123 }, - HP{.val=1.000000e-107, .off= -1.585470431324073925e-125 }, - HP{.val=1.000000e-108, .off= -3.940375084977444795e-125 }, - HP{.val=1.000000e-109, .off= 7.869099673288519908e-127 }, - HP{.val=1.000000e-110, .off= -5.122196348054018581e-127 }, - HP{.val=1.000000e-111, .off= -8.815387795168313713e-128 }, - HP{.val=1.000000e-112, .off= 5.034080131510290214e-129 }, - HP{.val=1.000000e-113, .off= 2.148774313452247863e-130 }, - HP{.val=1.000000e-114, .off= -5.064490231692858416e-131 }, - HP{.val=1.000000e-115, .off= -5.064490231692858166e-132 }, - HP{.val=1.000000e-116, .off= 5.708726942017560559e-134 }, - HP{.val=1.000000e-117, .off= -2.951229134482377772e-134 }, - HP{.val=1.000000e-118, .off= 1.451398151372789513e-135 }, - HP{.val=1.000000e-119, .off= -1.300243902286690040e-136 }, - HP{.val=1.000000e-120, .off= 2.139308664787659449e-137 }, - HP{.val=1.000000e-121, .off= 2.139308664787659329e-138 }, - HP{.val=1.000000e-122, .off= -5.922142664292847471e-139 }, - HP{.val=1.000000e-123, .off= -5.922142664292846912e-140 }, - HP{.val=1.000000e-124, .off= 6.673875037395443799e-141 }, - HP{.val=1.000000e-125, .off= -1.198636026159737932e-142 }, - HP{.val=1.000000e-126, .off= 5.361789860136246995e-143 }, - HP{.val=1.000000e-127, .off= -2.838742497733733936e-144 }, - HP{.val=1.000000e-128, .off= -5.401408859568103261e-145 }, - HP{.val=1.000000e-129, .off= 7.411922949603743011e-146 }, - HP{.val=1.000000e-130, .off= -8.604741811861064385e-147 }, - HP{.val=1.000000e-131, .off= 1.405673664054439890e-148 }, - HP{.val=1.000000e-132, .off= 1.405673664054439933e-149 }, - HP{.val=1.000000e-133, .off= -6.414963426504548053e-150 }, - HP{.val=1.000000e-134, .off= -3.971014335704864578e-151 }, - HP{.val=1.000000e-135, .off= -3.971014335704864748e-152 }, - HP{.val=1.000000e-136, .off= -1.523438813303585576e-154 }, - HP{.val=1.000000e-137, .off= 2.234325152653707766e-154 }, - HP{.val=1.000000e-138, .off= -6.715683724786540160e-155 }, - HP{.val=1.000000e-139, .off= -2.986513359186437306e-156 }, - HP{.val=1.000000e-140, .off= 1.674949597813692102e-157 }, - HP{.val=1.000000e-141, .off= -4.151879098436469092e-158 }, - HP{.val=1.000000e-142, .off= -4.151879098436469295e-159 }, - HP{.val=1.000000e-143, .off= 4.952540739454407825e-160 }, - HP{.val=1.000000e-144, .off= 4.952540739454407667e-161 }, - HP{.val=1.000000e-145, .off= 8.508954738630531443e-162 }, - HP{.val=1.000000e-146, .off= -2.604839008794855481e-163 }, - HP{.val=1.000000e-147, .off= 2.952057864917838382e-164 }, - HP{.val=1.000000e-148, .off= 6.425118410988271757e-165 }, - HP{.val=1.000000e-149, .off= 2.083792728400229858e-166 }, - HP{.val=1.000000e-150, .off= -6.295358232172964237e-168 }, - HP{.val=1.000000e-151, .off= 6.153785555826519421e-168 }, - HP{.val=1.000000e-152, .off= -6.564942029880634994e-169 }, - HP{.val=1.000000e-153, .off= -3.915207116191644540e-170 }, - HP{.val=1.000000e-154, .off= 2.709130168030831503e-171 }, - HP{.val=1.000000e-155, .off= -1.431080634608215966e-172 }, - HP{.val=1.000000e-156, .off= -4.018712386257620994e-173 }, - HP{.val=1.000000e-157, .off= 5.684906682427646782e-174 }, - HP{.val=1.000000e-158, .off= -6.444617153428937489e-175 }, - HP{.val=1.000000e-159, .off= 1.136335243981427681e-176 }, - HP{.val=1.000000e-160, .off= 1.136335243981427725e-177 }, - HP{.val=1.000000e-161, .off= -2.812077463003137395e-178 }, - HP{.val=1.000000e-162, .off= 4.591196362592922204e-179 }, - HP{.val=1.000000e-163, .off= 7.675893789924613703e-180 }, - HP{.val=1.000000e-164, .off= 3.820022005759999543e-181 }, - HP{.val=1.000000e-165, .off= -9.998177244457686588e-183 }, - HP{.val=1.000000e-166, .off= -4.012217555824373639e-183 }, - HP{.val=1.000000e-167, .off= -2.467177666011174334e-185 }, - HP{.val=1.000000e-168, .off= -4.953592503130188139e-185 }, - HP{.val=1.000000e-169, .off= -2.011795792799518887e-186 }, - HP{.val=1.000000e-170, .off= 1.665450095113817423e-187 }, - HP{.val=1.000000e-171, .off= 1.665450095113817487e-188 }, - HP{.val=1.000000e-172, .off= -4.080246604750770577e-189 }, - HP{.val=1.000000e-173, .off= -4.080246604750770677e-190 }, - HP{.val=1.000000e-174, .off= 4.085789420184387951e-192 }, - HP{.val=1.000000e-175, .off= 4.085789420184388146e-193 }, - HP{.val=1.000000e-176, .off= 4.085789420184388146e-194 }, - HP{.val=1.000000e-177, .off= 4.792197640035244894e-194 }, - HP{.val=1.000000e-178, .off= 4.792197640035244742e-195 }, - HP{.val=1.000000e-179, .off= -2.057206575616014662e-196 }, - HP{.val=1.000000e-180, .off= -2.057206575616014662e-197 }, - HP{.val=1.000000e-181, .off= -4.732755097354788053e-198 }, - HP{.val=1.000000e-182, .off= -4.732755097354787867e-199 }, - HP{.val=1.000000e-183, .off= -5.522105321379546765e-201 }, - HP{.val=1.000000e-184, .off= -5.777891238658996019e-201 }, - HP{.val=1.000000e-185, .off= 7.542096444923057046e-203 }, - HP{.val=1.000000e-186, .off= 8.919335748431433483e-203 }, - HP{.val=1.000000e-187, .off= -1.287071881492476028e-204 }, - HP{.val=1.000000e-188, .off= 5.091932887209967018e-205 }, - HP{.val=1.000000e-189, .off= -6.868701054107114024e-206 }, - HP{.val=1.000000e-190, .off= -1.885103578558330118e-207 }, - HP{.val=1.000000e-191, .off= -1.885103578558330205e-208 }, - HP{.val=1.000000e-192, .off= -9.671974634103305058e-209 }, - HP{.val=1.000000e-193, .off= -4.805180224387695640e-210 }, - HP{.val=1.000000e-194, .off= -1.763433718315439838e-211 }, - HP{.val=1.000000e-195, .off= -9.367799983496079132e-212 }, - HP{.val=1.000000e-196, .off= -4.615071067758179837e-213 }, - HP{.val=1.000000e-197, .off= 1.325840076914194777e-214 }, - HP{.val=1.000000e-198, .off= 8.751979007754662425e-215 }, - HP{.val=1.000000e-199, .off= 1.789973760091724198e-216 }, - HP{.val=1.000000e-200, .off= 1.789973760091724077e-217 }, - HP{.val=1.000000e-201, .off= 5.416018159916171171e-218 }, - HP{.val=1.000000e-202, .off= -3.649092839644947067e-219 }, - HP{.val=1.000000e-203, .off= -3.649092839644947067e-220 }, - HP{.val=1.000000e-204, .off= -1.080338554413850956e-222 }, - HP{.val=1.000000e-205, .off= -1.080338554413850841e-223 }, - HP{.val=1.000000e-206, .off= -2.874486186850417807e-223 }, - HP{.val=1.000000e-207, .off= 7.499710055933455072e-224 }, - HP{.val=1.000000e-208, .off= -9.790617015372999087e-225 }, - HP{.val=1.000000e-209, .off= -4.387389805589732612e-226 }, - HP{.val=1.000000e-210, .off= -4.387389805589732612e-227 }, - HP{.val=1.000000e-211, .off= -8.608661063232909897e-228 }, - HP{.val=1.000000e-212, .off= 4.582811616902018972e-229 }, - HP{.val=1.000000e-213, .off= 4.582811616902019155e-230 }, - HP{.val=1.000000e-214, .off= 8.705146829444184930e-231 }, - HP{.val=1.000000e-215, .off= -4.177150709750081830e-232 }, - HP{.val=1.000000e-216, .off= -4.177150709750082366e-233 }, - HP{.val=1.000000e-217, .off= -8.202868690748290237e-234 }, - HP{.val=1.000000e-218, .off= -3.170721214500530119e-235 }, - HP{.val=1.000000e-219, .off= -3.170721214500529857e-236 }, - HP{.val=1.000000e-220, .off= 7.606440013180328441e-238 }, - HP{.val=1.000000e-221, .off= -1.696459258568569049e-238 }, - HP{.val=1.000000e-222, .off= -4.767838333426821244e-239 }, - HP{.val=1.000000e-223, .off= 2.910609353718809138e-240 }, - HP{.val=1.000000e-224, .off= -1.888420450747209784e-241 }, - HP{.val=1.000000e-225, .off= 4.110366804835314035e-242 }, - HP{.val=1.000000e-226, .off= 7.859608839574391006e-243 }, - HP{.val=1.000000e-227, .off= 5.516332567862468419e-244 }, - HP{.val=1.000000e-228, .off= -3.270953451057244613e-245 }, - HP{.val=1.000000e-229, .off= -6.932322625607124670e-246 }, - HP{.val=1.000000e-230, .off= -4.643966891513449762e-247 }, - HP{.val=1.000000e-231, .off= 1.076922443720738305e-248 }, - HP{.val=1.000000e-232, .off= -2.498633390800628939e-249 }, - HP{.val=1.000000e-233, .off= 4.205533798926934891e-250 }, - HP{.val=1.000000e-234, .off= 4.205533798926934891e-251 }, - HP{.val=1.000000e-235, .off= 4.205533798926934697e-252 }, - HP{.val=1.000000e-236, .off= -4.523850562697497656e-253 }, - HP{.val=1.000000e-237, .off= 9.320146633177728298e-255 }, - HP{.val=1.000000e-238, .off= 9.320146633177728062e-256 }, - HP{.val=1.000000e-239, .off= -7.592774752331086440e-256 }, - HP{.val=1.000000e-240, .off= 3.063212017229987840e-257 }, - HP{.val=1.000000e-241, .off= 3.063212017229987562e-258 }, - HP{.val=1.000000e-242, .off= 3.063212017229987562e-259 }, - HP{.val=1.000000e-243, .off= 4.616527473176159842e-261 }, - HP{.val=1.000000e-244, .off= 6.965550922098544975e-261 }, - HP{.val=1.000000e-245, .off= 6.965550922098544749e-262 }, - HP{.val=1.000000e-246, .off= 4.424965697574744679e-263 }, - HP{.val=1.000000e-247, .off= -1.926497363734756420e-264 }, - HP{.val=1.000000e-248, .off= 2.043167049583681740e-265 }, - HP{.val=1.000000e-249, .off= -5.399953725388390154e-266 }, - HP{.val=1.000000e-250, .off= -5.399953725388389982e-267 }, - HP{.val=1.000000e-251, .off= -1.523328321757102663e-268 }, - HP{.val=1.000000e-252, .off= 5.745344310051561161e-269 }, - HP{.val=1.000000e-253, .off= -6.369110076296211879e-270 }, - HP{.val=1.000000e-254, .off= 8.773957906638504842e-271 }, - HP{.val=1.000000e-255, .off= -6.904595826956931908e-273 }, - HP{.val=1.000000e-256, .off= 2.267170882721243669e-273 }, - HP{.val=1.000000e-257, .off= 2.267170882721243669e-274 }, - HP{.val=1.000000e-258, .off= 4.577819683828225398e-275 }, - HP{.val=1.000000e-259, .off= -6.975424321706684210e-276 }, - HP{.val=1.000000e-260, .off= 3.855741933482293648e-277 }, - HP{.val=1.000000e-261, .off= 1.599248963651256552e-278 }, - HP{.val=1.000000e-262, .off= -1.221367248637539543e-279 }, - HP{.val=1.000000e-263, .off= -1.221367248637539494e-280 }, - HP{.val=1.000000e-264, .off= -1.221367248637539647e-281 }, - HP{.val=1.000000e-265, .off= 1.533140771175737943e-282 }, - HP{.val=1.000000e-266, .off= 1.533140771175737895e-283 }, - HP{.val=1.000000e-267, .off= 1.533140771175738074e-284 }, - HP{.val=1.000000e-268, .off= 4.223090009274641634e-285 }, - HP{.val=1.000000e-269, .off= 4.223090009274641634e-286 }, - HP{.val=1.000000e-270, .off= -4.183001359784432924e-287 }, - HP{.val=1.000000e-271, .off= 3.697709298708449474e-288 }, - HP{.val=1.000000e-272, .off= 6.981338739747150474e-289 }, - HP{.val=1.000000e-273, .off= -9.436808465446354751e-290 }, - HP{.val=1.000000e-274, .off= 3.389869038611071740e-291 }, - HP{.val=1.000000e-275, .off= 6.596538414625427829e-292 }, - HP{.val=1.000000e-276, .off= -9.436808465446354618e-293 }, - HP{.val=1.000000e-277, .off= 3.089243784609725523e-294 }, - HP{.val=1.000000e-278, .off= 6.220756847123745836e-295 }, - HP{.val=1.000000e-279, .off= -5.522417137303829470e-296 }, - HP{.val=1.000000e-280, .off= 4.263561183052483059e-297 }, - HP{.val=1.000000e-281, .off= -1.852675267170212272e-298 }, - HP{.val=1.000000e-282, .off= -1.852675267170212378e-299 }, - HP{.val=1.000000e-283, .off= 5.314789322934508480e-300 }, - HP{.val=1.000000e-284, .off= -3.644541414696392675e-301 }, - HP{.val=1.000000e-285, .off= -7.377595888709267777e-302 }, - HP{.val=1.000000e-286, .off= -5.044436842451220838e-303 }, - HP{.val=1.000000e-287, .off= -2.127988034628661760e-304 }, - HP{.val=1.000000e-288, .off= -5.773549044406860911e-305 }, - HP{.val=1.000000e-289, .off= -1.216597782184112068e-306 }, - HP{.val=1.000000e-290, .off= -6.912786859962547924e-307 }, - HP{.val=1.000000e-291, .off= 3.767567660872018813e-308 }, + HP{ .val = 1.000000e+308, .off = -1.097906362944045488e+291 }, + HP{ .val = 1.000000e+307, .off = 1.396894023974354241e+290 }, + HP{ .val = 1.000000e+306, .off = -1.721606459673645508e+289 }, + HP{ .val = 1.000000e+305, .off = 6.074644749446353973e+288 }, + HP{ .val = 1.000000e+304, .off = 6.074644749446353567e+287 }, + HP{ .val = 1.000000e+303, .off = -1.617650767864564452e+284 }, + HP{ .val = 1.000000e+302, .off = -7.629703079084895055e+285 }, + HP{ .val = 1.000000e+301, .off = -5.250476025520442286e+284 }, + HP{ .val = 1.000000e+300, .off = -5.250476025520441956e+283 }, + HP{ .val = 1.000000e+299, .off = -5.250476025520441750e+282 }, + HP{ .val = 1.000000e+298, .off = 4.043379652465702264e+281 }, + HP{ .val = 1.000000e+297, .off = -1.765280146275637946e+280 }, + HP{ .val = 1.000000e+296, .off = 1.865132227937699609e+279 }, + HP{ .val = 1.000000e+295, .off = 1.865132227937699609e+278 }, + HP{ .val = 1.000000e+294, .off = -6.643646774124810287e+277 }, + HP{ .val = 1.000000e+293, .off = 7.537651562646039934e+276 }, + HP{ .val = 1.000000e+292, .off = -1.325659897835741608e+275 }, + HP{ .val = 1.000000e+291, .off = 4.213909764965371606e+274 }, + HP{ .val = 1.000000e+290, .off = -6.172783352786715670e+273 }, + HP{ .val = 1.000000e+289, .off = -6.172783352786715670e+272 }, + HP{ .val = 1.000000e+288, .off = -7.630473539575035471e+270 }, + HP{ .val = 1.000000e+287, .off = -7.525217352494018700e+270 }, + HP{ .val = 1.000000e+286, .off = -3.298861103408696612e+269 }, + HP{ .val = 1.000000e+285, .off = 1.984084207947955778e+268 }, + HP{ .val = 1.000000e+284, .off = -7.921438250845767591e+267 }, + HP{ .val = 1.000000e+283, .off = 4.460464822646386735e+266 }, + HP{ .val = 1.000000e+282, .off = -3.278224598286209647e+265 }, + HP{ .val = 1.000000e+281, .off = -3.278224598286209737e+264 }, + HP{ .val = 1.000000e+280, .off = -3.278224598286209961e+263 }, + HP{ .val = 1.000000e+279, .off = -5.797329227496039232e+262 }, + HP{ .val = 1.000000e+278, .off = 3.649313132040821498e+261 }, + HP{ .val = 1.000000e+277, .off = -2.867878510995372374e+259 }, + HP{ .val = 1.000000e+276, .off = -5.206914080024985409e+259 }, + HP{ .val = 1.000000e+275, .off = 4.018322599210230404e+258 }, + HP{ .val = 1.000000e+274, .off = 7.862171215558236495e+257 }, + HP{ .val = 1.000000e+273, .off = 5.459765830340732821e+256 }, + HP{ .val = 1.000000e+272, .off = -6.552261095746788047e+255 }, + HP{ .val = 1.000000e+271, .off = 4.709014147460262298e+254 }, + HP{ .val = 1.000000e+270, .off = -4.675381888545612729e+253 }, + HP{ .val = 1.000000e+269, .off = -4.675381888545612892e+252 }, + HP{ .val = 1.000000e+268, .off = 2.656177514583977380e+251 }, + HP{ .val = 1.000000e+267, .off = 2.656177514583977190e+250 }, + HP{ .val = 1.000000e+266, .off = -3.071603269111014892e+249 }, + HP{ .val = 1.000000e+265, .off = -6.651466258920385440e+248 }, + HP{ .val = 1.000000e+264, .off = -4.414051890289528972e+247 }, + HP{ .val = 1.000000e+263, .off = -1.617283929500958387e+246 }, + HP{ .val = 1.000000e+262, .off = -1.617283929500958241e+245 }, + HP{ .val = 1.000000e+261, .off = 7.122615947963323868e+244 }, + HP{ .val = 1.000000e+260, .off = -6.533477610574617382e+243 }, + HP{ .val = 1.000000e+259, .off = 7.122615947963323982e+242 }, + HP{ .val = 1.000000e+258, .off = -5.679971763165996225e+241 }, + HP{ .val = 1.000000e+257, .off = -3.012765990014054219e+240 }, + HP{ .val = 1.000000e+256, .off = -3.012765990014054219e+239 }, + HP{ .val = 1.000000e+255, .off = 1.154743030535854616e+238 }, + HP{ .val = 1.000000e+254, .off = 6.364129306223240767e+237 }, + HP{ .val = 1.000000e+253, .off = 6.364129306223241129e+236 }, + HP{ .val = 1.000000e+252, .off = -9.915202805299840595e+235 }, + HP{ .val = 1.000000e+251, .off = -4.827911520448877980e+234 }, + HP{ .val = 1.000000e+250, .off = 7.890316691678530146e+233 }, + HP{ .val = 1.000000e+249, .off = 7.890316691678529484e+232 }, + HP{ .val = 1.000000e+248, .off = -4.529828046727141859e+231 }, + HP{ .val = 1.000000e+247, .off = 4.785280507077111924e+230 }, + HP{ .val = 1.000000e+246, .off = -6.858605185178205305e+229 }, + HP{ .val = 1.000000e+245, .off = -4.432795665958347728e+228 }, + HP{ .val = 1.000000e+244, .off = -7.465057564983169531e+227 }, + HP{ .val = 1.000000e+243, .off = -7.465057564983169741e+226 }, + HP{ .val = 1.000000e+242, .off = -5.096102956370027445e+225 }, + HP{ .val = 1.000000e+241, .off = -5.096102956370026952e+224 }, + HP{ .val = 1.000000e+240, .off = -1.394611380411992474e+223 }, + HP{ .val = 1.000000e+239, .off = 9.188208545617793960e+221 }, + HP{ .val = 1.000000e+238, .off = -4.864759732872650359e+221 }, + HP{ .val = 1.000000e+237, .off = 5.979453868566904629e+220 }, + HP{ .val = 1.000000e+236, .off = -5.316601966265964857e+219 }, + HP{ .val = 1.000000e+235, .off = -5.316601966265964701e+218 }, + HP{ .val = 1.000000e+234, .off = -1.786584517880693123e+217 }, + HP{ .val = 1.000000e+233, .off = 2.625937292600896716e+216 }, + HP{ .val = 1.000000e+232, .off = -5.647541102052084079e+215 }, + HP{ .val = 1.000000e+231, .off = -5.647541102052083888e+214 }, + HP{ .val = 1.000000e+230, .off = -9.956644432600511943e+213 }, + HP{ .val = 1.000000e+229, .off = 8.161138937705571862e+211 }, + HP{ .val = 1.000000e+228, .off = 7.549087847752475275e+211 }, + HP{ .val = 1.000000e+227, .off = -9.283347037202319948e+210 }, + HP{ .val = 1.000000e+226, .off = 3.866992716668613820e+209 }, + HP{ .val = 1.000000e+225, .off = 7.154577655136347262e+208 }, + HP{ .val = 1.000000e+224, .off = 3.045096482051680688e+207 }, + HP{ .val = 1.000000e+223, .off = -4.660180717482069567e+206 }, + HP{ .val = 1.000000e+222, .off = -4.660180717482070101e+205 }, + HP{ .val = 1.000000e+221, .off = -4.660180717482069544e+204 }, + HP{ .val = 1.000000e+220, .off = 3.562757926310489022e+202 }, + HP{ .val = 1.000000e+219, .off = 3.491561111451748149e+202 }, + HP{ .val = 1.000000e+218, .off = -8.265758834125874135e+201 }, + HP{ .val = 1.000000e+217, .off = 3.981449442517482365e+200 }, + HP{ .val = 1.000000e+216, .off = -2.142154695804195936e+199 }, + HP{ .val = 1.000000e+215, .off = 9.339603063548950188e+198 }, + HP{ .val = 1.000000e+214, .off = 4.555537330485139746e+197 }, + HP{ .val = 1.000000e+213, .off = 1.565496247320257804e+196 }, + HP{ .val = 1.000000e+212, .off = 9.040598955232462036e+195 }, + HP{ .val = 1.000000e+211, .off = 4.368659762787334780e+194 }, + HP{ .val = 1.000000e+210, .off = 7.288621758065539072e+193 }, + HP{ .val = 1.000000e+209, .off = -7.311188218325485628e+192 }, + HP{ .val = 1.000000e+208, .off = 1.813693016918905189e+191 }, + HP{ .val = 1.000000e+207, .off = -3.889357755108838992e+190 }, + HP{ .val = 1.000000e+206, .off = -3.889357755108838992e+189 }, + HP{ .val = 1.000000e+205, .off = -1.661603547285501360e+188 }, + HP{ .val = 1.000000e+204, .off = 1.123089212493670643e+187 }, + HP{ .val = 1.000000e+203, .off = 1.123089212493670643e+186 }, + HP{ .val = 1.000000e+202, .off = 9.825254086803583029e+185 }, + HP{ .val = 1.000000e+201, .off = -3.771878529305654999e+184 }, + HP{ .val = 1.000000e+200, .off = 3.026687778748963675e+183 }, + HP{ .val = 1.000000e+199, .off = -9.720624048853446693e+182 }, + HP{ .val = 1.000000e+198, .off = -1.753554156601940139e+181 }, + HP{ .val = 1.000000e+197, .off = 4.885670753607648963e+180 }, + HP{ .val = 1.000000e+196, .off = 4.885670753607648963e+179 }, + HP{ .val = 1.000000e+195, .off = 2.292223523057028076e+178 }, + HP{ .val = 1.000000e+194, .off = 5.534032561245303825e+177 }, + HP{ .val = 1.000000e+193, .off = -6.622751331960730683e+176 }, + HP{ .val = 1.000000e+192, .off = -4.090088020876139692e+175 }, + HP{ .val = 1.000000e+191, .off = -7.255917159731877552e+174 }, + HP{ .val = 1.000000e+190, .off = -7.255917159731877992e+173 }, + HP{ .val = 1.000000e+189, .off = -2.309309130269787104e+172 }, + HP{ .val = 1.000000e+188, .off = -2.309309130269787019e+171 }, + HP{ .val = 1.000000e+187, .off = 9.284303438781988230e+170 }, + HP{ .val = 1.000000e+186, .off = 2.038295583124628364e+169 }, + HP{ .val = 1.000000e+185, .off = 2.038295583124628532e+168 }, + HP{ .val = 1.000000e+184, .off = -1.735666841696912925e+167 }, + HP{ .val = 1.000000e+183, .off = 5.340512704843477241e+166 }, + HP{ .val = 1.000000e+182, .off = -6.453119872723839321e+165 }, + HP{ .val = 1.000000e+181, .off = 8.288920849235306587e+164 }, + HP{ .val = 1.000000e+180, .off = -9.248546019891598293e+162 }, + HP{ .val = 1.000000e+179, .off = 1.954450226518486016e+162 }, + HP{ .val = 1.000000e+178, .off = -5.243811844750628197e+161 }, + HP{ .val = 1.000000e+177, .off = -7.448980502074320639e+159 }, + HP{ .val = 1.000000e+176, .off = -7.448980502074319858e+158 }, + HP{ .val = 1.000000e+175, .off = 6.284654753766312753e+158 }, + HP{ .val = 1.000000e+174, .off = -6.895756753684458388e+157 }, + HP{ .val = 1.000000e+173, .off = -1.403918625579970616e+156 }, + HP{ .val = 1.000000e+172, .off = -8.268716285710580522e+155 }, + HP{ .val = 1.000000e+171, .off = 4.602779327034313170e+154 }, + HP{ .val = 1.000000e+170, .off = -3.441905430931244940e+153 }, + HP{ .val = 1.000000e+169, .off = 6.613950516525702884e+152 }, + HP{ .val = 1.000000e+168, .off = 6.613950516525702652e+151 }, + HP{ .val = 1.000000e+167, .off = -3.860899428741951187e+150 }, + HP{ .val = 1.000000e+166, .off = 5.959272394946474605e+149 }, + HP{ .val = 1.000000e+165, .off = 1.005101065481665103e+149 }, + HP{ .val = 1.000000e+164, .off = -1.783349948587918355e+146 }, + HP{ .val = 1.000000e+163, .off = 6.215006036188360099e+146 }, + HP{ .val = 1.000000e+162, .off = 6.215006036188360099e+145 }, + HP{ .val = 1.000000e+161, .off = -3.774589324822814903e+144 }, + HP{ .val = 1.000000e+160, .off = -6.528407745068226929e+142 }, + HP{ .val = 1.000000e+159, .off = 7.151530601283157561e+142 }, + HP{ .val = 1.000000e+158, .off = 4.712664546348788765e+141 }, + HP{ .val = 1.000000e+157, .off = 1.664081977680827856e+140 }, + HP{ .val = 1.000000e+156, .off = 1.664081977680827750e+139 }, + HP{ .val = 1.000000e+155, .off = -7.176231540910168265e+137 }, + HP{ .val = 1.000000e+154, .off = -3.694754568805822650e+137 }, + HP{ .val = 1.000000e+153, .off = 2.665969958768462622e+134 }, + HP{ .val = 1.000000e+152, .off = -4.625108135904199522e+135 }, + HP{ .val = 1.000000e+151, .off = -1.717753238721771919e+134 }, + HP{ .val = 1.000000e+150, .off = 1.916440382756262433e+133 }, + HP{ .val = 1.000000e+149, .off = -4.897672657515052040e+132 }, + HP{ .val = 1.000000e+148, .off = -4.897672657515052198e+131 }, + HP{ .val = 1.000000e+147, .off = 2.200361759434233991e+130 }, + HP{ .val = 1.000000e+146, .off = 6.636633270027537273e+129 }, + HP{ .val = 1.000000e+145, .off = 1.091293881785907977e+128 }, + HP{ .val = 1.000000e+144, .off = -2.374543235865110597e+127 }, + HP{ .val = 1.000000e+143, .off = -2.374543235865110537e+126 }, + HP{ .val = 1.000000e+142, .off = -5.082228484029969099e+125 }, + HP{ .val = 1.000000e+141, .off = -1.697621923823895943e+124 }, + HP{ .val = 1.000000e+140, .off = -5.928380124081487212e+123 }, + HP{ .val = 1.000000e+139, .off = -3.284156248920492522e+122 }, + HP{ .val = 1.000000e+138, .off = -3.284156248920492706e+121 }, + HP{ .val = 1.000000e+137, .off = -3.284156248920492476e+120 }, + HP{ .val = 1.000000e+136, .off = -5.866406127007401066e+119 }, + HP{ .val = 1.000000e+135, .off = 3.817030915818506056e+118 }, + HP{ .val = 1.000000e+134, .off = 7.851796350329300951e+117 }, + HP{ .val = 1.000000e+133, .off = -2.235117235947686077e+116 }, + HP{ .val = 1.000000e+132, .off = 9.170432597638723691e+114 }, + HP{ .val = 1.000000e+131, .off = 8.797444499042767883e+114 }, + HP{ .val = 1.000000e+130, .off = -5.978307824605161274e+113 }, + HP{ .val = 1.000000e+129, .off = 1.782556435814758516e+111 }, + HP{ .val = 1.000000e+128, .off = -7.517448691651820362e+111 }, + HP{ .val = 1.000000e+127, .off = 4.507089332150205498e+110 }, + HP{ .val = 1.000000e+126, .off = 7.513223838100711695e+109 }, + HP{ .val = 1.000000e+125, .off = 7.513223838100712113e+108 }, + HP{ .val = 1.000000e+124, .off = 5.164681255326878494e+107 }, + HP{ .val = 1.000000e+123, .off = 2.229003026859587122e+106 }, + HP{ .val = 1.000000e+122, .off = -1.440594758724527399e+105 }, + HP{ .val = 1.000000e+121, .off = -3.734093374714598783e+104 }, + HP{ .val = 1.000000e+120, .off = 1.999653165260579757e+103 }, + HP{ .val = 1.000000e+119, .off = 5.583244752745066693e+102 }, + HP{ .val = 1.000000e+118, .off = 3.343500010567262234e+101 }, + HP{ .val = 1.000000e+117, .off = -5.055542772599503556e+100 }, + HP{ .val = 1.000000e+116, .off = -1.555941612946684331e+99 }, + HP{ .val = 1.000000e+115, .off = -1.555941612946684331e+98 }, + HP{ .val = 1.000000e+114, .off = -1.555941612946684293e+97 }, + HP{ .val = 1.000000e+113, .off = -1.555941612946684246e+96 }, + HP{ .val = 1.000000e+112, .off = 6.988006530736955847e+95 }, + HP{ .val = 1.000000e+111, .off = 4.318022735835818244e+94 }, + HP{ .val = 1.000000e+110, .off = -2.356936751417025578e+93 }, + HP{ .val = 1.000000e+109, .off = 1.814912928116001926e+92 }, + HP{ .val = 1.000000e+108, .off = -3.399899171300282744e+91 }, + HP{ .val = 1.000000e+107, .off = 3.118615952970072913e+90 }, + HP{ .val = 1.000000e+106, .off = -9.103599905036843605e+89 }, + HP{ .val = 1.000000e+105, .off = 6.174169917471802325e+88 }, + HP{ .val = 1.000000e+104, .off = -1.915675085734668657e+86 }, + HP{ .val = 1.000000e+103, .off = -1.915675085734668864e+85 }, + HP{ .val = 1.000000e+102, .off = 2.295048673475466221e+85 }, + HP{ .val = 1.000000e+101, .off = 2.295048673475466135e+84 }, + HP{ .val = 1.000000e+100, .off = -1.590289110975991792e+83 }, + HP{ .val = 1.000000e+99, .off = 3.266383119588331155e+82 }, + HP{ .val = 1.000000e+98, .off = 2.309629754856292029e+80 }, + HP{ .val = 1.000000e+97, .off = -7.357587384771124533e+80 }, + HP{ .val = 1.000000e+96, .off = -4.986165397190889509e+79 }, + HP{ .val = 1.000000e+95, .off = -2.021887912715594741e+78 }, + HP{ .val = 1.000000e+94, .off = -2.021887912715594638e+77 }, + HP{ .val = 1.000000e+93, .off = -4.337729697461918675e+76 }, + HP{ .val = 1.000000e+92, .off = -4.337729697461918997e+75 }, + HP{ .val = 1.000000e+91, .off = -7.956232486128049702e+74 }, + HP{ .val = 1.000000e+90, .off = 3.351588728453609882e+73 }, + HP{ .val = 1.000000e+89, .off = 5.246334248081951113e+71 }, + HP{ .val = 1.000000e+88, .off = 4.058327554364963672e+71 }, + HP{ .val = 1.000000e+87, .off = 4.058327554364963918e+70 }, + HP{ .val = 1.000000e+86, .off = -1.463069523067487266e+69 }, + HP{ .val = 1.000000e+85, .off = -1.463069523067487314e+68 }, + HP{ .val = 1.000000e+84, .off = -5.776660989811589441e+67 }, + HP{ .val = 1.000000e+83, .off = -3.080666323096525761e+66 }, + HP{ .val = 1.000000e+82, .off = 3.659320343691134468e+65 }, + HP{ .val = 1.000000e+81, .off = 7.871812010433421235e+64 }, + HP{ .val = 1.000000e+80, .off = -2.660986470836727449e+61 }, + HP{ .val = 1.000000e+79, .off = 3.264399249934044627e+62 }, + HP{ .val = 1.000000e+78, .off = -8.493621433689703070e+60 }, + HP{ .val = 1.000000e+77, .off = 1.721738727445414063e+60 }, + HP{ .val = 1.000000e+76, .off = -4.706013449590547218e+59 }, + HP{ .val = 1.000000e+75, .off = 7.346021882351880518e+58 }, + HP{ .val = 1.000000e+74, .off = 4.835181188197207515e+57 }, + HP{ .val = 1.000000e+73, .off = 1.696630320503867482e+56 }, + HP{ .val = 1.000000e+72, .off = 5.619818905120542959e+55 }, + HP{ .val = 1.000000e+71, .off = -4.188152556421145598e+54 }, + HP{ .val = 1.000000e+70, .off = -7.253143638152923145e+53 }, + HP{ .val = 1.000000e+69, .off = -7.253143638152923145e+52 }, + HP{ .val = 1.000000e+68, .off = 4.719477774861832896e+51 }, + HP{ .val = 1.000000e+67, .off = 1.726322421608144052e+50 }, + HP{ .val = 1.000000e+66, .off = 5.467766613175255107e+49 }, + HP{ .val = 1.000000e+65, .off = 7.909613737163661911e+47 }, + HP{ .val = 1.000000e+64, .off = -2.132041900945439564e+47 }, + HP{ .val = 1.000000e+63, .off = -5.785795994272697265e+46 }, + HP{ .val = 1.000000e+62, .off = -3.502199685943161329e+45 }, + HP{ .val = 1.000000e+61, .off = 5.061286470292598274e+44 }, + HP{ .val = 1.000000e+60, .off = 5.061286470292598472e+43 }, + HP{ .val = 1.000000e+59, .off = 2.831211950439536034e+42 }, + HP{ .val = 1.000000e+58, .off = 5.618805100255863927e+41 }, + HP{ .val = 1.000000e+57, .off = -4.834669211555366251e+40 }, + HP{ .val = 1.000000e+56, .off = -9.190283508143378583e+39 }, + HP{ .val = 1.000000e+55, .off = -1.023506702040855158e+38 }, + HP{ .val = 1.000000e+54, .off = -7.829154040459624616e+37 }, + HP{ .val = 1.000000e+53, .off = 6.779051325638372659e+35 }, + HP{ .val = 1.000000e+52, .off = 6.779051325638372290e+34 }, + HP{ .val = 1.000000e+51, .off = 6.779051325638371598e+33 }, + HP{ .val = 1.000000e+50, .off = -7.629769841091887392e+33 }, + HP{ .val = 1.000000e+49, .off = 5.350972305245182400e+32 }, + HP{ .val = 1.000000e+48, .off = -4.384584304507619764e+31 }, + HP{ .val = 1.000000e+47, .off = -4.384584304507619876e+30 }, + HP{ .val = 1.000000e+46, .off = 6.860180964052978705e+28 }, + HP{ .val = 1.000000e+45, .off = 7.024271097546444878e+28 }, + HP{ .val = 1.000000e+44, .off = -8.821361405306422641e+27 }, + HP{ .val = 1.000000e+43, .off = -1.393721169594140991e+26 }, + HP{ .val = 1.000000e+42, .off = -4.488571267807591679e+25 }, + HP{ .val = 1.000000e+41, .off = -6.200086450407783195e+23 }, + HP{ .val = 1.000000e+40, .off = -3.037860284270036669e+23 }, + HP{ .val = 1.000000e+39, .off = 6.029083362839682141e+22 }, + HP{ .val = 1.000000e+38, .off = 2.251190176543965970e+21 }, + HP{ .val = 1.000000e+37, .off = 4.612373417978788577e+20 }, + HP{ .val = 1.000000e+36, .off = -4.242063737401796198e+19 }, + HP{ .val = 1.000000e+35, .off = 3.136633892082024448e+18 }, + HP{ .val = 1.000000e+34, .off = 5.442476901295718400e+17 }, + HP{ .val = 1.000000e+33, .off = 5.442476901295718400e+16 }, + HP{ .val = 1.000000e+32, .off = -5.366162204393472000e+15 }, + HP{ .val = 1.000000e+31, .off = 3.641037050347520000e+14 }, + HP{ .val = 1.000000e+30, .off = -1.988462483865600000e+13 }, + HP{ .val = 1.000000e+29, .off = 8.566849142784000000e+12 }, + HP{ .val = 1.000000e+28, .off = 4.168802631680000000e+11 }, + HP{ .val = 1.000000e+27, .off = -1.328755507200000000e+10 }, + HP{ .val = 1.000000e+26, .off = -4.764729344000000000e+09 }, + HP{ .val = 1.000000e+25, .off = -9.059696640000000000e+08 }, + HP{ .val = 1.000000e+24, .off = 1.677721600000000000e+07 }, + HP{ .val = 1.000000e+23, .off = 8.388608000000000000e+06 }, + HP{ .val = 1.000000e+22, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+21, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+20, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+19, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+18, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+17, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+16, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+15, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+14, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+13, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+12, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+11, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+10, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+09, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+08, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+07, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+06, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+05, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+04, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+03, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+02, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+01, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e+00, .off = 0.000000000000000000e+00 }, + HP{ .val = 1.000000e-01, .off = -5.551115123125783010e-18 }, + HP{ .val = 1.000000e-02, .off = -2.081668171172168436e-19 }, + HP{ .val = 1.000000e-03, .off = -2.081668171172168557e-20 }, + HP{ .val = 1.000000e-04, .off = -4.792173602385929943e-21 }, + HP{ .val = 1.000000e-05, .off = -8.180305391403130547e-22 }, + HP{ .val = 1.000000e-06, .off = 4.525188817411374069e-23 }, + HP{ .val = 1.000000e-07, .off = 4.525188817411373922e-24 }, + HP{ .val = 1.000000e-08, .off = -2.092256083012847109e-25 }, + HP{ .val = 1.000000e-09, .off = -6.228159145777985254e-26 }, + HP{ .val = 1.000000e-10, .off = -3.643219731549774344e-27 }, + HP{ .val = 1.000000e-11, .off = 6.050303071806019080e-28 }, + HP{ .val = 1.000000e-12, .off = 2.011335237074438524e-29 }, + HP{ .val = 1.000000e-13, .off = -3.037374556340037101e-30 }, + HP{ .val = 1.000000e-14, .off = 1.180690645440101289e-32 }, + HP{ .val = 1.000000e-15, .off = -7.770539987666107583e-32 }, + HP{ .val = 1.000000e-16, .off = 2.090221327596539779e-33 }, + HP{ .val = 1.000000e-17, .off = -7.154242405462192144e-34 }, + HP{ .val = 1.000000e-18, .off = -7.154242405462192572e-35 }, + HP{ .val = 1.000000e-19, .off = 2.475407316473986894e-36 }, + HP{ .val = 1.000000e-20, .off = 5.484672854579042914e-37 }, + HP{ .val = 1.000000e-21, .off = 9.246254777210362522e-38 }, + HP{ .val = 1.000000e-22, .off = -4.859677432657087182e-39 }, + HP{ .val = 1.000000e-23, .off = 3.956530198510069291e-40 }, + HP{ .val = 1.000000e-24, .off = 7.629950044829717753e-41 }, + HP{ .val = 1.000000e-25, .off = -3.849486974919183692e-42 }, + HP{ .val = 1.000000e-26, .off = -3.849486974919184170e-43 }, + HP{ .val = 1.000000e-27, .off = -3.849486974919184070e-44 }, + HP{ .val = 1.000000e-28, .off = 2.876745653839937870e-45 }, + HP{ .val = 1.000000e-29, .off = 5.679342582489572168e-46 }, + HP{ .val = 1.000000e-30, .off = -8.333642060758598930e-47 }, + HP{ .val = 1.000000e-31, .off = -8.333642060758597958e-48 }, + HP{ .val = 1.000000e-32, .off = -5.596730997624190224e-49 }, + HP{ .val = 1.000000e-33, .off = -5.596730997624190604e-50 }, + HP{ .val = 1.000000e-34, .off = 7.232539610818348498e-51 }, + HP{ .val = 1.000000e-35, .off = -7.857545194582380514e-53 }, + HP{ .val = 1.000000e-36, .off = 5.896157255772251528e-53 }, + HP{ .val = 1.000000e-37, .off = -6.632427322784915796e-54 }, + HP{ .val = 1.000000e-38, .off = 3.808059826012723592e-55 }, + HP{ .val = 1.000000e-39, .off = 7.070712060011985131e-56 }, + HP{ .val = 1.000000e-40, .off = 7.070712060011985584e-57 }, + HP{ .val = 1.000000e-41, .off = -5.761291134237854167e-59 }, + HP{ .val = 1.000000e-42, .off = -3.762312935688689794e-59 }, + HP{ .val = 1.000000e-43, .off = -7.745042713519821150e-60 }, + HP{ .val = 1.000000e-44, .off = 4.700987842202462817e-61 }, + HP{ .val = 1.000000e-45, .off = 1.589480203271891964e-62 }, + HP{ .val = 1.000000e-46, .off = -2.299904345391321765e-63 }, + HP{ .val = 1.000000e-47, .off = 2.561826340437695261e-64 }, + HP{ .val = 1.000000e-48, .off = 2.561826340437695345e-65 }, + HP{ .val = 1.000000e-49, .off = 6.360053438741614633e-66 }, + HP{ .val = 1.000000e-50, .off = -7.616223705782342295e-68 }, + HP{ .val = 1.000000e-51, .off = -7.616223705782343324e-69 }, + HP{ .val = 1.000000e-52, .off = -7.616223705782342295e-70 }, + HP{ .val = 1.000000e-53, .off = -3.079876214757872338e-70 }, + HP{ .val = 1.000000e-54, .off = -3.079876214757872821e-71 }, + HP{ .val = 1.000000e-55, .off = 5.423954167728123147e-73 }, + HP{ .val = 1.000000e-56, .off = -3.985444122640543680e-73 }, + HP{ .val = 1.000000e-57, .off = 4.504255013759498850e-74 }, + HP{ .val = 1.000000e-58, .off = -2.570494266573869991e-75 }, + HP{ .val = 1.000000e-59, .off = -2.570494266573869930e-76 }, + HP{ .val = 1.000000e-60, .off = 2.956653608686574324e-77 }, + HP{ .val = 1.000000e-61, .off = -3.952281235388981376e-78 }, + HP{ .val = 1.000000e-62, .off = -3.952281235388981376e-79 }, + HP{ .val = 1.000000e-63, .off = -6.651083908855995172e-80 }, + HP{ .val = 1.000000e-64, .off = 3.469426116645307030e-81 }, + HP{ .val = 1.000000e-65, .off = 7.686305293937516319e-82 }, + HP{ .val = 1.000000e-66, .off = 2.415206322322254927e-83 }, + HP{ .val = 1.000000e-67, .off = 5.709643179581793251e-84 }, + HP{ .val = 1.000000e-68, .off = -6.644495035141475923e-85 }, + HP{ .val = 1.000000e-69, .off = 3.650620143794581913e-86 }, + HP{ .val = 1.000000e-70, .off = 4.333966503770636492e-88 }, + HP{ .val = 1.000000e-71, .off = 8.476455383920859113e-88 }, + HP{ .val = 1.000000e-72, .off = 3.449543675455986564e-89 }, + HP{ .val = 1.000000e-73, .off = 3.077238576654418974e-91 }, + HP{ .val = 1.000000e-74, .off = 4.234998629903623140e-91 }, + HP{ .val = 1.000000e-75, .off = 4.234998629903623412e-92 }, + HP{ .val = 1.000000e-76, .off = 7.303182045714702338e-93 }, + HP{ .val = 1.000000e-77, .off = 7.303182045714701699e-94 }, + HP{ .val = 1.000000e-78, .off = 1.121271649074855759e-96 }, + HP{ .val = 1.000000e-79, .off = 1.121271649074855863e-97 }, + HP{ .val = 1.000000e-80, .off = 3.857468248661243988e-97 }, + HP{ .val = 1.000000e-81, .off = 3.857468248661244248e-98 }, + HP{ .val = 1.000000e-82, .off = 3.857468248661244410e-99 }, + HP{ .val = 1.000000e-83, .off = -3.457651055545315679e-100 }, + HP{ .val = 1.000000e-84, .off = -3.457651055545315933e-101 }, + HP{ .val = 1.000000e-85, .off = 2.257285900866059216e-102 }, + HP{ .val = 1.000000e-86, .off = -8.458220892405268345e-103 }, + HP{ .val = 1.000000e-87, .off = -1.761029146610688867e-104 }, + HP{ .val = 1.000000e-88, .off = 6.610460535632536565e-105 }, + HP{ .val = 1.000000e-89, .off = -3.853901567171494935e-106 }, + HP{ .val = 1.000000e-90, .off = 5.062493089968513723e-108 }, + HP{ .val = 1.000000e-91, .off = -2.218844988608365240e-108 }, + HP{ .val = 1.000000e-92, .off = 1.187522883398155383e-109 }, + HP{ .val = 1.000000e-93, .off = 9.703442563414457296e-110 }, + HP{ .val = 1.000000e-94, .off = 4.380992763404268896e-111 }, + HP{ .val = 1.000000e-95, .off = 1.054461638397900823e-112 }, + HP{ .val = 1.000000e-96, .off = 9.370789450913819736e-113 }, + HP{ .val = 1.000000e-97, .off = -3.623472756142303998e-114 }, + HP{ .val = 1.000000e-98, .off = 6.122223899149788839e-115 }, + HP{ .val = 1.000000e-99, .off = -1.999189980260288281e-116 }, + HP{ .val = 1.000000e-100, .off = -1.999189980260288281e-117 }, + HP{ .val = 1.000000e-101, .off = -5.171617276904849634e-118 }, + HP{ .val = 1.000000e-102, .off = 6.724985085512256320e-119 }, + HP{ .val = 1.000000e-103, .off = 4.246526260008692213e-120 }, + HP{ .val = 1.000000e-104, .off = 7.344599791888147003e-121 }, + HP{ .val = 1.000000e-105, .off = 3.472007877038828407e-122 }, + HP{ .val = 1.000000e-106, .off = 5.892377823819652194e-123 }, + HP{ .val = 1.000000e-107, .off = -1.585470431324073925e-125 }, + HP{ .val = 1.000000e-108, .off = -3.940375084977444795e-125 }, + HP{ .val = 1.000000e-109, .off = 7.869099673288519908e-127 }, + HP{ .val = 1.000000e-110, .off = -5.122196348054018581e-127 }, + HP{ .val = 1.000000e-111, .off = -8.815387795168313713e-128 }, + HP{ .val = 1.000000e-112, .off = 5.034080131510290214e-129 }, + HP{ .val = 1.000000e-113, .off = 2.148774313452247863e-130 }, + HP{ .val = 1.000000e-114, .off = -5.064490231692858416e-131 }, + HP{ .val = 1.000000e-115, .off = -5.064490231692858166e-132 }, + HP{ .val = 1.000000e-116, .off = 5.708726942017560559e-134 }, + HP{ .val = 1.000000e-117, .off = -2.951229134482377772e-134 }, + HP{ .val = 1.000000e-118, .off = 1.451398151372789513e-135 }, + HP{ .val = 1.000000e-119, .off = -1.300243902286690040e-136 }, + HP{ .val = 1.000000e-120, .off = 2.139308664787659449e-137 }, + HP{ .val = 1.000000e-121, .off = 2.139308664787659329e-138 }, + HP{ .val = 1.000000e-122, .off = -5.922142664292847471e-139 }, + HP{ .val = 1.000000e-123, .off = -5.922142664292846912e-140 }, + HP{ .val = 1.000000e-124, .off = 6.673875037395443799e-141 }, + HP{ .val = 1.000000e-125, .off = -1.198636026159737932e-142 }, + HP{ .val = 1.000000e-126, .off = 5.361789860136246995e-143 }, + HP{ .val = 1.000000e-127, .off = -2.838742497733733936e-144 }, + HP{ .val = 1.000000e-128, .off = -5.401408859568103261e-145 }, + HP{ .val = 1.000000e-129, .off = 7.411922949603743011e-146 }, + HP{ .val = 1.000000e-130, .off = -8.604741811861064385e-147 }, + HP{ .val = 1.000000e-131, .off = 1.405673664054439890e-148 }, + HP{ .val = 1.000000e-132, .off = 1.405673664054439933e-149 }, + HP{ .val = 1.000000e-133, .off = -6.414963426504548053e-150 }, + HP{ .val = 1.000000e-134, .off = -3.971014335704864578e-151 }, + HP{ .val = 1.000000e-135, .off = -3.971014335704864748e-152 }, + HP{ .val = 1.000000e-136, .off = -1.523438813303585576e-154 }, + HP{ .val = 1.000000e-137, .off = 2.234325152653707766e-154 }, + HP{ .val = 1.000000e-138, .off = -6.715683724786540160e-155 }, + HP{ .val = 1.000000e-139, .off = -2.986513359186437306e-156 }, + HP{ .val = 1.000000e-140, .off = 1.674949597813692102e-157 }, + HP{ .val = 1.000000e-141, .off = -4.151879098436469092e-158 }, + HP{ .val = 1.000000e-142, .off = -4.151879098436469295e-159 }, + HP{ .val = 1.000000e-143, .off = 4.952540739454407825e-160 }, + HP{ .val = 1.000000e-144, .off = 4.952540739454407667e-161 }, + HP{ .val = 1.000000e-145, .off = 8.508954738630531443e-162 }, + HP{ .val = 1.000000e-146, .off = -2.604839008794855481e-163 }, + HP{ .val = 1.000000e-147, .off = 2.952057864917838382e-164 }, + HP{ .val = 1.000000e-148, .off = 6.425118410988271757e-165 }, + HP{ .val = 1.000000e-149, .off = 2.083792728400229858e-166 }, + HP{ .val = 1.000000e-150, .off = -6.295358232172964237e-168 }, + HP{ .val = 1.000000e-151, .off = 6.153785555826519421e-168 }, + HP{ .val = 1.000000e-152, .off = -6.564942029880634994e-169 }, + HP{ .val = 1.000000e-153, .off = -3.915207116191644540e-170 }, + HP{ .val = 1.000000e-154, .off = 2.709130168030831503e-171 }, + HP{ .val = 1.000000e-155, .off = -1.431080634608215966e-172 }, + HP{ .val = 1.000000e-156, .off = -4.018712386257620994e-173 }, + HP{ .val = 1.000000e-157, .off = 5.684906682427646782e-174 }, + HP{ .val = 1.000000e-158, .off = -6.444617153428937489e-175 }, + HP{ .val = 1.000000e-159, .off = 1.136335243981427681e-176 }, + HP{ .val = 1.000000e-160, .off = 1.136335243981427725e-177 }, + HP{ .val = 1.000000e-161, .off = -2.812077463003137395e-178 }, + HP{ .val = 1.000000e-162, .off = 4.591196362592922204e-179 }, + HP{ .val = 1.000000e-163, .off = 7.675893789924613703e-180 }, + HP{ .val = 1.000000e-164, .off = 3.820022005759999543e-181 }, + HP{ .val = 1.000000e-165, .off = -9.998177244457686588e-183 }, + HP{ .val = 1.000000e-166, .off = -4.012217555824373639e-183 }, + HP{ .val = 1.000000e-167, .off = -2.467177666011174334e-185 }, + HP{ .val = 1.000000e-168, .off = -4.953592503130188139e-185 }, + HP{ .val = 1.000000e-169, .off = -2.011795792799518887e-186 }, + HP{ .val = 1.000000e-170, .off = 1.665450095113817423e-187 }, + HP{ .val = 1.000000e-171, .off = 1.665450095113817487e-188 }, + HP{ .val = 1.000000e-172, .off = -4.080246604750770577e-189 }, + HP{ .val = 1.000000e-173, .off = -4.080246604750770677e-190 }, + HP{ .val = 1.000000e-174, .off = 4.085789420184387951e-192 }, + HP{ .val = 1.000000e-175, .off = 4.085789420184388146e-193 }, + HP{ .val = 1.000000e-176, .off = 4.085789420184388146e-194 }, + HP{ .val = 1.000000e-177, .off = 4.792197640035244894e-194 }, + HP{ .val = 1.000000e-178, .off = 4.792197640035244742e-195 }, + HP{ .val = 1.000000e-179, .off = -2.057206575616014662e-196 }, + HP{ .val = 1.000000e-180, .off = -2.057206575616014662e-197 }, + HP{ .val = 1.000000e-181, .off = -4.732755097354788053e-198 }, + HP{ .val = 1.000000e-182, .off = -4.732755097354787867e-199 }, + HP{ .val = 1.000000e-183, .off = -5.522105321379546765e-201 }, + HP{ .val = 1.000000e-184, .off = -5.777891238658996019e-201 }, + HP{ .val = 1.000000e-185, .off = 7.542096444923057046e-203 }, + HP{ .val = 1.000000e-186, .off = 8.919335748431433483e-203 }, + HP{ .val = 1.000000e-187, .off = -1.287071881492476028e-204 }, + HP{ .val = 1.000000e-188, .off = 5.091932887209967018e-205 }, + HP{ .val = 1.000000e-189, .off = -6.868701054107114024e-206 }, + HP{ .val = 1.000000e-190, .off = -1.885103578558330118e-207 }, + HP{ .val = 1.000000e-191, .off = -1.885103578558330205e-208 }, + HP{ .val = 1.000000e-192, .off = -9.671974634103305058e-209 }, + HP{ .val = 1.000000e-193, .off = -4.805180224387695640e-210 }, + HP{ .val = 1.000000e-194, .off = -1.763433718315439838e-211 }, + HP{ .val = 1.000000e-195, .off = -9.367799983496079132e-212 }, + HP{ .val = 1.000000e-196, .off = -4.615071067758179837e-213 }, + HP{ .val = 1.000000e-197, .off = 1.325840076914194777e-214 }, + HP{ .val = 1.000000e-198, .off = 8.751979007754662425e-215 }, + HP{ .val = 1.000000e-199, .off = 1.789973760091724198e-216 }, + HP{ .val = 1.000000e-200, .off = 1.789973760091724077e-217 }, + HP{ .val = 1.000000e-201, .off = 5.416018159916171171e-218 }, + HP{ .val = 1.000000e-202, .off = -3.649092839644947067e-219 }, + HP{ .val = 1.000000e-203, .off = -3.649092839644947067e-220 }, + HP{ .val = 1.000000e-204, .off = -1.080338554413850956e-222 }, + HP{ .val = 1.000000e-205, .off = -1.080338554413850841e-223 }, + HP{ .val = 1.000000e-206, .off = -2.874486186850417807e-223 }, + HP{ .val = 1.000000e-207, .off = 7.499710055933455072e-224 }, + HP{ .val = 1.000000e-208, .off = -9.790617015372999087e-225 }, + HP{ .val = 1.000000e-209, .off = -4.387389805589732612e-226 }, + HP{ .val = 1.000000e-210, .off = -4.387389805589732612e-227 }, + HP{ .val = 1.000000e-211, .off = -8.608661063232909897e-228 }, + HP{ .val = 1.000000e-212, .off = 4.582811616902018972e-229 }, + HP{ .val = 1.000000e-213, .off = 4.582811616902019155e-230 }, + HP{ .val = 1.000000e-214, .off = 8.705146829444184930e-231 }, + HP{ .val = 1.000000e-215, .off = -4.177150709750081830e-232 }, + HP{ .val = 1.000000e-216, .off = -4.177150709750082366e-233 }, + HP{ .val = 1.000000e-217, .off = -8.202868690748290237e-234 }, + HP{ .val = 1.000000e-218, .off = -3.170721214500530119e-235 }, + HP{ .val = 1.000000e-219, .off = -3.170721214500529857e-236 }, + HP{ .val = 1.000000e-220, .off = 7.606440013180328441e-238 }, + HP{ .val = 1.000000e-221, .off = -1.696459258568569049e-238 }, + HP{ .val = 1.000000e-222, .off = -4.767838333426821244e-239 }, + HP{ .val = 1.000000e-223, .off = 2.910609353718809138e-240 }, + HP{ .val = 1.000000e-224, .off = -1.888420450747209784e-241 }, + HP{ .val = 1.000000e-225, .off = 4.110366804835314035e-242 }, + HP{ .val = 1.000000e-226, .off = 7.859608839574391006e-243 }, + HP{ .val = 1.000000e-227, .off = 5.516332567862468419e-244 }, + HP{ .val = 1.000000e-228, .off = -3.270953451057244613e-245 }, + HP{ .val = 1.000000e-229, .off = -6.932322625607124670e-246 }, + HP{ .val = 1.000000e-230, .off = -4.643966891513449762e-247 }, + HP{ .val = 1.000000e-231, .off = 1.076922443720738305e-248 }, + HP{ .val = 1.000000e-232, .off = -2.498633390800628939e-249 }, + HP{ .val = 1.000000e-233, .off = 4.205533798926934891e-250 }, + HP{ .val = 1.000000e-234, .off = 4.205533798926934891e-251 }, + HP{ .val = 1.000000e-235, .off = 4.205533798926934697e-252 }, + HP{ .val = 1.000000e-236, .off = -4.523850562697497656e-253 }, + HP{ .val = 1.000000e-237, .off = 9.320146633177728298e-255 }, + HP{ .val = 1.000000e-238, .off = 9.320146633177728062e-256 }, + HP{ .val = 1.000000e-239, .off = -7.592774752331086440e-256 }, + HP{ .val = 1.000000e-240, .off = 3.063212017229987840e-257 }, + HP{ .val = 1.000000e-241, .off = 3.063212017229987562e-258 }, + HP{ .val = 1.000000e-242, .off = 3.063212017229987562e-259 }, + HP{ .val = 1.000000e-243, .off = 4.616527473176159842e-261 }, + HP{ .val = 1.000000e-244, .off = 6.965550922098544975e-261 }, + HP{ .val = 1.000000e-245, .off = 6.965550922098544749e-262 }, + HP{ .val = 1.000000e-246, .off = 4.424965697574744679e-263 }, + HP{ .val = 1.000000e-247, .off = -1.926497363734756420e-264 }, + HP{ .val = 1.000000e-248, .off = 2.043167049583681740e-265 }, + HP{ .val = 1.000000e-249, .off = -5.399953725388390154e-266 }, + HP{ .val = 1.000000e-250, .off = -5.399953725388389982e-267 }, + HP{ .val = 1.000000e-251, .off = -1.523328321757102663e-268 }, + HP{ .val = 1.000000e-252, .off = 5.745344310051561161e-269 }, + HP{ .val = 1.000000e-253, .off = -6.369110076296211879e-270 }, + HP{ .val = 1.000000e-254, .off = 8.773957906638504842e-271 }, + HP{ .val = 1.000000e-255, .off = -6.904595826956931908e-273 }, + HP{ .val = 1.000000e-256, .off = 2.267170882721243669e-273 }, + HP{ .val = 1.000000e-257, .off = 2.267170882721243669e-274 }, + HP{ .val = 1.000000e-258, .off = 4.577819683828225398e-275 }, + HP{ .val = 1.000000e-259, .off = -6.975424321706684210e-276 }, + HP{ .val = 1.000000e-260, .off = 3.855741933482293648e-277 }, + HP{ .val = 1.000000e-261, .off = 1.599248963651256552e-278 }, + HP{ .val = 1.000000e-262, .off = -1.221367248637539543e-279 }, + HP{ .val = 1.000000e-263, .off = -1.221367248637539494e-280 }, + HP{ .val = 1.000000e-264, .off = -1.221367248637539647e-281 }, + HP{ .val = 1.000000e-265, .off = 1.533140771175737943e-282 }, + HP{ .val = 1.000000e-266, .off = 1.533140771175737895e-283 }, + HP{ .val = 1.000000e-267, .off = 1.533140771175738074e-284 }, + HP{ .val = 1.000000e-268, .off = 4.223090009274641634e-285 }, + HP{ .val = 1.000000e-269, .off = 4.223090009274641634e-286 }, + HP{ .val = 1.000000e-270, .off = -4.183001359784432924e-287 }, + HP{ .val = 1.000000e-271, .off = 3.697709298708449474e-288 }, + HP{ .val = 1.000000e-272, .off = 6.981338739747150474e-289 }, + HP{ .val = 1.000000e-273, .off = -9.436808465446354751e-290 }, + HP{ .val = 1.000000e-274, .off = 3.389869038611071740e-291 }, + HP{ .val = 1.000000e-275, .off = 6.596538414625427829e-292 }, + HP{ .val = 1.000000e-276, .off = -9.436808465446354618e-293 }, + HP{ .val = 1.000000e-277, .off = 3.089243784609725523e-294 }, + HP{ .val = 1.000000e-278, .off = 6.220756847123745836e-295 }, + HP{ .val = 1.000000e-279, .off = -5.522417137303829470e-296 }, + HP{ .val = 1.000000e-280, .off = 4.263561183052483059e-297 }, + HP{ .val = 1.000000e-281, .off = -1.852675267170212272e-298 }, + HP{ .val = 1.000000e-282, .off = -1.852675267170212378e-299 }, + HP{ .val = 1.000000e-283, .off = 5.314789322934508480e-300 }, + HP{ .val = 1.000000e-284, .off = -3.644541414696392675e-301 }, + HP{ .val = 1.000000e-285, .off = -7.377595888709267777e-302 }, + HP{ .val = 1.000000e-286, .off = -5.044436842451220838e-303 }, + HP{ .val = 1.000000e-287, .off = -2.127988034628661760e-304 }, + HP{ .val = 1.000000e-288, .off = -5.773549044406860911e-305 }, + HP{ .val = 1.000000e-289, .off = -1.216597782184112068e-306 }, + HP{ .val = 1.000000e-290, .off = -6.912786859962547924e-307 }, + HP{ .val = 1.000000e-291, .off = 3.767567660872018813e-308 }, }; diff --git a/std/fmt/index.zig b/std/fmt/index.zig index 624751822a..71ac764b0b 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -107,7 +107,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), '}' => { return output(context, args[next_arg]); }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.BufWidth; }, @@ -127,7 +127,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.IntegerWidth; }, @@ -141,7 +141,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => {}, + '0'...'9' => {}, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, State.FloatScientific => switch (c) { @@ -151,7 +151,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.FloatScientificWidth; }, @@ -165,7 +165,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => {}, + '0'...'9' => {}, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, State.Float => switch (c) { @@ -175,7 +175,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.FloatWidth; }, @@ -189,7 +189,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => {}, + '0'...'9' => {}, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, State.BufWidth => switch (c) { @@ -200,7 +200,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => {}, + '0'...'9' => {}, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, State.Character => switch (c) { @@ -223,7 +223,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), radix = 1024; state = State.BytesBase; }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.BytesWidth; }, @@ -236,7 +236,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => { + '0'...'9' => { width_start = i; state = State.BytesWidth; }, @@ -250,7 +250,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), state = State.Start; start_index = i + 1; }, - '0' ... '9' => {}, + '0'...'9' => {}, else => @compileError("Unexpected character in format string: " ++ []u8{c}), }, } @@ -562,9 +562,14 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com } } -pub fn formatBytes(value: var, width: ?usize, comptime radix: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +pub fn formatBytes( + value: var, + width: ?usize, + comptime radix: usize, + context: var, + comptime Errors: type, + output: fn(@typeOf(context), []const u8) Errors!void, +) Errors!void { if (value == 0) { return output(context, "0B"); } @@ -585,16 +590,22 @@ pub fn formatBytes(value: var, width: ?usize, comptime radix: usize, } const buf = switch (radix) { - 1000 => []u8 { suffix, 'B' }, - 1024 => []u8 { suffix, 'i', 'B' }, + 1000 => []u8{ suffix, 'B' }, + 1024 => []u8{ suffix, 'i', 'B' }, else => unreachable, }; return output(context, buf); } -pub fn formatInt(value: var, base: u8, uppercase: bool, width: usize, - context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8)Errors!void) Errors!void -{ +pub fn formatInt( + value: var, + base: u8, + uppercase: bool, + width: usize, + context: var, + comptime Errors: type, + output: fn(@typeOf(context), []const u8) Errors!void, +) Errors!void { if (@typeOf(value).is_signed) { return formatIntSigned(value, base, uppercase, width, context, Errors, output); } else { @@ -717,9 +728,9 @@ pub fn parseUnsigned(comptime T: type, buf: []const u8, radix: u8) ParseUnsigned pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) { const value = switch (c) { - '0' ... '9' => c - '0', - 'A' ... 'Z' => c - 'A' + 10, - 'a' ... 'z' => c - 'a' + 10, + '0'...'9' => c - '0', + 'A'...'Z' => c - 'A' + 10, + 'a'...'z' => c - 'a' + 10, else => return error.InvalidCharacter, }; @@ -730,8 +741,8 @@ pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) { fn digitToChar(digit: u8, uppercase: bool) u8 { return switch (digit) { - 0 ... 9 => digit + '0', - 10 ... 35 => digit + ((if (uppercase) u8('A') else u8('a')) - 10), + 0...9 => digit + '0', + 10...35 => digit + ((if (uppercase) u8('A') else u8('a')) - 10), else => unreachable, }; } @@ -754,8 +765,7 @@ pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: ...) ![]u8 { pub fn allocPrint(allocator: &mem.Allocator, comptime fmt: []const u8, args: ...) ![]u8 { var size: usize = 0; - format(&size, error{}, countSize, fmt, args) catch |err| switch (err) { - }; + format(&size, error{}, countSize, fmt, args) catch |err| switch (err) {}; const buf = try allocator.alloc(u8, size); return bufPrint(buf, fmt, args); } @@ -1043,8 +1053,7 @@ test "fmt.format" { fn testFmt(expected: []const u8, comptime template: []const u8, args: ...) !void { var buf: [100]u8 = undefined; const result = try bufPrint(buf[0..], template, args); - if (mem.eql(u8, result, expected)) - return; + if (mem.eql(u8, result, expected)) return; std.debug.warn("\n====== expected this output: =========\n"); std.debug.warn("{}", expected); @@ -1082,10 +1091,7 @@ test "fmt.trim" { pub fn isWhiteSpace(byte: u8) bool { return switch (byte) { - ' ', - '\t', - '\n', - '\r' => true, + ' ', '\t', '\n', '\r' => true, else => false, }; } diff --git a/std/hash/adler.zig b/std/hash/adler.zig index c77a5aaf50..12dab1457c 100644 --- a/std/hash/adler.zig +++ b/std/hash/adler.zig @@ -13,9 +13,7 @@ pub const Adler32 = struct { adler: u32, pub fn init() Adler32 { - return Adler32 { - .adler = 1, - }; + return Adler32{ .adler = 1 }; } // This fast variant is taken from zlib. It reduces the required modulos and unrolls longer @@ -33,8 +31,7 @@ pub const Adler32 = struct { if (s2 >= base) { s2 -= base; } - } - else if (input.len < 16) { + } else if (input.len < 16) { for (input) |b| { s1 +%= b; s2 +%= s1; @@ -44,8 +41,7 @@ pub const Adler32 = struct { } s2 %= base; - } - else { + } else { var i: usize = 0; while (i + nmax <= input.len) : (i += nmax) { const n = nmax / 16; // note: 16 | nmax @@ -98,15 +94,14 @@ test "adler32 sanity" { } test "adler32 long" { - const long1 = []u8 {1} ** 1024; + const long1 = []u8{1} ** 1024; debug.assert(Adler32.hash(long1[0..]) == 0x06780401); - const long2 = []u8 {1} ** 1025; + const long2 = []u8{1} ** 1025; debug.assert(Adler32.hash(long2[0..]) == 0x0a7a0402); } test "adler32 very long" { - const long = []u8 {1} ** 5553; + const long = []u8{1} ** 5553; debug.assert(Adler32.hash(long[0..]) == 0x707f15b2); } - diff --git a/std/hash/crc.zig b/std/hash/crc.zig index e4c1405a1c..72c4e467c2 100644 --- a/std/hash/crc.zig +++ b/std/hash/crc.zig @@ -69,7 +69,6 @@ pub fn Crc32WithPoly(comptime poly: u32) type { self.crc ^= (u32(p[2]) << 16); self.crc ^= (u32(p[3]) << 24); - self.crc = lookup_tables[0][p[7]] ^ lookup_tables[1][p[6]] ^ @@ -77,8 +76,8 @@ pub fn Crc32WithPoly(comptime poly: u32) type { lookup_tables[3][p[4]] ^ lookup_tables[4][@truncate(u8, self.crc >> 24)] ^ lookup_tables[5][@truncate(u8, self.crc >> 16)] ^ - lookup_tables[6][@truncate(u8, self.crc >> 8)] ^ - lookup_tables[7][@truncate(u8, self.crc >> 0)]; + lookup_tables[6][@truncate(u8, self.crc >> 8)] ^ + lookup_tables[7][@truncate(u8, self.crc >> 0)]; } while (i < input.len) : (i += 1) { diff --git a/std/hash/fnv.zig b/std/hash/fnv.zig index 88b965b76a..c2439e0ebc 100644 --- a/std/hash/fnv.zig +++ b/std/hash/fnv.zig @@ -7,7 +7,7 @@ const std = @import("../index.zig"); const debug = std.debug; -pub const Fnv1a_32 = Fnv1a(u32, 0x01000193 , 0x811c9dc5); +pub const Fnv1a_32 = Fnv1a(u32, 0x01000193, 0x811c9dc5); pub const Fnv1a_64 = Fnv1a(u64, 0x100000001b3, 0xcbf29ce484222325); pub const Fnv1a_128 = Fnv1a(u128, 0x1000000000000000000013b, 0x6c62272e07bb014262b821756295c58d); @@ -18,9 +18,7 @@ fn Fnv1a(comptime T: type, comptime prime: T, comptime offset: T) type { value: T, pub fn init() Self { - return Self { - .value = offset, - }; + return Self{ .value = offset }; } pub fn update(self: &Self, input: []const u8) void { diff --git a/std/hash/siphash.zig b/std/hash/siphash.zig index 301c35cf05..b75866a403 100644 --- a/std/hash/siphash.zig +++ b/std/hash/siphash.zig @@ -45,7 +45,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) const k0 = mem.readInt(key[0..8], u64, Endian.Little); const k1 = mem.readInt(key[8..16], u64, Endian.Little); - var d = Self { + var d = Self{ .v0 = k0 ^ 0x736f6d6570736575, .v1 = k1 ^ 0x646f72616e646f6d, .v2 = k0 ^ 0x6c7967656e657261, @@ -162,7 +162,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) const test_key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"; test "siphash64-2-4 sanity" { - const vectors = [][]const u8 { + const vectors = [][]const u8{ "\x31\x0e\x0e\xdd\x47\xdb\x6f\x72", // "" "\xfd\x67\xdc\x93\xc5\x39\xf8\x74", // "\x00" "\x5a\x4f\xa9\xd9\x09\x80\x6c\x0d", // "\x00\x01" ... etc @@ -241,7 +241,7 @@ test "siphash64-2-4 sanity" { } test "siphash128-2-4 sanity" { - const vectors = [][]const u8 { + const vectors = [][]const u8{ "\xa3\x81\x7f\x04\xba\x25\xa8\xe6\x6d\xf6\x72\x14\xc7\x55\x02\x93", "\xda\x87\xc1\xd8\x6b\x99\xaf\x44\x34\x76\x59\x11\x9b\x22\xfc\x45", "\x81\x77\x22\x8d\xa4\xa4\x5d\xc7\xfc\xa3\x8b\xde\xf6\x0a\xff\xe4", diff --git a/std/heap.zig b/std/heap.zig index 7b753524a6..8d4938a7c3 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -68,9 +68,7 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => { + Os.linux, Os.macosx, Os.ios => { const p = os.posix; const alloc_size = if (alignment <= os.page_size) n else n + alignment; const addr = p.mmap(null, alloc_size, p.PROT_READ | p.PROT_WRITE, p.MAP_PRIVATE | p.MAP_ANONYMOUS, -1, 0); @@ -121,9 +119,7 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => { + Os.linux, Os.macosx, Os.ios => { if (new_size <= old_mem.len) { const base_addr = @ptrToInt(old_mem.ptr); const old_addr_end = base_addr + old_mem.len; @@ -168,9 +164,7 @@ pub const DirectAllocator = struct { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => { + Os.linux, Os.macosx, Os.ios => { _ = os.posix.munmap(@ptrToInt(bytes.ptr), bytes.len); }, Os.windows => { @@ -430,7 +424,7 @@ fn testAllocator(allocator: &mem.Allocator) !void { } fn testAllocatorLargeAlignment(allocator: &mem.Allocator) mem.Allocator.Error!void { - //Maybe a platform's page_size is actually the same as or + //Maybe a platform's page_size is actually the same as or // very near usize? if (os.page_size << 2 > @maxValue(usize)) return; diff --git a/std/io_test.zig b/std/io_test.zig index 5f53556785..ca4eeb3aaa 100644 --- a/std/io_test.zig +++ b/std/io_test.zig @@ -42,7 +42,7 @@ test "write a file, read it, then delete it" { assert(mem.eql(u8, contents[0.."begin".len], "begin")); assert(mem.eql(u8, contents["begin".len..contents.len - "end".len], data)); - assert(mem.eql(u8, contents[contents.len - "end".len ..], "end")); + assert(mem.eql(u8, contents[contents.len - "end".len..], "end")); } try os.deleteFile(allocator, tmp_file_name); } diff --git a/std/json.zig b/std/json.zig index e969899403..c88ce59139 100644 --- a/std/json.zig +++ b/std/json.zig @@ -252,7 +252,7 @@ pub const StreamingJsonParser = struct { p.after_value_state = State.TopLevelEnd; p.count = 0; }, - '1' ... '9' => { + '1'...'9' => { p.number_is_integer = true; p.state = State.NumberMaybeDigitOrDotOrExponent; p.after_value_state = State.TopLevelEnd; @@ -281,10 +281,7 @@ pub const StreamingJsonParser = struct { p.after_value_state = State.TopLevelEnd; p.count = 0; }, - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -293,10 +290,7 @@ pub const StreamingJsonParser = struct { }, State.TopLevelEnd => switch (c) { - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -392,7 +386,7 @@ pub const StreamingJsonParser = struct { p.state = State.NumberMaybeDotOrExponent; p.count = 0; }, - '1' ... '9' => { + '1'...'9' => { p.state = State.NumberMaybeDigitOrDotOrExponent; p.count = 0; }, @@ -412,10 +406,7 @@ pub const StreamingJsonParser = struct { p.state = State.NullLiteral1; p.count = 0; }, - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -461,7 +452,7 @@ pub const StreamingJsonParser = struct { p.state = State.NumberMaybeDotOrExponent; p.count = 0; }, - '1' ... '9' => { + '1'...'9' => { p.state = State.NumberMaybeDigitOrDotOrExponent; p.count = 0; }, @@ -481,10 +472,7 @@ pub const StreamingJsonParser = struct { p.state = State.NullLiteral1; p.count = 0; }, - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -533,10 +521,7 @@ pub const StreamingJsonParser = struct { token.* = Token.initMarker(Token.Id.ObjectEnd); }, - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -549,10 +534,7 @@ pub const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; }, - 0x09, - 0x0A, - 0x0D, - 0x20 => { + 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { @@ -561,7 +543,7 @@ pub const StreamingJsonParser = struct { }, State.String => switch (c) { - 0x00 ... 0x1F => { + 0x00...0x1F => { return error.InvalidControlCharacter; }, '"' => { @@ -576,19 +558,16 @@ pub const StreamingJsonParser = struct { '\\' => { p.state = State.StringEscapeCharacter; }, - 0x20, - 0x21, - 0x23 ... 0x5B, - 0x5D ... 0x7F => { + 0x20, 0x21, 0x23...0x5B, 0x5D...0x7F => { // non-control ascii }, - 0xC0 ... 0xDF => { + 0xC0...0xDF => { p.state = State.StringUtf8Byte1; }, - 0xE0 ... 0xEF => { + 0xE0...0xEF => { p.state = State.StringUtf8Byte2; }, - 0xF0 ... 0xFF => { + 0xF0...0xFF => { p.state = State.StringUtf8Byte3; }, else => { @@ -620,14 +599,7 @@ pub const StreamingJsonParser = struct { // The current JSONTestSuite tests rely on both of this behaviour being present // however, so we default to the status quo where both are accepted until this // is further clarified. - '"', - '\\', - '/', - 'b', - 'f', - 'n', - 'r', - 't' => { + '"', '\\', '/', 'b', 'f', 'n', 'r', 't' => { p.string_has_escape = true; p.state = State.String; }, @@ -641,36 +613,28 @@ pub const StreamingJsonParser = struct { }, State.StringEscapeHexUnicode4 => switch (c) { - '0' ... '9', - 'A' ... 'F', - 'a' ... 'f' => { + '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.StringEscapeHexUnicode3; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode3 => switch (c) { - '0' ... '9', - 'A' ... 'F', - 'a' ... 'f' => { + '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.StringEscapeHexUnicode2; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode2 => switch (c) { - '0' ... '9', - 'A' ... 'F', - 'a' ... 'f' => { + '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.StringEscapeHexUnicode1; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode1 => switch (c) { - '0' ... '9', - 'A' ... 'F', - 'a' ... 'f' => { + '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.String; }, else => return error.InvalidUnicodeHexSymbol, @@ -682,7 +646,7 @@ pub const StreamingJsonParser = struct { '0' => { p.state = State.NumberMaybeDotOrExponent; }, - '1' ... '9' => { + '1'...'9' => { p.state = State.NumberMaybeDigitOrDotOrExponent; }, else => { @@ -698,8 +662,7 @@ pub const StreamingJsonParser = struct { p.number_is_integer = false; p.state = State.NumberFractionalRequired; }, - 'e', - 'E' => { + 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, @@ -718,12 +681,11 @@ pub const StreamingJsonParser = struct { p.number_is_integer = false; p.state = State.NumberFractionalRequired; }, - 'e', - 'E' => { + 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, - '0' ... '9' => { + '0'...'9' => { // another digit }, else => { @@ -737,7 +699,7 @@ pub const StreamingJsonParser = struct { State.NumberFractionalRequired => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { - '0' ... '9' => { + '0'...'9' => { p.state = State.NumberFractional; }, else => { @@ -749,11 +711,10 @@ pub const StreamingJsonParser = struct { State.NumberFractional => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { - '0' ... '9' => { + '0'...'9' => { // another digit }, - 'e', - 'E' => { + 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, @@ -768,8 +729,7 @@ pub const StreamingJsonParser = struct { State.NumberMaybeExponent => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { - 'e', - 'E' => { + 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, @@ -782,12 +742,11 @@ pub const StreamingJsonParser = struct { }, State.NumberExponent => switch (c) { - '-', - '+' => { + '-', '+' => { p.complete = false; p.state = State.NumberExponentDigitsRequired; }, - '0' ... '9' => { + '0'...'9' => { p.complete = p.after_value_state == State.TopLevelEnd; p.state = State.NumberExponentDigits; }, @@ -797,7 +756,7 @@ pub const StreamingJsonParser = struct { }, State.NumberExponentDigitsRequired => switch (c) { - '0' ... '9' => { + '0'...'9' => { p.complete = p.after_value_state == State.TopLevelEnd; p.state = State.NumberExponentDigits; }, @@ -809,7 +768,7 @@ pub const StreamingJsonParser = struct { State.NumberExponentDigits => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { - '0' ... '9' => { + '0'...'9' => { // another digit }, else => { @@ -1257,8 +1216,7 @@ pub const JsonParser = struct { Token.Id.Null => { try p.stack.append(Value.Null); }, - Token.Id.ObjectEnd, - Token.Id.ArrayEnd => { + Token.Id.ObjectEnd, Token.Id.ArrayEnd => { unreachable; }, }, diff --git a/std/macho.zig b/std/macho.zig index 70e2c09788..615569e4b4 100644 --- a/std/macho.zig +++ b/std/macho.zig @@ -58,15 +58,15 @@ pub const SymbolTable = struct { // code, its displacement is different. pub fn deinit(self: &SymbolTable) void { self.allocator.free(self.symbols); - self.symbols = []const Symbol {}; + self.symbols = []const Symbol{}; self.allocator.free(self.strings); - self.strings = []const u8 {}; + self.strings = []const u8{}; } pub fn search(self: &const SymbolTable, address: usize) ?&const Symbol { var min: usize = 0; - var max: usize = self.symbols.len - 1; // Exclude sentinel. + var max: usize = self.symbols.len - 1; // Exclude sentinel. while (min < max) { const mid = min + (max - min) / 2; const curr = &self.symbols[mid]; @@ -118,10 +118,11 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable try in.stream.readNoEof(strings); var nsyms: usize = 0; - for (syms) |sym| if (isSymbol(sym)) nsyms += 1; + for (syms) |sym| + if (isSymbol(sym)) nsyms += 1; if (nsyms == 0) return error.MissingDebugInfo; - var symbols = try allocator.alloc(Symbol, nsyms + 1); // Room for sentinel. + var symbols = try allocator.alloc(Symbol, nsyms + 1); // Room for sentinel. errdefer allocator.free(symbols); var pie_slide: usize = 0; @@ -132,7 +133,7 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable const end = ??mem.indexOfScalarPos(u8, strings, start, 0); const name = strings[start..end]; const address = sym.n_value; - symbols[nsym] = Symbol { .name = name, .address = address }; + symbols[nsym] = Symbol{ .name = name, .address = address }; nsym += 1; if (is_pie and mem.eql(u8, name, "_SymbolTable_deinit")) { pie_slide = @ptrToInt(SymbolTable.deinit) - address; @@ -145,13 +146,14 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable // Insert the sentinel. Since we don't know where the last function ends, // we arbitrarily limit it to the start address + 4 KB. const top = symbols[nsyms - 1].address + 4096; - symbols[nsyms] = Symbol { .name = "", .address = top }; + symbols[nsyms] = Symbol{ .name = "", .address = top }; if (pie_slide != 0) { - for (symbols) |*symbol| symbol.address += pie_slide; + for (symbols) |*symbol| + symbol.address += pie_slide; } - return SymbolTable { + return SymbolTable{ .allocator = allocator, .symbols = symbols, .strings = strings, diff --git a/std/math/atan.zig b/std/math/atan.zig index c315adc42d..7eceef98e3 100644 --- a/std/math/atan.zig +++ b/std/math/atan.zig @@ -17,25 +17,25 @@ pub fn atan(x: var) @typeOf(x) { } fn atan32(x_: f32) f32 { - const atanhi = []const f32 { + const atanhi = []const f32{ 4.6364760399e-01, // atan(0.5)hi 7.8539812565e-01, // atan(1.0)hi 9.8279368877e-01, // atan(1.5)hi 1.5707962513e+00, // atan(inf)hi }; - const atanlo = []const f32 { + const atanlo = []const f32{ 5.0121582440e-09, // atan(0.5)lo 3.7748947079e-08, // atan(1.0)lo 3.4473217170e-08, // atan(1.5)lo 7.5497894159e-08, // atan(inf)lo }; - const aT = []const f32 { + const aT = []const f32{ 3.3333328366e-01, - -1.9999158382e-01, + -1.9999158382e-01, 1.4253635705e-01, - -1.0648017377e-01, + -1.0648017377e-01, 6.1687607318e-02, }; @@ -80,8 +80,7 @@ fn atan32(x_: f32) f32 { id = 1; x = (x - 1.0) / (x + 1.0); } - } - else { + } else { // |x| < 2.4375 if (ix < 0x401C0000) { id = 2; @@ -109,31 +108,31 @@ fn atan32(x_: f32) f32 { } fn atan64(x_: f64) f64 { - const atanhi = []const f64 { + const atanhi = []const f64{ 4.63647609000806093515e-01, // atan(0.5)hi 7.85398163397448278999e-01, // atan(1.0)hi 9.82793723247329054082e-01, // atan(1.5)hi 1.57079632679489655800e+00, // atan(inf)hi }; - const atanlo = []const f64 { + const atanlo = []const f64{ 2.26987774529616870924e-17, // atan(0.5)lo 3.06161699786838301793e-17, // atan(1.0)lo 1.39033110312309984516e-17, // atan(1.5)lo 6.12323399573676603587e-17, // atan(inf)lo }; - const aT = []const f64 { + const aT = []const f64{ 3.33333333333329318027e-01, - -1.99999999998764832476e-01, + -1.99999999998764832476e-01, 1.42857142725034663711e-01, - -1.11111104054623557880e-01, + -1.11111104054623557880e-01, 9.09088713343650656196e-02, - -7.69187620504482999495e-02, + -7.69187620504482999495e-02, 6.66107313738753120669e-02, - -5.83357013379057348645e-02, + -5.83357013379057348645e-02, 4.97687799461593236017e-02, - -3.65315727442169155270e-02, + -3.65315727442169155270e-02, 1.62858201153657823623e-02, }; @@ -179,8 +178,7 @@ fn atan64(x_: f64) f64 { id = 1; x = (x - 1.0) / (x + 1.0); } - } - else { + } else { // |x| < 2.4375 if (ix < 0x40038000) { id = 2; diff --git a/std/math/atan2.zig b/std/math/atan2.zig index 0892f0b438..f0a8e67c46 100644 --- a/std/math/atan2.zig +++ b/std/math/atan2.zig @@ -53,8 +53,7 @@ fn atan2_32(y: f32, x: f32) f32 { if (iy == 0) { switch (m) { - 0, - 1 => return y, // atan(+-0, +...) + 0, 1 => return y, // atan(+-0, +...) 2 => return pi, // atan(+0, -...) 3 => return -pi, // atan(-0, -...) else => unreachable, @@ -144,8 +143,7 @@ fn atan2_64(y: f64, x: f64) f64 { if (iy | ly == 0) { switch (m) { - 0, - 1 => return y, // atan(+-0, +...) + 0, 1 => return y, // atan(+-0, +...) 2 => return pi, // atan(+0, -...) 3 => return -pi, // atan(-0, -...) else => unreachable, diff --git a/std/math/complex/index.zig b/std/math/complex/index.zig index a4d493307e..5902ffaa19 100644 --- a/std/math/complex/index.zig +++ b/std/math/complex/index.zig @@ -31,28 +31,28 @@ pub fn Complex(comptime T: type) type { im: T, pub fn new(re: T, im: T) Self { - return Self { + return Self{ .re = re, .im = im, }; } pub fn add(self: &const Self, other: &const Self) Self { - return Self { + return Self{ .re = self.re + other.re, .im = self.im + other.im, }; } pub fn sub(self: &const Self, other: &const Self) Self { - return Self { + return Self{ .re = self.re - other.re, .im = self.im - other.im, }; } pub fn mul(self: &const Self, other: &const Self) Self { - return Self { + return Self{ .re = self.re * other.re - self.im * other.im, .im = self.im * other.re + self.re * other.im, }; @@ -63,14 +63,14 @@ pub fn Complex(comptime T: type) type { const im_num = self.im * other.re - self.re * other.im; const den = other.re * other.re + other.im * other.im; - return Self { + return Self{ .re = re_num / den, .im = im_num / den, }; } pub fn conjugate(self: &const Self) Self { - return Self { + return Self{ .re = self.re, .im = -self.im, }; @@ -78,7 +78,7 @@ pub fn Complex(comptime T: type) type { pub fn reciprocal(self: &const Self) Self { const m = self.re * self.re + self.im * self.im; - return Self { + return Self{ .re = self.re / m, .im = -self.im / m, }; @@ -121,8 +121,8 @@ test "complex.div" { const b = Complex(f32).new(2, 7); const c = a.div(b); - debug.assert(math.approxEq(f32, c.re, f32(31)/53, epsilon) and - math.approxEq(f32, c.im, f32(-29)/53, epsilon)); + debug.assert(math.approxEq(f32, c.re, f32(31) / 53, epsilon) and + math.approxEq(f32, c.im, f32(-29) / 53, epsilon)); } test "complex.conjugate" { @@ -136,8 +136,8 @@ test "complex.reciprocal" { const a = Complex(f32).new(5, 3); const c = a.reciprocal(); - debug.assert(math.approxEq(f32, c.re, f32(5)/34, epsilon) and - math.approxEq(f32, c.im, f32(-3)/34, epsilon)); + debug.assert(math.approxEq(f32, c.re, f32(5) / 34, epsilon) and + math.approxEq(f32, c.im, f32(-3) / 34, epsilon)); } test "complex.magnitude" { diff --git a/std/math/complex/tanh.zig b/std/math/complex/tanh.zig index 6af62f48ae..34250b1b4a 100644 --- a/std/math/complex/tanh.zig +++ b/std/math/complex/tanh.zig @@ -98,7 +98,7 @@ test "complex.ctanh32" { const a = Complex(f32).new(5, 3); const c = tanh(a); - debug.assert(math.approxEq(f32, c.re, 0.999913, epsilon)); + debug.assert(math.approxEq(f32, c.re, 0.999913, epsilon)); debug.assert(math.approxEq(f32, c.im, -0.000025, epsilon)); } @@ -106,6 +106,6 @@ test "complex.ctanh64" { const a = Complex(f64).new(5, 3); const c = tanh(a); - debug.assert(math.approxEq(f64, c.re, 0.999913, epsilon)); + debug.assert(math.approxEq(f64, c.re, 0.999913, epsilon)); debug.assert(math.approxEq(f64, c.im, -0.000025, epsilon)); } diff --git a/std/math/exp.zig b/std/math/exp.zig index 21aa558c57..76dc47d04b 100644 --- a/std/math/exp.zig +++ b/std/math/exp.zig @@ -20,10 +20,10 @@ pub fn exp(x: var) @typeOf(x) { fn exp32(x_: f32) f32 { @setFloatMode(this, builtin.FloatMode.Strict); - const half = []f32 { 0.5, -0.5 }; + const half = []f32{ 0.5, -0.5 }; const ln2hi = 6.9314575195e-1; const ln2lo = 1.4286067653e-6; - const invln2 = 1.4426950216e+0; + const invln2 = 1.4426950216e+0; const P1 = 1.6666625440e-1; const P2 = -2.7667332906e-3; @@ -47,7 +47,7 @@ fn exp32(x_: f32) f32 { return x * 0x1.0p127; } if (sign != 0) { - math.forceEval(-0x1.0p-149 / x); // overflow + math.forceEval(-0x1.0p-149 / x); // overflow // x <= -103.972084 if (hx >= 0x42CFF1B5) { return 0; @@ -64,8 +64,7 @@ fn exp32(x_: f32) f32 { // |x| > 1.5 * ln2 if (hx > 0x3F851592) { k = i32(invln2 * x + half[usize(sign)]); - } - else { + } else { k = 1 - sign - sign; } @@ -79,8 +78,7 @@ fn exp32(x_: f32) f32 { k = 0; hi = x; lo = 0; - } - else { + } else { math.forceEval(0x1.0p127 + x); // inexact return 1 + x; } @@ -99,15 +97,15 @@ fn exp32(x_: f32) f32 { fn exp64(x_: f64) f64 { @setFloatMode(this, builtin.FloatMode.Strict); - const half = []const f64 { 0.5, -0.5 }; + const half = []const f64{ 0.5, -0.5 }; const ln2hi: f64 = 6.93147180369123816490e-01; const ln2lo: f64 = 1.90821492927058770002e-10; const invln2: f64 = 1.44269504088896338700e+00; - const P1: f64 = 1.66666666666666019037e-01; - const P2: f64 = -2.77777777770155933842e-03; - const P3: f64 = 6.61375632143793436117e-05; - const P4: f64 = -1.65339022054652515390e-06; - const P5: f64 = 4.13813679705723846039e-08; + const P1: f64 = 1.66666666666666019037e-01; + const P2: f64 = -2.77777777770155933842e-03; + const P3: f64 = 6.61375632143793436117e-05; + const P4: f64 = -1.65339022054652515390e-06; + const P5: f64 = 4.13813679705723846039e-08; var x = x_; var ux = @bitCast(u64, x); @@ -151,8 +149,7 @@ fn exp64(x_: f64) f64 { // |x| >= 1.5 * ln2 if (hx > 0x3FF0A2B2) { k = i32(invln2 * x + half[usize(sign)]); - } - else { + } else { k = 1 - sign - sign; } @@ -166,8 +163,7 @@ fn exp64(x_: f64) f64 { k = 0; hi = x; lo = 0; - } - else { + } else { // inexact if x != 0 // math.forceEval(0x1.0p1023 + x); return 1 + x; diff --git a/std/math/exp2.zig b/std/math/exp2.zig index 790bd1a558..62a3eb85b6 100644 --- a/std/math/exp2.zig +++ b/std/math/exp2.zig @@ -16,7 +16,7 @@ pub fn exp2(x: var) @typeOf(x) { }; } -const exp2ft = []const f64 { +const exp2ft = []const f64{ 0x1.6a09e667f3bcdp-1, 0x1.7a11473eb0187p-1, 0x1.8ace5422aa0dbp-1, @@ -92,195 +92,195 @@ fn exp2_32(x: f32) f32 { return f32(r * uk); } -const exp2dt = []f64 { +const exp2dt = []f64{ // exp2(z + eps) eps - 0x1.6a09e667f3d5dp-1, 0x1.9880p-44, - 0x1.6b052fa751744p-1, 0x1.8000p-50, + 0x1.6a09e667f3d5dp-1, 0x1.9880p-44, + 0x1.6b052fa751744p-1, 0x1.8000p-50, 0x1.6c012750bd9fep-1, -0x1.8780p-45, - 0x1.6cfdcddd476bfp-1, 0x1.ec00p-46, + 0x1.6cfdcddd476bfp-1, 0x1.ec00p-46, 0x1.6dfb23c651a29p-1, -0x1.8000p-50, 0x1.6ef9298593ae3p-1, -0x1.c000p-52, 0x1.6ff7df9519386p-1, -0x1.fd80p-45, 0x1.70f7466f42da3p-1, -0x1.c880p-45, - 0x1.71f75e8ec5fc3p-1, 0x1.3c00p-46, + 0x1.71f75e8ec5fc3p-1, 0x1.3c00p-46, 0x1.72f8286eacf05p-1, -0x1.8300p-44, 0x1.73f9a48a58152p-1, -0x1.0c00p-47, - 0x1.74fbd35d7ccfcp-1, 0x1.f880p-45, - 0x1.75feb564267f1p-1, 0x1.3e00p-47, + 0x1.74fbd35d7ccfcp-1, 0x1.f880p-45, + 0x1.75feb564267f1p-1, 0x1.3e00p-47, 0x1.77024b1ab6d48p-1, -0x1.7d00p-45, 0x1.780694fde5d38p-1, -0x1.d000p-50, - 0x1.790b938ac1d00p-1, 0x1.3000p-49, + 0x1.790b938ac1d00p-1, 0x1.3000p-49, 0x1.7a11473eb0178p-1, -0x1.d000p-49, - 0x1.7b17b0976d060p-1, 0x1.0400p-45, - 0x1.7c1ed0130c133p-1, 0x1.0000p-53, + 0x1.7b17b0976d060p-1, 0x1.0400p-45, + 0x1.7c1ed0130c133p-1, 0x1.0000p-53, 0x1.7d26a62ff8636p-1, -0x1.6900p-45, 0x1.7e2f336cf4e3bp-1, -0x1.2e00p-47, 0x1.7f3878491c3e8p-1, -0x1.4580p-45, - 0x1.80427543e1b4ep-1, 0x1.3000p-44, - 0x1.814d2add1071ap-1, 0x1.f000p-47, + 0x1.80427543e1b4ep-1, 0x1.3000p-44, + 0x1.814d2add1071ap-1, 0x1.f000p-47, 0x1.82589994ccd7ep-1, -0x1.1c00p-45, - 0x1.8364c1eb942d0p-1, 0x1.9d00p-45, - 0x1.8471a4623cab5p-1, 0x1.7100p-43, - 0x1.857f4179f5bbcp-1, 0x1.2600p-45, + 0x1.8364c1eb942d0p-1, 0x1.9d00p-45, + 0x1.8471a4623cab5p-1, 0x1.7100p-43, + 0x1.857f4179f5bbcp-1, 0x1.2600p-45, 0x1.868d99b4491afp-1, -0x1.2c40p-44, 0x1.879cad931a395p-1, -0x1.3000p-45, 0x1.88ac7d98a65b8p-1, -0x1.a800p-45, 0x1.89bd0a4785800p-1, -0x1.d000p-49, - 0x1.8ace5422aa223p-1, 0x1.3280p-44, - 0x1.8be05bad619fap-1, 0x1.2b40p-43, + 0x1.8ace5422aa223p-1, 0x1.3280p-44, + 0x1.8be05bad619fap-1, 0x1.2b40p-43, 0x1.8cf3216b54383p-1, -0x1.ed00p-45, 0x1.8e06a5e08664cp-1, -0x1.0500p-45, - 0x1.8f1ae99157807p-1, 0x1.8280p-45, + 0x1.8f1ae99157807p-1, 0x1.8280p-45, 0x1.902fed0282c0ep-1, -0x1.cb00p-46, 0x1.9145b0b91ff96p-1, -0x1.5e00p-47, - 0x1.925c353aa2ff9p-1, 0x1.5400p-48, - 0x1.93737b0cdc64ap-1, 0x1.7200p-46, + 0x1.925c353aa2ff9p-1, 0x1.5400p-48, + 0x1.93737b0cdc64ap-1, 0x1.7200p-46, 0x1.948b82b5f98aep-1, -0x1.9000p-47, - 0x1.95a44cbc852cbp-1, 0x1.5680p-45, + 0x1.95a44cbc852cbp-1, 0x1.5680p-45, 0x1.96bdd9a766f21p-1, -0x1.6d00p-44, 0x1.97d829fde4e2ap-1, -0x1.1000p-47, - 0x1.98f33e47a23a3p-1, 0x1.d000p-45, + 0x1.98f33e47a23a3p-1, 0x1.d000p-45, 0x1.9a0f170ca0604p-1, -0x1.8a40p-44, - 0x1.9b2bb4d53ff89p-1, 0x1.55c0p-44, - 0x1.9c49182a3f15bp-1, 0x1.6b80p-45, + 0x1.9b2bb4d53ff89p-1, 0x1.55c0p-44, + 0x1.9c49182a3f15bp-1, 0x1.6b80p-45, 0x1.9d674194bb8c5p-1, -0x1.c000p-49, - 0x1.9e86319e3238ep-1, 0x1.7d00p-46, - 0x1.9fa5e8d07f302p-1, 0x1.6400p-46, + 0x1.9e86319e3238ep-1, 0x1.7d00p-46, + 0x1.9fa5e8d07f302p-1, 0x1.6400p-46, 0x1.a0c667b5de54dp-1, -0x1.5000p-48, - 0x1.a1e7aed8eb8f6p-1, 0x1.9e00p-47, - 0x1.a309bec4a2e27p-1, 0x1.ad80p-45, + 0x1.a1e7aed8eb8f6p-1, 0x1.9e00p-47, + 0x1.a309bec4a2e27p-1, 0x1.ad80p-45, 0x1.a42c980460a5dp-1, -0x1.af00p-46, - 0x1.a5503b23e259bp-1, 0x1.b600p-47, - 0x1.a674a8af46213p-1, 0x1.8880p-44, - 0x1.a799e1330b3a7p-1, 0x1.1200p-46, - 0x1.a8bfe53c12e8dp-1, 0x1.6c00p-47, + 0x1.a5503b23e259bp-1, 0x1.b600p-47, + 0x1.a674a8af46213p-1, 0x1.8880p-44, + 0x1.a799e1330b3a7p-1, 0x1.1200p-46, + 0x1.a8bfe53c12e8dp-1, 0x1.6c00p-47, 0x1.a9e6b5579fcd2p-1, -0x1.9b80p-45, - 0x1.ab0e521356fb8p-1, 0x1.b700p-45, - 0x1.ac36bbfd3f381p-1, 0x1.9000p-50, - 0x1.ad5ff3a3c2780p-1, 0x1.4000p-49, + 0x1.ab0e521356fb8p-1, 0x1.b700p-45, + 0x1.ac36bbfd3f381p-1, 0x1.9000p-50, + 0x1.ad5ff3a3c2780p-1, 0x1.4000p-49, 0x1.ae89f995ad2a3p-1, -0x1.c900p-45, - 0x1.afb4ce622f367p-1, 0x1.6500p-46, - 0x1.b0e07298db790p-1, 0x1.fd40p-45, - 0x1.b20ce6c9a89a9p-1, 0x1.2700p-46, - 0x1.b33a2b84f1a4bp-1, 0x1.d470p-43, + 0x1.afb4ce622f367p-1, 0x1.6500p-46, + 0x1.b0e07298db790p-1, 0x1.fd40p-45, + 0x1.b20ce6c9a89a9p-1, 0x1.2700p-46, + 0x1.b33a2b84f1a4bp-1, 0x1.d470p-43, 0x1.b468415b747e7p-1, -0x1.8380p-44, - 0x1.b59728de5593ap-1, 0x1.8000p-54, - 0x1.b6c6e29f1c56ap-1, 0x1.ad00p-47, - 0x1.b7f76f2fb5e50p-1, 0x1.e800p-50, + 0x1.b59728de5593ap-1, 0x1.8000p-54, + 0x1.b6c6e29f1c56ap-1, 0x1.ad00p-47, + 0x1.b7f76f2fb5e50p-1, 0x1.e800p-50, 0x1.b928cf22749b2p-1, -0x1.4c00p-47, 0x1.ba5b030a10603p-1, -0x1.d700p-47, - 0x1.bb8e0b79a6f66p-1, 0x1.d900p-47, - 0x1.bcc1e904bc1ffp-1, 0x1.2a00p-47, + 0x1.bb8e0b79a6f66p-1, 0x1.d900p-47, + 0x1.bcc1e904bc1ffp-1, 0x1.2a00p-47, 0x1.bdf69c3f3a16fp-1, -0x1.f780p-46, 0x1.bf2c25bd71db8p-1, -0x1.0a00p-46, 0x1.c06286141b2e9p-1, -0x1.1400p-46, - 0x1.c199bdd8552e0p-1, 0x1.be00p-47, + 0x1.c199bdd8552e0p-1, 0x1.be00p-47, 0x1.c2d1cd9fa64eep-1, -0x1.9400p-47, 0x1.c40ab5fffd02fp-1, -0x1.ed00p-47, - 0x1.c544778fafd15p-1, 0x1.9660p-44, + 0x1.c544778fafd15p-1, 0x1.9660p-44, 0x1.c67f12e57d0cbp-1, -0x1.a100p-46, 0x1.c7ba88988c1b6p-1, -0x1.8458p-42, 0x1.c8f6d9406e733p-1, -0x1.a480p-46, - 0x1.ca3405751c4dfp-1, 0x1.b000p-51, - 0x1.cb720dcef9094p-1, 0x1.1400p-47, - 0x1.ccb0f2e6d1689p-1, 0x1.0200p-48, - 0x1.cdf0b555dc412p-1, 0x1.3600p-48, + 0x1.ca3405751c4dfp-1, 0x1.b000p-51, + 0x1.cb720dcef9094p-1, 0x1.1400p-47, + 0x1.ccb0f2e6d1689p-1, 0x1.0200p-48, + 0x1.cdf0b555dc412p-1, 0x1.3600p-48, 0x1.cf3155b5bab3bp-1, -0x1.6900p-47, - 0x1.d072d4a0789bcp-1, 0x1.9a00p-47, + 0x1.d072d4a0789bcp-1, 0x1.9a00p-47, 0x1.d1b532b08c8fap-1, -0x1.5e00p-46, - 0x1.d2f87080d8a85p-1, 0x1.d280p-46, - 0x1.d43c8eacaa203p-1, 0x1.1a00p-47, - 0x1.d5818dcfba491p-1, 0x1.f000p-50, + 0x1.d2f87080d8a85p-1, 0x1.d280p-46, + 0x1.d43c8eacaa203p-1, 0x1.1a00p-47, + 0x1.d5818dcfba491p-1, 0x1.f000p-50, 0x1.d6c76e862e6a1p-1, -0x1.3a00p-47, 0x1.d80e316c9834ep-1, -0x1.cd80p-47, - 0x1.d955d71ff6090p-1, 0x1.4c00p-48, - 0x1.da9e603db32aep-1, 0x1.f900p-48, - 0x1.dbe7cd63a8325p-1, 0x1.9800p-49, + 0x1.d955d71ff6090p-1, 0x1.4c00p-48, + 0x1.da9e603db32aep-1, 0x1.f900p-48, + 0x1.dbe7cd63a8325p-1, 0x1.9800p-49, 0x1.dd321f301b445p-1, -0x1.5200p-48, 0x1.de7d5641c05bfp-1, -0x1.d700p-46, 0x1.dfc97337b9aecp-1, -0x1.6140p-46, - 0x1.e11676b197d5ep-1, 0x1.b480p-47, - 0x1.e264614f5a3e7p-1, 0x1.0ce0p-43, - 0x1.e3b333b16ee5cp-1, 0x1.c680p-47, + 0x1.e11676b197d5ep-1, 0x1.b480p-47, + 0x1.e264614f5a3e7p-1, 0x1.0ce0p-43, + 0x1.e3b333b16ee5cp-1, 0x1.c680p-47, 0x1.e502ee78b3fb4p-1, -0x1.9300p-47, 0x1.e653924676d68p-1, -0x1.5000p-49, 0x1.e7a51fbc74c44p-1, -0x1.7f80p-47, 0x1.e8f7977cdb726p-1, -0x1.3700p-48, - 0x1.ea4afa2a490e8p-1, 0x1.5d00p-49, - 0x1.eb9f4867ccae4p-1, 0x1.61a0p-46, - 0x1.ecf482d8e680dp-1, 0x1.5500p-48, - 0x1.ee4aaa2188514p-1, 0x1.6400p-51, + 0x1.ea4afa2a490e8p-1, 0x1.5d00p-49, + 0x1.eb9f4867ccae4p-1, 0x1.61a0p-46, + 0x1.ecf482d8e680dp-1, 0x1.5500p-48, + 0x1.ee4aaa2188514p-1, 0x1.6400p-51, 0x1.efa1bee615a13p-1, -0x1.e800p-49, 0x1.f0f9c1cb64106p-1, -0x1.a880p-48, 0x1.f252b376bb963p-1, -0x1.c900p-45, - 0x1.f3ac948dd7275p-1, 0x1.a000p-53, + 0x1.f3ac948dd7275p-1, 0x1.a000p-53, 0x1.f50765b6e4524p-1, -0x1.4f00p-48, - 0x1.f6632798844fdp-1, 0x1.a800p-51, - 0x1.f7bfdad9cbe38p-1, 0x1.abc0p-48, + 0x1.f6632798844fdp-1, 0x1.a800p-51, + 0x1.f7bfdad9cbe38p-1, 0x1.abc0p-48, 0x1.f91d802243c82p-1, -0x1.4600p-50, 0x1.fa7c1819e908ep-1, -0x1.b0c0p-47, 0x1.fbdba3692d511p-1, -0x1.0e00p-51, 0x1.fd3c22b8f7194p-1, -0x1.0de8p-46, - 0x1.fe9d96b2a23eep-1, 0x1.e430p-49, - 0x1.0000000000000p+0, 0x0.0000p+0, + 0x1.fe9d96b2a23eep-1, 0x1.e430p-49, + 0x1.0000000000000p+0, 0x0.0000p+0, 0x1.00b1afa5abcbep+0, -0x1.3400p-52, 0x1.0163da9fb3303p+0, -0x1.2170p-46, - 0x1.02168143b0282p+0, 0x1.a400p-52, - 0x1.02c9a3e77806cp+0, 0x1.f980p-49, + 0x1.02168143b0282p+0, 0x1.a400p-52, + 0x1.02c9a3e77806cp+0, 0x1.f980p-49, 0x1.037d42e11bbcap+0, -0x1.7400p-51, - 0x1.04315e86e7f89p+0, 0x1.8300p-50, + 0x1.04315e86e7f89p+0, 0x1.8300p-50, 0x1.04e5f72f65467p+0, -0x1.a3f0p-46, 0x1.059b0d315855ap+0, -0x1.2840p-47, - 0x1.0650a0e3c1f95p+0, 0x1.1600p-48, - 0x1.0706b29ddf71ap+0, 0x1.5240p-46, + 0x1.0650a0e3c1f95p+0, 0x1.1600p-48, + 0x1.0706b29ddf71ap+0, 0x1.5240p-46, 0x1.07bd42b72a82dp+0, -0x1.9a00p-49, - 0x1.0874518759bd0p+0, 0x1.6400p-49, + 0x1.0874518759bd0p+0, 0x1.6400p-49, 0x1.092bdf66607c8p+0, -0x1.0780p-47, 0x1.09e3ecac6f383p+0, -0x1.8000p-54, - 0x1.0a9c79b1f3930p+0, 0x1.fa00p-48, + 0x1.0a9c79b1f3930p+0, 0x1.fa00p-48, 0x1.0b5586cf988fcp+0, -0x1.ac80p-48, - 0x1.0c0f145e46c8ap+0, 0x1.9c00p-50, - 0x1.0cc922b724816p+0, 0x1.5200p-47, + 0x1.0c0f145e46c8ap+0, 0x1.9c00p-50, + 0x1.0cc922b724816p+0, 0x1.5200p-47, 0x1.0d83b23395dd8p+0, -0x1.ad00p-48, - 0x1.0e3ec32d3d1f3p+0, 0x1.bac0p-46, + 0x1.0e3ec32d3d1f3p+0, 0x1.bac0p-46, 0x1.0efa55fdfa9a6p+0, -0x1.4e80p-47, 0x1.0fb66affed2f0p+0, -0x1.d300p-47, - 0x1.1073028d7234bp+0, 0x1.1500p-48, - 0x1.11301d0125b5bp+0, 0x1.c000p-49, - 0x1.11edbab5e2af9p+0, 0x1.6bc0p-46, - 0x1.12abdc06c31d5p+0, 0x1.8400p-49, + 0x1.1073028d7234bp+0, 0x1.1500p-48, + 0x1.11301d0125b5bp+0, 0x1.c000p-49, + 0x1.11edbab5e2af9p+0, 0x1.6bc0p-46, + 0x1.12abdc06c31d5p+0, 0x1.8400p-49, 0x1.136a814f2047dp+0, -0x1.ed00p-47, - 0x1.1429aaea92de9p+0, 0x1.8e00p-49, - 0x1.14e95934f3138p+0, 0x1.b400p-49, - 0x1.15a98c8a58e71p+0, 0x1.5300p-47, - 0x1.166a45471c3dfp+0, 0x1.3380p-47, - 0x1.172b83c7d5211p+0, 0x1.8d40p-45, + 0x1.1429aaea92de9p+0, 0x1.8e00p-49, + 0x1.14e95934f3138p+0, 0x1.b400p-49, + 0x1.15a98c8a58e71p+0, 0x1.5300p-47, + 0x1.166a45471c3dfp+0, 0x1.3380p-47, + 0x1.172b83c7d5211p+0, 0x1.8d40p-45, 0x1.17ed48695bb9fp+0, -0x1.5d00p-47, 0x1.18af9388c8d93p+0, -0x1.c880p-46, - 0x1.1972658375d66p+0, 0x1.1f00p-46, - 0x1.1a35beb6fcba7p+0, 0x1.0480p-46, + 0x1.1972658375d66p+0, 0x1.1f00p-46, + 0x1.1a35beb6fcba7p+0, 0x1.0480p-46, 0x1.1af99f81387e3p+0, -0x1.7390p-43, - 0x1.1bbe084045d54p+0, 0x1.4e40p-45, + 0x1.1bbe084045d54p+0, 0x1.4e40p-45, 0x1.1c82f95281c43p+0, -0x1.a200p-47, - 0x1.1d4873168b9b2p+0, 0x1.3800p-49, - 0x1.1e0e75eb44031p+0, 0x1.ac00p-49, - 0x1.1ed5022fcd938p+0, 0x1.1900p-47, + 0x1.1d4873168b9b2p+0, 0x1.3800p-49, + 0x1.1e0e75eb44031p+0, 0x1.ac00p-49, + 0x1.1ed5022fcd938p+0, 0x1.1900p-47, 0x1.1f9c18438cdf7p+0, -0x1.b780p-46, - 0x1.2063b88628d8fp+0, 0x1.d940p-45, - 0x1.212be3578a81ep+0, 0x1.8000p-50, - 0x1.21f49917ddd41p+0, 0x1.b340p-45, - 0x1.22bdda2791323p+0, 0x1.9f80p-46, + 0x1.2063b88628d8fp+0, 0x1.d940p-45, + 0x1.212be3578a81ep+0, 0x1.8000p-50, + 0x1.21f49917ddd41p+0, 0x1.b340p-45, + 0x1.22bdda2791323p+0, 0x1.9f80p-46, 0x1.2387a6e7561e7p+0, -0x1.9c80p-46, - 0x1.2451ffb821427p+0, 0x1.2300p-47, + 0x1.2451ffb821427p+0, 0x1.2300p-47, 0x1.251ce4fb2a602p+0, -0x1.3480p-46, - 0x1.25e85711eceb0p+0, 0x1.2700p-46, - 0x1.26b4565e27d16p+0, 0x1.1d00p-46, - 0x1.2780e341de00fp+0, 0x1.1ee0p-44, + 0x1.25e85711eceb0p+0, 0x1.2700p-46, + 0x1.26b4565e27d16p+0, 0x1.1d00p-46, + 0x1.2780e341de00fp+0, 0x1.1ee0p-44, 0x1.284dfe1f5633ep+0, -0x1.4c00p-46, 0x1.291ba7591bb30p+0, -0x1.3d80p-46, - 0x1.29e9df51fdf09p+0, 0x1.8b00p-47, + 0x1.29e9df51fdf09p+0, 0x1.8b00p-47, 0x1.2ab8a66d10e9bp+0, -0x1.27c0p-45, - 0x1.2b87fd0dada3ap+0, 0x1.a340p-45, + 0x1.2b87fd0dada3ap+0, 0x1.a340p-45, 0x1.2c57e39771af9p+0, -0x1.0800p-46, 0x1.2d285a6e402d9p+0, -0x1.ed00p-47, 0x1.2df961f641579p+0, -0x1.4200p-48, @@ -290,78 +290,78 @@ const exp2dt = []f64 { 0x1.31432edeea50bp+0, -0x1.0df8p-40, 0x1.32170fc4cd7b8p+0, -0x1.2480p-45, 0x1.32eb83ba8e9a2p+0, -0x1.5980p-45, - 0x1.33c08b2641766p+0, 0x1.ed00p-46, + 0x1.33c08b2641766p+0, 0x1.ed00p-46, 0x1.3496266e3fa27p+0, -0x1.c000p-50, 0x1.356c55f929f0fp+0, -0x1.0d80p-44, - 0x1.36431a2de88b9p+0, 0x1.2c80p-45, - 0x1.371a7373aaa39p+0, 0x1.0600p-45, + 0x1.36431a2de88b9p+0, 0x1.2c80p-45, + 0x1.371a7373aaa39p+0, 0x1.0600p-45, 0x1.37f26231e74fep+0, -0x1.6600p-46, 0x1.38cae6d05d838p+0, -0x1.ae00p-47, 0x1.39a401b713ec3p+0, -0x1.4720p-43, - 0x1.3a7db34e5a020p+0, 0x1.8200p-47, - 0x1.3b57fbfec6e95p+0, 0x1.e800p-44, - 0x1.3c32dc313a8f2p+0, 0x1.f800p-49, + 0x1.3a7db34e5a020p+0, 0x1.8200p-47, + 0x1.3b57fbfec6e95p+0, 0x1.e800p-44, + 0x1.3c32dc313a8f2p+0, 0x1.f800p-49, 0x1.3d0e544ede122p+0, -0x1.7a00p-46, - 0x1.3dea64c1234bbp+0, 0x1.6300p-45, + 0x1.3dea64c1234bbp+0, 0x1.6300p-45, 0x1.3ec70df1c4eccp+0, -0x1.8a60p-43, 0x1.3fa4504ac7e8cp+0, -0x1.cdc0p-44, - 0x1.40822c367a0bbp+0, 0x1.5b80p-45, - 0x1.4160a21f72e95p+0, 0x1.ec00p-46, + 0x1.40822c367a0bbp+0, 0x1.5b80p-45, + 0x1.4160a21f72e95p+0, 0x1.ec00p-46, 0x1.423fb27094646p+0, -0x1.3600p-46, - 0x1.431f5d950a920p+0, 0x1.3980p-45, - 0x1.43ffa3f84b9ebp+0, 0x1.a000p-48, + 0x1.431f5d950a920p+0, 0x1.3980p-45, + 0x1.43ffa3f84b9ebp+0, 0x1.a000p-48, 0x1.44e0860618919p+0, -0x1.6c00p-48, 0x1.45c2042a7d201p+0, -0x1.bc00p-47, 0x1.46a41ed1d0016p+0, -0x1.2800p-46, - 0x1.4786d668b3326p+0, 0x1.0e00p-44, + 0x1.4786d668b3326p+0, 0x1.0e00p-44, 0x1.486a2b5c13c00p+0, -0x1.d400p-45, - 0x1.494e1e192af04p+0, 0x1.c200p-47, + 0x1.494e1e192af04p+0, 0x1.c200p-47, 0x1.4a32af0d7d372p+0, -0x1.e500p-46, - 0x1.4b17dea6db801p+0, 0x1.7800p-47, + 0x1.4b17dea6db801p+0, 0x1.7800p-47, 0x1.4bfdad53629e1p+0, -0x1.3800p-46, - 0x1.4ce41b817c132p+0, 0x1.0800p-47, - 0x1.4dcb299fddddbp+0, 0x1.c700p-45, + 0x1.4ce41b817c132p+0, 0x1.0800p-47, + 0x1.4dcb299fddddbp+0, 0x1.c700p-45, 0x1.4eb2d81d8ab96p+0, -0x1.ce00p-46, - 0x1.4f9b2769d2d02p+0, 0x1.9200p-46, + 0x1.4f9b2769d2d02p+0, 0x1.9200p-46, 0x1.508417f4531c1p+0, -0x1.8c00p-47, 0x1.516daa2cf662ap+0, -0x1.a000p-48, - 0x1.5257de83f51eap+0, 0x1.a080p-43, + 0x1.5257de83f51eap+0, 0x1.a080p-43, 0x1.5342b569d4edap+0, -0x1.6d80p-45, 0x1.542e2f4f6ac1ap+0, -0x1.2440p-44, - 0x1.551a4ca5d94dbp+0, 0x1.83c0p-43, - 0x1.56070dde9116bp+0, 0x1.4b00p-45, - 0x1.56f4736b529dep+0, 0x1.15a0p-43, + 0x1.551a4ca5d94dbp+0, 0x1.83c0p-43, + 0x1.56070dde9116bp+0, 0x1.4b00p-45, + 0x1.56f4736b529dep+0, 0x1.15a0p-43, 0x1.57e27dbe2c40ep+0, -0x1.9e00p-45, 0x1.58d12d497c76fp+0, -0x1.3080p-45, - 0x1.59c0827ff0b4cp+0, 0x1.dec0p-43, + 0x1.59c0827ff0b4cp+0, 0x1.dec0p-43, 0x1.5ab07dd485427p+0, -0x1.4000p-51, - 0x1.5ba11fba87af4p+0, 0x1.0080p-44, + 0x1.5ba11fba87af4p+0, 0x1.0080p-44, 0x1.5c9268a59460bp+0, -0x1.6c80p-45, - 0x1.5d84590998e3fp+0, 0x1.69a0p-43, + 0x1.5d84590998e3fp+0, 0x1.69a0p-43, 0x1.5e76f15ad20e1p+0, -0x1.b400p-46, - 0x1.5f6a320dcebcap+0, 0x1.7700p-46, - 0x1.605e1b976dcb8p+0, 0x1.6f80p-45, - 0x1.6152ae6cdf715p+0, 0x1.1000p-47, + 0x1.5f6a320dcebcap+0, 0x1.7700p-46, + 0x1.605e1b976dcb8p+0, 0x1.6f80p-45, + 0x1.6152ae6cdf715p+0, 0x1.1000p-47, 0x1.6247eb03a5531p+0, -0x1.5d00p-46, 0x1.633dd1d1929b5p+0, -0x1.2d00p-46, 0x1.6434634ccc313p+0, -0x1.a800p-49, 0x1.652b9febc8efap+0, -0x1.8600p-45, - 0x1.6623882553397p+0, 0x1.1fe0p-40, + 0x1.6623882553397p+0, 0x1.1fe0p-40, 0x1.671c1c708328ep+0, -0x1.7200p-44, - 0x1.68155d44ca97ep+0, 0x1.6800p-49, + 0x1.68155d44ca97ep+0, 0x1.6800p-49, 0x1.690f4b19e9471p+0, -0x1.9780p-45, }; fn exp2_64(x: f64) f64 { @setFloatMode(this, @import("builtin").FloatMode.Strict); - const tblsiz = u32(exp2dt.len / 2); + const tblsiz = u32(exp2dt.len / 2); const redux: f64 = 0x1.8p52 / f64(tblsiz); - const P1: f64 = 0x1.62e42fefa39efp-1; - const P2: f64 = 0x1.ebfbdff82c575p-3; - const P3: f64 = 0x1.c6b08d704a0a6p-5; - const P4: f64 = 0x1.3b2ab88f70400p-7; - const P5: f64 = 0x1.5d88003875c74p-10; + const P1: f64 = 0x1.62e42fefa39efp-1; + const P2: f64 = 0x1.ebfbdff82c575p-3; + const P3: f64 = 0x1.c6b08d704a0a6p-5; + const P4: f64 = 0x1.3b2ab88f70400p-7; + const P5: f64 = 0x1.5d88003875c74p-10; const ux = @bitCast(u64, x); const ix = u32(ux >> 32) & 0x7FFFFFFF; diff --git a/std/math/expm1.zig b/std/math/expm1.zig index 316f0e3e71..11af1b215f 100644 --- a/std/math/expm1.zig +++ b/std/math/expm1.zig @@ -21,11 +21,11 @@ pub fn expm1(x: var) @typeOf(x) { fn expm1_32(x_: f32) f32 { @setFloatMode(this, builtin.FloatMode.Strict); const o_threshold: f32 = 8.8721679688e+01; - const ln2_hi: f32 = 6.9313812256e-01; - const ln2_lo: f32 = 9.0580006145e-06; - const invln2: f32 = 1.4426950216e+00; + const ln2_hi: f32 = 6.9313812256e-01; + const ln2_lo: f32 = 9.0580006145e-06; + const invln2: f32 = 1.4426950216e+00; const Q1: f32 = -3.3333212137e-2; - const Q2: f32 = 1.5807170421e-3; + const Q2: f32 = 1.5807170421e-3; var x = x_; const ux = @bitCast(u32, x); @@ -93,8 +93,7 @@ fn expm1_32(x_: f32) f32 { math.forceEval(x * x); } return x; - } - else { + } else { k = 0; } @@ -148,13 +147,13 @@ fn expm1_32(x_: f32) f32 { fn expm1_64(x_: f64) f64 { @setFloatMode(this, builtin.FloatMode.Strict); const o_threshold: f64 = 7.09782712893383973096e+02; - const ln2_hi: f64 = 6.93147180369123816490e-01; - const ln2_lo: f64 = 1.90821492927058770002e-10; - const invln2: f64 = 1.44269504088896338700e+00; + const ln2_hi: f64 = 6.93147180369123816490e-01; + const ln2_lo: f64 = 1.90821492927058770002e-10; + const invln2: f64 = 1.44269504088896338700e+00; const Q1: f64 = -3.33333333333331316428e-02; - const Q2: f64 = 1.58730158725481460165e-03; + const Q2: f64 = 1.58730158725481460165e-03; const Q3: f64 = -7.93650757867487942473e-05; - const Q4: f64 = 4.00821782732936239552e-06; + const Q4: f64 = 4.00821782732936239552e-06; const Q5: f64 = -2.01099218183624371326e-07; var x = x_; @@ -223,8 +222,7 @@ fn expm1_64(x_: f64) f64 { math.forceEval(f32(x)); } return x; - } - else { + } else { k = 0; } diff --git a/std/math/index.zig b/std/math/index.zig index 8fcd05d760..847e972500 100644 --- a/std/math/index.zig +++ b/std/math/index.zig @@ -501,7 +501,7 @@ test "math.negateCast" { if (negateCast(u32(@maxValue(i32) + 10))) |_| unreachable else |err| assert(err == error.Overflow); } -/// Cast an integer to a different integer type. If the value doesn't fit, +/// Cast an integer to a different integer type. If the value doesn't fit, /// return an error. pub fn cast(comptime T: type, x: var) (error{Overflow}!T) { comptime assert(@typeId(T) == builtin.TypeId.Int); // must pass an integer diff --git a/std/math/log1p.zig b/std/math/log1p.zig index 4616a2f2ba..57efdaf51c 100644 --- a/std/math/log1p.zig +++ b/std/math/log1p.zig @@ -138,8 +138,7 @@ fn log1p_64(x: f64) f64 { c = 0; f = x; } - } - else if (hx >= 0x7FF00000) { + } else if (hx >= 0x7FF00000) { return x; } diff --git a/std/math/pow.zig b/std/math/pow.zig index 51908f30ea..dfe4fc09d6 100644 --- a/std/math/pow.zig +++ b/std/math/pow.zig @@ -28,7 +28,6 @@ const assert = std.debug.assert; // This implementation is taken from the go stlib, musl is a bit more complex. pub fn pow(comptime T: type, x: T, y: T) T { - @setFloatMode(this, @import("builtin").FloatMode.Strict); if (T != f32 and T != f64) { diff --git a/std/net.zig b/std/net.zig index b1e291ab92..3af4e0b525 100644 --- a/std/net.zig +++ b/std/net.zig @@ -19,24 +19,30 @@ pub const Address = struct { os_addr: OsAddress, pub fn initIp4(ip4: u32, port: u16) Address { - return Address{ .os_addr = posix.sockaddr{ .in = posix.sockaddr_in{ - .family = posix.AF_INET, - .port = std.mem.endianSwapIfLe(u16, port), - .addr = ip4, - .zero = []u8{0} ** 8, - } } }; + return Address{ + .os_addr = posix.sockaddr{ + .in = posix.sockaddr_in{ + .family = posix.AF_INET, + .port = std.mem.endianSwapIfLe(u16, port), + .addr = ip4, + .zero = []u8{0} ** 8, + }, + }, + }; } pub fn initIp6(ip6: &const Ip6Addr, port: u16) Address { return Address{ .family = posix.AF_INET6, - .os_addr = posix.sockaddr{ .in6 = posix.sockaddr_in6{ - .family = posix.AF_INET6, - .port = std.mem.endianSwapIfLe(u16, port), - .flowinfo = 0, - .addr = ip6.addr, - .scope_id = ip6.scope_id, - } }, + .os_addr = posix.sockaddr{ + .in6 = posix.sockaddr_in6{ + .family = posix.AF_INET6, + .port = std.mem.endianSwapIfLe(u16, port), + .flowinfo = 0, + .addr = ip6.addr, + .scope_id = ip6.scope_id, + }, + }, }; } diff --git a/std/os/child_process.zig b/std/os/child_process.zig index dc3a582707..51f1bd96e5 100644 --- a/std/os/child_process.zig +++ b/std/os/child_process.zig @@ -387,15 +387,12 @@ pub const ChildProcess = struct { const pid_err = posix.getErrno(pid_result); if (pid_err > 0) { return switch (pid_err) { - posix.EAGAIN, - posix.ENOMEM, - posix.ENOSYS => error.SystemResources, + posix.EAGAIN, posix.ENOMEM, posix.ENOSYS => error.SystemResources, else => os.unexpectedErrorPosix(pid_err), }; } if (pid_result == 0) { // we are the child - setUpChildIo(self.stdin_behavior, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); setUpChildIo(self.stdout_behavior, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); setUpChildIo(self.stderr_behavior, stderr_pipe[1], posix.STDERR_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); @@ -646,8 +643,7 @@ fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ? if (windows.CreateProcessA(app_name, cmd_line, null, null, windows.TRUE, 0, @ptrCast(?&c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation) == 0) { const err = windows.GetLastError(); return switch (err) { - windows.ERROR.FILE_NOT_FOUND, - windows.ERROR.PATH_NOT_FOUND => error.FileNotFound, + windows.ERROR.FILE_NOT_FOUND, windows.ERROR.PATH_NOT_FOUND => error.FileNotFound, windows.ERROR.INVALID_PARAMETER => unreachable, windows.ERROR.INVALID_NAME => error.InvalidName, else => os.unexpectedErrorWindows(err), @@ -745,8 +741,7 @@ fn makePipe() ![2]i32 { const err = posix.getErrno(posix.pipe(&fds)); if (err > 0) { return switch (err) { - posix.EMFILE, - posix.ENFILE => error.SystemResources, + posix.EMFILE, posix.ENFILE => error.SystemResources, else => os.unexpectedErrorPosix(err), }; } diff --git a/std/os/darwin.zig b/std/os/darwin.zig index 45359e757d..a01755d27b 100644 --- a/std/os/darwin.zig +++ b/std/os/darwin.zig @@ -12,52 +12,71 @@ pub const STDERR_FILENO = 2; /// [MC2] no permissions pub const PROT_NONE = 0x00; + /// [MC2] pages can be read pub const PROT_READ = 0x01; + /// [MC2] pages can be written pub const PROT_WRITE = 0x02; + /// [MC2] pages can be executed pub const PROT_EXEC = 0x04; /// allocated from memory, swap space pub const MAP_ANONYMOUS = 0x1000; + /// map from file (default) pub const MAP_FILE = 0x0000; + /// interpret addr exactly pub const MAP_FIXED = 0x0010; + /// region may contain semaphores pub const MAP_HASSEMAPHORE = 0x0200; + /// changes are private pub const MAP_PRIVATE = 0x0002; + /// share changes pub const MAP_SHARED = 0x0001; + /// don't cache pages for this mapping pub const MAP_NOCACHE = 0x0400; + /// don't reserve needed swap area pub const MAP_NORESERVE = 0x0040; pub const MAP_FAILED = @maxValue(usize); /// [XSI] no hang in wait/no child to reap pub const WNOHANG = 0x00000001; + /// [XSI] notify on stop, untraced child pub const WUNTRACED = 0x00000002; /// take signal on signal stack pub const SA_ONSTACK = 0x0001; + /// restart system on signal return pub const SA_RESTART = 0x0002; + /// reset to SIG_DFL when taking signal pub const SA_RESETHAND = 0x0004; + /// do not generate SIGCHLD on child stop pub const SA_NOCLDSTOP = 0x0008; + /// don't mask the signal we're delivering pub const SA_NODEFER = 0x0010; + /// don't keep zombies around pub const SA_NOCLDWAIT = 0x0020; + /// signal handler with SA_SIGINFO args pub const SA_SIGINFO = 0x0040; + /// do not bounce off kernel's sigtramp pub const SA_USERTRAMP = 0x0100; + /// signal handler with SA_SIGINFO args with 64bit regs information pub const SA_64REGSET = 0x0200; @@ -71,30 +90,43 @@ pub const R_OK = 4; /// open for reading only pub const O_RDONLY = 0x0000; + /// open for writing only pub const O_WRONLY = 0x0001; + /// open for reading and writing pub const O_RDWR = 0x0002; + /// do not block on open or for data to become available pub const O_NONBLOCK = 0x0004; + /// append on each write pub const O_APPEND = 0x0008; + /// create file if it does not exist pub const O_CREAT = 0x0200; + /// truncate size to 0 pub const O_TRUNC = 0x0400; + /// error if O_CREAT and the file exists pub const O_EXCL = 0x0800; + /// atomically obtain a shared lock pub const O_SHLOCK = 0x0010; + /// atomically obtain an exclusive lock pub const O_EXLOCK = 0x0020; + /// do not follow symlinks pub const O_NOFOLLOW = 0x0100; + /// allow open of symlinks pub const O_SYMLINK = 0x200000; + /// descriptor requested for event notifications only pub const O_EVTONLY = 0x8000; + /// mark as close-on-exec pub const O_CLOEXEC = 0x1000000; @@ -126,75 +158,109 @@ pub const DT_WHT = 14; /// block specified signal set pub const SIG_BLOCK = 1; + /// unblock specified signal set pub const SIG_UNBLOCK = 2; + /// set specified signal set pub const SIG_SETMASK = 3; /// hangup pub const SIGHUP = 1; + /// interrupt pub const SIGINT = 2; + /// quit pub const SIGQUIT = 3; + /// illegal instruction (not reset when caught) pub const SIGILL = 4; + /// trace trap (not reset when caught) pub const SIGTRAP = 5; + /// abort() pub const SIGABRT = 6; + /// pollable event ([XSR] generated, not supported) pub const SIGPOLL = 7; + /// compatibility pub const SIGIOT = SIGABRT; + /// EMT instruction pub const SIGEMT = 7; + /// floating point exception pub const SIGFPE = 8; + /// kill (cannot be caught or ignored) pub const SIGKILL = 9; + /// bus error pub const SIGBUS = 10; + /// segmentation violation pub const SIGSEGV = 11; + /// bad argument to system call pub const SIGSYS = 12; + /// write on a pipe with no one to read it pub const SIGPIPE = 13; + /// alarm clock pub const SIGALRM = 14; + /// software termination signal from kill pub const SIGTERM = 15; + /// urgent condition on IO channel pub const SIGURG = 16; + /// sendable stop signal not from tty pub const SIGSTOP = 17; + /// stop signal from tty pub const SIGTSTP = 18; + /// continue a stopped process pub const SIGCONT = 19; + /// to parent on child stop or exit pub const SIGCHLD = 20; + /// to readers pgrp upon background tty read pub const SIGTTIN = 21; + /// like TTIN for output if (tp->t_local<OSTOP) pub const SIGTTOU = 22; + /// input/output possible signal pub const SIGIO = 23; + /// exceeded CPU time limit pub const SIGXCPU = 24; + /// exceeded file size limit pub const SIGXFSZ = 25; + /// virtual time alarm pub const SIGVTALRM = 26; + /// profiling time alarm pub const SIGPROF = 27; + /// window size changes pub const SIGWINCH = 28; + /// information request pub const SIGINFO = 29; + /// user defined signal 1 pub const SIGUSR1 = 30; + /// user defined signal 2 pub const SIGUSR2 = 31; diff --git a/std/os/darwin_errno.zig b/std/os/darwin_errno.zig index 6b47e5a9fa..438f3382ad 100644 --- a/std/os/darwin_errno.zig +++ b/std/os/darwin_errno.zig @@ -1,142 +1,328 @@ +/// Operation not permitted +pub const EPERM = 1; -pub const EPERM = 1; /// Operation not permitted -pub const ENOENT = 2; /// No such file or directory -pub const ESRCH = 3; /// No such process -pub const EINTR = 4; /// Interrupted system call -pub const EIO = 5; /// Input/output error -pub const ENXIO = 6; /// Device not configured -pub const E2BIG = 7; /// Argument list too long -pub const ENOEXEC = 8; /// Exec format error -pub const EBADF = 9; /// Bad file descriptor -pub const ECHILD = 10; /// No child processes -pub const EDEADLK = 11; /// Resource deadlock avoided - -pub const ENOMEM = 12; /// Cannot allocate memory -pub const EACCES = 13; /// Permission denied -pub const EFAULT = 14; /// Bad address -pub const ENOTBLK = 15; /// Block device required -pub const EBUSY = 16; /// Device / Resource busy -pub const EEXIST = 17; /// File exists -pub const EXDEV = 18; /// Cross-device link -pub const ENODEV = 19; /// Operation not supported by device -pub const ENOTDIR = 20; /// Not a directory -pub const EISDIR = 21; /// Is a directory -pub const EINVAL = 22; /// Invalid argument -pub const ENFILE = 23; /// Too many open files in system -pub const EMFILE = 24; /// Too many open files -pub const ENOTTY = 25; /// Inappropriate ioctl for device -pub const ETXTBSY = 26; /// Text file busy -pub const EFBIG = 27; /// File too large -pub const ENOSPC = 28; /// No space left on device -pub const ESPIPE = 29; /// Illegal seek -pub const EROFS = 30; /// Read-only file system -pub const EMLINK = 31; /// Too many links -pub const EPIPE = 32; /// Broken pipe +/// No such file or directory +pub const ENOENT = 2; + +/// No such process +pub const ESRCH = 3; + +/// Interrupted system call +pub const EINTR = 4; + +/// Input/output error +pub const EIO = 5; + +/// Device not configured +pub const ENXIO = 6; + +/// Argument list too long +pub const E2BIG = 7; + +/// Exec format error +pub const ENOEXEC = 8; + +/// Bad file descriptor +pub const EBADF = 9; + +/// No child processes +pub const ECHILD = 10; + +/// Resource deadlock avoided +pub const EDEADLK = 11; + +/// Cannot allocate memory +pub const ENOMEM = 12; + +/// Permission denied +pub const EACCES = 13; + +/// Bad address +pub const EFAULT = 14; + +/// Block device required +pub const ENOTBLK = 15; + +/// Device / Resource busy +pub const EBUSY = 16; + +/// File exists +pub const EEXIST = 17; + +/// Cross-device link +pub const EXDEV = 18; + +/// Operation not supported by device +pub const ENODEV = 19; + +/// Not a directory +pub const ENOTDIR = 20; + +/// Is a directory +pub const EISDIR = 21; + +/// Invalid argument +pub const EINVAL = 22; + +/// Too many open files in system +pub const ENFILE = 23; + +/// Too many open files +pub const EMFILE = 24; + +/// Inappropriate ioctl for device +pub const ENOTTY = 25; + +/// Text file busy +pub const ETXTBSY = 26; + +/// File too large +pub const EFBIG = 27; + +/// No space left on device +pub const ENOSPC = 28; + +/// Illegal seek +pub const ESPIPE = 29; + +/// Read-only file system +pub const EROFS = 30; + +/// Too many links +pub const EMLINK = 31; +/// Broken pipe // math software -pub const EDOM = 33; /// Numerical argument out of domain -pub const ERANGE = 34; /// Result too large +pub const EPIPE = 32; + +/// Numerical argument out of domain +pub const EDOM = 33; +/// Result too large // non-blocking and interrupt i/o -pub const EAGAIN = 35; /// Resource temporarily unavailable -pub const EWOULDBLOCK = EAGAIN; /// Operation would block -pub const EINPROGRESS = 36; /// Operation now in progress -pub const EALREADY = 37; /// Operation already in progress +pub const ERANGE = 34; + +/// Resource temporarily unavailable +pub const EAGAIN = 35; + +/// Operation would block +pub const EWOULDBLOCK = EAGAIN; + +/// Operation now in progress +pub const EINPROGRESS = 36; +/// Operation already in progress // ipc/network software -- argument errors -pub const ENOTSOCK = 38; /// Socket operation on non-socket -pub const EDESTADDRREQ = 39; /// Destination address required -pub const EMSGSIZE = 40; /// Message too long -pub const EPROTOTYPE = 41; /// Protocol wrong type for socket -pub const ENOPROTOOPT = 42; /// Protocol not available -pub const EPROTONOSUPPORT = 43; /// Protocol not supported +pub const EALREADY = 37; + +/// Socket operation on non-socket +pub const ENOTSOCK = 38; + +/// Destination address required +pub const EDESTADDRREQ = 39; + +/// Message too long +pub const EMSGSIZE = 40; + +/// Protocol wrong type for socket +pub const EPROTOTYPE = 41; + +/// Protocol not available +pub const ENOPROTOOPT = 42; + +/// Protocol not supported +pub const EPROTONOSUPPORT = 43; + +/// Socket type not supported +pub const ESOCKTNOSUPPORT = 44; -pub const ESOCKTNOSUPPORT = 44; /// Socket type not supported +/// Operation not supported +pub const ENOTSUP = 45; -pub const ENOTSUP = 45; /// Operation not supported +/// Protocol family not supported +pub const EPFNOSUPPORT = 46; -pub const EPFNOSUPPORT = 46; /// Protocol family not supported -pub const EAFNOSUPPORT = 47; /// Address family not supported by protocol family -pub const EADDRINUSE = 48; /// Address already in use -pub const EADDRNOTAVAIL = 49; /// Can't assign requested address +/// Address family not supported by protocol family +pub const EAFNOSUPPORT = 47; + +/// Address already in use +pub const EADDRINUSE = 48; +/// Can't assign requested address // ipc/network software -- operational errors -pub const ENETDOWN = 50; /// Network is down -pub const ENETUNREACH = 51; /// Network is unreachable -pub const ENETRESET = 52; /// Network dropped connection on reset -pub const ECONNABORTED = 53; /// Software caused connection abort -pub const ECONNRESET = 54; /// Connection reset by peer -pub const ENOBUFS = 55; /// No buffer space available -pub const EISCONN = 56; /// Socket is already connected -pub const ENOTCONN = 57; /// Socket is not connected +pub const EADDRNOTAVAIL = 49; + +/// Network is down +pub const ENETDOWN = 50; + +/// Network is unreachable +pub const ENETUNREACH = 51; + +/// Network dropped connection on reset +pub const ENETRESET = 52; + +/// Software caused connection abort +pub const ECONNABORTED = 53; + +/// Connection reset by peer +pub const ECONNRESET = 54; + +/// No buffer space available +pub const ENOBUFS = 55; + +/// Socket is already connected +pub const EISCONN = 56; + +/// Socket is not connected +pub const ENOTCONN = 57; + +/// Can't send after socket shutdown +pub const ESHUTDOWN = 58; -pub const ESHUTDOWN = 58; /// Can't send after socket shutdown -pub const ETOOMANYREFS = 59; /// Too many references: can't splice +/// Too many references: can't splice +pub const ETOOMANYREFS = 59; -pub const ETIMEDOUT = 60; /// Operation timed out -pub const ECONNREFUSED = 61; /// Connection refused +/// Operation timed out +pub const ETIMEDOUT = 60; -pub const ELOOP = 62; /// Too many levels of symbolic links -pub const ENAMETOOLONG = 63; /// File name too long +/// Connection refused +pub const ECONNREFUSED = 61; -pub const EHOSTDOWN = 64; /// Host is down -pub const EHOSTUNREACH = 65; /// No route to host -pub const ENOTEMPTY = 66; /// Directory not empty +/// Too many levels of symbolic links +pub const ELOOP = 62; + +/// File name too long +pub const ENAMETOOLONG = 63; + +/// Host is down +pub const EHOSTDOWN = 64; + +/// No route to host +pub const EHOSTUNREACH = 65; +/// Directory not empty // quotas & mush -pub const EPROCLIM = 67; /// Too many processes -pub const EUSERS = 68; /// Too many users -pub const EDQUOT = 69; /// Disc quota exceeded +pub const ENOTEMPTY = 66; + +/// Too many processes +pub const EPROCLIM = 67; + +/// Too many users +pub const EUSERS = 68; +/// Disc quota exceeded // Network File System -pub const ESTALE = 70; /// Stale NFS file handle -pub const EREMOTE = 71; /// Too many levels of remote in path -pub const EBADRPC = 72; /// RPC struct is bad -pub const ERPCMISMATCH = 73; /// RPC version wrong -pub const EPROGUNAVAIL = 74; /// RPC prog. not avail -pub const EPROGMISMATCH = 75; /// Program version wrong -pub const EPROCUNAVAIL = 76; /// Bad procedure for program +pub const EDQUOT = 69; + +/// Stale NFS file handle +pub const ESTALE = 70; + +/// Too many levels of remote in path +pub const EREMOTE = 71; + +/// RPC struct is bad +pub const EBADRPC = 72; + +/// RPC version wrong +pub const ERPCMISMATCH = 73; + +/// RPC prog. not avail +pub const EPROGUNAVAIL = 74; -pub const ENOLCK = 77; /// No locks available -pub const ENOSYS = 78; /// Function not implemented +/// Program version wrong +pub const EPROGMISMATCH = 75; -pub const EFTYPE = 79; /// Inappropriate file type or format -pub const EAUTH = 80; /// Authentication error -pub const ENEEDAUTH = 81; /// Need authenticator +/// Bad procedure for program +pub const EPROCUNAVAIL = 76; + +/// No locks available +pub const ENOLCK = 77; + +/// Function not implemented +pub const ENOSYS = 78; + +/// Inappropriate file type or format +pub const EFTYPE = 79; + +/// Authentication error +pub const EAUTH = 80; +/// Need authenticator // Intelligent device errors -pub const EPWROFF = 82; /// Device power is off -pub const EDEVERR = 83; /// Device error, e.g. paper out +pub const ENEEDAUTH = 81; + +/// Device power is off +pub const EPWROFF = 82; -pub const EOVERFLOW = 84; /// Value too large to be stored in data type +/// Device error, e.g. paper out +pub const EDEVERR = 83; +/// Value too large to be stored in data type // Program loading errors -pub const EBADEXEC = 85; /// Bad executable -pub const EBADARCH = 86; /// Bad CPU type in executable -pub const ESHLIBVERS = 87; /// Shared library version mismatch -pub const EBADMACHO = 88; /// Malformed Macho file +pub const EOVERFLOW = 84; + +/// Bad executable +pub const EBADEXEC = 85; + +/// Bad CPU type in executable +pub const EBADARCH = 86; + +/// Shared library version mismatch +pub const ESHLIBVERS = 87; + +/// Malformed Macho file +pub const EBADMACHO = 88; + +/// Operation canceled +pub const ECANCELED = 89; + +/// Identifier removed +pub const EIDRM = 90; + +/// No message of desired type +pub const ENOMSG = 91; + +/// Illegal byte sequence +pub const EILSEQ = 92; + +/// Attribute not found +pub const ENOATTR = 93; + +/// Bad message +pub const EBADMSG = 94; + +/// Reserved +pub const EMULTIHOP = 95; + +/// No message available on STREAM +pub const ENODATA = 96; + +/// Reserved +pub const ENOLINK = 97; + +/// No STREAM resources +pub const ENOSR = 98; + +/// Not a STREAM +pub const ENOSTR = 99; -pub const ECANCELED = 89; /// Operation canceled +/// Protocol error +pub const EPROTO = 100; -pub const EIDRM = 90; /// Identifier removed -pub const ENOMSG = 91; /// No message of desired type -pub const EILSEQ = 92; /// Illegal byte sequence -pub const ENOATTR = 93; /// Attribute not found +/// STREAM ioctl timeout +pub const ETIME = 101; -pub const EBADMSG = 94; /// Bad message -pub const EMULTIHOP = 95; /// Reserved -pub const ENODATA = 96; /// No message available on STREAM -pub const ENOLINK = 97; /// Reserved -pub const ENOSR = 98; /// No STREAM resources -pub const ENOSTR = 99; /// Not a STREAM -pub const EPROTO = 100; /// Protocol error -pub const ETIME = 101; /// STREAM ioctl timeout +/// No such policy registered +pub const ENOPOLICY = 103; -pub const ENOPOLICY = 103; /// No such policy registered +/// State not recoverable +pub const ENOTRECOVERABLE = 104; -pub const ENOTRECOVERABLE = 104; /// State not recoverable -pub const EOWNERDEAD = 105; /// Previous owner died +/// Previous owner died +pub const EOWNERDEAD = 105; -pub const EQFULL = 106; /// Interface output queue is full -pub const ELAST = 106; /// Must be equal largest errno +/// Interface output queue is full +pub const EQFULL = 106; +/// Must be equal largest errno +pub const ELAST = 106; diff --git a/std/os/epoch.zig b/std/os/epoch.zig index e1256c1374..fc031521a5 100644 --- a/std/os/epoch.zig +++ b/std/os/epoch.zig @@ -1,26 +1,26 @@ /// Epoch reference times in terms of their difference from /// posix epoch in seconds. -pub const posix = 0; //Jan 01, 1970 AD -pub const dos = 315532800; //Jan 01, 1980 AD -pub const ios = 978307200; //Jan 01, 2001 AD -pub const openvms = -3506716800; //Nov 17, 1858 AD -pub const zos = -2208988800; //Jan 01, 1900 AD -pub const windows = -11644473600; //Jan 01, 1601 AD -pub const amiga = 252460800; //Jan 01, 1978 AD -pub const pickos = -63244800; //Dec 31, 1967 AD -pub const gps = 315964800; //Jan 06, 1980 AD -pub const clr = -62135769600; //Jan 01, 0001 AD +pub const posix = 0; //Jan 01, 1970 AD +pub const dos = 315532800; //Jan 01, 1980 AD +pub const ios = 978307200; //Jan 01, 2001 AD +pub const openvms = -3506716800; //Nov 17, 1858 AD +pub const zos = -2208988800; //Jan 01, 1900 AD +pub const windows = -11644473600; //Jan 01, 1601 AD +pub const amiga = 252460800; //Jan 01, 1978 AD +pub const pickos = -63244800; //Dec 31, 1967 AD +pub const gps = 315964800; //Jan 06, 1980 AD +pub const clr = -62135769600; //Jan 01, 0001 AD -pub const unix = posix; -pub const android = posix; -pub const os2 = dos; -pub const bios = dos; -pub const vfat = dos; -pub const ntfs = windows; -pub const ntp = zos; -pub const jbase = pickos; -pub const aros = amiga; -pub const morphos = amiga; -pub const brew = gps; -pub const atsc = gps; -pub const go = clr; \ No newline at end of file +pub const unix = posix; +pub const android = posix; +pub const os2 = dos; +pub const bios = dos; +pub const vfat = dos; +pub const ntfs = windows; +pub const ntp = zos; +pub const jbase = pickos; +pub const aros = amiga; +pub const morphos = amiga; +pub const brew = gps; +pub const atsc = gps; +pub const go = clr; diff --git a/std/os/file.zig b/std/os/file.zig index 61fc2b1455..c07e2c5c8b 100644 --- a/std/os/file.zig +++ b/std/os/file.zig @@ -21,12 +21,18 @@ pub const File = struct { /// Call close to clean up. pub fn openRead(allocator: &mem.Allocator, path: []const u8) OpenError!File { if (is_posix) { - const flags = posix.O_LARGEFILE|posix.O_RDONLY; + const flags = posix.O_LARGEFILE | posix.O_RDONLY; const fd = try os.posixOpen(allocator, path, flags, 0); return openHandle(fd); } else if (is_windows) { - const handle = try os.windowsOpen(allocator, path, windows.GENERIC_READ, windows.FILE_SHARE_READ, - windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL); + const handle = try os.windowsOpen( + allocator, + path, + windows.GENERIC_READ, + windows.FILE_SHARE_READ, + windows.OPEN_EXISTING, + windows.FILE_ATTRIBUTE_NORMAL, + ); return openHandle(handle); } else { @compileError("TODO implement openRead for this OS"); @@ -36,7 +42,6 @@ pub const File = struct { /// Calls `openWriteMode` with os.default_file_mode for the mode. pub fn openWrite(allocator: &mem.Allocator, path: []const u8) OpenError!File { return openWriteMode(allocator, path, os.default_file_mode); - } /// If the path does not exist it will be created. @@ -45,18 +50,22 @@ pub const File = struct { /// Call close to clean up. pub fn openWriteMode(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File { if (is_posix) { - const flags = posix.O_LARGEFILE|posix.O_WRONLY|posix.O_CREAT|posix.O_CLOEXEC|posix.O_TRUNC; + const flags = posix.O_LARGEFILE | posix.O_WRONLY | posix.O_CREAT | posix.O_CLOEXEC | posix.O_TRUNC; const fd = try os.posixOpen(allocator, path, flags, file_mode); return openHandle(fd); } else if (is_windows) { - const handle = try os.windowsOpen(allocator, path, windows.GENERIC_WRITE, - windows.FILE_SHARE_WRITE|windows.FILE_SHARE_READ|windows.FILE_SHARE_DELETE, - windows.CREATE_ALWAYS, windows.FILE_ATTRIBUTE_NORMAL); + const handle = try os.windowsOpen( + allocator, + path, + windows.GENERIC_WRITE, + windows.FILE_SHARE_WRITE | windows.FILE_SHARE_READ | windows.FILE_SHARE_DELETE, + windows.CREATE_ALWAYS, + windows.FILE_ATTRIBUTE_NORMAL, + ); return openHandle(handle); } else { @compileError("TODO implement openWriteMode for this OS"); } - } /// If the path does not exist it will be created. @@ -65,24 +74,26 @@ pub const File = struct { /// Call close to clean up. pub fn openWriteNoClobber(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File { if (is_posix) { - const flags = posix.O_LARGEFILE|posix.O_WRONLY|posix.O_CREAT|posix.O_CLOEXEC|posix.O_EXCL; + const flags = posix.O_LARGEFILE | posix.O_WRONLY | posix.O_CREAT | posix.O_CLOEXEC | posix.O_EXCL; const fd = try os.posixOpen(allocator, path, flags, file_mode); return openHandle(fd); } else if (is_windows) { - const handle = try os.windowsOpen(allocator, path, windows.GENERIC_WRITE, - windows.FILE_SHARE_WRITE|windows.FILE_SHARE_READ|windows.FILE_SHARE_DELETE, - windows.CREATE_NEW, windows.FILE_ATTRIBUTE_NORMAL); + const handle = try os.windowsOpen( + allocator, + path, + windows.GENERIC_WRITE, + windows.FILE_SHARE_WRITE | windows.FILE_SHARE_READ | windows.FILE_SHARE_DELETE, + windows.CREATE_NEW, + windows.FILE_ATTRIBUTE_NORMAL, + ); return openHandle(handle); } else { @compileError("TODO implement openWriteMode for this OS"); } - } pub fn openHandle(handle: os.FileHandle) File { - return File { - .handle = handle, - }; + return File{ .handle = handle }; } pub fn access(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) !bool { @@ -217,7 +228,7 @@ pub const File = struct { return result; }, Os.windows => { - var pos : windows.LARGE_INTEGER = undefined; + var pos: windows.LARGE_INTEGER = undefined; if (windows.SetFilePointerEx(self.handle, 0, &pos, windows.FILE_CURRENT) == 0) { const err = windows.GetLastError(); return switch (err) { @@ -268,7 +279,7 @@ pub const File = struct { } } - pub const ModeError = error { + pub const ModeError = error{ BadFd, SystemResources, Unexpected, @@ -296,7 +307,7 @@ pub const File = struct { } } - pub const ReadError = error {}; + pub const ReadError = error{}; pub fn read(self: &File, buffer: []u8) !usize { if (is_posix) { @@ -306,12 +317,12 @@ pub const File = struct { const read_err = posix.getErrno(amt_read); if (read_err > 0) { switch (read_err) { - posix.EINTR => continue, + posix.EINTR => continue, posix.EINVAL => unreachable, posix.EFAULT => unreachable, - posix.EBADF => return error.BadFd, - posix.EIO => return error.Io, - else => return os.unexpectedErrorPosix(read_err), + posix.EBADF => return error.BadFd, + posix.EIO => return error.Io, + else => return os.unexpectedErrorPosix(read_err), } } if (amt_read == 0) return index; diff --git a/std/os/get_user_id.zig b/std/os/get_user_id.zig index 11410ffa64..2a15e1d495 100644 --- a/std/os/get_user_id.zig +++ b/std/os/get_user_id.zig @@ -74,7 +74,7 @@ pub fn posixGetUserInfo(name: []const u8) !UserInfo { '\n' => return error.CorruptPasswordFile, else => { const digit = switch (byte) { - '0' ... '9' => byte - '0', + '0'...'9' => byte - '0', else => return error.CorruptPasswordFile, }; if (@mulWithOverflow(u32, uid, 10, &uid)) return error.CorruptPasswordFile; @@ -83,14 +83,14 @@ pub fn posixGetUserInfo(name: []const u8) !UserInfo { }, State.ReadGroupId => switch (byte) { '\n', ':' => { - return UserInfo { + return UserInfo{ .uid = uid, .gid = gid, }; }, else => { const digit = switch (byte) { - '0' ... '9' => byte - '0', + '0'...'9' => byte - '0', else => return error.CorruptPasswordFile, }; if (@mulWithOverflow(u32, gid, 10, &gid)) return error.CorruptPasswordFile; diff --git a/std/os/index.zig b/std/os/index.zig index 01e2092e1c..db182ed669 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -3,8 +3,7 @@ const builtin = @import("builtin"); const Os = builtin.Os; const is_windows = builtin.os == Os.windows; const is_posix = switch (builtin.os) { - builtin.Os.linux, - builtin.Os.macosx => true, + builtin.Os.linux, builtin.Os.macosx => true, else => false, }; const os = this; @@ -27,8 +26,7 @@ pub const linux = @import("linux/index.zig"); pub const zen = @import("zen.zig"); pub const posix = switch (builtin.os) { Os.linux => linux, - Os.macosx, - Os.ios => darwin, + Os.macosx, Os.ios => darwin, Os.zen => zen, else => @compileError("Unsupported OS"), }; @@ -112,8 +110,7 @@ pub fn getRandomBytes(buf: []u8) !void { } return; }, - Os.macosx, - Os.ios => { + Os.macosx, Os.ios => { const fd = try posixOpenC(c"/dev/urandom", posix.O_RDONLY | posix.O_CLOEXEC, 0); defer close(fd); @@ -175,9 +172,7 @@ pub fn abort() noreturn { c.abort(); } switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => { + Os.linux, Os.macosx, Os.ios => { _ = posix.raise(posix.SIGABRT); _ = posix.raise(posix.SIGKILL); while (true) {} @@ -199,9 +194,7 @@ pub fn exit(status: u8) noreturn { c.exit(status); } switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => { + Os.linux, Os.macosx, Os.ios => { posix.exit(status); }, Os.windows => { @@ -250,14 +243,12 @@ pub fn posixRead(fd: i32, buf: []u8) !void { if (err > 0) { return switch (err) { posix.EINTR => continue, - posix.EINVAL, - posix.EFAULT => unreachable, + posix.EINVAL, posix.EFAULT => unreachable, posix.EAGAIN => error.WouldBlock, posix.EBADF => error.FileClosed, posix.EIO => error.InputOutput, posix.EISDIR => error.IsDir, - posix.ENOBUFS, - posix.ENOMEM => error.SystemResources, + posix.ENOBUFS, posix.ENOMEM => error.SystemResources, else => unexpectedErrorPosix(err), }; } @@ -292,8 +283,7 @@ pub fn posixWrite(fd: i32, bytes: []const u8) !void { if (write_err > 0) { return switch (write_err) { posix.EINTR => continue, - posix.EINVAL, - posix.EFAULT => unreachable, + posix.EINVAL, posix.EFAULT => unreachable, posix.EAGAIN => PosixWriteError.WouldBlock, posix.EBADF => PosixWriteError.FileClosed, posix.EDESTADDRREQ => PosixWriteError.DestinationAddressRequired, @@ -349,8 +339,7 @@ pub fn posixOpenC(file_path: &const u8, flags: u32, perm: usize) !i32 { posix.EFAULT => unreachable, posix.EINVAL => unreachable, posix.EACCES => return PosixOpenError.AccessDenied, - posix.EFBIG, - posix.EOVERFLOW => return PosixOpenError.FileTooBig, + posix.EFBIG, posix.EOVERFLOW => return PosixOpenError.FileTooBig, posix.EISDIR => return PosixOpenError.IsDir, posix.ELOOP => return PosixOpenError.SymLinkLoop, posix.EMFILE => return PosixOpenError.ProcessFdQuotaExceeded, @@ -375,8 +364,7 @@ pub fn posixDup2(old_fd: i32, new_fd: i32) !void { const err = posix.getErrno(posix.dup2(old_fd, new_fd)); if (err > 0) { return switch (err) { - posix.EBUSY, - posix.EINTR => continue, + posix.EBUSY, posix.EINTR => continue, posix.EMFILE => error.ProcessFdQuotaExceeded, posix.EINVAL => unreachable, else => unexpectedErrorPosix(err), @@ -493,17 +481,10 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError { assert(err > 0); return switch (err) { posix.EFAULT => unreachable, - posix.E2BIG, - posix.EMFILE, - posix.ENAMETOOLONG, - posix.ENFILE, - posix.ENOMEM => error.SystemResources, - posix.EACCES, - posix.EPERM => error.AccessDenied, - posix.EINVAL, - posix.ENOEXEC => error.InvalidExe, - posix.EIO, - posix.ELOOP => error.FileSystem, + posix.E2BIG, posix.EMFILE, posix.ENAMETOOLONG, posix.ENFILE, posix.ENOMEM => error.SystemResources, + posix.EACCES, posix.EPERM => error.AccessDenied, + posix.EINVAL, posix.ENOEXEC => error.InvalidExe, + posix.EIO, posix.ELOOP => error.FileSystem, posix.EISDIR => error.IsDir, posix.ENOENT => error.FileNotFound, posix.ENOTDIR => error.NotDir, @@ -717,10 +698,8 @@ pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path: const err = posix.getErrno(posix.symlink(existing_buf.ptr, new_buf.ptr)); if (err > 0) { return switch (err) { - posix.EFAULT, - posix.EINVAL => unreachable, - posix.EACCES, - posix.EPERM => error.AccessDenied, + posix.EFAULT, posix.EINVAL => unreachable, + posix.EACCES, posix.EPERM => error.AccessDenied, posix.EDQUOT => error.DiskQuota, posix.EEXIST => error.PathAlreadyExists, posix.EIO => error.FileSystem, @@ -787,8 +766,7 @@ pub fn deleteFileWindows(allocator: &Allocator, file_path: []const u8) !void { return switch (err) { windows.ERROR.FILE_NOT_FOUND => error.FileNotFound, windows.ERROR.ACCESS_DENIED => error.AccessDenied, - windows.ERROR.FILENAME_EXCED_RANGE, - windows.ERROR.INVALID_PARAMETER => error.NameTooLong, + windows.ERROR.FILENAME_EXCED_RANGE, windows.ERROR.INVALID_PARAMETER => error.NameTooLong, else => unexpectedErrorWindows(err), }; } @@ -804,11 +782,9 @@ pub fn deleteFilePosix(allocator: &Allocator, file_path: []const u8) !void { const err = posix.getErrno(posix.unlink(buf.ptr)); if (err > 0) { return switch (err) { - posix.EACCES, - posix.EPERM => error.AccessDenied, + posix.EACCES, posix.EPERM => error.AccessDenied, posix.EBUSY => error.FileBusy, - posix.EFAULT, - posix.EINVAL => unreachable, + posix.EFAULT, posix.EINVAL => unreachable, posix.EIO => error.FileSystem, posix.EISDIR => error.IsDir, posix.ELOOP => error.SymLinkLoop, @@ -948,12 +924,10 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8) const err = posix.getErrno(posix.rename(old_buf.ptr, new_buf.ptr)); if (err > 0) { return switch (err) { - posix.EACCES, - posix.EPERM => error.AccessDenied, + posix.EACCES, posix.EPERM => error.AccessDenied, posix.EBUSY => error.FileBusy, posix.EDQUOT => error.DiskQuota, - posix.EFAULT, - posix.EINVAL => unreachable, + posix.EFAULT, posix.EINVAL => unreachable, posix.EISDIR => error.IsDir, posix.ELOOP => error.SymLinkLoop, posix.EMLINK => error.LinkQuotaExceeded, @@ -962,8 +936,7 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8) posix.ENOTDIR => error.NotDir, posix.ENOMEM => error.SystemResources, posix.ENOSPC => error.NoSpaceLeft, - posix.EEXIST, - posix.ENOTEMPTY => error.PathAlreadyExists, + posix.EEXIST, posix.ENOTEMPTY => error.PathAlreadyExists, posix.EROFS => error.ReadOnlyFileSystem, posix.EXDEV => error.RenameAcrossMountPoints, else => unexpectedErrorPosix(err), @@ -1001,8 +974,7 @@ pub fn makeDirPosix(allocator: &Allocator, dir_path: []const u8) !void { const err = posix.getErrno(posix.mkdir(path_buf.ptr, 0o755)); if (err > 0) { return switch (err) { - posix.EACCES, - posix.EPERM => error.AccessDenied, + posix.EACCES, posix.EPERM => error.AccessDenied, posix.EDQUOT => error.DiskQuota, posix.EEXIST => error.PathAlreadyExists, posix.EFAULT => unreachable, @@ -1065,18 +1037,15 @@ pub fn deleteDir(allocator: &Allocator, dir_path: []const u8) !void { const err = posix.getErrno(posix.rmdir(path_buf.ptr)); if (err > 0) { return switch (err) { - posix.EACCES, - posix.EPERM => error.AccessDenied, + posix.EACCES, posix.EPERM => error.AccessDenied, posix.EBUSY => error.FileBusy, - posix.EFAULT, - posix.EINVAL => unreachable, + posix.EFAULT, posix.EINVAL => unreachable, posix.ELOOP => error.SymLinkLoop, posix.ENAMETOOLONG => error.NameTooLong, posix.ENOENT => error.FileNotFound, posix.ENOMEM => error.SystemResources, posix.ENOTDIR => error.NotDir, - posix.EEXIST, - posix.ENOTEMPTY => error.DirNotEmpty, + posix.EEXIST, posix.ENOTEMPTY => error.DirNotEmpty, posix.EROFS => error.ReadOnlyFileSystem, else => unexpectedErrorPosix(err), }; @@ -1128,7 +1097,8 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError! error.NotDir, error.FileSystem, error.FileBusy, - error.Unexpected => return err, + error.Unexpected, + => return err, } { var dir = Dir.open(allocator, full_path) catch |err| switch (err) { @@ -1152,7 +1122,8 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError! error.SystemResources, error.NoSpaceLeft, error.PathAlreadyExists, - error.Unexpected => return err, + error.Unexpected, + => return err, }; defer dir.close(); @@ -1182,8 +1153,7 @@ pub const Dir = struct { end_index: usize, const darwin_seek_t = switch (builtin.os) { - Os.macosx, - Os.ios => i64, + Os.macosx, Os.ios => i64, else => void, }; @@ -1208,13 +1178,16 @@ pub const Dir = struct { const fd = switch (builtin.os) { Os.windows => @compileError("TODO support Dir.open for windows"), Os.linux => try posixOpen(allocator, dir_path, posix.O_RDONLY | posix.O_DIRECTORY | posix.O_CLOEXEC, 0), - Os.macosx, - Os.ios => try posixOpen(allocator, dir_path, posix.O_RDONLY | posix.O_NONBLOCK | posix.O_DIRECTORY | posix.O_CLOEXEC, 0), + Os.macosx, Os.ios => try posixOpen( + allocator, + dir_path, + posix.O_RDONLY | posix.O_NONBLOCK | posix.O_DIRECTORY | posix.O_CLOEXEC, + 0, + ), else => @compileError("Dir.open is not supported for this platform"), }; const darwin_seek_init = switch (builtin.os) { - Os.macosx, - Os.ios => 0, + Os.macosx, Os.ios => 0, else => {}, }; return Dir{ @@ -1237,8 +1210,7 @@ pub const Dir = struct { pub fn next(self: &Dir) !?Entry { switch (builtin.os) { Os.linux => return self.nextLinux(), - Os.macosx, - Os.ios => return self.nextDarwin(), + Os.macosx, Os.ios => return self.nextDarwin(), Os.windows => return self.nextWindows(), else => @compileError("Dir.next not supported on " ++ @tagName(builtin.os)), } @@ -1256,9 +1228,7 @@ pub const Dir = struct { const err = posix.getErrno(result); if (err > 0) { switch (err) { - posix.EBADF, - posix.EFAULT, - posix.ENOTDIR => unreachable, + posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable, posix.EINVAL => { self.buf = try self.allocator.realloc(u8, self.buf, self.buf.len * 2); continue; @@ -1317,9 +1287,7 @@ pub const Dir = struct { const err = posix.getErrno(result); if (err > 0) { switch (err) { - posix.EBADF, - posix.EFAULT, - posix.ENOTDIR => unreachable, + posix.EBADF, posix.EFAULT, posix.ENOTDIR => unreachable, posix.EINVAL => { self.buf = try self.allocator.realloc(u8, self.buf, self.buf.len * 2); continue; @@ -1402,8 +1370,7 @@ pub fn readLink(allocator: &Allocator, pathname: []const u8) ![]u8 { if (err > 0) { return switch (err) { posix.EACCES => error.AccessDenied, - posix.EFAULT, - posix.EINVAL => unreachable, + posix.EFAULT, posix.EINVAL => unreachable, posix.EIO => error.FileSystem, posix.ELOOP => error.SymLinkLoop, posix.ENAMETOOLONG => error.NameTooLong, @@ -1545,8 +1512,7 @@ pub const ArgIteratorWindows = struct { const byte = self.cmd_line[self.index]; switch (byte) { 0 => return null, - ' ', - '\t' => continue, + ' ', '\t' => continue, else => break, } } @@ -1560,8 +1526,7 @@ pub const ArgIteratorWindows = struct { const byte = self.cmd_line[self.index]; switch (byte) { 0 => return false, - ' ', - '\t' => continue, + ' ', '\t' => continue, else => break, } } @@ -1580,8 +1545,7 @@ pub const ArgIteratorWindows = struct { '\\' => { backslash_count += 1; }, - ' ', - '\t' => { + ' ', '\t' => { if (self.seen_quote_count % 2 == 0 or self.seen_quote_count == self.quote_count) { return true; } @@ -1621,8 +1585,7 @@ pub const ArgIteratorWindows = struct { '\\' => { backslash_count += 1; }, - ' ', - '\t' => { + ' ', '\t' => { try self.emitBackslashes(&buf, backslash_count); backslash_count = 0; if (self.seen_quote_count % 2 == 1 and self.seen_quote_count != self.quote_count) { @@ -1840,8 +1803,7 @@ pub fn openSelfExe() !os.File { var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]); return os.File.openRead(&fixed_allocator.allocator, proc_file_path); }, - Os.macosx, - Os.ios => { + Os.macosx, Os.ios => { var fixed_buffer_mem: [darwin.PATH_MAX * 2]u8 = undefined; var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]); const self_exe_path = try selfExePath(&fixed_allocator.allocator); @@ -1853,9 +1815,7 @@ pub fn openSelfExe() !os.File { test "openSelfExe" { switch (builtin.os) { - Os.linux, - Os.macosx, - Os.ios => (try openSelfExe()).close(), + Os.linux, Os.macosx, Os.ios => (try openSelfExe()).close(), else => return, // Unsupported OS. } } @@ -1893,8 +1853,7 @@ pub fn selfExePath(allocator: &mem.Allocator) ![]u8 { try out_path.resize(new_len); } }, - Os.macosx, - Os.ios => { + Os.macosx, Os.ios => { var u32_len: u32 = 0; const ret1 = c._NSGetExecutablePath(undefined, &u32_len); assert(ret1 != 0); @@ -1922,9 +1881,7 @@ pub fn selfExeDirPath(allocator: &mem.Allocator) ![]u8 { const dir = path.dirname(full_exe_path); return allocator.shrink(u8, full_exe_path, dir.len); }, - Os.windows, - Os.macosx, - Os.ios => { + Os.windows, Os.macosx, Os.ios => { const self_exe_path = try selfExePath(allocator); errdefer allocator.free(self_exe_path); const dirname = os.path.dirname(self_exe_path); @@ -1981,8 +1938,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 { posix.EINVAL => return PosixSocketError.ProtocolFamilyNotAvailable, posix.EMFILE => return PosixSocketError.ProcessFdQuotaExceeded, posix.ENFILE => return PosixSocketError.SystemFdQuotaExceeded, - posix.ENOBUFS, - posix.ENOMEM => return PosixSocketError.SystemResources, + posix.ENOBUFS, posix.ENOMEM => return PosixSocketError.SystemResources, posix.EPROTONOSUPPORT => return PosixSocketError.ProtocolNotSupported, else => return unexpectedErrorPosix(err), } @@ -1990,7 +1946,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 { pub const PosixBindError = error{ /// The address is protected, and the user is not the superuser. - /// For UNIX domain sockets: Search permission is denied on a component + /// For UNIX domain sockets: Search permission is denied on a component /// of the path prefix. AccessDenied, @@ -2151,8 +2107,7 @@ pub fn posixAccept(fd: i32, addr: &posix.sockaddr, flags: u32) PosixAcceptError! posix.EINVAL => return PosixAcceptError.InvalidSyscall, posix.EMFILE => return PosixAcceptError.ProcessFdQuotaExceeded, posix.ENFILE => return PosixAcceptError.SystemFdQuotaExceeded, - posix.ENOBUFS, - posix.ENOMEM => return PosixAcceptError.SystemResources, + posix.ENOBUFS, posix.ENOMEM => return PosixAcceptError.SystemResources, posix.ENOTSOCK => return PosixAcceptError.FileDescriptorNotASocket, posix.EOPNOTSUPP => return PosixAcceptError.OperationNotSupported, posix.EPROTO => return PosixAcceptError.ProtocolFailure, @@ -2363,8 +2318,7 @@ pub fn posixConnectAsync(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConn const rc = posix.connect(sockfd, sockaddr, @sizeOf(posix.sockaddr)); const err = posix.getErrno(rc); switch (err) { - 0, - posix.EINPROGRESS => return, + 0, posix.EINPROGRESS => return, else => return unexpectedErrorPosix(err), posix.EACCES => return PosixConnectError.PermissionDenied, @@ -2416,7 +2370,7 @@ pub fn posixGetSockOptConnectError(sockfd: i32) PosixConnectError!void { }, else => return unexpectedErrorPosix(err), posix.EBADF => unreachable, // The argument sockfd is not a valid file descriptor. - posix.EFAULT => unreachable, // The address pointed to by optval or optlen is not in a valid part of the process address space. + posix.EFAULT => unreachable, // The address pointed to by optval or optlen is not in a valid part of the process address space. posix.EINVAL => unreachable, posix.ENOPROTOOPT => unreachable, // The option is unknown at the level indicated. posix.ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket. @@ -2427,11 +2381,13 @@ pub const Thread = struct { data: Data, pub const use_pthreads = is_posix and builtin.link_libc; - const Data = if (use_pthreads) struct { - handle: c.pthread_t, - stack_addr: usize, - stack_len: usize, - } else switch (builtin.os) { + const Data = if (use_pthreads) + struct { + handle: c.pthread_t, + stack_addr: usize, + stack_len: usize, + } + else switch (builtin.os) { builtin.Os.linux => struct { pid: i32, stack_addr: usize, diff --git a/std/os/linux/errno.zig b/std/os/linux/errno.zig index 39f4e37a10..5ad8777f92 100644 --- a/std/os/linux/errno.zig +++ b/std/os/linux/errno.zig @@ -1,146 +1,427 @@ -pub const EPERM = 1; /// Operation not permitted -pub const ENOENT = 2; /// No such file or directory -pub const ESRCH = 3; /// No such process -pub const EINTR = 4; /// Interrupted system call -pub const EIO = 5; /// I/O error -pub const ENXIO = 6; /// No such device or address -pub const E2BIG = 7; /// Arg list too long -pub const ENOEXEC = 8; /// Exec format error -pub const EBADF = 9; /// Bad file number -pub const ECHILD = 10; /// No child processes -pub const EAGAIN = 11; /// Try again -pub const ENOMEM = 12; /// Out of memory -pub const EACCES = 13; /// Permission denied -pub const EFAULT = 14; /// Bad address -pub const ENOTBLK = 15; /// Block device required -pub const EBUSY = 16; /// Device or resource busy -pub const EEXIST = 17; /// File exists -pub const EXDEV = 18; /// Cross-device link -pub const ENODEV = 19; /// No such device -pub const ENOTDIR = 20; /// Not a directory -pub const EISDIR = 21; /// Is a directory -pub const EINVAL = 22; /// Invalid argument -pub const ENFILE = 23; /// File table overflow -pub const EMFILE = 24; /// Too many open files -pub const ENOTTY = 25; /// Not a typewriter -pub const ETXTBSY = 26; /// Text file busy -pub const EFBIG = 27; /// File too large -pub const ENOSPC = 28; /// No space left on device -pub const ESPIPE = 29; /// Illegal seek -pub const EROFS = 30; /// Read-only file system -pub const EMLINK = 31; /// Too many links -pub const EPIPE = 32; /// Broken pipe -pub const EDOM = 33; /// Math argument out of domain of func -pub const ERANGE = 34; /// Math result not representable -pub const EDEADLK = 35; /// Resource deadlock would occur -pub const ENAMETOOLONG = 36; /// File name too long -pub const ENOLCK = 37; /// No record locks available -pub const ENOSYS = 38; /// Function not implemented -pub const ENOTEMPTY = 39; /// Directory not empty -pub const ELOOP = 40; /// Too many symbolic links encountered -pub const EWOULDBLOCK = EAGAIN; /// Operation would block -pub const ENOMSG = 42; /// No message of desired type -pub const EIDRM = 43; /// Identifier removed -pub const ECHRNG = 44; /// Channel number out of range -pub const EL2NSYNC = 45; /// Level 2 not synchronized -pub const EL3HLT = 46; /// Level 3 halted -pub const EL3RST = 47; /// Level 3 reset -pub const ELNRNG = 48; /// Link number out of range -pub const EUNATCH = 49; /// Protocol driver not attached -pub const ENOCSI = 50; /// No CSI structure available -pub const EL2HLT = 51; /// Level 2 halted -pub const EBADE = 52; /// Invalid exchange -pub const EBADR = 53; /// Invalid request descriptor -pub const EXFULL = 54; /// Exchange full -pub const ENOANO = 55; /// No anode -pub const EBADRQC = 56; /// Invalid request code -pub const EBADSLT = 57; /// Invalid slot - -pub const EBFONT = 59; /// Bad font file format -pub const ENOSTR = 60; /// Device not a stream -pub const ENODATA = 61; /// No data available -pub const ETIME = 62; /// Timer expired -pub const ENOSR = 63; /// Out of streams resources -pub const ENONET = 64; /// Machine is not on the network -pub const ENOPKG = 65; /// Package not installed -pub const EREMOTE = 66; /// Object is remote -pub const ENOLINK = 67; /// Link has been severed -pub const EADV = 68; /// Advertise error -pub const ESRMNT = 69; /// Srmount error -pub const ECOMM = 70; /// Communication error on send -pub const EPROTO = 71; /// Protocol error -pub const EMULTIHOP = 72; /// Multihop attempted -pub const EDOTDOT = 73; /// RFS specific error -pub const EBADMSG = 74; /// Not a data message -pub const EOVERFLOW = 75; /// Value too large for defined data type -pub const ENOTUNIQ = 76; /// Name not unique on network -pub const EBADFD = 77; /// File descriptor in bad state -pub const EREMCHG = 78; /// Remote address changed -pub const ELIBACC = 79; /// Can not access a needed shared library -pub const ELIBBAD = 80; /// Accessing a corrupted shared library -pub const ELIBSCN = 81; /// .lib section in a.out corrupted -pub const ELIBMAX = 82; /// Attempting to link in too many shared libraries -pub const ELIBEXEC = 83; /// Cannot exec a shared library directly -pub const EILSEQ = 84; /// Illegal byte sequence -pub const ERESTART = 85; /// Interrupted system call should be restarted -pub const ESTRPIPE = 86; /// Streams pipe error -pub const EUSERS = 87; /// Too many users -pub const ENOTSOCK = 88; /// Socket operation on non-socket -pub const EDESTADDRREQ = 89; /// Destination address required -pub const EMSGSIZE = 90; /// Message too long -pub const EPROTOTYPE = 91; /// Protocol wrong type for socket -pub const ENOPROTOOPT = 92; /// Protocol not available -pub const EPROTONOSUPPORT = 93; /// Protocol not supported -pub const ESOCKTNOSUPPORT = 94; /// Socket type not supported -pub const EOPNOTSUPP = 95; /// Operation not supported on transport endpoint -pub const EPFNOSUPPORT = 96; /// Protocol family not supported -pub const EAFNOSUPPORT = 97; /// Address family not supported by protocol -pub const EADDRINUSE = 98; /// Address already in use -pub const EADDRNOTAVAIL = 99; /// Cannot assign requested address -pub const ENETDOWN = 100; /// Network is down -pub const ENETUNREACH = 101; /// Network is unreachable -pub const ENETRESET = 102; /// Network dropped connection because of reset -pub const ECONNABORTED = 103; /// Software caused connection abort -pub const ECONNRESET = 104; /// Connection reset by peer -pub const ENOBUFS = 105; /// No buffer space available -pub const EISCONN = 106; /// Transport endpoint is already connected -pub const ENOTCONN = 107; /// Transport endpoint is not connected -pub const ESHUTDOWN = 108; /// Cannot send after transport endpoint shutdown -pub const ETOOMANYREFS = 109; /// Too many references: cannot splice -pub const ETIMEDOUT = 110; /// Connection timed out -pub const ECONNREFUSED = 111; /// Connection refused -pub const EHOSTDOWN = 112; /// Host is down -pub const EHOSTUNREACH = 113; /// No route to host -pub const EALREADY = 114; /// Operation already in progress -pub const EINPROGRESS = 115; /// Operation now in progress -pub const ESTALE = 116; /// Stale NFS file handle -pub const EUCLEAN = 117; /// Structure needs cleaning -pub const ENOTNAM = 118; /// Not a XENIX named type file -pub const ENAVAIL = 119; /// No XENIX semaphores available -pub const EISNAM = 120; /// Is a named type file -pub const EREMOTEIO = 121; /// Remote I/O error -pub const EDQUOT = 122; /// Quota exceeded - -pub const ENOMEDIUM = 123; /// No medium found -pub const EMEDIUMTYPE = 124; /// Wrong medium type +/// Operation not permitted +pub const EPERM = 1; + +/// No such file or directory +pub const ENOENT = 2; + +/// No such process +pub const ESRCH = 3; + +/// Interrupted system call +pub const EINTR = 4; + +/// I/O error +pub const EIO = 5; + +/// No such device or address +pub const ENXIO = 6; + +/// Arg list too long +pub const E2BIG = 7; + +/// Exec format error +pub const ENOEXEC = 8; + +/// Bad file number +pub const EBADF = 9; + +/// No child processes +pub const ECHILD = 10; + +/// Try again +pub const EAGAIN = 11; + +/// Out of memory +pub const ENOMEM = 12; + +/// Permission denied +pub const EACCES = 13; + +/// Bad address +pub const EFAULT = 14; + +/// Block device required +pub const ENOTBLK = 15; + +/// Device or resource busy +pub const EBUSY = 16; + +/// File exists +pub const EEXIST = 17; + +/// Cross-device link +pub const EXDEV = 18; + +/// No such device +pub const ENODEV = 19; + +/// Not a directory +pub const ENOTDIR = 20; + +/// Is a directory +pub const EISDIR = 21; + +/// Invalid argument +pub const EINVAL = 22; + +/// File table overflow +pub const ENFILE = 23; + +/// Too many open files +pub const EMFILE = 24; + +/// Not a typewriter +pub const ENOTTY = 25; + +/// Text file busy +pub const ETXTBSY = 26; + +/// File too large +pub const EFBIG = 27; + +/// No space left on device +pub const ENOSPC = 28; + +/// Illegal seek +pub const ESPIPE = 29; + +/// Read-only file system +pub const EROFS = 30; + +/// Too many links +pub const EMLINK = 31; + +/// Broken pipe +pub const EPIPE = 32; + +/// Math argument out of domain of func +pub const EDOM = 33; + +/// Math result not representable +pub const ERANGE = 34; + +/// Resource deadlock would occur +pub const EDEADLK = 35; + +/// File name too long +pub const ENAMETOOLONG = 36; + +/// No record locks available +pub const ENOLCK = 37; + +/// Function not implemented +pub const ENOSYS = 38; + +/// Directory not empty +pub const ENOTEMPTY = 39; + +/// Too many symbolic links encountered +pub const ELOOP = 40; + +/// Operation would block +pub const EWOULDBLOCK = EAGAIN; + +/// No message of desired type +pub const ENOMSG = 42; + +/// Identifier removed +pub const EIDRM = 43; + +/// Channel number out of range +pub const ECHRNG = 44; + +/// Level 2 not synchronized +pub const EL2NSYNC = 45; + +/// Level 3 halted +pub const EL3HLT = 46; + +/// Level 3 reset +pub const EL3RST = 47; + +/// Link number out of range +pub const ELNRNG = 48; + +/// Protocol driver not attached +pub const EUNATCH = 49; + +/// No CSI structure available +pub const ENOCSI = 50; + +/// Level 2 halted +pub const EL2HLT = 51; + +/// Invalid exchange +pub const EBADE = 52; + +/// Invalid request descriptor +pub const EBADR = 53; + +/// Exchange full +pub const EXFULL = 54; + +/// No anode +pub const ENOANO = 55; + +/// Invalid request code +pub const EBADRQC = 56; + +/// Invalid slot +pub const EBADSLT = 57; + +/// Bad font file format +pub const EBFONT = 59; + +/// Device not a stream +pub const ENOSTR = 60; + +/// No data available +pub const ENODATA = 61; + +/// Timer expired +pub const ETIME = 62; + +/// Out of streams resources +pub const ENOSR = 63; + +/// Machine is not on the network +pub const ENONET = 64; + +/// Package not installed +pub const ENOPKG = 65; + +/// Object is remote +pub const EREMOTE = 66; + +/// Link has been severed +pub const ENOLINK = 67; + +/// Advertise error +pub const EADV = 68; + +/// Srmount error +pub const ESRMNT = 69; + +/// Communication error on send +pub const ECOMM = 70; + +/// Protocol error +pub const EPROTO = 71; + +/// Multihop attempted +pub const EMULTIHOP = 72; + +/// RFS specific error +pub const EDOTDOT = 73; + +/// Not a data message +pub const EBADMSG = 74; + +/// Value too large for defined data type +pub const EOVERFLOW = 75; + +/// Name not unique on network +pub const ENOTUNIQ = 76; + +/// File descriptor in bad state +pub const EBADFD = 77; + +/// Remote address changed +pub const EREMCHG = 78; + +/// Can not access a needed shared library +pub const ELIBACC = 79; + +/// Accessing a corrupted shared library +pub const ELIBBAD = 80; + +/// .lib section in a.out corrupted +pub const ELIBSCN = 81; + +/// Attempting to link in too many shared libraries +pub const ELIBMAX = 82; + +/// Cannot exec a shared library directly +pub const ELIBEXEC = 83; + +/// Illegal byte sequence +pub const EILSEQ = 84; + +/// Interrupted system call should be restarted +pub const ERESTART = 85; + +/// Streams pipe error +pub const ESTRPIPE = 86; + +/// Too many users +pub const EUSERS = 87; + +/// Socket operation on non-socket +pub const ENOTSOCK = 88; + +/// Destination address required +pub const EDESTADDRREQ = 89; + +/// Message too long +pub const EMSGSIZE = 90; + +/// Protocol wrong type for socket +pub const EPROTOTYPE = 91; + +/// Protocol not available +pub const ENOPROTOOPT = 92; + +/// Protocol not supported +pub const EPROTONOSUPPORT = 93; + +/// Socket type not supported +pub const ESOCKTNOSUPPORT = 94; + +/// Operation not supported on transport endpoint +pub const EOPNOTSUPP = 95; + +/// Protocol family not supported +pub const EPFNOSUPPORT = 96; + +/// Address family not supported by protocol +pub const EAFNOSUPPORT = 97; + +/// Address already in use +pub const EADDRINUSE = 98; + +/// Cannot assign requested address +pub const EADDRNOTAVAIL = 99; + +/// Network is down +pub const ENETDOWN = 100; + +/// Network is unreachable +pub const ENETUNREACH = 101; + +/// Network dropped connection because of reset +pub const ENETRESET = 102; + +/// Software caused connection abort +pub const ECONNABORTED = 103; + +/// Connection reset by peer +pub const ECONNRESET = 104; + +/// No buffer space available +pub const ENOBUFS = 105; + +/// Transport endpoint is already connected +pub const EISCONN = 106; + +/// Transport endpoint is not connected +pub const ENOTCONN = 107; + +/// Cannot send after transport endpoint shutdown +pub const ESHUTDOWN = 108; + +/// Too many references: cannot splice +pub const ETOOMANYREFS = 109; + +/// Connection timed out +pub const ETIMEDOUT = 110; + +/// Connection refused +pub const ECONNREFUSED = 111; + +/// Host is down +pub const EHOSTDOWN = 112; + +/// No route to host +pub const EHOSTUNREACH = 113; + +/// Operation already in progress +pub const EALREADY = 114; + +/// Operation now in progress +pub const EINPROGRESS = 115; + +/// Stale NFS file handle +pub const ESTALE = 116; + +/// Structure needs cleaning +pub const EUCLEAN = 117; + +/// Not a XENIX named type file +pub const ENOTNAM = 118; + +/// No XENIX semaphores available +pub const ENAVAIL = 119; + +/// Is a named type file +pub const EISNAM = 120; + +/// Remote I/O error +pub const EREMOTEIO = 121; + +/// Quota exceeded +pub const EDQUOT = 122; + +/// No medium found +pub const ENOMEDIUM = 123; + +/// Wrong medium type +pub const EMEDIUMTYPE = 124; // nameserver query return codes -pub const ENSROK = 0; /// DNS server returned answer with no data -pub const ENSRNODATA = 160; /// DNS server returned answer with no data -pub const ENSRFORMERR = 161; /// DNS server claims query was misformatted -pub const ENSRSERVFAIL = 162; /// DNS server returned general failure -pub const ENSRNOTFOUND = 163; /// Domain name not found -pub const ENSRNOTIMP = 164; /// DNS server does not implement requested operation -pub const ENSRREFUSED = 165; /// DNS server refused query -pub const ENSRBADQUERY = 166; /// Misformatted DNS query -pub const ENSRBADNAME = 167; /// Misformatted domain name -pub const ENSRBADFAMILY = 168; /// Unsupported address family -pub const ENSRBADRESP = 169; /// Misformatted DNS reply -pub const ENSRCONNREFUSED = 170; /// Could not contact DNS servers -pub const ENSRTIMEOUT = 171; /// Timeout while contacting DNS servers -pub const ENSROF = 172; /// End of file -pub const ENSRFILE = 173; /// Error reading file -pub const ENSRNOMEM = 174; /// Out of memory -pub const ENSRDESTRUCTION = 175; /// Application terminated lookup -pub const ENSRQUERYDOMAINTOOLONG = 176; /// Domain name is too long -pub const ENSRCNAMELOOP = 177; /// Domain name is too long + +/// DNS server returned answer with no data +pub const ENSROK = 0; + +/// DNS server returned answer with no data +pub const ENSRNODATA = 160; + +/// DNS server claims query was misformatted +pub const ENSRFORMERR = 161; + +/// DNS server returned general failure +pub const ENSRSERVFAIL = 162; + +/// Domain name not found +pub const ENSRNOTFOUND = 163; + +/// DNS server does not implement requested operation +pub const ENSRNOTIMP = 164; + +/// DNS server refused query +pub const ENSRREFUSED = 165; + +/// Misformatted DNS query +pub const ENSRBADQUERY = 166; + +/// Misformatted domain name +pub const ENSRBADNAME = 167; + +/// Unsupported address family +pub const ENSRBADFAMILY = 168; + +/// Misformatted DNS reply +pub const ENSRBADRESP = 169; + +/// Could not contact DNS servers +pub const ENSRCONNREFUSED = 170; + +/// Timeout while contacting DNS servers +pub const ENSRTIMEOUT = 171; + +/// End of file +pub const ENSROF = 172; + +/// Error reading file +pub const ENSRFILE = 173; + +/// Out of memory +pub const ENSRNOMEM = 174; + +/// Application terminated lookup +pub const ENSRDESTRUCTION = 175; + +/// Domain name is too long +pub const ENSRQUERYDOMAINTOOLONG = 176; + +/// Domain name is too long +pub const ENSRCNAMELOOP = 177; diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 4e0e9ee5d5..1cf5bbd432 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -823,8 +823,7 @@ pub fn clock_gettime(clk_id: i32, tp: ×pec) usize { if (@ptrToInt(f) != 0) { const rc = f(clk_id, tp); switch (rc) { - 0, - @bitCast(usize, isize(-EINVAL)) => return rc, + 0, @bitCast(usize, isize(-EINVAL)) => return rc, else => {}, } } diff --git a/std/os/linux/test.zig b/std/os/linux/test.zig index 18a6e5f19f..06aae1968f 100644 --- a/std/os/linux/test.zig +++ b/std/os/linux/test.zig @@ -11,22 +11,22 @@ test "timer" { const timer_fd = linux.timerfd_create(linux.CLOCK_MONOTONIC, 0); assert(linux.getErrno(timer_fd) == 0); - const time_interval = linux.timespec { + const time_interval = linux.timespec{ .tv_sec = 0, - .tv_nsec = 2000000 + .tv_nsec = 2000000, }; - const new_time = linux.itimerspec { + const new_time = linux.itimerspec{ .it_interval = time_interval, - .it_value = time_interval + .it_value = time_interval, }; err = linux.timerfd_settime(i32(timer_fd), 0, &new_time, null); assert(err == 0); - var event = linux.epoll_event { + var event = linux.epoll_event{ .events = linux.EPOLLIN | linux.EPOLLOUT | linux.EPOLLET, - .data = linux.epoll_data { .ptr = 0 }, + .data = linux.epoll_data{ .ptr = 0 }, }; err = linux.epoll_ctl(i32(epoll_fd), linux.EPOLL_CTL_ADD, i32(timer_fd), &event); diff --git a/std/os/linux/vdso.zig b/std/os/linux/vdso.zig index f4fb513af9..8e0a285841 100644 --- a/std/os/linux/vdso.zig +++ b/std/os/linux/vdso.zig @@ -16,7 +16,10 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { var base: usize = @maxValue(usize); { var i: usize = 0; - while (i < eh.e_phnum) : ({i += 1; ph_addr += eh.e_phentsize;}) { + while (i < eh.e_phnum) : ({ + i += 1; + ph_addr += eh.e_phentsize; + }) { const this_ph = @intToPtr(&elf.Phdr, ph_addr); switch (this_ph.p_type) { elf.PT_LOAD => base = vdso_addr + this_ph.p_offset - this_ph.p_vaddr, @@ -54,15 +57,14 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { const hashtab = maybe_hashtab ?? return 0; if (maybe_verdef == null) maybe_versym = null; - - const OK_TYPES = (1<>4) & OK_BINDS)) continue; - if (0==syms[i].st_shndx) continue; + if (0 == (u32(1) << u5(syms[i].st_info & 0xf) & OK_TYPES)) continue; + if (0 == (u32(1) << u5(syms[i].st_info >> 4) & OK_BINDS)) continue; + if (0 == syms[i].st_shndx) continue; if (!mem.eql(u8, name, cstr.toSliceConst(&strings[syms[i].st_name]))) continue; if (maybe_versym) |versym| { if (!checkver(??maybe_verdef, versym[i], vername, strings)) @@ -78,12 +80,12 @@ fn checkver(def_arg: &elf.Verdef, vsym_arg: i32, vername: []const u8, strings: & var def = def_arg; const vsym = @bitCast(u32, vsym_arg) & 0x7fff; while (true) { - if (0==(def.vd_flags & elf.VER_FLG_BASE) and (def.vd_ndx & 0x7fff) == vsym) + if (0 == (def.vd_flags & elf.VER_FLG_BASE) and (def.vd_ndx & 0x7fff) == vsym) break; if (def.vd_next == 0) return false; def = @intToPtr(&elf.Verdef, @ptrToInt(def) + def.vd_next); } - const aux = @intToPtr(&elf.Verdaux, @ptrToInt(def ) + def.vd_aux); + const aux = @intToPtr(&elf.Verdaux, @ptrToInt(def) + def.vd_aux); return mem.eql(u8, vername, cstr.toSliceConst(&strings[aux.vda_name])); } diff --git a/std/os/linux/x86_64.zig b/std/os/linux/x86_64.zig index 544b2365ce..ed32d59688 100644 --- a/std/os/linux/x86_64.zig +++ b/std/os/linux/x86_64.zig @@ -330,26 +330,26 @@ pub const SYS_userfaultfd = 323; pub const SYS_membarrier = 324; pub const SYS_mlock2 = 325; -pub const O_CREAT = 0o100; -pub const O_EXCL = 0o200; -pub const O_NOCTTY = 0o400; -pub const O_TRUNC = 0o1000; -pub const O_APPEND = 0o2000; -pub const O_NONBLOCK = 0o4000; -pub const O_DSYNC = 0o10000; -pub const O_SYNC = 0o4010000; -pub const O_RSYNC = 0o4010000; +pub const O_CREAT = 0o100; +pub const O_EXCL = 0o200; +pub const O_NOCTTY = 0o400; +pub const O_TRUNC = 0o1000; +pub const O_APPEND = 0o2000; +pub const O_NONBLOCK = 0o4000; +pub const O_DSYNC = 0o10000; +pub const O_SYNC = 0o4010000; +pub const O_RSYNC = 0o4010000; pub const O_DIRECTORY = 0o200000; -pub const O_NOFOLLOW = 0o400000; -pub const O_CLOEXEC = 0o2000000; +pub const O_NOFOLLOW = 0o400000; +pub const O_CLOEXEC = 0o2000000; -pub const O_ASYNC = 0o20000; -pub const O_DIRECT = 0o40000; -pub const O_LARGEFILE = 0; -pub const O_NOATIME = 0o1000000; -pub const O_PATH = 0o10000000; +pub const O_ASYNC = 0o20000; +pub const O_DIRECT = 0o40000; +pub const O_LARGEFILE = 0; +pub const O_NOATIME = 0o1000000; +pub const O_PATH = 0o10000000; pub const O_TMPFILE = 0o20200000; -pub const O_NDELAY = O_NONBLOCK; +pub const O_NDELAY = O_NONBLOCK; pub const F_DUPFD = 0; pub const F_GETFD = 1; @@ -371,7 +371,6 @@ pub const F_GETOWN_EX = 16; pub const F_GETOWNER_UIDS = 17; - pub const VDSO_USEFUL = true; pub const VDSO_CGT_SYM = "__vdso_clock_gettime"; pub const VDSO_CGT_VER = "LINUX_2.6"; @@ -382,72 +381,85 @@ pub fn syscall0(number: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number) - : "rcx", "r11"); + : "rcx", "r11" + ); } pub fn syscall1(number: usize, arg1: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1) + : "rcx", "r11" + ); } pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1), - [arg2] "{rsi}" (arg2) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1), + [arg2] "{rsi}" (arg2) + : "rcx", "r11" + ); } pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1), - [arg2] "{rsi}" (arg2), - [arg3] "{rdx}" (arg3) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1), + [arg2] "{rsi}" (arg2), + [arg3] "{rdx}" (arg3) + : "rcx", "r11" + ); } pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1), - [arg2] "{rsi}" (arg2), - [arg3] "{rdx}" (arg3), - [arg4] "{r10}" (arg4) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1), + [arg2] "{rsi}" (arg2), + [arg3] "{rdx}" (arg3), + [arg4] "{r10}" (arg4) + : "rcx", "r11" + ); } pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1), - [arg2] "{rsi}" (arg2), - [arg3] "{rdx}" (arg3), - [arg4] "{r10}" (arg4), - [arg5] "{r8}" (arg5) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1), + [arg2] "{rsi}" (arg2), + [arg3] "{rdx}" (arg3), + [arg4] "{r10}" (arg4), + [arg5] "{r8}" (arg5) + : "rcx", "r11" + ); } -pub fn syscall6(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, - arg5: usize, arg6: usize) usize -{ +pub fn syscall6( + number: usize, + arg1: usize, + arg2: usize, + arg3: usize, + arg4: usize, + arg5: usize, + arg6: usize, +) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) : [number] "{rax}" (number), - [arg1] "{rdi}" (arg1), - [arg2] "{rsi}" (arg2), - [arg3] "{rdx}" (arg3), - [arg4] "{r10}" (arg4), - [arg5] "{r8}" (arg5), - [arg6] "{r9}" (arg6) - : "rcx", "r11"); + [arg1] "{rdi}" (arg1), + [arg2] "{rsi}" (arg2), + [arg3] "{rdx}" (arg3), + [arg4] "{r10}" (arg4), + [arg5] "{r8}" (arg5), + [arg6] "{r9}" (arg6) + : "rcx", "r11" + ); } /// This matches the libc clone function. @@ -457,10 +469,10 @@ pub nakedcc fn restore_rt() void { return asm volatile ("syscall" : : [number] "{rax}" (usize(SYS_rt_sigreturn)) - : "rcx", "r11"); + : "rcx", "r11" + ); } - pub const msghdr = extern struct { msg_name: &u8, msg_namelen: socklen_t, diff --git a/std/os/path.zig b/std/os/path.zig index 0ea5d5a753..5b2b031aab 100644 --- a/std/os/path.zig +++ b/std/os/path.zig @@ -55,9 +55,7 @@ test "os.path.join" { assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\", "a", "b\\", "c"), "c:\\a\\b\\c")); assert(mem.eql(u8, try joinWindows(debug.global_allocator, "c:\\a\\", "b\\", "c"), "c:\\a\\b\\c")); - 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")); + 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")); assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/b", "c"), "/a/b/c")); assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/b/", "c"), "/a/b/c")); @@ -65,8 +63,7 @@ test "os.path.join" { assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/", "a", "b/", "c"), "/a/b/c")); assert(mem.eql(u8, try joinPosix(debug.global_allocator, "/a/", "b/", "c"), "/a/b/c")); - 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")); + 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")); } pub fn isAbsolute(path: []const u8) bool { @@ -151,22 +148,22 @@ pub const WindowsPath = struct { pub fn windowsParsePath(path: []const u8) WindowsPath { if (path.len >= 2 and path[1] == ':') { - return WindowsPath { + return WindowsPath{ .is_abs = isAbsoluteWindows(path), .kind = WindowsPath.Kind.Drive, .disk_designator = path[0..2], }; } if (path.len >= 1 and (path[0] == '/' or path[0] == '\\') and - (path.len == 1 or (path[1] != '/' and path[1] != '\\'))) + (path.len == 1 or (path[1] != '/' and path[1] != '\\'))) { - return WindowsPath { + return WindowsPath{ .is_abs = true, .kind = WindowsPath.Kind.None, .disk_designator = path[0..0], }; } - const relative_path = WindowsPath { + const relative_path = WindowsPath{ .kind = WindowsPath.Kind.None, .disk_designator = []u8{}, .is_abs = false, @@ -178,7 +175,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath { // TODO when I combined these together with `inline for` the compiler crashed { const this_sep = '/'; - const two_sep = []u8{this_sep, this_sep}; + const two_sep = []u8{ this_sep, this_sep }; if (mem.startsWith(u8, path, two_sep)) { if (path[2] == this_sep) { return relative_path; @@ -187,7 +184,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath { var it = mem.split(path, []u8{this_sep}); _ = (it.next() ?? return relative_path); _ = (it.next() ?? return relative_path); - return WindowsPath { + return WindowsPath{ .is_abs = isAbsoluteWindows(path), .kind = WindowsPath.Kind.NetworkShare, .disk_designator = path[0..it.index], @@ -196,7 +193,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath { } { const this_sep = '\\'; - const two_sep = []u8{this_sep, this_sep}; + const two_sep = []u8{ this_sep, this_sep }; if (mem.startsWith(u8, path, two_sep)) { if (path[2] == this_sep) { return relative_path; @@ -205,7 +202,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath { var it = mem.split(path, []u8{this_sep}); _ = (it.next() ?? return relative_path); _ = (it.next() ?? return relative_path); - return WindowsPath { + return WindowsPath{ .is_abs = isAbsoluteWindows(path), .kind = WindowsPath.Kind.NetworkShare, .disk_designator = path[0..it.index], @@ -296,7 +293,7 @@ fn compareDiskDesignators(kind: WindowsPath.Kind, p1: []const u8, p2: []const u8 fn asciiUpper(byte: u8) u8 { return switch (byte) { - 'a' ... 'z' => 'A' + (byte - 'a'), + 'a'...'z' => 'A' + (byte - 'a'), else => byte, }; } @@ -372,7 +369,6 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 { max_size += p.len + 1; } - // if we will result with a disk designator, loop again to determine // which is the last time the disk designator is absolutely specified, if any // 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 { const parsed = windowsParsePath(p); if (parsed.kind != WindowsPath.Kind.None) { if (parsed.kind == have_drive_kind) { - correct_disk_designator = compareDiskDesignators(have_drive_kind, - result_disk_designator, parsed.disk_designator); + correct_disk_designator = compareDiskDesignators(have_drive_kind, result_disk_designator, parsed.disk_designator); } else { continue; } @@ -404,7 +399,6 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 { } } - // Allocate result and fill in the disk designator, calling getCwd if we have to. var result: []u8 = undefined; var result_index: usize = 0; @@ -433,7 +427,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 { result_index += 1; mem.copy(u8, result[result_index..], other_name); result_index += other_name.len; - + result_disk_designator = result[0..result_index]; }, WindowsPath.Kind.None => { @@ -478,8 +472,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 { if (parsed.kind != WindowsPath.Kind.None) { if (parsed.kind == have_drive_kind) { - correct_disk_designator = compareDiskDesignators(have_drive_kind, - result_disk_designator, parsed.disk_designator); + correct_disk_designator = compareDiskDesignators(have_drive_kind, result_disk_designator, parsed.disk_designator); } else { continue; } @@ -591,7 +584,7 @@ test "os.path.resolve" { } assert(mem.eql(u8, testResolveWindows([][]const u8{"."}), cwd)); } else { - assert(mem.eql(u8, testResolvePosix([][]const u8{"a/b/c/", "../../.."}), cwd)); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "a/b/c/", "../../.." }), cwd)); assert(mem.eql(u8, testResolvePosix([][]const u8{"."}), cwd)); } } @@ -601,16 +594,15 @@ test "os.path.resolveWindows" { const cwd = try os.getCwd(debug.global_allocator); const parsed_cwd = windowsParsePath(cwd); { - const result = testResolveWindows([][]const u8{"/usr/local", "lib\\zig\\std\\array_list.zig"}); - const expected = try join(debug.global_allocator, - parsed_cwd.disk_designator, "usr\\local\\lib\\zig\\std\\array_list.zig"); + const result = testResolveWindows([][]const u8{ "/usr/local", "lib\\zig\\std\\array_list.zig" }); + const expected = try join(debug.global_allocator, parsed_cwd.disk_designator, "usr\\local\\lib\\zig\\std\\array_list.zig"); if (parsed_cwd.kind == WindowsPath.Kind.Drive) { expected[0] = asciiUpper(parsed_cwd.disk_designator[0]); } assert(mem.eql(u8, result, expected)); } { - const result = testResolveWindows([][]const u8{"usr/local", "lib\\zig"}); + const result = testResolveWindows([][]const u8{ "usr/local", "lib\\zig" }); const expected = try join(debug.global_allocator, cwd, "usr\\local\\lib\\zig"); if (parsed_cwd.kind == WindowsPath.Kind.Drive) { expected[0] = asciiUpper(parsed_cwd.disk_designator[0]); @@ -619,33 +611,32 @@ test "os.path.resolveWindows" { } } - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:\\a\\b\\c", "/hi", "ok"}), "C:\\hi\\ok")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/blah\\blah", "d:/games", "c:../a"}), "C:\\blah\\a")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/blah\\blah", "d:/games", "C:../a"}), "C:\\blah\\a")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/ignore", "d:\\a/b\\c/d", "\\e.exe"}), "D:\\e.exe")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/ignore", "c:/some/file"}), "C:\\some\\file")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"d:/ignore", "d:some/dir//"}), "D:\\ignore\\some\\dir")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"//server/share", "..", "relative\\"}), "\\\\server\\share\\relative")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//"}), "C:\\")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//dir"}), "C:\\dir")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//server/share"}), "\\\\server\\share\\")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "//server//share"}), "\\\\server\\share\\")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"c:/", "///some//dir"}), "C:\\some\\dir")); - assert(mem.eql(u8, testResolveWindows([][]const u8{"C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js"}), - "C:\\foo\\tmp.3\\cycles\\root.js")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:\\a\\b\\c", "/hi", "ok" }), "C:\\hi\\ok")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/blah\\blah", "d:/games", "c:../a" }), "C:\\blah\\a")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/blah\\blah", "d:/games", "C:../a" }), "C:\\blah\\a")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/ignore", "d:\\a/b\\c/d", "\\e.exe" }), "D:\\e.exe")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/ignore", "c:/some/file" }), "C:\\some\\file")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "d:/ignore", "d:some/dir//" }), "D:\\ignore\\some\\dir")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "//server/share", "..", "relative\\" }), "\\\\server\\share\\relative")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//" }), "C:\\")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//dir" }), "C:\\dir")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//server/share" }), "\\\\server\\share\\")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "//server//share" }), "\\\\server\\share\\")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "c:/", "///some//dir" }), "C:\\some\\dir")); + assert(mem.eql(u8, testResolveWindows([][]const u8{ "C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js" }), "C:\\foo\\tmp.3\\cycles\\root.js")); } test "os.path.resolvePosix" { - assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b", "c"}), "/a/b/c")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b", "c", "//d", "e///"}), "/d/e")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b/c", "..", "../"}), "/a")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/", "..", ".."}), "/")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b", "c" }), "/a/b/c")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b", "c", "//d", "e///" }), "/d/e")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/a/b/c", "..", "../" }), "/a")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/", "..", ".." }), "/")); assert(mem.eql(u8, testResolvePosix([][]const u8{"/a/b/c/"}), "/a/b/c")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/var/lib", "../", "file/"}), "/var/file")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/var/lib", "/../", "file/"}), "/file")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/some/dir", ".", "/absolute/"}), "/absolute")); - assert(mem.eql(u8, testResolvePosix([][]const u8{"/foo/tmp.3/", "../tmp.3/cycles/root.js"}), "/foo/tmp.3/cycles/root.js")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/var/lib", "../", "file/" }), "/var/file")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/var/lib", "/../", "file/" }), "/file")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/some/dir", ".", "/absolute/" }), "/absolute")); + assert(mem.eql(u8, testResolvePosix([][]const u8{ "/foo/tmp.3/", "../tmp.3/cycles/root.js" }), "/foo/tmp.3/cycles/root.js")); } fn testResolveWindows(paths: []const []const u8) []u8 { @@ -1079,9 +1070,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) ![]u8 { mem.copy(u8, pathname_buf, pathname); pathname_buf[pathname.len] = 0; - const h_file = windows.CreateFileA(pathname_buf.ptr, - windows.GENERIC_READ, windows.FILE_SHARE_READ, null, windows.OPEN_EXISTING, - windows.FILE_ATTRIBUTE_NORMAL, null); + const h_file = windows.CreateFileA(pathname_buf.ptr, windows.GENERIC_READ, windows.FILE_SHARE_READ, null, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, null); if (h_file == windows.INVALID_HANDLE_VALUE) { const err = windows.GetLastError(); return switch (err) { @@ -1161,7 +1150,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) ![]u8 { return allocator.shrink(u8, result_buf, cstr.len(result_buf.ptr)); }, Os.linux => { - const fd = try os.posixOpen(allocator, pathname, posix.O_PATH|posix.O_NONBLOCK|posix.O_CLOEXEC, 0); + const fd = try os.posixOpen(allocator, pathname, posix.O_PATH | posix.O_NONBLOCK | posix.O_CLOEXEC, 0); defer os.close(fd); var buf: ["/proc/self/fd/-2147483648".len]u8 = undefined; diff --git a/std/os/time.zig b/std/os/time.zig index 3af150ab6a..9a7c682483 100644 --- a/std/os/time.zig +++ b/std/os/time.zig @@ -27,7 +27,7 @@ pub fn sleep(seconds: usize, nanoseconds: usize) void { const u63 = @IntType(false, 63); pub fn posixSleep(seconds: u63, nanoseconds: u63) void { - var req = posix.timespec { + var req = posix.timespec{ .tv_sec = seconds, .tv_nsec = nanoseconds, }; @@ -71,7 +71,7 @@ fn milliTimestampWindows() u64 { var ft: i64 = undefined; windows.GetSystemTimeAsFileTime(&ft); const hns_per_ms = (ns_per_s / 100) / ms_per_s; - const epoch_adj = epoch.windows * ms_per_s; + const epoch_adj = epoch.windows * ms_per_s; return u64(@divFloor(ft, hns_per_ms) + epoch_adj); } @@ -83,7 +83,7 @@ fn milliTimestampDarwin() u64 { debug.assert(err == 0); const sec_ms = u64(tv.tv_sec) * ms_per_s; const usec_ms = @divFloor(u64(tv.tv_usec), us_per_s / ms_per_s); - return u64(sec_ms) + u64(usec_ms); + return u64(sec_ms) + u64(usec_ms); } fn milliTimestampPosix() u64 { @@ -110,17 +110,16 @@ pub const s_per_hour = s_per_min * 60; pub const s_per_day = s_per_hour * 24; pub const s_per_week = s_per_day * 7; - /// A monotonic high-performance timer. /// Timer.start() must be called to initialize the struct, which captures /// the counter frequency on windows and darwin, records the resolution, /// and gives the user an oportunity to check for the existnece of /// monotonic clocks without forcing them to check for error on each read. -/// .resolution is in nanoseconds on all platforms but .start_time's meaning -/// depends on the OS. On Windows and Darwin it is a hardware counter +/// .resolution is in nanoseconds on all platforms but .start_time's meaning +/// depends on the OS. On Windows and Darwin it is a hardware counter /// value that requires calculation to convert to a meaninful unit. pub const Timer = struct { - + //if we used resolution's value when performing the // performance counter calc on windows/darwin, it would // be less precise @@ -131,10 +130,9 @@ pub const Timer = struct { }, resolution: u64, start_time: u64, - - + //At some point we may change our minds on RAW, but for now we're - // sticking with posix standard MONOTONIC. For more information, see: + // sticking with posix standard MONOTONIC. For more information, see: // https://github.com/ziglang/zig/pull/933 // //const monotonic_clock_id = switch(builtin.os) { @@ -142,20 +140,21 @@ pub const Timer = struct { // else => posix.CLOCK_MONOTONIC, //}; const monotonic_clock_id = posix.CLOCK_MONOTONIC; - - /// Initialize the timer structure. //This gives us an oportunity to grab the counter frequency in windows. //On Windows: QueryPerformanceCounter will succeed on anything >= XP/2000. - //On Posix: CLOCK_MONOTONIC will only fail if the monotonic counter is not - // supported, or if the timespec pointer is out of bounds, which should be + //On Posix: CLOCK_MONOTONIC will only fail if the monotonic counter is not + // supported, or if the timespec pointer is out of bounds, which should be // impossible here barring cosmic rays or other such occurances of // incredibly bad luck. //On Darwin: This cannot fail, as far as I am able to tell. - const TimerError = error{TimerUnsupported, Unexpected}; + const TimerError = error{ + TimerUnsupported, + Unexpected, + }; pub fn start() TimerError!Timer { var self: Timer = undefined; - + switch (builtin.os) { Os.windows => { var freq: i64 = undefined; @@ -163,7 +162,7 @@ pub const Timer = struct { if (err == windows.FALSE) return error.TimerUnsupported; self.frequency = u64(freq); self.resolution = @divFloor(ns_per_s, self.frequency); - + var start_time: i64 = undefined; err = windows.QueryPerformanceCounter(&start_time); debug.assert(err != windows.FALSE); @@ -171,9 +170,9 @@ pub const Timer = struct { }, Os.linux => { //On Linux, seccomp can do arbitrary things to our ability to call - // syscalls, including return any errno value it wants and + // syscalls, including return any errno value it wants and // inconsistently throwing errors. Since we can't account for - // abuses of seccomp in a reasonable way, we'll assume that if + // abuses of seccomp in a reasonable way, we'll assume that if // seccomp is going to block us it will at least do so consistently var ts: posix.timespec = undefined; var result = posix.clock_getres(monotonic_clock_id, &ts); @@ -184,7 +183,7 @@ pub const Timer = struct { else => return std.os.unexpectedErrorPosix(errno), } self.resolution = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec); - + result = posix.clock_gettime(monotonic_clock_id, &ts); errno = posix.getErrno(result); if (errno != 0) return std.os.unexpectedErrorPosix(errno); @@ -199,7 +198,7 @@ pub const Timer = struct { } return self; } - + /// Reads the timer value since start or the last reset in nanoseconds pub fn read(self: &Timer) u64 { var clock = clockNative() - self.start_time; @@ -210,13 +209,12 @@ pub const Timer = struct { else => @compileError("Unsupported OS"), }; } - + /// Resets the timer value to 0/now. - pub fn reset(self: &Timer) void - { + pub fn reset(self: &Timer) void { self.start_time = clockNative(); } - + /// Returns the current value of the timer in nanoseconds, then resets it pub fn lap(self: &Timer) u64 { var now = clockNative(); @@ -224,26 +222,25 @@ pub const Timer = struct { self.start_time = now; return lap_time; } - - + const clockNative = switch (builtin.os) { Os.windows => clockWindows, Os.linux => clockLinux, Os.macosx, Os.ios => clockDarwin, else => @compileError("Unsupported OS"), }; - + fn clockWindows() u64 { var result: i64 = undefined; var err = windows.QueryPerformanceCounter(&result); debug.assert(err != windows.FALSE); return u64(result); } - + fn clockDarwin() u64 { return darwin.mach_absolute_time(); } - + fn clockLinux() u64 { var ts: posix.timespec = undefined; var result = posix.clock_gettime(monotonic_clock_id, &ts); @@ -252,10 +249,6 @@ pub const Timer = struct { } }; - - - - test "os.time.sleep" { sleep(0, 1); } @@ -263,7 +256,7 @@ test "os.time.sleep" { test "os.time.timestamp" { const ns_per_ms = (ns_per_s / ms_per_s); const margin = 50; - + const time_0 = milliTimestamp(); sleep(0, ns_per_ms); const time_1 = milliTimestamp(); @@ -274,15 +267,15 @@ test "os.time.timestamp" { test "os.time.Timer" { const ns_per_ms = (ns_per_s / ms_per_s); const margin = ns_per_ms * 50; - + var timer = try Timer.start(); sleep(0, 10 * ns_per_ms); const time_0 = timer.read(); debug.assert(time_0 > 0 and time_0 < margin); - + const time_1 = timer.lap(); debug.assert(time_1 >= time_0); - + timer.reset(); debug.assert(timer.read() < time_1); } diff --git a/std/os/windows/error.zig b/std/os/windows/error.zig index 6a4087ab97..f90945d00e 100644 --- a/std/os/windows/error.zig +++ b/std/os/windows/error.zig @@ -1,2379 +1,3567 @@ /// The operation completed successfully. pub const SUCCESS = 0; + /// Incorrect function. pub const INVALID_FUNCTION = 1; + /// The system cannot find the file specified. pub const FILE_NOT_FOUND = 2; + /// The system cannot find the path specified. pub const PATH_NOT_FOUND = 3; + /// The system cannot open the file. pub const TOO_MANY_OPEN_FILES = 4; + /// Access is denied. pub const ACCESS_DENIED = 5; + /// The handle is invalid. pub const INVALID_HANDLE = 6; + /// The storage control blocks were destroyed. pub const ARENA_TRASHED = 7; + /// Not enough storage is available to process this command. pub const NOT_ENOUGH_MEMORY = 8; + /// The storage control block address is invalid. pub const INVALID_BLOCK = 9; + /// The environment is incorrect. pub const BAD_ENVIRONMENT = 10; + /// An attempt was made to load a program with an incorrect format. pub const BAD_FORMAT = 11; + /// The access code is invalid. pub const INVALID_ACCESS = 12; + /// The data is invalid. pub const INVALID_DATA = 13; + /// Not enough storage is available to complete this operation. pub const OUTOFMEMORY = 14; + /// The system cannot find the drive specified. pub const INVALID_DRIVE = 15; + /// The directory cannot be removed. pub const CURRENT_DIRECTORY = 16; + /// The system cannot move the file to a different disk drive. pub const NOT_SAME_DEVICE = 17; + /// There are no more files. pub const NO_MORE_FILES = 18; + /// The media is write protected. pub const WRITE_PROTECT = 19; + /// The system cannot find the device specified. pub const BAD_UNIT = 20; + /// The device is not ready. pub const NOT_READY = 21; + /// The device does not recognize the command. pub const BAD_COMMAND = 22; + /// Data error (cyclic redundancy check). pub const CRC = 23; + /// The program issued a command but the command length is incorrect. pub const BAD_LENGTH = 24; + /// The drive cannot locate a specific area or track on the disk. pub const SEEK = 25; + /// The specified disk or diskette cannot be accessed. pub const NOT_DOS_DISK = 26; + /// The drive cannot find the sector requested. pub const SECTOR_NOT_FOUND = 27; + /// The printer is out of paper. pub const OUT_OF_PAPER = 28; + /// The system cannot write to the specified device. pub const WRITE_FAULT = 29; + /// The system cannot read from the specified device. pub const READ_FAULT = 30; + /// A device attached to the system is not functioning. pub const GEN_FAILURE = 31; + /// The process cannot access the file because it is being used by another process. pub const SHARING_VIOLATION = 32; + /// The process cannot access the file because another process has locked a portion of the file. pub const LOCK_VIOLATION = 33; + /// The wrong diskette is in the drive. Insert %2 (Volume Serial Number: %3) into drive %1. pub const WRONG_DISK = 34; + /// Too many files opened for sharing. pub const SHARING_BUFFER_EXCEEDED = 36; + /// Reached the end of the file. pub const HANDLE_EOF = 38; + /// The disk is full. pub const HANDLE_DISK_FULL = 39; + /// The request is not supported. pub const NOT_SUPPORTED = 50; + /// 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. pub const REM_NOT_LIST = 51; + /// 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. pub const DUP_NAME = 52; + /// The network path was not found. pub const BAD_NETPATH = 53; + /// The network is busy. pub const NETWORK_BUSY = 54; + /// The specified network resource or device is no longer available. pub const DEV_NOT_EXIST = 55; + /// The network BIOS command limit has been reached. pub const TOO_MANY_CMDS = 56; + /// A network adapter hardware error occurred. pub const ADAP_HDW_ERR = 57; + /// The specified server cannot perform the requested operation. pub const BAD_NET_RESP = 58; + /// An unexpected network error occurred. pub const UNEXP_NET_ERR = 59; + /// The remote adapter is not compatible. pub const BAD_REM_ADAP = 60; + /// The printer queue is full. pub const PRINTQ_FULL = 61; + /// Space to store the file waiting to be printed is not available on the server. pub const NO_SPOOL_SPACE = 62; + /// Your file waiting to be printed was deleted. pub const PRINT_CANCELLED = 63; + /// The specified network name is no longer available. pub const NETNAME_DELETED = 64; + /// Network access is denied. pub const NETWORK_ACCESS_DENIED = 65; + /// The network resource type is not correct. pub const BAD_DEV_TYPE = 66; + /// The network name cannot be found. pub const BAD_NET_NAME = 67; + /// The name limit for the local computer network adapter card was exceeded. pub const TOO_MANY_NAMES = 68; + /// The network BIOS session limit was exceeded. pub const TOO_MANY_SESS = 69; + /// The remote server has been paused or is in the process of being started. pub const SHARING_PAUSED = 70; + /// 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. pub const REQ_NOT_ACCEP = 71; + /// The specified printer or disk device has been paused. pub const REDIR_PAUSED = 72; + /// The file exists. pub const FILE_EXISTS = 80; + /// The directory or file cannot be created. pub const CANNOT_MAKE = 82; + /// Fail on INT 24. pub const FAIL_I24 = 83; + /// Storage to process this request is not available. pub const OUT_OF_STRUCTURES = 84; + /// The local device name is already in use. pub const ALREADY_ASSIGNED = 85; + /// The specified network password is not correct. pub const INVALID_PASSWORD = 86; + /// The parameter is incorrect. pub const INVALID_PARAMETER = 87; + /// A write fault occurred on the network. pub const NET_WRITE_FAULT = 88; + /// The system cannot start another process at this time. pub const NO_PROC_SLOTS = 89; + /// Cannot create another system semaphore. pub const TOO_MANY_SEMAPHORES = 100; + /// The exclusive semaphore is owned by another process. pub const EXCL_SEM_ALREADY_OWNED = 101; + /// The semaphore is set and cannot be closed. pub const SEM_IS_SET = 102; + /// The semaphore cannot be set again. pub const TOO_MANY_SEM_REQUESTS = 103; + /// Cannot request exclusive semaphores at interrupt time. pub const INVALID_AT_INTERRUPT_TIME = 104; + /// The previous ownership of this semaphore has ended. pub const SEM_OWNER_DIED = 105; + /// Insert the diskette for drive %1. pub const SEM_USER_LIMIT = 106; + /// The program stopped because an alternate diskette was not inserted. pub const DISK_CHANGE = 107; + /// The disk is in use or locked by another process. pub const DRIVE_LOCKED = 108; + /// The pipe has been ended. pub const BROKEN_PIPE = 109; + /// The system cannot open the device or file specified. pub const OPEN_FAILED = 110; + /// The file name is too long. pub const BUFFER_OVERFLOW = 111; + /// There is not enough space on the disk. pub const DISK_FULL = 112; + /// No more internal file identifiers available. pub const NO_MORE_SEARCH_HANDLES = 113; + /// The target internal file identifier is incorrect. pub const INVALID_TARGET_HANDLE = 114; + /// The IOCTL call made by the application program is not correct. pub const INVALID_CATEGORY = 117; + /// The verify-on-write switch parameter value is not correct. pub const INVALID_VERIFY_SWITCH = 118; + /// The system does not support the command requested. pub const BAD_DRIVER_LEVEL = 119; + /// This function is not supported on this system. pub const CALL_NOT_IMPLEMENTED = 120; + /// The semaphore timeout period has expired. pub const SEM_TIMEOUT = 121; + /// The data area passed to a system call is too small. pub const INSUFFICIENT_BUFFER = 122; + /// The filename, directory name, or volume label syntax is incorrect. pub const INVALID_NAME = 123; + /// The system call level is not correct. pub const INVALID_LEVEL = 124; + /// The disk has no volume label. pub const NO_VOLUME_LABEL = 125; + /// The specified module could not be found. pub const MOD_NOT_FOUND = 126; + /// The specified procedure could not be found. pub const PROC_NOT_FOUND = 127; + /// There are no child processes to wait for. pub const WAIT_NO_CHILDREN = 128; + /// The %1 application cannot be run in Win32 mode. pub const CHILD_NOT_COMPLETE = 129; + /// Attempt to use a file handle to an open disk partition for an operation other than raw disk I/O. pub const DIRECT_ACCESS_HANDLE = 130; + /// An attempt was made to move the file pointer before the beginning of the file. pub const NEGATIVE_SEEK = 131; + /// The file pointer cannot be set on the specified device or file. pub const SEEK_ON_DEVICE = 132; + /// A JOIN or SUBST command cannot be used for a drive that contains previously joined drives. pub const IS_JOIN_TARGET = 133; + /// An attempt was made to use a JOIN or SUBST command on a drive that has already been joined. pub const IS_JOINED = 134; + /// An attempt was made to use a JOIN or SUBST command on a drive that has already been substituted. pub const IS_SUBSTED = 135; + /// The system tried to delete the JOIN of a drive that is not joined. pub const NOT_JOINED = 136; + /// The system tried to delete the substitution of a drive that is not substituted. pub const NOT_SUBSTED = 137; + /// The system tried to join a drive to a directory on a joined drive. pub const JOIN_TO_JOIN = 138; + /// The system tried to substitute a drive to a directory on a substituted drive. pub const SUBST_TO_SUBST = 139; + /// The system tried to join a drive to a directory on a substituted drive. pub const JOIN_TO_SUBST = 140; + /// The system tried to SUBST a drive to a directory on a joined drive. pub const SUBST_TO_JOIN = 141; + /// The system cannot perform a JOIN or SUBST at this time. pub const BUSY_DRIVE = 142; + /// The system cannot join or substitute a drive to or for a directory on the same drive. pub const SAME_DRIVE = 143; + /// The directory is not a subdirectory of the root directory. pub const DIR_NOT_ROOT = 144; + /// The directory is not empty. pub const DIR_NOT_EMPTY = 145; + /// The path specified is being used in a substitute. pub const IS_SUBST_PATH = 146; + /// Not enough resources are available to process this command. pub const IS_JOIN_PATH = 147; + /// The path specified cannot be used at this time. pub const PATH_BUSY = 148; + /// An attempt was made to join or substitute a drive for which a directory on the drive is the target of a previous substitute. pub const IS_SUBST_TARGET = 149; + /// System trace information was not specified in your CONFIG.SYS file, or tracing is disallowed. pub const SYSTEM_TRACE = 150; + /// The number of specified semaphore events for DosMuxSemWait is not correct. pub const INVALID_EVENT_COUNT = 151; + /// DosMuxSemWait did not execute; too many semaphores are already set. pub const TOO_MANY_MUXWAITERS = 152; + /// The DosMuxSemWait list is not correct. pub const INVALID_LIST_FORMAT = 153; + /// The volume label you entered exceeds the label character limit of the target file system. pub const LABEL_TOO_LONG = 154; + /// Cannot create another thread. pub const TOO_MANY_TCBS = 155; + /// The recipient process has refused the signal. pub const SIGNAL_REFUSED = 156; + /// The segment is already discarded and cannot be locked. pub const DISCARDED = 157; + /// The segment is already unlocked. pub const NOT_LOCKED = 158; + /// The address for the thread ID is not correct. pub const BAD_THREADID_ADDR = 159; + /// One or more arguments are not correct. pub const BAD_ARGUMENTS = 160; + /// The specified path is invalid. pub const BAD_PATHNAME = 161; + /// A signal is already pending. pub const SIGNAL_PENDING = 162; + /// No more threads can be created in the system. pub const MAX_THRDS_REACHED = 164; + /// Unable to lock a region of a file. pub const LOCK_FAILED = 167; + /// The requested resource is in use. pub const BUSY = 170; + /// Device's command support detection is in progress. pub const DEVICE_SUPPORT_IN_PROGRESS = 171; + /// A lock request was not outstanding for the supplied cancel region. pub const CANCEL_VIOLATION = 173; + /// The file system does not support atomic changes to the lock type. pub const ATOMIC_LOCKS_NOT_SUPPORTED = 174; + /// The system detected a segment number that was not correct. pub const INVALID_SEGMENT_NUMBER = 180; + /// The operating system cannot run %1. pub const INVALID_ORDINAL = 182; + /// Cannot create a file when that file already exists. pub const ALREADY_EXISTS = 183; + /// The flag passed is not correct. pub const INVALID_FLAG_NUMBER = 186; + /// The specified system semaphore name was not found. pub const SEM_NOT_FOUND = 187; + /// The operating system cannot run %1. pub const INVALID_STARTING_CODESEG = 188; + /// The operating system cannot run %1. pub const INVALID_STACKSEG = 189; + /// The operating system cannot run %1. pub const INVALID_MODULETYPE = 190; + /// Cannot run %1 in Win32 mode. pub const INVALID_EXE_SIGNATURE = 191; + /// The operating system cannot run %1. pub const EXE_MARKED_INVALID = 192; + /// %1 is not a valid Win32 application. pub const BAD_EXE_FORMAT = 193; + /// The operating system cannot run %1. pub const ITERATED_DATA_EXCEEDS_64k = 194; + /// The operating system cannot run %1. pub const INVALID_MINALLOCSIZE = 195; + /// The operating system cannot run this application program. pub const DYNLINK_FROM_INVALID_RING = 196; + /// The operating system is not presently configured to run this application. pub const IOPL_NOT_ENABLED = 197; + /// The operating system cannot run %1. pub const INVALID_SEGDPL = 198; + /// The operating system cannot run this application program. pub const AUTODATASEG_EXCEEDS_64k = 199; + /// The code segment cannot be greater than or equal to 64K. pub const RING2SEG_MUST_BE_MOVABLE = 200; + /// The operating system cannot run %1. pub const RELOC_CHAIN_XEEDS_SEGLIM = 201; + /// The operating system cannot run %1. pub const INFLOOP_IN_RELOC_CHAIN = 202; + /// The system could not find the environment option that was entered. pub const ENVVAR_NOT_FOUND = 203; + /// No process in the command subtree has a signal handler. pub const NO_SIGNAL_SENT = 205; + /// The filename or extension is too long. pub const FILENAME_EXCED_RANGE = 206; + /// The ring 2 stack is in use. pub const RING2_STACK_IN_USE = 207; + /// The global filename characters, * or ?, are entered incorrectly or too many global filename characters are specified. pub const META_EXPANSION_TOO_LONG = 208; + /// The signal being posted is not correct. pub const INVALID_SIGNAL_NUMBER = 209; + /// The signal handler cannot be set. pub const THREAD_1_INACTIVE = 210; + /// The segment is locked and cannot be reallocated. pub const LOCKED = 212; + /// Too many dynamic-link modules are attached to this program or dynamic-link module. pub const TOO_MANY_MODULES = 214; + /// Cannot nest calls to LoadModule. pub const NESTING_NOT_ALLOWED = 215; + /// 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. pub const EXE_MACHINE_TYPE_MISMATCH = 216; + /// The image file %1 is signed, unable to modify. pub const EXE_CANNOT_MODIFY_SIGNED_BINARY = 217; + /// The image file %1 is strong signed, unable to modify. pub const EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY = 218; + /// This file is checked out or locked for editing by another user. pub const FILE_CHECKED_OUT = 220; + /// The file must be checked out before saving changes. pub const CHECKOUT_REQUIRED = 221; + /// The file type being saved or retrieved has been blocked. pub const BAD_FILE_TYPE = 222; + /// The file size exceeds the limit allowed and cannot be saved. pub const FILE_TOO_LARGE = 223; + /// 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. pub const FORMS_AUTH_REQUIRED = 224; + /// Operation did not complete successfully because the file contains a virus or potentially unwanted software. pub const VIRUS_INFECTED = 225; + /// 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. pub const VIRUS_DELETED = 226; + /// The pipe is local. pub const PIPE_LOCAL = 229; + /// The pipe state is invalid. pub const BAD_PIPE = 230; + /// All pipe instances are busy. pub const PIPE_BUSY = 231; + /// The pipe is being closed. pub const NO_DATA = 232; + /// No process is on the other end of the pipe. pub const PIPE_NOT_CONNECTED = 233; + /// More data is available. pub const MORE_DATA = 234; + /// The session was canceled. pub const VC_DISCONNECTED = 240; + /// The specified extended attribute name was invalid. pub const INVALID_EA_NAME = 254; + /// The extended attributes are inconsistent. pub const EA_LIST_INCONSISTENT = 255; + /// The wait operation timed out. pub const IMEOUT = 258; + /// No more data is available. pub const NO_MORE_ITEMS = 259; + /// The copy functions cannot be used. pub const CANNOT_COPY = 266; + /// The directory name is invalid. pub const DIRECTORY = 267; + /// The extended attributes did not fit in the buffer. pub const EAS_DIDNT_FIT = 275; + /// The extended attribute file on the mounted file system is corrupt. pub const EA_FILE_CORRUPT = 276; + /// The extended attribute table file is full. pub const EA_TABLE_FULL = 277; + /// The specified extended attribute handle is invalid. pub const INVALID_EA_HANDLE = 278; + /// The mounted file system does not support extended attributes. pub const EAS_NOT_SUPPORTED = 282; + /// Attempt to release mutex not owned by caller. pub const NOT_OWNER = 288; + /// Too many posts were made to a semaphore. pub const TOO_MANY_POSTS = 298; + /// Only part of a ReadProcessMemory or WriteProcessMemory request was completed. pub const PARTIAL_COPY = 299; + /// The oplock request is denied. pub const OPLOCK_NOT_GRANTED = 300; + /// An invalid oplock acknowledgment was received by the system. pub const INVALID_OPLOCK_PROTOCOL = 301; + /// The volume is too fragmented to complete this operation. pub const DISK_TOO_FRAGMENTED = 302; + /// The file cannot be opened because it is in the process of being deleted. pub const DELETE_PENDING = 303; + /// Short name settings may not be changed on this volume due to the global registry setting. pub const INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING = 304; + /// Short names are not enabled on this volume. pub const SHORT_NAMES_NOT_ENABLED_ON_VOLUME = 305; + /// The security stream for the given volume is in an inconsistent state. Please run CHKDSK on the volume. pub const SECURITY_STREAM_IS_INCONSISTENT = 306; + /// A requested file lock operation cannot be processed due to an invalid byte range. pub const INVALID_LOCK_RANGE = 307; + /// The subsystem needed to support the image type is not present. pub const IMAGE_SUBSYSTEM_NOT_PRESENT = 308; + /// The specified file already has a notification GUID associated with it. pub const NOTIFICATION_GUID_ALREADY_DEFINED = 309; + /// An invalid exception handler routine has been detected. pub const INVALID_EXCEPTION_HANDLER = 310; + /// Duplicate privileges were specified for the token. pub const DUPLICATE_PRIVILEGES = 311; + /// No ranges for the specified operation were able to be processed. pub const NO_RANGES_PROCESSED = 312; + /// Operation is not allowed on a file system internal file. pub const NOT_ALLOWED_ON_SYSTEM_FILE = 313; + /// The physical resources of this disk have been exhausted. pub const DISK_RESOURCES_EXHAUSTED = 314; + /// The token representing the data is invalid. pub const INVALID_TOKEN = 315; + /// The device does not support the command feature. pub const DEVICE_FEATURE_NOT_SUPPORTED = 316; + /// The system cannot find message text for message number 0x%1 in the message file for %2. pub const MR_MID_NOT_FOUND = 317; + /// The scope specified was not found. pub const SCOPE_NOT_FOUND = 318; + /// The Central Access Policy specified is not defined on the target machine. pub const UNDEFINED_SCOPE = 319; + /// The Central Access Policy obtained from Active Directory is invalid. pub const INVALID_CAP = 320; + /// The device is unreachable. pub const DEVICE_UNREACHABLE = 321; + /// The target device has insufficient resources to complete the operation. pub const DEVICE_NO_RESOURCES = 322; + /// A data integrity checksum error occurred. Data in the file stream is corrupt. pub const DATA_CHECKSUM_ERROR = 323; + /// An attempt was made to modify both a KERNEL and normal Extended Attribute (EA) in the same operation. pub const INTERMIXED_KERNEL_EA_OPERATION = 324; + /// Device does not support file-level TRIM. pub const FILE_LEVEL_TRIM_NOT_SUPPORTED = 326; + /// The command specified a data offset that does not align to the device's granularity/alignment. pub const OFFSET_ALIGNMENT_VIOLATION = 327; + /// The command specified an invalid field in its parameter list. pub const INVALID_FIELD_IN_PARAMETER_LIST = 328; + /// An operation is currently in progress with the device. pub const OPERATION_IN_PROGRESS = 329; + /// An attempt was made to send down the command via an invalid path to the target device. pub const BAD_DEVICE_PATH = 330; + /// The command specified a number of descriptors that exceeded the maximum supported by the device. pub const TOO_MANY_DESCRIPTORS = 331; + /// Scrub is disabled on the specified file. pub const SCRUB_DATA_DISABLED = 332; + /// The storage device does not provide redundancy. pub const NOT_REDUNDANT_STORAGE = 333; + /// An operation is not supported on a resident file. pub const RESIDENT_FILE_NOT_SUPPORTED = 334; + /// An operation is not supported on a compressed file. pub const COMPRESSED_FILE_NOT_SUPPORTED = 335; + /// An operation is not supported on a directory. pub const DIRECTORY_NOT_SUPPORTED = 336; + /// The specified copy of the requested data could not be read. pub const NOT_READ_FROM_COPY = 337; + /// No action was taken as a system reboot is required. pub const FAIL_NOACTION_REBOOT = 350; + /// The shutdown operation failed. pub const FAIL_SHUTDOWN = 351; + /// The restart operation failed. pub const FAIL_RESTART = 352; + /// The maximum number of sessions has been reached. pub const MAX_SESSIONS_REACHED = 353; + /// The thread is already in background processing mode. pub const THREAD_MODE_ALREADY_BACKGROUND = 400; + /// The thread is not in background processing mode. pub const THREAD_MODE_NOT_BACKGROUND = 401; + /// The process is already in background processing mode. pub const PROCESS_MODE_ALREADY_BACKGROUND = 402; + /// The process is not in background processing mode. pub const PROCESS_MODE_NOT_BACKGROUND = 403; + /// Attempt to access invalid address. pub const INVALID_ADDRESS = 487; + /// User profile cannot be loaded. pub const USER_PROFILE_LOAD = 500; + /// Arithmetic result exceeded 32 bits. pub const ARITHMETIC_OVERFLOW = 534; + /// There is a process on other end of the pipe. pub const PIPE_CONNECTED = 535; + /// Waiting for a process to open the other end of the pipe. pub const PIPE_LISTENING = 536; + /// Application verifier has found an error in the current process. pub const VERIFIER_STOP = 537; + /// An error occurred in the ABIOS subsystem. pub const ABIOS_ERROR = 538; + /// A warning occurred in the WX86 subsystem. pub const WX86_WARNING = 539; + /// An error occurred in the WX86 subsystem. pub const WX86_ERROR = 540; + /// 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. pub const TIMER_NOT_CANCELED = 541; + /// Unwind exception code. pub const UNWIND = 542; + /// An invalid or unaligned stack was encountered during an unwind operation. pub const BAD_STACK = 543; + /// An invalid unwind target was encountered during an unwind operation. pub const INVALID_UNWIND_TARGET = 544; + /// Invalid Object Attributes specified to NtCreatePort or invalid Port Attributes specified to NtConnectPort pub const INVALID_PORT_ATTRIBUTES = 545; + /// Length of message passed to NtRequestPort or NtRequestWaitReplyPort was longer than the maximum message allowed by the port. pub const PORT_MESSAGE_TOO_LONG = 546; + /// An attempt was made to lower a quota limit below the current usage. pub const INVALID_QUOTA_LOWER = 547; + /// An attempt was made to attach to a device that was already attached to another device. pub const DEVICE_ALREADY_ATTACHED = 548; + /// An attempt was made to execute an instruction at an unaligned address and the host system does not support unaligned instruction references. pub const INSTRUCTION_MISALIGNMENT = 549; + /// Profiling not started. pub const PROFILING_NOT_STARTED = 550; + /// Profiling not stopped. pub const PROFILING_NOT_STOPPED = 551; + /// The passed ACL did not contain the minimum required information. pub const COULD_NOT_INTERPRET = 552; + /// The number of active profiling objects is at the maximum and no more may be started. pub const PROFILING_AT_LIMIT = 553; + /// Used to indicate that an operation cannot continue without blocking for I/O. pub const CANT_WAIT = 554; + /// Indicates that a thread attempted to terminate itself by default (called NtTerminateThread with NULL) and it was the last thread in the current process. pub const CANT_TERMINATE_SELF = 555; + /// 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. pub const UNEXPECTED_MM_CREATE_ERR = 556; + /// 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. pub const UNEXPECTED_MM_MAP_ERROR = 557; + /// 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. pub const UNEXPECTED_MM_EXTEND_ERR = 558; + /// A malformed function table was encountered during an unwind operation. pub const BAD_FUNCTION_TABLE = 559; + /// 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. pub const NO_GUID_TRANSLATION = 560; + /// 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. pub const INVALID_LDT_SIZE = 561; + /// Indicates that the starting value for the LDT information was not an integral multiple of the selector size. pub const INVALID_LDT_OFFSET = 563; + /// Indicates that the user supplied an invalid descriptor when trying to set up Ldt descriptors. pub const INVALID_LDT_DESCRIPTOR = 564; + /// 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. pub const TOO_MANY_THREADS = 565; + /// An attempt was made to operate on a thread within a specific process, but the thread specified is not in the process specified. pub const THREAD_NOT_IN_PROCESS = 566; + /// Page file quota was exceeded. pub const PAGEFILE_QUOTA_EXCEEDED = 567; + /// The Netlogon service cannot start because another Netlogon service running in the domain conflicts with the specified role. pub const LOGON_SERVER_CONFLICT = 568; + /// The SAM database on a Windows Server is significantly out of synchronization with the copy on the Domain Controller. A complete synchronization is required. pub const SYNCHRONIZATION_REQUIRED = 569; + /// 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. pub const NET_OPEN_FAILED = 570; + /// {Privilege Failed} The I/O permissions for the process could not be changed. pub const IO_PRIVILEGE_FAILED = 571; + /// {Application Exit by CTRL+C} The application terminated as a result of a CTRL+C. pub const CONTROL_C_EXIT = 572; + /// {Missing System File} The required system file %hs is bad or missing. pub const MISSING_SYSTEMFILE = 573; + /// {Application Error} The exception %s (0x%08lx) occurred in the application at location 0x%08lx. pub const UNHANDLED_EXCEPTION = 574; + /// {Application Error} The application was unable to start correctly (0x%lx). Click OK to close the application. pub const APP_INIT_FAILURE = 575; + /// {Unable to Create Paging File} The creation of the paging file %hs failed (%lx). The requested size was %ld. pub const PAGEFILE_CREATE_FAILED = 576; + /// 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. pub const INVALID_IMAGE_HASH = 577; + /// {No Paging File Specified} No paging file was specified in the system configuration. pub const NO_PAGEFILE = 578; + /// {EXCEPTION} A real-mode application issued a floating-point instruction and floating-point hardware is not present. pub const ILLEGAL_FLOAT_CONTEXT = 579; + /// 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. pub const NO_EVENT_PAIR = 580; + /// A Windows Server has an incorrect configuration. pub const DOMAIN_CTRLR_CONFIG_ERROR = 581; + /// 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. pub const ILLEGAL_CHARACTER = 582; + /// The Unicode character is not defined in the Unicode character set installed on the system. pub const UNDEFINED_CHARACTER = 583; + /// The paging file cannot be created on a floppy diskette. pub const FLOPPY_VOLUME = 584; + /// The system BIOS failed to connect a system interrupt to the device or bus for which the device is connected. pub const BIOS_FAILED_TO_CONNECT_INTERRUPT = 585; + /// This operation is only allowed for the Primary Domain Controller of the domain. pub const BACKUP_CONTROLLER = 586; + /// An attempt was made to acquire a mutant such that its maximum count would have been exceeded. pub const MUTANT_LIMIT_EXCEEDED = 587; + /// A volume has been accessed for which a file system driver is required that has not yet been loaded. pub const FS_DRIVER_REQUIRED = 588; + /// {Registry File Failure} The registry cannot load the hive (file): %hs or its log or alternate. It is corrupt, absent, or not writable. pub const CANNOT_LOAD_REGISTRY_FILE = 589; + /// {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. pub const DEBUG_ATTACH_FAILED = 590; + /// {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. pub const SYSTEM_PROCESS_TERMINATED = 591; + /// {Data Not Accepted} The TDI client could not handle the data received during an indication. pub const DATA_NOT_ACCEPTED = 592; + /// NTVDM encountered a hard error. pub const VDM_HARD_ERROR = 593; + /// {Cancel Timeout} The driver %hs failed to complete a cancelled I/O request in the allotted time. pub const DRIVER_CANCEL_TIMEOUT = 594; + /// {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. pub const REPLY_MESSAGE_MISMATCH = 595; + /// {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. pub const LOST_WRITEBEHIND_DATA = 596; + /// 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. pub const CLIENT_SERVER_PARAMETERS_INVALID = 597; + /// The stream is not a tiny stream. pub const NOT_TINY_STREAM = 598; + /// The request must be handled by the stack overflow code. pub const STACK_OVERFLOW_READ = 599; + /// 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. pub const CONVERT_TO_LARGE = 600; + /// 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. pub const FOUND_OUT_OF_SCOPE = 601; + /// The bucket array must be grown. Retry transaction after doing so. pub const ALLOCATE_BUCKET = 602; + /// The user/kernel marshalling buffer has overflowed. pub const MARSHALL_OVERFLOW = 603; + /// The supplied variant structure contains invalid data. pub const INVALID_VARIANT = 604; + /// The specified buffer contains ill-formed data. pub const BAD_COMPRESSION_BUFFER = 605; + /// {Audit Failed} An attempt to generate a security audit failed. pub const AUDIT_FAILED = 606; + /// The timer resolution was not previously set by the current process. pub const TIMER_RESOLUTION_NOT_SET = 607; + /// There is insufficient account information to log you on. pub const INSUFFICIENT_LOGON_INFO = 608; + /// {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. pub const BAD_DLL_ENTRYPOINT = 609; + /// {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. pub const BAD_SERVICE_ENTRYPOINT = 610; + /// There is an IP address conflict with another system on the network. pub const IP_ADDRESS_CONFLICT1 = 611; + /// There is an IP address conflict with another system on the network. pub const IP_ADDRESS_CONFLICT2 = 612; + /// {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. pub const REGISTRY_QUOTA_LIMIT = 613; + /// A callback return system service cannot be executed when no callback is active. pub const NO_CALLBACK_ACTIVE = 614; + /// The password provided is too short to meet the policy of your user account. Please choose a longer password. pub const PWD_TOO_SHORT = 615; + /// 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. pub const PWD_TOO_RECENT = 616; + /// 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. pub const PWD_HISTORY_CONFLICT = 617; + /// The specified compression format is unsupported. pub const UNSUPPORTED_COMPRESSION = 618; + /// The specified hardware profile configuration is invalid. pub const INVALID_HW_PROFILE = 619; + /// The specified Plug and Play registry device path is invalid. pub const INVALID_PLUGPLAY_DEVICE_PATH = 620; + /// The specified quota list is internally inconsistent with its descriptor. pub const QUOTA_LIST_INCONSISTENT = 621; + /// {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. pub const EVALUATION_EXPIRATION = 622; + /// {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. pub const ILLEGAL_DLL_RELOCATION = 623; + /// {DLL Initialization Failed} The application failed to initialize because the window station is shutting down. pub const DLL_INIT_FAILED_LOGOFF = 624; + /// The validation process needs to continue on to the next step. pub const VALIDATE_CONTINUE = 625; + /// There are no more matches for the current index enumeration. pub const NO_MORE_MATCHES = 626; + /// The range could not be added to the range list because of a conflict. pub const RANGE_LIST_CONFLICT = 627; + /// The server process is running under a SID different than that required by client. pub const SERVER_SID_MISMATCH = 628; + /// A group marked use for deny only cannot be enabled. pub const CANT_ENABLE_DENY_ONLY = 629; + /// {EXCEPTION} Multiple floating point faults. pub const FLOAT_MULTIPLE_FAULTS = 630; + /// {EXCEPTION} Multiple floating point traps. pub const FLOAT_MULTIPLE_TRAPS = 631; + /// The requested interface is not supported. pub const NOINTERFACE = 632; + /// {System Standby Failed} The driver %hs does not support standby mode. Updating this driver may allow the system to go to standby mode. pub const DRIVER_FAILED_SLEEP = 633; + /// The system file %1 has become corrupt and has been replaced. pub const CORRUPT_SYSTEM_FILE = 634; + /// {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. pub const COMMITMENT_MINIMUM = 635; + /// A device was removed so enumeration must be restarted. pub const PNP_RESTART_ENUMERATION = 636; + /// {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. pub const SYSTEM_IMAGE_BAD_SIGNATURE = 637; + /// Device will not start without a reboot. pub const PNP_REBOOT_REQUIRED = 638; + /// There is not enough power to complete the requested operation. pub const INSUFFICIENT_POWER = 639; + /// ERROR_MULTIPLE_FAULT_VIOLATION pub const MULTIPLE_FAULT_VIOLATION = 640; + /// The system is in the process of shutting down. pub const SYSTEM_SHUTDOWN = 641; + /// An attempt to remove a processes DebugPort was made, but a port was not already associated with the process. pub const PORT_NOT_SET = 642; + /// This version of Windows is not compatible with the behavior version of directory forest, domain or domain controller. pub const DS_VERSION_CHECK_FAILURE = 643; + /// The specified range could not be found in the range list. pub const RANGE_NOT_FOUND = 644; + /// The driver was not loaded because the system is booting into safe mode. pub const NOT_SAFE_MODE_DRIVER = 646; + /// The driver was not loaded because it failed its initialization call. pub const FAILED_DRIVER_ENTRY = 647; + /// 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. pub const DEVICE_ENUMERATION_ERROR = 648; + /// 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. pub const MOUNT_POINT_NOT_RESOLVED = 649; + /// The device object parameter is either not a valid device object or is not attached to the volume specified by the file name. pub const INVALID_DEVICE_OBJECT_PARAMETER = 650; + /// A Machine Check Error has occurred. Please check the system eventlog for additional information. pub const MCA_OCCURED = 651; + /// There was error [%2] processing the driver database. pub const DRIVER_DATABASE_ERROR = 652; + /// System hive size has exceeded its limit. pub const SYSTEM_HIVE_TOO_LARGE = 653; + /// The driver could not be loaded because a previous version of the driver is still in memory. pub const DRIVER_FAILED_PRIOR_UNLOAD = 654; + /// {Volume Shadow Copy Service} Please wait while the Volume Shadow Copy Service prepares volume %hs for hibernation. pub const VOLSNAP_PREPARE_HIBERNATE = 655; + /// The system has failed to hibernate (The error code is %hs). Hibernation will be disabled until the system is restarted. pub const HIBERNATION_FAILURE = 656; + /// The password provided is too long to meet the policy of your user account. Please choose a shorter password. pub const PWD_TOO_LONG = 657; + /// The requested operation could not be completed due to a file system limitation. pub const FILE_SYSTEM_LIMITATION = 665; + /// An assertion failure has occurred. pub const ASSERTION_FAILURE = 668; + /// An error occurred in the ACPI subsystem. pub const ACPI_ERROR = 669; + /// WOW Assertion Error. pub const WOW_ASSERTION = 670; + /// 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. pub const PNP_BAD_MPS_TABLE = 671; + /// A translator failed to translate resources. pub const PNP_TRANSLATION_FAILED = 672; + /// A IRQ translator failed to translate resources. pub const PNP_IRQ_TRANSLATION_FAILED = 673; + /// Driver %2 returned invalid ID for a child device (%3). pub const PNP_INVALID_ID = 674; + /// {Kernel Debugger Awakened} the system debugger was awakened by an interrupt. pub const WAKE_SYSTEM_DEBUGGER = 675; + /// {Handles Closed} Handles to objects have been automatically closed as a result of the requested operation. pub const HANDLES_CLOSED = 676; + /// {Too Much Information} The specified access control list (ACL) contained more information than was expected. pub const EXTRANEOUS_INFORMATION = 677; + /// 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). pub const RXACT_COMMIT_NECESSARY = 678; + /// {Media Changed} The media may have changed. pub const MEDIA_CHECK = 679; + /// {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. pub const GUID_SUBSTITUTION_MADE = 680; + /// The create operation stopped after reaching a symbolic link. pub const STOPPED_ON_SYMLINK = 681; + /// A long jump has been executed. pub const LONGJUMP = 682; + /// The Plug and Play query operation was not successful. pub const PLUGPLAY_QUERY_VETOED = 683; + /// A frame consolidation has been executed. pub const UNWIND_CONSOLIDATE = 684; + /// {Registry Hive Recovered} Registry hive (file): %hs was corrupted and it has been recovered. Some data might have been lost. pub const REGISTRY_HIVE_RECOVERED = 685; + /// 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? pub const DLL_MIGHT_BE_INSECURE = 686; + /// 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? pub const DLL_MIGHT_BE_INCOMPATIBLE = 687; + /// Debugger did not handle the exception. pub const DBG_EXCEPTION_NOT_HANDLED = 688; + /// Debugger will reply later. pub const DBG_REPLY_LATER = 689; + /// Debugger cannot provide handle. pub const DBG_UNABLE_TO_PROVIDE_HANDLE = 690; + /// Debugger terminated thread. pub const DBG_TERMINATE_THREAD = 691; + /// Debugger terminated process. pub const DBG_TERMINATE_PROCESS = 692; + /// Debugger got control C. pub const DBG_CONTROL_C = 693; + /// Debugger printed exception on control C. pub const DBG_PRINTEXCEPTION_C = 694; + /// Debugger received RIP exception. pub const DBG_RIPEXCEPTION = 695; + /// Debugger received control break. pub const DBG_CONTROL_BREAK = 696; + /// Debugger command communication exception. pub const DBG_COMMAND_EXCEPTION = 697; + /// {Object Exists} An attempt was made to create an object and the object name already existed. pub const OBJECT_NAME_EXISTS = 698; + /// {Thread Suspended} A thread termination occurred while the thread was suspended. The thread was resumed, and termination proceeded. pub const THREAD_WAS_SUSPENDED = 699; + /// {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. pub const IMAGE_NOT_AT_BASE = 700; + /// This informational level status indicates that a specified registry sub-tree transaction state did not yet exist and had to be created. pub const RXACT_STATE_CREATED = 701; + /// {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. pub const SEGMENT_NOTIFICATION = 702; + /// {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. pub const BAD_CURRENT_DIRECTORY = 703; + /// {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. pub const FT_READ_RECOVERY_FROM_BACKUP = 704; + /// {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. pub const FT_WRITE_RECOVERY = 705; + /// {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. pub const IMAGE_MACHINE_TYPE_MISMATCH = 706; + /// {Partial Data Received} The network transport returned partial data to its client. The remaining data will be sent later. pub const RECEIVE_PARTIAL = 707; + /// {Expedited Data Received} The network transport returned data to its client that was marked as expedited by the remote system. pub const RECEIVE_EXPEDITED = 708; + /// {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. pub const RECEIVE_PARTIAL_EXPEDITED = 709; + /// {TDI Event Done} The TDI indication has completed successfully. pub const EVENT_DONE = 710; + /// {TDI Event Pending} The TDI indication has entered the pending state. pub const EVENT_PENDING = 711; + /// Checking file system on %wZ. pub const CHECKING_FILE_SYSTEM = 712; + /// {Fatal Application Exit} %hs. pub const FATAL_APP_EXIT = 713; + /// The specified registry key is referenced by a predefined handle. pub const PREDEFINED_HANDLE = 714; + /// {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. pub const WAS_UNLOCKED = 715; + /// %hs pub const SERVICE_NOTIFICATION = 716; + /// {Page Locked} One of the pages to lock was already locked. pub const WAS_LOCKED = 717; + /// Application popup: %1 : %2 pub const LOG_HARD_ERROR = 718; + /// ERROR_ALREADY_WIN32 pub const ALREADY_WIN32 = 719; + /// {Machine Type Mismatch} The image file %hs is valid, but is for a machine type other than the current machine. pub const IMAGE_MACHINE_TYPE_MISMATCH_EXE = 720; + /// A yield execution was performed and no thread was available to run. pub const NO_YIELD_PERFORMED = 721; + /// The resumable flag to a timer API was ignored. pub const TIMER_RESUME_IGNORED = 722; + /// The arbiter has deferred arbitration of these resources to its parent. pub const ARBITRATION_UNHANDLED = 723; + /// The inserted CardBus device cannot be started because of a configuration error on "%hs". pub const CARDBUS_NOT_SUPPORTED = 724; + /// 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. pub const MP_PROCESSOR_MISMATCH = 725; + /// The system was put into hibernation. pub const HIBERNATED = 726; + /// The system was resumed from hibernation. pub const RESUME_HIBERNATION = 727; + /// Windows has detected that the system firmware (BIOS) was updated [previous firmware date = %2, current firmware date %3]. pub const FIRMWARE_UPDATED = 728; + /// 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. pub const DRIVERS_LEAKING_LOCKED_PAGES = 729; + /// The system has awoken. pub const WAKE_SYSTEM = 730; + /// ERROR_WAIT_1 pub const WAIT_1 = 731; + /// ERROR_WAIT_2 pub const WAIT_2 = 732; + /// ERROR_WAIT_3 pub const WAIT_3 = 733; + /// ERROR_WAIT_63 pub const WAIT_63 = 734; + /// ERROR_ABANDONED_WAIT_0 pub const ABANDONED_WAIT_0 = 735; + /// ERROR_ABANDONED_WAIT_63 pub const ABANDONED_WAIT_63 = 736; + /// ERROR_USER_APC pub const USER_APC = 737; + /// ERROR_KERNEL_APC pub const KERNEL_APC = 738; + /// ERROR_ALERTED pub const ALERTED = 739; + /// The requested operation requires elevation. pub const ELEVATION_REQUIRED = 740; + /// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link. pub const REPARSE = 741; + /// An open/create operation completed while an oplock break is underway. pub const OPLOCK_BREAK_IN_PROGRESS = 742; + /// A new volume has been mounted by a file system. pub const VOLUME_MOUNTED = 743; + /// 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. pub const RXACT_COMMITTED = 744; + /// This indicates that a notify change request has been completed due to closing the handle which made the notify change request. pub const NOTIFY_CLEANUP = 745; + /// {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. pub const PRIMARY_TRANSPORT_CONNECT_FAILED = 746; + /// Page fault was a transition fault. pub const PAGE_FAULT_TRANSITION = 747; + /// Page fault was a demand zero fault. pub const PAGE_FAULT_DEMAND_ZERO = 748; + /// Page fault was a demand zero fault. pub const PAGE_FAULT_COPY_ON_WRITE = 749; + /// Page fault was a demand zero fault. pub const PAGE_FAULT_GUARD_PAGE = 750; + /// Page fault was satisfied by reading from a secondary storage device. pub const PAGE_FAULT_PAGING_FILE = 751; + /// Cached page was locked during operation. pub const CACHE_PAGE_LOCKED = 752; + /// Crash dump exists in paging file. pub const CRASH_DUMP = 753; + /// Specified buffer contains all zeros. pub const BUFFER_ALL_ZEROS = 754; + /// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link. pub const REPARSE_OBJECT = 755; + /// The device has succeeded a query-stop and its resource requirements have changed. pub const RESOURCE_REQUIREMENTS_CHANGED = 756; + /// The translator has translated these resources into the global space and no further translations should be performed. pub const TRANSLATION_COMPLETE = 757; + /// A process being terminated has no threads to terminate. pub const NOTHING_TO_TERMINATE = 758; + /// The specified process is not part of a job. pub const PROCESS_NOT_IN_JOB = 759; + /// The specified process is part of a job. pub const PROCESS_IN_JOB = 760; + /// {Volume Shadow Copy Service} The system is now ready for hibernation. pub const VOLSNAP_HIBERNATE_READY = 761; + /// A file system or file system filter driver has successfully completed an FsFilter operation. pub const FSFILTER_OP_COMPLETED_SUCCESSFULLY = 762; + /// The specified interrupt vector was already connected. pub const INTERRUPT_VECTOR_ALREADY_CONNECTED = 763; + /// The specified interrupt vector is still connected. pub const INTERRUPT_STILL_CONNECTED = 764; + /// An operation is blocked waiting for an oplock. pub const WAIT_FOR_OPLOCK = 765; + /// Debugger handled exception. pub const DBG_EXCEPTION_HANDLED = 766; + /// Debugger continued. pub const DBG_CONTINUE = 767; + /// An exception occurred in a user mode callback and the kernel callback frame should be removed. pub const CALLBACK_POP_STACK = 768; + /// Compression is disabled for this volume. pub const COMPRESSION_DISABLED = 769; + /// The data provider cannot fetch backwards through a result set. pub const CANTFETCHBACKWARDS = 770; + /// The data provider cannot scroll backwards through a result set. pub const CANTSCROLLBACKWARDS = 771; + /// The data provider requires that previously fetched data is released before asking for more data. pub const ROWSNOTRELEASED = 772; + /// The data provider was not able to interpret the flags set for a column binding in an accessor. pub const BAD_ACCESSOR_FLAGS = 773; + /// One or more errors occurred while processing the request. pub const ERRORS_ENCOUNTERED = 774; + /// The implementation is not capable of performing the request. pub const NOT_CAPABLE = 775; + /// The client of a component requested an operation which is not valid given the state of the component instance. pub const REQUEST_OUT_OF_SEQUENCE = 776; + /// A version number could not be parsed. pub const VERSION_PARSE_ERROR = 777; + /// The iterator's start position is invalid. pub const BADSTARTPOSITION = 778; + /// The hardware has reported an uncorrectable memory error. pub const MEMORY_HARDWARE = 779; + /// The attempted operation required self healing to be enabled. pub const DISK_REPAIR_DISABLED = 780; + /// The Desktop heap encountered an error while allocating session memory. There is more information in the system event log. pub const INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE = 781; + /// The system power state is transitioning from %2 to %3. pub const SYSTEM_POWERSTATE_TRANSITION = 782; + /// The system power state is transitioning from %2 to %3 but could enter %4. pub const SYSTEM_POWERSTATE_COMPLEX_TRANSITION = 783; + /// A thread is getting dispatched with MCA EXCEPTION because of MCA. pub const MCA_EXCEPTION = 784; + /// Access to %1 is monitored by policy rule %2. pub const ACCESS_AUDIT_BY_POLICY = 785; + /// Access to %1 has been restricted by your Administrator by policy rule %2. pub const ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY = 786; + /// A valid hibernation file has been invalidated and should be abandoned. pub const ABANDON_HIBERFILE = 787; + /// {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. pub const LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED = 788; + /// {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. pub const LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR = 789; + /// {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. pub const LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR = 790; + /// The resources required for this device conflict with the MCFG table. pub const BAD_MCFG_TABLE = 791; + /// The volume repair could not be performed while it is online. Please schedule to take the volume offline so that it can be repaired. pub const DISK_REPAIR_REDIRECTED = 792; + /// The volume repair was not successful. pub const DISK_REPAIR_UNSUCCESSFUL = 793; + /// One of the volume corruption logs is full. Further corruptions that may be detected won't be logged. pub const CORRUPT_LOG_OVERFULL = 794; + /// One of the volume corruption logs is internally corrupted and needs to be recreated. The volume may contain undetected corruptions and must be scanned. pub const CORRUPT_LOG_CORRUPTED = 795; + /// One of the volume corruption logs is unavailable for being operated on. pub const CORRUPT_LOG_UNAVAILABLE = 796; + /// One of the volume corruption logs was deleted while still having corruption records in them. The volume contains detected corruptions and must be scanned. pub const CORRUPT_LOG_DELETED_FULL = 797; + /// One of the volume corruption logs was cleared by chkdsk and no longer contains real corruptions. pub const CORRUPT_LOG_CLEARED = 798; + /// 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. pub const ORPHAN_NAME_EXHAUSTED = 799; + /// The oplock that was associated with this handle is now associated with a different handle. pub const OPLOCK_SWITCHED_TO_NEW_HANDLE = 800; + /// An oplock of the requested level cannot be granted. An oplock of a lower level may be available. pub const CANNOT_GRANT_REQUESTED_OPLOCK = 801; + /// 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. pub const CANNOT_BREAK_OPLOCK = 802; + /// The handle with which this oplock was associated has been closed. The oplock is now broken. pub const OPLOCK_HANDLE_CLOSED = 803; + /// The specified access control entry (ACE) does not contain a condition. pub const NO_ACE_CONDITION = 804; + /// The specified access control entry (ACE) contains an invalid condition. pub const INVALID_ACE_CONDITION = 805; + /// Access to the specified file handle has been revoked. pub const FILE_HANDLE_REVOKED = 806; + /// 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. pub const IMAGE_AT_DIFFERENT_BASE = 807; + /// Access to the extended attribute was denied. pub const EA_ACCESS_DENIED = 994; + /// The I/O operation has been aborted because of either a thread exit or an application request. pub const OPERATION_ABORTED = 995; + /// Overlapped I/O event is not in a signaled state. pub const IO_INCOMPLETE = 996; + /// Overlapped I/O operation is in progress. pub const IO_PENDING = 997; + /// Invalid access to memory location. pub const NOACCESS = 998; + /// Error performing inpage operation. pub const SWAPERROR = 999; + /// Recursion too deep; the stack overflowed. pub const STACK_OVERFLOW = 1001; + /// The window cannot act on the sent message. pub const INVALID_MESSAGE = 1002; + /// Cannot complete this function. pub const CAN_NOT_COMPLETE = 1003; + /// Invalid flags. pub const INVALID_FLAGS = 1004; + /// 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. pub const UNRECOGNIZED_VOLUME = 1005; + /// The volume for a file has been externally altered so that the opened file is no longer valid. pub const FILE_INVALID = 1006; + /// The requested operation cannot be performed in full-screen mode. pub const FULLSCREEN_MODE = 1007; + /// An attempt was made to reference a token that does not exist. pub const NO_TOKEN = 1008; + /// The configuration registry database is corrupt. pub const BADDB = 1009; + /// The configuration registry key is invalid. pub const BADKEY = 1010; + /// The configuration registry key could not be opened. pub const CANTOPEN = 1011; + /// The configuration registry key could not be read. pub const CANTREAD = 1012; + /// The configuration registry key could not be written. pub const CANTWRITE = 1013; + /// One of the files in the registry database had to be recovered by use of a log or alternate copy. The recovery was successful. pub const REGISTRY_RECOVERED = 1014; + /// 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. pub const REGISTRY_CORRUPT = 1015; + /// 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. pub const REGISTRY_IO_FAILED = 1016; + /// The system has attempted to load or restore a file into the registry, but the specified file is not in a registry file format. pub const NOT_REGISTRY_FILE = 1017; + /// Illegal operation attempted on a registry key that has been marked for deletion. pub const KEY_DELETED = 1018; + /// System could not allocate the required space in a registry log. pub const NO_LOG_SPACE = 1019; + /// Cannot create a symbolic link in a registry key that already has subkeys or values. pub const KEY_HAS_CHILDREN = 1020; + /// Cannot create a stable subkey under a volatile parent key. pub const CHILD_MUST_BE_VOLATILE = 1021; + /// 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. pub const NOTIFY_ENUM_DIR = 1022; + /// A stop control has been sent to a service that other running services are dependent on. pub const DEPENDENT_SERVICES_RUNNING = 1051; + /// The requested control is not valid for this service. pub const INVALID_SERVICE_CONTROL = 1052; + /// The service did not respond to the start or control request in a timely fashion. pub const SERVICE_REQUEST_TIMEOUT = 1053; + /// A thread could not be created for the service. pub const SERVICE_NO_THREAD = 1054; + /// The service database is locked. pub const SERVICE_DATABASE_LOCKED = 1055; + /// An instance of the service is already running. pub const SERVICE_ALREADY_RUNNING = 1056; + /// The account name is invalid or does not exist, or the password is invalid for the account name specified. pub const INVALID_SERVICE_ACCOUNT = 1057; + /// The service cannot be started, either because it is disabled or because it has no enabled devices associated with it. pub const SERVICE_DISABLED = 1058; + /// Circular service dependency was specified. pub const CIRCULAR_DEPENDENCY = 1059; + /// The specified service does not exist as an installed service. pub const SERVICE_DOES_NOT_EXIST = 1060; + /// The service cannot accept control messages at this time. pub const SERVICE_CANNOT_ACCEPT_CTRL = 1061; + /// The service has not been started. pub const SERVICE_NOT_ACTIVE = 1062; + /// The service process could not connect to the service controller. pub const FAILED_SERVICE_CONTROLLER_CONNECT = 1063; + /// An exception occurred in the service when handling the control request. pub const EXCEPTION_IN_SERVICE = 1064; + /// The database specified does not exist. pub const DATABASE_DOES_NOT_EXIST = 1065; + /// The service has returned a service-specific error code. pub const SERVICE_SPECIFIC_ERROR = 1066; + /// The process terminated unexpectedly. pub const PROCESS_ABORTED = 1067; + /// The dependency service or group failed to start. pub const SERVICE_DEPENDENCY_FAIL = 1068; + /// The service did not start due to a logon failure. pub const SERVICE_LOGON_FAILED = 1069; + /// After starting, the service hung in a start-pending state. pub const SERVICE_START_HANG = 1070; + /// The specified service database lock is invalid. pub const INVALID_SERVICE_LOCK = 1071; + /// The specified service has been marked for deletion. pub const SERVICE_MARKED_FOR_DELETE = 1072; + /// The specified service already exists. pub const SERVICE_EXISTS = 1073; + /// The system is currently running with the last-known-good configuration. pub const ALREADY_RUNNING_LKG = 1074; + /// The dependency service does not exist or has been marked for deletion. pub const SERVICE_DEPENDENCY_DELETED = 1075; + /// The current boot has already been accepted for use as the last-known-good control set. pub const BOOT_ALREADY_ACCEPTED = 1076; + /// No attempts to start the service have been made since the last boot. pub const SERVICE_NEVER_STARTED = 1077; + /// The name is already in use as either a service name or a service display name. pub const DUPLICATE_SERVICE_NAME = 1078; + /// The account specified for this service is different from the account specified for other services running in the same process. pub const DIFFERENT_SERVICE_ACCOUNT = 1079; + /// Failure actions can only be set for Win32 services, not for drivers. pub const CANNOT_DETECT_DRIVER_FAILURE = 1080; + /// 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. pub const CANNOT_DETECT_PROCESS_ABORT = 1081; + /// No recovery program has been configured for this service. pub const NO_RECOVERY_PROGRAM = 1082; + /// The executable program that this service is configured to run in does not implement the service. pub const SERVICE_NOT_IN_EXE = 1083; + /// This service cannot be started in Safe Mode. pub const NOT_SAFEBOOT_SERVICE = 1084; + /// The physical end of the tape has been reached. pub const END_OF_MEDIA = 1100; + /// A tape access reached a filemark. pub const FILEMARK_DETECTED = 1101; + /// The beginning of the tape or a partition was encountered. pub const BEGINNING_OF_MEDIA = 1102; + /// A tape access reached the end of a set of files. pub const SETMARK_DETECTED = 1103; + /// No more data is on the tape. pub const NO_DATA_DETECTED = 1104; + /// Tape could not be partitioned. pub const PARTITION_FAILURE = 1105; + /// When accessing a new tape of a multivolume partition, the current block size is incorrect. pub const INVALID_BLOCK_LENGTH = 1106; + /// Tape partition information could not be found when loading a tape. pub const DEVICE_NOT_PARTITIONED = 1107; + /// Unable to lock the media eject mechanism. pub const UNABLE_TO_LOCK_MEDIA = 1108; + /// Unable to unload the media. pub const UNABLE_TO_UNLOAD_MEDIA = 1109; + /// The media in the drive may have changed. pub const MEDIA_CHANGED = 1110; + /// The I/O bus was reset. pub const BUS_RESET = 1111; + /// No media in drive. pub const NO_MEDIA_IN_DRIVE = 1112; + /// No mapping for the Unicode character exists in the target multi-byte code page. pub const NO_UNICODE_TRANSLATION = 1113; + /// A dynamic link library (DLL) initialization routine failed. pub const DLL_INIT_FAILED = 1114; + /// A system shutdown is in progress. pub const SHUTDOWN_IN_PROGRESS = 1115; + /// Unable to abort the system shutdown because no shutdown was in progress. pub const NO_SHUTDOWN_IN_PROGRESS = 1116; + /// The request could not be performed because of an I/O device error. pub const IO_DEVICE = 1117; + /// No serial device was successfully initialized. The serial driver will unload. pub const SERIAL_NO_DEVICE = 1118; + /// 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. pub const IRQ_BUSY = 1119; + /// A serial I/O operation was completed by another write to the serial port. The IOCTL_SERIAL_XOFF_COUNTER reached zero.) pub const MORE_WRITES = 1120; + /// A serial I/O operation completed because the timeout period expired. The IOCTL_SERIAL_XOFF_COUNTER did not reach zero.) pub const COUNTER_TIMEOUT = 1121; + /// No ID address mark was found on the floppy disk. pub const FLOPPY_ID_MARK_NOT_FOUND = 1122; + /// Mismatch between the floppy disk sector ID field and the floppy disk controller track address. pub const FLOPPY_WRONG_CYLINDER = 1123; + /// The floppy disk controller reported an error that is not recognized by the floppy disk driver. pub const FLOPPY_UNKNOWN_ERROR = 1124; + /// The floppy disk controller returned inconsistent results in its registers. pub const FLOPPY_BAD_REGISTERS = 1125; + /// While accessing the hard disk, a recalibrate operation failed, even after retries. pub const DISK_RECALIBRATE_FAILED = 1126; + /// While accessing the hard disk, a disk operation failed even after retries. pub const DISK_OPERATION_FAILED = 1127; + /// While accessing the hard disk, a disk controller reset was needed, but even that failed. pub const DISK_RESET_FAILED = 1128; + /// Physical end of tape encountered. pub const EOM_OVERFLOW = 1129; + /// Not enough server storage is available to process this command. pub const NOT_ENOUGH_SERVER_MEMORY = 1130; + /// A potential deadlock condition has been detected. pub const POSSIBLE_DEADLOCK = 1131; + /// The base address or the file offset specified does not have the proper alignment. pub const MAPPED_ALIGNMENT = 1132; + /// An attempt to change the system power state was vetoed by another application or driver. pub const SET_POWER_STATE_VETOED = 1140; + /// The system BIOS failed an attempt to change the system power state. pub const SET_POWER_STATE_FAILED = 1141; + /// An attempt was made to create more links on a file than the file system supports. pub const TOO_MANY_LINKS = 1142; + /// The specified program requires a newer version of Windows. pub const OLD_WIN_VERSION = 1150; + /// The specified program is not a Windows or MS-DOS program. pub const APP_WRONG_OS = 1151; + /// Cannot start more than one instance of the specified program. pub const SINGLE_INSTANCE_APP = 1152; + /// The specified program was written for an earlier version of Windows. pub const RMODE_APP = 1153; + /// One of the library files needed to run this application is damaged. pub const INVALID_DLL = 1154; + /// No application is associated with the specified file for this operation. pub const NO_ASSOCIATION = 1155; + /// An error occurred in sending the command to the application. pub const DDE_FAIL = 1156; + /// One of the library files needed to run this application cannot be found. pub const DLL_NOT_FOUND = 1157; + /// The current process has used all of its system allowance of handles for Window Manager objects. pub const NO_MORE_USER_HANDLES = 1158; + /// The message can be used only with synchronous operations. pub const MESSAGE_SYNC_ONLY = 1159; + /// The indicated source element has no media. pub const SOURCE_ELEMENT_EMPTY = 1160; + /// The indicated destination element already contains media. pub const DESTINATION_ELEMENT_FULL = 1161; + /// The indicated element does not exist. pub const ILLEGAL_ELEMENT_ADDRESS = 1162; + /// The indicated element is part of a magazine that is not present. pub const MAGAZINE_NOT_PRESENT = 1163; + /// The indicated device requires reinitialization due to hardware errors. pub const DEVICE_REINITIALIZATION_NEEDED = 1164; + /// The device has indicated that cleaning is required before further operations are attempted. pub const DEVICE_REQUIRES_CLEANING = 1165; + /// The device has indicated that its door is open. pub const DEVICE_DOOR_OPEN = 1166; + /// The device is not connected. pub const DEVICE_NOT_CONNECTED = 1167; + /// Element not found. pub const NOT_FOUND = 1168; + /// There was no match for the specified key in the index. pub const NO_MATCH = 1169; + /// The property set specified does not exist on the object. pub const SET_NOT_FOUND = 1170; + /// The point passed to GetMouseMovePoints is not in the buffer. pub const POINT_NOT_FOUND = 1171; + /// The tracking (workstation) service is not running. pub const NO_TRACKING_SERVICE = 1172; + /// The Volume ID could not be found. pub const NO_VOLUME_ID = 1173; + /// Unable to remove the file to be replaced. pub const UNABLE_TO_REMOVE_REPLACED = 1175; + /// Unable to move the replacement file to the file to be replaced. The file to be replaced has retained its original name. pub const UNABLE_TO_MOVE_REPLACEMENT = 1176; + /// Unable to move the replacement file to the file to be replaced. The file to be replaced has been renamed using the backup name. pub const UNABLE_TO_MOVE_REPLACEMENT_2 = 1177; + /// The volume change journal is being deleted. pub const JOURNAL_DELETE_IN_PROGRESS = 1178; + /// The volume change journal is not active. pub const JOURNAL_NOT_ACTIVE = 1179; + /// A file was found, but it may not be the correct file. pub const POTENTIAL_FILE_FOUND = 1180; + /// The journal entry has been deleted from the journal. pub const JOURNAL_ENTRY_DELETED = 1181; + /// A system shutdown has already been scheduled. pub const SHUTDOWN_IS_SCHEDULED = 1190; + /// The system shutdown cannot be initiated because there are other users logged on to the computer. pub const SHUTDOWN_USERS_LOGGED_ON = 1191; + /// The specified device name is invalid. pub const BAD_DEVICE = 1200; + /// The device is not currently connected but it is a remembered connection. pub const CONNECTION_UNAVAIL = 1201; + /// The local device name has a remembered connection to another network resource. pub const DEVICE_ALREADY_REMEMBERED = 1202; + /// 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. pub const NO_NET_OR_BAD_PATH = 1203; + /// The specified network provider name is invalid. pub const BAD_PROVIDER = 1204; + /// Unable to open the network connection profile. pub const CANNOT_OPEN_PROFILE = 1205; + /// The network connection profile is corrupted. pub const BAD_PROFILE = 1206; + /// Cannot enumerate a noncontainer. pub const NOT_CONTAINER = 1207; + /// An extended error has occurred. pub const EXTENDED_ERROR = 1208; + /// The format of the specified group name is invalid. pub const INVALID_GROUPNAME = 1209; + /// The format of the specified computer name is invalid. pub const INVALID_COMPUTERNAME = 1210; + /// The format of the specified event name is invalid. pub const INVALID_EVENTNAME = 1211; + /// The format of the specified domain name is invalid. pub const INVALID_DOMAINNAME = 1212; + /// The format of the specified service name is invalid. pub const INVALID_SERVICENAME = 1213; + /// The format of the specified network name is invalid. pub const INVALID_NETNAME = 1214; + /// The format of the specified share name is invalid. pub const INVALID_SHARENAME = 1215; + /// The format of the specified password is invalid. pub const INVALID_PASSWORDNAME = 1216; + /// The format of the specified message name is invalid. pub const INVALID_MESSAGENAME = 1217; + /// The format of the specified message destination is invalid. pub const INVALID_MESSAGEDEST = 1218; + /// 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. pub const SESSION_CREDENTIAL_CONFLICT = 1219; + /// An attempt was made to establish a session to a network server, but there are already too many sessions established to that server. pub const REMOTE_SESSION_LIMIT_EXCEEDED = 1220; + /// The workgroup or domain name is already in use by another computer on the network. pub const DUP_DOMAINNAME = 1221; + /// The network is not present or not started. pub const NO_NETWORK = 1222; + /// The operation was canceled by the user. pub const CANCELLED = 1223; + /// The requested operation cannot be performed on a file with a user-mapped section open. pub const USER_MAPPED_FILE = 1224; + /// The remote computer refused the network connection. pub const CONNECTION_REFUSED = 1225; + /// The network connection was gracefully closed. pub const GRACEFUL_DISCONNECT = 1226; + /// The network transport endpoint already has an address associated with it. pub const ADDRESS_ALREADY_ASSOCIATED = 1227; + /// An address has not yet been associated with the network endpoint. pub const ADDRESS_NOT_ASSOCIATED = 1228; + /// An operation was attempted on a nonexistent network connection. pub const CONNECTION_INVALID = 1229; + /// An invalid operation was attempted on an active network connection. pub const CONNECTION_ACTIVE = 1230; + /// The network location cannot be reached. For information about network troubleshooting, see Windows Help. pub const NETWORK_UNREACHABLE = 1231; + /// The network location cannot be reached. For information about network troubleshooting, see Windows Help. pub const HOST_UNREACHABLE = 1232; + /// The network location cannot be reached. For information about network troubleshooting, see Windows Help. pub const PROTOCOL_UNREACHABLE = 1233; + /// No service is operating at the destination network endpoint on the remote system. pub const PORT_UNREACHABLE = 1234; + /// The request was aborted. pub const REQUEST_ABORTED = 1235; + /// The network connection was aborted by the local system. pub const CONNECTION_ABORTED = 1236; + /// The operation could not be completed. A retry should be performed. pub const RETRY = 1237; + /// A connection to the server could not be made because the limit on the number of concurrent connections for this account has been reached. pub const CONNECTION_COUNT_LIMIT = 1238; + /// Attempting to log in during an unauthorized time of day for this account. pub const LOGIN_TIME_RESTRICTION = 1239; + /// The account is not authorized to log in from this station. pub const LOGIN_WKSTA_RESTRICTION = 1240; + /// The network address could not be used for the operation requested. pub const INCORRECT_ADDRESS = 1241; + /// The service is already registered. pub const ALREADY_REGISTERED = 1242; + /// The specified service does not exist. pub const SERVICE_NOT_FOUND = 1243; + /// The operation being requested was not performed because the user has not been authenticated. pub const NOT_AUTHENTICATED = 1244; + /// The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist. pub const NOT_LOGGED_ON = 1245; + /// Continue with work in progress. pub const CONTINUE = 1246; + /// An attempt was made to perform an initialization operation when initialization has already been completed. pub const ALREADY_INITIALIZED = 1247; + /// No more local devices. pub const NO_MORE_DEVICES = 1248; + /// The specified site does not exist. pub const NO_SUCH_SITE = 1249; + /// A domain controller with the specified name already exists. pub const DOMAIN_CONTROLLER_EXISTS = 1250; + /// This operation is supported only when you are connected to the server. pub const ONLY_IF_CONNECTED = 1251; + /// The group policy framework should call the extension even if there are no changes. pub const OVERRIDE_NOCHANGES = 1252; + /// The specified user does not have a valid profile. pub const BAD_USER_PROFILE = 1253; + /// This operation is not supported on a computer running Windows Server 2003 for Small Business Server. pub const NOT_SUPPORTED_ON_SBS = 1254; + /// The server machine is shutting down. pub const SERVER_SHUTDOWN_IN_PROGRESS = 1255; + /// The remote system is not available. For information about network troubleshooting, see Windows Help. pub const HOST_DOWN = 1256; + /// The security identifier provided is not from an account domain. pub const NON_ACCOUNT_SID = 1257; + /// The security identifier provided does not have a domain component. pub const NON_DOMAIN_SID = 1258; + /// AppHelp dialog canceled thus preventing the application from starting. pub const APPHELP_BLOCK = 1259; + /// This program is blocked by group policy. For more information, contact your system administrator. pub const ACCESS_DISABLED_BY_POLICY = 1260; + /// A program attempt to use an invalid register value. Normally caused by an uninitialized register. This error is Itanium specific. pub const REG_NAT_CONSUMPTION = 1261; + /// The share is currently offline or does not exist. pub const CSCSHARE_OFFLINE = 1262; + /// The Kerberos protocol encountered an error while validating the KDC certificate during smartcard logon. There is more information in the system event log. pub const PKINIT_FAILURE = 1263; + /// The Kerberos protocol encountered an error while attempting to utilize the smartcard subsystem. pub const SMARTCARD_SUBSYSTEM_FAILURE = 1264; + /// The system cannot contact a domain controller to service the authentication request. Please try again later. pub const DOWNGRADE_DETECTED = 1265; + /// The machine is locked and cannot be shut down without the force option. pub const MACHINE_LOCKED = 1271; + /// An application-defined callback gave invalid data when called. pub const CALLBACK_SUPPLIED_INVALID_DATA = 1273; + /// The group policy framework should call the extension in the synchronous foreground policy refresh. pub const SYNC_FOREGROUND_REFRESH_REQUIRED = 1274; + /// This driver has been blocked from loading. pub const DRIVER_BLOCKED = 1275; + /// A dynamic link library (DLL) referenced a module that was neither a DLL nor the process's executable image. pub const INVALID_IMPORT_OF_NON_DLL = 1276; + /// Windows cannot open this program since it has been disabled. pub const ACCESS_DISABLED_WEBBLADE = 1277; + /// Windows cannot open this program because the license enforcement system has been tampered with or become corrupted. pub const ACCESS_DISABLED_WEBBLADE_TAMPER = 1278; + /// A transaction recover failed. pub const RECOVERY_FAILURE = 1279; + /// The current thread has already been converted to a fiber. pub const ALREADY_FIBER = 1280; + /// The current thread has already been converted from a fiber. pub const ALREADY_THREAD = 1281; + /// 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. pub const STACK_BUFFER_OVERRUN = 1282; + /// Data present in one of the parameters is more than the function can operate on. pub const PARAMETER_QUOTA_EXCEEDED = 1283; + /// An attempt to do an operation on a debug object failed because the object is in the process of being deleted. pub const DEBUGGER_INACTIVE = 1284; + /// An attempt to delay-load a .dll or get a function address in a delay-loaded .dll failed. pub const DELAY_LOAD_FAILED = 1285; + /// %1 is a 16-bit application. You do not have permissions to execute 16-bit applications. Check your permissions with your system administrator. pub const VDM_DISALLOWED = 1286; + /// Insufficient information exists to identify the cause of failure. pub const UNIDENTIFIED_ERROR = 1287; + /// The parameter passed to a C runtime function is incorrect. pub const INVALID_CRUNTIME_PARAMETER = 1288; + /// The operation occurred beyond the valid data length of the file. pub const BEYOND_VDL = 1289; + /// 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. /// 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. pub const INCOMPATIBLE_SERVICE_SID_TYPE = 1290; + /// The process hosting the driver for this device has been terminated. pub const DRIVER_PROCESS_TERMINATED = 1291; + /// An operation attempted to exceed an implementation-defined limit. pub const IMPLEMENTATION_LIMIT = 1292; + /// Either the target process, or the target thread's containing process, is a protected process. pub const PROCESS_IS_PROTECTED = 1293; + /// The service notification client is lagging too far behind the current state of services in the machine. pub const SERVICE_NOTIFY_CLIENT_LAGGING = 1294; + /// 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. pub const DISK_QUOTA_EXCEEDED = 1295; + /// The requested file operation failed because the storage policy blocks that type of file. For more information, contact your system administrator. pub const CONTENT_BLOCKED = 1296; + /// 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. pub const INCOMPATIBLE_SERVICE_PRIVILEGE = 1297; + /// A thread involved in this operation appears to be unresponsive. pub const APP_HANG = 1298; + /// Indicates a particular Security ID may not be assigned as the label of an object. pub const INVALID_LABEL = 1299; + /// Not all privileges or groups referenced are assigned to the caller. pub const NOT_ALL_ASSIGNED = 1300; + /// Some mapping between account names and security IDs was not done. pub const SOME_NOT_MAPPED = 1301; + /// No system quota limits are specifically set for this account. pub const NO_QUOTAS_FOR_ACCOUNT = 1302; + /// No encryption key is available. A well-known encryption key was returned. pub const LOCAL_USER_SESSION_KEY = 1303; + /// The password is too complex to be converted to a LAN Manager password. The LAN Manager password returned is a NULL string. pub const NULL_LM_PASSWORD = 1304; + /// The revision level is unknown. pub const UNKNOWN_REVISION = 1305; + /// Indicates two revision levels are incompatible. pub const REVISION_MISMATCH = 1306; + /// This security ID may not be assigned as the owner of this object. pub const INVALID_OWNER = 1307; + /// This security ID may not be assigned as the primary group of an object. pub const INVALID_PRIMARY_GROUP = 1308; + /// An attempt has been made to operate on an impersonation token by a thread that is not currently impersonating a client. pub const NO_IMPERSONATION_TOKEN = 1309; + /// The group may not be disabled. pub const CANT_DISABLE_MANDATORY = 1310; + /// There are currently no logon servers available to service the logon request. pub const NO_LOGON_SERVERS = 1311; + /// A specified logon session does not exist. It may already have been terminated. pub const NO_SUCH_LOGON_SESSION = 1312; + /// A specified privilege does not exist. pub const NO_SUCH_PRIVILEGE = 1313; + /// A required privilege is not held by the client. pub const PRIVILEGE_NOT_HELD = 1314; + /// The name provided is not a properly formed account name. pub const INVALID_ACCOUNT_NAME = 1315; + /// The specified account already exists. pub const USER_EXISTS = 1316; + /// The specified account does not exist. pub const NO_SUCH_USER = 1317; + /// The specified group already exists. pub const GROUP_EXISTS = 1318; + /// The specified group does not exist. pub const NO_SUCH_GROUP = 1319; + /// 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. pub const MEMBER_IN_GROUP = 1320; + /// The specified user account is not a member of the specified group account. pub const MEMBER_NOT_IN_GROUP = 1321; + /// This operation is disallowed as it could result in an administration account being disabled, deleted or unable to log on. pub const LAST_ADMIN = 1322; + /// Unable to update the password. The value provided as the current password is incorrect. pub const WRONG_PASSWORD = 1323; + /// Unable to update the password. The value provided for the new password contains values that are not allowed in passwords. pub const ILL_FORMED_PASSWORD = 1324; + /// Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain. pub const PASSWORD_RESTRICTION = 1325; + /// The user name or password is incorrect. pub const LOGON_FAILURE = 1326; + /// 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. pub const ACCOUNT_RESTRICTION = 1327; + /// Your account has time restrictions that keep you from signing in right now. pub const INVALID_LOGON_HOURS = 1328; + /// This user isn't allowed to sign in to this computer. pub const INVALID_WORKSTATION = 1329; + /// The password for this account has expired. pub const PASSWORD_EXPIRED = 1330; + /// This user can't sign in because this account is currently disabled. pub const ACCOUNT_DISABLED = 1331; + /// No mapping between account names and security IDs was done. pub const NONE_MAPPED = 1332; + /// Too many local user identifiers (LUIDs) were requested at one time. pub const TOO_MANY_LUIDS_REQUESTED = 1333; + /// No more local user identifiers (LUIDs) are available. pub const LUIDS_EXHAUSTED = 1334; + /// The subauthority part of a security ID is invalid for this particular use. pub const INVALID_SUB_AUTHORITY = 1335; + /// The access control list (ACL) structure is invalid. pub const INVALID_ACL = 1336; + /// The security ID structure is invalid. pub const INVALID_SID = 1337; + /// The security descriptor structure is invalid. pub const INVALID_SECURITY_DESCR = 1338; + /// The inherited access control list (ACL) or access control entry (ACE) could not be built. pub const BAD_INHERITANCE_ACL = 1340; + /// The server is currently disabled. pub const SERVER_DISABLED = 1341; + /// The server is currently enabled. pub const SERVER_NOT_DISABLED = 1342; + /// The value provided was an invalid value for an identifier authority. pub const INVALID_ID_AUTHORITY = 1343; + /// No more memory is available for security information updates. pub const ALLOTTED_SPACE_EXCEEDED = 1344; + /// The specified attributes are invalid, or incompatible with the attributes for the group as a whole. pub const INVALID_GROUP_ATTRIBUTES = 1345; + /// Either a required impersonation level was not provided, or the provided impersonation level is invalid. pub const BAD_IMPERSONATION_LEVEL = 1346; + /// Cannot open an anonymous level security token. pub const CANT_OPEN_ANONYMOUS = 1347; + /// The validation information class requested was invalid. pub const BAD_VALIDATION_CLASS = 1348; + /// The type of the token is inappropriate for its attempted use. pub const BAD_TOKEN_TYPE = 1349; + /// Unable to perform a security operation on an object that has no associated security. pub const NO_SECURITY_ON_OBJECT = 1350; + /// Configuration information could not be read from the domain controller, either because the machine is unavailable, or access has been denied. pub const CANT_ACCESS_DOMAIN_INFO = 1351; + /// The security account manager (SAM) or local security authority (LSA) server was in the wrong state to perform the security operation. pub const INVALID_SERVER_STATE = 1352; + /// The domain was in the wrong state to perform the security operation. pub const INVALID_DOMAIN_STATE = 1353; + /// This operation is only allowed for the Primary Domain Controller of the domain. pub const INVALID_DOMAIN_ROLE = 1354; + /// The specified domain either does not exist or could not be contacted. pub const NO_SUCH_DOMAIN = 1355; + /// The specified domain already exists. pub const DOMAIN_EXISTS = 1356; + /// An attempt was made to exceed the limit on the number of domains per server. pub const DOMAIN_LIMIT_EXCEEDED = 1357; + /// Unable to complete the requested operation because of either a catastrophic media failure or a data structure corruption on the disk. pub const INTERNAL_DB_CORRUPTION = 1358; + /// An internal error occurred. pub const INTERNAL_ERROR = 1359; + /// Generic access types were contained in an access mask which should already be mapped to nongeneric types. pub const GENERIC_NOT_MAPPED = 1360; + /// A security descriptor is not in the right format (absolute or self-relative). pub const BAD_DESCRIPTOR_FORMAT = 1361; + /// The requested action is restricted for use by logon processes only. The calling process has not registered as a logon process. pub const NOT_LOGON_PROCESS = 1362; + /// Cannot start a new logon session with an ID that is already in use. pub const LOGON_SESSION_EXISTS = 1363; + /// A specified authentication package is unknown. pub const NO_SUCH_PACKAGE = 1364; + /// The logon session is not in a state that is consistent with the requested operation. pub const BAD_LOGON_SESSION_STATE = 1365; + /// The logon session ID is already in use. pub const LOGON_SESSION_COLLISION = 1366; + /// A logon request contained an invalid logon type value. pub const INVALID_LOGON_TYPE = 1367; + /// Unable to impersonate using a named pipe until data has been read from that pipe. pub const CANNOT_IMPERSONATE = 1368; + /// The transaction state of a registry subtree is incompatible with the requested operation. pub const RXACT_INVALID_STATE = 1369; + /// An internal security database corruption has been encountered. pub const RXACT_COMMIT_FAILURE = 1370; + /// Cannot perform this operation on built-in accounts. pub const SPECIAL_ACCOUNT = 1371; + /// Cannot perform this operation on this built-in special group. pub const SPECIAL_GROUP = 1372; + /// Cannot perform this operation on this built-in special user. pub const SPECIAL_USER = 1373; + /// The user cannot be removed from a group because the group is currently the user's primary group. pub const MEMBERS_PRIMARY_GROUP = 1374; + /// The token is already in use as a primary token. pub const TOKEN_ALREADY_IN_USE = 1375; + /// The specified local group does not exist. pub const NO_SUCH_ALIAS = 1376; + /// The specified account name is not a member of the group. pub const MEMBER_NOT_IN_ALIAS = 1377; + /// The specified account name is already a member of the group. pub const MEMBER_IN_ALIAS = 1378; + /// The specified local group already exists. pub const ALIAS_EXISTS = 1379; + /// Logon failure: the user has not been granted the requested logon type at this computer. pub const LOGON_NOT_GRANTED = 1380; + /// The maximum number of secrets that may be stored in a single system has been exceeded. pub const TOO_MANY_SECRETS = 1381; + /// The length of a secret exceeds the maximum length allowed. pub const SECRET_TOO_LONG = 1382; + /// The local security authority database contains an internal inconsistency. pub const INTERNAL_DB_ERROR = 1383; + /// During a logon attempt, the user's security context accumulated too many security IDs. pub const TOO_MANY_CONTEXT_IDS = 1384; + /// Logon failure: the user has not been granted the requested logon type at this computer. pub const LOGON_TYPE_NOT_GRANTED = 1385; + /// A cross-encrypted password is necessary to change a user password. pub const NT_CROSS_ENCRYPTION_REQUIRED = 1386; + /// A member could not be added to or removed from the local group because the member does not exist. pub const NO_SUCH_MEMBER = 1387; + /// A new member could not be added to a local group because the member has the wrong account type. pub const INVALID_MEMBER = 1388; + /// Too many security IDs have been specified. pub const TOO_MANY_SIDS = 1389; + /// A cross-encrypted password is necessary to change this user password. pub const LM_CROSS_ENCRYPTION_REQUIRED = 1390; + /// Indicates an ACL contains no inheritable components. pub const NO_INHERITANCE = 1391; + /// The file or directory is corrupted and unreadable. pub const FILE_CORRUPT = 1392; + /// The disk structure is corrupted and unreadable. pub const DISK_CORRUPT = 1393; + /// There is no user session key for the specified logon session. pub const NO_USER_SESSION_KEY = 1394; + /// 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. pub const LICENSE_QUOTA_EXCEEDED = 1395; + /// The target account name is incorrect. pub const WRONG_TARGET_NAME = 1396; + /// Mutual Authentication failed. The server's password is out of date at the domain controller. pub const MUTUAL_AUTH_FAILED = 1397; + /// There is a time and/or date difference between the client and server. pub const TIME_SKEW = 1398; + /// This operation cannot be performed on the current domain. pub const CURRENT_DOMAIN_NOT_ALLOWED = 1399; + /// Invalid window handle. pub const INVALID_WINDOW_HANDLE = 1400; + /// Invalid menu handle. pub const INVALID_MENU_HANDLE = 1401; + /// Invalid cursor handle. pub const INVALID_CURSOR_HANDLE = 1402; + /// Invalid accelerator table handle. pub const INVALID_ACCEL_HANDLE = 1403; + /// Invalid hook handle. pub const INVALID_HOOK_HANDLE = 1404; + /// Invalid handle to a multiple-window position structure. pub const INVALID_DWP_HANDLE = 1405; + /// Cannot create a top-level child window. pub const TLW_WITH_WSCHILD = 1406; + /// Cannot find window class. pub const CANNOT_FIND_WND_CLASS = 1407; + /// Invalid window; it belongs to other thread. pub const WINDOW_OF_OTHER_THREAD = 1408; + /// Hot key is already registered. pub const HOTKEY_ALREADY_REGISTERED = 1409; + /// Class already exists. pub const CLASS_ALREADY_EXISTS = 1410; + /// Class does not exist. pub const CLASS_DOES_NOT_EXIST = 1411; + /// Class still has open windows. pub const CLASS_HAS_WINDOWS = 1412; + /// Invalid index. pub const INVALID_INDEX = 1413; + /// Invalid icon handle. pub const INVALID_ICON_HANDLE = 1414; + /// Using private DIALOG window words. pub const PRIVATE_DIALOG_INDEX = 1415; + /// The list box identifier was not found. pub const LISTBOX_ID_NOT_FOUND = 1416; + /// No wildcards were found. pub const NO_WILDCARD_CHARACTERS = 1417; + /// Thread does not have a clipboard open. pub const CLIPBOARD_NOT_OPEN = 1418; + /// Hot key is not registered. pub const HOTKEY_NOT_REGISTERED = 1419; + /// The window is not a valid dialog window. pub const WINDOW_NOT_DIALOG = 1420; + /// Control ID not found. pub const CONTROL_ID_NOT_FOUND = 1421; + /// Invalid message for a combo box because it does not have an edit control. pub const INVALID_COMBOBOX_MESSAGE = 1422; + /// The window is not a combo box. pub const WINDOW_NOT_COMBOBOX = 1423; + /// Height must be less than 256. pub const INVALID_EDIT_HEIGHT = 1424; + /// Invalid device context (DC) handle. pub const DC_NOT_FOUND = 1425; + /// Invalid hook procedure type. pub const INVALID_HOOK_FILTER = 1426; + /// Invalid hook procedure. pub const INVALID_FILTER_PROC = 1427; + /// Cannot set nonlocal hook without a module handle. pub const HOOK_NEEDS_HMOD = 1428; + /// This hook procedure can only be set globally. pub const GLOBAL_ONLY_HOOK = 1429; + /// The journal hook procedure is already installed. pub const JOURNAL_HOOK_SET = 1430; + /// The hook procedure is not installed. pub const HOOK_NOT_INSTALLED = 1431; + /// Invalid message for single-selection list box. pub const INVALID_LB_MESSAGE = 1432; + /// LB_SETCOUNT sent to non-lazy list box. pub const SETCOUNT_ON_BAD_LB = 1433; + /// This list box does not support tab stops. pub const LB_WITHOUT_TABSTOPS = 1434; + /// Cannot destroy object created by another thread. pub const DESTROY_OBJECT_OF_OTHER_THREAD = 1435; + /// Child windows cannot have menus. pub const CHILD_WINDOW_MENU = 1436; + /// The window does not have a system menu. pub const NO_SYSTEM_MENU = 1437; + /// Invalid message box style. pub const INVALID_MSGBOX_STYLE = 1438; + /// Invalid system-wide (SPI_*) parameter. pub const INVALID_SPI_VALUE = 1439; + /// Screen already locked. pub const SCREEN_ALREADY_LOCKED = 1440; + /// All handles to windows in a multiple-window position structure must have the same parent. pub const HWNDS_HAVE_DIFF_PARENT = 1441; + /// The window is not a child window. pub const NOT_CHILD_WINDOW = 1442; + /// Invalid GW_* command. pub const INVALID_GW_COMMAND = 1443; + /// Invalid thread identifier. pub const INVALID_THREAD_ID = 1444; + /// Cannot process a message from a window that is not a multiple document interface (MDI) window. pub const NON_MDICHILD_WINDOW = 1445; + /// Popup menu already active. pub const POPUP_ALREADY_ACTIVE = 1446; + /// The window does not have scroll bars. pub const NO_SCROLLBARS = 1447; + /// Scroll bar range cannot be greater than MAXLONG. pub const INVALID_SCROLLBAR_RANGE = 1448; + /// Cannot show or remove the window in the way specified. pub const INVALID_SHOWWIN_COMMAND = 1449; + /// Insufficient system resources exist to complete the requested service. pub const NO_SYSTEM_RESOURCES = 1450; + /// Insufficient system resources exist to complete the requested service. pub const NONPAGED_SYSTEM_RESOURCES = 1451; + /// Insufficient system resources exist to complete the requested service. pub const PAGED_SYSTEM_RESOURCES = 1452; + /// Insufficient quota to complete the requested service. pub const WORKING_SET_QUOTA = 1453; + /// Insufficient quota to complete the requested service. pub const PAGEFILE_QUOTA = 1454; + /// The paging file is too small for this operation to complete. pub const COMMITMENT_LIMIT = 1455; + /// A menu item was not found. pub const MENU_ITEM_NOT_FOUND = 1456; + /// Invalid keyboard layout handle. pub const INVALID_KEYBOARD_HANDLE = 1457; + /// Hook type not allowed. pub const HOOK_TYPE_NOT_ALLOWED = 1458; + /// This operation requires an interactive window station. pub const REQUIRES_INTERACTIVE_WINDOWSTATION = 1459; + /// This operation returned because the timeout period expired. pub const TIMEOUT = 1460; + /// Invalid monitor handle. pub const INVALID_MONITOR_HANDLE = 1461; + /// Incorrect size argument. pub const INCORRECT_SIZE = 1462; + /// The symbolic link cannot be followed because its type is disabled. pub const SYMLINK_CLASS_DISABLED = 1463; + /// This application does not support the current operation on symbolic links. pub const SYMLINK_NOT_SUPPORTED = 1464; + /// Windows was unable to parse the requested XML data. pub const XML_PARSE_ERROR = 1465; + /// An error was encountered while processing an XML digital signature. pub const XMLDSIG_ERROR = 1466; + /// This application must be restarted. pub const RESTART_APPLICATION = 1467; + /// The caller made the connection request in the wrong routing compartment. pub const WRONG_COMPARTMENT = 1468; + /// There was an AuthIP failure when attempting to connect to the remote host. pub const AUTHIP_FAILURE = 1469; + /// Insufficient NVRAM resources exist to complete the requested service. A reboot might be required. pub const NO_NVRAM_RESOURCES = 1470; + /// Unable to finish the requested operation because the specified process is not a GUI process. pub const NOT_GUI_PROCESS = 1471; + /// The event log file is corrupted. pub const EVENTLOG_FILE_CORRUPT = 1500; + /// No event log file could be opened, so the event logging service did not start. pub const EVENTLOG_CANT_START = 1501; + /// The event log file is full. pub const LOG_FILE_FULL = 1502; + /// The event log file has changed between read operations. pub const EVENTLOG_FILE_CHANGED = 1503; + /// The specified task name is invalid. pub const INVALID_TASK_NAME = 1550; + /// The specified task index is invalid. pub const INVALID_TASK_INDEX = 1551; + /// The specified thread is already joining a task. pub const THREAD_ALREADY_IN_TASK = 1552; + /// 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. pub const INSTALL_SERVICE_FAILURE = 1601; + /// User cancelled installation. pub const INSTALL_USEREXIT = 1602; + /// Fatal error during installation. pub const INSTALL_FAILURE = 1603; + /// Installation suspended, incomplete. pub const INSTALL_SUSPEND = 1604; + /// This action is only valid for products that are currently installed. pub const UNKNOWN_PRODUCT = 1605; + /// Feature ID not registered. pub const UNKNOWN_FEATURE = 1606; + /// Component ID not registered. pub const UNKNOWN_COMPONENT = 1607; + /// Unknown property. pub const UNKNOWN_PROPERTY = 1608; + /// Handle is in an invalid state. pub const INVALID_HANDLE_STATE = 1609; + /// The configuration data for this product is corrupt. Contact your support personnel. pub const BAD_CONFIGURATION = 1610; + /// Component qualifier not present. pub const INDEX_ABSENT = 1611; + /// The installation source for this product is not available. Verify that the source exists and that you can access it. pub const INSTALL_SOURCE_ABSENT = 1612; + /// 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. pub const INSTALL_PACKAGE_VERSION = 1613; + /// Product is uninstalled. pub const PRODUCT_UNINSTALLED = 1614; + /// SQL query syntax invalid or unsupported. pub const BAD_QUERY_SYNTAX = 1615; + /// Record field does not exist. pub const INVALID_FIELD = 1616; + /// The device has been removed. pub const DEVICE_REMOVED = 1617; + /// Another installation is already in progress. Complete that installation before proceeding with this install. pub const INSTALL_ALREADY_RUNNING = 1618; + /// 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. pub const INSTALL_PACKAGE_OPEN_FAILED = 1619; + /// This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package. pub const INSTALL_PACKAGE_INVALID = 1620; + /// There was an error starting the Windows Installer service user interface. Contact your support personnel. pub const INSTALL_UI_FAILURE = 1621; + /// Error opening installation log file. Verify that the specified log file location exists and that you can write to it. pub const INSTALL_LOG_FAILURE = 1622; + /// The language of this installation package is not supported by your system. pub const INSTALL_LANGUAGE_UNSUPPORTED = 1623; + /// Error applying transforms. Verify that the specified transform paths are valid. pub const INSTALL_TRANSFORM_FAILURE = 1624; + /// This installation is forbidden by system policy. Contact your system administrator. pub const INSTALL_PACKAGE_REJECTED = 1625; + /// Function could not be executed. pub const FUNCTION_NOT_CALLED = 1626; + /// Function failed during execution. pub const FUNCTION_FAILED = 1627; + /// Invalid or unknown table specified. pub const INVALID_TABLE = 1628; + /// Data supplied is of wrong type. pub const DATATYPE_MISMATCH = 1629; + /// Data of this type is not supported. pub const UNSUPPORTED_TYPE = 1630; + /// The Windows Installer service failed to start. Contact your support personnel. pub const CREATE_FAILED = 1631; + /// 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. pub const INSTALL_TEMP_UNWRITABLE = 1632; + /// This installation package is not supported by this processor type. Contact your product vendor. pub const INSTALL_PLATFORM_UNSUPPORTED = 1633; + /// Component not used on this computer. pub const INSTALL_NOTUSED = 1634; + /// 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. pub const PATCH_PACKAGE_OPEN_FAILED = 1635; + /// This update package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer update package. pub const PATCH_PACKAGE_INVALID = 1636; + /// 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. pub const PATCH_PACKAGE_UNSUPPORTED = 1637; + /// 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. pub const PRODUCT_VERSION = 1638; + /// Invalid command line argument. Consult the Windows Installer SDK for detailed command line help. pub const INVALID_COMMAND_LINE = 1639; + /// 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. pub const INSTALL_REMOTE_DISALLOWED = 1640; + /// The requested operation completed successfully. The system will be restarted so the changes can take effect. pub const SUCCESS_REBOOT_INITIATED = 1641; + /// 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. pub const PATCH_TARGET_NOT_FOUND = 1642; + /// The update package is not permitted by software restriction policy. pub const PATCH_PACKAGE_REJECTED = 1643; + /// One or more customizations are not permitted by software restriction policy. pub const INSTALL_TRANSFORM_REJECTED = 1644; + /// The Windows Installer does not permit installation from a Remote Desktop Connection. pub const INSTALL_REMOTE_PROHIBITED = 1645; + /// Uninstallation of the update package is not supported. pub const PATCH_REMOVAL_UNSUPPORTED = 1646; + /// The update is not applied to this product. pub const UNKNOWN_PATCH = 1647; + /// No valid sequence could be found for the set of updates. pub const PATCH_NO_SEQUENCE = 1648; + /// Update removal was disallowed by policy. pub const PATCH_REMOVAL_DISALLOWED = 1649; + /// The XML update data is invalid. pub const INVALID_PATCH_XML = 1650; + /// Windows Installer does not permit updating of managed advertised products. At least one feature of the product must be installed before applying the update. pub const PATCH_MANAGED_ADVERTISED_PRODUCT = 1651; + /// 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. pub const INSTALL_SERVICE_SAFEBOOT = 1652; + /// A fail fast exception occurred. Exception handlers will not be invoked and the process will be terminated immediately. pub const FAIL_FAST_EXCEPTION = 1653; + /// The app that you are trying to run is not supported on this version of Windows. pub const INSTALL_REJECTED = 1654; + /// The string binding is invalid. pub const RPC_S_INVALID_STRING_BINDING = 1700; + /// The binding handle is not the correct type. pub const RPC_S_WRONG_KIND_OF_BINDING = 1701; + /// The binding handle is invalid. pub const RPC_S_INVALID_BINDING = 1702; + /// The RPC protocol sequence is not supported. pub const RPC_S_PROTSEQ_NOT_SUPPORTED = 1703; + /// The RPC protocol sequence is invalid. pub const RPC_S_INVALID_RPC_PROTSEQ = 1704; + /// The string universal unique identifier (UUID) is invalid. pub const RPC_S_INVALID_STRING_UUID = 1705; + /// The endpoint format is invalid. pub const RPC_S_INVALID_ENDPOINT_FORMAT = 1706; + /// The network address is invalid. pub const RPC_S_INVALID_NET_ADDR = 1707; + /// No endpoint was found. pub const RPC_S_NO_ENDPOINT_FOUND = 1708; + /// The timeout value is invalid. pub const RPC_S_INVALID_TIMEOUT = 1709; + /// The object universal unique identifier (UUID) was not found. pub const RPC_S_OBJECT_NOT_FOUND = 1710; + /// The object universal unique identifier (UUID) has already been registered. pub const RPC_S_ALREADY_REGISTERED = 1711; + /// The type universal unique identifier (UUID) has already been registered. pub const RPC_S_TYPE_ALREADY_REGISTERED = 1712; + /// The RPC server is already listening. pub const RPC_S_ALREADY_LISTENING = 1713; + /// No protocol sequences have been registered. pub const RPC_S_NO_PROTSEQS_REGISTERED = 1714; + /// The RPC server is not listening. pub const RPC_S_NOT_LISTENING = 1715; + /// The manager type is unknown. pub const RPC_S_UNKNOWN_MGR_TYPE = 1716; + /// The interface is unknown. pub const RPC_S_UNKNOWN_IF = 1717; + /// There are no bindings. pub const RPC_S_NO_BINDINGS = 1718; + /// There are no protocol sequences. pub const RPC_S_NO_PROTSEQS = 1719; + /// The endpoint cannot be created. pub const RPC_S_CANT_CREATE_ENDPOINT = 1720; + /// Not enough resources are available to complete this operation. pub const RPC_S_OUT_OF_RESOURCES = 1721; + /// The RPC server is unavailable. pub const RPC_S_SERVER_UNAVAILABLE = 1722; + /// The RPC server is too busy to complete this operation. pub const RPC_S_SERVER_TOO_BUSY = 1723; + /// The network options are invalid. pub const RPC_S_INVALID_NETWORK_OPTIONS = 1724; + /// There are no remote procedure calls active on this thread. pub const RPC_S_NO_CALL_ACTIVE = 1725; + /// The remote procedure call failed. pub const RPC_S_CALL_FAILED = 1726; + /// The remote procedure call failed and did not execute. pub const RPC_S_CALL_FAILED_DNE = 1727; + /// A remote procedure call (RPC) protocol error occurred. pub const RPC_S_PROTOCOL_ERROR = 1728; + /// Access to the HTTP proxy is denied. pub const RPC_S_PROXY_ACCESS_DENIED = 1729; + /// The transfer syntax is not supported by the RPC server. pub const RPC_S_UNSUPPORTED_TRANS_SYN = 1730; + /// The universal unique identifier (UUID) type is not supported. pub const RPC_S_UNSUPPORTED_TYPE = 1732; + /// The tag is invalid. pub const RPC_S_INVALID_TAG = 1733; + /// The array bounds are invalid. pub const RPC_S_INVALID_BOUND = 1734; + /// The binding does not contain an entry name. pub const RPC_S_NO_ENTRY_NAME = 1735; + /// The name syntax is invalid. pub const RPC_S_INVALID_NAME_SYNTAX = 1736; + /// The name syntax is not supported. pub const RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737; + /// No network address is available to use to construct a universal unique identifier (UUID). pub const RPC_S_UUID_NO_ADDRESS = 1739; + /// The endpoint is a duplicate. pub const RPC_S_DUPLICATE_ENDPOINT = 1740; + /// The authentication type is unknown. pub const RPC_S_UNKNOWN_AUTHN_TYPE = 1741; + /// The maximum number of calls is too small. pub const RPC_S_MAX_CALLS_TOO_SMALL = 1742; + /// The string is too long. pub const RPC_S_STRING_TOO_LONG = 1743; + /// The RPC protocol sequence was not found. pub const RPC_S_PROTSEQ_NOT_FOUND = 1744; + /// The procedure number is out of range. pub const RPC_S_PROCNUM_OUT_OF_RANGE = 1745; + /// The binding does not contain any authentication information. pub const RPC_S_BINDING_HAS_NO_AUTH = 1746; + /// The authentication service is unknown. pub const RPC_S_UNKNOWN_AUTHN_SERVICE = 1747; + /// The authentication level is unknown. pub const RPC_S_UNKNOWN_AUTHN_LEVEL = 1748; + /// The security context is invalid. pub const RPC_S_INVALID_AUTH_IDENTITY = 1749; + /// The authorization service is unknown. pub const RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750; + /// The entry is invalid. pub const EPT_S_INVALID_ENTRY = 1751; + /// The server endpoint cannot perform the operation. pub const EPT_S_CANT_PERFORM_OP = 1752; + /// There are no more endpoints available from the endpoint mapper. pub const EPT_S_NOT_REGISTERED = 1753; + /// No interfaces have been exported. pub const RPC_S_NOTHING_TO_EXPORT = 1754; + /// The entry name is incomplete. pub const RPC_S_INCOMPLETE_NAME = 1755; + /// The version option is invalid. pub const RPC_S_INVALID_VERS_OPTION = 1756; + /// There are no more members. pub const RPC_S_NO_MORE_MEMBERS = 1757; + /// There is nothing to unexport. pub const RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758; + /// The interface was not found. pub const RPC_S_INTERFACE_NOT_FOUND = 1759; + /// The entry already exists. pub const RPC_S_ENTRY_ALREADY_EXISTS = 1760; + /// The entry is not found. pub const RPC_S_ENTRY_NOT_FOUND = 1761; + /// The name service is unavailable. pub const RPC_S_NAME_SERVICE_UNAVAILABLE = 1762; + /// The network address family is invalid. pub const RPC_S_INVALID_NAF_ID = 1763; + /// The requested operation is not supported. pub const RPC_S_CANNOT_SUPPORT = 1764; + /// No security context is available to allow impersonation. pub const RPC_S_NO_CONTEXT_AVAILABLE = 1765; + /// An internal error occurred in a remote procedure call (RPC). pub const RPC_S_INTERNAL_ERROR = 1766; + /// The RPC server attempted an integer division by zero. pub const RPC_S_ZERO_DIVIDE = 1767; + /// An addressing error occurred in the RPC server. pub const RPC_S_ADDRESS_ERROR = 1768; + /// A floating-point operation at the RPC server caused a division by zero. pub const RPC_S_FP_DIV_ZERO = 1769; + /// A floating-point underflow occurred at the RPC server. pub const RPC_S_FP_UNDERFLOW = 1770; + /// A floating-point overflow occurred at the RPC server. pub const RPC_S_FP_OVERFLOW = 1771; + /// The list of RPC servers available for the binding of auto handles has been exhausted. pub const RPC_X_NO_MORE_ENTRIES = 1772; + /// Unable to open the character translation table file. pub const RPC_X_SS_CHAR_TRANS_OPEN_FAIL = 1773; + /// The file containing the character translation table has fewer than 512 bytes. pub const RPC_X_SS_CHAR_TRANS_SHORT_FILE = 1774; + /// A null context handle was passed from the client to the host during a remote procedure call. pub const RPC_X_SS_IN_NULL_CONTEXT = 1775; + /// The context handle changed during a remote procedure call. pub const RPC_X_SS_CONTEXT_DAMAGED = 1777; + /// The binding handles passed to a remote procedure call do not match. pub const RPC_X_SS_HANDLES_MISMATCH = 1778; + /// The stub is unable to get the remote procedure call handle. pub const RPC_X_SS_CANNOT_GET_CALL_HANDLE = 1779; + /// A null reference pointer was passed to the stub. pub const RPC_X_NULL_REF_POINTER = 1780; + /// The enumeration value is out of range. pub const RPC_X_ENUM_VALUE_OUT_OF_RANGE = 1781; + /// The byte count is too small. pub const RPC_X_BYTE_COUNT_TOO_SMALL = 1782; + /// The stub received bad data. pub const RPC_X_BAD_STUB_DATA = 1783; + /// The supplied user buffer is not valid for the requested operation. pub const INVALID_USER_BUFFER = 1784; + /// The disk media is not recognized. It may not be formatted. pub const UNRECOGNIZED_MEDIA = 1785; + /// The workstation does not have a trust secret. pub const NO_TRUST_LSA_SECRET = 1786; + /// The security database on the server does not have a computer account for this workstation trust relationship. pub const NO_TRUST_SAM_ACCOUNT = 1787; + /// The trust relationship between the primary domain and the trusted domain failed. pub const TRUSTED_DOMAIN_FAILURE = 1788; + /// The trust relationship between this workstation and the primary domain failed. pub const TRUSTED_RELATIONSHIP_FAILURE = 1789; + /// The network logon failed. pub const TRUST_FAILURE = 1790; + /// A remote procedure call is already in progress for this thread. pub const RPC_S_CALL_IN_PROGRESS = 1791; + /// An attempt was made to logon, but the network logon service was not started. pub const NETLOGON_NOT_STARTED = 1792; + /// The user's account has expired. pub const ACCOUNT_EXPIRED = 1793; + /// The redirector is in use and cannot be unloaded. pub const REDIRECTOR_HAS_OPEN_HANDLES = 1794; + /// The specified printer driver is already installed. pub const PRINTER_DRIVER_ALREADY_INSTALLED = 1795; + /// The specified port is unknown. pub const UNKNOWN_PORT = 1796; + /// The printer driver is unknown. pub const UNKNOWN_PRINTER_DRIVER = 1797; + /// The print processor is unknown. pub const UNKNOWN_PRINTPROCESSOR = 1798; + /// The specified separator file is invalid. pub const INVALID_SEPARATOR_FILE = 1799; + /// The specified priority is invalid. pub const INVALID_PRIORITY = 1800; + /// The printer name is invalid. pub const INVALID_PRINTER_NAME = 1801; + /// The printer already exists. pub const PRINTER_ALREADY_EXISTS = 1802; + /// The printer command is invalid. pub const INVALID_PRINTER_COMMAND = 1803; + /// The specified datatype is invalid. pub const INVALID_DATATYPE = 1804; + /// The environment specified is invalid. pub const INVALID_ENVIRONMENT = 1805; + /// There are no more bindings. pub const RPC_S_NO_MORE_BINDINGS = 1806; + /// The account used is an interdomain trust account. Use your global user account or local user account to access this server. pub const NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 1807; + /// The account used is a computer account. Use your global user account or local user account to access this server. pub const NOLOGON_WORKSTATION_TRUST_ACCOUNT = 1808; + /// The account used is a server trust account. Use your global user account or local user account to access this server. pub const NOLOGON_SERVER_TRUST_ACCOUNT = 1809; + /// The name or security ID (SID) of the domain specified is inconsistent with the trust information for that domain. pub const DOMAIN_TRUST_INCONSISTENT = 1810; + /// The server is in use and cannot be unloaded. pub const SERVER_HAS_OPEN_HANDLES = 1811; + /// The specified image file did not contain a resource section. pub const RESOURCE_DATA_NOT_FOUND = 1812; + /// The specified resource type cannot be found in the image file. pub const RESOURCE_TYPE_NOT_FOUND = 1813; + /// The specified resource name cannot be found in the image file. pub const RESOURCE_NAME_NOT_FOUND = 1814; + /// The specified resource language ID cannot be found in the image file. pub const RESOURCE_LANG_NOT_FOUND = 1815; + /// Not enough quota is available to process this command. pub const NOT_ENOUGH_QUOTA = 1816; + /// No interfaces have been registered. pub const RPC_S_NO_INTERFACES = 1817; + /// The remote procedure call was cancelled. pub const RPC_S_CALL_CANCELLED = 1818; + /// The binding handle does not contain all required information. pub const RPC_S_BINDING_INCOMPLETE = 1819; + /// A communications failure occurred during a remote procedure call. pub const RPC_S_COMM_FAILURE = 1820; + /// The requested authentication level is not supported. pub const RPC_S_UNSUPPORTED_AUTHN_LEVEL = 1821; + /// No principal name registered. pub const RPC_S_NO_PRINC_NAME = 1822; + /// The error specified is not a valid Windows RPC error code. pub const RPC_S_NOT_RPC_ERROR = 1823; + /// A UUID that is valid only on this computer has been allocated. pub const RPC_S_UUID_LOCAL_ONLY = 1824; + /// A security package specific error occurred. pub const RPC_S_SEC_PKG_ERROR = 1825; + /// Thread is not canceled. pub const RPC_S_NOT_CANCELLED = 1826; + /// Invalid operation on the encoding/decoding handle. pub const RPC_X_INVALID_ES_ACTION = 1827; + /// Incompatible version of the serializing package. pub const RPC_X_WRONG_ES_VERSION = 1828; + /// Incompatible version of the RPC stub. pub const RPC_X_WRONG_STUB_VERSION = 1829; + /// The RPC pipe object is invalid or corrupted. pub const RPC_X_INVALID_PIPE_OBJECT = 1830; + /// An invalid operation was attempted on an RPC pipe object. pub const RPC_X_WRONG_PIPE_ORDER = 1831; + /// Unsupported RPC pipe version. pub const RPC_X_WRONG_PIPE_VERSION = 1832; + /// HTTP proxy server rejected the connection because the cookie authentication failed. pub const RPC_S_COOKIE_AUTH_FAILED = 1833; + /// The group member was not found. pub const RPC_S_GROUP_MEMBER_NOT_FOUND = 1898; + /// The endpoint mapper database entry could not be created. pub const EPT_S_CANT_CREATE = 1899; + /// The object universal unique identifier (UUID) is the nil UUID. pub const RPC_S_INVALID_OBJECT = 1900; + /// The specified time is invalid. pub const INVALID_TIME = 1901; + /// The specified form name is invalid. pub const INVALID_FORM_NAME = 1902; + /// The specified form size is invalid. pub const INVALID_FORM_SIZE = 1903; + /// The specified printer handle is already being waited on. pub const ALREADY_WAITING = 1904; + /// The specified printer has been deleted. pub const PRINTER_DELETED = 1905; + /// The state of the printer is invalid. pub const INVALID_PRINTER_STATE = 1906; + /// The user's password must be changed before signing in. pub const PASSWORD_MUST_CHANGE = 1907; + /// Could not find the domain controller for this domain. pub const DOMAIN_CONTROLLER_NOT_FOUND = 1908; + /// The referenced account is currently locked out and may not be logged on to. pub const ACCOUNT_LOCKED_OUT = 1909; + /// The object exporter specified was not found. pub const OR_INVALID_OXID = 1910; + /// The object specified was not found. pub const OR_INVALID_OID = 1911; + /// The object resolver set specified was not found. pub const OR_INVALID_SET = 1912; + /// Some data remains to be sent in the request buffer. pub const RPC_S_SEND_INCOMPLETE = 1913; + /// Invalid asynchronous remote procedure call handle. pub const RPC_S_INVALID_ASYNC_HANDLE = 1914; + /// Invalid asynchronous RPC call handle for this operation. pub const RPC_S_INVALID_ASYNC_CALL = 1915; + /// The RPC pipe object has already been closed. pub const RPC_X_PIPE_CLOSED = 1916; + /// The RPC call completed before all pipes were processed. pub const RPC_X_PIPE_DISCIPLINE_ERROR = 1917; + /// No more data is available from the RPC pipe. pub const RPC_X_PIPE_EMPTY = 1918; + /// No site name is available for this machine. pub const NO_SITENAME = 1919; + /// The file cannot be accessed by the system. pub const CANT_ACCESS_FILE = 1920; + /// The name of the file cannot be resolved by the system. pub const CANT_RESOLVE_FILENAME = 1921; + /// The entry is not of the expected type. pub const RPC_S_ENTRY_TYPE_MISMATCH = 1922; + /// Not all object UUIDs could be exported to the specified entry. pub const RPC_S_NOT_ALL_OBJS_EXPORTED = 1923; + /// Interface could not be exported to the specified entry. pub const RPC_S_INTERFACE_NOT_EXPORTED = 1924; + /// The specified profile entry could not be added. pub const RPC_S_PROFILE_NOT_ADDED = 1925; + /// The specified profile element could not be added. pub const RPC_S_PRF_ELT_NOT_ADDED = 1926; + /// The specified profile element could not be removed. pub const RPC_S_PRF_ELT_NOT_REMOVED = 1927; + /// The group element could not be added. pub const RPC_S_GRP_ELT_NOT_ADDED = 1928; + /// The group element could not be removed. pub const RPC_S_GRP_ELT_NOT_REMOVED = 1929; + /// The printer driver is not compatible with a policy enabled on your computer that blocks NT 4.0 drivers. pub const KM_DRIVER_BLOCKED = 1930; + /// The context has expired and can no longer be used. pub const CONTEXT_EXPIRED = 1931; + /// The current user's delegated trust creation quota has been exceeded. pub const PER_USER_TRUST_QUOTA_EXCEEDED = 1932; + /// The total delegated trust creation quota has been exceeded. pub const ALL_USER_TRUST_QUOTA_EXCEEDED = 1933; + /// The current user's delegated trust deletion quota has been exceeded. pub const USER_DELETE_TRUST_QUOTA_EXCEEDED = 1934; + /// The computer you are signing into is protected by an authentication firewall. The specified account is not allowed to authenticate to the computer. pub const AUTHENTICATION_FIREWALL_FAILED = 1935; + /// Remote connections to the Print Spooler are blocked by a policy set on your machine. pub const REMOTE_PRINT_CONNECTIONS_BLOCKED = 1936; + /// Authentication failed because NTLM authentication has been disabled. pub const NTLM_BLOCKED = 1937; + /// Logon Failure: EAS policy requires that the user change their password before this operation can be performed. pub const PASSWORD_CHANGE_REQUIRED = 1938; + /// The pixel format is invalid. pub const INVALID_PIXEL_FORMAT = 2000; + /// The specified driver is invalid. pub const BAD_DRIVER = 2001; + /// The window style or class attribute is invalid for this operation. pub const INVALID_WINDOW_STYLE = 2002; + /// The requested metafile operation is not supported. pub const METAFILE_NOT_SUPPORTED = 2003; + /// The requested transformation operation is not supported. pub const TRANSFORM_NOT_SUPPORTED = 2004; + /// The requested clipping operation is not supported. pub const CLIPPING_NOT_SUPPORTED = 2005; + /// The specified color management module is invalid. pub const INVALID_CMM = 2010; + /// The specified color profile is invalid. pub const INVALID_PROFILE = 2011; + /// The specified tag was not found. pub const TAG_NOT_FOUND = 2012; + /// A required tag is not present. pub const TAG_NOT_PRESENT = 2013; + /// The specified tag is already present. pub const DUPLICATE_TAG = 2014; + /// The specified color profile is not associated with the specified device. pub const PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015; + /// The specified color profile was not found. pub const PROFILE_NOT_FOUND = 2016; + /// The specified color space is invalid. pub const INVALID_COLORSPACE = 2017; + /// Image Color Management is not enabled. pub const ICM_NOT_ENABLED = 2018; + /// There was an error while deleting the color transform. pub const DELETING_ICM_XFORM = 2019; + /// The specified color transform is invalid. pub const INVALID_TRANSFORM = 2020; + /// The specified transform does not match the bitmap's color space. pub const COLORSPACE_MISMATCH = 2021; + /// The specified named color index is not present in the profile. pub const INVALID_COLORINDEX = 2022; + /// The specified profile is intended for a device of a different type than the specified device. pub const PROFILE_DOES_NOT_MATCH_DEVICE = 2023; + /// The network connection was made successfully, but the user had to be prompted for a password other than the one originally specified. pub const CONNECTED_OTHER_PASSWORD = 2108; + /// The network connection was made successfully using default credentials. pub const CONNECTED_OTHER_PASSWORD_DEFAULT = 2109; + /// The specified username is invalid. pub const BAD_USERNAME = 2202; + /// This network connection does not exist. pub const NOT_CONNECTED = 2250; + /// This network connection has files open or requests pending. pub const OPEN_FILES = 2401; + /// Active connections still exist. pub const ACTIVE_CONNECTIONS = 2402; + /// The device is in use by an active process and cannot be disconnected. pub const DEVICE_IN_USE = 2404; + /// The specified print monitor is unknown. pub const UNKNOWN_PRINT_MONITOR = 3000; + /// The specified printer driver is currently in use. pub const PRINTER_DRIVER_IN_USE = 3001; + /// The spool file was not found. pub const SPOOL_FILE_NOT_FOUND = 3002; + /// A StartDocPrinter call was not issued. pub const SPL_NO_STARTDOC = 3003; + /// An AddJob call was not issued. pub const SPL_NO_ADDJOB = 3004; + /// The specified print processor has already been installed. pub const PRINT_PROCESSOR_ALREADY_INSTALLED = 3005; + /// The specified print monitor has already been installed. pub const PRINT_MONITOR_ALREADY_INSTALLED = 3006; + /// The specified print monitor does not have the required functions. pub const INVALID_PRINT_MONITOR = 3007; + /// The specified print monitor is currently in use. pub const PRINT_MONITOR_IN_USE = 3008; + /// The requested operation is not allowed when there are jobs queued to the printer. pub const PRINTER_HAS_JOBS_QUEUED = 3009; + /// The requested operation is successful. Changes will not be effective until the system is rebooted. pub const SUCCESS_REBOOT_REQUIRED = 3010; + /// The requested operation is successful. Changes will not be effective until the service is restarted. pub const SUCCESS_RESTART_REQUIRED = 3011; + /// No printers were found. pub const PRINTER_NOT_FOUND = 3012; + /// The printer driver is known to be unreliable. pub const PRINTER_DRIVER_WARNED = 3013; + /// The printer driver is known to harm the system. pub const PRINTER_DRIVER_BLOCKED = 3014; + /// The specified printer driver package is currently in use. pub const PRINTER_DRIVER_PACKAGE_IN_USE = 3015; + /// Unable to find a core driver package that is required by the printer driver package. pub const CORE_DRIVER_PACKAGE_NOT_FOUND = 3016; + /// The requested operation failed. A system reboot is required to roll back changes made. pub const FAIL_REBOOT_REQUIRED = 3017; + /// The requested operation failed. A system reboot has been initiated to roll back changes made. pub const FAIL_REBOOT_INITIATED = 3018; + /// The specified printer driver was not found on the system and needs to be downloaded. pub const PRINTER_DRIVER_DOWNLOAD_NEEDED = 3019; + /// The requested print job has failed to print. A print system update requires the job to be resubmitted. pub const PRINT_JOB_RESTART_REQUIRED = 3020; + /// The printer driver does not contain a valid manifest, or contains too many manifests. pub const INVALID_PRINTER_DRIVER_MANIFEST = 3021; + /// The specified printer cannot be shared. pub const PRINTER_NOT_SHAREABLE = 3022; + /// The operation was paused. pub const REQUEST_PAUSED = 3050; + /// Reissue the given operation as a cached IO operation. pub const IO_REISSUE_AS_CACHED = 3950; diff --git a/std/os/windows/index.zig b/std/os/windows/index.zig index e13ed0f131..426514f7d7 100644 --- a/std/os/windows/index.zig +++ b/std/os/windows/index.zig @@ -1,33 +1,59 @@ pub const ERROR = @import("error.zig"); -pub extern "advapi32" stdcallcc fn CryptAcquireContextA(phProv: &HCRYPTPROV, pszContainer: ?LPCSTR, - pszProvider: ?LPCSTR, dwProvType: DWORD, dwFlags: DWORD) BOOL; +pub extern "advapi32" stdcallcc fn CryptAcquireContextA( + phProv: &HCRYPTPROV, + pszContainer: ?LPCSTR, + pszProvider: ?LPCSTR, + dwProvType: DWORD, + dwFlags: DWORD, +) BOOL; pub extern "advapi32" stdcallcc fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) BOOL; pub extern "advapi32" stdcallcc fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: &BYTE) BOOL; - pub extern "kernel32" stdcallcc fn CloseHandle(hObject: HANDLE) BOOL; -pub extern "kernel32" stdcallcc fn CreateDirectoryA(lpPathName: LPCSTR, - lpSecurityAttributes: ?&SECURITY_ATTRIBUTES) BOOL; - -pub extern "kernel32" stdcallcc fn CreateFileA(lpFileName: LPCSTR, dwDesiredAccess: DWORD, - dwShareMode: DWORD, lpSecurityAttributes: ?LPSECURITY_ATTRIBUTES, dwCreationDisposition: DWORD, - dwFlagsAndAttributes: DWORD, hTemplateFile: ?HANDLE) HANDLE; - -pub extern "kernel32" stdcallcc fn CreatePipe(hReadPipe: &HANDLE, hWritePipe: &HANDLE, - lpPipeAttributes: &const SECURITY_ATTRIBUTES, nSize: DWORD) BOOL; - -pub extern "kernel32" stdcallcc fn CreateProcessA(lpApplicationName: ?LPCSTR, lpCommandLine: LPSTR, - lpProcessAttributes: ?&SECURITY_ATTRIBUTES, lpThreadAttributes: ?&SECURITY_ATTRIBUTES, bInheritHandles: BOOL, - dwCreationFlags: DWORD, lpEnvironment: ?&c_void, lpCurrentDirectory: ?LPCSTR, lpStartupInfo: &STARTUPINFOA, - lpProcessInformation: &PROCESS_INFORMATION) BOOL; - -pub extern "kernel32" stdcallcc fn CreateSymbolicLinkA(lpSymlinkFileName: LPCSTR, lpTargetFileName: LPCSTR, - dwFlags: DWORD) BOOLEAN; - +pub extern "kernel32" stdcallcc fn CreateDirectoryA( + lpPathName: LPCSTR, + lpSecurityAttributes: ?&SECURITY_ATTRIBUTES, +) BOOL; + +pub extern "kernel32" stdcallcc fn CreateFileA( + lpFileName: LPCSTR, + dwDesiredAccess: DWORD, + dwShareMode: DWORD, + lpSecurityAttributes: ?LPSECURITY_ATTRIBUTES, + dwCreationDisposition: DWORD, + dwFlagsAndAttributes: DWORD, + hTemplateFile: ?HANDLE, +) HANDLE; + +pub extern "kernel32" stdcallcc fn CreatePipe( + hReadPipe: &HANDLE, + hWritePipe: &HANDLE, + lpPipeAttributes: &const SECURITY_ATTRIBUTES, + nSize: DWORD, +) BOOL; + +pub extern "kernel32" stdcallcc fn CreateProcessA( + lpApplicationName: ?LPCSTR, + lpCommandLine: LPSTR, + lpProcessAttributes: ?&SECURITY_ATTRIBUTES, + lpThreadAttributes: ?&SECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: ?&c_void, + lpCurrentDirectory: ?LPCSTR, + lpStartupInfo: &STARTUPINFOA, + lpProcessInformation: &PROCESS_INFORMATION, +) BOOL; + +pub extern "kernel32" stdcallcc fn CreateSymbolicLinkA( + lpSymlinkFileName: LPCSTR, + lpTargetFileName: LPCSTR, + dwFlags: DWORD, +) BOOLEAN; pub extern "kernel32" stdcallcc fn CreateThread(lpThreadAttributes: ?LPSECURITY_ATTRIBUTES, dwStackSize: SIZE_T, lpStartAddress: LPTHREAD_START_ROUTINE, lpParameter: ?LPVOID, dwCreationFlags: DWORD, lpThreadId: ?LPDWORD) ?HANDLE; @@ -55,12 +81,19 @@ pub extern "kernel32" stdcallcc fn GetModuleFileNameA(hModule: ?HMODULE, lpFilen pub extern "kernel32" stdcallcc fn GetLastError() DWORD; -pub extern "kernel32" stdcallcc fn GetFileInformationByHandleEx(in_hFile: HANDLE, - in_FileInformationClass: FILE_INFO_BY_HANDLE_CLASS, out_lpFileInformation: &c_void, - in_dwBufferSize: DWORD) BOOL; - -pub extern "kernel32" stdcallcc fn GetFinalPathNameByHandleA(hFile: HANDLE, lpszFilePath: LPSTR, - cchFilePath: DWORD, dwFlags: DWORD) DWORD; +pub extern "kernel32" stdcallcc fn GetFileInformationByHandleEx( + in_hFile: HANDLE, + in_FileInformationClass: FILE_INFO_BY_HANDLE_CLASS, + out_lpFileInformation: &c_void, + in_dwBufferSize: DWORD, +) BOOL; + +pub extern "kernel32" stdcallcc fn GetFinalPathNameByHandleA( + hFile: HANDLE, + lpszFilePath: LPSTR, + cchFilePath: DWORD, + dwFlags: DWORD, +) DWORD; pub extern "kernel32" stdcallcc fn GetProcessHeap() ?HANDLE; @@ -80,21 +113,32 @@ pub extern "kernel32" stdcallcc fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBy pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: &c_void) BOOL; -pub extern "kernel32" stdcallcc fn MoveFileExA(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, - dwFlags: DWORD) BOOL; - +pub extern "kernel32" stdcallcc fn MoveFileExA( + lpExistingFileName: LPCSTR, + lpNewFileName: LPCSTR, + dwFlags: DWORD, +) BOOL; + pub extern "kernel32" stdcallcc fn QueryPerformanceCounter(lpPerformanceCount: &LARGE_INTEGER) BOOL; pub extern "kernel32" stdcallcc fn QueryPerformanceFrequency(lpFrequency: &LARGE_INTEGER) BOOL; pub extern "kernel32" stdcallcc fn PathFileExists(pszPath: ?LPCTSTR) BOOL; -pub extern "kernel32" stdcallcc fn ReadFile(in_hFile: HANDLE, out_lpBuffer: &c_void, - in_nNumberOfBytesToRead: DWORD, out_lpNumberOfBytesRead: &DWORD, - in_out_lpOverlapped: ?&OVERLAPPED) BOOL; - -pub extern "kernel32" stdcallcc fn SetFilePointerEx(in_fFile: HANDLE, in_liDistanceToMove: LARGE_INTEGER, - out_opt_ldNewFilePointer: ?&LARGE_INTEGER, in_dwMoveMethod: DWORD) BOOL; +pub extern "kernel32" stdcallcc fn ReadFile( + in_hFile: HANDLE, + out_lpBuffer: &c_void, + in_nNumberOfBytesToRead: DWORD, + out_lpNumberOfBytesRead: &DWORD, + in_out_lpOverlapped: ?&OVERLAPPED, +) BOOL; + +pub extern "kernel32" stdcallcc fn SetFilePointerEx( + in_fFile: HANDLE, + in_liDistanceToMove: LARGE_INTEGER, + out_opt_ldNewFilePointer: ?&LARGE_INTEGER, + in_dwMoveMethod: DWORD, +) BOOL; pub extern "kernel32" stdcallcc fn SetHandleInformation(hObject: HANDLE, dwMask: DWORD, dwFlags: DWORD) BOOL; @@ -104,14 +148,18 @@ pub extern "kernel32" stdcallcc fn TerminateProcess(hProcess: HANDLE, uExitCode: pub extern "kernel32" stdcallcc fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) DWORD; -pub extern "kernel32" stdcallcc fn WriteFile(in_hFile: HANDLE, in_lpBuffer: &const c_void, - in_nNumberOfBytesToWrite: DWORD, out_lpNumberOfBytesWritten: ?&DWORD, - in_out_lpOverlapped: ?&OVERLAPPED) BOOL; +pub extern "kernel32" stdcallcc fn WriteFile( + in_hFile: HANDLE, + in_lpBuffer: &const c_void, + in_nNumberOfBytesToWrite: DWORD, + out_lpNumberOfBytesWritten: ?&DWORD, + in_out_lpOverlapped: ?&OVERLAPPED, +) BOOL; //TODO: call unicode versions instead of relying on ANSI code page pub extern "kernel32" stdcallcc fn LoadLibraryA(lpLibFileName: LPCSTR) ?HMODULE; -pub extern "kernel32" stdcallcc fn FreeLibrary(hModule: HMODULE) BOOL; +pub extern "kernel32" stdcallcc fn FreeLibrary(hModule: HMODULE) BOOL; pub extern "user32" stdcallcc fn MessageBoxA(hWnd: ?HANDLE, lpText: ?LPCTSTR, lpCaption: ?LPCTSTR, uType: UINT) c_int; @@ -176,49 +224,51 @@ pub const MAX_PATH = 260; // TODO issue #305 pub const FILE_INFO_BY_HANDLE_CLASS = u32; -pub const FileBasicInfo = 0; -pub const FileStandardInfo = 1; -pub const FileNameInfo = 2; -pub const FileRenameInfo = 3; -pub const FileDispositionInfo = 4; -pub const FileAllocationInfo = 5; -pub const FileEndOfFileInfo = 6; -pub const FileStreamInfo = 7; -pub const FileCompressionInfo = 8; -pub const FileAttributeTagInfo = 9; -pub const FileIdBothDirectoryInfo = 10; -pub const FileIdBothDirectoryRestartInfo = 11; -pub const FileIoPriorityHintInfo = 12; -pub const FileRemoteProtocolInfo = 13; -pub const FileFullDirectoryInfo = 14; -pub const FileFullDirectoryRestartInfo = 15; -pub const FileStorageInfo = 16; -pub const FileAlignmentInfo = 17; -pub const FileIdInfo = 18; -pub const FileIdExtdDirectoryInfo = 19; -pub const FileIdExtdDirectoryRestartInfo = 20; +pub const FileBasicInfo = 0; +pub const FileStandardInfo = 1; +pub const FileNameInfo = 2; +pub const FileRenameInfo = 3; +pub const FileDispositionInfo = 4; +pub const FileAllocationInfo = 5; +pub const FileEndOfFileInfo = 6; +pub const FileStreamInfo = 7; +pub const FileCompressionInfo = 8; +pub const FileAttributeTagInfo = 9; +pub const FileIdBothDirectoryInfo = 10; +pub const FileIdBothDirectoryRestartInfo = 11; +pub const FileIoPriorityHintInfo = 12; +pub const FileRemoteProtocolInfo = 13; +pub const FileFullDirectoryInfo = 14; +pub const FileFullDirectoryRestartInfo = 15; +pub const FileStorageInfo = 16; +pub const FileAlignmentInfo = 17; +pub const FileIdInfo = 18; +pub const FileIdExtdDirectoryInfo = 19; +pub const FileIdExtdDirectoryRestartInfo = 20; pub const FILE_NAME_INFO = extern struct { FileNameLength: DWORD, FileName: [1]WCHAR, }; - /// Return the normalized drive name. This is the default. pub const FILE_NAME_NORMALIZED = 0x0; + /// Return the opened file name (not normalized). pub const FILE_NAME_OPENED = 0x8; /// Return the path with the drive letter. This is the default. pub const VOLUME_NAME_DOS = 0x0; + /// Return the path with a volume GUID path instead of the drive name. pub const VOLUME_NAME_GUID = 0x1; + /// Return the path with no drive information. pub const VOLUME_NAME_NONE = 0x4; + /// Return the path with the volume device path. pub const VOLUME_NAME_NT = 0x2; - pub const SECURITY_ATTRIBUTES = extern struct { nLength: DWORD, lpSecurityDescriptor: ?&c_void, @@ -227,7 +277,6 @@ pub const SECURITY_ATTRIBUTES = extern struct { pub const PSECURITY_ATTRIBUTES = &SECURITY_ATTRIBUTES; pub const LPSECURITY_ATTRIBUTES = &SECURITY_ATTRIBUTES; - pub const GENERIC_READ = 0x80000000; pub const GENERIC_WRITE = 0x40000000; pub const GENERIC_EXECUTE = 0x20000000; @@ -243,7 +292,6 @@ pub const OPEN_ALWAYS = 4; pub const OPEN_EXISTING = 3; pub const TRUNCATE_EXISTING = 5; - pub const FILE_ATTRIBUTE_ARCHIVE = 0x20; pub const FILE_ATTRIBUTE_ENCRYPTED = 0x4000; pub const FILE_ATTRIBUTE_HIDDEN = 0x2; diff --git a/std/os/windows/util.zig b/std/os/windows/util.zig index 5af318b7b0..7b7fdfae08 100644 --- a/std/os/windows/util.zig +++ b/std/os/windows/util.zig @@ -7,7 +7,7 @@ const mem = std.mem; const BufMap = std.BufMap; const cstr = std.cstr; -pub const WaitError = error { +pub const WaitError = error{ WaitAbandoned, WaitTimeOut, Unexpected, @@ -33,7 +33,7 @@ pub fn windowsClose(handle: windows.HANDLE) void { assert(windows.CloseHandle(handle) != 0); } -pub const WriteError = error { +pub const WriteError = error{ SystemResources, OperationAborted, IoPending, @@ -68,20 +68,18 @@ pub fn windowsIsCygwinPty(handle: windows.HANDLE) bool { const size = @sizeOf(windows.FILE_NAME_INFO); var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = []u8{0} ** (size + windows.MAX_PATH); - if (windows.GetFileInformationByHandleEx(handle, windows.FileNameInfo, - @ptrCast(&c_void, &name_info_bytes[0]), u32(name_info_bytes.len)) == 0) - { + if (windows.GetFileInformationByHandleEx(handle, windows.FileNameInfo, @ptrCast(&c_void, &name_info_bytes[0]), u32(name_info_bytes.len)) == 0) { return true; } const name_info = @ptrCast(&const windows.FILE_NAME_INFO, &name_info_bytes[0]); const name_bytes = name_info_bytes[size..size + usize(name_info.FileNameLength)]; - const name_wide = ([]u16)(name_bytes); - return mem.indexOf(u16, name_wide, []u16{'m','s','y','s','-'}) != null or - mem.indexOf(u16, name_wide, []u16{'-','p','t','y'}) != null; + const name_wide = ([]u16)(name_bytes); + return mem.indexOf(u16, name_wide, []u16{ 'm', 's', 'y', 's', '-' }) != null or + mem.indexOf(u16, name_wide, []u16{ '-', 'p', 't', 'y' }) != null; } -pub const OpenError = error { +pub const OpenError = error{ SharingViolation, PathAlreadyExists, FileNotFound, @@ -92,15 +90,18 @@ pub const OpenError = error { }; /// `file_path` needs to be copied in memory to add a null terminating byte, hence the allocator. -pub fn windowsOpen(allocator: &mem.Allocator, file_path: []const u8, desired_access: windows.DWORD, share_mode: windows.DWORD, - creation_disposition: windows.DWORD, flags_and_attrs: windows.DWORD) - OpenError!windows.HANDLE -{ +pub fn windowsOpen( + allocator: &mem.Allocator, + file_path: []const u8, + desired_access: windows.DWORD, + share_mode: windows.DWORD, + creation_disposition: windows.DWORD, + flags_and_attrs: windows.DWORD, +) OpenError!windows.HANDLE { const path_with_null = try cstr.addNullByte(allocator, file_path); defer allocator.free(path_with_null); - const result = windows.CreateFileA(path_with_null.ptr, desired_access, share_mode, null, creation_disposition, - flags_and_attrs, null); + const result = windows.CreateFileA(path_with_null.ptr, desired_access, share_mode, null, creation_disposition, flags_and_attrs, null); if (result == windows.INVALID_HANDLE_VALUE) { const err = windows.GetLastError(); @@ -156,18 +157,16 @@ pub fn windowsLoadDll(allocator: &mem.Allocator, dll_path: []const u8) !windows. } pub fn windowsUnloadDll(hModule: windows.HMODULE) void { - assert(windows.FreeLibrary(hModule)!= 0); + assert(windows.FreeLibrary(hModule) != 0); } - test "InvalidDll" { if (builtin.os != builtin.Os.windows) return; const DllName = "asdf.dll"; const allocator = std.debug.global_allocator; - const handle = os.windowsLoadDll(allocator, DllName) catch |err| { + const handle = os.windowsLoadDll(allocator, DllName) catch |err| { assert(err == error.DllNotFound); return; }; } - diff --git a/std/os/zen.zig b/std/os/zen.zig index 51528ca391..7517cc0d69 100644 --- a/std/os/zen.zig +++ b/std/os/zen.zig @@ -3,35 +3,35 @@ ////////////////////////// pub const Message = struct { - sender: MailboxId, + sender: MailboxId, receiver: MailboxId, - type: usize, - payload: usize, + type: usize, + payload: usize, pub fn from(mailbox_id: &const MailboxId) Message { - return Message { - .sender = MailboxId.Undefined, + return Message{ + .sender = MailboxId.Undefined, .receiver = *mailbox_id, - .type = 0, - .payload = 0, + .type = 0, + .payload = 0, }; } pub fn to(mailbox_id: &const MailboxId, msg_type: usize) Message { - return Message { - .sender = MailboxId.This, + return Message{ + .sender = MailboxId.This, .receiver = *mailbox_id, - .type = msg_type, - .payload = 0, + .type = msg_type, + .payload = 0, }; } pub fn withData(mailbox_id: &const MailboxId, msg_type: usize, payload: usize) Message { - return Message { - .sender = MailboxId.This, + return Message{ + .sender = MailboxId.This, .receiver = *mailbox_id, - .type = msg_type, - .payload = payload, + .type = msg_type, + .payload = payload, }; } }; @@ -40,27 +40,25 @@ pub const MailboxId = union(enum) { Undefined, This, Kernel, - Port: u16, + Port: u16, Thread: u16, }; - ////////////////////////////////////// //// Ports reserved for servers //// ////////////////////////////////////// pub const Server = struct { - pub const Keyboard = MailboxId { .Port = 0 }; - pub const Terminal = MailboxId { .Port = 1 }; + pub const Keyboard = MailboxId{ .Port = 0 }; + pub const Terminal = MailboxId{ .Port = 1 }; }; - //////////////////////// //// POSIX things //// //////////////////////// // Standard streams. -pub const STDIN_FILENO = 0; +pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; @@ -101,26 +99,24 @@ pub fn write(fd: i32, buf: &const u8, count: usize) usize { return count; } - /////////////////////////// //// Syscall numbers //// /////////////////////////// pub const Syscall = enum(usize) { - exit = 0, - createPort = 1, - send = 2, - receive = 3, - subscribeIRQ = 4, - inb = 5, - map = 6, - createThread = 7, + exit = 0, + createPort = 1, + send = 2, + receive = 3, + subscribeIRQ = 4, + inb = 5, + map = 6, + createThread = 7, createProcess = 8, - wait = 9, - portReady = 10, + wait = 9, + portReady = 10, }; - //////////////////// //// Syscalls //// //////////////////// @@ -157,7 +153,7 @@ pub fn map(v_addr: usize, p_addr: usize, size: usize, writable: bool) bool { return syscall4(Syscall.map, v_addr, p_addr, size, usize(writable)) != 0; } -pub fn createThread(function: fn()void) u16 { +pub fn createThread(function: fn() void) u16 { return u16(syscall1(Syscall.createThread, @ptrToInt(function))); } @@ -180,66 +176,84 @@ pub fn portReady(port: u16) bool { inline fn syscall0(number: Syscall) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number)); + : [number] "{eax}" (number) + ); } inline fn syscall1(number: Syscall, arg1: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1)); + [arg1] "{ecx}" (arg1) + ); } inline fn syscall2(number: Syscall, arg1: usize, arg2: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2)); + [arg1] "{ecx}" (arg1), + [arg2] "{edx}" (arg2) + ); } inline fn syscall3(number: Syscall, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3)); + [arg1] "{ecx}" (arg1), + [arg2] "{edx}" (arg2), + [arg3] "{ebx}" (arg3) + ); } inline fn syscall4(number: Syscall, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3), - [arg4] "{esi}" (arg4)); + [arg1] "{ecx}" (arg1), + [arg2] "{edx}" (arg2), + [arg3] "{ebx}" (arg3), + [arg4] "{esi}" (arg4) + ); } -inline fn syscall5(number: Syscall, arg1: usize, arg2: usize, arg3: usize, - arg4: usize, arg5: usize) usize -{ +inline fn syscall5( + number: Syscall, + arg1: usize, + arg2: usize, + arg3: usize, + arg4: usize, + arg5: usize, +) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3), - [arg4] "{esi}" (arg4), - [arg5] "{edi}" (arg5)); + [arg1] "{ecx}" (arg1), + [arg2] "{edx}" (arg2), + [arg3] "{ebx}" (arg3), + [arg4] "{esi}" (arg4), + [arg5] "{edi}" (arg5) + ); } -inline fn syscall6(number: Syscall, arg1: usize, arg2: usize, arg3: usize, - arg4: usize, arg5: usize, arg6: usize) usize -{ +inline fn syscall6( + number: Syscall, + arg1: usize, + arg2: usize, + arg3: usize, + arg4: usize, + arg5: usize, + arg6: usize, +) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) : [number] "{eax}" (number), - [arg1] "{ecx}" (arg1), - [arg2] "{edx}" (arg2), - [arg3] "{ebx}" (arg3), - [arg4] "{esi}" (arg4), - [arg5] "{edi}" (arg5), - [arg6] "{ebp}" (arg6)); + [arg1] "{ecx}" (arg1), + [arg2] "{edx}" (arg2), + [arg3] "{ebx}" (arg3), + [arg4] "{esi}" (arg4), + [arg5] "{edi}" (arg5), + [arg6] "{ebp}" (arg6) + ); } diff --git a/std/rand/index.zig b/std/rand/index.zig index bd6209009e..68e6d3cb4d 100644 --- a/std/rand/index.zig +++ b/std/rand/index.zig @@ -69,7 +69,7 @@ pub const Random = struct { break :x start; } else x: { // Can't overflow because the range is over signed ints - break :x math.negateCast(value - end_uint) catch unreachable; + break :x math.negateCast(value - end_uint) catch unreachable; }; return result; } else { @@ -156,7 +156,7 @@ const SplitMix64 = struct { s: u64, pub fn init(seed: u64) SplitMix64 { - return SplitMix64 { .s = seed }; + return SplitMix64{ .s = seed }; } pub fn next(self: &SplitMix64) u64 { @@ -172,7 +172,7 @@ const SplitMix64 = struct { test "splitmix64 sequence" { var r = SplitMix64.init(0xaeecf86f7878dd75); - const seq = []const u64 { + const seq = []const u64{ 0x5dbd39db0178eb44, 0xa9900fb66b397da3, 0x5c1a28b1aeebcf5c, @@ -198,8 +198,8 @@ pub const Pcg = struct { i: u64, pub fn init(init_s: u64) Pcg { - var pcg = Pcg { - .random = Random { .fillFn = fill }, + var pcg = Pcg{ + .random = Random{ .fillFn = fill }, .s = undefined, .i = undefined, }; @@ -265,7 +265,7 @@ test "pcg sequence" { const s1: u64 = 0x84e9c579ef59bbf7; r.seedTwo(s0, s1); - const seq = []const u32 { + const seq = []const u32{ 2881561918, 3063928540, 1199791034, @@ -288,8 +288,8 @@ pub const Xoroshiro128 = struct { s: [2]u64, pub fn init(init_s: u64) Xoroshiro128 { - var x = Xoroshiro128 { - .random = Random { .fillFn = fill }, + var x = Xoroshiro128{ + .random = Random{ .fillFn = fill }, .s = undefined, }; @@ -314,9 +314,9 @@ pub const Xoroshiro128 = struct { var s0: u64 = 0; var s1: u64 = 0; - const table = []const u64 { + const table = []const u64{ 0xbeac0467eba5facb, - 0xd86b048b86aa9922 + 0xd86b048b86aa9922, }; inline for (table) |entry| { @@ -374,7 +374,7 @@ test "xoroshiro sequence" { r.s[0] = 0xaeecf86f7878dd75; r.s[1] = 0x01cd153642e72622; - const seq1 = []const u64 { + const seq1 = []const u64{ 0xb0ba0da5bb600397, 0x18a08afde614dccc, 0xa2635b956a31b929, @@ -387,10 +387,9 @@ test "xoroshiro sequence" { std.debug.assert(s == r.next()); } - r.jump(); - const seq2 = []const u64 { + const seq2 = []const u64{ 0x95344a13556d3e22, 0xb4fb32dafa4d00df, 0xb2011d9ccdcfe2dd, @@ -421,8 +420,8 @@ pub const Isaac64 = struct { i: usize, pub fn init(init_s: u64) Isaac64 { - var isaac = Isaac64 { - .random = Random { .fillFn = fill }, + var isaac = Isaac64{ + .random = Random{ .fillFn = fill }, .r = undefined, .m = undefined, .a = undefined, @@ -456,20 +455,20 @@ pub const Isaac64 = struct { { var i: usize = 0; while (i < midpoint) : (i += 4) { - self.step( ~(self.a ^ (self.a << 21)), i + 0, 0, midpoint); - self.step( self.a ^ (self.a >> 5) , i + 1, 0, midpoint); - self.step( self.a ^ (self.a << 12) , i + 2, 0, midpoint); - self.step( self.a ^ (self.a >> 33) , i + 3, 0, midpoint); + self.step(~(self.a ^ (self.a << 21)), i + 0, 0, midpoint); + self.step(self.a ^ (self.a >> 5), i + 1, 0, midpoint); + self.step(self.a ^ (self.a << 12), i + 2, 0, midpoint); + self.step(self.a ^ (self.a >> 33), i + 3, 0, midpoint); } } { var i: usize = 0; while (i < midpoint) : (i += 4) { - self.step( ~(self.a ^ (self.a << 21)), i + 0, midpoint, 0); - self.step( self.a ^ (self.a >> 5) , i + 1, midpoint, 0); - self.step( self.a ^ (self.a << 12) , i + 2, midpoint, 0); - self.step( self.a ^ (self.a >> 33) , i + 3, midpoint, 0); + self.step(~(self.a ^ (self.a << 21)), i + 0, midpoint, 0); + self.step(self.a ^ (self.a >> 5), i + 1, midpoint, 0); + self.step(self.a ^ (self.a << 12), i + 2, midpoint, 0); + self.step(self.a ^ (self.a >> 33), i + 3, midpoint, 0); } } @@ -493,7 +492,7 @@ pub const Isaac64 = struct { self.m[0] = init_s; // prescrambled golden ratio constants - var a = []const u64 { + var a = []const u64{ 0x647c4677a2884b7c, 0xb9f8b322c73ac862, 0x8c0ea5053d4712a0, @@ -513,14 +512,30 @@ pub const Isaac64 = struct { a[x1] +%= self.m[j + x1]; } - a[0] -%= a[4]; a[5] ^= a[7] >> 9; a[7] +%= a[0]; - a[1] -%= a[5]; a[6] ^= a[0] << 9; a[0] +%= a[1]; - a[2] -%= a[6]; a[7] ^= a[1] >> 23; a[1] +%= a[2]; - a[3] -%= a[7]; a[0] ^= a[2] << 15; a[2] +%= a[3]; - a[4] -%= a[0]; a[1] ^= a[3] >> 14; a[3] +%= a[4]; - a[5] -%= a[1]; a[2] ^= a[4] << 20; a[4] +%= a[5]; - a[6] -%= a[2]; a[3] ^= a[5] >> 17; a[5] +%= a[6]; - a[7] -%= a[3]; a[4] ^= a[6] << 14; a[6] +%= a[7]; + a[0] -%= a[4]; + a[5] ^= a[7] >> 9; + a[7] +%= a[0]; + a[1] -%= a[5]; + a[6] ^= a[0] << 9; + a[0] +%= a[1]; + a[2] -%= a[6]; + a[7] ^= a[1] >> 23; + a[1] +%= a[2]; + a[3] -%= a[7]; + a[0] ^= a[2] << 15; + a[2] +%= a[3]; + a[4] -%= a[0]; + a[1] ^= a[3] >> 14; + a[3] +%= a[4]; + a[5] -%= a[1]; + a[2] ^= a[4] << 20; + a[4] +%= a[5]; + a[6] -%= a[2]; + a[3] ^= a[5] >> 17; + a[5] +%= a[6]; + a[7] -%= a[3]; + a[4] ^= a[6] << 14; + a[6] +%= a[7]; comptime var x2: usize = 0; inline while (x2 < 8) : (x2 += 1) { @@ -533,7 +548,7 @@ pub const Isaac64 = struct { self.a = 0; self.b = 0; self.c = 0; - self.i = self.r.len; // trigger refill on first value + self.i = self.r.len; // trigger refill on first value } fn fill(r: &Random, buf: []u8) void { @@ -567,7 +582,7 @@ test "isaac64 sequence" { var r = Isaac64.init(0); // from reference implementation - const seq = []const u64 { + const seq = []const u64{ 0xf67dfba498e4937c, 0x84a5066a9204f380, 0xfee34bd5f5514dbb, @@ -609,7 +624,7 @@ test "Random float" { test "Random scalar" { var prng = DefaultPrng.init(0); - const s = prng .random.scalar(u64); + const s = prng.random.scalar(u64); } test "Random bytes" { @@ -621,8 +636,8 @@ test "Random bytes" { test "Random shuffle" { var prng = DefaultPrng.init(0); - var seq = []const u8 { 0, 1, 2, 3, 4 }; - var seen = []bool {false} ** 5; + var seq = []const u8{ 0, 1, 2, 3, 4 }; + var seen = []bool{false} ** 5; var i: usize = 0; while (i < 1000) : (i += 1) { @@ -639,7 +654,8 @@ test "Random shuffle" { fn sumArray(s: []const u8) u32 { var r: u32 = 0; - for (s) |e| r += e; + for (s) |e| + r += e; return r; } diff --git a/std/rand/ziggurat.zig b/std/rand/ziggurat.zig index 7790b71d26..404687ad0c 100644 --- a/std/rand/ziggurat.zig +++ b/std/rand/ziggurat.zig @@ -64,8 +64,14 @@ pub const ZigTable = struct { }; // zigNorInit -fn 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 { +fn 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 { var tables: ZigTable = undefined; tables.is_symmetric = is_symmetric; @@ -98,8 +104,12 @@ pub const NormDist = blk: { const norm_r = 3.6541528853610088; const norm_v = 0.00492867323399; -fn norm_f(x: f64) f64 { return math.exp(-x * x / 2.0); } -fn norm_f_inv(y: f64) f64 { return math.sqrt(-2.0 * math.ln(y)); } +fn norm_f(x: f64) f64 { + return math.exp(-x * x / 2.0); +} +fn norm_f_inv(y: f64) f64 { + return math.sqrt(-2.0 * math.ln(y)); +} fn norm_zero_case(random: &Random, u: f64) f64 { var x: f64 = 1; var y: f64 = 0; @@ -133,9 +143,15 @@ pub const ExpDist = blk: { const exp_r = 7.69711747013104972; const exp_v = 0.0039496598225815571993; -fn exp_f(x: f64) f64 { return math.exp(-x); } -fn exp_f_inv(y: f64) f64 { return -math.ln(y); } -fn exp_zero_case(random: &Random, _: f64) f64 { return exp_r - math.ln(random.float(f64)); } +fn exp_f(x: f64) f64 { + return math.exp(-x); +} +fn exp_f_inv(y: f64) f64 { + return -math.ln(y); +} +fn exp_zero_case(random: &Random, _: f64) f64 { + return exp_r - math.ln(random.float(f64)); +} test "ziggurant exp dist sanity" { var prng = std.rand.DefaultPrng.init(0); diff --git a/std/segmented_list.zig b/std/segmented_list.zig index 098378de4e..d755135fe8 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -5,7 +5,7 @@ const Allocator = std.mem.Allocator; // Imagine that `fn at(self: &Self, index: usize) &T` is a customer asking for a box // from a warehouse, based on a flat array, boxes ordered from 0 to N - 1. // But the warehouse actually stores boxes in shelves of increasing powers of 2 sizes. -// So when the customer requests a box index, we have to translate it to shelf index +// So when the customer requests a box index, we have to translate it to shelf index // and box index within that shelf. Illustration: // // customer indexes: @@ -37,14 +37,14 @@ const Allocator = std.mem.Allocator; // Now we complicate it a little bit further by adding a preallocated shelf, which must be // a power of 2: // prealloc=4 -// +// // customer indexes: // prealloc: 0 1 2 3 // shelf 0: 4 5 6 7 8 9 10 11 // shelf 1: 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // shelf 2: 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 // ... -// +// // warehouse indexes: // prealloc: 0 1 2 3 // shelf 0: 0 1 2 3 4 5 6 7 diff --git a/std/sort.zig b/std/sort.zig index 4cc7ad503a..5596c9063d 100644 --- a/std/sort.zig +++ b/std/sort.zig @@ -317,7 +317,6 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // 6. merge each A block with any B values that follow, using the cache or the second internal buffer // 7. sort the second internal buffer if it exists // 8. redistribute the two internal buffers back into the items - var block_size: usize = math.sqrt(iterator.length()); var buffer_size = iterator.length() / block_size + 1; diff --git a/std/special/bootstrap.zig b/std/special/bootstrap.zig index 056ab35003..c10f4aa806 100644 --- a/std/special/bootstrap.zig +++ b/std/special/bootstrap.zig @@ -27,10 +27,14 @@ extern fn zen_start() noreturn { nakedcc fn _start() noreturn { switch (builtin.arch) { builtin.Arch.x86_64 => { - argc_ptr = asm ("lea (%%rsp), %[argc]" : [argc] "=r" (-> &usize)); + argc_ptr = asm ("lea (%%rsp), %[argc]" + : [argc] "=r" (-> &usize) + ); }, builtin.Arch.i386 => { - argc_ptr = asm ("lea (%%esp), %[argc]" : [argc] "=r" (-> &usize)); + argc_ptr = asm ("lea (%%esp), %[argc]" + : [argc] "=r" (-> &usize) + ); }, else => @compileError("unsupported arch"), } diff --git a/std/special/bootstrap_lib.zig b/std/special/bootstrap_lib.zig index f55aaed96a..f029495cb0 100644 --- a/std/special/bootstrap_lib.zig +++ b/std/special/bootstrap_lib.zig @@ -7,8 +7,10 @@ comptime { @export("_DllMainCRTStartup", _DllMainCRTStartup, builtin.GlobalLinkage.Strong); } -stdcallcc fn _DllMainCRTStartup(hinstDLL: std.os.windows.HINSTANCE, fdwReason: std.os.windows.DWORD, - lpReserved: std.os.windows.LPVOID) std.os.windows.BOOL -{ +stdcallcc fn _DllMainCRTStartup( + hinstDLL: std.os.windows.HINSTANCE, + fdwReason: std.os.windows.DWORD, + lpReserved: std.os.windows.LPVOID, +) std.os.windows.BOOL { return std.os.windows.TRUE; } diff --git a/std/special/build_runner.zig b/std/special/build_runner.zig index e1a35f6648..cf8f19d49e 100644 --- a/std/special/build_runner.zig +++ b/std/special/build_runner.zig @@ -24,7 +24,6 @@ pub fn main() !void { const allocator = &arena.allocator; - // skip my own exe name _ = arg_it.skip(); @@ -175,8 +174,7 @@ fn usage(builder: &Builder, already_ran_build: bool, out_stream: var) !void { try out_stream.print(" (none)\n"); } else { for (builder.available_options_list.toSliceConst()) |option| { - const name = try fmt.allocPrint(allocator, - " -D{}=[{}]", option.name, Builder.typeIdName(option.type_id)); + const name = try fmt.allocPrint(allocator, " -D{}=[{}]", option.name, Builder.typeIdName(option.type_id)); defer allocator.free(name); try out_stream.print("{s24} {}\n", name, option.description); } @@ -202,7 +200,7 @@ fn usageAndErr(builder: &Builder, already_ran_build: bool, out_stream: var) erro return error.InvalidArgs; } -const UnwrapArgError = error {OutOfMemory}; +const UnwrapArgError = error{OutOfMemory}; fn unwrapArg(arg: UnwrapArgError![]u8) UnwrapArgError![]u8 { return arg catch |err| { diff --git a/std/special/builtin.zig b/std/special/builtin.zig index a5126bc4f3..63149d5161 100644 --- a/std/special/builtin.zig +++ b/std/special/builtin.zig @@ -56,7 +56,8 @@ export fn memmove(dest: ?&u8, src: ?&const u8, n: usize) ?&u8 { comptime { if (builtin.mode != builtin.Mode.ReleaseFast and builtin.mode != builtin.Mode.ReleaseSmall and - builtin.os != builtin.Os.windows) { + builtin.os != builtin.Os.windows) + { @export("__stack_chk_fail", __stack_chk_fail, builtin.GlobalLinkage.Strong); } if (builtin.os == builtin.Os.linux and builtin.arch == builtin.Arch.x86_64) { @@ -101,15 +102,27 @@ nakedcc fn clone() void { const math = @import("../math/index.zig"); -export fn fmodf(x: f32, y: f32) f32 { return generic_fmod(f32, x, y); } -export fn fmod(x: f64, y: f64) f64 { return generic_fmod(f64, x, y); } +export fn fmodf(x: f32, y: f32) f32 { + return generic_fmod(f32, x, y); +} +export fn fmod(x: f64, y: f64) f64 { + return generic_fmod(f64, x, y); +} // TODO add intrinsics for these (and probably the double version too) // and have the math stuff use the intrinsic. same as @mod and @rem -export fn floorf(x: f32) f32 { return math.floor(x); } -export fn ceilf(x: f32) f32 { return math.ceil(x); } -export fn floor(x: f64) f64 { return math.floor(x); } -export fn ceil(x: f64) f64 { return math.ceil(x); } +export fn floorf(x: f32) f32 { + return math.floor(x); +} +export fn ceilf(x: f32) f32 { + return math.ceil(x); +} +export fn floor(x: f64) f64 { + return math.floor(x); +} +export fn ceil(x: f64) f64 { + return math.ceil(x); +} fn generic_fmod(comptime T: type, x: T, y: T) T { @setRuntimeSafety(false); @@ -139,7 +152,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { // normalize x and y if (ex == 0) { i = ux << exp_bits; - while (i >> bits_minus_1 == 0) : (b: {ex -= 1; break :b i <<= 1;}) {} + while (i >> bits_minus_1 == 0) : (b: { + ex -= 1; + i <<= 1; + }) {} ux <<= log2uint(@bitCast(u32, -ex + 1)); } else { ux &= @maxValue(uint) >> exp_bits; @@ -147,7 +163,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { } if (ey == 0) { i = uy << exp_bits; - while (i >> bits_minus_1 == 0) : (b: {ey -= 1; break :b i <<= 1;}) {} + while (i >> bits_minus_1 == 0) : (b: { + ey -= 1; + i <<= 1; + }) {} uy <<= log2uint(@bitCast(u32, -ey + 1)); } else { uy &= @maxValue(uint) >> exp_bits; @@ -170,7 +189,10 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { return 0 * x; ux = i; } - while (ux >> digits == 0) : (b: {ux <<= 1; break :b ex -= 1;}) {} + while (ux >> digits == 0) : (b: { + ux <<= 1; + ex -= 1; + }) {} // scale result up if (ex > 0) { @@ -298,7 +320,7 @@ export fn sqrt(x: f64) f64 { // rounding direction if (ix0 | ix1 != 0) { - var z = 1.0 - tiny; // raise inexact + var z = 1.0 - tiny; // raise inexact if (z >= 1.0) { z = 1.0 + tiny; if (q1 == 0xFFFFFFFF) { @@ -336,13 +358,13 @@ export fn sqrtf(x: f32) f32 { var ix: i32 = @bitCast(i32, x); if ((ix & 0x7F800000) == 0x7F800000) { - return x * x + x; // sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = snan + return x * x + x; // sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = snan } // zero if (ix <= 0) { if (ix & ~sign == 0) { - return x; // sqrt (+-0) = +-0 + return x; // sqrt (+-0) = +-0 } if (ix < 0) { return math.snan(f32); @@ -360,20 +382,20 @@ export fn sqrtf(x: f32) f32 { m -= i - 1; } - m -= 127; // unbias exponent + m -= 127; // unbias exponent ix = (ix & 0x007FFFFF) | 0x00800000; - if (m & 1 != 0) { // odd m, double x to even + if (m & 1 != 0) { // odd m, double x to even ix += ix; } - m >>= 1; // m = [m / 2] + m >>= 1; // m = [m / 2] // sqrt(x) bit by bit ix += ix; - var q: i32 = 0; // q = sqrt(x) + var q: i32 = 0; // q = sqrt(x) var s: i32 = 0; - var r: i32 = 0x01000000; // r = moving bit right -> left + var r: i32 = 0x01000000; // r = moving bit right -> left while (r != 0) { const t = s + r; @@ -388,7 +410,7 @@ export fn sqrtf(x: f32) f32 { // floating add to find rounding direction if (ix != 0) { - var z = 1.0 - tiny; // inexact + var z = 1.0 - tiny; // inexact if (z >= 1.0) { z = 1.0 + tiny; if (z > 1.0) { diff --git a/std/special/compiler_rt/comparetf2.zig b/std/special/compiler_rt/comparetf2.zig index 760c3689c0..d63b7a7c92 100644 --- a/std/special/compiler_rt/comparetf2.zig +++ b/std/special/compiler_rt/comparetf2.zig @@ -38,25 +38,22 @@ pub extern fn __letf2(a: f128, b: f128) c_int { // If at least one of a and b is positive, we get the same result comparing // a and b as signed integers as we would with a floating-point compare. - return if ((aInt & bInt) >= 0) - if (aInt < bInt) - LE_LESS - else if (aInt == bInt) - LE_EQUAL - else - LE_GREATER + return if ((aInt & bInt) >= 0) if (aInt < bInt) + LE_LESS + else if (aInt == bInt) + LE_EQUAL else - // Otherwise, both are negative, so we need to flip the sense of the - // comparison to get the correct result. (This assumes a twos- or ones- - // complement integer representation; if integers are represented in a - // sign-magnitude representation, then this flip is incorrect). - if (aInt > bInt) - LE_LESS - else if (aInt == bInt) - LE_EQUAL - else - LE_GREATER - ; + LE_GREATER else + // Otherwise, both are negative, so we need to flip the sense of the + // comparison to get the correct result. (This assumes a twos- or ones- + // complement integer representation; if integers are represented in a + // sign-magnitude representation, then this flip is incorrect). + if (aInt > bInt) + LE_LESS + else if (aInt == bInt) + LE_EQUAL + else + LE_GREATER; } // TODO https://github.com/ziglang/zig/issues/305 @@ -76,21 +73,17 @@ pub extern fn __getf2(a: f128, b: f128) c_int { if (aAbs > infRep or bAbs > infRep) return GE_UNORDERED; if ((aAbs | bAbs) == 0) return GE_EQUAL; - return if ((aInt & bInt) >= 0) - if (aInt < bInt) - GE_LESS - else if (aInt == bInt) - GE_EQUAL - else - GE_GREATER + return if ((aInt & bInt) >= 0) if (aInt < bInt) + GE_LESS + else if (aInt == bInt) + GE_EQUAL + else + GE_GREATER else if (aInt > bInt) + GE_LESS + else if (aInt == bInt) + GE_EQUAL else - if (aInt > bInt) - GE_LESS - else if (aInt == bInt) - GE_EQUAL - else - GE_GREATER - ; + GE_GREATER; } pub extern fn __unordtf2(a: f128, b: f128) c_int { diff --git a/std/special/compiler_rt/fixunsdfti_test.zig b/std/special/compiler_rt/fixunsdfti_test.zig index 7283b35c0e..7f7b083d19 100644 --- a/std/special/compiler_rt/fixunsdfti_test.zig +++ b/std/special/compiler_rt/fixunsdfti_test.zig @@ -44,4 +44,3 @@ test "fixunsdfti" { test__fixunsdfti(-0x1.FFFFFFFFFFFFFp+62, 0); test__fixunsdfti(-0x1.FFFFFFFFFFFFEp+62, 0); } - diff --git a/std/special/compiler_rt/index.zig b/std/special/compiler_rt/index.zig index b051ccfc9d..3e014d4d16 100644 --- a/std/special/compiler_rt/index.zig +++ b/std/special/compiler_rt/index.zig @@ -92,10 +92,10 @@ pub fn setXmm0(comptime T: type, value: T) void { const aligned_value: T align(16) = value; asm volatile ( \\movaps (%[ptr]), %%xmm0 - - : + : : [ptr] "r" (&aligned_value) - : "xmm0"); + : "xmm0" + ); } extern fn __udivdi3(a: u64, b: u64) u64 { @@ -159,7 +159,8 @@ fn isArmArch() bool { builtin.Arch.armebv6t2, builtin.Arch.armebv5, builtin.Arch.armebv5te, - builtin.Arch.armebv4t => true, + builtin.Arch.armebv4t, + => true, else => false, }; } @@ -174,7 +175,10 @@ nakedcc fn __aeabi_uidivmod() void { \\ ldr r1, [sp] \\ add sp, sp, #4 \\ pop { pc } - ::: "r2", "r1"); + : + : + : "r2", "r1" + ); } // _chkstk (_alloca) routine - probe stack between %esp and (%esp-%eax) in 4k increments, diff --git a/std/unicode.zig b/std/unicode.zig index 300e129647..8bcc2705dd 100644 --- a/std/unicode.zig +++ b/std/unicode.zig @@ -58,6 +58,7 @@ pub fn utf8Encode(c: u32, out: []u8) !u3 { } const Utf8DecodeError = Utf8Decode2Error || Utf8Decode3Error || Utf8Decode4Error; + /// Decodes the UTF-8 codepoint encoded in the given slice of bytes. /// bytes.len must be equal to utf8ByteSequenceLength(bytes[0]) catch unreachable. /// If you already know the length at comptime, you can call one of @@ -150,7 +151,9 @@ pub fn utf8ValidateSlice(s: []const u8) bool { return false; } - if (utf8Decode(s[i..i+cp_len])) |_| {} else |_| { return false; } + if (utf8Decode(s[i..i + cp_len])) |_| {} else |_| { + return false; + } i += cp_len; } else |err| { return false; @@ -179,9 +182,7 @@ pub const Utf8View = struct { } pub fn initUnchecked(s: []const u8) Utf8View { - return Utf8View { - .bytes = s, - }; + return Utf8View{ .bytes = s }; } pub fn initComptime(comptime s: []const u8) Utf8View { @@ -191,12 +192,12 @@ pub const Utf8View = struct { error.InvalidUtf8 => { @compileError("invalid utf8"); unreachable; - } + }, } } pub fn iterator(s: &const Utf8View) Utf8Iterator { - return Utf8Iterator { + return Utf8Iterator{ .bytes = s.bytes, .i = 0, }; @@ -215,7 +216,7 @@ const Utf8Iterator = struct { const cp_len = utf8ByteSequenceLength(it.bytes[it.i]) catch unreachable; it.i += cp_len; - return it.bytes[it.i-cp_len..it.i]; + return it.bytes[it.i - cp_len..it.i]; } pub fn nextCodepoint(it: &Utf8Iterator) ?u32 { @@ -304,9 +305,12 @@ test "utf8 view bad" { fn testUtf8ViewBad() void { // Compile-time error. // const s3 = Utf8View.initComptime("\xfe\xf2"); - const s = Utf8View.init("hel\xadlo"); - if (s) |_| { unreachable; } else |err| { debug.assert(err == error.InvalidUtf8); } + if (s) |_| { + unreachable; + } else |err| { + debug.assert(err == error.InvalidUtf8); + } } test "utf8 view ok" { diff --git a/std/zig/ast.zig b/std/zig/ast.zig index e86c40e310..3e1b4fe16a 100644 --- a/std/zig/ast.zig +++ b/std/zig/ast.zig @@ -388,7 +388,8 @@ pub const Node = struct { Id.SwitchElse, Id.FieldInitializer, Id.DocComment, - Id.TestDecl => return false, + Id.TestDecl, + => return false, Id.While => { const while_node = @fieldParentPtr(While, "base", n); if (while_node.@"else") |@"else"| { @@ -608,8 +609,7 @@ pub const Node = struct { if (i < 1) return t; i -= 1; }, - InitArg.None, - InitArg.Enum => {}, + InitArg.None, InitArg.Enum => {}, } if (i < self.fields_and_decls.len) return self.fields_and_decls.at(i).*; @@ -1475,7 +1475,8 @@ pub const Node = struct { Op.Range, Op.Sub, Op.SubWrap, - Op.UnwrapMaybe => {}, + Op.UnwrapMaybe, + => {}, } if (i < 1) return self.rhs; diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 1bc64c3ddb..05554f5d34 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -81,10 +81,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try root_node.decls.push(&test_node.base); try stack.append(State{ .Block = block }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.LBrace, - .ptr = &block.lbrace, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.LBrace, + .ptr = &block.lbrace, + }, + }); try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &test_node.name } }); continue; }, @@ -95,13 +97,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, Token.Id.Keyword_pub => { stack.append(State.TopLevel) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &root_node.decls, - .visib_token = token_index, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &root_node.decls, + .visib_token = token_index, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + }, + }); continue; }, Token.Id.Keyword_comptime => { @@ -122,22 +126,26 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State.TopLevel) catch unreachable; try stack.append(State{ .Block = block }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.LBrace, - .ptr = &block.lbrace, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.LBrace, + .ptr = &block.lbrace, + }, + }); continue; }, else => { prevToken(&tok_it, &tree); stack.append(State.TopLevel) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &root_node.decls, - .visib_token = null, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &root_node.decls, + .visib_token = null, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + }, + }); continue; }, } @@ -147,31 +155,34 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; switch (token_ptr.id) { - Token.Id.Keyword_export, - Token.Id.Keyword_inline => { - stack.append(State{ .TopLevelDecl = TopLevelDeclCtx{ - .decls = ctx.decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = AnnotatedToken{ - .index = token_index, - .ptr = token_ptr, + Token.Id.Keyword_export, Token.Id.Keyword_inline => { + stack.append(State{ + .TopLevelDecl = TopLevelDeclCtx{ + .decls = ctx.decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = AnnotatedToken{ + .index = token_index, + .ptr = token_ptr, + }, + .lib_name = null, + .comments = ctx.comments, }, - .lib_name = null, - .comments = ctx.comments, - } }) catch unreachable; + }) catch unreachable; continue; }, Token.Id.Keyword_extern => { - stack.append(State{ .TopLevelLibname = TopLevelDeclCtx{ - .decls = ctx.decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = AnnotatedToken{ - .index = token_index, - .ptr = token_ptr, + stack.append(State{ + .TopLevelLibname = TopLevelDeclCtx{ + .decls = ctx.decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = AnnotatedToken{ + .index = token_index, + .ptr = token_ptr, + }, + .lib_name = null, + .comments = ctx.comments, }, - .lib_name = null, - .comments = ctx.comments, - } }) catch unreachable; + }) catch unreachable; continue; }, else => { @@ -192,13 +203,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }; }; - stack.append(State{ .TopLevelDecl = TopLevelDeclCtx{ - .decls = ctx.decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = ctx.extern_export_inline_token, - .lib_name = lib_name, - .comments = ctx.comments, - } }) catch unreachable; + stack.append(State{ + .TopLevelDecl = TopLevelDeclCtx{ + .decls = ctx.decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = ctx.extern_export_inline_token, + .lib_name = lib_name, + .comments = ctx.comments, + }, + }) catch unreachable; continue; }, State.TopLevelDecl => |ctx| { @@ -222,15 +235,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try ctx.decls.push(&node.base); - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Semicolon, - .ptr = &node.semicolon_token, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Semicolon, + .ptr = &node.semicolon_token, + }, + }) catch unreachable; try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); continue; }, - Token.Id.Keyword_var, - Token.Id.Keyword_const => { + Token.Id.Keyword_var, Token.Id.Keyword_const => { if (ctx.extern_export_inline_token) |annotated_token| { if (annotated_token.ptr.id == Token.Id.Keyword_inline) { ((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 { } } - try stack.append(State{ .VarDecl = VarDeclCtx{ - .comments = ctx.comments, - .visib_token = ctx.visib_token, - .lib_name = ctx.lib_name, - .comptime_token = null, - .extern_export_token = if (ctx.extern_export_inline_token) |at| at.index else null, - .mut_token = token_index, - .list = ctx.decls, - } }); + try stack.append(State{ + .VarDecl = VarDeclCtx{ + .comments = ctx.comments, + .visib_token = ctx.visib_token, + .lib_name = ctx.lib_name, + .comptime_token = null, + .extern_export_token = if (ctx.extern_export_inline_token) |at| at.index else null, + .mut_token = token_index, + .list = ctx.decls, + }, + }); continue; }, - Token.Id.Keyword_fn, - Token.Id.Keyword_nakedcc, - Token.Id.Keyword_stdcallcc, - Token.Id.Keyword_async => { + Token.Id.Keyword_fn, Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc, Token.Id.Keyword_async => { const fn_proto = try arena.construct(ast.Node.FnProto{ .base = ast.Node{ .id = ast.Node.Id.FnProto }, .doc_comments = ctx.comments, @@ -274,13 +287,14 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .FnProto = fn_proto }); switch (token_ptr.id) { - Token.Id.Keyword_nakedcc, - Token.Id.Keyword_stdcallcc => { + Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc => { fn_proto.cc_token = token_index; - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Keyword_fn, - .ptr = &fn_proto.fn_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Keyword_fn, + .ptr = &fn_proto.fn_token, + }, + }); continue; }, Token.Id.Keyword_async => { @@ -292,10 +306,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); fn_proto.async_attr = async_node; - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Keyword_fn, - .ptr = &fn_proto.fn_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Keyword_fn, + .ptr = &fn_proto.fn_token, + }, + }); try stack.append(State{ .AsyncAllocator = async_node }); continue; }, @@ -331,13 +347,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } stack.append(State{ .ContainerDecl = ctx.container_decl }) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &ctx.container_decl.fields_and_decls, - .visib_token = ctx.visib_token, - .extern_export_inline_token = null, - .lib_name = null, - .comments = ctx.comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &ctx.container_decl.fields_and_decls, + .visib_token = ctx.visib_token, + .extern_export_inline_token = null, + .lib_name = null, + .comments = ctx.comments, + }, + }); continue; }, @@ -361,9 +379,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .base = ast.Node{ .id = ast.Node.Id.ContainerDecl }, .layout_token = ctx.layout_token, .kind_token = switch (token_ptr.id) { - Token.Id.Keyword_struct, - Token.Id.Keyword_union, - Token.Id.Keyword_enum => token_index, + Token.Id.Keyword_struct, Token.Id.Keyword_union, Token.Id.Keyword_enum => token_index, else => { ((try tree.errors.addOne())).* = Error{ .ExpectedAggregateKw = Error.ExpectedAggregateKw{ .token = token_index } }; return tree; @@ -377,10 +393,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { ctx.opt_ctx.store(&node.base); stack.append(State{ .ContainerDecl = node }) catch unreachable; - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.LBrace, - .ptr = &node.lbrace_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.LBrace, + .ptr = &node.lbrace_token, + }, + }); try stack.append(State{ .ContainerInitArgStart = node }); continue; }, @@ -481,35 +499,41 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.Keyword_pub => { switch (tree.tokens.at(container_decl.kind_token).id) { Token.Id.Keyword_struct => { - try stack.append(State{ .TopLevelExternOrField = TopLevelExternOrFieldCtx{ - .visib_token = token_index, - .container_decl = container_decl, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExternOrField = TopLevelExternOrFieldCtx{ + .visib_token = token_index, + .container_decl = container_decl, + .comments = comments, + }, + }); continue; }, else => { stack.append(State{ .ContainerDecl = container_decl }) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &container_decl.fields_and_decls, - .visib_token = token_index, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &container_decl.fields_and_decls, + .visib_token = token_index, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + }, + }); continue; }, } }, Token.Id.Keyword_export => { stack.append(State{ .ContainerDecl = container_decl }) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &container_decl.fields_and_decls, - .visib_token = token_index, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &container_decl.fields_and_decls, + .visib_token = token_index, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + }, + }); continue; }, Token.Id.RBrace => { @@ -523,13 +547,15 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { else => { prevToken(&tok_it, &tree); stack.append(State{ .ContainerDecl = container_decl }) catch unreachable; - try stack.append(State{ .TopLevelExtern = TopLevelDeclCtx{ - .decls = &container_decl.fields_and_decls, - .visib_token = null, - .extern_export_inline_token = null, - .lib_name = null, - .comments = comments, - } }); + try stack.append(State{ + .TopLevelExtern = TopLevelDeclCtx{ + .decls = &container_decl.fields_and_decls, + .visib_token = null, + .extern_export_inline_token = null, + .lib_name = null, + .comments = comments, + }, + }); continue; }, } @@ -557,10 +583,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .VarDeclAlign = var_decl }); try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &var_decl.type_node } }); try stack.append(State{ .IfToken = Token.Id.Colon }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Identifier, - .ptr = &var_decl.name_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Identifier, + .ptr = &var_decl.name_token, + }, + }); continue; }, State.VarDeclAlign => |var_decl| { @@ -605,10 +633,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const semicolon_token = nextToken(&tok_it, &tree); if (semicolon_token.ptr.id != Token.Id.Semicolon) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = semicolon_token.index, - .expected_id = Token.Id.Semicolon, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = semicolon_token.index, + .expected_id = Token.Id.Semicolon, + }, + }; return tree; } @@ -713,10 +743,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try fn_proto.params.push(¶m_decl.base); - stack.append(State{ .ParamDeclEnd = ParamDeclEndCtx{ - .param_decl = param_decl, - .fn_proto = fn_proto, - } }) catch unreachable; + stack.append(State{ + .ParamDeclEnd = ParamDeclEndCtx{ + .param_decl = param_decl, + .fn_proto = fn_proto, + }, + }) catch unreachable; try stack.append(State{ .ParamDeclName = param_decl }); try stack.append(State{ .ParamDeclAliasOrComptime = param_decl }); continue; @@ -769,10 +801,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { State.MaybeLabeledExpression => |ctx| { if (eatToken(&tok_it, &tree, Token.Id.Colon)) |_| { - stack.append(State{ .LabeledExpression = LabelCtx{ - .label = ctx.label, - .opt_ctx = ctx.opt_ctx, - } }) catch unreachable; + stack.append(State{ + .LabeledExpression = LabelCtx{ + .label = ctx.label, + .opt_ctx = ctx.opt_ctx, + }, + }) catch unreachable; continue; } @@ -797,21 +831,25 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Keyword_while => { - stack.append(State{ .While = LoopCtx{ - .label = ctx.label, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } }) catch unreachable; + stack.append(State{ + .While = LoopCtx{ + .label = ctx.label, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + }, + }) catch unreachable; continue; }, Token.Id.Keyword_for => { - stack.append(State{ .For = LoopCtx{ - .label = ctx.label, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } }) catch unreachable; + stack.append(State{ + .For = LoopCtx{ + .label = ctx.label, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + }, + }) catch unreachable; continue; }, Token.Id.Keyword_suspend => { @@ -828,11 +866,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Keyword_inline => { - stack.append(State{ .Inline = InlineCtx{ - .label = ctx.label, - .inline_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } }) catch unreachable; + stack.append(State{ + .Inline = InlineCtx{ + .label = ctx.label, + .inline_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + }, + }) catch unreachable; continue; }, else => { @@ -852,21 +892,25 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.Keyword_while => { - stack.append(State{ .While = LoopCtx{ - .inline_token = ctx.inline_token, - .label = ctx.label, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } }) catch unreachable; + stack.append(State{ + .While = LoopCtx{ + .inline_token = ctx.inline_token, + .label = ctx.label, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + }, + }) catch unreachable; continue; }, Token.Id.Keyword_for => { - stack.append(State{ .For = LoopCtx{ - .inline_token = ctx.inline_token, - .label = ctx.label, - .loop_token = token_index, - .opt_ctx = ctx.opt_ctx.toRequired(), - } }) catch unreachable; + stack.append(State{ + .For = LoopCtx{ + .inline_token = ctx.inline_token, + .label = ctx.label, + .loop_token = token_index, + .opt_ctx = ctx.opt_ctx.toRequired(), + }, + }) catch unreachable; continue; }, else => { @@ -971,27 +1015,29 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; switch (token_ptr.id) { Token.Id.Keyword_comptime => { - stack.append(State{ .ComptimeStatement = ComptimeStatementCtx{ - .comptime_token = token_index, - .block = block, - } }) catch unreachable; - continue; - }, - Token.Id.Keyword_var, - Token.Id.Keyword_const => { - stack.append(State{ .VarDecl = VarDeclCtx{ - .comments = null, - .visib_token = null, - .comptime_token = null, - .extern_export_token = null, - .lib_name = null, - .mut_token = token_index, - .list = &block.statements, - } }) catch unreachable; + stack.append(State{ + .ComptimeStatement = ComptimeStatementCtx{ + .comptime_token = token_index, + .block = block, + }, + }) catch unreachable; + continue; + }, + Token.Id.Keyword_var, Token.Id.Keyword_const => { + stack.append(State{ + .VarDecl = VarDeclCtx{ + .comments = null, + .visib_token = null, + .comptime_token = null, + .extern_export_token = null, + .lib_name = null, + .mut_token = token_index, + .list = &block.statements, + }, + }) catch unreachable; continue; }, - Token.Id.Keyword_defer, - Token.Id.Keyword_errdefer => { + Token.Id.Keyword_defer, Token.Id.Keyword_errdefer => { const node = try arena.construct(ast.Node.Defer{ .base = ast.Node{ .id = ast.Node.Id.Defer }, .defer_token = token_index, @@ -1036,17 +1082,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; switch (token_ptr.id) { - Token.Id.Keyword_var, - Token.Id.Keyword_const => { - stack.append(State{ .VarDecl = VarDeclCtx{ - .comments = null, - .visib_token = null, - .comptime_token = ctx.comptime_token, - .extern_export_token = null, - .lib_name = null, - .mut_token = token_index, - .list = &ctx.block.statements, - } }) catch unreachable; + Token.Id.Keyword_var, Token.Id.Keyword_const => { + stack.append(State{ + .VarDecl = VarDeclCtx{ + .comments = null, + .visib_token = null, + .comptime_token = ctx.comptime_token, + .extern_export_token = null, + .lib_name = null, + .mut_token = token_index, + .list = &ctx.block.statements, + }, + }) catch unreachable; continue; }, else => { @@ -1089,10 +1136,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .AsmOutputItems = items }) catch unreachable; try stack.append(State{ .IfToken = Token.Id.Comma }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.RParen, - .ptr = &node.rparen, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + }, + }); try stack.append(State{ .AsmOutputReturnOrType = node }); try stack.append(State{ .ExpectToken = Token.Id.LParen }); try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } }); @@ -1141,10 +1190,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .AsmInputItems = items }) catch unreachable; try stack.append(State{ .IfToken = Token.Id.Comma }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.RParen, - .ptr = &node.rparen, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + }, + }); try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); try stack.append(State{ .ExpectToken = Token.Id.LParen }); try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.constraint } }); @@ -1203,14 +1254,18 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .FieldInitListCommaOrEnd = list_state }) catch unreachable; try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); try stack.append(State{ .ExpectToken = Token.Id.Equal }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Identifier, - .ptr = &node.name_token, - } }); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Period, - .ptr = &node.period_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Identifier, + .ptr = &node.name_token, + }, + }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Period, + .ptr = &node.period_token, + }, + }); continue; }, State.FieldInitListCommaOrEnd => |list_state| { @@ -1320,10 +1375,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); try switch_case.items.push(&else_node.base); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.EqualAngleBracketRight, - .ptr = &switch_case.arrow_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.EqualAngleBracketRight, + .ptr = &switch_case.arrow_token, + }, + }); continue; } else { prevToken(&tok_it, &tree); @@ -1374,10 +1431,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } async_node.rangle_bracket = TokenIndex(0); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.AngleBracketRight, - .ptr = &??async_node.rangle_bracket, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.AngleBracketRight, + .ptr = &??async_node.rangle_bracket, + }, + }); try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &async_node.allocator_type } }); continue; }, @@ -1430,10 +1489,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; } - stack.append(State{ .ContainerKind = ContainerKindCtx{ - .opt_ctx = ctx.opt_ctx, - .layout_token = ctx.extern_token, - } }) catch unreachable; + stack.append(State{ + .ContainerKind = ContainerKindCtx{ + .opt_ctx = ctx.opt_ctx, + .layout_token = ctx.extern_token, + }, + }) catch unreachable; continue; }, State.SliceOrArrayAccess => |node| { @@ -1443,15 +1504,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { switch (token_ptr.id) { Token.Id.Ellipsis2 => { const start = node.op.ArrayAccess; - node.op = ast.Node.SuffixOp.Op{ .Slice = ast.Node.SuffixOp.Op.Slice{ - .start = start, - .end = null, - } }; + node.op = ast.Node.SuffixOp.Op{ + .Slice = ast.Node.SuffixOp.Op.Slice{ + .start = start, + .end = null, + }, + }; - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.RBracket, - .ptr = &node.rtoken, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RBracket, + .ptr = &node.rtoken, + }, + }) catch unreachable; try stack.append(State{ .Expression = OptionalCtx{ .Optional = &node.op.Slice.end } }); continue; }, @@ -1467,11 +1532,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }, State.SliceOrArrayType => |node| { if (eatToken(&tok_it, &tree, Token.Id.RBracket)) |_| { - node.op = ast.Node.PrefixOp.Op{ .SliceType = ast.Node.PrefixOp.AddrOfInfo{ - .align_info = null, - .const_token = null, - .volatile_token = null, - } }; + node.op = ast.Node.PrefixOp.Op{ + .SliceType = ast.Node.PrefixOp.AddrOfInfo{ + .align_info = null, + .const_token = null, + .volatile_token = null, + }, + }; stack.append(State{ .TypeExprBegin = OptionalCtx{ .Required = &node.rhs } }) catch unreachable; try stack.append(State{ .AddrOfModifiers = &node.op.SliceType }); continue; @@ -1495,7 +1562,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { ((try tree.errors.addOne())).* = Error{ .ExtraAlignQualifier = Error.ExtraAlignQualifier{ .token = token_index } }; return tree; } - addr_of_info.align_info = ast.Node.PrefixOp.AddrOfInfo.Align { + addr_of_info.align_info = ast.Node.PrefixOp.AddrOfInfo.Align{ .node = undefined, .bit_range = null, }; @@ -1548,9 +1615,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { Token.Id.RParen => continue, else => { (try tree.errors.addOne()).* = Error{ - .ExpectedColonOrRParen = Error.ExpectedColonOrRParen{ - .token = token.index, - } + .ExpectedColonOrRParen = Error.ExpectedColonOrRParen{ .token = token.index }, }; return tree; }, @@ -1563,10 +1628,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; if (token_ptr.id != Token.Id.Pipe) { if (opt_ctx != OptionalCtx.Optional) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = Token.Id.Pipe, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Pipe, + }, + }; return tree; } @@ -1582,10 +1649,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Pipe, - .ptr = &node.rpipe, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Pipe, + .ptr = &node.rpipe, + }, + }) catch unreachable; try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.error_symbol } }); continue; }, @@ -1595,10 +1664,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; if (token_ptr.id != Token.Id.Pipe) { if (opt_ctx != OptionalCtx.Optional) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = Token.Id.Pipe, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Pipe, + }, + }; return tree; } @@ -1615,15 +1686,19 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Pipe, - .ptr = &node.rpipe, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Pipe, + .ptr = &node.rpipe, + }, + }); try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.value_symbol } }); - try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{ - .id = Token.Id.Asterisk, - .ptr = &node.ptr_token, - } }); + try stack.append(State{ + .OptionalTokenSave = OptionalTokenSave{ + .id = Token.Id.Asterisk, + .ptr = &node.ptr_token, + }, + }); continue; }, State.PointerIndexPayload => |opt_ctx| { @@ -1632,10 +1707,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_ptr = token.ptr; if (token_ptr.id != Token.Id.Pipe) { if (opt_ctx != OptionalCtx.Optional) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = Token.Id.Pipe, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Pipe, + }, + }; return tree; } @@ -1653,17 +1730,21 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Pipe, - .ptr = &node.rpipe, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Pipe, + .ptr = &node.rpipe, + }, + }) catch unreachable; try stack.append(State{ .Identifier = OptionalCtx{ .RequiredNull = &node.index_symbol } }); try stack.append(State{ .IfToken = Token.Id.Comma }); try stack.append(State{ .Identifier = OptionalCtx{ .Required = &node.value_symbol } }); - try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{ - .id = Token.Id.Asterisk, - .ptr = &node.ptr_token, - } }); + try stack.append(State{ + .OptionalTokenSave = OptionalTokenSave{ + .id = Token.Id.Asterisk, + .ptr = &node.ptr_token, + }, + }); continue; }, @@ -1672,9 +1753,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; switch (token_ptr.id) { - Token.Id.Keyword_return, - Token.Id.Keyword_break, - Token.Id.Keyword_continue => { + Token.Id.Keyword_return, Token.Id.Keyword_break, Token.Id.Keyword_continue => { const node = try arena.construct(ast.Node.ControlFlowExpression{ .base = ast.Node{ .id = ast.Node.Id.ControlFlowExpression }, .ltoken = token_index, @@ -1703,9 +1782,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } continue; }, - Token.Id.Keyword_try, - Token.Id.Keyword_cancel, - Token.Id.Keyword_resume => { + Token.Id.Keyword_try, Token.Id.Keyword_cancel, Token.Id.Keyword_resume => { const node = try arena.construct(ast.Node.PrefixOp{ .base = ast.Node{ .id = ast.Node.Id.PrefixOp }, .op_token = token_index, @@ -2078,10 +2155,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State{ .IfToken = Token.Id.LBrace }); - try stack.append(State{ .FieldInitListItemOrEnd = ListSave(@typeOf(node.op.StructInitializer)){ - .list = &node.op.StructInitializer, - .ptr = &node.rtoken, - } }); + try stack.append(State{ + .FieldInitListItemOrEnd = ListSave(@typeOf(node.op.StructInitializer)){ + .list = &node.op.StructInitializer, + .ptr = &node.rtoken, + }, + }); continue; } @@ -2094,11 +2173,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { opt_ctx.store(&node.base); stack.append(State{ .CurlySuffixExpressionEnd = opt_ctx.toRequired() }) catch unreachable; try stack.append(State{ .IfToken = Token.Id.LBrace }); - try stack.append(State{ .ExprListItemOrEnd = ExprListCtx{ - .list = &node.op.ArrayInitializer, - .end = Token.Id.RBrace, - .ptr = &node.rtoken, - } }); + try stack.append(State{ + .ExprListItemOrEnd = ExprListCtx{ + .list = &node.op.ArrayInitializer, + .end = Token.Id.RBrace, + .ptr = &node.rtoken, + }, + }); continue; }, @@ -2171,10 +2252,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { .allocator_type = null, .rangle_bracket = null, }); - stack.append(State{ .AsyncEnd = AsyncEndCtx{ - .ctx = opt_ctx, - .attribute = async_node, - } }) catch unreachable; + stack.append(State{ + .AsyncEnd = AsyncEndCtx{ + .ctx = opt_ctx, + .attribute = async_node, + }, + }) catch unreachable; try stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }); try stack.append(State{ .PrimaryExpression = opt_ctx.toRequired() }); try stack.append(State{ .AsyncAllocator = async_node }); @@ -2197,20 +2280,24 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const node = try arena.construct(ast.Node.SuffixOp{ .base = ast.Node{ .id = ast.Node.Id.SuffixOp }, .lhs = lhs, - .op = ast.Node.SuffixOp.Op{ .Call = ast.Node.SuffixOp.Op.Call{ - .params = ast.Node.SuffixOp.Op.Call.ParamList.init(arena), - .async_attr = null, - } }, + .op = ast.Node.SuffixOp.Op{ + .Call = ast.Node.SuffixOp.Op.Call{ + .params = ast.Node.SuffixOp.Op.Call.ParamList.init(arena), + .async_attr = null, + }, + }, .rtoken = undefined, }); opt_ctx.store(&node.base); stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; - try stack.append(State{ .ExprListItemOrEnd = ExprListCtx{ - .list = &node.op.Call.params, - .end = Token.Id.RParen, - .ptr = &node.rtoken, - } }); + try stack.append(State{ + .ExprListItemOrEnd = ExprListCtx{ + .list = &node.op.Call.params, + .end = Token.Id.RParen, + .ptr = &node.rtoken, + }, + }); continue; }, Token.Id.LBracket => { @@ -2278,8 +2365,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { _ = try createToCtxLiteral(arena, opt_ctx, ast.Node.UndefinedLiteral, token.index); continue; }, - Token.Id.Keyword_true, - Token.Id.Keyword_false => { + Token.Id.Keyword_true, Token.Id.Keyword_false => { _ = try createToCtxLiteral(arena, opt_ctx, ast.Node.BoolLiteral, token.index); continue; }, @@ -2321,8 +2407,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .Expression = OptionalCtx{ .Required = return_type_ptr } }); continue; }, - Token.Id.StringLiteral, - Token.Id.MultilineStringLiteralLine => { + Token.Id.StringLiteral, Token.Id.MultilineStringLiteralLine => { opt_ctx.store((try parseStringLiteral(arena, &tok_it, token.ptr, token.index, &tree)) ?? unreachable); continue; }, @@ -2335,10 +2420,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.RParen, - .ptr = &node.rparen, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + }, + }) catch unreachable; try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); continue; }, @@ -2351,11 +2438,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State{ .ExprListItemOrEnd = ExprListCtx{ - .list = &node.params, - .end = Token.Id.RParen, - .ptr = &node.rparen_token, - } }) catch unreachable; + stack.append(State{ + .ExprListItemOrEnd = ExprListCtx{ + .list = &node.params, + .end = Token.Id.RParen, + .ptr = &node.rparen_token, + }, + }) catch unreachable; try stack.append(State{ .ExpectToken = Token.Id.LParen }); continue; }, @@ -2372,42 +2461,50 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.Keyword_error => { - stack.append(State{ .ErrorTypeOrSetDecl = ErrorTypeOrSetDeclCtx{ - .error_token = token.index, - .opt_ctx = opt_ctx, - } }) catch unreachable; + stack.append(State{ + .ErrorTypeOrSetDecl = ErrorTypeOrSetDeclCtx{ + .error_token = token.index, + .opt_ctx = opt_ctx, + }, + }) catch unreachable; continue; }, Token.Id.Keyword_packed => { - stack.append(State{ .ContainerKind = ContainerKindCtx{ - .opt_ctx = opt_ctx, - .layout_token = token.index, - } }) catch unreachable; + stack.append(State{ + .ContainerKind = ContainerKindCtx{ + .opt_ctx = opt_ctx, + .layout_token = token.index, + }, + }) catch unreachable; continue; }, Token.Id.Keyword_extern => { - stack.append(State{ .ExternType = ExternTypeCtx{ - .opt_ctx = opt_ctx, - .extern_token = token.index, - .comments = null, - } }) catch unreachable; + stack.append(State{ + .ExternType = ExternTypeCtx{ + .opt_ctx = opt_ctx, + .extern_token = token.index, + .comments = null, + }, + }) catch unreachable; continue; }, - Token.Id.Keyword_struct, - Token.Id.Keyword_union, - Token.Id.Keyword_enum => { + Token.Id.Keyword_struct, Token.Id.Keyword_union, Token.Id.Keyword_enum => { prevToken(&tok_it, &tree); - stack.append(State{ .ContainerKind = ContainerKindCtx{ - .opt_ctx = opt_ctx, - .layout_token = null, - } }) catch unreachable; + stack.append(State{ + .ContainerKind = ContainerKindCtx{ + .opt_ctx = opt_ctx, + .layout_token = null, + }, + }) catch unreachable; continue; }, Token.Id.Identifier => { - stack.append(State{ .MaybeLabeledExpression = MaybeLabeledExpressionCtx{ - .label = token.index, - .opt_ctx = opt_ctx, - } }) catch unreachable; + stack.append(State{ + .MaybeLabeledExpression = MaybeLabeledExpressionCtx{ + .label = token.index, + .opt_ctx = opt_ctx, + }, + }) catch unreachable; continue; }, Token.Id.Keyword_fn => { @@ -2431,8 +2528,7 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .FnProto = fn_proto }) catch unreachable; continue; }, - Token.Id.Keyword_nakedcc, - Token.Id.Keyword_stdcallcc => { + Token.Id.Keyword_nakedcc, Token.Id.Keyword_stdcallcc => { const fn_proto = try arena.construct(ast.Node.FnProto{ .base = ast.Node{ .id = ast.Node.Id.FnProto }, .doc_comments = null, @@ -2451,10 +2547,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&fn_proto.base); stack.append(State{ .FnProto = fn_proto }) catch unreachable; - try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.Keyword_fn, - .ptr = &fn_proto.fn_token, - } }); + try stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.Keyword_fn, + .ptr = &fn_proto.fn_token, + }, + }); continue; }, Token.Id.Keyword_asm => { @@ -2470,10 +2568,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); opt_ctx.store(&node.base); - stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ - .id = Token.Id.RParen, - .ptr = &node.rparen, - } }) catch unreachable; + stack.append(State{ + .ExpectTokenSave = ExpectTokenSave{ + .id = Token.Id.RParen, + .ptr = &node.rparen, + }, + }) catch unreachable; try stack.append(State{ .AsmClobberItems = &node.clobbers }); try stack.append(State{ .IfToken = Token.Id.Colon }); try stack.append(State{ .AsmInputItems = &node.inputs }); @@ -2482,17 +2582,21 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .IfToken = Token.Id.Colon }); try stack.append(State{ .StringLiteral = OptionalCtx{ .Required = &node.template } }); try stack.append(State{ .ExpectToken = Token.Id.LParen }); - try stack.append(State{ .OptionalTokenSave = OptionalTokenSave{ - .id = Token.Id.Keyword_volatile, - .ptr = &node.volatile_token, - } }); + try stack.append(State{ + .OptionalTokenSave = OptionalTokenSave{ + .id = Token.Id.Keyword_volatile, + .ptr = &node.volatile_token, + }, + }); }, Token.Id.Keyword_inline => { - stack.append(State{ .Inline = InlineCtx{ - .label = null, - .inline_token = token.index, - .opt_ctx = opt_ctx, - } }) catch unreachable; + stack.append(State{ + .Inline = InlineCtx{ + .label = null, + .inline_token = token.index, + .opt_ctx = opt_ctx, + }, + }) catch unreachable; continue; }, else => { @@ -2522,10 +2626,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { }); ctx.opt_ctx.store(&node.base); - stack.append(State{ .ErrorTagListItemOrEnd = ListSave(@typeOf(node.decls)){ - .list = &node.decls, - .ptr = &node.rbrace_token, - } }) catch unreachable; + stack.append(State{ + .ErrorTagListItemOrEnd = ListSave(@typeOf(node.decls)){ + .list = &node.decls, + .ptr = &node.rbrace_token, + }, + }) catch unreachable; continue; }, State.StringLiteral => |opt_ctx| { @@ -2553,10 +2659,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = Token.Id.Identifier, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = Token.Id.Identifier, + }, + }; return tree; } }, @@ -2567,10 +2675,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const ident_token_index = ident_token.index; const ident_token_ptr = ident_token.ptr; if (ident_token_ptr.id != Token.Id.Identifier) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = ident_token_index, - .expected_id = Token.Id.Identifier, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = ident_token_index, + .expected_id = Token.Id.Identifier, + }, + }; return tree; } @@ -2588,10 +2698,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (token_ptr.id != token_id) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = token_id, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = token_id, + }, + }; return tree; } continue; @@ -2601,10 +2713,12 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { const token_index = token.index; const token_ptr = token.ptr; if (token_ptr.id != expect_token_save.id) { - ((try tree.errors.addOne())).* = Error{ .ExpectedToken = Error.ExpectedToken{ - .token = token_index, - .expected_id = expect_token_save.id, - } }; + ((try tree.errors.addOne())).* = Error{ + .ExpectedToken = Error.ExpectedToken{ + .token = token_index, + .expected_id = expect_token_save.id, + }, + }; return tree; } expect_token_save.ptr.* = token_index; @@ -2997,21 +3111,25 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con return true; }, Token.Id.Keyword_while => { - stack.append(State{ .While = LoopCtx{ - .label = null, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = ctx.*, - } }) catch unreachable; + stack.append(State{ + .While = LoopCtx{ + .label = null, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.*, + }, + }) catch unreachable; return true; }, Token.Id.Keyword_for => { - stack.append(State{ .For = LoopCtx{ - .label = null, - .inline_token = null, - .loop_token = token_index, - .opt_ctx = ctx.*, - } }) catch unreachable; + stack.append(State{ + .For = LoopCtx{ + .label = null, + .inline_token = null, + .loop_token = token_index, + .opt_ctx = ctx.*, + }, + }) catch unreachable; return true; }, Token.Id.Keyword_switch => { @@ -3024,10 +3142,12 @@ fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &con }); ctx.store(&node.base); - stack.append(State{ .SwitchCaseOrEnd = ListSave(@typeOf(node.cases)){ - .list = &node.cases, - .ptr = &node.rbrace, - } }) catch unreachable; + stack.append(State{ + .SwitchCaseOrEnd = ListSave(@typeOf(node.cases)){ + .list = &node.cases, + .ptr = &node.rbrace, + }, + }) catch unreachable; try stack.append(State{ .ExpectToken = Token.Id.LBrace }); try stack.append(State{ .ExpectToken = Token.Id.RParen }); try stack.append(State{ .Expression = OptionalCtx{ .Required = &node.expr } }); @@ -3080,10 +3200,14 @@ fn expectCommaOrEnd(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, end: return ExpectCommaOrEndResult{ .end_token = token_index }; } - return ExpectCommaOrEndResult{ .parse_error = Error{ .ExpectedCommaOrEnd = Error.ExpectedCommaOrEnd{ - .token = token_index, - .end_id = end, - } } }; + return ExpectCommaOrEndResult{ + .parse_error = Error{ + .ExpectedCommaOrEnd = Error.ExpectedCommaOrEnd{ + .token = token_index, + .end_id = end, + }, + }, + }; }, } } @@ -3167,13 +3291,14 @@ fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op { Token.Id.Tilde => ast.Node.PrefixOp.Op{ .BitNot = void{} }, Token.Id.Minus => ast.Node.PrefixOp.Op{ .Negation = void{} }, Token.Id.MinusPercent => ast.Node.PrefixOp.Op{ .NegationWrap = void{} }, - Token.Id.Asterisk, - Token.Id.AsteriskAsterisk => ast.Node.PrefixOp.Op{ .PointerType = void{} }, - Token.Id.Ampersand => ast.Node.PrefixOp.Op{ .AddrOf = ast.Node.PrefixOp.AddrOfInfo{ - .align_info = null, - .const_token = null, - .volatile_token = null, - } }, + Token.Id.Asterisk, Token.Id.AsteriskAsterisk => ast.Node.PrefixOp.Op{ .PointerType = void{} }, + Token.Id.Ampersand => ast.Node.PrefixOp.Op{ + .AddrOf = ast.Node.PrefixOp.AddrOfInfo{ + .align_info = null, + .const_token = null, + .volatile_token = null, + }, + }, Token.Id.QuestionMark => ast.Node.PrefixOp.Op{ .MaybeType = void{} }, Token.Id.QuestionMarkQuestionMark => ast.Node.PrefixOp.Op{ .UnwrapMaybe = void{} }, Token.Id.Keyword_await => ast.Node.PrefixOp.Op{ .Await = void{} }, diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 1f60fae270..75ba9e61d7 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1021,7 +1021,7 @@ test "zig fmt: extern declaration" { } test "zig fmt: alignment" { - try testCanonical( + try testCanonical( \\var foo: c_int align(1); \\ ); @@ -1070,7 +1070,7 @@ test "zig fmt: slice attributes" { } test "zig fmt: test declaration" { - try testCanonical( + try testCanonical( \\test "test name" { \\ const a = 1; \\ var b = 1; @@ -1312,7 +1312,7 @@ test "zig fmt: struct declaration" { } test "zig fmt: enum declaration" { - try testCanonical( + try testCanonical( \\const E = enum { \\ Ok, \\ SomethingElse = 0, @@ -1340,7 +1340,7 @@ test "zig fmt: enum declaration" { } test "zig fmt: union declaration" { - try testCanonical( + try testCanonical( \\const U = union { \\ Int: u8, \\ Float: f32, @@ -1860,10 +1860,15 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void { } else |err| switch (err) { error.OutOfMemory => { if (failing_allocator.allocated_bytes != failing_allocator.freed_bytes) { - warn("\nfail_index: {}/{}\nallocated bytes: {}\nfreed bytes: {}\nallocations: {}\ndeallocations: {}\n", - fail_index, needed_alloc_count, - failing_allocator.allocated_bytes, failing_allocator.freed_bytes, - failing_allocator.index, failing_allocator.deallocations); + warn( + "\nfail_index: {}/{}\nallocated bytes: {}\nfreed bytes: {}\nallocations: {}\ndeallocations: {}\n", + fail_index, + needed_alloc_count, + failing_allocator.allocated_bytes, + failing_allocator.freed_bytes, + failing_allocator.index, + failing_allocator.deallocations, + ); return error.MemoryLeakDetected; } }, @@ -1876,4 +1881,3 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void { fn testCanonical(source: []const u8) !void { return testTransform(source, source); } - diff --git a/std/zig/render.zig b/std/zig/render.zig index dce659f1ef..e3bf5fe38e 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -161,7 +161,15 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i } } -fn 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 { +fn 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 { switch (base.id) { ast.Node.Id.Identifier => { const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base); @@ -259,8 +267,7 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind try renderExpression(allocator, stream, tree, indent, start_col, infix_op_node.lhs, op_space); const after_op_space = blk: { - const loc = tree.tokenLocation(tree.tokens.at(infix_op_node.op_token).end, - tree.nextToken(infix_op_node.op_token)); + const loc = tree.tokenLocation(tree.tokens.at(infix_op_node.op_token).end, tree.nextToken(infix_op_node.op_token)); break :blk if (loc.line == 0) op_space else Space.Newline; }; @@ -367,14 +374,16 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.PrefixOp.Op.NegationWrap, ast.Node.PrefixOp.Op.UnwrapMaybe, ast.Node.PrefixOp.Op.MaybeType, - ast.Node.PrefixOp.Op.PointerType => { + ast.Node.PrefixOp.Op.PointerType, + => { try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None); }, ast.Node.PrefixOp.Op.Try, ast.Node.PrefixOp.Op.Await, ast.Node.PrefixOp.Op.Cancel, - ast.Node.PrefixOp.Op.Resume => { + ast.Node.PrefixOp.Op.Resume, + => { try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.Space); }, } @@ -1568,13 +1577,19 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind ast.Node.Id.VarDecl, ast.Node.Id.Use, ast.Node.Id.TestDecl, - ast.Node.Id.ParamDecl => unreachable, + ast.Node.Id.ParamDecl, + => unreachable, } } -fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, - var_decl: &ast.Node.VarDecl,) (@typeOf(stream).Child.Error || Error)!void -{ +fn renderVarDecl( + allocator: &mem.Allocator, + stream: var, + tree: &ast.Tree, + indent: usize, + start_col: &usize, + var_decl: &ast.Node.VarDecl, +) (@typeOf(stream).Child.Error || Error)!void { if (var_decl.visib_token) |visib_token| { try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub } @@ -1623,7 +1638,15 @@ fn renderVarDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent try renderToken(tree, stream, var_decl.semicolon_token, indent, start_col, Space.Newline); } -fn 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 { +fn 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 { const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base); if (param_decl.comptime_token) |comptime_token| { @@ -1643,7 +1666,14 @@ fn renderParamDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, inde } } -fn renderStatement(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, base: &ast.Node,) (@typeOf(stream).Child.Error || Error)!void { +fn renderStatement( + allocator: &mem.Allocator, + stream: var, + tree: &ast.Tree, + indent: usize, + start_col: &usize, + base: &ast.Node, +) (@typeOf(stream).Child.Error || Error)!void { switch (base.id) { ast.Node.Id.VarDecl => { const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base); @@ -1840,7 +1870,13 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent } } -fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize, start_col: &usize,) (@typeOf(stream).Child.Error || Error)!void { +fn renderDocComments( + tree: &ast.Tree, + stream: var, + node: var, + indent: usize, + start_col: &usize, +) (@typeOf(stream).Child.Error || Error)!void { const comment = node.doc_comments ?? return; var it = comment.lines.iterator(0); const first_token = node.firstToken(); diff --git a/std/zig/tokenizer.zig b/std/zig/tokenizer.zig index b90a40108f..4881e952b7 100644 --- a/std/zig/tokenizer.zig +++ b/std/zig/tokenizer.zig @@ -11,55 +11,55 @@ pub const Token = struct { id: Id, }; - pub const keywords = []Keyword { - Keyword{.bytes="align", .id = Id.Keyword_align}, - Keyword{.bytes="and", .id = Id.Keyword_and}, - Keyword{.bytes="asm", .id = Id.Keyword_asm}, - Keyword{.bytes="async", .id = Id.Keyword_async}, - Keyword{.bytes="await", .id = Id.Keyword_await}, - Keyword{.bytes="break", .id = Id.Keyword_break}, - Keyword{.bytes="catch", .id = Id.Keyword_catch}, - Keyword{.bytes="cancel", .id = Id.Keyword_cancel}, - Keyword{.bytes="comptime", .id = Id.Keyword_comptime}, - Keyword{.bytes="const", .id = Id.Keyword_const}, - Keyword{.bytes="continue", .id = Id.Keyword_continue}, - Keyword{.bytes="defer", .id = Id.Keyword_defer}, - Keyword{.bytes="else", .id = Id.Keyword_else}, - Keyword{.bytes="enum", .id = Id.Keyword_enum}, - Keyword{.bytes="errdefer", .id = Id.Keyword_errdefer}, - Keyword{.bytes="error", .id = Id.Keyword_error}, - Keyword{.bytes="export", .id = Id.Keyword_export}, - Keyword{.bytes="extern", .id = Id.Keyword_extern}, - Keyword{.bytes="false", .id = Id.Keyword_false}, - Keyword{.bytes="fn", .id = Id.Keyword_fn}, - Keyword{.bytes="for", .id = Id.Keyword_for}, - Keyword{.bytes="if", .id = Id.Keyword_if}, - Keyword{.bytes="inline", .id = Id.Keyword_inline}, - Keyword{.bytes="nakedcc", .id = Id.Keyword_nakedcc}, - Keyword{.bytes="noalias", .id = Id.Keyword_noalias}, - Keyword{.bytes="null", .id = Id.Keyword_null}, - Keyword{.bytes="or", .id = Id.Keyword_or}, - Keyword{.bytes="packed", .id = Id.Keyword_packed}, - Keyword{.bytes="promise", .id = Id.Keyword_promise}, - Keyword{.bytes="pub", .id = Id.Keyword_pub}, - Keyword{.bytes="resume", .id = Id.Keyword_resume}, - Keyword{.bytes="return", .id = Id.Keyword_return}, - Keyword{.bytes="section", .id = Id.Keyword_section}, - Keyword{.bytes="stdcallcc", .id = Id.Keyword_stdcallcc}, - Keyword{.bytes="struct", .id = Id.Keyword_struct}, - Keyword{.bytes="suspend", .id = Id.Keyword_suspend}, - Keyword{.bytes="switch", .id = Id.Keyword_switch}, - Keyword{.bytes="test", .id = Id.Keyword_test}, - Keyword{.bytes="this", .id = Id.Keyword_this}, - Keyword{.bytes="true", .id = Id.Keyword_true}, - Keyword{.bytes="try", .id = Id.Keyword_try}, - Keyword{.bytes="undefined", .id = Id.Keyword_undefined}, - Keyword{.bytes="union", .id = Id.Keyword_union}, - Keyword{.bytes="unreachable", .id = Id.Keyword_unreachable}, - Keyword{.bytes="use", .id = Id.Keyword_use}, - Keyword{.bytes="var", .id = Id.Keyword_var}, - Keyword{.bytes="volatile", .id = Id.Keyword_volatile}, - Keyword{.bytes="while", .id = Id.Keyword_while}, + pub const keywords = []Keyword{ + Keyword{ .bytes = "align", .id = Id.Keyword_align }, + Keyword{ .bytes = "and", .id = Id.Keyword_and }, + Keyword{ .bytes = "asm", .id = Id.Keyword_asm }, + Keyword{ .bytes = "async", .id = Id.Keyword_async }, + Keyword{ .bytes = "await", .id = Id.Keyword_await }, + Keyword{ .bytes = "break", .id = Id.Keyword_break }, + Keyword{ .bytes = "catch", .id = Id.Keyword_catch }, + Keyword{ .bytes = "cancel", .id = Id.Keyword_cancel }, + Keyword{ .bytes = "comptime", .id = Id.Keyword_comptime }, + Keyword{ .bytes = "const", .id = Id.Keyword_const }, + Keyword{ .bytes = "continue", .id = Id.Keyword_continue }, + Keyword{ .bytes = "defer", .id = Id.Keyword_defer }, + Keyword{ .bytes = "else", .id = Id.Keyword_else }, + Keyword{ .bytes = "enum", .id = Id.Keyword_enum }, + Keyword{ .bytes = "errdefer", .id = Id.Keyword_errdefer }, + Keyword{ .bytes = "error", .id = Id.Keyword_error }, + Keyword{ .bytes = "export", .id = Id.Keyword_export }, + Keyword{ .bytes = "extern", .id = Id.Keyword_extern }, + Keyword{ .bytes = "false", .id = Id.Keyword_false }, + Keyword{ .bytes = "fn", .id = Id.Keyword_fn }, + Keyword{ .bytes = "for", .id = Id.Keyword_for }, + Keyword{ .bytes = "if", .id = Id.Keyword_if }, + Keyword{ .bytes = "inline", .id = Id.Keyword_inline }, + Keyword{ .bytes = "nakedcc", .id = Id.Keyword_nakedcc }, + Keyword{ .bytes = "noalias", .id = Id.Keyword_noalias }, + Keyword{ .bytes = "null", .id = Id.Keyword_null }, + Keyword{ .bytes = "or", .id = Id.Keyword_or }, + Keyword{ .bytes = "packed", .id = Id.Keyword_packed }, + Keyword{ .bytes = "promise", .id = Id.Keyword_promise }, + Keyword{ .bytes = "pub", .id = Id.Keyword_pub }, + Keyword{ .bytes = "resume", .id = Id.Keyword_resume }, + Keyword{ .bytes = "return", .id = Id.Keyword_return }, + Keyword{ .bytes = "section", .id = Id.Keyword_section }, + Keyword{ .bytes = "stdcallcc", .id = Id.Keyword_stdcallcc }, + Keyword{ .bytes = "struct", .id = Id.Keyword_struct }, + Keyword{ .bytes = "suspend", .id = Id.Keyword_suspend }, + Keyword{ .bytes = "switch", .id = Id.Keyword_switch }, + Keyword{ .bytes = "test", .id = Id.Keyword_test }, + Keyword{ .bytes = "this", .id = Id.Keyword_this }, + Keyword{ .bytes = "true", .id = Id.Keyword_true }, + Keyword{ .bytes = "try", .id = Id.Keyword_try }, + Keyword{ .bytes = "undefined", .id = Id.Keyword_undefined }, + Keyword{ .bytes = "union", .id = Id.Keyword_union }, + Keyword{ .bytes = "unreachable", .id = Id.Keyword_unreachable }, + Keyword{ .bytes = "use", .id = Id.Keyword_use }, + Keyword{ .bytes = "var", .id = Id.Keyword_var }, + Keyword{ .bytes = "volatile", .id = Id.Keyword_volatile }, + Keyword{ .bytes = "while", .id = Id.Keyword_while }, }; // TODO perfect hash at comptime @@ -72,7 +72,10 @@ pub const Token = struct { return null; } - const StrLitKind = enum {Normal, C}; + const StrLitKind = enum { + Normal, + C, + }; pub const Id = union(enum) { Invalid, @@ -202,7 +205,7 @@ pub const Tokenizer = struct { } pub fn init(buffer: []const u8) Tokenizer { - return Tokenizer { + return Tokenizer{ .buffer = buffer, .index = 0, .pending_invalid_token = null, @@ -269,7 +272,7 @@ pub const Tokenizer = struct { } const start_index = self.index; var state = State.Start; - var result = Token { + var result = Token{ .id = Token.Id.Eof, .start = self.index, .end = undefined, @@ -290,7 +293,7 @@ pub const Tokenizer = struct { }, '"' => { state = State.StringLiteral; - result.id = Token.Id { .StringLiteral = Token.StrLitKind.Normal }; + result.id = Token.Id{ .StringLiteral = Token.StrLitKind.Normal }; }, '\'' => { state = State.CharLiteral; @@ -369,7 +372,7 @@ pub const Tokenizer = struct { }, '\\' => { state = State.Backslash; - result.id = Token.Id { .MultilineStringLiteralLine = Token.StrLitKind.Normal }; + result.id = Token.Id{ .MultilineStringLiteralLine = Token.StrLitKind.Normal }; }, '{' => { result.id = Token.Id.LBrace; @@ -455,7 +458,7 @@ pub const Tokenizer = struct { else => { result.id = Token.Id.Asterisk; break; - } + }, }, State.AsteriskPercent => switch (c) { @@ -467,7 +470,7 @@ pub const Tokenizer = struct { else => { result.id = Token.Id.AsteriskPercent; break; - } + }, }, State.QuestionMark => switch (c) { @@ -535,7 +538,7 @@ pub const Tokenizer = struct { else => { result.id = Token.Id.Caret; break; - } + }, }, State.Identifier => switch (c) { @@ -560,11 +563,11 @@ pub const Tokenizer = struct { State.C => switch (c) { '\\' => { state = State.Backslash; - result.id = Token.Id { .MultilineStringLiteralLine = Token.StrLitKind.C }; + result.id = Token.Id{ .MultilineStringLiteralLine = Token.StrLitKind.C }; }, '"' => { state = State.StringLiteral; - result.id = Token.Id { .StringLiteral = Token.StrLitKind.C }; + result.id = Token.Id{ .StringLiteral = Token.StrLitKind.C }; }, 'a'...'z', 'A'...'Z', '_', '0'...'9' => { state = State.Identifier; @@ -605,7 +608,7 @@ pub const Tokenizer = struct { } state = State.CharLiteralEnd; - } + }, }, State.CharLiteralBackslash => switch (c) { @@ -736,7 +739,7 @@ pub const Tokenizer = struct { else => { result.id = Token.Id.MinusPercent; break; - } + }, }, State.AngleBracketLeft => switch (c) { @@ -944,7 +947,7 @@ pub const Tokenizer = struct { // reinterpret as a normal exponent number self.index -= 1; state = State.FloatExponentNumber; - } + }, }, State.FloatExponentUnsignedHex => switch (c) { '+', '-' => { @@ -954,7 +957,7 @@ pub const Tokenizer = struct { // reinterpret as a normal exponent number self.index -= 1; state = State.FloatExponentNumberHex; - } + }, }, State.FloatExponentNumber => switch (c) { '0'...'9' => {}, @@ -978,15 +981,15 @@ pub const Tokenizer = struct { State.FloatExponentNumberHex, State.StringLiteral, // find this error later State.MultilineStringLiteralLine, - State.Builtin => {}, + State.Builtin, + => {}, State.Identifier => { if (Token.getKeyword(self.buffer[result.start..self.index])) |id| { result.id = id; } }, - State.LineCommentStart, - State.LineComment => { + State.LineCommentStart, State.LineComment => { result.id = Token.Id.LineComment; }, State.DocComment, State.DocCommentStart => { @@ -1004,7 +1007,8 @@ pub const Tokenizer = struct { State.CharLiteralEscape1, State.CharLiteralEscape2, State.CharLiteralEnd, - State.StringLiteralBackslash => { + State.StringLiteralBackslash, + => { result.id = Token.Id.Invalid; }, @@ -1089,7 +1093,7 @@ pub const Tokenizer = struct { if (self.pending_invalid_token != null) return; const invalid_length = self.getInvalidCharacterLength(); if (invalid_length == 0) return; - self.pending_invalid_token = Token { + self.pending_invalid_token = Token{ .id = Token.Id.Invalid, .start = self.index, .end = self.index + invalid_length, @@ -1134,23 +1138,18 @@ pub const Tokenizer = struct { } }; - - test "tokenizer" { - testTokenize("test", []Token.Id { - Token.Id.Keyword_test, - }); + testTokenize("test", []Token.Id{Token.Id.Keyword_test}); } test "tokenizer - char literal with hex escape" { - testTokenize( \\'\x1b' - , []Token.Id { - Token.Id.CharLiteral, - }); + testTokenize( + \\'\x1b' + , []Token.Id{Token.Id.CharLiteral}); } test "tokenizer - float literal e exponent" { - testTokenize("a = 4.94065645841246544177e-324;\n", []Token.Id { + testTokenize("a = 4.94065645841246544177e-324;\n", []Token.Id{ Token.Id.Identifier, Token.Id.Equal, Token.Id.FloatLiteral, @@ -1159,7 +1158,7 @@ test "tokenizer - float literal e exponent" { } test "tokenizer - float literal p exponent" { - testTokenize("a = 0x1.a827999fcef32p+1022;\n", []Token.Id { + testTokenize("a = 0x1.a827999fcef32p+1022;\n", []Token.Id{ Token.Id.Identifier, Token.Id.Equal, Token.Id.FloatLiteral, @@ -1168,31 +1167,31 @@ test "tokenizer - float literal p exponent" { } test "tokenizer - chars" { - testTokenize("'c'", []Token.Id {Token.Id.CharLiteral}); + testTokenize("'c'", []Token.Id{Token.Id.CharLiteral}); } test "tokenizer - invalid token characters" { testTokenize("#", []Token.Id{Token.Id.Invalid}); testTokenize("`", []Token.Id{Token.Id.Invalid}); - testTokenize("'c", []Token.Id {Token.Id.Invalid}); - testTokenize("'", []Token.Id {Token.Id.Invalid}); - testTokenize("''", []Token.Id {Token.Id.Invalid, Token.Id.Invalid}); + testTokenize("'c", []Token.Id{Token.Id.Invalid}); + testTokenize("'", []Token.Id{Token.Id.Invalid}); + testTokenize("''", []Token.Id{ Token.Id.Invalid, Token.Id.Invalid }); } test "tokenizer - invalid literal/comment characters" { - testTokenize("\"\x00\"", []Token.Id { - Token.Id { .StringLiteral = Token.StrLitKind.Normal }, + testTokenize("\"\x00\"", []Token.Id{ + Token.Id{ .StringLiteral = Token.StrLitKind.Normal }, Token.Id.Invalid, }); - testTokenize("//\x00", []Token.Id { + testTokenize("//\x00", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); - testTokenize("//\x1f", []Token.Id { + testTokenize("//\x1f", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); - testTokenize("//\x7f", []Token.Id { + testTokenize("//\x7f", []Token.Id{ Token.Id.LineComment, Token.Id.Invalid, }); @@ -1261,18 +1260,16 @@ test "tokenizer - illegal unicode codepoints" { test "tokenizer - string identifier and builtin fns" { testTokenize( \\const @"if" = @import("std"); - , - []Token.Id{ - Token.Id.Keyword_const, - Token.Id.Identifier, - Token.Id.Equal, - Token.Id.Builtin, - Token.Id.LParen, - Token.Id {.StringLiteral = Token.StrLitKind.Normal}, - Token.Id.RParen, - Token.Id.Semicolon, - } - ); + , []Token.Id{ + Token.Id.Keyword_const, + Token.Id.Identifier, + Token.Id.Equal, + Token.Id.Builtin, + Token.Id.LParen, + Token.Id{ .StringLiteral = Token.StrLitKind.Normal }, + Token.Id.RParen, + Token.Id.Semicolon, + }); } test "tokenizer - pipe and then invalid" { @@ -1314,7 +1311,10 @@ fn testTokenize(source: []const u8, expected_tokens: []const Token.Id) void { } switch (expected_token_id) { Token.Id.StringLiteral => |expected_kind| { - std.debug.assert(expected_kind == switch (token.id) { Token.Id.StringLiteral => |kind| kind, else => unreachable }); + std.debug.assert(expected_kind == switch (token.id) { + Token.Id.StringLiteral => |kind| kind, + else => unreachable, + }); }, else => {}, } diff --git a/test/cases/align.zig b/test/cases/align.zig index a1259e96bf..f82aa6cfc4 100644 --- a/test/cases/align.zig +++ b/test/cases/align.zig @@ -70,7 +70,7 @@ test "specifying alignment allows pointer cast" { testBytesAlign(0x33); } fn testBytesAlign(b: u8) void { - var bytes align(4) = []u8 { + var bytes align(4) = []u8{ b, b, b, @@ -84,7 +84,7 @@ test "specifying alignment allows slice cast" { testBytesAlignSlice(0x33); } fn testBytesAlignSlice(b: u8) void { - var bytes align(4) = []u8 { + var bytes align(4) = []u8{ b, b, b, @@ -107,7 +107,7 @@ fn expects4(x: &align(4) u32) void { } test "@alignCast slices" { - var array align(4) = []u32 { + var array align(4) = []u32{ 1, 1, }; @@ -169,7 +169,7 @@ test "@ptrCast preserves alignment of bigger source" { test "compile-time known array index has best alignment possible" { // take full advantage of over-alignment - var array align(4) = []u8 { + var array align(4) = []u8{ 1, 2, 3, @@ -181,7 +181,7 @@ test "compile-time known array index has best alignment possible" { assert(@typeOf(&array[3]) == &u8); // because align is too small but we still figure out to use 2 - var bigger align(2) = []u64 { + var bigger align(2) = []u64{ 1, 2, 3, @@ -193,7 +193,7 @@ test "compile-time known array index has best alignment possible" { assert(@typeOf(&bigger[3]) == &align(2) u64); // because pointer is align 2 and u32 align % 2 == 0 we can assume align 2 - var smaller align(2) = []u32 { + var smaller align(2) = []u32{ 1, 2, 3, diff --git a/test/cases/array.zig b/test/cases/array.zig index 0fb61b2a9f..9a405216d8 100644 --- a/test/cases/array.zig +++ b/test/cases/array.zig @@ -34,7 +34,7 @@ test "void arrays" { } test "array literal" { - const hex_mult = []u16 { + const hex_mult = []u16{ 4096, 256, 16, @@ -54,7 +54,7 @@ test "array dot len const expr" { const ArrayDotLenConstExpr = struct { y: [some_array.len]u8, }; -const some_array = []u8 { +const some_array = []u8{ 0, 1, 2, @@ -62,7 +62,7 @@ const some_array = []u8 { }; test "nested arrays" { - const array_of_strings = [][]const u8 { + const array_of_strings = [][]const u8{ "hello", "this", "is", @@ -86,9 +86,7 @@ const Str = struct { a: []Sub, }; test "set global var array via slice embedded in struct" { - var s = Str { - .a = s_array[0..], - }; + var s = Str{ .a = s_array[0..] }; s.a[0].b = 1; s.a[1].b = 2; @@ -100,7 +98,7 @@ test "set global var array via slice embedded in struct" { } test "array literal with specified size" { - var array = [2]u8 { + var array = [2]u8{ 1, 2, }; diff --git a/test/cases/bugs/394.zig b/test/cases/bugs/394.zig index a99bd18b28..b0afec2357 100644 --- a/test/cases/bugs/394.zig +++ b/test/cases/bugs/394.zig @@ -10,11 +10,9 @@ const S = struct { const assert = @import("std").debug.assert; test "bug 394 fixed" { - const x = S { + const x = S{ .x = 3, - .y = E { - .B = 1, - }, + .y = E{ .B = 1 }, }; assert(x.x == 3); } diff --git a/test/cases/bugs/656.zig b/test/cases/bugs/656.zig index 24a28bf411..a6035d51bb 100644 --- a/test/cases/bugs/656.zig +++ b/test/cases/bugs/656.zig @@ -14,10 +14,8 @@ test "nullable if after an if in a switch prong of a switch with 2 prongs in an } fn foo(a: bool, b: bool) void { - var prefix_op = PrefixOp { - .AddrOf = Value { - .align_expr = 1234, - }, + var prefix_op = PrefixOp{ + .AddrOf = Value{ .align_expr = 1234 }, }; if (a) {} else { switch (prefix_op) { diff --git a/test/cases/bugs/828.zig b/test/cases/bugs/828.zig index 8f329e4f82..10d7370b90 100644 --- a/test/cases/bugs/828.zig +++ b/test/cases/bugs/828.zig @@ -1,14 +1,10 @@ const CountBy = struct { a: usize, - const One = CountBy { - .a = 1, - }; + const One = CountBy{ .a = 1 }; pub fn counter(self: &const CountBy) Counter { - return Counter { - .i = 0, - }; + return Counter{ .i = 0 }; } }; diff --git a/test/cases/cast.zig b/test/cases/cast.zig index 8b6afb4310..e37451ea93 100644 --- a/test/cases/cast.zig +++ b/test/cases/cast.zig @@ -33,27 +33,21 @@ fn funcWithConstPtrPtr(x: &const &i32) void { } test "implicitly cast a container to a const pointer of it" { - const z = Struct(void) { - .x = void{}, - }; + const z = Struct(void){ .x = void{} }; assert(0 == @sizeOf(@typeOf(z))); assert(void{} == Struct(void).pointer(z).x); assert(void{} == Struct(void).pointer(&z).x); assert(void{} == Struct(void).maybePointer(z).x); assert(void{} == Struct(void).maybePointer(&z).x); assert(void{} == Struct(void).maybePointer(null).x); - const s = Struct(u8) { - .x = 42, - }; + const s = Struct(u8){ .x = 42 }; assert(0 != @sizeOf(@typeOf(s))); assert(42 == Struct(u8).pointer(s).x); assert(42 == Struct(u8).pointer(&s).x); assert(42 == Struct(u8).maybePointer(s).x); assert(42 == Struct(u8).maybePointer(&s).x); assert(0 == Struct(u8).maybePointer(null).x); - const u = Union { - .x = 42, - }; + const u = Union{ .x = 42 }; assert(42 == Union.pointer(u).x); assert(42 == Union.pointer(&u).x); assert(42 == Union.maybePointer(u).x); @@ -77,9 +71,7 @@ fn Struct(comptime T: type) type { } fn maybePointer(self: ?&const Self) Self { - const none = Self { - .x = if (T == void) void{} else 0, - }; + const none = Self{ .x = if (T == void) void{} else 0 }; return (self ?? &none).*; } }; @@ -93,9 +85,7 @@ const Union = union { } fn maybePointer(self: ?&const Union) Union { - const none = Union { - .x = 0, - }; + const none = Union{ .x = 0 }; return (self ?? &none).*; } }; @@ -130,9 +120,7 @@ test "implicitly cast indirect pointer to maybe-indirect pointer" { return ((??p).*.*).x; } }; - const s = S { - .x = 42, - }; + const s = S{ .x = 42 }; const p = &s; const q = &p; const r = &q; @@ -202,9 +190,7 @@ fn castToMaybeTypeError(z: i32) void { const f = z; const g: error!?i32 = f; - const a = A { - .a = z, - }; + const a = A{ .a = z }; const b: error!?A = a; assert((??(b catch unreachable)).a == 1); } @@ -343,7 +329,6 @@ test "peer type resolution: error and [N]T" { // TODO: implicit error!T to error!U where T can implicitly cast to U //assert(mem.eql(u8, try testPeerErrorAndArray(0), "OK")); //comptime assert(mem.eql(u8, try testPeerErrorAndArray(0), "OK")); - assert(mem.eql(u8, try testPeerErrorAndArray2(1), "OKK")); comptime assert(mem.eql(u8, try testPeerErrorAndArray2(1), "OKK")); } @@ -387,7 +372,7 @@ fn cast128Float(x: u128) f128 { } test "const slice widen cast" { - const bytes align(4) = []u8 { + const bytes align(4) = []u8{ 0x12, 0x12, 0x12, diff --git a/test/cases/const_slice_child.zig b/test/cases/const_slice_child.zig index 456b115234..a92c589186 100644 --- a/test/cases/const_slice_child.zig +++ b/test/cases/const_slice_child.zig @@ -4,7 +4,7 @@ const assert = debug.assert; var argv: &const &const u8 = undefined; test "const slice child" { - const strs = ([]&const u8) { + const strs = ([]&const u8){ c"one", c"two", c"three", diff --git a/test/cases/coroutines.zig b/test/cases/coroutines.zig index e983947a4c..8a0218aeb7 100644 --- a/test/cases/coroutines.zig +++ b/test/cases/coroutines.zig @@ -10,7 +10,6 @@ test "create a coroutine and cancel it" { cancel p; assert(x == 2); } - async fn simpleAsyncFn() void { x += 1; suspend; @@ -28,7 +27,6 @@ test "coroutine suspend, resume, cancel" { assert(std.mem.eql(u8, points, "abcdefg")); } - async fn testAsyncSeq() void { defer seq('e'); @@ -36,7 +34,7 @@ async fn testAsyncSeq() void { suspend; seq('d'); } -var points = []u8 {0} ** "abcdefg".len; +var points = []u8{0} ** "abcdefg".len; var index: usize = 0; fn seq(c: u8) void { @@ -54,7 +52,6 @@ test "coroutine suspend with block" { var a_promise: promise = undefined; var result = false; - async fn testSuspendBlock() void { suspend |p| { comptime assert(@typeOf(p) == promise->void); @@ -75,7 +72,6 @@ test "coroutine await" { assert(await_final_result == 1234); assert(std.mem.eql(u8, await_points, "abcdefghi")); } - async fn await_amain() void { await_seq('b'); const p = async await_another() catch unreachable; @@ -83,7 +79,6 @@ async fn await_amain() void { await_final_result = await p; await_seq('h'); } - async fn await_another() i32 { await_seq('c'); suspend |p| { @@ -94,7 +89,7 @@ async fn await_another() i32 { return 1234; } -var await_points = []u8 {0} ** "abcdefghi".len; +var await_points = []u8{0} ** "abcdefghi".len; var await_seq_index: usize = 0; fn await_seq(c: u8) void { @@ -111,7 +106,6 @@ test "coroutine await early return" { assert(early_final_result == 1234); assert(std.mem.eql(u8, early_points, "abcdef")); } - async fn early_amain() void { early_seq('b'); const p = async early_another() catch unreachable; @@ -119,13 +113,12 @@ async fn early_amain() void { early_final_result = await p; early_seq('e'); } - async fn early_another() i32 { early_seq('c'); return 1234; } -var early_points = []u8 {0} ** "abcdef".len; +var early_points = []u8{0} ** "abcdef".len; var early_seq_index: usize = 0; fn early_seq(c: u8) void { @@ -141,7 +134,6 @@ test "coro allocation failure" { error.OutOfMemory => {}, } } - async fn asyncFuncThatNeverGetsRun() void { @panic("coro frame allocation should fail"); } @@ -164,15 +156,12 @@ test "async fn pointer in a struct field" { const Foo = struct { bar: async<&std.mem.Allocator> fn(&i32) void, }; - var foo = Foo { - .bar = simpleAsyncFn2, - }; + var foo = Foo{ .bar = simpleAsyncFn2 }; const p = (async foo.bar(&data)) catch unreachable; assert(data == 2); cancel p; assert(data == 4); } - async<&std.mem.Allocator> fn simpleAsyncFn2(y: &i32) void { defer y.* += 2; y.* += 1; @@ -184,7 +173,6 @@ test "async fn with inferred error set" { resume p; cancel p; } - async fn failing() !void { suspend; return error.Fail; @@ -208,12 +196,10 @@ test "error return trace across suspend points - async return" { fn nonFailing() (promise->error!void) { return async suspendThenFail() catch unreachable; } - async fn suspendThenFail() error!void { suspend; return error.Fail; } - async fn printTrace(p: promise->error!void) void { (await p) catch |e| { std.debug.assert(e == error.Fail); @@ -234,7 +220,6 @@ test "break from suspend" { cancel p; std.debug.assert(my_result == 2); } - async fn testBreakFromSuspend(my_result: &i32) void { s: suspend |p| { break :s; diff --git a/test/cases/enum.zig b/test/cases/enum.zig index 1c46a3d9e0..cbcbc5e306 100644 --- a/test/cases/enum.zig +++ b/test/cases/enum.zig @@ -2,11 +2,9 @@ const assert = @import("std").debug.assert; const mem = @import("std").mem; test "enum type" { - const foo1 = Foo { - .One = 13, - }; - const foo2 = Foo { - .Two = Point { + const foo1 = Foo{ .One = 13 }; + const foo2 = Foo{ + .Two = Point{ .x = 1234, .y = 5678, }, @@ -48,18 +46,12 @@ const Bar = enum { }; fn returnAnInt(x: i32) Foo { - return Foo { - .One = x, - }; + return Foo{ .One = x }; } test "constant enum with payload" { - var empty = AnEnumWithPayload { - .Empty = {}, - }; - var full = AnEnumWithPayload { - .Full = 13, - }; + var empty = AnEnumWithPayload{ .Empty = {} }; + var full = AnEnumWithPayload{ .Full = 13 }; shouldBeEmpty(empty); shouldBeNotEmpty(full); } @@ -737,7 +729,7 @@ const BitFieldOfEnums = packed struct { c: C, }; -const bit_field_1 = BitFieldOfEnums { +const bit_field_1 = BitFieldOfEnums{ .a = A.Two, .b = B.Three3, .c = C.Four4, diff --git a/test/cases/enum_with_members.zig b/test/cases/enum_with_members.zig index 9e3e031f92..8fafa70b02 100644 --- a/test/cases/enum_with_members.zig +++ b/test/cases/enum_with_members.zig @@ -15,12 +15,8 @@ const ET = union(enum) { }; test "enum with members" { - const a = ET { - .SINT = -42, - }; - const b = ET { - .UINT = 42, - }; + const a = ET{ .SINT = -42 }; + const b = ET{ .UINT = 42 }; var buf: [20]u8 = undefined; assert((a.print(buf[0..]) catch unreachable) == 3); diff --git a/test/cases/error.zig b/test/cases/error.zig index 70d96e4d01..92b2a012bd 100644 --- a/test/cases/error.zig +++ b/test/cases/error.zig @@ -92,7 +92,7 @@ test "error set type " { comptime testErrorSetType(); } -const MyErrSet = error { +const MyErrSet = error{ OutOfMemory, FileNotFound, }; @@ -114,11 +114,11 @@ test "explicit error set cast" { comptime testExplicitErrorSetCast(Set1.A); } -const Set1 = error { +const Set1 = error{ A, B, }; -const Set2 = error { +const Set2 = error{ A, C, }; @@ -134,8 +134,7 @@ test "comptime test error for empty error set" { comptime testComptimeTestErrorEmptySet(1234); } -const EmptyErrorSet = error { -}; +const EmptyErrorSet = error{}; fn testComptimeTestErrorEmptySet(x: EmptyErrorSet!i32) void { 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" { testErrToIntWithOnePossibleValue(error.A, u32(error.A)); comptime testErrToIntWithOnePossibleValue(error.A, u32(error.A)); } -fn testErrToIntWithOnePossibleValue(x: error { - A, -}, comptime value: u32) void { +fn testErrToIntWithOnePossibleValue( + x: error{A}, + comptime value: u32, +) void { if (u32(x) != value) { @compileError("bad"); } @@ -197,16 +197,14 @@ fn foo2(f: fn() error!void) void { const x = f(); } -fn bar2() (error { -}!void) {} +fn bar2() (error{}!void) {} test "error: Zero sized error set returned with value payload crash" { _ = foo3(0); _ = comptime foo3(0); } -const Error = error { -}; +const Error = error{}; fn foo3(b: usize) Error!usize { return b; } diff --git a/test/cases/eval.zig b/test/cases/eval.zig index d7ad68b74e..3a1c67445a 100644 --- a/test/cases/eval.zig +++ b/test/cases/eval.zig @@ -72,12 +72,12 @@ const Point = struct { x: i32, y: i32, }; -const static_point_list = []Point { +const static_point_list = []Point{ makePoint(1, 2), makePoint(3, 4), }; fn makePoint(x: i32, y: i32) Point { - return Point { + return Point{ .x = x, .y = y, }; @@ -92,13 +92,11 @@ pub const Vec3 = struct { data: [3]f32, }; pub fn vec3(x: f32, y: f32, z: f32) Vec3 { - return Vec3 { - .data = []f32 { - x, - y, - z, - }, - }; + return Vec3{ .data = []f32{ + x, + y, + z, + } }; } test "constant expressions" { @@ -117,22 +115,22 @@ const Vertex = struct { g: f32, b: f32, }; -const vertices = []Vertex { - Vertex { +const vertices = []Vertex{ + Vertex{ .x = -0.6, .y = -0.4, .r = 1.0, .g = 0.0, .b = 0.0, }, - Vertex { + Vertex{ .x = 0.6, .y = -0.4, .r = 0.0, .g = 1.0, .b = 0.0, }, - Vertex { + Vertex{ .x = 0.0, .y = 0.6, .r = 0.0, @@ -149,7 +147,7 @@ const StInitStrFoo = struct { x: i32, y: bool, }; -var st_init_str_foo = StInitStrFoo { +var st_init_str_foo = StInitStrFoo{ .x = 13, .y = true, }; @@ -158,7 +156,7 @@ test "statically initalized array literal" { const y: [4]u8 = st_init_arr_lit_x; assert(y[3] == 4); } -const st_init_arr_lit_x = []u8 { +const st_init_arr_lit_x = []u8{ 1, 2, 3, @@ -220,16 +218,16 @@ const CmdFn = struct { func: fn(i32) i32, }; -const cmd_fns = []CmdFn { - CmdFn { +const cmd_fns = []CmdFn{ + CmdFn{ .name = "one", .func = one, }, - CmdFn { + CmdFn{ .name = "two", .func = two, }, - CmdFn { + CmdFn{ .name = "three", .func = three, }, @@ -289,9 +287,7 @@ const SimpleStruct = struct { } }; -var simple_struct = SimpleStruct { - .field = 1234, -}; +var simple_struct = SimpleStruct{ .field = 1234 }; const bound_fn = simple_struct.method; @@ -341,9 +337,7 @@ const Foo = struct { name: []const u8, }; -var foo_contents = Foo { - .name = "a", -}; +var foo_contents = Foo{ .name = "a" }; const foo_ref = &foo_contents; test "create global array with for loop" { @@ -529,9 +523,7 @@ const SingleFieldStruct = struct { }; test "const ptr to comptime mutable data is not memoized" { comptime { - var foo = SingleFieldStruct { - .x = 1, - }; + var foo = SingleFieldStruct{ .x = 1 }; assert(foo.read_x() == 1); foo.x = 2; assert(foo.read_x() == 2); @@ -574,9 +566,7 @@ pub const Info = struct { version: u8, }; -pub const diamond_info = Info { - .version = 0, -}; +pub const diamond_info = Info{ .version = 0 }; test "comptime modification of const struct field" { comptime { diff --git a/test/cases/field_parent_ptr.zig b/test/cases/field_parent_ptr.zig index 2e519098cc..1a7de9ce35 100644 --- a/test/cases/field_parent_ptr.zig +++ b/test/cases/field_parent_ptr.zig @@ -17,7 +17,7 @@ const Foo = struct { d: i32, }; -const foo = Foo { +const foo = Foo{ .a = true, .b = 0.123, .c = 1234, diff --git a/test/cases/fn.zig b/test/cases/fn.zig index 6d47dafad4..a0691fbffc 100644 --- a/test/cases/fn.zig +++ b/test/cases/fn.zig @@ -73,7 +73,7 @@ fn fnWithUnreachable() noreturn { } test "function pointers" { - const fns = []@typeOf(fn1) { + const fns = []@typeOf(fn1){ fn1, fn2, fn3, diff --git a/test/cases/fn_in_struct_in_comptime.zig b/test/cases/fn_in_struct_in_comptime.zig index 4f181d7ffb..51e494036b 100644 --- a/test/cases/fn_in_struct_in_comptime.zig +++ b/test/cases/fn_in_struct_in_comptime.zig @@ -1,6 +1,6 @@ const assert = @import("std").debug.assert; -fn get_foo() fn(&u8)usize { +fn get_foo() fn(&u8) usize { comptime { return struct { fn func(ptr: &u8) usize { diff --git a/test/cases/for.zig b/test/cases/for.zig index f13e6ec6e5..c624035708 100644 --- a/test/cases/for.zig +++ b/test/cases/for.zig @@ -3,7 +3,7 @@ const assert = std.debug.assert; const mem = std.mem; test "continue in for loop" { - const array = []i32 { + const array = []i32{ 1, 2, 3, @@ -35,7 +35,7 @@ fn mangleString(s: []u8) void { } test "basic for loop" { - const expected_result = []u8 { + const expected_result = []u8{ 9, 8, 7, @@ -57,7 +57,7 @@ test "basic for loop" { var buffer: [expected_result.len]u8 = undefined; var buf_index: usize = 0; - const array = []u8 { + const array = []u8{ 9, 8, 7, diff --git a/test/cases/generics.zig b/test/cases/generics.zig index 3fb33d0495..93fecc7295 100644 --- a/test/cases/generics.zig +++ b/test/cases/generics.zig @@ -81,11 +81,11 @@ test "function with return type type" { } test "generic struct" { - var a1 = GenNode(i32) { + var a1 = GenNode(i32){ .value = 13, .next = null, }; - var b1 = GenNode(bool) { + var b1 = GenNode(bool){ .value = true, .next = null, }; @@ -120,8 +120,8 @@ fn aGenericFn(comptime T: type, comptime a: T, b: T) T { } test "generic fn with implicit cast" { - assert(getFirstByte(u8, []u8 {13}) == 13); - assert(getFirstByte(u16, []u16 { + assert(getFirstByte(u8, []u8{13}) == 13); + assert(getFirstByte(u16, []u16{ 0, 13, }) == 0); @@ -133,7 +133,7 @@ fn getFirstByte(comptime T: type, mem: []const T) u8 { return getByte(@ptrCast(&const u8, &mem[0])); } -const foos = []fn(var) bool { +const foos = []fn(var) bool{ foo1, foo2, }; diff --git a/test/cases/incomplete_struct_param_tld.zig b/test/cases/incomplete_struct_param_tld.zig index a907ca748a..a2f57743d0 100644 --- a/test/cases/incomplete_struct_param_tld.zig +++ b/test/cases/incomplete_struct_param_tld.zig @@ -21,11 +21,9 @@ fn foo(a: &const A) i32 { } test "incomplete struct param top level declaration" { - const a = A { - .b = B { - .c = C { - .x = 13, - }, + const a = A{ + .b = B{ + .c = C{ .x = 13 }, }, }; assert(foo(a) == 13); diff --git a/test/cases/math.zig b/test/cases/math.zig index 3c6156a3ea..0b4622702f 100644 --- a/test/cases/math.zig +++ b/test/cases/math.zig @@ -197,7 +197,7 @@ fn test_u64_div() void { assert(result.remainder == 100663296); } fn divWithResult(a: u64, b: u64) DivResult { - return DivResult { + return DivResult{ .quotient = a / b, .remainder = a % b, }; diff --git a/test/cases/misc.zig b/test/cases/misc.zig index deeeca8c3a..42de163ea5 100644 --- a/test/cases/misc.zig +++ b/test/cases/misc.zig @@ -232,7 +232,7 @@ test "string escapes" { } test "multiline string" { - const s1 = + const s1 = \\one \\two) \\three @@ -242,7 +242,7 @@ test "multiline string" { } test "multiline C string" { - const s1 = + const s1 = c\\one c\\two) c\\three @@ -350,15 +350,13 @@ const Test3Point = struct { x: i32, y: i32, }; -const test3_foo = Test3Foo { - .Three = Test3Point { +const test3_foo = Test3Foo{ + .Three = Test3Point{ .x = 3, .y = 4, }, }; -const test3_bar = Test3Foo { - .Two = 13, -}; +const test3_bar = Test3Foo{ .Two = 13 }; fn test3_1(f: &const Test3Foo) void { switch (f.*) { Test3Foo.Three => |pt| { @@ -417,7 +415,7 @@ test "C string concatenation" { test "cast slice to u8 slice" { assert(@sizeOf(i32) == 4); - var big_thing_array = []i32 { + var big_thing_array = []i32{ 1, 2, 3, @@ -458,9 +456,9 @@ test "non const ptr to aliased type" { } test "array 2D const double ptr" { - const rect_2d_vertexes = [][1]f32 { - []f32 {1.0}, - []f32 {2.0}, + const rect_2d_vertexes = [][1]f32{ + []f32{1.0}, + []f32{2.0}, }; testArray2DConstDoublePtr(&rect_2d_vertexes[0][0]); } @@ -565,7 +563,7 @@ test "volatile load and store" { test "slice string literal has type []const u8" { comptime { assert(@typeOf("aoeu"[0..]) == []const u8); - const array = []i32 { + const array = []i32{ 1, 2, 3, @@ -581,13 +579,9 @@ test "global variable initialized to global variable array element" { const GDTEntry = struct { field: i32, }; -var gdt = []GDTEntry { - GDTEntry { - .field = 1, - }, - GDTEntry { - .field = 2, - }, +var gdt = []GDTEntry{ + GDTEntry{ .field = 1 }, + GDTEntry{ .field = 2 }, }; var global_ptr = &gdt[0]; @@ -648,9 +642,7 @@ fn testStructInFn() void { kind: BlockKind, }; - var block = Block { - .kind = 1234, - }; + var block = Block{ .kind = 1234 }; block.kind += 1; @@ -694,12 +686,10 @@ const PackedEnum = packed enum { }; test "packed struct, enum, union parameters in extern function" { - testPackedStuff(PackedStruct { + testPackedStuff(PackedStruct{ .a = 1, .b = 2, - }, PackedUnion { - .a = 1, - }, PackedEnum.A); + }, PackedUnion{ .a = 1 }, PackedEnum.A); } export fn testPackedStuff(a: &const PackedStruct, b: &const PackedUnion, c: PackedEnum) void {} diff --git a/test/cases/null.zig b/test/cases/null.zig index 96a62ab1ed..936e5fafbd 100644 --- a/test/cases/null.zig +++ b/test/cases/null.zig @@ -58,7 +58,7 @@ fn foo(x: ?i32) ?bool { } test "if var maybe pointer" { - assert(shouldBeAPlus1(Particle { + assert(shouldBeAPlus1(Particle{ .a = 14, .b = 1, .c = 1, @@ -92,9 +92,7 @@ test "null literal outside function" { const SillyStruct = struct { context: ?i32, }; -const here_is_a_null_literal = SillyStruct { - .context = null, -}; +const here_is_a_null_literal = SillyStruct{ .context = null }; test "test null runtime" { testTestNullRuntime(null); diff --git a/test/cases/reflection.zig b/test/cases/reflection.zig index f9b64c80eb..b82ce6340f 100644 --- a/test/cases/reflection.zig +++ b/test/cases/reflection.zig @@ -59,7 +59,7 @@ test "reflection: enum member types and names" { } test "reflection: @field" { - var f = Foo { + var f = Foo{ .one = 42, .two = true, .three = void{}, diff --git a/test/cases/slice.zig b/test/cases/slice.zig index 4ca194672c..eae6fa895e 100644 --- a/test/cases/slice.zig +++ b/test/cases/slice.zig @@ -18,7 +18,7 @@ test "slice child property" { } test "runtime safety lets us slice from len..len" { - var an_array = []u8 { + var an_array = []u8{ 1, 2, 3, diff --git a/test/cases/struct.zig b/test/cases/struct.zig index c474d99f2b..37b0e497f0 100644 --- a/test/cases/struct.zig +++ b/test/cases/struct.zig @@ -27,7 +27,7 @@ test "invake static method in global scope" { } test "void struct fields" { - const foo = VoidStructFieldsFoo { + const foo = VoidStructFieldsFoo{ .a = void{}, .b = 1, .c = void{}, @@ -96,16 +96,12 @@ test "struct byval assign" { } fn structInitializer() void { - const val = Val { - .x = 42, - }; + const val = Val{ .x = 42 }; assert(val.x == 42); } test "fn call of struct field" { - assert(callStructField(Foo { - .ptr = aFunc, - }) == 13); + assert(callStructField(Foo{ .ptr = aFunc }) == 13); } const Foo = struct { @@ -121,9 +117,7 @@ fn callStructField(foo: &const Foo) i32 { } test "store member function in variable" { - const instance = MemberFnTestFoo { - .x = 1234, - }; + const instance = MemberFnTestFoo{ .x = 1234 }; const memberFn = MemberFnTestFoo.member; const result = memberFn(instance); assert(result == 1234); @@ -136,17 +130,13 @@ const MemberFnTestFoo = struct { }; test "call member function directly" { - const instance = MemberFnTestFoo { - .x = 1234, - }; + const instance = MemberFnTestFoo{ .x = 1234 }; const result = MemberFnTestFoo.member(instance); assert(result == 1234); } test "member functions" { - const r = MemberFnRand { - .seed = 1234, - }; + const r = MemberFnRand{ .seed = 1234 }; assert(r.getSeed() == 1234); } const MemberFnRand = struct { @@ -165,7 +155,7 @@ const Bar = struct { y: i32, }; fn makeBar(x: i32, y: i32) Bar { - return Bar { + return Bar{ .x = x, .y = y, }; @@ -190,7 +180,7 @@ fn testReturnEmptyStructFromFn() EmptyStruct2 { } test "pass slice of empty struct to fn" { - assert(testPassSliceOfEmptyStructToFn([]EmptyStruct2 {EmptyStruct2{}}) == 1); + assert(testPassSliceOfEmptyStructToFn([]EmptyStruct2{EmptyStruct2{}}) == 1); } fn testPassSliceOfEmptyStructToFn(slice: []const EmptyStruct2) usize { return slice.len; @@ -202,7 +192,7 @@ const APackedStruct = packed struct { }; test "packed struct" { - var foo = APackedStruct { + var foo = APackedStruct{ .x = 1, .y = 2, }; @@ -217,7 +207,7 @@ const BitField1 = packed struct { c: u2, }; -const bit_field_1 = BitField1 { +const bit_field_1 = BitField1{ .a = 1, .b = 2, .c = 3, @@ -267,7 +257,7 @@ test "packed struct 24bits" { assert(@sizeOf(Foo96Bits) == 12); } - var value = Foo96Bits { + var value = Foo96Bits{ .a = 0, .b = 0, .c = 0, @@ -310,7 +300,7 @@ test "packed array 24bits" { assert(@sizeOf(FooArray24Bits) == 2 + 2 * 3 + 2); } - var bytes = []u8 {0} ** (@sizeOf(FooArray24Bits) + 1); + var bytes = []u8{0} ** (@sizeOf(FooArray24Bits) + 1); bytes[bytes.len - 1] = 0xaa; const ptr = &([]FooArray24Bits)(bytes[0..bytes.len - 1])[0]; assert(ptr.a == 0); @@ -360,7 +350,7 @@ test "aligned array of packed struct" { assert(@sizeOf(FooArrayOfAligned) == 2 * 2); } - var bytes = []u8 {0xbb} ** @sizeOf(FooArrayOfAligned); + var bytes = []u8{0xbb} ** @sizeOf(FooArrayOfAligned); const ptr = &([]FooArrayOfAligned)(bytes[0..bytes.len])[0]; assert(ptr.a[0].a == 0xbb); @@ -370,11 +360,11 @@ test "aligned array of packed struct" { } test "runtime struct initialization of bitfield" { - const s1 = Nibbles { + const s1 = Nibbles{ .x = x1, .y = x1, }; - const s2 = Nibbles { + const s2 = Nibbles{ .x = u4(x2), .y = u4(x2), }; diff --git a/test/cases/struct_contains_slice_of_itself.zig b/test/cases/struct_contains_slice_of_itself.zig index ee34c16baf..07987ae32b 100644 --- a/test/cases/struct_contains_slice_of_itself.zig +++ b/test/cases/struct_contains_slice_of_itself.zig @@ -6,31 +6,31 @@ const Node = struct { }; test "struct contains slice of itself" { - var other_nodes = []Node { - Node { + var other_nodes = []Node{ + Node{ .payload = 31, .children = []Node{}, }, - Node { + Node{ .payload = 32, .children = []Node{}, }, }; - var nodes = []Node { - Node { + var nodes = []Node{ + Node{ .payload = 1, .children = []Node{}, }, - Node { + Node{ .payload = 2, .children = []Node{}, }, - Node { + Node{ .payload = 3, .children = other_nodes[0..], }, }; - const root = Node { + const root = Node{ .payload = 1234, .children = nodes[0..], }; diff --git a/test/cases/switch.zig b/test/cases/switch.zig index b870297f18..495fa9f3ed 100644 --- a/test/cases/switch.zig +++ b/test/cases/switch.zig @@ -6,10 +6,7 @@ test "switch with numbers" { fn testSwitchWithNumbers(x: u32) void { const result = switch (x) { - 1, - 2, - 3, - 4 ... 8 => false, + 1, 2, 3, 4...8 => false, 13 => true, else => false, }; @@ -25,9 +22,9 @@ test "switch with all ranges" { fn testSwitchWithAllRanges(x: u32, y: u32) u32 { return switch (x) { - 0 ... 100 => 1, - 101 ... 200 => 2, - 201 ... 300 => 3, + 0...100 => 1, + 101...200 => 2, + 201...300 => 3, else => y, }; } @@ -37,10 +34,8 @@ test "implicit comptime switch" { const result = switch (x) { 3 => 10, 4 => 11, - 5, - 6 => 12, - 7, - 8 => 13, + 5, 6 => 12, + 7, 8 => 13, else => 14, }; @@ -86,15 +81,9 @@ const SwitchStatmentFoo = enum { }; test "switch prong with variable" { - switchProngWithVarFn(SwitchProngWithVarEnum { - .One = 13, - }); - switchProngWithVarFn(SwitchProngWithVarEnum { - .Two = 13.0, - }); - switchProngWithVarFn(SwitchProngWithVarEnum { - .Meh = {}, - }); + switchProngWithVarFn(SwitchProngWithVarEnum{ .One = 13 }); + switchProngWithVarFn(SwitchProngWithVarEnum{ .Two = 13.0 }); + switchProngWithVarFn(SwitchProngWithVarEnum{ .Meh = {} }); } const SwitchProngWithVarEnum = union(enum) { One: i32, @@ -121,9 +110,7 @@ test "switch on enum using pointer capture" { } fn testSwitchEnumPtrCapture() void { - var value = SwitchProngWithVarEnum { - .One = 1234, - }; + var value = SwitchProngWithVarEnum{ .One = 1234 }; switch (value) { SwitchProngWithVarEnum.One => |*x| x.* += 1, else => unreachable, @@ -136,12 +123,8 @@ fn testSwitchEnumPtrCapture() void { test "switch with multiple expressions" { const x = switch (returnsFive()) { - 1, - 2, - 3 => 1, - 4, - 5, - 6 => 2, + 1, 2, 3 => 1, + 4, 5, 6 => 2, else => i32(3), }; assert(x == 2); @@ -156,9 +139,7 @@ const Number = union(enum) { Three: f32, }; -const number = Number { - .Three = 1.23, -}; +const number = Number{ .Three = 1.23 }; fn returnsFalse() bool { switch (number) { @@ -212,12 +193,11 @@ fn testSwitchHandleAllCasesExhaustive(x: u2) u2 { fn testSwitchHandleAllCasesRange(x: u8) u8 { return switch (x) { - 0 ... 100 => u8(0), - 101 ... 200 => 1, - 201, - 203 => 2, + 0...100 => u8(0), + 101...200 => 1, + 201, 203 => 2, 202 => 4, - 204 ... 255 => 3, + 204...255 => 3, }; } diff --git a/test/cases/switch_prong_err_enum.zig b/test/cases/switch_prong_err_enum.zig index 2d28d2f4c7..f060ac2c57 100644 --- a/test/cases/switch_prong_err_enum.zig +++ b/test/cases/switch_prong_err_enum.zig @@ -14,9 +14,7 @@ const FormValue = union(enum) { fn doThing(form_id: u64) error!FormValue { return switch (form_id) { - 17 => FormValue { - .Address = try readOnce(), - }, + 17 => FormValue{ .Address = try readOnce() }, else => error.InvalidDebugInfo, }; } diff --git a/test/cases/switch_prong_implicit_cast.zig b/test/cases/switch_prong_implicit_cast.zig index 3d80f3fdb2..56d37e290f 100644 --- a/test/cases/switch_prong_implicit_cast.zig +++ b/test/cases/switch_prong_implicit_cast.zig @@ -7,12 +7,8 @@ const FormValue = union(enum) { fn foo(id: u64) !FormValue { return switch (id) { - 2 => FormValue { - .Two = true, - }, - 1 => FormValue { - .One = {}, - }, + 2 => FormValue{ .Two = true }, + 1 => FormValue{ .One = {} }, else => return error.Whatever, }; } diff --git a/test/cases/this.zig b/test/cases/this.zig index 8ed5e1ae1a..5e433b5037 100644 --- a/test/cases/this.zig +++ b/test/cases/this.zig @@ -29,7 +29,7 @@ test "this refer to module call private fn" { } test "this refer to container" { - var pt = Point(i32) { + var pt = Point(i32){ .x = 12, .y = 34, }; diff --git a/test/cases/try.zig b/test/cases/try.zig index 483bf6a915..cf5fa5862a 100644 --- a/test/cases/try.zig +++ b/test/cases/try.zig @@ -7,8 +7,7 @@ test "try on error union" { fn tryOnErrorUnionImpl() void { const x = if (returnsTen()) |val| val + 1 else |err| switch (err) { - error.ItBroke, - error.NoMem => 1, + error.ItBroke, error.NoMem => 1, error.CrappedOut => i32(2), else => unreachable, }; diff --git a/test/cases/type_info.zig b/test/cases/type_info.zig index 7bf1e68180..eee5d1f2ca 100644 --- a/test/cases/type_info.zig +++ b/test/cases/type_info.zig @@ -103,7 +103,7 @@ test "type info: error set, error union info" { } fn testErrorSet() void { - const TestErrorSet = error { + const TestErrorSet = error{ First, Second, Third, @@ -196,7 +196,7 @@ fn testStruct() void { assert(!struct_info.Struct.defs[0].data.Fn.is_extern); assert(struct_info.Struct.defs[0].data.Fn.lib_name == null); assert(struct_info.Struct.defs[0].data.Fn.return_type == void); - assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn(&const TestStruct)void); + assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn(&const TestStruct) void); } const TestStruct = packed struct { diff --git a/test/cases/union.zig b/test/cases/union.zig index 93b5f740be..005ad08e6a 100644 --- a/test/cases/union.zig +++ b/test/cases/union.zig @@ -50,10 +50,10 @@ test "basic unions" { test "comptime union field access" { comptime { - var foo = Foo { .int = 0 }; + var foo = Foo{ .int = 0 }; assert(foo.int == 0); - foo = Foo { .float = 42.42 }; + foo = Foo{ .float = 42.42 }; assert(foo.float == 42.42); } } @@ -286,7 +286,6 @@ const PartialInstWithPayload = union(enum) { Compiled: i32, }; - test "access a member of tagged union with conflicting enum tag name" { const Bar = union(enum) { A: A, diff --git a/test/cases/var_args.zig b/test/cases/var_args.zig index 81f800568c..ec4d2059f3 100644 --- a/test/cases/var_args.zig +++ b/test/cases/var_args.zig @@ -58,7 +58,7 @@ fn extraFn(extra: u32, args: ...) usize { return args.len; } -const foos = []fn(...) bool { +const foos = []fn(...) bool{ foo1, foo2, }; diff --git a/test/cases/void.zig b/test/cases/void.zig index f4d72209e4..ef91690878 100644 --- a/test/cases/void.zig +++ b/test/cases/void.zig @@ -8,7 +8,7 @@ const Foo = struct { test "compare void with void compile time known" { comptime { - const foo = Foo { + const foo = Foo{ .a = {}, .b = 1, .c = {}, diff --git a/test/cases/while.zig b/test/cases/while.zig index 574a7b7e76..a95481668d 100644 --- a/test/cases/while.zig +++ b/test/cases/while.zig @@ -151,7 +151,7 @@ test "while on nullable with else result follow break prong" { test "while on error union with else result follow else prong" { const result = while (returnError()) |value| { break value; - } else|err| + } else |err| i32(2); assert(result == 2); } @@ -159,7 +159,7 @@ test "while on error union with else result follow else prong" { test "while on error union with else result follow break prong" { const result = while (returnSuccess(10)) |value| { break value; - } else|err| + } else |err| i32(2); assert(result == 10); } diff --git a/test/compare_output.zig b/test/compare_output.zig index 905ffd37a9..0170477b8b 100644 --- a/test/compare_output.zig +++ b/test/compare_output.zig @@ -475,7 +475,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void { \\ ); - tc.setCommandLineArgs([][]const u8 { + tc.setCommandLineArgs([][]const u8{ "first arg", "'a' 'b' \\", "bare", @@ -516,7 +516,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void { \\ ); - tc.setCommandLineArgs([][]const u8 { + tc.setCommandLineArgs([][]const u8{ "first arg", "'a' 'b' \\", "bare", diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 904ba6d9d8..5215953d0a 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -1,7 +1,8 @@ const tests = @import("tests.zig"); pub fn addCases(cases: &tests.CompileErrorContext) void { - cases.add("invalid deref on switch target", + cases.add( + "invalid deref on switch target", \\comptime { \\ var tile = Tile.Empty; \\ switch (tile.*) { @@ -14,15 +15,19 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ Filled, \\}; , - ".tmp_source.zig:3:17: error: invalid deref on switch target"); + ".tmp_source.zig:3:17: error: invalid deref on switch target", + ); - cases.add("invalid field access in comptime", + cases.add( + "invalid field access in comptime", \\comptime { var x = doesnt_exist.whatever; } , - ".tmp_source.zig:1:20: error: use of undeclared identifier 'doesnt_exist'"); + ".tmp_source.zig:1:20: error: use of undeclared identifier 'doesnt_exist'", + ); - cases.add("suspend inside suspend block", - \\const std = @import("std"); + cases.add( + "suspend inside suspend block", + \\const std = @import("std",); \\ \\export fn entry() void { \\ var buf: [500]u8 = undefined; @@ -39,27 +44,32 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:12:9: error: cannot suspend inside suspend block", - ".tmp_source.zig:11:5: note: other suspend block here"); + ".tmp_source.zig:11:5: note: other suspend block here", + ); - cases.add("assign inline fn to non-comptime var", + cases.add( + "assign inline fn to non-comptime var", \\export fn entry() void { \\ var a = b; \\} \\inline fn b() void { } , ".tmp_source.zig:2:5: error: functions marked inline must be stored in const or comptime var", - ".tmp_source.zig:4:8: note: declared here"); + ".tmp_source.zig:4:8: note: declared here", + ); - cases.add("wrong type passed to @panic", + cases.add( + "wrong type passed to @panic", \\export fn entry() void { \\ var e = error.Foo; \\ @panic(e); \\} , - ".tmp_source.zig:3:12: error: expected type '[]const u8', found 'error{Foo}'"); + ".tmp_source.zig:3:12: error: expected type '[]const u8', found 'error{Foo}'", + ); - - cases.add("@tagName used on union with no associated enum tag", + cases.add( + "@tagName used on union with no associated enum tag", \\const FloatInt = extern union { \\ Float: f32, \\ Int: i32, @@ -70,10 +80,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:7:19: error: union has no associated enum", - ".tmp_source.zig:1:18: note: declared here"); + ".tmp_source.zig:1:18: note: declared here", + ); - cases.add("returning error from void async function", - \\const std = @import("std"); + cases.add( + "returning error from void async function", + \\const std = @import("std",); \\export fn entry() void { \\ const p = async amain() catch unreachable; \\} @@ -81,31 +93,39 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ return error.ShouldBeCompileError; \\} , - ".tmp_source.zig:6:17: error: expected type 'void', found 'error{ShouldBeCompileError}'"); + ".tmp_source.zig:6:17: error: expected type 'void', found 'error{ShouldBeCompileError}'", + ); - cases.add("var not allowed in structs", + cases.add( + "var not allowed in structs", \\export fn entry() void { \\ var s = (struct{v: var}){.v=i32(10)}; \\} , - ".tmp_source.zig:2:23: error: invalid token: 'var'"); + ".tmp_source.zig:2:23: error: invalid token: 'var'", + ); - cases.add("@ptrCast discards const qualifier", + cases.add( + "@ptrCast discards const qualifier", \\export fn entry() void { \\ const x: i32 = 1234; \\ const y = @ptrCast(&i32, &x); \\} , - ".tmp_source.zig:3:15: error: cast discards const qualifier"); + ".tmp_source.zig:3:15: error: cast discards const qualifier", + ); - cases.add("comptime slice of undefined pointer non-zero len", + cases.add( + "comptime slice of undefined pointer non-zero len", \\export fn entry() void { \\ const slice = (&i32)(undefined)[0..1]; \\} , - ".tmp_source.zig:2:36: error: non-zero length slice of undefined pointer"); + ".tmp_source.zig:2:36: error: non-zero length slice of undefined pointer", + ); - cases.add("type checking function pointers", + cases.add( + "type checking function pointers", \\fn a(b: fn (&const u8) void) void { \\ b('a'); \\} @@ -116,9 +136,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ a(c); \\} , - ".tmp_source.zig:8:7: error: expected type 'fn(&const u8) void', found 'fn(u8) void'"); + ".tmp_source.zig:8:7: error: expected type 'fn(&const u8) void', found 'fn(u8) void'", + ); - cases.add("no else prong on switch on global error set", + cases.add( + "no else prong on switch on global error set", \\export fn entry() void { \\ foo(error.A); \\} @@ -128,18 +150,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:5:5: error: else prong required when switching on type 'error'"); + ".tmp_source.zig:5:5: error: else prong required when switching on type 'error'", + ); - cases.add("inferred error set with no returned error", + cases.add( + "inferred error set with no returned error", \\export fn entry() void { \\ foo() catch unreachable; \\} \\fn foo() !void { \\} , - ".tmp_source.zig:4:11: error: function with inferred error set must return at least one possible error"); + ".tmp_source.zig:4:11: error: function with inferred error set must return at least one possible error", + ); - cases.add("error not handled in switch", + cases.add( + "error not handled in switch", \\export fn entry() void { \\ foo(452) catch |err| switch (err) { \\ error.Foo => {}, @@ -155,9 +181,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:2:26: error: error.Baz not handled in switch", - ".tmp_source.zig:2:26: error: error.Bar not handled in switch"); + ".tmp_source.zig:2:26: error: error.Bar not handled in switch", + ); - cases.add("duplicate error in switch", + cases.add( + "duplicate error in switch", \\export fn entry() void { \\ foo(452) catch |err| switch (err) { \\ error.Foo => {}, @@ -175,9 +203,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:5:14: error: duplicate switch value: '@typeOf(foo).ReturnType.ErrorSet.Foo'", - ".tmp_source.zig:3:14: note: other value is here"); + ".tmp_source.zig:3:14: note: other value is here", + ); - cases.add("range operator in switch used on error set", + cases.add( + "range operator in switch used on error set", \\export fn entry() void { \\ try foo(452) catch |err| switch (err) { \\ error.A ... error.B => {}, @@ -192,31 +222,39 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:3:17: error: operator not allowed for errors"); + ".tmp_source.zig:3:17: error: operator not allowed for errors", + ); - cases.add("inferring error set of function pointer", + cases.add( + "inferring error set of function pointer", \\comptime { \\ const z: ?fn()!void = null; \\} , - ".tmp_source.zig:2:15: error: inferring error set of return type valid only for function definitions"); + ".tmp_source.zig:2:15: error: inferring error set of return type valid only for function definitions", + ); - cases.add("access non-existent member of error set", + cases.add( + "access non-existent member of error set", \\const Foo = error{A}; \\comptime { \\ const z = Foo.Bar; \\} , - ".tmp_source.zig:3:18: error: no error named 'Bar' in 'Foo'"); + ".tmp_source.zig:3:18: error: no error named 'Bar' in 'Foo'", + ); - cases.add("error union operator with non error set LHS", + cases.add( + "error union operator with non error set LHS", \\comptime { \\ const z = i32!i32; \\} , - ".tmp_source.zig:2:15: error: expected error set type, found type 'i32'"); + ".tmp_source.zig:2:15: error: expected error set type, found type 'i32'", + ); - cases.add("error equality but sets have no common members", + cases.add( + "error equality but sets have no common members", \\const Set1 = error{A, C}; \\const Set2 = error{B, D}; \\export fn entry() void { @@ -228,16 +266,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:7:11: error: error sets 'Set1' and 'Set2' have no common errors"); + ".tmp_source.zig:7:11: error: error sets 'Set1' and 'Set2' have no common errors", + ); - cases.add("only equality binary operator allowed for error sets", + cases.add( + "only equality binary operator allowed for error sets", \\comptime { \\ const z = error.A > error.B; \\} , - ".tmp_source.zig:2:23: error: operator not allowed for errors"); + ".tmp_source.zig:2:23: error: operator not allowed for errors", + ); - cases.add("explicit error set cast known at comptime violates error sets", + cases.add( + "explicit error set cast known at comptime violates error sets", \\const Set1 = error {A, B}; \\const Set2 = error {A, C}; \\comptime { @@ -245,9 +287,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var y = Set2(x); \\} , - ".tmp_source.zig:5:17: error: error.B not a member of error set 'Set2'"); + ".tmp_source.zig:5:17: error: error.B not a member of error set 'Set2'", + ); - cases.add("cast error union of global error set to error union of smaller error set", + cases.add( + "cast error union of global error set to error union of smaller error set", \\const SmallErrorSet = error{A}; \\export fn entry() void { \\ var x: SmallErrorSet!i32 = foo(); @@ -257,9 +301,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:35: error: expected 'SmallErrorSet!i32', found 'error!i32'", - ".tmp_source.zig:3:35: note: unable to cast global error set into smaller set"); + ".tmp_source.zig:3:35: note: unable to cast global error set into smaller set", + ); - cases.add("cast global error set to error set", + cases.add( + "cast global error set to error set", \\const SmallErrorSet = error{A}; \\export fn entry() void { \\ var x: SmallErrorSet = foo(); @@ -269,9 +315,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:31: error: expected 'SmallErrorSet', found 'error'", - ".tmp_source.zig:3:31: note: unable to cast global error set into smaller set"); + ".tmp_source.zig:3:31: note: unable to cast global error set into smaller set", + ); - cases.add("recursive inferred error set", + cases.add( + "recursive inferred error set", \\export fn entry() void { \\ foo() catch unreachable; \\} @@ -279,9 +327,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ try foo(); \\} , - ".tmp_source.zig:5:5: error: cannot resolve inferred error set '@typeOf(foo).ReturnType.ErrorSet': function 'foo' not fully analyzed yet"); + ".tmp_source.zig:5:5: error: cannot resolve inferred error set '@typeOf(foo).ReturnType.ErrorSet': function 'foo' not fully analyzed yet", + ); - cases.add("implicit cast of error set not a subset", + cases.add( + "implicit cast of error set not a subset", \\const Set1 = error{A, B}; \\const Set2 = error{A, C}; \\export fn entry() void { @@ -292,18 +342,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:7:19: error: expected 'Set2', found 'Set1'", - ".tmp_source.zig:1:23: note: 'error.B' not a member of destination error set"); + ".tmp_source.zig:1:23: note: 'error.B' not a member of destination error set", + ); - cases.add("int to err global invalid number", + cases.add( + "int to err global invalid number", \\const Set1 = error{A, B}; \\comptime { \\ var x: usize = 3; \\ var y = error(x); \\} , - ".tmp_source.zig:4:18: error: integer value 3 represents no error"); + ".tmp_source.zig:4:18: error: integer value 3 represents no error", + ); - cases.add("int to err non global invalid number", + cases.add( + "int to err non global invalid number", \\const Set1 = error{A, B}; \\const Set2 = error{A, C}; \\comptime { @@ -311,16 +365,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var y = Set2(x); \\} , - ".tmp_source.zig:5:17: error: integer value 2 represents no error in 'Set2'"); + ".tmp_source.zig:5:17: error: integer value 2 represents no error in 'Set2'", + ); - cases.add("@memberCount of error", + cases.add( + "@memberCount of error", \\comptime { \\ _ = @memberCount(error); \\} , - ".tmp_source.zig:2:9: error: global error set member count not available at comptime"); + ".tmp_source.zig:2:9: error: global error set member count not available at comptime", + ); - cases.add("duplicate error value in error set", + cases.add( + "duplicate error value in error set", \\const Foo = error { \\ Bar, \\ Bar, @@ -330,22 +388,30 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:5: error: duplicate error: 'Bar'", - ".tmp_source.zig:2:5: note: other error here"); + ".tmp_source.zig:2:5: note: other error here", + ); - cases.add("cast negative integer literal to usize", + cases.add( + "cast negative integer literal to usize", \\export fn entry() void { \\ const x = usize(-10); \\} - , ".tmp_source.zig:2:21: error: cannot cast negative value -10 to unsigned integer type 'usize'"); + , + ".tmp_source.zig:2:21: error: cannot cast negative value -10 to unsigned integer type 'usize'", + ); - cases.add("use invalid number literal as array index", + cases.add( + "use invalid number literal as array index", \\var v = 25; \\export fn entry() void { \\ var arr: [v]u8 = undefined; \\} - , ".tmp_source.zig:1:1: error: unable to infer variable type"); + , + ".tmp_source.zig:1:1: error: unable to infer variable type", + ); - cases.add("duplicate struct field", + cases.add( + "duplicate struct field", \\const Foo = struct { \\ Bar: i32, \\ Bar: usize, @@ -355,9 +421,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:5: error: duplicate struct field: 'Bar'", - ".tmp_source.zig:2:5: note: other field here"); + ".tmp_source.zig:2:5: note: other field here", + ); - cases.add("duplicate union field", + cases.add( + "duplicate union field", \\const Foo = union { \\ Bar: i32, \\ Bar: usize, @@ -367,9 +435,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:5: error: duplicate union field: 'Bar'", - ".tmp_source.zig:2:5: note: other field here"); + ".tmp_source.zig:2:5: note: other field here", + ); - cases.add("duplicate enum field", + cases.add( + "duplicate enum field", \\const Foo = enum { \\ Bar, \\ Bar, @@ -380,77 +450,108 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:3:5: error: duplicate enum field: 'Bar'", - ".tmp_source.zig:2:5: note: other field here"); + ".tmp_source.zig:2:5: note: other field here", + ); - cases.add("calling function with naked calling convention", + cases.add( + "calling function with naked calling convention", \\export fn entry() void { \\ foo(); \\} \\nakedcc fn foo() void { } , ".tmp_source.zig:2:5: error: unable to call function with naked calling convention", - ".tmp_source.zig:4:9: note: declared here"); + ".tmp_source.zig:4:9: note: declared here", + ); - cases.add("function with invalid return type", + cases.add( + "function with invalid return type", \\export fn foo() boid {} - , ".tmp_source.zig:1:17: error: use of undeclared identifier 'boid'"); + , + ".tmp_source.zig:1:17: error: use of undeclared identifier 'boid'", + ); - cases.add("function with non-extern non-packed enum parameter", + cases.add( + "function with non-extern non-packed enum parameter", \\const Foo = enum { A, B, C }; \\export fn entry(foo: Foo) void { } - , ".tmp_source.zig:2:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:2:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'", + ); - cases.add("function with non-extern non-packed struct parameter", + cases.add( + "function with non-extern non-packed struct parameter", \\const Foo = struct { \\ A: i32, \\ B: f32, \\ C: bool, \\}; \\export fn entry(foo: Foo) void { } - , ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'", + ); - cases.add("function with non-extern non-packed union parameter", + cases.add( + "function with non-extern non-packed union parameter", \\const Foo = union { \\ A: i32, \\ B: f32, \\ C: bool, \\}; \\export fn entry(foo: Foo) void { } - , ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:6:22: error: parameter of type 'Foo' not allowed in function with calling convention 'ccc'", + ); - cases.add("switch on enum with 1 field with no prongs", + cases.add( + "switch on enum with 1 field with no prongs", \\const Foo = enum { M }; \\ \\export fn entry() void { \\ var f = Foo.M; \\ switch (f) {} \\} - , ".tmp_source.zig:5:5: error: enumeration value 'Foo.M' not handled in switch"); + , + ".tmp_source.zig:5:5: error: enumeration value 'Foo.M' not handled in switch", + ); - cases.add("shift by negative comptime integer", + cases.add( + "shift by negative comptime integer", \\comptime { \\ var a = 1 >> -1; \\} - , ".tmp_source.zig:2:18: error: shift by negative value -1"); + , + ".tmp_source.zig:2:18: error: shift by negative value -1", + ); - cases.add("@panic called at compile time", + cases.add( + "@panic called at compile time", \\export fn entry() void { \\ comptime { - \\ @panic("aoeu"); + \\ @panic("aoeu",); \\ } \\} - , ".tmp_source.zig:3:9: error: encountered @panic at compile-time"); + , + ".tmp_source.zig:3:9: error: encountered @panic at compile-time", + ); - cases.add("wrong return type for main", + cases.add( + "wrong return type for main", \\pub fn main() f32 { } - , "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'"); + , + "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'", + ); - cases.add("double ?? on main return value", + cases.add( + "double ?? on main return value", \\pub fn main() ??void { \\} - , "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'"); + , + "error: expected return type of main to be 'u8', 'noreturn', 'void', or '!void'", + ); - cases.add("bad identifier in function with struct defined inside function which references local const", + cases.add( + "bad identifier in function with struct defined inside function which references local const", \\export fn entry() void { \\ const BlockKind = u32; \\ @@ -460,9 +561,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\ bogus; \\} - , ".tmp_source.zig:8:5: error: use of undeclared identifier 'bogus'"); + , + ".tmp_source.zig:8:5: error: use of undeclared identifier 'bogus'", + ); - cases.add("labeled break not found", + cases.add( + "labeled break not found", \\export fn entry() void { \\ blah: while (true) { \\ while (true) { @@ -470,9 +574,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\ } \\} - , ".tmp_source.zig:4:13: error: label not found: 'outer'"); + , + ".tmp_source.zig:4:13: error: label not found: 'outer'", + ); - cases.add("labeled continue not found", + cases.add( + "labeled continue not found", \\export fn entry() void { \\ var i: usize = 0; \\ blah: while (i < 10) : (i += 1) { @@ -481,9 +588,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\ } \\} - , ".tmp_source.zig:5:13: error: labeled loop not found: 'outer'"); + , + ".tmp_source.zig:5:13: error: labeled loop not found: 'outer'", + ); - cases.add("attempt to use 0 bit type in extern fn", + cases.add( + "attempt to use 0 bit type in extern fn", \\extern fn foo(ptr: extern fn(&void) void) void; \\ \\export fn entry() void { @@ -491,390 +601,541 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\extern fn bar(x: &void) void { } - , ".tmp_source.zig:7:18: error: parameter of type '&void' has 0 bits; not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:7:18: error: parameter of type '&void' has 0 bits; not allowed in function with calling convention 'ccc'", + ); - cases.add("implicit semicolon - block statement", + cases.add( + "implicit semicolon - block statement", \\export fn entry() void { \\ {} \\ var good = {}; \\ ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - block expr", + cases.add( + "implicit semicolon - block expr", \\export fn entry() void { \\ _ = {}; \\ var good = {}; \\ _ = {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - comptime statement", + cases.add( + "implicit semicolon - comptime statement", \\export fn entry() void { \\ comptime {} \\ var good = {}; \\ comptime ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - comptime expression", + cases.add( + "implicit semicolon - comptime expression", \\export fn entry() void { \\ _ = comptime {}; \\ var good = {}; \\ _ = comptime {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - defer", + cases.add( + "implicit semicolon - defer", \\export fn entry() void { \\ defer {} \\ var good = {}; \\ defer ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if statement", + cases.add( + "implicit semicolon - if statement", \\export fn entry() void { \\ if(true) {} \\ var good = {}; \\ if(true) ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if expression", + cases.add( + "implicit semicolon - if expression", \\export fn entry() void { \\ _ = if(true) {}; \\ var good = {}; \\ _ = if(true) {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else statement", + cases.add( + "implicit semicolon - if-else statement", \\export fn entry() void { \\ if(true) {} else {} \\ var good = {}; \\ if(true) ({}) else ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else expression", + cases.add( + "implicit semicolon - if-else expression", \\export fn entry() void { \\ _ = if(true) {} else {}; \\ var good = {}; \\ _ = if(true) {} else {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else-if statement", + cases.add( + "implicit semicolon - if-else-if statement", \\export fn entry() void { \\ if(true) {} else if(true) {} \\ var good = {}; \\ if(true) ({}) else if(true) ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else-if expression", + cases.add( + "implicit semicolon - if-else-if expression", \\export fn entry() void { \\ _ = if(true) {} else if(true) {}; \\ var good = {}; \\ _ = if(true) {} else if(true) {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else-if-else statement", + cases.add( + "implicit semicolon - if-else-if-else statement", \\export fn entry() void { \\ if(true) {} else if(true) {} else {} \\ var good = {}; \\ if(true) ({}) else if(true) ({}) else ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - if-else-if-else expression", + cases.add( + "implicit semicolon - if-else-if-else expression", \\export fn entry() void { \\ _ = if(true) {} else if(true) {} else {}; \\ var good = {}; \\ _ = if(true) {} else if(true) {} else {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - test statement", + cases.add( + "implicit semicolon - test statement", \\export fn entry() void { \\ if (foo()) |_| {} \\ var good = {}; \\ if (foo()) |_| ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - test expression", + cases.add( + "implicit semicolon - test expression", \\export fn entry() void { \\ _ = if (foo()) |_| {}; \\ var good = {}; \\ _ = if (foo()) |_| {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - while statement", + cases.add( + "implicit semicolon - while statement", \\export fn entry() void { \\ while(true) {} \\ var good = {}; \\ while(true) ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - while expression", + cases.add( + "implicit semicolon - while expression", \\export fn entry() void { \\ _ = while(true) {}; \\ var good = {}; \\ _ = while(true) {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - while-continue statement", + cases.add( + "implicit semicolon - while-continue statement", \\export fn entry() void { \\ while(true):({}) {} \\ var good = {}; \\ while(true):({}) ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - while-continue expression", + cases.add( + "implicit semicolon - while-continue expression", \\export fn entry() void { \\ _ = while(true):({}) {}; \\ var good = {}; \\ _ = while(true):({}) {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - for statement", + cases.add( + "implicit semicolon - for statement", \\export fn entry() void { \\ for(foo()) {} \\ var good = {}; \\ for(foo()) ({}) \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("implicit semicolon - for expression", + cases.add( + "implicit semicolon - for expression", \\export fn entry() void { \\ _ = for(foo()) {}; \\ var good = {}; \\ _ = for(foo()) {} \\ var bad = {}; \\} - , ".tmp_source.zig:5:5: error: expected token ';', found 'var'"); + , + ".tmp_source.zig:5:5: error: expected token ';', found 'var'", + ); - cases.add("multiple function definitions", + cases.add( + "multiple function definitions", \\fn a() void {} \\fn a() void {} \\export fn entry() void { a(); } - , ".tmp_source.zig:2:1: error: redefinition of 'a'"); + , + ".tmp_source.zig:2:1: error: redefinition of 'a'", + ); - cases.add("unreachable with return", + cases.add( + "unreachable with return", \\fn a() noreturn {return;} \\export fn entry() void { a(); } - , ".tmp_source.zig:1:18: error: expected type 'noreturn', found 'void'"); + , + ".tmp_source.zig:1:18: error: expected type 'noreturn', found 'void'", + ); - cases.add("control reaches end of non-void function", + cases.add( + "control reaches end of non-void function", \\fn a() i32 {} \\export fn entry() void { _ = a(); } - , ".tmp_source.zig:1:12: error: expected type 'i32', found 'void'"); + , + ".tmp_source.zig:1:12: error: expected type 'i32', found 'void'", + ); - cases.add("undefined function call", + cases.add( + "undefined function call", \\export fn a() void { \\ b(); \\} - , ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'"); + , + ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'", + ); - cases.add("wrong number of arguments", + cases.add( + "wrong number of arguments", \\export fn a() void { \\ b(1); \\} \\fn b(a: i32, b: i32, c: i32) void { } - , ".tmp_source.zig:2:6: error: expected 3 arguments, found 1"); + , + ".tmp_source.zig:2:6: error: expected 3 arguments, found 1", + ); - cases.add("invalid type", + cases.add( + "invalid type", \\fn a() bogus {} \\export fn entry() void { _ = a(); } - , ".tmp_source.zig:1:8: error: use of undeclared identifier 'bogus'"); + , + ".tmp_source.zig:1:8: error: use of undeclared identifier 'bogus'", + ); - cases.add("pointer to noreturn", + cases.add( + "pointer to noreturn", \\fn a() &noreturn {} \\export fn entry() void { _ = a(); } - , ".tmp_source.zig:1:9: error: pointer to noreturn not allowed"); + , + ".tmp_source.zig:1:9: error: pointer to noreturn not allowed", + ); - cases.add("unreachable code", + cases.add( + "unreachable code", \\export fn a() void { \\ return; \\ b(); \\} \\ \\fn b() void {} - , ".tmp_source.zig:3:5: error: unreachable code"); + , + ".tmp_source.zig:3:5: error: unreachable code", + ); - cases.add("bad import", - \\const bogus = @import("bogus-does-not-exist.zig"); + cases.add( + "bad import", + \\const bogus = @import("bogus-does-not-exist.zig",); \\export fn entry() void { bogus.bogo(); } - , ".tmp_source.zig:1:15: error: unable to find 'bogus-does-not-exist.zig'"); + , + ".tmp_source.zig:1:15: error: unable to find 'bogus-does-not-exist.zig'", + ); - cases.add("undeclared identifier", + cases.add( + "undeclared identifier", \\export fn a() void { \\ return \\ b + \\ c; \\} , - ".tmp_source.zig:3:5: error: use of undeclared identifier 'b'", - ".tmp_source.zig:4:5: error: use of undeclared identifier 'c'"); + ".tmp_source.zig:3:5: error: use of undeclared identifier 'b'", + ".tmp_source.zig:4:5: error: use of undeclared identifier 'c'", + ); - cases.add("parameter redeclaration", + cases.add( + "parameter redeclaration", \\fn f(a : i32, a : i32) void { \\} \\export fn entry() void { f(1, 2); } - , ".tmp_source.zig:1:15: error: redeclaration of variable 'a'"); + , + ".tmp_source.zig:1:15: error: redeclaration of variable 'a'", + ); - cases.add("local variable redeclaration", + cases.add( + "local variable redeclaration", \\export fn f() void { \\ const a : i32 = 0; \\ const a = 0; \\} - , ".tmp_source.zig:3:5: error: redeclaration of variable 'a'"); + , + ".tmp_source.zig:3:5: error: redeclaration of variable 'a'", + ); - cases.add("local variable redeclares parameter", + cases.add( + "local variable redeclares parameter", \\fn f(a : i32) void { \\ const a = 0; \\} \\export fn entry() void { f(1); } - , ".tmp_source.zig:2:5: error: redeclaration of variable 'a'"); + , + ".tmp_source.zig:2:5: error: redeclaration of variable 'a'", + ); - cases.add("variable has wrong type", + cases.add( + "variable has wrong type", \\export fn f() i32 { \\ const a = c"a"; \\ return a; \\} - , ".tmp_source.zig:3:12: error: expected type 'i32', found '&const u8'"); + , + ".tmp_source.zig:3:12: error: expected type 'i32', found '&const u8'", + ); - cases.add("if condition is bool, not int", + cases.add( + "if condition is bool, not int", \\export fn f() void { \\ if (0) {} \\} - , ".tmp_source.zig:2:9: error: integer value 0 cannot be implicitly casted to type 'bool'"); + , + ".tmp_source.zig:2:9: error: integer value 0 cannot be implicitly casted to type 'bool'", + ); - cases.add("assign unreachable", + cases.add( + "assign unreachable", \\export fn f() void { \\ const a = return; \\} - , ".tmp_source.zig:2:5: error: unreachable code"); + , + ".tmp_source.zig:2:5: error: unreachable code", + ); - cases.add("unreachable variable", + cases.add( + "unreachable variable", \\export fn f() void { \\ const a: noreturn = {}; \\} - , ".tmp_source.zig:2:14: error: variable of type 'noreturn' not allowed"); + , + ".tmp_source.zig:2:14: error: variable of type 'noreturn' not allowed", + ); - cases.add("unreachable parameter", + cases.add( + "unreachable parameter", \\fn f(a: noreturn) void {} \\export fn entry() void { f(); } - , ".tmp_source.zig:1:9: error: parameter of type 'noreturn' not allowed"); + , + ".tmp_source.zig:1:9: error: parameter of type 'noreturn' not allowed", + ); - cases.add("bad assignment target", + cases.add( + "bad assignment target", \\export fn f() void { \\ 3 = 3; \\} - , ".tmp_source.zig:2:7: error: cannot assign to constant"); + , + ".tmp_source.zig:2:7: error: cannot assign to constant", + ); - cases.add("assign to constant variable", + cases.add( + "assign to constant variable", \\export fn f() void { \\ const a = 3; \\ a = 4; \\} - , ".tmp_source.zig:3:7: error: cannot assign to constant"); + , + ".tmp_source.zig:3:7: error: cannot assign to constant", + ); - cases.add("use of undeclared identifier", + cases.add( + "use of undeclared identifier", \\export fn f() void { \\ b = 3; \\} - , ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'"); + , + ".tmp_source.zig:2:5: error: use of undeclared identifier 'b'", + ); - cases.add("const is a statement, not an expression", + cases.add( + "const is a statement, not an expression", \\export fn f() void { \\ (const a = 0); \\} - , ".tmp_source.zig:2:6: error: invalid token: 'const'"); + , + ".tmp_source.zig:2:6: error: invalid token: 'const'", + ); - cases.add("array access of undeclared identifier", + cases.add( + "array access of undeclared identifier", \\export fn f() void { \\ i[i] = i[i]; \\} - , ".tmp_source.zig:2:5: error: use of undeclared identifier 'i'", - ".tmp_source.zig:2:12: error: use of undeclared identifier 'i'"); + , + ".tmp_source.zig:2:5: error: use of undeclared identifier 'i'", + ".tmp_source.zig:2:12: error: use of undeclared identifier 'i'", + ); - cases.add("array access of non array", + cases.add( + "array access of non array", \\export fn f() void { \\ var bad : bool = undefined; \\ bad[bad] = bad[bad]; \\} - , ".tmp_source.zig:3:8: error: array access of non-array type 'bool'", - ".tmp_source.zig:3:19: error: array access of non-array type 'bool'"); + , + ".tmp_source.zig:3:8: error: array access of non-array type 'bool'", + ".tmp_source.zig:3:19: error: array access of non-array type 'bool'", + ); - cases.add("array access with non integer index", + cases.add( + "array access with non integer index", \\export fn f() void { \\ var array = "aoeu"; \\ var bad = false; \\ array[bad] = array[bad]; \\} - , ".tmp_source.zig:4:11: error: expected type 'usize', found 'bool'", - ".tmp_source.zig:4:24: error: expected type 'usize', found 'bool'"); + , + ".tmp_source.zig:4:11: error: expected type 'usize', found 'bool'", + ".tmp_source.zig:4:24: error: expected type 'usize', found 'bool'", + ); - cases.add("write to const global variable", + cases.add( + "write to const global variable", \\const x : i32 = 99; \\fn f() void { \\ x = 1; \\} \\export fn entry() void { f(); } - , ".tmp_source.zig:3:7: error: cannot assign to constant"); - + , + ".tmp_source.zig:3:7: error: cannot assign to constant", + ); - cases.add("missing else clause", + cases.add( + "missing else clause", \\fn f(b: bool) void { \\ const x : i32 = if (b) h: { break :h 1; }; \\ const y = if (b) h: { break :h i32(1); }; \\} \\export fn entry() void { f(true); } - , ".tmp_source.zig:2:42: error: integer value 1 cannot be implicitly casted to type 'void'", - ".tmp_source.zig:3:15: error: incompatible types: 'i32' and 'void'"); + , + ".tmp_source.zig:2:42: error: integer value 1 cannot be implicitly casted to type 'void'", + ".tmp_source.zig:3:15: error: incompatible types: 'i32' and 'void'", + ); - cases.add("direct struct loop", + cases.add( + "direct struct loop", \\const A = struct { a : A, }; \\export fn entry() usize { return @sizeOf(A); } - , ".tmp_source.zig:1:11: error: struct 'A' contains itself"); + , + ".tmp_source.zig:1:11: error: struct 'A' contains itself", + ); - cases.add("indirect struct loop", + cases.add( + "indirect struct loop", \\const A = struct { b : B, }; \\const B = struct { c : C, }; \\const C = struct { a : A, }; \\export fn entry() usize { return @sizeOf(A); } - , ".tmp_source.zig:1:11: error: struct 'A' contains itself"); + , + ".tmp_source.zig:1:11: error: struct 'A' contains itself", + ); - cases.add("invalid struct field", + cases.add( + "invalid struct field", \\const A = struct { x : i32, }; \\export fn f() void { \\ var a : A = undefined; @@ -882,27 +1143,37 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const y = a.bar; \\} , - ".tmp_source.zig:4:6: error: no member named 'foo' in struct 'A'", - ".tmp_source.zig:5:16: error: no member named 'bar' in struct 'A'"); + ".tmp_source.zig:4:6: error: no member named 'foo' in struct 'A'", + ".tmp_source.zig:5:16: error: no member named 'bar' in struct 'A'", + ); - cases.add("redefinition of struct", + cases.add( + "redefinition of struct", \\const A = struct { x : i32, }; \\const A = struct { y : i32, }; - , ".tmp_source.zig:2:1: error: redefinition of 'A'"); + , + ".tmp_source.zig:2:1: error: redefinition of 'A'", + ); - cases.add("redefinition of enums", + cases.add( + "redefinition of enums", \\const A = enum {}; \\const A = enum {}; - , ".tmp_source.zig:2:1: error: redefinition of 'A'"); + , + ".tmp_source.zig:2:1: error: redefinition of 'A'", + ); - cases.add("redefinition of global variables", + cases.add( + "redefinition of global variables", \\var a : i32 = 1; \\var a : i32 = 2; , - ".tmp_source.zig:2:1: error: redefinition of 'a'", - ".tmp_source.zig:1:1: note: previous definition is here"); + ".tmp_source.zig:2:1: error: redefinition of 'a'", + ".tmp_source.zig:1:1: note: previous definition is here", + ); - cases.add("duplicate field in struct value expression", + cases.add( + "duplicate field in struct value expression", \\const A = struct { \\ x : i32, \\ y : i32, @@ -916,9 +1187,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ .z = 4, \\ }; \\} - , ".tmp_source.zig:11:9: error: duplicate field"); + , + ".tmp_source.zig:11:9: error: duplicate field", + ); - cases.add("missing field in struct value expression", + cases.add( + "missing field in struct value expression", \\const A = struct { \\ x : i32, \\ y : i32, @@ -932,9 +1206,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ .y = 2, \\ }; \\} - , ".tmp_source.zig:9:17: error: missing field: 'x'"); + , + ".tmp_source.zig:9:17: error: missing field: 'x'", + ); - cases.add("invalid field in struct value expression", + cases.add( + "invalid field in struct value expression", \\const A = struct { \\ x : i32, \\ y : i32, @@ -947,66 +1224,95 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ .foo = 42, \\ }; \\} - , ".tmp_source.zig:10:9: error: no member named 'foo' in struct 'A'"); + , + ".tmp_source.zig:10:9: error: no member named 'foo' in struct 'A'", + ); - cases.add("invalid break expression", + cases.add( + "invalid break expression", \\export fn f() void { \\ break; \\} - , ".tmp_source.zig:2:5: error: break expression outside loop"); + , + ".tmp_source.zig:2:5: error: break expression outside loop", + ); - cases.add("invalid continue expression", + cases.add( + "invalid continue expression", \\export fn f() void { \\ continue; \\} - , ".tmp_source.zig:2:5: error: continue expression outside loop"); + , + ".tmp_source.zig:2:5: error: continue expression outside loop", + ); - cases.add("invalid maybe type", + cases.add( + "invalid maybe type", \\export fn f() void { \\ if (true) |x| { } \\} - , ".tmp_source.zig:2:9: error: expected nullable type, found 'bool'"); + , + ".tmp_source.zig:2:9: error: expected nullable type, found 'bool'", + ); - cases.add("cast unreachable", + cases.add( + "cast unreachable", \\fn f() i32 { \\ return i32(return 1); \\} \\export fn entry() void { _ = f(); } - , ".tmp_source.zig:2:15: error: unreachable code"); + , + ".tmp_source.zig:2:15: error: unreachable code", + ); - cases.add("invalid builtin fn", + cases.add( + "invalid builtin fn", \\fn f() @bogus(foo) { \\} \\export fn entry() void { _ = f(); } - , ".tmp_source.zig:1:8: error: invalid builtin function: 'bogus'"); + , + ".tmp_source.zig:1:8: error: invalid builtin function: 'bogus'", + ); - cases.add("top level decl dependency loop", + cases.add( + "top level decl dependency loop", \\const a : @typeOf(b) = 0; \\const b : @typeOf(a) = 0; \\export fn entry() void { \\ const c = a + b; \\} - , ".tmp_source.zig:1:1: error: 'a' depends on itself"); + , + ".tmp_source.zig:1:1: error: 'a' depends on itself", + ); - cases.add("noalias on non pointer param", + cases.add( + "noalias on non pointer param", \\fn f(noalias x: i32) void {} \\export fn entry() void { f(1234); } - , ".tmp_source.zig:1:6: error: noalias on non-pointer parameter"); + , + ".tmp_source.zig:1:6: error: noalias on non-pointer parameter", + ); - cases.add("struct init syntax for array", + cases.add( + "struct init syntax for array", \\const foo = []u16{.x = 1024,}; \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:1:18: error: type '[]u16' does not support struct initialization syntax"); + , + ".tmp_source.zig:1:18: error: type '[]u16' does not support struct initialization syntax", + ); - cases.add("type variables must be constant", + cases.add( + "type variables must be constant", \\var foo = u8; \\export fn entry() foo { \\ return 1; \\} - , ".tmp_source.zig:1:1: error: variable of type 'type' must be constant"); - + , + ".tmp_source.zig:1:1: error: variable of type 'type' must be constant", + ); - cases.add("variables shadowing types", + cases.add( + "variables shadowing types", \\const Foo = struct {}; \\const Bar = struct {}; \\ @@ -1018,12 +1324,14 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ f(1234); \\} , - ".tmp_source.zig:4:6: error: redefinition of 'Foo'", - ".tmp_source.zig:1:1: note: previous definition is here", - ".tmp_source.zig:5:5: error: redefinition of 'Bar'", - ".tmp_source.zig:2:1: note: previous definition is here"); + ".tmp_source.zig:4:6: error: redefinition of 'Foo'", + ".tmp_source.zig:1:1: note: previous definition is here", + ".tmp_source.zig:5:5: error: redefinition of 'Bar'", + ".tmp_source.zig:2:1: note: previous definition is here", + ); - cases.add("switch expression - missing enumeration prong", + cases.add( + "switch expression - missing enumeration prong", \\const Number = enum { \\ One, \\ Two, @@ -1039,9 +1347,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:8:5: error: enumeration value 'Number.Four' not handled in switch"); + , + ".tmp_source.zig:8:5: error: enumeration value 'Number.Four' not handled in switch", + ); - cases.add("switch expression - duplicate enumeration prong", + cases.add( + "switch expression - duplicate enumeration prong", \\const Number = enum { \\ One, \\ Two, @@ -1059,10 +1370,13 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:13:15: error: duplicate switch value", - ".tmp_source.zig:10:15: note: other value is here"); + , + ".tmp_source.zig:13:15: error: duplicate switch value", + ".tmp_source.zig:10:15: note: other value is here", + ); - cases.add("switch expression - duplicate enumeration prong when else present", + cases.add( + "switch expression - duplicate enumeration prong when else present", \\const Number = enum { \\ One, \\ Two, @@ -1081,10 +1395,13 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:13:15: error: duplicate switch value", - ".tmp_source.zig:10:15: note: other value is here"); + , + ".tmp_source.zig:13:15: error: duplicate switch value", + ".tmp_source.zig:10:15: note: other value is here", + ); - cases.add("switch expression - multiple else prongs", + cases.add( + "switch expression - multiple else prongs", \\fn f(x: u32) void { \\ const value: bool = switch (x) { \\ 1234 => false, @@ -1095,9 +1412,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\export fn entry() void { \\ f(1234); \\} - , ".tmp_source.zig:5:9: error: multiple else prongs in switch expression"); + , + ".tmp_source.zig:5:9: error: multiple else prongs in switch expression", + ); - cases.add("switch expression - non exhaustive integer prongs", + cases.add( + "switch expression - non exhaustive integer prongs", \\fn foo(x: u8) void { \\ switch (x) { \\ 0 => {}, @@ -1105,9 +1425,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , - ".tmp_source.zig:2:5: error: switch must handle all possibilities"); + ".tmp_source.zig:2:5: error: switch must handle all possibilities", + ); - cases.add("switch expression - duplicate or overlapping integer value", + cases.add( + "switch expression - duplicate or overlapping integer value", \\fn foo(x: u8) u8 { \\ return switch (x) { \\ 0 ... 100 => u8(0), @@ -1119,9 +1441,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , ".tmp_source.zig:6:9: error: duplicate switch value", - ".tmp_source.zig:5:14: note: previous value is here"); + ".tmp_source.zig:5:14: note: previous value is here", + ); - cases.add("switch expression - switch on pointer type with no else", + cases.add( + "switch expression - switch on pointer type with no else", \\fn foo(x: &u8) void { \\ switch (x) { \\ &y => {}, @@ -1130,54 +1454,77 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\const y: u8 = 100; \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , - ".tmp_source.zig:2:5: error: else prong required when switching on type '&u8'"); + ".tmp_source.zig:2:5: error: else prong required when switching on type '&u8'", + ); - cases.add("global variable initializer must be constant expression", + cases.add( + "global variable initializer must be constant expression", \\extern fn foo() i32; \\const x = foo(); \\export fn entry() i32 { return x; } - , ".tmp_source.zig:2:11: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:2:11: error: unable to evaluate constant expression", + ); - cases.add("array concatenation with wrong type", + cases.add( + "array concatenation with wrong type", \\const src = "aoeu"; \\const derp = usize(1234); \\const a = derp ++ "foo"; \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } - , ".tmp_source.zig:3:11: error: expected array or C string literal, found 'usize'"); + , + ".tmp_source.zig:3:11: error: expected array or C string literal, found 'usize'", + ); - cases.add("non compile time array concatenation", + cases.add( + "non compile time array concatenation", \\fn f() []u8 { \\ return s ++ "foo"; \\} \\var s: [10]u8 = undefined; \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:2:12: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:2:12: error: unable to evaluate constant expression", + ); - cases.add("@cImport with bogus include", + cases.add( + "@cImport with bogus include", \\const c = @cImport(@cInclude("bogus.h")); \\export fn entry() usize { return @sizeOf(@typeOf(c.bogo)); } - , ".tmp_source.zig:1:11: error: C import failed", - ".h:1:10: note: 'bogus.h' file not found"); + , + ".tmp_source.zig:1:11: error: C import failed", + ".h:1:10: note: 'bogus.h' file not found", + ); - cases.add("address of number literal", + cases.add( + "address of number literal", \\const x = 3; \\const y = &x; \\fn foo() &const i32 { return y; } \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:3:30: error: expected type '&const i32', found '&const (integer literal)'"); + , + ".tmp_source.zig:3:30: error: expected type '&const i32', found '&const (integer literal)'", + ); - cases.add("integer overflow error", + cases.add( + "integer overflow error", \\const x : u8 = 300; \\export fn entry() usize { return @sizeOf(@typeOf(x)); } - , ".tmp_source.zig:1:16: error: integer value 300 cannot be implicitly casted to type 'u8'"); + , + ".tmp_source.zig:1:16: error: integer value 300 cannot be implicitly casted to type 'u8'", + ); - cases.add("incompatible number literals", + cases.add( + "incompatible number literals", \\const x = 2 == 2.0; \\export fn entry() usize { return @sizeOf(@typeOf(x)); } - , ".tmp_source.zig:1:11: error: integer value 2 cannot be implicitly casted to type '(float literal)'"); + , + ".tmp_source.zig:1:11: error: integer value 2 cannot be implicitly casted to type '(float literal)'", + ); - cases.add("missing function call param", + cases.add( + "missing function call param", \\const Foo = struct { \\ a: i32, \\ b: i32, @@ -1201,58 +1548,73 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:20:34: error: expected 1 arguments, found 0"); + , + ".tmp_source.zig:20:34: error: expected 1 arguments, found 0", + ); - cases.add("missing function name and param name", + cases.add( + "missing function name and param name", \\fn () void {} \\fn f(i32) void {} \\export fn entry() usize { return @sizeOf(@typeOf(f)); } , - ".tmp_source.zig:1:1: error: missing function name", - ".tmp_source.zig:2:6: error: missing parameter name"); + ".tmp_source.zig:1:1: error: missing function name", + ".tmp_source.zig:2:6: error: missing parameter name", + ); - cases.add("wrong function type", + cases.add( + "wrong function type", \\const fns = []fn() void { a, b, c }; \\fn a() i32 {return 0;} \\fn b() i32 {return 1;} \\fn c() i32 {return 2;} \\export fn entry() usize { return @sizeOf(@typeOf(fns)); } - , ".tmp_source.zig:1:27: error: expected type 'fn() void', found 'fn() i32'"); + , + ".tmp_source.zig:1:27: error: expected type 'fn() void', found 'fn() i32'", + ); - cases.add("extern function pointer mismatch", + cases.add( + "extern function pointer mismatch", \\const fns = [](fn(i32)i32) { a, b, c }; \\pub fn a(x: i32) i32 {return x + 0;} \\pub fn b(x: i32) i32 {return x + 1;} \\export fn c(x: i32) i32 {return x + 2;} \\ \\export fn entry() usize { return @sizeOf(@typeOf(fns)); } - , ".tmp_source.zig:1:36: error: expected type 'fn(i32) i32', found 'extern fn(i32) i32'"); - + , + ".tmp_source.zig:1:36: error: expected type 'fn(i32) i32', found 'extern fn(i32) i32'", + ); - cases.add("implicit cast from f64 to f32", + cases.add( + "implicit cast from f64 to f32", \\const x : f64 = 1.0; \\const y : f32 = x; \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } - , ".tmp_source.zig:2:17: error: expected type 'f32', found 'f64'"); - + , + ".tmp_source.zig:2:17: error: expected type 'f32', found 'f64'", + ); - cases.add("colliding invalid top level functions", + cases.add( + "colliding invalid top level functions", \\fn func() bogus {} \\fn func() bogus {} \\export fn entry() usize { return @sizeOf(@typeOf(func)); } , - ".tmp_source.zig:2:1: error: redefinition of 'func'", - ".tmp_source.zig:1:11: error: use of undeclared identifier 'bogus'"); + ".tmp_source.zig:2:1: error: redefinition of 'func'", + ".tmp_source.zig:1:11: error: use of undeclared identifier 'bogus'", + ); - - cases.add("bogus compile var", + cases.add( + "bogus compile var", \\const x = @import("builtin").bogus; \\export fn entry() usize { return @sizeOf(@typeOf(x)); } - , ".tmp_source.zig:1:29: error: no member named 'bogus' in '"); - + , + ".tmp_source.zig:1:29: error: no member named 'bogus' in '", + ); - cases.add("non constant expression in array size outside function", + cases.add( + "non constant expression in array size outside function", \\const Foo = struct { \\ y: [get()]u8, \\}; @@ -1261,22 +1623,25 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(Foo)); } , - ".tmp_source.zig:5:25: error: unable to evaluate constant expression", - ".tmp_source.zig:2:12: note: called from here", - ".tmp_source.zig:2:8: note: called from here"); - + ".tmp_source.zig:5:25: error: unable to evaluate constant expression", + ".tmp_source.zig:2:12: note: called from here", + ".tmp_source.zig:2:8: note: called from here", + ); - cases.add("addition with non numbers", + cases.add( + "addition with non numbers", \\const Foo = struct { \\ field: i32, \\}; \\const x = Foo {.field = 1} + Foo {.field = 2}; \\ \\export fn entry() usize { return @sizeOf(@typeOf(x)); } - , ".tmp_source.zig:4:28: error: invalid operands to binary expression: 'Foo' and 'Foo'"); - + , + ".tmp_source.zig:4:28: error: invalid operands to binary expression: 'Foo' and 'Foo'", + ); - cases.add("division by zero", + cases.add( + "division by zero", \\const lit_int_x = 1 / 0; \\const lit_float_x = 1.0 / 0.0; \\const int_x = u32(1) / u32(0); @@ -1287,49 +1652,65 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\export fn entry3() usize { return @sizeOf(@typeOf(int_x)); } \\export fn entry4() usize { return @sizeOf(@typeOf(float_x)); } , - ".tmp_source.zig:1:21: error: division by zero", - ".tmp_source.zig:2:25: error: division by zero", - ".tmp_source.zig:3:22: error: division by zero", - ".tmp_source.zig:4:26: error: division by zero"); - + ".tmp_source.zig:1:21: error: division by zero", + ".tmp_source.zig:2:25: error: division by zero", + ".tmp_source.zig:3:22: error: division by zero", + ".tmp_source.zig:4:26: error: division by zero", + ); - cases.add("normal string with newline", + cases.add( + "normal string with newline", \\const foo = "a \\b"; \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:1:13: error: newline not allowed in string literal"); + , + ".tmp_source.zig:1:13: error: newline not allowed in string literal", + ); - cases.add("invalid comparison for function pointers", + cases.add( + "invalid comparison for function pointers", \\fn foo() void {} \\const invalid = foo > foo; \\ \\export fn entry() usize { return @sizeOf(@typeOf(invalid)); } - , ".tmp_source.zig:2:21: error: operator not allowed for type 'fn() void'"); + , + ".tmp_source.zig:2:21: error: operator not allowed for type 'fn() void'", + ); - cases.add("generic function instance with non-constant expression", + cases.add( + "generic function instance with non-constant expression", \\fn foo(comptime x: i32, y: i32) i32 { return x + y; } \\fn test1(a: i32, b: i32) i32 { \\ return foo(a, b); \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(test1)); } - , ".tmp_source.zig:3:16: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:3:16: error: unable to evaluate constant expression", + ); - cases.add("assign null to non-nullable pointer", + cases.add( + "assign null to non-nullable pointer", \\const a: &u8 = null; \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } - , ".tmp_source.zig:1:16: error: expected type '&u8', found '(null)'"); + , + ".tmp_source.zig:1:16: error: expected type '&u8', found '(null)'", + ); - cases.add("indexing an array of size zero", + cases.add( + "indexing an array of size zero", \\const array = []u8{}; \\export fn foo() void { \\ const pointer = &array[0]; \\} - , ".tmp_source.zig:3:27: error: index 0 outside array of size 0"); + , + ".tmp_source.zig:3:27: error: index 0 outside array of size 0", + ); - cases.add("compile time division by zero", + cases.add( + "compile time division by zero", \\const y = foo(0); \\fn foo(x: u32) u32 { \\ return 1 / x; @@ -1337,17 +1718,21 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } , - ".tmp_source.zig:3:14: error: division by zero", - ".tmp_source.zig:1:14: note: called from here"); + ".tmp_source.zig:3:14: error: division by zero", + ".tmp_source.zig:1:14: note: called from here", + ); - cases.add("branch on undefined value", + cases.add( + "branch on undefined value", \\const x = if (undefined) true else false; \\ \\export fn entry() usize { return @sizeOf(@typeOf(x)); } - , ".tmp_source.zig:1:15: error: use of undefined value"); - + , + ".tmp_source.zig:1:15: error: use of undefined value", + ); - cases.add("endless loop in function evaluation", + cases.add( + "endless loop in function evaluation", \\const seventh_fib_number = fibbonaci(7); \\fn fibbonaci(x: i32) i32 { \\ return fibbonaci(x - 1) + fibbonaci(x - 2); @@ -1355,16 +1740,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(seventh_fib_number)); } , - ".tmp_source.zig:3:21: error: evaluation exceeded 1000 backwards branches", - ".tmp_source.zig:3:21: note: called from here"); + ".tmp_source.zig:3:21: error: evaluation exceeded 1000 backwards branches", + ".tmp_source.zig:3:21: note: called from here", + ); - cases.add("@embedFile with bogus file", - \\const resource = @embedFile("bogus.txt"); + cases.add( + "@embedFile with bogus file", + \\const resource = @embedFile("bogus.txt",); \\ \\export fn entry() usize { return @sizeOf(@typeOf(resource)); } - , ".tmp_source.zig:1:29: error: unable to find '", "bogus.txt'"); + , + ".tmp_source.zig:1:29: error: unable to find '", + "bogus.txt'", + ); - cases.add("non-const expression in struct literal outside function", + cases.add( + "non-const expression in struct literal outside function", \\const Foo = struct { \\ x: i32, \\}; @@ -1372,9 +1763,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\extern fn get_it() i32; \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } - , ".tmp_source.zig:4:21: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:4:21: error: unable to evaluate constant expression", + ); - cases.add("non-const expression function call with struct return value outside function", + cases.add( + "non-const expression function call with struct return value outside function", \\const Foo = struct { \\ x: i32, \\}; @@ -1387,19 +1781,24 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } , - ".tmp_source.zig:6:24: error: unable to evaluate constant expression", - ".tmp_source.zig:4:17: note: called from here"); + ".tmp_source.zig:6:24: error: unable to evaluate constant expression", + ".tmp_source.zig:4:17: note: called from here", + ); - cases.add("undeclared identifier error should mark fn as impure", + cases.add( + "undeclared identifier error should mark fn as impure", \\export fn foo() void { \\ test_a_thing(); \\} \\fn test_a_thing() void { \\ bad_fn_call(); \\} - , ".tmp_source.zig:5:5: error: use of undeclared identifier 'bad_fn_call'"); + , + ".tmp_source.zig:5:5: error: use of undeclared identifier 'bad_fn_call'", + ); - cases.add("illegal comparison of types", + cases.add( + "illegal comparison of types", \\fn bad_eql_1(a: []u8, b: []u8) bool { \\ return a == b; \\} @@ -1414,10 +1813,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\export fn entry1() usize { return @sizeOf(@typeOf(bad_eql_1)); } \\export fn entry2() usize { return @sizeOf(@typeOf(bad_eql_2)); } , - ".tmp_source.zig:2:14: error: operator not allowed for type '[]u8'", - ".tmp_source.zig:9:16: error: operator not allowed for type 'EnumWithData'"); + ".tmp_source.zig:2:14: error: operator not allowed for type '[]u8'", + ".tmp_source.zig:9:16: error: operator not allowed for type 'EnumWithData'", + ); - cases.add("non-const switch number literal", + cases.add( + "non-const switch number literal", \\export fn foo() void { \\ const x = switch (bar()) { \\ 1, 2 => 1, @@ -1428,25 +1829,34 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\fn bar() i32 { \\ return 2; \\} - , ".tmp_source.zig:2:15: error: unable to infer expression type"); + , + ".tmp_source.zig:2:15: error: unable to infer expression type", + ); - cases.add("atomic orderings of cmpxchg - failure stricter than success", + cases.add( + "atomic orderings of cmpxchg - failure stricter than success", \\const AtomicOrder = @import("builtin").AtomicOrder; \\export fn f() void { \\ var x: i32 = 1234; \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.Monotonic, AtomicOrder.SeqCst)) {} \\} - , ".tmp_source.zig:4:81: error: failure atomic ordering must be no stricter than success"); + , + ".tmp_source.zig:4:81: error: failure atomic ordering must be no stricter than success", + ); - cases.add("atomic orderings of cmpxchg - success Monotonic or stricter", + cases.add( + "atomic orderings of cmpxchg - success Monotonic or stricter", \\const AtomicOrder = @import("builtin").AtomicOrder; \\export fn f() void { \\ var x: i32 = 1234; \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.Unordered, AtomicOrder.Unordered)) {} \\} - , ".tmp_source.zig:4:58: error: success atomic ordering must be Monotonic or stricter"); + , + ".tmp_source.zig:4:58: error: success atomic ordering must be Monotonic or stricter", + ); - cases.add("negation overflow in function evaluation", + cases.add( + "negation overflow in function evaluation", \\const y = neg(-128); \\fn neg(x: i8) i8 { \\ return -x; @@ -1454,10 +1864,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } , - ".tmp_source.zig:3:12: error: negation caused overflow", - ".tmp_source.zig:1:14: note: called from here"); + ".tmp_source.zig:3:12: error: negation caused overflow", + ".tmp_source.zig:1:14: note: called from here", + ); - cases.add("add overflow in function evaluation", + cases.add( + "add overflow in function evaluation", \\const y = add(65530, 10); \\fn add(a: u16, b: u16) u16 { \\ return a + b; @@ -1465,11 +1877,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } , - ".tmp_source.zig:3:14: error: operation caused overflow", - ".tmp_source.zig:1:14: note: called from here"); - + ".tmp_source.zig:3:14: error: operation caused overflow", + ".tmp_source.zig:1:14: note: called from here", + ); - cases.add("sub overflow in function evaluation", + cases.add( + "sub overflow in function evaluation", \\const y = sub(10, 20); \\fn sub(a: u16, b: u16) u16 { \\ return a - b; @@ -1477,10 +1890,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } , - ".tmp_source.zig:3:14: error: operation caused overflow", - ".tmp_source.zig:1:14: note: called from here"); + ".tmp_source.zig:3:14: error: operation caused overflow", + ".tmp_source.zig:1:14: note: called from here", + ); - cases.add("mul overflow in function evaluation", + cases.add( + "mul overflow in function evaluation", \\const y = mul(300, 6000); \\fn mul(a: u16, b: u16) u16 { \\ return a * b; @@ -1488,27 +1903,34 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(y)); } , - ".tmp_source.zig:3:14: error: operation caused overflow", - ".tmp_source.zig:1:14: note: called from here"); + ".tmp_source.zig:3:14: error: operation caused overflow", + ".tmp_source.zig:1:14: note: called from here", + ); - cases.add("truncate sign mismatch", + cases.add( + "truncate sign mismatch", \\fn f() i8 { \\ const x: u32 = 10; \\ return @truncate(i8, x); \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:3:26: error: expected signed integer type, found 'u32'"); + , + ".tmp_source.zig:3:26: error: expected signed integer type, found 'u32'", + ); - cases.add("try in function with non error return type", + cases.add( + "try in function with non error return type", \\export fn f() void { \\ try something(); \\} \\fn something() error!void { } , - ".tmp_source.zig:2:5: error: expected type 'void', found 'error'"); + ".tmp_source.zig:2:5: error: expected type 'void', found 'error'", + ); - cases.add("invalid pointer for var type", + cases.add( + "invalid pointer for var type", \\extern fn ext() usize; \\var bytes: [ext()]u8 = undefined; \\export fn f() void { @@ -1516,30 +1938,42 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ b.* = u8(i); \\ } \\} - , ".tmp_source.zig:2:13: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:2:13: error: unable to evaluate constant expression", + ); - cases.add("export function with comptime parameter", + cases.add( + "export function with comptime parameter", \\export fn foo(comptime x: i32, y: i32) i32{ \\ return x + y; \\} - , ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'", + ); - cases.add("extern function with comptime parameter", + cases.add( + "extern function with comptime parameter", \\extern fn foo(comptime x: i32, y: i32) i32; \\fn f() i32 { \\ return foo(1, 2); \\} \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'"); + , + ".tmp_source.zig:1:15: error: comptime parameter not allowed in function with calling convention 'ccc'", + ); - cases.add("convert fixed size array to slice with invalid size", + cases.add( + "convert fixed size array to slice with invalid size", \\export fn f() void { \\ var array: [5]u8 = undefined; \\ var foo = ([]const u32)(array)[0]; \\} - , ".tmp_source.zig:3:28: error: unable to convert [5]u8 to []const u32: size mismatch"); + , + ".tmp_source.zig:3:28: error: unable to convert [5]u8 to []const u32: size mismatch", + ); - cases.add("non-pure function returns type", + cases.add( + "non-pure function returns type", \\var a: u32 = 0; \\pub fn List(comptime T: type) type { \\ a += 1; @@ -1558,18 +1992,24 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var list: List(i32) = undefined; \\ list.length = 10; \\} - , ".tmp_source.zig:3:7: error: unable to evaluate constant expression", - ".tmp_source.zig:16:19: note: called from here"); + , + ".tmp_source.zig:3:7: error: unable to evaluate constant expression", + ".tmp_source.zig:16:19: note: called from here", + ); - cases.add("bogus method call on slice", + cases.add( + "bogus method call on slice", \\var self = "aoeu"; \\fn f(m: []const u8) void { \\ m.copy(u8, self[0..], m); \\} \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:3:6: error: no member named 'copy' in '[]const u8'"); + , + ".tmp_source.zig:3:6: error: no member named 'copy' in '[]const u8'", + ); - cases.add("wrong number of arguments for method fn call", + cases.add( + "wrong number of arguments for method fn call", \\const Foo = struct { \\ fn method(self: &const Foo, a: i32) void {} \\}; @@ -1578,34 +2018,49 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ foo.method(1, 2); \\} \\export fn entry() usize { return @sizeOf(@typeOf(f)); } - , ".tmp_source.zig:6:15: error: expected 2 arguments, found 3"); + , + ".tmp_source.zig:6:15: error: expected 2 arguments, found 3", + ); - cases.add("assign through constant pointer", + cases.add( + "assign through constant pointer", \\export fn f() void { \\ var cstr = c"Hat"; \\ cstr[0] = 'W'; \\} - , ".tmp_source.zig:3:11: error: cannot assign to constant"); + , + ".tmp_source.zig:3:11: error: cannot assign to constant", + ); - cases.add("assign through constant slice", + cases.add( + "assign through constant slice", \\export fn f() void { \\ var cstr: []const u8 = "Hat"; \\ cstr[0] = 'W'; \\} - , ".tmp_source.zig:3:11: error: cannot assign to constant"); + , + ".tmp_source.zig:3:11: error: cannot assign to constant", + ); - cases.add("main function with bogus args type", + cases.add( + "main function with bogus args type", \\pub fn main(args: [][]bogus) !void {} - , ".tmp_source.zig:1:23: error: use of undeclared identifier 'bogus'"); + , + ".tmp_source.zig:1:23: error: use of undeclared identifier 'bogus'", + ); - cases.add("for loop missing element param", + cases.add( + "for loop missing element param", \\fn foo(blah: []u8) void { \\ for (blah) { } \\} \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:2:5: error: for loop expression missing element parameter"); + , + ".tmp_source.zig:2:5: error: for loop expression missing element parameter", + ); - cases.add("misspelled type with pointer only reference", + cases.add( + "misspelled type with pointer only reference", \\const JasonHM = u8; \\const JasonList = &JsonNode; \\ @@ -1636,9 +2091,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:5:16: error: use of undeclared identifier 'JsonList'"); + , + ".tmp_source.zig:5:16: error: use of undeclared identifier 'JsonList'", + ); - cases.add("method call with first arg type primitive", + cases.add( + "method call with first arg type primitive", \\const Foo = struct { \\ x: i32, \\ @@ -1654,9 +2112,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\ derp.init(); \\} - , ".tmp_source.zig:14:5: error: expected type 'i32', found '&const Foo'"); + , + ".tmp_source.zig:14:5: error: expected type 'i32', found '&const Foo'", + ); - cases.add("method call with first arg type wrong container", + cases.add( + "method call with first arg type wrong container", \\pub const List = struct { \\ len: usize, \\ allocator: &Allocator, @@ -1681,26 +2142,33 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x = List.init(&global_allocator); \\ x.init(); \\} - , ".tmp_source.zig:23:5: error: expected type '&Allocator', found '&List'"); + , + ".tmp_source.zig:23:5: error: expected type '&Allocator', found '&List'", + ); - cases.add("binary not on number literal", + cases.add( + "binary not on number literal", \\const TINY_QUANTUM_SHIFT = 4; \\const TINY_QUANTUM_SIZE = 1 << TINY_QUANTUM_SHIFT; \\var block_aligned_stuff: usize = (4 + TINY_QUANTUM_SIZE) & ~(TINY_QUANTUM_SIZE - 1); \\ \\export fn entry() usize { return @sizeOf(@typeOf(block_aligned_stuff)); } - , ".tmp_source.zig:3:60: error: unable to perform binary not operation on type '(integer literal)'"); + , + ".tmp_source.zig:3:60: error: unable to perform binary not operation on type '(integer literal)'", + ); cases.addCase(x: { - const tc = cases.create("multiple files with private function error", - \\const foo = @import("foo.zig"); + const tc = cases.create( + "multiple files with private function error", + \\const foo = @import("foo.zig",); \\ \\export fn callPrivFunction() void { \\ foo.privateFunction(); \\} , ".tmp_source.zig:4:8: error: 'privateFunction' is private", - "foo.zig:1:1: note: declared here"); + "foo.zig:1:1: note: declared here", + ); tc.addSourceFile("foo.zig", \\fn privateFunction() void { } @@ -1709,14 +2177,18 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { break :x tc; }); - cases.add("container init with non-type", + cases.add( + "container init with non-type", \\const zero: i32 = 0; \\const a = zero{1}; \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } - , ".tmp_source.zig:2:11: error: expected type, found 'i32'"); + , + ".tmp_source.zig:2:11: error: expected type, found 'i32'", + ); - cases.add("assign to constant field", + cases.add( + "assign to constant field", \\const Foo = struct { \\ field: i32, \\}; @@ -1724,9 +2196,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const f = Foo {.field = 1234,}; \\ f.field = 0; \\} - , ".tmp_source.zig:6:13: error: cannot assign to constant"); + , + ".tmp_source.zig:6:13: error: cannot assign to constant", + ); - cases.add("return from defer expression", + cases.add( + "return from defer expression", \\pub fn testTrickyDefer() !void { \\ defer canFail() catch {}; \\ @@ -1742,9 +2217,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(testTrickyDefer)); } - , ".tmp_source.zig:4:11: error: cannot return from defer expression"); + , + ".tmp_source.zig:4:11: error: cannot return from defer expression", + ); - cases.add("attempt to access var args out of bounds", + cases.add( + "attempt to access var args out of bounds", \\fn add(args: ...) i32 { \\ return args[0] + args[1]; \\} @@ -1755,10 +2233,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , - ".tmp_source.zig:2:26: error: index 1 outside argument list of size 1", - ".tmp_source.zig:6:15: note: called from here"); + ".tmp_source.zig:2:26: error: index 1 outside argument list of size 1", + ".tmp_source.zig:6:15: note: called from here", + ); - cases.add("pass integer literal to var args", + cases.add( + "pass integer literal to var args", \\fn add(args: ...) i32 { \\ var sum = i32(0); \\ {comptime var i: usize = 0; inline while (i < args.len) : (i += 1) { @@ -1772,32 +2252,44 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(bar)); } - , ".tmp_source.zig:10:16: error: compiler bug: integer and float literals in var args function must be casted"); + , + ".tmp_source.zig:10:16: error: compiler bug: integer and float literals in var args function must be casted", + ); - cases.add("assign too big number to u16", + cases.add( + "assign too big number to u16", \\export fn foo() void { \\ var vga_mem: u16 = 0xB8000; \\} - , ".tmp_source.zig:2:24: error: integer value 753664 cannot be implicitly casted to type 'u16'"); + , + ".tmp_source.zig:2:24: error: integer value 753664 cannot be implicitly casted to type 'u16'", + ); - cases.add("global variable alignment non power of 2", + cases.add( + "global variable alignment non power of 2", \\const some_data: [100]u8 align(3) = undefined; \\export fn entry() usize { return @sizeOf(@typeOf(some_data)); } - , ".tmp_source.zig:1:32: error: alignment value 3 is not a power of 2"); + , + ".tmp_source.zig:1:32: error: alignment value 3 is not a power of 2", + ); - cases.add("function alignment non power of 2", + cases.add( + "function alignment non power of 2", \\extern fn foo() align(3) void; \\export fn entry() void { return foo(); } - , ".tmp_source.zig:1:23: error: alignment value 3 is not a power of 2"); + , + ".tmp_source.zig:1:23: error: alignment value 3 is not a power of 2", + ); - cases.add("compile log", + cases.add( + "compile log", \\export fn foo() void { - \\ comptime bar(12, "hi"); + \\ comptime bar(12, "hi",); \\} \\fn bar(a: i32, b: []const u8) void { - \\ @compileLog("begin"); + \\ @compileLog("begin",); \\ @compileLog("a", a, "b", b); - \\ @compileLog("end"); + \\ @compileLog("end",); \\} , ".tmp_source.zig:5:5: error: found compile log statement", @@ -1805,9 +2297,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { ".tmp_source.zig:6:5: error: found compile log statement", ".tmp_source.zig:2:17: note: called from here", ".tmp_source.zig:7:5: error: found compile log statement", - ".tmp_source.zig:2:17: note: called from here"); + ".tmp_source.zig:2:17: note: called from here", + ); - cases.add("casting bit offset pointer to regular pointer", + cases.add( + "casting bit offset pointer to regular pointer", \\const BitField = packed struct { \\ a: u3, \\ b: u3, @@ -1823,9 +2317,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:8:26: error: expected type '&const u3', found '&align(1:3:6) const u3'"); + , + ".tmp_source.zig:8:26: error: expected type '&const u3', found '&align(1:3:6) const u3'", + ); - cases.add("referring to a struct that is invalid", + cases.add( + "referring to a struct that is invalid", \\const UsbDeviceRequest = struct { \\ Type: u8, \\}; @@ -1838,10 +2335,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ if (!ok) unreachable; \\} , - ".tmp_source.zig:10:14: error: unable to evaluate constant expression", - ".tmp_source.zig:6:20: note: called from here"); + ".tmp_source.zig:10:14: error: unable to evaluate constant expression", + ".tmp_source.zig:6:20: note: called from here", + ); - cases.add("control flow uses comptime var at runtime", + cases.add( + "control flow uses comptime var at runtime", \\export fn foo() void { \\ comptime var i = 0; \\ while (i < 5) : (i += 1) { @@ -1851,55 +2350,78 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\fn bar() void { } , - ".tmp_source.zig:3:5: error: control flow attempts to use compile-time variable at runtime", - ".tmp_source.zig:3:24: note: compile-time variable assigned here"); + ".tmp_source.zig:3:5: error: control flow attempts to use compile-time variable at runtime", + ".tmp_source.zig:3:24: note: compile-time variable assigned here", + ); - cases.add("ignored return value", + cases.add( + "ignored return value", \\export fn foo() void { \\ bar(); \\} \\fn bar() i32 { return 0; } - , ".tmp_source.zig:2:8: error: expression value is ignored"); + , + ".tmp_source.zig:2:8: error: expression value is ignored", + ); - cases.add("ignored assert-err-ok return value", + cases.add( + "ignored assert-err-ok return value", \\export fn foo() void { \\ bar() catch unreachable; \\} \\fn bar() error!i32 { return 0; } - , ".tmp_source.zig:2:11: error: expression value is ignored"); + , + ".tmp_source.zig:2:11: error: expression value is ignored", + ); - cases.add("ignored statement value", + cases.add( + "ignored statement value", \\export fn foo() void { \\ 1; \\} - , ".tmp_source.zig:2:5: error: expression value is ignored"); + , + ".tmp_source.zig:2:5: error: expression value is ignored", + ); - cases.add("ignored comptime statement value", + cases.add( + "ignored comptime statement value", \\export fn foo() void { \\ comptime {1;} \\} - , ".tmp_source.zig:2:15: error: expression value is ignored"); + , + ".tmp_source.zig:2:15: error: expression value is ignored", + ); - cases.add("ignored comptime value", + cases.add( + "ignored comptime value", \\export fn foo() void { \\ comptime 1; \\} - , ".tmp_source.zig:2:5: error: expression value is ignored"); + , + ".tmp_source.zig:2:5: error: expression value is ignored", + ); - cases.add("ignored defered statement value", + cases.add( + "ignored defered statement value", \\export fn foo() void { \\ defer {1;} \\} - , ".tmp_source.zig:2:12: error: expression value is ignored"); + , + ".tmp_source.zig:2:12: error: expression value is ignored", + ); - cases.add("ignored defered function call", + cases.add( + "ignored defered function call", \\export fn foo() void { \\ defer bar(); \\} \\fn bar() error!i32 { return 0; } - , ".tmp_source.zig:2:14: error: expression value is ignored"); + , + ".tmp_source.zig:2:14: error: expression value is ignored", + ); - cases.add("dereference an array", + cases.add( + "dereference an array", \\var s_buffer: [10]u8 = undefined; \\pub fn pass(in: []u8) []u8 { \\ var out = &s_buffer; @@ -1908,11 +2430,14 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(pass)); } - , ".tmp_source.zig:4:11: error: attempt to dereference non pointer type '[10]u8'"); + , + ".tmp_source.zig:4:11: error: attempt to dereference non pointer type '[10]u8'", + ); - cases.add("pass const ptr to mutable ptr fn", + cases.add( + "pass const ptr to mutable ptr fn", \\fn foo() bool { - \\ const a = ([]const u8)("a"); + \\ const a = ([]const u8)("a",); \\ const b = &a; \\ return ptrEql(b, b); \\} @@ -1921,18 +2446,22 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:4:19: error: expected type '&[]const u8', found '&const []const u8'"); + , + ".tmp_source.zig:4:19: error: expected type '&[]const u8', found '&const []const u8'", + ); cases.addCase(x: { - const tc = cases.create("export collision", - \\const foo = @import("foo.zig"); + const tc = cases.create( + "export collision", + \\const foo = @import("foo.zig",); \\ \\export fn bar() usize { \\ return foo.baz; \\} , "foo.zig:1:8: error: exported symbol collision: 'bar'", - ".tmp_source.zig:3:8: note: other symbol here"); + ".tmp_source.zig:3:8: note: other symbol here", + ); tc.addSourceFile("foo.zig", \\export fn bar() void {} @@ -1942,35 +2471,48 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { break :x tc; }); - cases.add("pass non-copyable type by value to function", + cases.add( + "pass non-copyable type by value to function", \\const Point = struct { x: i32, y: i32, }; \\fn foo(p: Point) void { } \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:2:11: error: type 'Point' is not copyable; cannot pass by value"); + , + ".tmp_source.zig:2:11: error: type 'Point' is not copyable; cannot pass by value", + ); - cases.add("implicit cast from array to mutable slice", + cases.add( + "implicit cast from array to mutable slice", \\var global_array: [10]i32 = undefined; \\fn foo(param: []i32) void {} \\export fn entry() void { \\ foo(global_array); \\} - , ".tmp_source.zig:4:9: error: expected type '[]i32', found '[10]i32'"); + , + ".tmp_source.zig:4:9: error: expected type '[]i32', found '[10]i32'", + ); - cases.add("ptrcast to non-pointer", + cases.add( + "ptrcast to non-pointer", \\export fn entry(a: &i32) usize { \\ return @ptrCast(usize, a); \\} - , ".tmp_source.zig:2:21: error: expected pointer, found 'usize'"); + , + ".tmp_source.zig:2:21: error: expected pointer, found 'usize'", + ); - cases.add("too many error values to cast to small integer", + cases.add( + "too many error values to cast to small integer", \\const Error = error { A, B, C, D, E, F, G, H }; \\fn foo(e: Error) u2 { \\ return u2(e); \\} \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } - , ".tmp_source.zig:3:14: error: too many error values to fit in 'u2'"); + , + ".tmp_source.zig:3:14: error: too many error values to fit in 'u2'", + ); - cases.add("asm at compile time", + cases.add( + "asm at compile time", \\comptime { \\ doSomeAsm(); \\} @@ -1982,48 +2524,66 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\.set aoeu, derp; \\ ); \\} - , ".tmp_source.zig:6:5: error: unable to evaluate constant expression"); + , + ".tmp_source.zig:6:5: error: unable to evaluate constant expression", + ); - cases.add("invalid member of builtin enum", - \\const builtin = @import("builtin"); + cases.add( + "invalid member of builtin enum", + \\const builtin = @import("builtin",); \\export fn entry() void { \\ const foo = builtin.Arch.x86; \\} - , ".tmp_source.zig:3:29: error: container 'Arch' has no member called 'x86'"); + , + ".tmp_source.zig:3:29: error: container 'Arch' has no member called 'x86'", + ); - cases.add("int to ptr of 0 bits", + cases.add( + "int to ptr of 0 bits", \\export fn foo() void { \\ var x: usize = 0x1000; \\ var y: &void = @intToPtr(&void, x); \\} - , ".tmp_source.zig:3:31: error: type '&void' has 0 bits and cannot store information"); + , + ".tmp_source.zig:3:31: error: type '&void' has 0 bits and cannot store information", + ); - cases.add("@fieldParentPtr - non struct", + cases.add( + "@fieldParentPtr - non struct", \\const Foo = i32; \\export fn foo(a: &i32) &Foo { \\ return @fieldParentPtr(Foo, "a", a); \\} - , ".tmp_source.zig:3:28: error: expected struct type, found 'i32'"); + , + ".tmp_source.zig:3:28: error: expected struct type, found 'i32'", + ); - cases.add("@fieldParentPtr - bad field name", + cases.add( + "@fieldParentPtr - bad field name", \\const Foo = extern struct { \\ derp: i32, \\}; \\export fn foo(a: &i32) &Foo { \\ return @fieldParentPtr(Foo, "a", a); \\} - , ".tmp_source.zig:5:33: error: struct 'Foo' has no field 'a'"); + , + ".tmp_source.zig:5:33: error: struct 'Foo' has no field 'a'", + ); - cases.add("@fieldParentPtr - field pointer is not pointer", + cases.add( + "@fieldParentPtr - field pointer is not pointer", \\const Foo = extern struct { \\ a: i32, \\}; \\export fn foo(a: i32) &Foo { \\ return @fieldParentPtr(Foo, "a", a); \\} - , ".tmp_source.zig:5:38: error: expected pointer, found 'i32'"); + , + ".tmp_source.zig:5:38: error: expected pointer, found 'i32'", + ); - cases.add("@fieldParentPtr - comptime field ptr not based on struct", + cases.add( + "@fieldParentPtr - comptime field ptr not based on struct", \\const Foo = struct { \\ a: i32, \\ b: i32, @@ -2034,9 +2594,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const field_ptr = @intToPtr(&i32, 0x1234); \\ const another_foo_ptr = @fieldParentPtr(Foo, "b", field_ptr); \\} - , ".tmp_source.zig:9:55: error: pointer value not based on parent struct"); + , + ".tmp_source.zig:9:55: error: pointer value not based on parent struct", + ); - cases.add("@fieldParentPtr - comptime wrong field index", + cases.add( + "@fieldParentPtr - comptime wrong field index", \\const Foo = struct { \\ a: i32, \\ b: i32, @@ -2046,76 +2609,100 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\comptime { \\ const another_foo_ptr = @fieldParentPtr(Foo, "b", &foo.a); \\} - , ".tmp_source.zig:8:29: error: field 'b' has index 1 but pointer value is index 0 of struct 'Foo'"); + , + ".tmp_source.zig:8:29: error: field 'b' has index 1 but pointer value is index 0 of struct 'Foo'", + ); - cases.add("@offsetOf - non struct", + cases.add( + "@offsetOf - non struct", \\const Foo = i32; \\export fn foo() usize { - \\ return @offsetOf(Foo, "a"); + \\ return @offsetOf(Foo, "a",); \\} - , ".tmp_source.zig:3:22: error: expected struct type, found 'i32'"); + , + ".tmp_source.zig:3:22: error: expected struct type, found 'i32'", + ); - cases.add("@offsetOf - bad field name", + cases.add( + "@offsetOf - bad field name", \\const Foo = struct { \\ derp: i32, \\}; \\export fn foo() usize { - \\ return @offsetOf(Foo, "a"); + \\ return @offsetOf(Foo, "a",); \\} - , ".tmp_source.zig:5:27: error: struct 'Foo' has no field 'a'"); + , + ".tmp_source.zig:5:27: error: struct 'Foo' has no field 'a'", + ); - cases.addExe("missing main fn in executable", + cases.addExe( + "missing main fn in executable", \\ - , "error: no member named 'main' in '"); + , + "error: no member named 'main' in '", + ); - cases.addExe("private main fn", + cases.addExe( + "private main fn", \\fn main() void {} , "error: 'main' is private", - ".tmp_source.zig:1:1: note: declared here"); + ".tmp_source.zig:1:1: note: declared here", + ); - cases.add("setting a section on an extern variable", + cases.add( + "setting a section on an extern variable", \\extern var foo: i32 section(".text2"); \\export fn entry() i32 { \\ return foo; \\} , - ".tmp_source.zig:1:29: error: cannot set section of external variable 'foo'"); + ".tmp_source.zig:1:29: error: cannot set section of external variable 'foo'", + ); - cases.add("setting a section on a local variable", + cases.add( + "setting a section on a local variable", \\export fn entry() i32 { \\ var foo: i32 section(".text2") = 1234; \\ return foo; \\} , - ".tmp_source.zig:2:26: error: cannot set section of local variable 'foo'"); + ".tmp_source.zig:2:26: error: cannot set section of local variable 'foo'", + ); - cases.add("setting a section on an extern fn", + cases.add( + "setting a section on an extern fn", \\extern fn foo() section(".text2") void; \\export fn entry() void { \\ foo(); \\} , - ".tmp_source.zig:1:25: error: cannot set section of external function 'foo'"); + ".tmp_source.zig:1:25: error: cannot set section of external function 'foo'", + ); - cases.add("returning address of local variable - simple", + cases.add( + "returning address of local variable - simple", \\export fn foo() &i32 { \\ var a: i32 = undefined; \\ return &a; \\} , - ".tmp_source.zig:3:13: error: function returns address of local variable"); + ".tmp_source.zig:3:13: error: function returns address of local variable", + ); - cases.add("returning address of local variable - phi", + cases.add( + "returning address of local variable - phi", \\export fn foo(c: bool) &i32 { \\ var a: i32 = undefined; \\ var b: i32 = undefined; \\ return if (c) &a else &b; \\} , - ".tmp_source.zig:4:12: error: function returns address of local variable"); + ".tmp_source.zig:4:12: error: function returns address of local variable", + ); - cases.add("inner struct member shadowing outer struct member", + cases.add( + "inner struct member shadowing outer struct member", \\fn A() type { \\ return struct { \\ b: B(), @@ -2137,57 +2724,71 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:9:17: error: redefinition of 'Self'", - ".tmp_source.zig:5:9: note: previous definition is here"); + ".tmp_source.zig:5:9: note: previous definition is here", + ); - cases.add("while expected bool, got nullable", + cases.add( + "while expected bool, got nullable", \\export fn foo() void { \\ while (bar()) {} \\} \\fn bar() ?i32 { return 1; } , - ".tmp_source.zig:2:15: error: expected type 'bool', found '?i32'"); + ".tmp_source.zig:2:15: error: expected type 'bool', found '?i32'", + ); - cases.add("while expected bool, got error union", + cases.add( + "while expected bool, got error union", \\export fn foo() void { \\ while (bar()) {} \\} \\fn bar() error!i32 { return 1; } , - ".tmp_source.zig:2:15: error: expected type 'bool', found 'error!i32'"); + ".tmp_source.zig:2:15: error: expected type 'bool', found 'error!i32'", + ); - cases.add("while expected nullable, got bool", + cases.add( + "while expected nullable, got bool", \\export fn foo() void { \\ while (bar()) |x| {} \\} \\fn bar() bool { return true; } , - ".tmp_source.zig:2:15: error: expected nullable type, found 'bool'"); + ".tmp_source.zig:2:15: error: expected nullable type, found 'bool'", + ); - cases.add("while expected nullable, got error union", + cases.add( + "while expected nullable, got error union", \\export fn foo() void { \\ while (bar()) |x| {} \\} \\fn bar() error!i32 { return 1; } , - ".tmp_source.zig:2:15: error: expected nullable type, found 'error!i32'"); + ".tmp_source.zig:2:15: error: expected nullable type, found 'error!i32'", + ); - cases.add("while expected error union, got bool", + cases.add( + "while expected error union, got bool", \\export fn foo() void { \\ while (bar()) |x| {} else |err| {} \\} \\fn bar() bool { return true; } , - ".tmp_source.zig:2:15: error: expected error union type, found 'bool'"); + ".tmp_source.zig:2:15: error: expected error union type, found 'bool'", + ); - cases.add("while expected error union, got nullable", + cases.add( + "while expected error union, got nullable", \\export fn foo() void { \\ while (bar()) |x| {} else |err| {} \\} \\fn bar() ?i32 { return 1; } , - ".tmp_source.zig:2:15: error: expected error union type, found '?i32'"); + ".tmp_source.zig:2:15: error: expected error union type, found '?i32'", + ); - cases.add("inline fn calls itself indirectly", + cases.add( + "inline fn calls itself indirectly", \\export fn foo() void { \\ bar(); \\} @@ -2201,91 +2802,113 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\extern fn quux() void; , - ".tmp_source.zig:4:8: error: unable to inline function"); + ".tmp_source.zig:4:8: error: unable to inline function", + ); - cases.add("save reference to inline function", + cases.add( + "save reference to inline function", \\export fn foo() void { \\ quux(@ptrToInt(bar)); \\} \\inline fn bar() void { } \\extern fn quux(usize) void; , - ".tmp_source.zig:4:8: error: unable to inline function"); + ".tmp_source.zig:4:8: error: unable to inline function", + ); - cases.add("signed integer division", + cases.add( + "signed integer division", \\export fn foo(a: i32, b: i32) i32 { \\ return a / b; \\} , - ".tmp_source.zig:2:14: error: division with 'i32' and 'i32': signed integers must use @divTrunc, @divFloor, or @divExact"); + ".tmp_source.zig:2:14: error: division with 'i32' and 'i32': signed integers must use @divTrunc, @divFloor, or @divExact", + ); - cases.add("signed integer remainder division", + cases.add( + "signed integer remainder division", \\export fn foo(a: i32, b: i32) i32 { \\ return a % b; \\} , - ".tmp_source.zig:2:14: error: remainder division with 'i32' and 'i32': signed integers and floats must use @rem or @mod"); + ".tmp_source.zig:2:14: error: remainder division with 'i32' and 'i32': signed integers and floats must use @rem or @mod", + ); - cases.add("cast negative value to unsigned integer", + cases.add( + "cast negative value to unsigned integer", \\comptime { \\ const value: i32 = -1; \\ const unsigned = u32(value); \\} , - ".tmp_source.zig:3:25: error: attempt to cast negative value to unsigned integer"); + ".tmp_source.zig:3:25: error: attempt to cast negative value to unsigned integer", + ); - cases.add("compile-time division by zero", + cases.add( + "compile-time division by zero", \\comptime { \\ const a: i32 = 1; \\ const b: i32 = 0; \\ const c = a / b; \\} , - ".tmp_source.zig:4:17: error: division by zero"); + ".tmp_source.zig:4:17: error: division by zero", + ); - cases.add("compile-time remainder division by zero", + cases.add( + "compile-time remainder division by zero", \\comptime { \\ const a: i32 = 1; \\ const b: i32 = 0; \\ const c = a % b; \\} , - ".tmp_source.zig:4:17: error: division by zero"); + ".tmp_source.zig:4:17: error: division by zero", + ); - cases.add("compile-time integer cast truncates bits", + cases.add( + "compile-time integer cast truncates bits", \\comptime { \\ const spartan_count: u16 = 300; \\ const byte = u8(spartan_count); \\} , - ".tmp_source.zig:3:20: error: cast from 'u16' to 'u8' truncates bits"); + ".tmp_source.zig:3:20: error: cast from 'u16' to 'u8' truncates bits", + ); - cases.add("@setRuntimeSafety twice for same scope", + cases.add( + "@setRuntimeSafety twice for same scope", \\export fn foo() void { \\ @setRuntimeSafety(false); \\ @setRuntimeSafety(false); \\} , ".tmp_source.zig:3:5: error: runtime safety set twice for same scope", - ".tmp_source.zig:2:5: note: first set here"); + ".tmp_source.zig:2:5: note: first set here", + ); - cases.add("@setFloatMode twice for same scope", + cases.add( + "@setFloatMode twice for same scope", \\export fn foo() void { \\ @setFloatMode(this, @import("builtin").FloatMode.Optimized); \\ @setFloatMode(this, @import("builtin").FloatMode.Optimized); \\} , ".tmp_source.zig:3:5: error: float mode set twice for same scope", - ".tmp_source.zig:2:5: note: first set here"); + ".tmp_source.zig:2:5: note: first set here", + ); - cases.add("array access of type", + cases.add( + "array access of type", \\export fn foo() void { \\ var b: u8[40] = undefined; \\} , - ".tmp_source.zig:2:14: error: array access of non-array type 'type'"); + ".tmp_source.zig:2:14: error: array access of non-array type 'type'", + ); - cases.add("cannot break out of defer expression", + cases.add( + "cannot break out of defer expression", \\export fn foo() void { \\ while (true) { \\ defer { @@ -2294,9 +2917,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:4:13: error: cannot break out of defer expression"); + ".tmp_source.zig:4:13: error: cannot break out of defer expression", + ); - cases.add("cannot continue out of defer expression", + cases.add( + "cannot continue out of defer expression", \\export fn foo() void { \\ while (true) { \\ defer { @@ -2305,9 +2930,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:4:13: error: cannot continue out of defer expression"); + ".tmp_source.zig:4:13: error: cannot continue out of defer expression", + ); - cases.add("calling a var args function only known at runtime", + cases.add( + "calling a var args function only known at runtime", \\var foos = []fn(...) void { foo1, foo2 }; \\ \\fn foo1(args: ...) void {} @@ -2317,9 +2944,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ foos[0](); \\} , - ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value"); + ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value", + ); - cases.add("calling a generic function only known at runtime", + cases.add( + "calling a generic function only known at runtime", \\var foos = []fn(var) void { foo1, foo2 }; \\ \\fn foo1(arg: var) void {} @@ -2329,10 +2958,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ foos[0](true); \\} , - ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value"); + ".tmp_source.zig:7:9: error: calling a generic function requires compile-time known function value", + ); - cases.add("@compileError shows traceback of references that caused it", - \\const foo = @compileError("aoeu"); + cases.add( + "@compileError shows traceback of references that caused it", + \\const foo = @compileError("aoeu",); \\ \\const bar = baz + foo; \\const baz = 1; @@ -2343,9 +2974,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { , ".tmp_source.zig:1:13: error: aoeu", ".tmp_source.zig:3:19: note: referenced here", - ".tmp_source.zig:7:12: note: referenced here"); + ".tmp_source.zig:7:12: note: referenced here", + ); - cases.add("instantiating an undefined value for an invalid struct that contains itself", + cases.add( + "instantiating an undefined value for an invalid struct that contains itself", \\const Foo = struct { \\ x: Foo, \\}; @@ -2356,73 +2989,93 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ return @sizeOf(@typeOf(foo.x)); \\} , - ".tmp_source.zig:1:13: error: struct 'Foo' contains itself"); + ".tmp_source.zig:1:13: error: struct 'Foo' contains itself", + ); - cases.add("float literal too large error", + cases.add( + "float literal too large error", \\comptime { \\ const a = 0x1.0p16384; \\} , - ".tmp_source.zig:2:15: error: float literal out of range of any type"); + ".tmp_source.zig:2:15: error: float literal out of range of any type", + ); - cases.add("float literal too small error (denormal)", + cases.add( + "float literal too small error (denormal)", \\comptime { \\ const a = 0x1.0p-16384; \\} , - ".tmp_source.zig:2:15: error: float literal out of range of any type"); + ".tmp_source.zig:2:15: error: float literal out of range of any type", + ); - cases.add("explicit cast float literal to integer when there is a fraction component", + cases.add( + "explicit cast float literal to integer when there is a fraction component", \\export fn entry() i32 { \\ return i32(12.34); \\} , - ".tmp_source.zig:2:16: error: fractional component prevents float value 12.340000 from being casted to type 'i32'"); + ".tmp_source.zig:2:16: error: fractional component prevents float value 12.340000 from being casted to type 'i32'", + ); - cases.add("non pointer given to @ptrToInt", + cases.add( + "non pointer given to @ptrToInt", \\export fn entry(x: i32) usize { \\ return @ptrToInt(x); \\} , - ".tmp_source.zig:2:22: error: expected pointer, found 'i32'"); + ".tmp_source.zig:2:22: error: expected pointer, found 'i32'", + ); - cases.add("@shlExact shifts out 1 bits", + cases.add( + "@shlExact shifts out 1 bits", \\comptime { \\ const x = @shlExact(u8(0b01010101), 2); \\} , - ".tmp_source.zig:2:15: error: operation caused overflow"); + ".tmp_source.zig:2:15: error: operation caused overflow", + ); - cases.add("@shrExact shifts out 1 bits", + cases.add( + "@shrExact shifts out 1 bits", \\comptime { \\ const x = @shrExact(u8(0b10101010), 2); \\} , - ".tmp_source.zig:2:15: error: exact shift shifted out 1 bits"); + ".tmp_source.zig:2:15: error: exact shift shifted out 1 bits", + ); - cases.add("shifting without int type or comptime known", + cases.add( + "shifting without int type or comptime known", \\export fn entry(x: u8) u8 { \\ return 0x11 << x; \\} , - ".tmp_source.zig:2:17: error: LHS of shift must be an integer type, or RHS must be compile-time known"); + ".tmp_source.zig:2:17: error: LHS of shift must be an integer type, or RHS must be compile-time known", + ); - cases.add("shifting RHS is log2 of LHS int bit width", + cases.add( + "shifting RHS is log2 of LHS int bit width", \\export fn entry(x: u8, y: u8) u8 { \\ return x << y; \\} , - ".tmp_source.zig:2:17: error: expected type 'u3', found 'u8'"); + ".tmp_source.zig:2:17: error: expected type 'u3', found 'u8'", + ); - cases.add("globally shadowing a primitive type", + cases.add( + "globally shadowing a primitive type", \\const u16 = @intType(false, 8); \\export fn entry() void { \\ const a: u16 = 300; \\} , - ".tmp_source.zig:1:1: error: declaration shadows type 'u16'"); + ".tmp_source.zig:1:1: error: declaration shadows type 'u16'", + ); - cases.add("implicitly increasing pointer alignment", + cases.add( + "implicitly increasing pointer alignment", \\const Foo = packed struct { \\ a: u8, \\ b: u32, @@ -2437,9 +3090,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ x.* += 1; \\} , - ".tmp_source.zig:8:13: error: expected type '&u32', found '&align(1) u32'"); + ".tmp_source.zig:8:13: error: expected type '&u32', found '&align(1) u32'", + ); - cases.add("implicitly increasing slice alignment", + cases.add( + "implicitly increasing slice alignment", \\const Foo = packed struct { \\ a: u8, \\ b: u32, @@ -2455,9 +3110,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ x[0] += 1; \\} , - ".tmp_source.zig:9:17: error: expected type '[]u32', found '[]align(1) u32'"); + ".tmp_source.zig:9:17: error: expected type '[]u32', found '[]align(1) u32'", + ); - cases.add("increase pointer alignment in @ptrCast", + cases.add( + "increase pointer alignment in @ptrCast", \\export fn entry() u32 { \\ var bytes: [4]u8 = []u8{0x01, 0x02, 0x03, 0x04}; \\ const ptr = @ptrCast(&u32, &bytes[0]); @@ -2466,9 +3123,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { , ".tmp_source.zig:3:17: error: cast increases pointer alignment", ".tmp_source.zig:3:38: note: '&u8' has alignment 1", - ".tmp_source.zig:3:27: note: '&u32' has alignment 4"); + ".tmp_source.zig:3:27: note: '&u32' has alignment 4", + ); - cases.add("increase pointer alignment in slice resize", + cases.add( + "increase pointer alignment in slice resize", \\export fn entry() u32 { \\ var bytes = []u8{0x01, 0x02, 0x03, 0x04}; \\ return ([]u32)(bytes[0..])[0]; @@ -2476,16 +3135,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { , ".tmp_source.zig:3:19: error: cast increases pointer alignment", ".tmp_source.zig:3:19: note: '[]u8' has alignment 1", - ".tmp_source.zig:3:19: note: '[]u32' has alignment 4"); + ".tmp_source.zig:3:19: note: '[]u32' has alignment 4", + ); - cases.add("@alignCast expects pointer or slice", + cases.add( + "@alignCast expects pointer or slice", \\export fn entry() void { \\ @alignCast(4, u32(3)); \\} , - ".tmp_source.zig:2:22: error: expected pointer or slice, found 'u32'"); + ".tmp_source.zig:2:22: error: expected pointer or slice, found 'u32'", + ); - cases.add("passing an under-aligned function pointer", + cases.add( + "passing an under-aligned function pointer", \\export fn entry() void { \\ testImplicitlyDecreaseFnAlign(alignedSmall, 1234); \\} @@ -2494,9 +3157,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\fn alignedSmall() align(4) i32 { return 1234; } , - ".tmp_source.zig:2:35: error: expected type 'fn() align(8) i32', found 'fn() align(4) i32'"); + ".tmp_source.zig:2:35: error: expected type 'fn() align(8) i32', found 'fn() align(4) i32'", + ); - cases.add("passing a not-aligned-enough pointer to cmpxchg", + cases.add( + "passing a not-aligned-enough pointer to cmpxchg", \\const AtomicOrder = @import("builtin").AtomicOrder; \\export fn entry() bool { \\ var x: i32 align(1) = 1234; @@ -2504,16 +3169,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ return x == 5678; \\} , - ".tmp_source.zig:4:32: error: expected type '&i32', found '&align(1) i32'"); + ".tmp_source.zig:4:32: error: expected type '&i32', found '&align(1) i32'", + ); - cases.add("wrong size to an array literal", + cases.add( + "wrong size to an array literal", \\comptime { \\ const array = [2]u8{1, 2, 3}; \\} , - ".tmp_source.zig:2:24: error: expected [2]u8 literal, found [3]u8 literal"); + ".tmp_source.zig:2:24: error: expected [2]u8 literal, found [3]u8 literal", + ); - cases.add("@setEvalBranchQuota in non-root comptime execution context", + cases.add( + "@setEvalBranchQuota in non-root comptime execution context", \\comptime { \\ foo(); \\} @@ -2523,9 +3192,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { , ".tmp_source.zig:5:5: error: @setEvalBranchQuota must be called from the top of the comptime stack", ".tmp_source.zig:2:8: note: called from here", - ".tmp_source.zig:1:10: note: called from here"); + ".tmp_source.zig:1:10: note: called from here", + ); - cases.add("wrong pointer implicitly casted to pointer to @OpaqueType()", + cases.add( + "wrong pointer implicitly casted to pointer to @OpaqueType()", \\const Derp = @OpaqueType(); \\extern fn bar(d: &Derp) void; \\export fn foo() void { @@ -2533,9 +3204,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ bar(@ptrCast(&c_void, &x)); \\} , - ".tmp_source.zig:5:9: error: expected type '&Derp', found '&c_void'"); + ".tmp_source.zig:5:9: error: expected type '&Derp', found '&c_void'", + ); - cases.add("non-const variables of things that require const variables", + cases.add( + "non-const variables of things that require const variables", \\const Opaque = @OpaqueType(); \\ \\export fn entry(opaque: &Opaque) void { @@ -2549,7 +3222,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var e = null; \\ var f = opaque.*; \\ var g = i32; - \\ var h = @import("std"); + \\ var h = @import("std",); \\ var i = (Foo {}).bar; \\ \\ var z: noreturn = return; @@ -2569,26 +3242,32 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { ".tmp_source.zig:13:4: error: variable of type 'type' must be const or comptime", ".tmp_source.zig:14:4: error: variable of type '(namespace)' must be const or comptime", ".tmp_source.zig:15:4: error: variable of type '(bound fn(&const Foo) void)' must be const or comptime", - ".tmp_source.zig:17:4: error: unreachable code"); + ".tmp_source.zig:17:4: error: unreachable code", + ); - cases.add("wrong types given to atomic order args in cmpxchg", + cases.add( + "wrong types given to atomic order args in cmpxchg", \\export fn entry() void { \\ var x: i32 = 1234; \\ while (!@cmpxchgWeak(i32, &x, 1234, 5678, u32(1234), u32(1234))) {} \\} , - ".tmp_source.zig:3:50: error: expected type 'AtomicOrder', found 'u32'"); + ".tmp_source.zig:3:50: error: expected type 'AtomicOrder', found 'u32'", + ); - cases.add("wrong types given to @export", + cases.add( + "wrong types given to @export", \\extern fn entry() void { } \\comptime { \\ @export("entry", entry, u32(1234)); \\} , - ".tmp_source.zig:3:32: error: expected type 'GlobalLinkage', found 'u32'"); + ".tmp_source.zig:3:32: error: expected type 'GlobalLinkage', found 'u32'", + ); - cases.add("struct with invalid field", - \\const std = @import("std"); + cases.add( + "struct with invalid field", + \\const std = @import("std",); \\const Allocator = std.mem.Allocator; \\const ArrayList = std.ArrayList; \\ @@ -2612,23 +3291,29 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ }; \\} , - ".tmp_source.zig:14:17: error: use of undeclared identifier 'HeaderValue'"); + ".tmp_source.zig:14:17: error: use of undeclared identifier 'HeaderValue'", + ); - cases.add("@setAlignStack outside function", + cases.add( + "@setAlignStack outside function", \\comptime { \\ @setAlignStack(16); \\} , - ".tmp_source.zig:2:5: error: @setAlignStack outside function"); + ".tmp_source.zig:2:5: error: @setAlignStack outside function", + ); - cases.add("@setAlignStack in naked function", + cases.add( + "@setAlignStack in naked function", \\export nakedcc fn entry() void { \\ @setAlignStack(16); \\} , - ".tmp_source.zig:2:5: error: @setAlignStack in naked function"); + ".tmp_source.zig:2:5: error: @setAlignStack in naked function", + ); - cases.add("@setAlignStack in inline function", + cases.add( + "@setAlignStack in inline function", \\export fn entry() void { \\ foo(); \\} @@ -2636,25 +3321,31 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ @setAlignStack(16); \\} , - ".tmp_source.zig:5:5: error: @setAlignStack in inline function"); + ".tmp_source.zig:5:5: error: @setAlignStack in inline function", + ); - cases.add("@setAlignStack set twice", + cases.add( + "@setAlignStack set twice", \\export fn entry() void { \\ @setAlignStack(16); \\ @setAlignStack(16); \\} , ".tmp_source.zig:3:5: error: alignstack set twice", - ".tmp_source.zig:2:5: note: first set here"); + ".tmp_source.zig:2:5: note: first set here", + ); - cases.add("@setAlignStack too big", + cases.add( + "@setAlignStack too big", \\export fn entry() void { \\ @setAlignStack(511 + 1); \\} , - ".tmp_source.zig:2:5: error: attempt to @setAlignStack(512); maximum is 256"); + ".tmp_source.zig:2:5: error: attempt to @setAlignStack(512); maximum is 256", + ); - cases.add("storing runtime value in compile time variable then using it", + cases.add( + "storing runtime value in compile time variable then using it", \\const Mode = @import("builtin").Mode; \\ \\fn Free(comptime filename: []const u8) TestCase { @@ -2697,9 +3388,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ } \\} , - ".tmp_source.zig:37:16: error: cannot store runtime value in compile time variable"); + ".tmp_source.zig:37:16: error: cannot store runtime value in compile time variable", + ); - cases.add("field access of opaque type", + cases.add( + "field access of opaque type", \\const MyType = @OpaqueType(); \\ \\export fn entry() bool { @@ -2711,120 +3404,148 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ return x.blah; \\} , - ".tmp_source.zig:9:13: error: type '&MyType' does not support field access"); + ".tmp_source.zig:9:13: error: type '&MyType' does not support field access", + ); - cases.add("carriage return special case", + cases.add( + "carriage return special case", "fn test() bool {\r\n" ++ - " true\r\n" ++ - "}\r\n" - , - ".tmp_source.zig:1:17: error: invalid carriage return, only '\\n' line endings are supported"); - - cases.add("non-printable invalid character", - "\xff\xfe" ++ - \\fn test() bool {\r - \\ true\r - \\} - , - ".tmp_source.zig:1:1: error: invalid character: '\\xff'"); + " true\r\n" ++ + "}\r\n", + ".tmp_source.zig:1:17: error: invalid carriage return, only '\\n' line endings are supported", + ); + + cases.add( + "non-printable invalid character", + "\xff\xfe" ++ + \\fn test() bool {\r + \\ true\r + \\} + , + ".tmp_source.zig:1:1: error: invalid character: '\\xff'", + ); - cases.add("non-printable invalid character with escape alternative", + cases.add( + "non-printable invalid character with escape alternative", "fn test() bool {\n" ++ - "\ttrue\n" ++ - "}\n" - , - ".tmp_source.zig:2:1: error: invalid character: '\\t'"); + "\ttrue\n" ++ + "}\n", + ".tmp_source.zig:2:1: error: invalid character: '\\t'", + ); - cases.add("@ArgType given non function parameter", + cases.add( + "@ArgType given non function parameter", \\comptime { \\ _ = @ArgType(i32, 3); \\} , - ".tmp_source.zig:2:18: error: expected function, found 'i32'"); + ".tmp_source.zig:2:18: error: expected function, found 'i32'", + ); - cases.add("@ArgType arg index out of bounds", + cases.add( + "@ArgType arg index out of bounds", \\comptime { \\ _ = @ArgType(@typeOf(add), 2); \\} \\fn add(a: i32, b: i32) i32 { return a + b; } , - ".tmp_source.zig:2:32: error: arg index 2 out of bounds; 'fn(i32, i32) i32' has 2 arguments"); + ".tmp_source.zig:2:32: error: arg index 2 out of bounds; 'fn(i32, i32) i32' has 2 arguments", + ); - cases.add("@memberType on unsupported type", + cases.add( + "@memberType on unsupported type", \\comptime { \\ _ = @memberType(i32, 0); \\} , - ".tmp_source.zig:2:21: error: type 'i32' does not support @memberType"); + ".tmp_source.zig:2:21: error: type 'i32' does not support @memberType", + ); - cases.add("@memberType on enum", + cases.add( + "@memberType on enum", \\comptime { \\ _ = @memberType(Foo, 0); \\} \\const Foo = enum {A,}; , - ".tmp_source.zig:2:21: error: type 'Foo' does not support @memberType"); + ".tmp_source.zig:2:21: error: type 'Foo' does not support @memberType", + ); - cases.add("@memberType struct out of bounds", + cases.add( + "@memberType struct out of bounds", \\comptime { \\ _ = @memberType(Foo, 0); \\} \\const Foo = struct {}; , - ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members"); + ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members", + ); - cases.add("@memberType union out of bounds", + cases.add( + "@memberType union out of bounds", \\comptime { \\ _ = @memberType(Foo, 1); \\} \\const Foo = union {A: void,}; , - ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members"); + ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members", + ); - cases.add("@memberName on unsupported type", + cases.add( + "@memberName on unsupported type", \\comptime { \\ _ = @memberName(i32, 0); \\} , - ".tmp_source.zig:2:21: error: type 'i32' does not support @memberName"); + ".tmp_source.zig:2:21: error: type 'i32' does not support @memberName", + ); - cases.add("@memberName struct out of bounds", + cases.add( + "@memberName struct out of bounds", \\comptime { \\ _ = @memberName(Foo, 0); \\} \\const Foo = struct {}; , - ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members"); + ".tmp_source.zig:2:26: error: member index 0 out of bounds; 'Foo' has 0 members", + ); - cases.add("@memberName enum out of bounds", + cases.add( + "@memberName enum out of bounds", \\comptime { \\ _ = @memberName(Foo, 1); \\} \\const Foo = enum {A,}; , - ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members"); + ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members", + ); - cases.add("@memberName union out of bounds", + cases.add( + "@memberName union out of bounds", \\comptime { \\ _ = @memberName(Foo, 1); \\} \\const Foo = union {A:i32,}; , - ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members"); + ".tmp_source.zig:2:26: error: member index 1 out of bounds; 'Foo' has 1 members", + ); - cases.add("calling var args extern function, passing array instead of pointer", + cases.add( + "calling var args extern function, passing array instead of pointer", \\export fn entry() void { - \\ foo("hello"); + \\ foo("hello",); \\} \\pub extern fn foo(format: &const u8, ...) void; , - ".tmp_source.zig:2:9: error: expected type '&const u8', found '[5]u8'"); + ".tmp_source.zig:2:9: error: expected type '&const u8', found '[5]u8'", + ); - cases.add("constant inside comptime function has compile error", + cases.add( + "constant inside comptime function has compile error", \\const ContextAllocator = MemoryPool(usize); \\ \\pub fn MemoryPool(comptime T: type) type { - \\ const free_list_t = @compileError("aoeu"); + \\ const free_list_t = @compileError("aoeu",); \\ \\ return struct { \\ free_list: free_list_t, @@ -2837,9 +3558,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { , ".tmp_source.zig:4:25: error: aoeu", ".tmp_source.zig:1:36: note: called from here", - ".tmp_source.zig:12:20: note: referenced here"); + ".tmp_source.zig:12:20: note: referenced here", + ); - cases.add("specify enum tag type that is too small", + cases.add( + "specify enum tag type that is too small", \\const Small = enum (u2) { \\ One, \\ Two, @@ -2852,9 +3575,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x = Small.One; \\} , - ".tmp_source.zig:1:20: error: 'u2' too small to hold all bits; must be at least 'u3'"); + ".tmp_source.zig:1:20: error: 'u2' too small to hold all bits; must be at least 'u3'", + ); - cases.add("specify non-integer enum tag type", + cases.add( + "specify non-integer enum tag type", \\const Small = enum (f32) { \\ One, \\ Two, @@ -2865,9 +3590,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x = Small.One; \\} , - ".tmp_source.zig:1:20: error: expected integer, found 'f32'"); + ".tmp_source.zig:1:20: error: expected integer, found 'f32'", + ); - cases.add("implicitly casting enum to tag type", + cases.add( + "implicitly casting enum to tag type", \\const Small = enum(u2) { \\ One, \\ Two, @@ -2879,9 +3606,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x: u2 = Small.Two; \\} , - ".tmp_source.zig:9:22: error: expected type 'u2', found 'Small'"); + ".tmp_source.zig:9:22: error: expected type 'u2', found 'Small'", + ); - cases.add("explicitly casting enum to non tag type", + cases.add( + "explicitly casting enum to non tag type", \\const Small = enum(u2) { \\ One, \\ Two, @@ -2893,9 +3622,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x = u3(Small.Two); \\} , - ".tmp_source.zig:9:15: error: enum to integer cast to 'u3' instead of its tag type, 'u2'"); + ".tmp_source.zig:9:15: error: enum to integer cast to 'u3' instead of its tag type, 'u2'", + ); - cases.add("explicitly casting non tag type to enum", + cases.add( + "explicitly casting non tag type to enum", \\const Small = enum(u2) { \\ One, \\ Two, @@ -2908,9 +3639,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x = Small(y); \\} , - ".tmp_source.zig:10:18: error: integer to enum cast from 'u3' instead of its tag type, 'u2'"); + ".tmp_source.zig:10:18: error: integer to enum cast from 'u3' instead of its tag type, 'u2'", + ); - cases.add("non unsigned integer enum tag type", + cases.add( + "non unsigned integer enum tag type", \\const Small = enum(i2) { \\ One, \\ Two, @@ -2922,9 +3655,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var y = Small.Two; \\} , - ".tmp_source.zig:1:19: error: expected unsigned integer, found 'i2'"); + ".tmp_source.zig:1:19: error: expected unsigned integer, found 'i2'", + ); - cases.add("struct fields with value assignments", + cases.add( + "struct fields with value assignments", \\const MultipleChoice = struct { \\ A: i32 = 20, \\}; @@ -2932,9 +3667,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var x: MultipleChoice = undefined; \\} , - ".tmp_source.zig:2:14: error: enums, not structs, support field assignment"); + ".tmp_source.zig:2:14: error: enums, not structs, support field assignment", + ); - cases.add("union fields with value assignments", + cases.add( + "union fields with value assignments", \\const MultipleChoice = union { \\ A: i32 = 20, \\}; @@ -2943,25 +3680,31 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:2:14: error: non-enum union field assignment", - ".tmp_source.zig:1:24: note: consider 'union(enum)' here"); + ".tmp_source.zig:1:24: note: consider 'union(enum)' here", + ); - cases.add("enum with 0 fields", + cases.add( + "enum with 0 fields", \\const Foo = enum {}; \\export fn entry() usize { \\ return @sizeOf(Foo); \\} , - ".tmp_source.zig:1:13: error: enums must have 1 or more fields"); + ".tmp_source.zig:1:13: error: enums must have 1 or more fields", + ); - cases.add("union with 0 fields", + cases.add( + "union with 0 fields", \\const Foo = union {}; \\export fn entry() usize { \\ return @sizeOf(Foo); \\} , - ".tmp_source.zig:1:13: error: unions must have 1 or more fields"); + ".tmp_source.zig:1:13: error: unions must have 1 or more fields", + ); - cases.add("enum value already taken", + cases.add( + "enum value already taken", \\const MultipleChoice = enum(u32) { \\ A = 20, \\ B = 40, @@ -2974,9 +3717,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:6:9: error: enum tag value 60 already taken", - ".tmp_source.zig:4:9: note: other occurrence here"); + ".tmp_source.zig:4:9: note: other occurrence here", + ); - cases.add("union with specified enum omits field", + cases.add( + "union with specified enum omits field", \\const Letter = enum { \\ A, \\ B, @@ -2991,9 +3736,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:6:17: error: enum field missing: 'C'", - ".tmp_source.zig:4:5: note: declared here"); + ".tmp_source.zig:4:5: note: declared here", + ); - cases.add("@TagType when union has no attached enum", + cases.add( + "@TagType when union has no attached enum", \\const Foo = union { \\ A: i32, \\}; @@ -3002,9 +3749,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:5:24: error: union 'Foo' has no tag", - ".tmp_source.zig:1:13: note: consider 'union(enum)' here"); + ".tmp_source.zig:1:13: note: consider 'union(enum)' here", + ); - cases.add("non-integer tag type to automatic union enum", + cases.add( + "non-integer tag type to automatic union enum", \\const Foo = union(enum(f32)) { \\ A: i32, \\}; @@ -3012,9 +3761,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const x = @TagType(Foo); \\} , - ".tmp_source.zig:1:23: error: expected integer tag type, found 'f32'"); + ".tmp_source.zig:1:23: error: expected integer tag type, found 'f32'", + ); - cases.add("non-enum tag type passed to union", + cases.add( + "non-enum tag type passed to union", \\const Foo = union(u32) { \\ A: i32, \\}; @@ -3022,9 +3773,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const x = @TagType(Foo); \\} , - ".tmp_source.zig:1:18: error: expected enum tag type, found 'u32'"); + ".tmp_source.zig:1:18: error: expected enum tag type, found 'u32'", + ); - cases.add("union auto-enum value already taken", + cases.add( + "union auto-enum value already taken", \\const MultipleChoice = union(enum(u32)) { \\ A = 20, \\ B = 40, @@ -3037,9 +3790,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:6:9: error: enum tag value 60 already taken", - ".tmp_source.zig:4:9: note: other occurrence here"); + ".tmp_source.zig:4:9: note: other occurrence here", + ); - cases.add("union enum field does not match enum", + cases.add( + "union enum field does not match enum", \\const Letter = enum { \\ A, \\ B, @@ -3056,9 +3811,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:10:5: error: enum field not found: 'D'", - ".tmp_source.zig:1:16: note: enum declared here"); + ".tmp_source.zig:1:16: note: enum declared here", + ); - cases.add("field type supplied in an enum", + cases.add( + "field type supplied in an enum", \\const Letter = enum { \\ A: void, \\ B, @@ -3069,9 +3826,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:2:8: error: structs and unions, not enums, support field types", - ".tmp_source.zig:1:16: note: consider 'union(enum)' here"); + ".tmp_source.zig:1:16: note: consider 'union(enum)' here", + ); - cases.add("struct field missing type", + cases.add( + "struct field missing type", \\const Letter = struct { \\ A, \\}; @@ -3079,9 +3838,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var a = Letter { .A = {} }; \\} , - ".tmp_source.zig:2:5: error: struct field missing type"); + ".tmp_source.zig:2:5: error: struct field missing type", + ); - cases.add("extern union field missing type", + cases.add( + "extern union field missing type", \\const Letter = extern union { \\ A, \\}; @@ -3089,9 +3850,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var a = Letter { .A = {} }; \\} , - ".tmp_source.zig:2:5: error: union field missing type"); + ".tmp_source.zig:2:5: error: union field missing type", + ); - cases.add("extern union given enum tag type", + cases.add( + "extern union given enum tag type", \\const Letter = enum { \\ A, \\ B, @@ -3106,9 +3869,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var a = Payload { .A = 1234 }; \\} , - ".tmp_source.zig:6:29: error: extern union does not support enum tag type"); + ".tmp_source.zig:6:29: error: extern union does not support enum tag type", + ); - cases.add("packed union given enum tag type", + cases.add( + "packed union given enum tag type", \\const Letter = enum { \\ A, \\ B, @@ -3123,9 +3888,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var a = Payload { .A = 1234 }; \\} , - ".tmp_source.zig:6:29: error: packed union does not support enum tag type"); + ".tmp_source.zig:6:29: error: packed union does not support enum tag type", + ); - cases.add("switch on union with no attached enum", + cases.add( + "switch on union with no attached enum", \\const Payload = union { \\ A: i32, \\ B: f64, @@ -3143,9 +3910,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:11:14: error: switch on union which has no attached enum", - ".tmp_source.zig:1:17: note: consider 'union(enum)' here"); + ".tmp_source.zig:1:17: note: consider 'union(enum)' here", + ); - cases.add("enum in field count range but not matching tag", + cases.add( + "enum in field count range but not matching tag", \\const Foo = enum(u32) { \\ A = 10, \\ B = 11, @@ -3155,9 +3924,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:6:16: error: enum 'Foo' has no tag matching integer value 0", - ".tmp_source.zig:1:13: note: 'Foo' declared here"); + ".tmp_source.zig:1:13: note: 'Foo' declared here", + ); - cases.add("comptime cast enum to union but field has payload", + cases.add( + "comptime cast enum to union but field has payload", \\const Letter = enum { A, B, C }; \\const Value = union(Letter) { \\ A: i32, @@ -3169,9 +3940,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:8:26: error: cast to union 'Value' must initialize 'i32' field 'A'", - ".tmp_source.zig:3:5: note: field 'A' declared here"); + ".tmp_source.zig:3:5: note: field 'A' declared here", + ); - cases.add("runtime cast to union which has non-void fields", + cases.add( + "runtime cast to union which has non-void fields", \\const Letter = enum { A, B, C }; \\const Value = union(Letter) { \\ A: i32, @@ -3186,9 +3959,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} , ".tmp_source.zig:11:20: error: runtime cast to union 'Value' which has non-void fields", - ".tmp_source.zig:3:5: note: field 'A' has type 'i32'"); + ".tmp_source.zig:3:5: note: field 'A' has type 'i32'", + ); - cases.add("self-referencing function pointer field", + cases.add( + "self-referencing function pointer field", \\const S = struct { \\ f: fn(_: S) void, \\}; @@ -3198,19 +3973,23 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ var _ = S { .f = f }; \\} , - ".tmp_source.zig:4:9: error: type 'S' is not copyable; cannot pass by value"); + ".tmp_source.zig:4:9: error: type 'S' is not copyable; cannot pass by value", + ); - cases.add("taking offset of void field in struct", + cases.add( + "taking offset of void field in struct", \\const Empty = struct { \\ val: void, \\}; \\export fn foo() void { - \\ const fieldOffset = @offsetOf(Empty, "val"); + \\ const fieldOffset = @offsetOf(Empty, "val",); \\} , - ".tmp_source.zig:5:42: error: zero-bit field 'val' in struct 'Empty' has no offset"); + ".tmp_source.zig:5:42: error: zero-bit field 'val' in struct 'Empty' has no offset", + ); - cases.add("invalid union field access in comptime", + cases.add( + "invalid union field access in comptime", \\const Foo = union { \\ Bar: u8, \\ Baz: void, @@ -3220,21 +3999,26 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const bar_val = foo.Bar; \\} , - ".tmp_source.zig:7:24: error: accessing union field 'Bar' while field 'Baz' is set"); + ".tmp_source.zig:7:24: error: accessing union field 'Bar' while field 'Baz' is set", + ); - cases.add("getting return type of generic function", + cases.add( + "getting return type of generic function", \\fn generic(a: var) void {} \\comptime { \\ _ = @typeOf(generic).ReturnType; \\} , - ".tmp_source.zig:3:25: error: ReturnType has not been resolved because 'fn(var)var' is generic"); + ".tmp_source.zig:3:25: error: ReturnType has not been resolved because 'fn(var)var' is generic", + ); - cases.add("getting @ArgType of generic function", + cases.add( + "getting @ArgType of generic function", \\fn generic(a: var) void {} \\comptime { \\ _ = @ArgType(@typeOf(generic), 0); \\} , - ".tmp_source.zig:3:36: error: @ArgType could not resolve the type of arg 0 because 'fn(var)var' is generic"); + ".tmp_source.zig:3:36: error: @ArgType could not resolve the type of arg 0 because 'fn(var)var' is generic", + ); } diff --git a/test/gen_h.zig b/test/gen_h.zig index 30d168cf2c..2def39bed7 100644 --- a/test/gen_h.zig +++ b/test/gen_h.zig @@ -76,5 +76,4 @@ pub fn addCases(cases: &tests.GenHContext) void { \\TEST_EXPORT void entry(struct Foo foo, uint8_t bar[]); \\ ); - } diff --git a/test/standalone/brace_expansion/main.zig b/test/standalone/brace_expansion/main.zig index 93089ae1ff..c96cc2cbb9 100644 --- a/test/standalone/brace_expansion/main.zig +++ b/test/standalone/brace_expansion/main.zig @@ -29,8 +29,7 @@ fn tokenize(input: []const u8) !ArrayList(Token) { for (input) |b, i| { switch (state) { State.Start => switch (b) { - 'a' ... 'z', - 'A' ... 'Z' => { + 'a'...'z', 'A'...'Z' => { state = State.Word; tok_begin = i; }, @@ -40,11 +39,8 @@ fn tokenize(input: []const u8) !ArrayList(Token) { else => return error.InvalidInput, }, State.Word => switch (b) { - 'a' ... 'z', - 'A' ... 'Z' => {}, - '{', - '}', - ',' => { + 'a'...'z', 'A'...'Z' => {}, + '{', '}', ',' => { try token_list.append(Token{ .Word = input[tok_begin..i] }); switch (b) { '{' => try token_list.append(Token.OpenBrace), @@ -103,8 +99,7 @@ fn parse(tokens: &const ArrayList(Token), token_index: &usize) ParseError!Node { }; switch (tokens.items[token_index.*]) { - Token.Word, - Token.OpenBrace => { + Token.Word, Token.OpenBrace => { const pair = try global_allocator.alloc(Node, 2); pair[0] = result_node; pair[1] = try parse(tokens, token_index); diff --git a/test/standalone/issue_339/test.zig b/test/standalone/issue_339/test.zig index f65b9f734e..da0747b8e6 100644 --- a/test/standalone/issue_339/test.zig +++ b/test/standalone/issue_339/test.zig @@ -1,5 +1,8 @@ const StackTrace = @import("builtin").StackTrace; -pub fn panic(msg: []const u8, stack_trace: ?&StackTrace) noreturn { @breakpoint(); while (true) {} } +pub fn panic(msg: []const u8, stack_trace: ?&StackTrace) noreturn { + @breakpoint(); + while (true) {} +} fn bar() error!void {} diff --git a/test/standalone/pkg_import/pkg.zig b/test/standalone/pkg_import/pkg.zig index abb977a2ef..19ab525b81 100644 --- a/test/standalone/pkg_import/pkg.zig +++ b/test/standalone/pkg_import/pkg.zig @@ -1 +1,3 @@ -pub fn add(a: i32, b: i32) i32 { return a + b; } +pub fn add(a: i32, b: i32) i32 { + return a + b; +} diff --git a/test/standalone/use_alias/main.zig b/test/standalone/use_alias/main.zig index 40cab9ad8a..873393cef7 100644 --- a/test/standalone/use_alias/main.zig +++ b/test/standalone/use_alias/main.zig @@ -2,7 +2,7 @@ const c = @import("c.zig"); const assert = @import("std").debug.assert; test "symbol exists" { - var foo = c.Foo { + var foo = c.Foo{ .a = 1, .b = 1, }; diff --git a/test/translate_c.zig b/test/translate_c.zig index 2054cfa246..4cf1e047fa 100644 --- a/test/translate_c.zig +++ b/test/translate_c.zig @@ -638,7 +638,6 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\} ); - cases.addC("c style cast", \\int float_to_int(float a) { \\ return (int)a; @@ -1289,29 +1288,29 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ } \\} , - \\pub fn switch_fn(i: c_int) c_int { - \\ var res: c_int = 0; - \\ __switch: { - \\ __case_2: { - \\ __default: { - \\ __case_1: { - \\ __case_0: { - \\ switch (i) { - \\ 0 => break :__case_0, - \\ 1 => break :__case_1, - \\ else => break :__default, - \\ 2 => break :__case_2, - \\ } - \\ } - \\ res = 1; - \\ } - \\ res = 2; - \\ } - \\ res = (3 * i); - \\ break :__switch; - \\ } - \\ res = 5; - \\ } - \\} + \\pub fn switch_fn(i: c_int) c_int { + \\ var res: c_int = 0; + \\ __switch: { + \\ __case_2: { + \\ __default: { + \\ __case_1: { + \\ __case_0: { + \\ switch (i) { + \\ 0 => break :__case_0, + \\ 1 => break :__case_1, + \\ else => break :__default, + \\ 2 => break :__case_2, + \\ } + \\ } + \\ res = 1; + \\ } + \\ res = 2; + \\ } + \\ res = (3 * i); + \\ break :__switch; + \\ } + \\ res = 5; + \\ } + \\} ); } -- cgit v1.2.3 From ea58f4a5a95662637d2142727a0452542bcdb196 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 30 May 2018 16:09:11 -0400 Subject: run zig fmt on the codebase --- src-self-hosted/main.zig | 4 ++-- std/array_list.zig | 6 ++--- std/base64.zig | 2 +- std/build.zig | 4 ++-- std/c/darwin.zig | 2 +- std/c/index.zig | 2 +- std/crypto/blake2.zig | 16 ++++++------- std/crypto/md5.zig | 4 ++-- std/crypto/sha1.zig | 4 ++-- std/crypto/sha2.zig | 12 +++++----- std/crypto/sha3.zig | 8 +++---- std/crypto/test.zig | 2 +- std/event.zig | 4 ++-- std/fmt/errol/index.zig | 4 ++-- std/fmt/index.zig | 26 ++++++++++---------- std/hash/crc.zig | 2 +- std/hash/siphash.zig | 2 +- std/hash_map.zig | 2 +- std/io.zig | 6 ++--- std/io_test.zig | 4 ++-- std/json.zig | 2 +- std/mem.zig | 12 +++++----- std/os/darwin.zig | 6 ++--- std/os/index.zig | 16 ++++++------- std/os/linux/index.zig | 14 +++++------ std/os/linux/x86_64.zig | 2 +- std/os/path.zig | 6 ++--- std/os/windows/index.zig | 2 +- std/os/windows/util.zig | 2 +- std/os/zen.zig | 2 +- std/rand/index.zig | 2 +- std/rand/ziggurat.zig | 10 ++++---- std/sort.zig | 42 ++++++++++++++++----------------- std/special/build_runner.zig | 2 +- std/unicode.zig | 4 ++-- std/zig/tokenizer.zig | 2 +- test/cases/align.zig | 10 ++++---- test/cases/bugs/920.zig | 6 ++--- test/cases/coroutines.zig | 2 +- test/cases/error.zig | 2 +- test/cases/eval.zig | 2 +- test/cases/fn.zig | 2 +- test/cases/fn_in_struct_in_comptime.zig | 2 +- test/cases/generics.zig | 2 +- test/cases/misc.zig | 2 +- test/cases/struct.zig | 4 ++-- test/cases/type_info.zig | 2 +- test/cases/var_args.zig | 2 +- 48 files changed, 140 insertions(+), 140 deletions(-) (limited to 'std/os/linux') diff --git a/src-self-hosted/main.zig b/src-self-hosted/main.zig index 02e5bbf921..9ad766dda2 100644 --- a/src-self-hosted/main.zig +++ b/src-self-hosted/main.zig @@ -41,7 +41,7 @@ const usage = const Command = struct { name: []const u8, - exec: fn(&Allocator, []const []const u8) error!void, + exec: fn (&Allocator, []const []const u8) error!void, }; pub fn main() !void { @@ -862,7 +862,7 @@ fn cmdRun(allocator: &Allocator, args: []const []const u8) !void { for (args) |argv, i| { if (mem.eql(u8, argv, "--")) { compile_args = args[0..i]; - runtime_args = args[i + 1..]; + runtime_args = args[i + 1 ..]; break; } } diff --git a/std/array_list.zig b/std/array_list.zig index 679f7d73b8..b315194c33 100644 --- a/std/array_list.zig +++ b/std/array_list.zig @@ -71,7 +71,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { try l.ensureCapacity(l.len + 1); l.len += 1; - mem.copy(T, l.items[n + 1..l.len], l.items[n..l.len - 1]); + mem.copy(T, l.items[n + 1 .. l.len], l.items[n .. l.len - 1]); l.items[n] = item.*; } @@ -79,8 +79,8 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { try l.ensureCapacity(l.len + items.len); l.len += items.len; - mem.copy(T, l.items[n + items.len..l.len], l.items[n..l.len - items.len]); - mem.copy(T, l.items[n..n + items.len], items); + mem.copy(T, l.items[n + items.len .. l.len], l.items[n .. l.len - items.len]); + mem.copy(T, l.items[n .. n + items.len], items); } pub fn append(l: &Self, item: &const T) !void { diff --git a/std/base64.zig b/std/base64.zig index b714250992..204628a405 100644 --- a/std/base64.zig +++ b/std/base64.zig @@ -450,7 +450,7 @@ fn testError(encoded: []const u8, expected_err: error) !void { fn testOutputTooSmallError(encoded: []const u8) !void { const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " "); var buffer: [0x100]u8 = undefined; - var decoded = buffer[0..calcDecodedSizeExactUnsafe(encoded, standard_pad_char) - 1]; + var decoded = buffer[0 .. calcDecodedSizeExactUnsafe(encoded, standard_pad_char) - 1]; if (standard_decoder_ignore_space.decode(decoded, encoded)) |_| { return error.ExpectedError; } else |err| if (err != error.OutputTooSmall) return err; diff --git a/std/build.zig b/std/build.zig index f86c3d394f..9a6e17f728 100644 --- a/std/build.zig +++ b/std/build.zig @@ -1912,12 +1912,12 @@ pub const RemoveDirStep = struct { pub const Step = struct { name: []const u8, - makeFn: fn(self: &Step) error!void, + makeFn: fn (self: &Step) error!void, dependencies: ArrayList(&Step), loop_flag: bool, done_flag: bool, - pub fn init(name: []const u8, allocator: &Allocator, makeFn: fn(&Step) error!void) Step { + pub fn init(name: []const u8, allocator: &Allocator, makeFn: fn (&Step) error!void) Step { return Step{ .name = name, .makeFn = makeFn, diff --git a/std/c/darwin.zig b/std/c/darwin.zig index 24be832d01..6a33c994bf 100644 --- a/std/c/darwin.zig +++ b/std/c/darwin.zig @@ -60,7 +60,7 @@ pub const sigset_t = u32; /// Renamed from `sigaction` to `Sigaction` to avoid conflict with function name. pub const Sigaction = extern struct { - handler: extern fn(c_int) void, + handler: extern fn (c_int) void, sa_mask: sigset_t, sa_flags: c_int, }; diff --git a/std/c/index.zig b/std/c/index.zig index b5e6b48751..f9704f4738 100644 --- a/std/c/index.zig +++ b/std/c/index.zig @@ -52,7 +52,7 @@ pub extern "c" fn realloc(&c_void, usize) ?&c_void; pub extern "c" fn free(&c_void) void; pub extern "c" fn posix_memalign(memptr: &&c_void, alignment: usize, size: usize) c_int; -pub 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; +pub 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; pub extern "pthread" fn pthread_attr_init(attr: &pthread_attr_t) c_int; pub extern "pthread" fn pthread_attr_setstack(attr: &pthread_attr_t, stackaddr: &c_void, stacksize: usize) c_int; pub extern "pthread" fn pthread_attr_destroy(attr: &pthread_attr_t) c_int; diff --git a/std/crypto/blake2.zig b/std/crypto/blake2.zig index b48e2fb4ba..bf3193b5d9 100644 --- a/std/crypto/blake2.zig +++ b/std/crypto/blake2.zig @@ -105,7 +105,7 @@ fn Blake2s(comptime out_len: usize) type { // Full middle blocks. while (off + 64 <= b.len) : (off += 64) { d.t += 64; - d.round(b[off..off + 64], false); + d.round(b[off .. off + 64], false); } // Copy any remainder for next pass. @@ -120,10 +120,10 @@ fn Blake2s(comptime out_len: usize) type { d.t += d.buf_len; d.round(d.buf[0..], true); - const rr = d.h[0..out_len / 32]; + const rr = d.h[0 .. out_len / 32]; for (rr) |s, j| { - mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Little); + mem.writeInt(out[4 * j .. 4 * j + 4], s, builtin.Endian.Little); } } @@ -134,7 +134,7 @@ fn Blake2s(comptime out_len: usize) type { var v: [16]u32 = undefined; for (m) |*r, i| { - r.* = mem.readIntLE(u32, b[4 * i..4 * i + 4]); + r.* = mem.readIntLE(u32, b[4 * i .. 4 * i + 4]); } var k: usize = 0; @@ -340,7 +340,7 @@ fn Blake2b(comptime out_len: usize) type { // Full middle blocks. while (off + 128 <= b.len) : (off += 128) { d.t += 128; - d.round(b[off..off + 128], false); + d.round(b[off .. off + 128], false); } // Copy any remainder for next pass. @@ -353,10 +353,10 @@ fn Blake2b(comptime out_len: usize) type { d.t += d.buf_len; d.round(d.buf[0..], true); - const rr = d.h[0..out_len / 64]; + const rr = d.h[0 .. out_len / 64]; for (rr) |s, j| { - mem.writeInt(out[8 * j..8 * j + 8], s, builtin.Endian.Little); + mem.writeInt(out[8 * j .. 8 * j + 8], s, builtin.Endian.Little); } } @@ -367,7 +367,7 @@ fn Blake2b(comptime out_len: usize) type { var v: [16]u64 = undefined; for (m) |*r, i| { - r.* = mem.readIntLE(u64, b[8 * i..8 * i + 8]); + r.* = mem.readIntLE(u64, b[8 * i .. 8 * i + 8]); } var k: usize = 0; diff --git a/std/crypto/md5.zig b/std/crypto/md5.zig index e0473884cd..3d05597273 100644 --- a/std/crypto/md5.zig +++ b/std/crypto/md5.zig @@ -73,7 +73,7 @@ pub const Md5 = struct { // Full middle blocks. while (off + 64 <= b.len) : (off += 64) { - d.round(b[off..off + 64]); + d.round(b[off .. off + 64]); } // Copy any remainder for next pass. @@ -112,7 +112,7 @@ pub const Md5 = struct { d.round(d.buf[0..]); for (d.s) |s, j| { - mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Little); + mem.writeInt(out[4 * j .. 4 * j + 4], s, builtin.Endian.Little); } } diff --git a/std/crypto/sha1.zig b/std/crypto/sha1.zig index 77324b482f..e9d8e3e132 100644 --- a/std/crypto/sha1.zig +++ b/std/crypto/sha1.zig @@ -73,7 +73,7 @@ pub const Sha1 = struct { // Full middle blocks. while (off + 64 <= b.len) : (off += 64) { - d.round(b[off..off + 64]); + d.round(b[off .. off + 64]); } // Copy any remainder for next pass. @@ -111,7 +111,7 @@ pub const Sha1 = struct { d.round(d.buf[0..]); for (d.s) |s, j| { - mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Big); + mem.writeInt(out[4 * j .. 4 * j + 4], s, builtin.Endian.Big); } } diff --git a/std/crypto/sha2.zig b/std/crypto/sha2.zig index a55182aacd..aedc820f44 100644 --- a/std/crypto/sha2.zig +++ b/std/crypto/sha2.zig @@ -126,7 +126,7 @@ fn Sha2_32(comptime params: Sha2Params32) type { // Full middle blocks. while (off + 64 <= b.len) : (off += 64) { - d.round(b[off..off + 64]); + d.round(b[off .. off + 64]); } // Copy any remainder for next pass. @@ -164,10 +164,10 @@ fn Sha2_32(comptime params: Sha2Params32) type { d.round(d.buf[0..]); // May truncate for possible 224 output - const rr = d.s[0..params.out_len / 32]; + const rr = d.s[0 .. params.out_len / 32]; for (rr) |s, j| { - mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Big); + mem.writeInt(out[4 * j .. 4 * j + 4], s, builtin.Endian.Big); } } @@ -467,7 +467,7 @@ fn Sha2_64(comptime params: Sha2Params64) type { // Full middle blocks. while (off + 128 <= b.len) : (off += 128) { - d.round(b[off..off + 128]); + d.round(b[off .. off + 128]); } // Copy any remainder for next pass. @@ -505,10 +505,10 @@ fn Sha2_64(comptime params: Sha2Params64) type { d.round(d.buf[0..]); // May truncate for possible 384 output - const rr = d.s[0..params.out_len / 64]; + const rr = d.s[0 .. params.out_len / 64]; for (rr) |s, j| { - mem.writeInt(out[8 * j..8 * j + 8], s, builtin.Endian.Big); + mem.writeInt(out[8 * j .. 8 * j + 8], s, builtin.Endian.Big); } } diff --git a/std/crypto/sha3.zig b/std/crypto/sha3.zig index 73b6415e1d..75bec57a87 100644 --- a/std/crypto/sha3.zig +++ b/std/crypto/sha3.zig @@ -46,7 +46,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type { // absorb while (len >= rate) { - for (d.s[offset..offset + rate]) |*r, i| + for (d.s[offset .. offset + rate]) |*r, i| r.* ^= b[ip..][i]; keccak_f(1600, d.s[0..]); @@ -57,7 +57,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type { offset = 0; } - for (d.s[offset..offset + len]) |*r, i| + for (d.s[offset .. offset + len]) |*r, i| r.* ^= b[ip..][i]; d.offset = offset + len; @@ -193,7 +193,7 @@ fn keccak_f(comptime F: usize, d: []u8) void { var c = []const u64{0} ** 5; for (s) |*r, i| { - r.* = mem.readIntLE(u64, d[8 * i..8 * i + 8]); + r.* = mem.readIntLE(u64, d[8 * i .. 8 * i + 8]); } comptime var x: usize = 0; @@ -240,7 +240,7 @@ fn keccak_f(comptime F: usize, d: []u8) void { } for (s) |r, i| { - mem.writeInt(d[8 * i..8 * i + 8], r, builtin.Endian.Little); + mem.writeInt(d[8 * i .. 8 * i + 8], r, builtin.Endian.Little); } } diff --git a/std/crypto/test.zig b/std/crypto/test.zig index c0a96a98de..3fa24272e5 100644 --- a/std/crypto/test.zig +++ b/std/crypto/test.zig @@ -14,7 +14,7 @@ pub fn assertEqualHash(comptime Hasher: var, comptime expected: []const u8, inpu pub fn assertEqual(comptime expected: []const u8, input: []const u8) void { var expected_bytes: [expected.len / 2]u8 = undefined; for (expected_bytes) |*r, i| { - r.* = fmt.parseInt(u8, expected[2 * i..2 * i + 2], 16) catch unreachable; + r.* = fmt.parseInt(u8, expected[2 * i .. 2 * i + 2], 16) catch unreachable; } debug.assert(mem.eql(u8, expected_bytes, input)); diff --git a/std/event.zig b/std/event.zig index 6ee8ab35f1..4604eb8d02 100644 --- a/std/event.zig +++ b/std/event.zig @@ -6,7 +6,7 @@ const mem = std.mem; const posix = std.os.posix; pub const TcpServer = struct { - handleRequestFn: async<&mem.Allocator> fn(&TcpServer, &const std.net.Address, &const std.os.File) void, + handleRequestFn: async<&mem.Allocator> fn (&TcpServer, &const std.net.Address, &const std.os.File) void, loop: &Loop, sockfd: i32, @@ -32,7 +32,7 @@ pub const TcpServer = struct { }; } - 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 { + 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 { self.handleRequestFn = handleRequestFn; try std.os.posixBind(self.sockfd, &address.os_addr); diff --git a/std/fmt/errol/index.zig b/std/fmt/errol/index.zig index 9c8fe343b5..65e8d448a8 100644 --- a/std/fmt/errol/index.zig +++ b/std/fmt/errol/index.zig @@ -60,7 +60,7 @@ pub fn roundToPrecision(float_decimal: &FloatDecimal, precision: usize, mode: Ro // Re-size the buffer to use the reserved leading byte. const one_before = @intToPtr(&u8, @ptrToInt(&float_decimal.digits[0]) - 1); - float_decimal.digits = one_before[0..float_decimal.digits.len + 1]; + float_decimal.digits = one_before[0 .. float_decimal.digits.len + 1]; float_decimal.digits[0] = '1'; return; } @@ -84,7 +84,7 @@ pub fn errol3(value: f64, buffer: []u8) FloatDecimal { const i = tableLowerBound(bits); if (i < enum3.len and enum3[i] == bits) { const data = enum3_data[i]; - const digits = buffer[1..data.str.len + 1]; + const digits = buffer[1 .. data.str.len + 1]; mem.copy(u8, digits, data.str); return FloatDecimal{ .digits = digits, diff --git a/std/fmt/index.zig b/std/fmt/index.zig index 71ac764b0b..0ffbc59895 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -11,7 +11,7 @@ const max_int_digits = 65; /// Renders fmt string with args, calling output with slices of bytes. /// If `output` returns an error, the error is returned from `format` and /// `output` is not called again. -pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void, comptime fmt: []const u8, args: ...) Errors!void { +pub fn format(context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void, comptime fmt: []const u8, args: ...) Errors!void { const State = enum { Start, OpenBrace, @@ -268,7 +268,7 @@ pub fn format(context: var, comptime Errors: type, output: fn(@typeOf(context), } } -pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { +pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void { const T = @typeOf(value); switch (@typeId(T)) { builtin.TypeId.Int => { @@ -317,11 +317,11 @@ pub fn formatValue(value: var, context: var, comptime Errors: type, output: fn(@ } } -pub fn formatAsciiChar(c: u8, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { +pub fn formatAsciiChar(c: u8, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void { return output(context, (&c)[0..1]); } -pub fn formatBuf(buf: []const u8, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { +pub fn formatBuf(buf: []const u8, width: usize, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void { try output(context, buf); 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 // Print a float in scientific notation to the specified precision. Null uses full precision. // It should be the case that every full precision, printed value can be re-parsed back to the // same type unambiguously. -pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { +pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void { var x = f64(value); // Errol doesn't handle these special cases. @@ -423,7 +423,7 @@ pub fn formatFloatScientific(value: var, maybe_precision: ?usize, context: var, // Print a float of the format x.yyyyy where the number of y is specified by the precision argument. // By default floats are printed at full precision (no rounding). -pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { +pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void { var x = f64(value); // Errol doesn't handle these special cases. @@ -512,7 +512,7 @@ pub fn formatFloatDecimal(value: var, maybe_precision: ?usize, context: var, com // Remaining fractional portion, zero-padding if insufficient. debug.assert(precision >= printed); if (num_digits_whole_no_pad + precision - printed < float_decimal.digits.len) { - try output(context, float_decimal.digits[num_digits_whole_no_pad..num_digits_whole_no_pad + precision - printed]); + try output(context, float_decimal.digits[num_digits_whole_no_pad .. num_digits_whole_no_pad + precision - printed]); return; } else { try output(context, float_decimal.digits[num_digits_whole_no_pad..]); @@ -568,7 +568,7 @@ pub fn formatBytes( comptime radix: usize, context: var, comptime Errors: type, - output: fn(@typeOf(context), []const u8) Errors!void, + output: fn (@typeOf(context), []const u8) Errors!void, ) Errors!void { if (value == 0) { return output(context, "0B"); @@ -604,7 +604,7 @@ pub fn formatInt( width: usize, context: var, comptime Errors: type, - output: fn(@typeOf(context), []const u8) Errors!void, + output: fn (@typeOf(context), []const u8) Errors!void, ) Errors!void { if (@typeOf(value).is_signed) { return formatIntSigned(value, base, uppercase, width, context, Errors, output); @@ -613,7 +613,7 @@ pub fn formatInt( } } -fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { +fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void { const uint = @IntType(false, @typeOf(value).bit_count); if (value < 0) { const minus_sign: u8 = '-'; @@ -632,7 +632,7 @@ fn formatIntSigned(value: var, base: u8, uppercase: bool, width: usize, context: } } -fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn(@typeOf(context), []const u8) Errors!void) Errors!void { +fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, context: var, comptime Errors: type, output: fn (@typeOf(context), []const u8) Errors!void) Errors!void { // max_int_digits accounts for the minus sign. when printing an unsigned // number we don't need to do that. var buf: [max_int_digits - 1]u8 = undefined; @@ -661,7 +661,7 @@ fn formatIntUnsigned(value: var, base: u8, uppercase: bool, width: usize, contex mem.set(u8, buf[0..index], '0'); return output(context, buf); } else { - const padded_buf = buf[index - padding..]; + const padded_buf = buf[index - padding ..]; mem.set(u8, padded_buf[0..padding], '0'); return output(context, padded_buf); } @@ -760,7 +760,7 @@ fn bufPrintWrite(context: &BufPrintContext, bytes: []const u8) !void { pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: ...) ![]u8 { var context = BufPrintContext{ .remaining = buf }; try format(&context, error{BufferTooSmall}, bufPrintWrite, fmt, args); - return buf[0..buf.len - context.remaining.len]; + return buf[0 .. buf.len - context.remaining.len]; } pub fn allocPrint(allocator: &mem.Allocator, comptime fmt: []const u8, args: ...) ![]u8 { diff --git a/std/hash/crc.zig b/std/hash/crc.zig index 72c4e467c2..45bcb70e8b 100644 --- a/std/hash/crc.zig +++ b/std/hash/crc.zig @@ -61,7 +61,7 @@ pub fn Crc32WithPoly(comptime poly: u32) type { pub fn update(self: &Self, input: []const u8) void { var i: usize = 0; while (i + 8 <= input.len) : (i += 8) { - const p = input[i..i + 8]; + const p = input[i .. i + 8]; // Unrolling this way gives ~50Mb/s increase self.crc ^= (u32(p[0]) << 0); diff --git a/std/hash/siphash.zig b/std/hash/siphash.zig index b75866a403..750e23d4c8 100644 --- a/std/hash/siphash.zig +++ b/std/hash/siphash.zig @@ -76,7 +76,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) // Full middle blocks. while (off + 8 <= b.len) : (off += 8) { - d.round(b[off..off + 8]); + d.round(b[off .. off + 8]); } // Remainder for next pass. diff --git a/std/hash_map.zig b/std/hash_map.zig index e3b86f8a3b..f51b9c66ba 100644 --- a/std/hash_map.zig +++ b/std/hash_map.zig @@ -9,7 +9,7 @@ const builtin = @import("builtin"); const want_modification_safety = builtin.mode != builtin.Mode.ReleaseFast; const debug_u32 = if (want_modification_safety) u32 else void; -pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32, comptime eql: fn(a: K, b: K) bool) type { +pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u32, comptime eql: fn (a: K, b: K) bool) type { return struct { entries: []Entry, size: usize, diff --git a/std/io.zig b/std/io.zig index 7c997fdf42..39d319159e 100644 --- a/std/io.zig +++ b/std/io.zig @@ -82,7 +82,7 @@ pub fn InStream(comptime ReadError: type) type { /// Return the number of bytes read. If the number read is smaller than buf.len, it /// means the stream reached the end. Reaching the end of a stream is not an error /// condition. - readFn: fn(self: &Self, buffer: []u8) Error!usize, + readFn: fn (self: &Self, buffer: []u8) Error!usize, /// Replaces `buffer` contents by reading from the stream until it is finished. /// If `buffer.len()` would exceed `max_size`, `error.StreamTooLong` is returned and @@ -208,7 +208,7 @@ pub fn OutStream(comptime WriteError: type) type { const Self = this; pub const Error = WriteError; - writeFn: fn(self: &Self, bytes: []const u8) Error!void, + writeFn: fn (self: &Self, bytes: []const u8) Error!void, pub fn print(self: &Self, comptime format: []const u8, args: ...) !void { return std.fmt.format(self, Error, self.writeFn, format, args); @@ -369,7 +369,7 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr while (src_index < bytes.len) { const dest_space_left = self.buffer.len - self.index; const copy_amt = math.min(dest_space_left, bytes.len - src_index); - mem.copy(u8, self.buffer[self.index..], bytes[src_index..src_index + copy_amt]); + mem.copy(u8, self.buffer[self.index..], bytes[src_index .. src_index + copy_amt]); self.index += copy_amt; assert(self.index <= self.buffer.len); if (self.index == self.buffer.len) { diff --git a/std/io_test.zig b/std/io_test.zig index ca4eeb3aaa..301a9a4cd0 100644 --- a/std/io_test.zig +++ b/std/io_test.zig @@ -41,8 +41,8 @@ test "write a file, read it, then delete it" { defer allocator.free(contents); assert(mem.eql(u8, contents[0.."begin".len], "begin")); - assert(mem.eql(u8, contents["begin".len..contents.len - "end".len], data)); - assert(mem.eql(u8, contents[contents.len - "end".len..], "end")); + assert(mem.eql(u8, contents["begin".len .. contents.len - "end".len], data)); + assert(mem.eql(u8, contents[contents.len - "end".len ..], "end")); } try os.deleteFile(allocator, tmp_file_name); } diff --git a/std/json.zig b/std/json.zig index c88ce59139..9de8f0b53e 100644 --- a/std/json.zig +++ b/std/json.zig @@ -77,7 +77,7 @@ pub const Token = struct { // Slice into the underlying input string. pub fn slice(self: &const Token, input: []const u8, i: usize) []const u8 { - return input[i + self.offset - self.count..i + self.offset]; + return input[i + self.offset - self.count .. i + self.offset]; } }; diff --git a/std/mem.zig b/std/mem.zig index 70f2fe22ac..f4696cff9f 100644 --- a/std/mem.zig +++ b/std/mem.zig @@ -13,7 +13,7 @@ pub const Allocator = struct { /// The returned newly allocated memory is undefined. /// `alignment` is guaranteed to be >= 1 /// `alignment` is guaranteed to be a power of 2 - allocFn: fn(self: &Allocator, byte_count: usize, alignment: u29) Error![]u8, + allocFn: fn (self: &Allocator, byte_count: usize, alignment: u29) Error![]u8, /// If `new_byte_count > old_mem.len`: /// * `old_mem.len` is the same as what was returned from allocFn or reallocFn. @@ -26,10 +26,10 @@ pub const Allocator = struct { /// The returned newly allocated memory is undefined. /// `alignment` is guaranteed to be >= 1 /// `alignment` is guaranteed to be a power of 2 - reallocFn: fn(self: &Allocator, old_mem: []u8, new_byte_count: usize, alignment: u29) Error![]u8, + reallocFn: fn (self: &Allocator, old_mem: []u8, new_byte_count: usize, alignment: u29) Error![]u8, /// Guaranteed: `old_mem.len` is the same as what was returned from `allocFn` or `reallocFn` - freeFn: fn(self: &Allocator, old_mem: []u8) void, + freeFn: fn (self: &Allocator, old_mem: []u8) void, fn create(self: &Allocator, comptime T: type) !&T { if (@sizeOf(T) == 0) return &{}; @@ -282,7 +282,7 @@ pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?us var i: usize = haystack.len - needle.len; while (true) : (i -= 1) { - if (mem.eql(T, haystack[i..i + needle.len], needle)) return i; + if (mem.eql(T, haystack[i .. i + needle.len], needle)) return i; if (i == 0) return null; } } @@ -294,7 +294,7 @@ pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, nee var i: usize = start_index; const end = haystack.len - needle.len; while (i <= end) : (i += 1) { - if (eql(T, haystack[i..i + needle.len], needle)) return i; + if (eql(T, haystack[i .. i + needle.len], needle)) return i; } return null; } @@ -444,7 +444,7 @@ test "mem.startsWith" { } pub fn endsWith(comptime T: type, haystack: []const T, needle: []const T) bool { - return if (needle.len > haystack.len) false else eql(T, haystack[haystack.len - needle.len..], needle); + return if (needle.len > haystack.len) false else eql(T, haystack[haystack.len - needle.len ..], needle); } test "mem.endsWith" { diff --git a/std/os/darwin.zig b/std/os/darwin.zig index a01755d27b..a3fc230ac5 100644 --- a/std/os/darwin.zig +++ b/std/os/darwin.zig @@ -437,7 +437,7 @@ pub fn sigaction(sig: u5, noalias act: &const Sigaction, noalias oact: ?&Sigacti assert(sig != SIGKILL); assert(sig != SIGSTOP); var cact = c.Sigaction{ - .handler = @ptrCast(extern fn(c_int) void, act.handler), + .handler = @ptrCast(extern fn (c_int) void, act.handler), .sa_flags = @bitCast(c_int, act.flags), .sa_mask = act.mask, }; @@ -448,7 +448,7 @@ pub fn sigaction(sig: u5, noalias act: &const Sigaction, noalias oact: ?&Sigacti } if (oact) |old| { old.* = Sigaction{ - .handler = @ptrCast(extern fn(i32) void, coact.handler), + .handler = @ptrCast(extern fn (i32) void, coact.handler), .flags = @bitCast(u32, coact.sa_flags), .mask = coact.sa_mask, }; @@ -468,7 +468,7 @@ pub const sockaddr = c.sockaddr; /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = struct { - handler: extern fn(i32) void, + handler: extern fn (i32) void, mask: sigset_t, flags: u32, }; diff --git a/std/os/index.zig b/std/os/index.zig index 645d993256..70e654bcd9 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -399,7 +399,7 @@ pub fn createNullDelimitedEnvMap(allocator: &Allocator, env_map: &const BufMap) pub fn freeNullDelimitedEnvMap(allocator: &Allocator, envp_buf: []?&u8) void { for (envp_buf) |env| { - const env_buf = if (env) |ptr| ptr[0..cstr.len(ptr) + 1] else break; + const env_buf = if (env) |ptr| ptr[0 .. cstr.len(ptr) + 1] else break; allocator.free(env_buf); } allocator.free(envp_buf); @@ -449,7 +449,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap, allocator: while (it.next()) |search_path| { mem.copy(u8, path_buf, search_path); path_buf[search_path.len] = '/'; - mem.copy(u8, path_buf[search_path.len + 1..], exe_path); + mem.copy(u8, path_buf[search_path.len + 1 ..], exe_path); path_buf[search_path.len + exe_path.len + 1] = 0; err = posix.getErrno(posix.execve(path_buf.ptr, argv_buf.ptr, envp_buf.ptr)); assert(err > 0); @@ -532,7 +532,7 @@ pub fn getEnvMap(allocator: &Allocator) !BufMap { var end_i: usize = line_i; while (ptr[end_i] != 0) : (end_i += 1) {} - const value = ptr[line_i + 1..end_i]; + const value = ptr[line_i + 1 .. end_i]; try result.set(key, value); } @@ -549,7 +549,7 @@ pub fn getEnvPosix(key: []const u8) ?[]const u8 { var end_i: usize = line_i; while (ptr[end_i] != 0) : (end_i += 1) {} - const this_value = ptr[line_i + 1..end_i]; + const this_value = ptr[line_i + 1 .. end_i]; return this_value; } @@ -691,7 +691,7 @@ pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path: mem.copy(u8, existing_buf, existing_path); existing_buf[existing_path.len] = 0; - const new_buf = full_buf[existing_path.len + 1..]; + const new_buf = full_buf[existing_path.len + 1 ..]; mem.copy(u8, new_buf, new_path); new_buf[new_path.len] = 0; @@ -735,7 +735,7 @@ pub fn atomicSymLink(allocator: &Allocator, existing_path: []const u8, new_path: tmp_path[dirname.len] = os.path.sep; while (true) { try getRandomBytes(rand_buf[0..]); - b64_fs_encoder.encode(tmp_path[dirname.len + 1..], rand_buf); + b64_fs_encoder.encode(tmp_path[dirname.len + 1 ..], rand_buf); if (symLink(allocator, existing_path, tmp_path)) { return rename(allocator, tmp_path, new_path); @@ -914,7 +914,7 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8) mem.copy(u8, old_buf, old_path); old_buf[old_path.len] = 0; - const new_buf = full_buf[old_path.len + 1..]; + const new_buf = full_buf[old_path.len + 1 ..]; mem.copy(u8, new_buf, new_path); new_buf[new_path.len] = 0; @@ -1141,7 +1141,7 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError! const full_entry_path = full_entry_buf.toSlice(); mem.copy(u8, full_entry_path, full_path); full_entry_path[full_path.len] = '/'; - mem.copy(u8, full_entry_path[full_path.len + 1..], entry.name); + mem.copy(u8, full_entry_path[full_path.len + 1 ..], entry.name); try deleteTree(allocator, full_entry_path); } diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 1cf5bbd432..5186ff32d3 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -939,7 +939,7 @@ pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigacti .handler = act.handler, .flags = act.flags | SA_RESTORER, .mask = undefined, - .restorer = @ptrCast(extern fn() void, restore_rt), + .restorer = @ptrCast(extern fn () void, restore_rt), }; var ksa_old: k_sigaction = undefined; @memcpy(@ptrCast(&u8, &ksa.mask), @ptrCast(&const u8, &act.mask), 8); @@ -962,22 +962,22 @@ const all_mask = []usize{@maxValue(usize)}; const app_mask = []usize{0xfffffffc7fffffff}; const k_sigaction = extern struct { - handler: extern fn(i32) void, + handler: extern fn (i32) void, flags: usize, - restorer: extern fn() void, + restorer: extern fn () void, mask: [2]u32, }; /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = struct { - handler: extern fn(i32) void, + handler: extern fn (i32) void, mask: sigset_t, flags: u32, }; -pub const SIG_ERR = @intToPtr(extern fn(i32) void, @maxValue(usize)); -pub const SIG_DFL = @intToPtr(extern fn(i32) void, 0); -pub const SIG_IGN = @intToPtr(extern fn(i32) void, 1); +pub const SIG_ERR = @intToPtr(extern fn (i32) void, @maxValue(usize)); +pub const SIG_DFL = @intToPtr(extern fn (i32) void, 0); +pub const SIG_IGN = @intToPtr(extern fn (i32) void, 1); pub const empty_sigset = []usize{0} ** sigset_t.len; pub fn raise(sig: i32) usize { diff --git a/std/os/linux/x86_64.zig b/std/os/linux/x86_64.zig index ed32d59688..b43a642038 100644 --- a/std/os/linux/x86_64.zig +++ b/std/os/linux/x86_64.zig @@ -463,7 +463,7 @@ pub fn syscall6( } /// This matches the libc clone function. -pub extern fn clone(func: extern fn(arg: usize) u8, stack: usize, flags: usize, arg: usize, ptid: &i32, tls: usize, ctid: &i32) usize; +pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: usize, arg: usize, ptid: &i32, tls: usize, ctid: &i32) usize; pub nakedcc fn restore_rt() void { return asm volatile ("syscall" diff --git a/std/os/path.zig b/std/os/path.zig index f2b3bb9b0a..162faffc42 100644 --- a/std/os/path.zig +++ b/std/os/path.zig @@ -793,7 +793,7 @@ pub fn basenamePosix(path: []const u8) []const u8 { start_index -= 1; } - return path[start_index + 1..end_index]; + return path[start_index + 1 .. end_index]; } pub fn basenameWindows(path: []const u8) []const u8 { @@ -825,7 +825,7 @@ pub fn basenameWindows(path: []const u8) []const u8 { start_index -= 1; } - return path[start_index + 1..end_index]; + return path[start_index + 1 .. end_index]; } test "os.path.basename" { @@ -999,7 +999,7 @@ pub fn relativePosix(allocator: &Allocator, from: []const u8, to: []const u8) ![ } if (to_rest.len == 0) { // shave off the trailing slash - return result[0..result_index - 1]; + return result[0 .. result_index - 1]; } mem.copy(u8, result[result_index..], to_rest); diff --git a/std/os/windows/index.zig b/std/os/windows/index.zig index 426514f7d7..264ea391c4 100644 --- a/std/os/windows/index.zig +++ b/std/os/windows/index.zig @@ -369,7 +369,7 @@ pub const HEAP_CREATE_ENABLE_EXECUTE = 0x00040000; pub const HEAP_GENERATE_EXCEPTIONS = 0x00000004; pub const HEAP_NO_SERIALIZE = 0x00000001; -pub const PTHREAD_START_ROUTINE = extern fn(LPVOID) DWORD; +pub const PTHREAD_START_ROUTINE = extern fn (LPVOID) DWORD; pub const LPTHREAD_START_ROUTINE = PTHREAD_START_ROUTINE; test "import" { diff --git a/std/os/windows/util.zig b/std/os/windows/util.zig index 7b7fdfae08..2bd8a157e4 100644 --- a/std/os/windows/util.zig +++ b/std/os/windows/util.zig @@ -73,7 +73,7 @@ pub fn windowsIsCygwinPty(handle: windows.HANDLE) bool { } const name_info = @ptrCast(&const windows.FILE_NAME_INFO, &name_info_bytes[0]); - const name_bytes = name_info_bytes[size..size + usize(name_info.FileNameLength)]; + const name_bytes = name_info_bytes[size .. size + usize(name_info.FileNameLength)]; const name_wide = ([]u16)(name_bytes); return mem.indexOf(u16, name_wide, []u16{ 'm', 's', 'y', 's', '-' }) != null or mem.indexOf(u16, name_wide, []u16{ '-', 'p', 't', 'y' }) != null; diff --git a/std/os/zen.zig b/std/os/zen.zig index 7517cc0d69..2411c5363e 100644 --- a/std/os/zen.zig +++ b/std/os/zen.zig @@ -153,7 +153,7 @@ pub fn map(v_addr: usize, p_addr: usize, size: usize, writable: bool) bool { return syscall4(Syscall.map, v_addr, p_addr, size, usize(writable)) != 0; } -pub fn createThread(function: fn() void) u16 { +pub fn createThread(function: fn () void) u16 { return u16(syscall1(Syscall.createThread, @ptrToInt(function))); } diff --git a/std/rand/index.zig b/std/rand/index.zig index 68e6d3cb4d..c32309a0fd 100644 --- a/std/rand/index.zig +++ b/std/rand/index.zig @@ -28,7 +28,7 @@ pub const DefaultPrng = Xoroshiro128; pub const DefaultCsprng = Isaac64; pub const Random = struct { - fillFn: fn(r: &Random, buf: []u8) void, + fillFn: fn (r: &Random, buf: []u8) void, /// Read random bytes into the specified buffer until fill. pub fn bytes(r: &Random, buf: []u8) void { diff --git a/std/rand/ziggurat.zig b/std/rand/ziggurat.zig index 404687ad0c..7daeb59165 100644 --- a/std/rand/ziggurat.zig +++ b/std/rand/ziggurat.zig @@ -56,11 +56,11 @@ pub const ZigTable = struct { f: [257]f64, // probability density function used as a fallback - pdf: fn(f64) f64, + pdf: fn (f64) f64, // whether the distribution is symmetric is_symmetric: bool, // fallback calculation in the case we are in the 0 block - zero_case: fn(&Random, f64) f64, + zero_case: fn (&Random, f64) f64, }; // zigNorInit @@ -68,9 +68,9 @@ fn 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, + comptime f: fn (f64) f64, + comptime f_inv: fn (f64) f64, + comptime zero_case: fn (&Random, f64) f64, ) ZigTable { var tables: ZigTable = undefined; diff --git a/std/sort.zig b/std/sort.zig index 5596c9063d..4e17718241 100644 --- a/std/sort.zig +++ b/std/sort.zig @@ -5,7 +5,7 @@ const math = std.math; const builtin = @import("builtin"); /// Stable in-place sort. O(n) best case, O(pow(n, 2)) worst case. O(1) memory (no allocator required). -pub fn insertionSort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) void { +pub fn insertionSort(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &const T) bool) void { { var i: usize = 1; while (i < items.len) : (i += 1) { @@ -108,7 +108,7 @@ const Pull = struct { /// Stable in-place sort. O(n) best case, O(n*log(n)) worst case and average case. O(1) memory (no allocator required). /// Currently implemented as block sort. -pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) void { +pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &const T) bool) void { // Implementation ported from https://github.com/BonzaiThePenguin/WikiSort/blob/master/WikiSort.c var cache: [512]T = undefined; @@ -257,7 +257,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // merge A2 and B2 into the cache if (lessThan(items[B2.end - 1], items[A2.start])) { // the two ranges are in reverse order, so copy them in reverse order into the cache - mem.copy(T, cache[A1.length() + B2.length()..], items[A2.start..A2.end]); + mem.copy(T, cache[A1.length() + B2.length() ..], items[A2.start..A2.end]); mem.copy(T, cache[A1.length()..], items[B2.start..B2.end]); } else if (lessThan(items[B2.start], items[A2.end - 1])) { // 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 } else { // copy A2 and B2 into the cache in the same order mem.copy(T, cache[A1.length()..], items[A2.start..A2.end]); - mem.copy(T, cache[A1.length() + A2.length()..], items[B2.start..B2.end]); + mem.copy(T, cache[A1.length() + A2.length() ..], items[B2.start..B2.end]); } A2 = Range.init(A2.start, B2.end); @@ -275,7 +275,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons if (lessThan(cache[B3.end - 1], cache[A3.start])) { // the two ranges are in reverse order, so copy them in reverse order into the items - mem.copy(T, items[A1.start + A2.length()..], cache[A3.start..A3.end]); + mem.copy(T, items[A1.start + A2.length() ..], cache[A3.start..A3.end]); mem.copy(T, items[A1.start..], cache[B3.start..B3.end]); } else if (lessThan(cache[B3.start], cache[A3.end - 1])) { // 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 } else { // copy A3 and B3 into the items in the same order mem.copy(T, items[A1.start..], cache[A3.start..A3.end]); - mem.copy(T, items[A1.start + A1.length()..], cache[B3.start..B3.end]); + mem.copy(T, items[A1.start + A1.length() ..], cache[B3.start..B3.end]); } } @@ -640,7 +640,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons if (buffer2.length() > 0 or block_size <= cache.len) { // 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 if (block_size <= cache.len) { - mem.copy(T, cache[0..], items[blockA.start..blockA.start + block_size]); + mem.copy(T, cache[0..], items[blockA.start .. blockA.start + block_size]); } else { blockSwap(T, items, blockA.start, buffer2.start, block_size); } @@ -651,7 +651,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons blockSwap(T, items, B_split, blockA.start + block_size - B_remaining, B_remaining); } else { // we are unable to use the 'buffer2' trick to speed up the rotation operation since buffer2 doesn't exist, so perform a normal rotation - mem.rotate(T, items[B_split..blockA.start + block_size], blockA.start - B_split); + mem.rotate(T, items[B_split .. blockA.start + block_size], blockA.start - B_split); } // update the range for the remaining A blocks, and the range remaining from the B block after it was split @@ -741,7 +741,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons } // merge operation without a buffer -fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const Range, lessThan: fn(&const T, &const T) bool) void { +fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const Range, lessThan: fn (&const T, &const T) bool) void { if (A_arg.length() == 0 or B_arg.length() == 0) return; // this just repeatedly binary searches into B and rotates A into position. @@ -783,7 +783,7 @@ fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const } // merge operation using an internal buffer -fn mergeInternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, buffer: &const Range) void { +fn mergeInternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn (&const T, &const T) bool, buffer: &const Range) void { // whenever we find a value to add to the final array, swap it with the value that's already in that spot // when this algorithm is finished, 'buffer' will contain its original contents, but in a different order var A_count: usize = 0; @@ -819,7 +819,7 @@ fn blockSwap(comptime T: type, items: []T, start1: usize, start2: usize, block_s // combine a linear search with a binary search to reduce the number of comparisons in situations // where have some idea as to how many unique values there are and where the next value might be -fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { +fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, usize(1)); @@ -833,7 +833,7 @@ fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const return binaryFirst(T, items, value, Range.init(index - skip, index), lessThan); } -fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { +fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, usize(1)); @@ -847,7 +847,7 @@ fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &cons return binaryFirst(T, items, value, Range.init(index, index + skip), lessThan); } -fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { +fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, usize(1)); @@ -861,7 +861,7 @@ fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const return binaryLast(T, items, value, Range.init(index - skip, index), lessThan); } -fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { +fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, usize(1)); @@ -875,7 +875,7 @@ fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const return binaryLast(T, items, value, Range.init(index, index + skip), lessThan); } -fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool) usize { +fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool) usize { var start = range.start; var end = range.end - 1; if (range.start >= range.end) return range.end; @@ -893,7 +893,7 @@ fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Rang return start; } -fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool) usize { +fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool) usize { var start = range.start; var end = range.end - 1; if (range.start >= range.end) return range.end; @@ -911,7 +911,7 @@ fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range return start; } -fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, into: []T) void { +fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, lessThan: fn (&const T, &const T) bool, into: []T) void { var A_index: usize = A.start; var B_index: usize = B.start; const A_last = A.end; @@ -941,7 +941,7 @@ fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, less } } -fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, cache: []T) void { +fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn (&const T, &const T) bool, cache: []T) void { // A fits into the cache, so use that instead of the internal buffer var A_index: usize = 0; var B_index: usize = B.start; @@ -969,7 +969,7 @@ fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, mem.copy(T, items[insert_index..], cache[A_index..A_last]); } -fn swap(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool, order: &[8]u8, x: usize, y: usize) void { +fn swap(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &const T) bool, order: &[8]u8, x: usize, y: usize) void { if (lessThan(items[y], items[x]) or ((order.*)[x] > (order.*)[y] and !lessThan(items[x], items[y]))) { mem.swap(T, &items[x], &items[y]); mem.swap(u8, &(order.*)[x], &(order.*)[y]); @@ -1345,7 +1345,7 @@ fn fuzzTest(rng: &std.rand.Random) void { } } -pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) T { +pub fn min(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &const T) bool) T { var i: usize = 0; var smallest = items[0]; for (items[1..]) |item| { @@ -1356,7 +1356,7 @@ pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const return smallest; } -pub fn max(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) T { +pub fn max(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &const T) bool) T { var i: usize = 0; var biggest = items[0]; for (items[1..]) |item| { diff --git a/std/special/build_runner.zig b/std/special/build_runner.zig index cf8f19d49e..3ff11bbee4 100644 --- a/std/special/build_runner.zig +++ b/std/special/build_runner.zig @@ -71,7 +71,7 @@ pub fn main() !void { } if (mem.indexOfScalar(u8, option_contents, '=')) |name_end| { const option_name = option_contents[0..name_end]; - const option_value = option_contents[name_end + 1..]; + const option_value = option_contents[name_end + 1 ..]; if (builder.addUserInputOption(option_name, option_value)) return usageAndErr(&builder, false, try stderr_stream); } else { diff --git a/std/unicode.zig b/std/unicode.zig index 8bcc2705dd..36f04778f4 100644 --- a/std/unicode.zig +++ b/std/unicode.zig @@ -151,7 +151,7 @@ pub fn utf8ValidateSlice(s: []const u8) bool { return false; } - if (utf8Decode(s[i..i + cp_len])) |_| {} else |_| { + if (utf8Decode(s[i .. i + cp_len])) |_| {} else |_| { return false; } i += cp_len; @@ -216,7 +216,7 @@ const Utf8Iterator = struct { const cp_len = utf8ByteSequenceLength(it.bytes[it.i]) catch unreachable; it.i += cp_len; - return it.bytes[it.i - cp_len..it.i]; + return it.bytes[it.i - cp_len .. it.i]; } pub fn nextCodepoint(it: &Utf8Iterator) ?u32 { diff --git a/std/zig/tokenizer.zig b/std/zig/tokenizer.zig index 4881e952b7..7c3b3210fb 100644 --- a/std/zig/tokenizer.zig +++ b/std/zig/tokenizer.zig @@ -1116,7 +1116,7 @@ pub const Tokenizer = struct { if (self.index + length > self.buffer.len) { return u3(self.buffer.len - self.index); } - const bytes = self.buffer[self.index..self.index + length]; + const bytes = self.buffer[self.index .. self.index + length]; switch (length) { 2 => { const value = std.unicode.utf8Decode2(bytes) catch return length; diff --git a/test/cases/align.zig b/test/cases/align.zig index f82aa6cfc4..582063766f 100644 --- a/test/cases/align.zig +++ b/test/cases/align.zig @@ -18,8 +18,8 @@ fn noop4() align(4) void {} test "function alignment" { assert(derp() == 1234); - assert(@typeOf(noop1) == fn() align(1) void); - assert(@typeOf(noop4) == fn() align(4) void); + assert(@typeOf(noop1) == fn () align(1) void); + assert(@typeOf(noop4) == fn () align(4) void); noop1(); noop4(); } @@ -127,7 +127,7 @@ test "implicitly decreasing fn alignment" { testImplicitlyDecreaseFnAlign(alignedBig, 5678); } -fn testImplicitlyDecreaseFnAlign(ptr: fn() align(1) i32, answer: i32) void { +fn testImplicitlyDecreaseFnAlign(ptr: fn () align(1) i32, answer: i32) void { assert(ptr() == answer); } @@ -141,10 +141,10 @@ fn alignedBig() align(16) i32 { test "@alignCast functions" { assert(fnExpectsOnly1(simple4) == 0x19); } -fn fnExpectsOnly1(ptr: fn() align(1) i32) i32 { +fn fnExpectsOnly1(ptr: fn () align(1) i32) i32 { return fnExpects4(@alignCast(4, ptr)); } -fn fnExpects4(ptr: fn() align(4) i32) i32 { +fn fnExpects4(ptr: fn () align(4) i32) i32 { return ptr(); } fn simple4() align(4) i32 { diff --git a/test/cases/bugs/920.zig b/test/cases/bugs/920.zig index c2b6816e94..c315206072 100644 --- a/test/cases/bugs/920.zig +++ b/test/cases/bugs/920.zig @@ -7,12 +7,12 @@ const ZigTable = struct { x: [257]f64, f: [257]f64, - pdf: fn(f64) f64, + pdf: fn (f64) f64, is_symmetric: bool, - zero_case: fn(&Random, f64) f64, + zero_case: fn (&Random, f64) f64, }; -fn 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 { +fn 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 { var tables: ZigTable = undefined; tables.is_symmetric = is_symmetric; diff --git a/test/cases/coroutines.zig b/test/cases/coroutines.zig index 8a0218aeb7..8a071c6aad 100644 --- a/test/cases/coroutines.zig +++ b/test/cases/coroutines.zig @@ -154,7 +154,7 @@ test "async function with dot syntax" { test "async fn pointer in a struct field" { var data: i32 = 1; const Foo = struct { - bar: async<&std.mem.Allocator> fn(&i32) void, + bar: async<&std.mem.Allocator> fn (&i32) void, }; var foo = Foo{ .bar = simpleAsyncFn2 }; const p = (async foo.bar(&data)) catch unreachable; diff --git a/test/cases/error.zig b/test/cases/error.zig index 92b2a012bd..ced49419d5 100644 --- a/test/cases/error.zig +++ b/test/cases/error.zig @@ -193,7 +193,7 @@ fn entry() void { foo2(bar2); } -fn foo2(f: fn() error!void) void { +fn foo2(f: fn () error!void) void { const x = f(); } diff --git a/test/cases/eval.zig b/test/cases/eval.zig index 3a1c67445a..8a6dc25bd8 100644 --- a/test/cases/eval.zig +++ b/test/cases/eval.zig @@ -215,7 +215,7 @@ test "inlined block and runtime block phi" { const CmdFn = struct { name: []const u8, - func: fn(i32) i32, + func: fn (i32) i32, }; const cmd_fns = []CmdFn{ diff --git a/test/cases/fn.zig b/test/cases/fn.zig index a0691fbffc..dfb254c6aa 100644 --- a/test/cases/fn.zig +++ b/test/cases/fn.zig @@ -66,7 +66,7 @@ test "implicit cast function unreachable return" { wantsFnWithVoid(fnWithUnreachable); } -fn wantsFnWithVoid(f: fn() void) void {} +fn wantsFnWithVoid(f: fn () void) void {} fn fnWithUnreachable() noreturn { unreachable; diff --git a/test/cases/fn_in_struct_in_comptime.zig b/test/cases/fn_in_struct_in_comptime.zig index 51e494036b..c22da71940 100644 --- a/test/cases/fn_in_struct_in_comptime.zig +++ b/test/cases/fn_in_struct_in_comptime.zig @@ -1,6 +1,6 @@ const assert = @import("std").debug.assert; -fn get_foo() fn(&u8) usize { +fn get_foo() fn (&u8) usize { comptime { return struct { fn func(ptr: &u8) usize { diff --git a/test/cases/generics.zig b/test/cases/generics.zig index 93fecc7295..37cd1b89e4 100644 --- a/test/cases/generics.zig +++ b/test/cases/generics.zig @@ -133,7 +133,7 @@ fn getFirstByte(comptime T: type, mem: []const T) u8 { return getByte(@ptrCast(&const u8, &mem[0])); } -const foos = []fn(var) bool{ +const foos = []fn (var) bool{ foo1, foo2, }; diff --git a/test/cases/misc.zig b/test/cases/misc.zig index 42de163ea5..b6b2da8de5 100644 --- a/test/cases/misc.zig +++ b/test/cases/misc.zig @@ -511,7 +511,7 @@ test "@typeId" { assert(@typeId(@typeOf(AUnionEnum.One)) == Tid.Enum); assert(@typeId(AUnionEnum) == Tid.Union); assert(@typeId(AUnion) == Tid.Union); - assert(@typeId(fn() void) == Tid.Fn); + assert(@typeId(fn () void) == Tid.Fn); assert(@typeId(@typeOf(builtin)) == Tid.Namespace); assert(@typeId(@typeOf(x: { break :x this; diff --git a/test/cases/struct.zig b/test/cases/struct.zig index 37b0e497f0..d4a1c7fbe3 100644 --- a/test/cases/struct.zig +++ b/test/cases/struct.zig @@ -105,7 +105,7 @@ test "fn call of struct field" { } const Foo = struct { - ptr: fn() i32, + ptr: fn () i32, }; fn aFunc() i32 { @@ -302,7 +302,7 @@ test "packed array 24bits" { var bytes = []u8{0} ** (@sizeOf(FooArray24Bits) + 1); bytes[bytes.len - 1] = 0xaa; - const ptr = &([]FooArray24Bits)(bytes[0..bytes.len - 1])[0]; + const ptr = &([]FooArray24Bits)(bytes[0 .. bytes.len - 1])[0]; assert(ptr.a == 0); assert(ptr.b[0].field == 0); assert(ptr.b[1].field == 0); diff --git a/test/cases/type_info.zig b/test/cases/type_info.zig index 05266feb9c..2561d70865 100644 --- a/test/cases/type_info.zig +++ b/test/cases/type_info.zig @@ -196,7 +196,7 @@ fn testStruct() void { assert(!struct_info.Struct.defs[0].data.Fn.is_extern); assert(struct_info.Struct.defs[0].data.Fn.lib_name == null); assert(struct_info.Struct.defs[0].data.Fn.return_type == void); - assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn(&const TestStruct) void); + assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn (&const TestStruct) void); } const TestStruct = packed struct { diff --git a/test/cases/var_args.zig b/test/cases/var_args.zig index ec4d2059f3..5ef41f52ba 100644 --- a/test/cases/var_args.zig +++ b/test/cases/var_args.zig @@ -58,7 +58,7 @@ fn extraFn(extra: u32, args: ...) usize { return args.len; } -const foos = []fn(...) bool{ +const foos = []fn (...) bool{ foo1, foo2, }; -- cgit v1.2.3 From fcbb7426faac5e693ef195defe2d8d2a2eddadb1 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 31 May 2018 10:56:59 -0400 Subject: use * for pointer type instead of & See #770 To help automatically translate code, see the zig-fmt-pointer-reform-2 branch. This will convert all & into *. Due to the syntax ambiguity (which is why we are making this change), even address-of & will turn into *, so you'll have to manually fix thes instances. You will be guaranteed to get compile errors for them - expected 'type', found 'foo' --- build.zig | 14 +- doc/docgen.zig | 22 +- doc/langref.html.in | 212 ++++----- example/cat/main.zig | 2 +- example/hello_world/hello_libc.zig | 2 +- example/mix_o_files/base64.zig | 2 +- example/mix_o_files/build.zig | 2 +- example/shared_library/build.zig | 2 +- src-self-hosted/arg.zig | 12 +- src-self-hosted/errmsg.zig | 14 +- src-self-hosted/introspect.zig | 6 +- src-self-hosted/ir.zig | 2 +- src-self-hosted/main.zig | 36 +- src-self-hosted/module.zig | 30 +- src-self-hosted/scope.zig | 2 +- src-self-hosted/target.zig | 10 +- src/all_types.hpp | 31 +- src/analyze.cpp | 8 +- src/ast_render.cpp | 31 +- src/codegen.cpp | 2 +- src/ir.cpp | 89 ++-- src/ir_print.cpp | 6 +- src/parser.cpp | 41 +- src/translate_c.cpp | 33 +- std/array_list.zig | 46 +- std/atomic/queue.zig | 32 +- std/atomic/stack.zig | 36 +- std/base64.zig | 12 +- std/buf_map.zig | 18 +- std/buf_set.zig | 18 +- std/buffer.zig | 40 +- std/build.zig | 278 ++++++------ std/c/darwin.zig | 8 +- std/c/index.zig | 72 ++-- std/c/linux.zig | 4 +- std/c/windows.zig | 2 +- std/crypto/blake2.zig | 16 +- std/crypto/md5.zig | 8 +- std/crypto/sha1.zig | 8 +- std/crypto/sha2.zig | 16 +- std/crypto/sha3.zig | 6 +- std/crypto/throughput_test.zig | 4 +- std/cstr.zig | 26 +- std/debug/failing_allocator.zig | 10 +- std/debug/index.zig | 106 ++--- std/elf.zig | 18 +- std/event.zig | 34 +- std/fmt/errol/index.zig | 14 +- std/fmt/index.zig | 8 +- std/hash/adler.zig | 4 +- std/hash/crc.zig | 8 +- std/hash/fnv.zig | 4 +- std/hash/siphash.zig | 8 +- std/hash_map.zig | 36 +- std/heap.zig | 82 ++-- std/io.zig | 80 ++-- std/json.zig | 36 +- std/linked_list.zig | 32 +- std/macho.zig | 16 +- std/math/complex/atan.zig | 4 +- std/math/complex/cosh.zig | 4 +- std/math/complex/exp.zig | 4 +- std/math/complex/index.zig | 14 +- std/math/complex/ldexp.zig | 8 +- std/math/complex/pow.zig | 2 +- std/math/complex/sinh.zig | 4 +- std/math/complex/sqrt.zig | 4 +- std/math/complex/tanh.zig | 4 +- std/math/hypot.zig | 2 +- std/math/index.zig | 4 +- std/mem.zig | 48 +-- std/net.zig | 8 +- std/os/child_process.zig | 62 +-- std/os/darwin.zig | 64 +-- std/os/file.zig | 32 +- std/os/get_user_id.zig | 8 +- std/os/index.zig | 164 +++---- std/os/linux/index.zig | 174 ++++---- std/os/linux/vdso.zig | 36 +- std/os/linux/x86_64.zig | 8 +- std/os/path.zig | 22 +- std/os/test.zig | 2 +- std/os/time.zig | 6 +- std/os/windows/index.zig | 96 ++--- std/os/windows/util.zig | 12 +- std/os/zen.zig | 20 +- std/rand/index.zig | 46 +- std/rand/ziggurat.zig | 10 +- std/segmented_list.zig | 54 +-- std/sort.zig | 54 +-- std/special/bootstrap.zig | 20 +- std/special/build_file_template.zig | 4 +- std/special/build_runner.zig | 6 +- std/special/builtin.zig | 8 +- std/special/compiler_rt/index.zig | 4 +- std/special/compiler_rt/udivmod.zig | 18 +- std/special/compiler_rt/udivmoddi4.zig | 2 +- std/special/compiler_rt/udivmodti4.zig | 4 +- std/special/compiler_rt/udivti3.zig | 2 +- std/special/compiler_rt/umodti3.zig | 2 +- std/special/panic.zig | 2 +- std/unicode.zig | 6 +- std/zig/ast.zig | 570 ++++++++++++------------- std/zig/bench.zig | 6 +- std/zig/parse.zig | 156 +++---- std/zig/parser_test.zig | 2 +- std/zig/render.zig | 56 +-- std/zig/tokenizer.zig | 8 +- test/assemble_and_link.zig | 2 +- test/build_examples.zig | 2 +- test/cases/align.zig | 56 +-- test/cases/atomics.zig | 12 +- test/cases/bugs/655.zig | 4 +- test/cases/bugs/828.zig | 6 +- test/cases/bugs/920.zig | 6 +- test/cases/cast.zig | 42 +- test/cases/const_slice_child.zig | 6 +- test/cases/coroutines.zig | 6 +- test/cases/enum.zig | 10 +- test/cases/enum_with_members.zig | 2 +- test/cases/eval.zig | 12 +- test/cases/field_parent_ptr.zig | 4 +- test/cases/fn_in_struct_in_comptime.zig | 6 +- test/cases/generics.zig | 8 +- test/cases/incomplete_struct_param_tld.zig | 4 +- test/cases/math.zig | 18 +- test/cases/misc.zig | 48 +-- test/cases/null.zig | 2 +- test/cases/reflection.zig | 2 +- test/cases/slice.zig | 2 +- test/cases/struct.zig | 28 +- test/cases/struct_contains_null_ptr_itself.zig | 4 +- test/cases/switch.zig | 2 +- test/cases/this.zig | 2 +- test/cases/type_info.zig | 16 +- test/cases/undefined.zig | 4 +- test/cases/union.zig | 16 +- test/compare_output.zig | 20 +- test/compile_errors.zig | 122 +++--- test/gen_h.zig | 2 +- test/runtime_safety.zig | 2 +- test/standalone/brace_expansion/build.zig | 2 +- test/standalone/brace_expansion/main.zig | 8 +- test/standalone/issue_339/build.zig | 2 +- test/standalone/issue_339/test.zig | 2 +- test/standalone/issue_794/build.zig | 2 +- test/standalone/pkg_import/build.zig | 2 +- test/standalone/use_alias/build.zig | 2 +- test/tests.zig | 136 +++--- test/translate_c.zig | 58 +-- 150 files changed, 2162 insertions(+), 2143 deletions(-) (limited to 'std/os/linux') diff --git a/build.zig b/build.zig index a4e3dbcdfa..109a799ac9 100644 --- a/build.zig +++ b/build.zig @@ -10,7 +10,7 @@ const ArrayList = std.ArrayList; const Buffer = std.Buffer; const io = std.io; -pub fn build(b: &Builder) !void { +pub fn build(b: *Builder) !void { const mode = b.standardReleaseOptions(); var docgen_exe = b.addExecutable("docgen", "doc/docgen.zig"); @@ -132,7 +132,7 @@ pub fn build(b: &Builder) !void { test_step.dependOn(tests.addGenHTests(b, test_filter)); } -fn dependOnLib(lib_exe_obj: &std.build.LibExeObjStep, dep: &const LibraryDep) void { +fn dependOnLib(lib_exe_obj: *std.build.LibExeObjStep, dep: *const LibraryDep) void { for (dep.libdirs.toSliceConst()) |lib_dir| { lib_exe_obj.addLibPath(lib_dir); } @@ -147,7 +147,7 @@ fn dependOnLib(lib_exe_obj: &std.build.LibExeObjStep, dep: &const LibraryDep) vo } } -fn addCppLib(b: &Builder, lib_exe_obj: &std.build.LibExeObjStep, cmake_binary_dir: []const u8, lib_name: []const u8) void { +fn addCppLib(b: *Builder, lib_exe_obj: *std.build.LibExeObjStep, cmake_binary_dir: []const u8, lib_name: []const u8) void { const lib_prefix = if (lib_exe_obj.target.isWindows()) "" else "lib"; 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); } @@ -159,7 +159,7 @@ const LibraryDep = struct { includes: ArrayList([]const u8), }; -fn findLLVM(b: &Builder, llvm_config_exe: []const u8) !LibraryDep { +fn findLLVM(b: *Builder, llvm_config_exe: []const u8) !LibraryDep { const libs_output = try b.exec([][]const u8{ llvm_config_exe, "--libs", @@ -217,7 +217,7 @@ fn findLLVM(b: &Builder, llvm_config_exe: []const u8) !LibraryDep { return result; } -pub fn installStdLib(b: &Builder, stdlib_files: []const u8) void { +pub fn installStdLib(b: *Builder, stdlib_files: []const u8) void { var it = mem.split(stdlib_files, ";"); while (it.next()) |stdlib_file| { 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 { } } -pub fn installCHeaders(b: &Builder, c_header_files: []const u8) void { +pub fn installCHeaders(b: *Builder, c_header_files: []const u8) void { var it = mem.split(c_header_files, ";"); while (it.next()) |c_header_file| { 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 { } } -fn nextValue(index: &usize, build_info: []const u8) []const u8 { +fn nextValue(index: *usize, build_info: []const u8) []const u8 { const start = index.*; while (true) : (index.* += 1) { switch (build_info[index.*]) { diff --git a/doc/docgen.zig b/doc/docgen.zig index 7dc444f127..fed4bb8eba 100644 --- a/doc/docgen.zig +++ b/doc/docgen.zig @@ -104,7 +104,7 @@ const Tokenizer = struct { }; } - fn next(self: &Tokenizer) Token { + fn next(self: *Tokenizer) Token { var result = Token{ .id = Token.Id.Eof, .start = self.index, @@ -196,7 +196,7 @@ const Tokenizer = struct { line_end: usize, }; - fn getTokenLocation(self: &Tokenizer, token: &const Token) Location { + fn getTokenLocation(self: *Tokenizer, token: *const Token) Location { var loc = Location{ .line = 0, .column = 0, @@ -221,7 +221,7 @@ const Tokenizer = struct { } }; -fn parseError(tokenizer: &Tokenizer, token: &const Token, comptime fmt: []const u8, args: ...) error { +fn parseError(tokenizer: *Tokenizer, token: *const Token, comptime fmt: []const u8, args: ...) error { const loc = tokenizer.getTokenLocation(token); warn("{}:{}:{}: error: " ++ fmt ++ "\n", tokenizer.source_file_name, loc.line + 1, loc.column + 1, args); if (loc.line_start <= loc.line_end) { @@ -244,13 +244,13 @@ fn parseError(tokenizer: &Tokenizer, token: &const Token, comptime fmt: []const return error.ParseError; } -fn assertToken(tokenizer: &Tokenizer, token: &const Token, id: Token.Id) !void { +fn assertToken(tokenizer: *Tokenizer, token: *const Token, id: Token.Id) !void { if (token.id != id) { return parseError(tokenizer, token, "expected {}, found {}", @tagName(id), @tagName(token.id)); } } -fn eatToken(tokenizer: &Tokenizer, id: Token.Id) !Token { +fn eatToken(tokenizer: *Tokenizer, id: Token.Id) !Token { const token = tokenizer.next(); try assertToken(tokenizer, token, id); return token; @@ -317,7 +317,7 @@ const Action = enum { Close, }; -fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc { +fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { var urls = std.HashMap([]const u8, Token, mem.hash_slice_u8, mem.eql_slice_u8).init(allocator); errdefer urls.deinit(); @@ -546,7 +546,7 @@ fn genToc(allocator: &mem.Allocator, tokenizer: &Tokenizer) !Toc { }; } -fn urlize(allocator: &mem.Allocator, input: []const u8) ![]u8 { +fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 { var buf = try std.Buffer.initSize(allocator, 0); defer buf.deinit(); @@ -566,7 +566,7 @@ fn urlize(allocator: &mem.Allocator, input: []const u8) ![]u8 { return buf.toOwnedSlice(); } -fn escapeHtml(allocator: &mem.Allocator, input: []const u8) ![]u8 { +fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 { var buf = try std.Buffer.initSize(allocator, 0); defer buf.deinit(); @@ -608,7 +608,7 @@ test "term color" { assert(mem.eql(u8, result, "AgreenB")); } -fn termColor(allocator: &mem.Allocator, input: []const u8) ![]u8 { +fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 { var buf = try std.Buffer.initSize(allocator, 0); defer buf.deinit(); @@ -688,7 +688,7 @@ fn termColor(allocator: &mem.Allocator, input: []const u8) ![]u8 { return buf.toOwnedSlice(); } -fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var, zig_exe: []const u8) !void { +fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var, zig_exe: []const u8) !void { var code_progress_index: usize = 0; for (toc.nodes) |node| { switch (node) { @@ -1036,7 +1036,7 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var } } -fn exec(allocator: &mem.Allocator, args: []const []const u8) !os.ChildProcess.ExecResult { +fn exec(allocator: *mem.Allocator, args: []const []const u8) !os.ChildProcess.ExecResult { const result = try os.ChildProcess.exec(allocator, args, null, null, max_doc_file_size); switch (result.term) { os.ChildProcess.Term.Exited => |exit_code| { diff --git a/doc/langref.html.in b/doc/langref.html.in index d63c38d0fe..3bd1124e00 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -458,7 +458,7 @@ test "string literals" { // A C string literal is a null terminated pointer. const null_terminated_bytes = c"hello"; - assert(@typeOf(null_terminated_bytes) == &const u8); + assert(@typeOf(null_terminated_bytes) == *const u8); assert(null_terminated_bytes[5] == 0); } {#code_end#} @@ -547,7 +547,7 @@ const c_string_literal = ; {#code_end#}

- In this example the variable c_string_literal has type &const char and + In this example the variable c_string_literal has type *const char and has a terminating null byte.

{#see_also|@embedFile#} @@ -1403,12 +1403,12 @@ test "address of syntax" { assert(x_ptr.* == 1234); // When you get the address of a const variable, you get a const pointer. - assert(@typeOf(x_ptr) == &const i32); + assert(@typeOf(x_ptr) == *const i32); // If you want to mutate the value, you'd need an address of a mutable variable: var y: i32 = 5678; const y_ptr = &y; - assert(@typeOf(y_ptr) == &i32); + assert(@typeOf(y_ptr) == *i32); y_ptr.* += 1; assert(y_ptr.* == 5679); } @@ -1455,7 +1455,7 @@ comptime { test "@ptrToInt and @intToPtr" { // To convert an integer address into a pointer, use @intToPtr: - const ptr = @intToPtr(&i32, 0xdeadbeef); + const ptr = @intToPtr(*i32, 0xdeadbeef); // To convert a pointer to an integer, use @ptrToInt: const addr = @ptrToInt(ptr); @@ -1467,7 +1467,7 @@ test "@ptrToInt and @intToPtr" { comptime { // Zig is able to do this at compile-time, as long as // ptr is never dereferenced. - const ptr = @intToPtr(&i32, 0xdeadbeef); + const ptr = @intToPtr(*i32, 0xdeadbeef); const addr = @ptrToInt(ptr); assert(@typeOf(addr) == usize); assert(addr == 0xdeadbeef); @@ -1477,17 +1477,17 @@ test "volatile" { // In Zig, loads and stores are assumed to not have side effects. // If a given load or store should have side effects, such as // Memory Mapped Input/Output (MMIO), use `volatile`: - const mmio_ptr = @intToPtr(&volatile u8, 0x12345678); + const mmio_ptr = @intToPtr(*volatile u8, 0x12345678); // Now loads and stores with mmio_ptr are guaranteed to all happen // and in the same order as in source code. - assert(@typeOf(mmio_ptr) == &volatile u8); + assert(@typeOf(mmio_ptr) == *volatile u8); } test "nullable pointers" { // Pointers cannot be null. If you want a null pointer, use the nullable // prefix `?` to make the pointer type nullable. - var ptr: ?&i32 = null; + var ptr: ?*i32 = null; var x: i32 = 1; ptr = &x; @@ -1496,7 +1496,7 @@ test "nullable pointers" { // Nullable pointers are the same size as normal pointers, because pointer // value 0 is used as the null value. - assert(@sizeOf(?&i32) == @sizeOf(&i32)); + assert(@sizeOf(?*i32) == @sizeOf(*i32)); } test "pointer casting" { @@ -1504,7 +1504,7 @@ test "pointer casting" { // operation that Zig cannot protect you against. Use @ptrCast only when other // conversions are not possible. const bytes align(@alignOf(u32)) = []u8{0x12, 0x12, 0x12, 0x12}; - const u32_ptr = @ptrCast(&const u32, &bytes[0]); + const u32_ptr = @ptrCast(*const u32, &bytes[0]); assert(u32_ptr.* == 0x12121212); // Even this example is contrived - there are better ways to do the above than @@ -1518,7 +1518,7 @@ test "pointer casting" { test "pointer child type" { // pointer types have a `child` field which tells you the type they point to. - assert((&u32).Child == u32); + assert((*u32).Child == u32); } {#code_end#} {#header_open|Alignment#} @@ -1543,15 +1543,15 @@ const builtin = @import("builtin"); test "variable alignment" { var x: i32 = 1234; const align_of_i32 = @alignOf(@typeOf(x)); - assert(@typeOf(&x) == &i32); - assert(&i32 == &align(align_of_i32) i32); + assert(@typeOf(&x) == *i32); + assert(*i32 == *align(align_of_i32) i32); if (builtin.arch == builtin.Arch.x86_64) { - assert((&i32).alignment == 4); + assert((*i32).alignment == 4); } } {#code_end#} -

In the same way that a &i32 can be implicitly cast to a - &const i32, a pointer with a larger alignment can be implicitly +

In the same way that a *i32 can be implicitly cast to a + *const i32, a pointer with a larger alignment can be implicitly cast to a pointer with a smaller alignment, but not vice versa.

@@ -1565,7 +1565,7 @@ var foo: u8 align(4) = 100; test "global variable alignment" { assert(@typeOf(&foo).alignment == 4); - assert(@typeOf(&foo) == &align(4) u8); + assert(@typeOf(&foo) == *align(4) u8); const slice = (&foo)[0..1]; assert(@typeOf(slice) == []align(4) u8); } @@ -1610,7 +1610,7 @@ fn foo(bytes: []u8) u32 { u8 can alias any memory.

As an example, this code produces undefined behavior:

-
@ptrCast(&u32, f32(12.34)).*
+
@ptrCast(*u32, f32(12.34)).*

Instead, use {#link|@bitCast#}:

@bitCast(u32, f32(12.34))

As an added benefit, the @bitcast version works at compile-time.

@@ -1736,7 +1736,7 @@ const Vec3 = struct { }; } - pub fn dot(self: &const Vec3, other: &const Vec3) f32 { + pub fn dot(self: *const Vec3, other: *const Vec3) f32 { return self.x * other.x + self.y * other.y + self.z * other.z; } }; @@ -1768,7 +1768,7 @@ test "struct namespaced variable" { // struct field order is determined by the compiler for optimal performance. // however, you can still calculate a struct base pointer given a field pointer: -fn setYBasedOnX(x: &f32, y: f32) void { +fn setYBasedOnX(x: *f32, y: f32) void { const point = @fieldParentPtr(Point, "x", x); point.y = y; } @@ -1786,13 +1786,13 @@ test "field parent pointer" { fn LinkedList(comptime T: type) type { return struct { pub const Node = struct { - prev: ?&Node, - next: ?&Node, + prev: ?*Node, + next: ?*Node, data: T, }; - first: ?&Node, - last: ?&Node, + first: ?*Node, + last: ?*Node, len: usize, }; } @@ -2039,7 +2039,7 @@ const Variant = union(enum) { Int: i32, Bool: bool, - fn truthy(self: &const Variant) bool { + fn truthy(self: *const Variant) bool { return switch (self.*) { Variant.Int => |x_int| x_int != 0, Variant.Bool => |x_bool| x_bool, @@ -2786,7 +2786,7 @@ test "pass aggregate type by value to function" { } {#code_end#}

- Instead, one must use &const. Zig allows implicitly casting something + Instead, one must use *const. Zig allows implicitly casting something to a const pointer to it:

{#code_begin|test#} @@ -2794,7 +2794,7 @@ const Foo = struct { x: i32, }; -fn bar(foo: &const Foo) void {} +fn bar(foo: *const Foo) void {} test "implicitly cast to const pointer" { bar(Foo {.x = 12,}); @@ -3208,16 +3208,16 @@ struct Foo *do_a_thing(void) {

Zig code

{#code_begin|syntax#} // malloc prototype included for reference -extern fn malloc(size: size_t) ?&u8; +extern fn malloc(size: size_t) ?*u8; -fn doAThing() ?&Foo { +fn doAThing() ?*Foo { const ptr = malloc(1234) ?? return null; // ... } {#code_end#}

Here, Zig is at least as convenient, if not more, than C. And, the type of "ptr" - is &u8 not ?&u8. The ?? operator + is *u8 not ?*u8. The ?? operator unwrapped the nullable type and therefore ptr is guaranteed to be non-null everywhere it is used in the function.

@@ -3237,7 +3237,7 @@ fn doAThing() ?&Foo { In Zig you can accomplish the same thing:

{#code_begin|syntax#} -fn doAThing(nullable_foo: ?&Foo) void { +fn doAThing(nullable_foo: ?*Foo) void { // do some stuff if (nullable_foo) |foo| { @@ -3713,7 +3713,7 @@ fn List(comptime T: type) type {

{#code_begin|syntax#} const Node = struct { - next: &Node, + next: *Node, name: []u8, }; {#code_end#} @@ -3745,7 +3745,7 @@ pub fn main() void { {#code_begin|syntax#} /// Calls print and then flushes the buffer. -pub fn printf(self: &OutStream, comptime format: []const u8, args: ...) error!void { +pub fn printf(self: *OutStream, comptime format: []const u8, args: ...) error!void { const State = enum { Start, OpenBrace, @@ -3817,7 +3817,7 @@ pub fn printf(self: &OutStream, comptime format: []const u8, args: ...) error!vo and emits a function that actually looks like this:

{#code_begin|syntax#} -pub fn printf(self: &OutStream, arg0: i32, arg1: []const u8) !void { +pub fn printf(self: *OutStream, arg0: i32, arg1: []const u8) !void { try self.write("here is a string: '"); try self.printValue(arg0); try self.write("' here is a number: "); @@ -3831,7 +3831,7 @@ pub fn printf(self: &OutStream, arg0: i32, arg1: []const u8) !void { on the type:

{#code_begin|syntax#} -pub fn printValue(self: &OutStream, value: var) !void { +pub fn printValue(self: *OutStream, value: var) !void { const T = @typeOf(value); if (@isInteger(T)) { return self.printInt(T, value); @@ -3911,7 +3911,7 @@ pub fn main() void { at compile time.

{#header_open|@addWithOverflow#} -
@addWithOverflow(comptime T: type, a: T, b: T, result: &T) -> bool
+
@addWithOverflow(comptime T: type, a: T, b: T, result: *T) bool

Performs result.* = a + b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. @@ -3919,7 +3919,7 @@ pub fn main() void {

{#header_close#} {#header_open|@ArgType#} -
@ArgType(comptime T: type, comptime n: usize) -> type
+
@ArgType(comptime T: type, comptime n: usize) type

This builtin function takes a function type and returns the type of the parameter at index n.

@@ -3931,7 +3931,7 @@ pub fn main() void {

{#header_close#} {#header_open|@atomicLoad#} -
@atomicLoad(comptime T: type, ptr: &const T, comptime ordering: builtin.AtomicOrder) -> T
+
@atomicLoad(comptime T: type, ptr: *const T, comptime ordering: builtin.AtomicOrder) T

This builtin function atomically dereferences a pointer and returns the value.

@@ -3950,7 +3950,7 @@ pub fn main() void {

{#header_close#} {#header_open|@atomicRmw#} -
@atomicRmw(comptime T: type, ptr: &T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) -> T
+
@atomicRmw(comptime T: type, ptr: *T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) T

This builtin function atomically modifies memory and then returns the previous value.

@@ -3969,7 +3969,7 @@ pub fn main() void {

{#header_close#} {#header_open|@bitCast#} -
@bitCast(comptime DestType: type, value: var) -> DestType
+
@bitCast(comptime DestType: type, value: var) DestType

Converts a value of one type to another type.

@@ -4002,9 +4002,9 @@ pub fn main() void { {#header_close#} {#header_open|@alignCast#} -
@alignCast(comptime alignment: u29, ptr: var) -> var
+
@alignCast(comptime alignment: u29, ptr: var) var

- ptr can be &T, fn(), ?&T, + ptr can be *T, fn(), ?*T, ?fn(), or []T. It returns the same type as ptr except with the alignment adjusted to the new value.

@@ -4013,7 +4013,7 @@ pub fn main() void { {#header_close#} {#header_open|@alignOf#} -
@alignOf(comptime T: type) -> (number literal)
+
@alignOf(comptime T: type) (number literal)

This function returns the number of bytes that this type should be aligned to for the current target to match the C ABI. When the child type of a pointer has @@ -4021,7 +4021,7 @@ pub fn main() void {

const assert = @import("std").debug.assert;
 comptime {
-    assert(&u32 == &align(@alignOf(u32)) u32);
+    assert(*u32 == *align(@alignOf(u32)) u32);
 }

The result is a target-specific compile time constant. It is guaranteed to be @@ -4049,7 +4049,7 @@ comptime { {#see_also|Import from C Header File|@cInclude|@cImport|@cUndef|void#} {#header_close#} {#header_open|@cImport#} -

@cImport(expression) -> (namespace)
+
@cImport(expression) (namespace)

This function parses C code and imports the functions, types, variables, and compatible macro definitions into the result namespace. @@ -4095,13 +4095,13 @@ comptime { {#see_also|Import from C Header File|@cImport|@cDefine|@cInclude#} {#header_close#} {#header_open|@canImplicitCast#} -

@canImplicitCast(comptime T: type, value) -> bool
+
@canImplicitCast(comptime T: type, value) bool

Returns whether a value can be implicitly casted to a given type.

{#header_close#} {#header_open|@clz#} -
@clz(x: T) -> U
+
@clz(x: T) U

This function counts the number of leading zeroes in x which is an integer type T. @@ -4116,13 +4116,13 @@ comptime { {#header_close#} {#header_open|@cmpxchgStrong#} -

@cmpxchgStrong(comptime T: type, ptr: &T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) -> ?T
+
@cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T

This function performs a strong atomic compare exchange operation. It's the equivalent of this code, except atomic:

{#code_begin|syntax#} -fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_value: T) ?T { +fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T { const old_value = ptr.*; if (old_value == expected_value) { ptr.* = new_value; @@ -4143,13 +4143,13 @@ fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_v {#see_also|Compile Variables|cmpxchgWeak#} {#header_close#} {#header_open|@cmpxchgWeak#} -
@cmpxchgWeak(comptime T: type, ptr: &T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) -> ?T
+
@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T

This function performs a weak atomic compare exchange operation. It's the equivalent of this code, except atomic:

{#code_begin|syntax#} -fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: &T, expected_value: T, new_value: T) ?T { +fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T { const old_value = ptr.*; if (old_value == expected_value and usuallyTrueButSometimesFalse()) { ptr.* = new_value; @@ -4237,7 +4237,7 @@ test "main" { {#code_end#} {#header_close#} {#header_open|@ctz#} -
@ctz(x: T) -> U
+
@ctz(x: T) U

This function counts the number of trailing zeroes in x which is an integer type T. @@ -4251,7 +4251,7 @@ test "main" {

{#header_close#} {#header_open|@divExact#} -
@divExact(numerator: T, denominator: T) -> T
+
@divExact(numerator: T, denominator: T) T

Exact division. Caller guarantees denominator != 0 and @divTrunc(numerator, denominator) * denominator == numerator. @@ -4264,7 +4264,7 @@ test "main" { {#see_also|@divTrunc|@divFloor#} {#header_close#} {#header_open|@divFloor#} -

@divFloor(numerator: T, denominator: T) -> T
+
@divFloor(numerator: T, denominator: T) T

Floored division. Rounds toward negative infinity. For unsigned integers it is the same as numerator / denominator. Caller guarantees denominator != 0 and @@ -4278,7 +4278,7 @@ test "main" { {#see_also|@divTrunc|@divExact#} {#header_close#} {#header_open|@divTrunc#} -

@divTrunc(numerator: T, denominator: T) -> T
+
@divTrunc(numerator: T, denominator: T) T

Truncated division. Rounds toward zero. For unsigned integers it is the same as numerator / denominator. Caller guarantees denominator != 0 and @@ -4292,7 +4292,7 @@ test "main" { {#see_also|@divFloor|@divExact#} {#header_close#} {#header_open|@embedFile#} -

@embedFile(comptime path: []const u8) -> [X]u8
+
@embedFile(comptime path: []const u8) [X]u8

This function returns a compile time constant fixed-size array with length equal to the byte count of the file given by path. The contents of the array @@ -4304,19 +4304,19 @@ test "main" { {#see_also|@import#} {#header_close#} {#header_open|@export#} -

@export(comptime name: []const u8, target: var, linkage: builtin.GlobalLinkage) -> []const u8
+
@export(comptime name: []const u8, target: var, linkage: builtin.GlobalLinkage) []const u8

Creates a symbol in the output object file.

{#header_close#} {#header_open|@tagName#} -
@tagName(value: var) -> []const u8
+
@tagName(value: var) []const u8

Converts an enum value or union value to a slice of bytes representing the name.

{#header_close#} {#header_open|@TagType#} -
@TagType(T: type) -> type
+
@TagType(T: type) type

For an enum, returns the integer type that is used to store the enumeration value.

@@ -4325,7 +4325,7 @@ test "main" {

{#header_close#} {#header_open|@errorName#} -
@errorName(err: error) -> []u8
+
@errorName(err: error) []u8

This function returns the string representation of an error. If an error declaration is: @@ -4341,7 +4341,7 @@ test "main" {

{#header_close#} {#header_open|@errorReturnTrace#} -
@errorReturnTrace() -> ?&builtin.StackTrace
+
@errorReturnTrace() ?*builtin.StackTrace

If the binary is built with error return tracing, and this function is invoked in a function that calls a function with an error or error union return type, returns a @@ -4360,7 +4360,7 @@ test "main" { {#header_close#} {#header_open|@fieldParentPtr#}

@fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8,
-    field_ptr: &T) -> &ParentType
+ field_ptr: *T) *ParentType

Given a pointer to a field, returns the base pointer of a struct.

@@ -4380,7 +4380,7 @@ test "main" {

{#header_close#} {#header_open|@import#} -
@import(comptime path: []u8) -> (namespace)
+
@import(comptime path: []u8) (namespace)

This function finds a zig file corresponding to path and imports all the public top level declarations into the resulting namespace. @@ -4400,7 +4400,7 @@ test "main" { {#see_also|Compile Variables|@embedFile#} {#header_close#} {#header_open|@inlineCall#} -

@inlineCall(function: X, args: ...) -> Y
+
@inlineCall(function: X, args: ...) Y

This calls a function, in the same way that invoking an expression with parentheses does:

@@ -4420,19 +4420,19 @@ fn add(a: i32, b: i32) i32 { return a + b; } {#see_also|@noInlineCall#} {#header_close#} {#header_open|@intToPtr#} -
@intToPtr(comptime DestType: type, int: usize) -> DestType
+
@intToPtr(comptime DestType: type, int: usize) DestType

Converts an integer to a pointer. To convert the other way, use {#link|@ptrToInt#}.

{#header_close#} {#header_open|@IntType#} -
@IntType(comptime is_signed: bool, comptime bit_count: u8) -> type
+
@IntType(comptime is_signed: bool, comptime bit_count: u8) type

This function returns an integer type with the given signness and bit count.

{#header_close#} {#header_open|@maxValue#} -
@maxValue(comptime T: type) -> (number literal)
+
@maxValue(comptime T: type) (number literal)

This function returns the maximum value of the integer type T.

@@ -4441,7 +4441,7 @@ fn add(a: i32, b: i32) i32 { return a + b; }

{#header_close#} {#header_open|@memberCount#} -
@memberCount(comptime T: type) -> (number literal)
+
@memberCount(comptime T: type) (number literal)

This function returns the number of members in a struct, enum, or union type.

@@ -4453,7 +4453,7 @@ fn add(a: i32, b: i32) i32 { return a + b; }

{#header_close#} {#header_open|@memberName#} -
@memberName(comptime T: type, comptime index: usize) -> [N]u8
+
@memberName(comptime T: type, comptime index: usize) [N]u8

Returns the field name of a struct, union, or enum.

The result is a compile time constant. @@ -4463,15 +4463,15 @@ fn add(a: i32, b: i32) i32 { return a + b; }

{#header_close#} {#header_open|@field#} -
@field(lhs: var, comptime field_name: []const u8) -> (field)
+
@field(lhs: var, comptime field_name: []const u8) (field)

Preforms field access equivalent to lhs.->field_name-<.

{#header_close#} {#header_open|@memberType#} -
@memberType(comptime T: type, comptime index: usize) -> type
+
@memberType(comptime T: type, comptime index: usize) type

Returns the field type of a struct or union.

{#header_close#} {#header_open|@memcpy#} -
@memcpy(noalias dest: &u8, noalias source: &const u8, byte_count: usize)
+
@memcpy(noalias dest: *u8, noalias source: *const u8, byte_count: usize)

This function copies bytes from one region of memory to another. dest and source are both pointers and must not overlap. @@ -4489,7 +4489,7 @@ fn add(a: i32, b: i32) i32 { return a + b; } mem.copy(u8, dest[0...byte_count], source[0...byte_count]); {#header_close#} {#header_open|@memset#} -

@memset(dest: &u8, c: u8, byte_count: usize)
+
@memset(dest: *u8, c: u8, byte_count: usize)

This function sets a region of memory to c. dest is a pointer.

@@ -4506,7 +4506,7 @@ mem.copy(u8, dest[0...byte_count], source[0...byte_count]); mem.set(u8, dest, c); {#header_close#} {#header_open|@minValue#} -
@minValue(comptime T: type) -> (number literal)
+
@minValue(comptime T: type) (number literal)

This function returns the minimum value of the integer type T.

@@ -4515,7 +4515,7 @@ mem.set(u8, dest, c);

{#header_close#} {#header_open|@mod#} -
@mod(numerator: T, denominator: T) -> T
+
@mod(numerator: T, denominator: T) T

Modulus division. For unsigned integers this is the same as numerator % denominator. Caller guarantees denominator > 0. @@ -4528,7 +4528,7 @@ mem.set(u8, dest, c); {#see_also|@rem#} {#header_close#} {#header_open|@mulWithOverflow#} -

@mulWithOverflow(comptime T: type, a: T, b: T, result: &T) -> bool
+
@mulWithOverflow(comptime T: type, a: T, b: T, result: *T) bool

Performs result.* = a * b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. @@ -4536,7 +4536,7 @@ mem.set(u8, dest, c);

{#header_close#} {#header_open|@newStackCall#} -
@newStackCall(new_stack: []u8, function: var, args: ...) -> var
+
@newStackCall(new_stack: []u8, function: var, args: ...) var

This calls a function, in the same way that invoking an expression with parentheses does. However, instead of using the same stack as the caller, the function uses the stack provided in the new_stack @@ -4572,7 +4572,7 @@ fn targetFunction(x: i32) usize { {#code_end#} {#header_close#} {#header_open|@noInlineCall#} -

@noInlineCall(function: var, args: ...) -> var
+
@noInlineCall(function: var, args: ...) var

This calls a function, in the same way that invoking an expression with parentheses does:

@@ -4594,13 +4594,13 @@ fn add(a: i32, b: i32) i32 { {#see_also|@inlineCall#} {#header_close#} {#header_open|@offsetOf#} -
@offsetOf(comptime T: type, comptime field_name: [] const u8) -> (number literal)
+
@offsetOf(comptime T: type, comptime field_name: [] const u8) (number literal)

This function returns the byte offset of a field relative to its containing struct.

{#header_close#} {#header_open|@OpaqueType#} -
@OpaqueType() -> type
+
@OpaqueType() type

Creates a new type with an unknown size and alignment.

@@ -4608,12 +4608,12 @@ fn add(a: i32, b: i32) i32 { This is typically used for type safety when interacting with C code that does not expose struct details. Example:

- {#code_begin|test_err|expected type '&Derp', found '&Wat'#} + {#code_begin|test_err|expected type '*Derp', found '*Wat'#} const Derp = @OpaqueType(); const Wat = @OpaqueType(); -extern fn bar(d: &Derp) void; -export fn foo(w: &Wat) void { +extern fn bar(d: *Derp) void; +export fn foo(w: *Wat) void { bar(w); } @@ -4623,7 +4623,7 @@ test "call foo" { {#code_end#} {#header_close#} {#header_open|@panic#} -
@panic(message: []const u8) -> noreturn
+
@panic(message: []const u8) noreturn

Invokes the panic handler function. By default the panic handler function calls the public panic function exposed in the root source file, or @@ -4639,19 +4639,19 @@ test "call foo" { {#see_also|Root Source File#} {#header_close#} {#header_open|@ptrCast#} -

@ptrCast(comptime DestType: type, value: var) -> DestType
+
@ptrCast(comptime DestType: type, value: var) DestType

Converts a pointer of one type to a pointer of another type.

{#header_close#} {#header_open|@ptrToInt#} -
@ptrToInt(value: var) -> usize
+
@ptrToInt(value: var) usize

Converts value to a usize which is the address of the pointer. value can be one of these types:

    -
  • &T
  • -
  • ?&T
  • +
  • *T
  • +
  • ?*T
  • fn()
  • ?fn()
@@ -4659,7 +4659,7 @@ test "call foo" { {#header_close#} {#header_open|@rem#} -
@rem(numerator: T, denominator: T) -> T
+
@rem(numerator: T, denominator: T) T

Remainder division. For unsigned integers this is the same as numerator % denominator. Caller guarantees denominator > 0. @@ -4776,13 +4776,13 @@ pub const FloatMode = enum { {#see_also|Compile Variables#} {#header_close#} {#header_open|@setGlobalSection#} -

@setGlobalSection(global_variable_name, comptime section_name: []const u8) -> bool
+
@setGlobalSection(global_variable_name, comptime section_name: []const u8) bool

Puts the global variable in the specified section.

{#header_close#} {#header_open|@shlExact#} -
@shlExact(value: T, shift_amt: Log2T) -> T
+
@shlExact(value: T, shift_amt: Log2T) T

Performs the left shift operation (<<). Caller guarantees that the shift will not shift any 1 bits out. @@ -4794,7 +4794,7 @@ pub const FloatMode = enum { {#see_also|@shrExact|@shlWithOverflow#} {#header_close#} {#header_open|@shlWithOverflow#} -

@shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: &T) -> bool
+
@shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: *T) bool

Performs result.* = a << b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. @@ -4807,7 +4807,7 @@ pub const FloatMode = enum { {#see_also|@shlExact|@shrExact#} {#header_close#} {#header_open|@shrExact#} -

@shrExact(value: T, shift_amt: Log2T) -> T
+
@shrExact(value: T, shift_amt: Log2T) T

Performs the right shift operation (>>). Caller guarantees that the shift will not shift any 1 bits out. @@ -4819,7 +4819,7 @@ pub const FloatMode = enum { {#see_also|@shlExact|@shlWithOverflow#} {#header_close#} {#header_open|@sizeOf#} -

@sizeOf(comptime T: type) -> (number literal)
+
@sizeOf(comptime T: type) (number literal)

This function returns the number of bytes it takes to store T in memory.

@@ -4828,7 +4828,7 @@ pub const FloatMode = enum {

{#header_close#} {#header_open|@sqrt#} -
@sqrt(comptime T: type, value: T) -> T
+
@sqrt(comptime T: type, value: T) T

Performs the square root of a floating point number. Uses a dedicated hardware instruction when available. Currently only supports f32 and f64 at runtime. f128 at runtime is TODO. @@ -4838,7 +4838,7 @@ pub const FloatMode = enum {

{#header_close#} {#header_open|@subWithOverflow#} -
@subWithOverflow(comptime T: type, a: T, b: T, result: &T) -> bool
+
@subWithOverflow(comptime T: type, a: T, b: T, result: *T) bool

Performs result.* = a - b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. @@ -4846,7 +4846,7 @@ pub const FloatMode = enum {

{#header_close#} {#header_open|@truncate#} -
@truncate(comptime T: type, integer) -> T
+
@truncate(comptime T: type, integer) T

This function truncates bits from an integer type, resulting in a smaller integer type. @@ -4870,7 +4870,7 @@ const b: u8 = @truncate(u8, a); {#header_close#} {#header_open|@typeId#} -

@typeId(comptime T: type) -> @import("builtin").TypeId
+
@typeId(comptime T: type) @import("builtin").TypeId

Returns which kind of type something is. Possible values:

@@ -4904,7 +4904,7 @@ pub const TypeId = enum { {#code_end#} {#header_close#} {#header_open|@typeInfo#} -
@typeInfo(comptime T: type) -> @import("builtin").TypeInfo
+
@typeInfo(comptime T: type) @import("builtin").TypeInfo

Returns information on the type. Returns a value of the following union:

@@ -5080,14 +5080,14 @@ pub const TypeInfo = union(TypeId) { {#code_end#} {#header_close#} {#header_open|@typeName#} -
@typeName(T: type) -> []u8
+
@typeName(T: type) []u8

This function returns the string representation of a type.

{#header_close#} {#header_open|@typeOf#} -
@typeOf(expression) -> type
+
@typeOf(expression) type

This function returns a compile-time constant, which is the type of the expression passed as an argument. The expression is evaluated. @@ -5937,7 +5937,7 @@ pub const __zig_test_fn_slice = {}; // overwritten later {#header_open|C String Literals#} {#code_begin|exe#} {#link_libc#} -extern fn puts(&const u8) void; +extern fn puts(*const u8) void; pub fn main() void { puts(c"this has a null terminator"); @@ -5996,8 +5996,8 @@ const c = @cImport({ {#code_begin|syntax#} const base64 = @import("std").base64; -export fn decode_base_64(dest_ptr: &u8, dest_len: usize, - source_ptr: &const u8, source_len: usize) usize +export fn decode_base_64(dest_ptr: *u8, dest_len: usize, + source_ptr: *const u8, source_len: usize) usize { const src = source_ptr[0..source_len]; const dest = dest_ptr[0..dest_len]; @@ -6028,7 +6028,7 @@ int main(int argc, char **argv) { {#code_begin|syntax#} const Builder = @import("std").build.Builder; -pub fn build(b: &Builder) void { +pub fn build(b: *Builder) void { const obj = b.addObject("base64", "base64.zig"); const exe = b.addCExecutable("test"); diff --git a/example/cat/main.zig b/example/cat/main.zig index de0d323bed..1b34cb22eb 100644 --- a/example/cat/main.zig +++ b/example/cat/main.zig @@ -41,7 +41,7 @@ fn usage(exe: []const u8) !void { return error.Invalid; } -fn cat_file(stdout: &os.File, file: &os.File) !void { +fn cat_file(stdout: *os.File, file: *os.File) !void { var buf: [1024 * 4]u8 = undefined; while (true) { diff --git a/example/hello_world/hello_libc.zig b/example/hello_world/hello_libc.zig index 1df8f04ce4..f64beda40f 100644 --- a/example/hello_world/hello_libc.zig +++ b/example/hello_world/hello_libc.zig @@ -7,7 +7,7 @@ const c = @cImport({ const msg = c"Hello, world!\n"; -export fn main(argc: c_int, argv: &&u8) c_int { +export fn main(argc: c_int, argv: **u8) c_int { if (c.printf(msg) != c_int(c.strlen(msg))) return -1; return 0; diff --git a/example/mix_o_files/base64.zig b/example/mix_o_files/base64.zig index e682a97055..35b090825b 100644 --- a/example/mix_o_files/base64.zig +++ b/example/mix_o_files/base64.zig @@ -1,6 +1,6 @@ const base64 = @import("std").base64; -export fn decode_base_64(dest_ptr: &u8, dest_len: usize, source_ptr: &const u8, source_len: usize) usize { +export fn decode_base_64(dest_ptr: *u8, dest_len: usize, source_ptr: *const u8, source_len: usize) usize { const src = source_ptr[0..source_len]; const dest = dest_ptr[0..dest_len]; const base64_decoder = base64.standard_decoder_unsafe; diff --git a/example/mix_o_files/build.zig b/example/mix_o_files/build.zig index e5d2e6a446..a4e7fbbf8f 100644 --- a/example/mix_o_files/build.zig +++ b/example/mix_o_files/build.zig @@ -1,6 +1,6 @@ const Builder = @import("std").build.Builder; -pub fn build(b: &Builder) void { +pub fn build(b: *Builder) void { const obj = b.addObject("base64", "base64.zig"); const exe = b.addCExecutable("test"); diff --git a/example/shared_library/build.zig b/example/shared_library/build.zig index 30c714c6c6..05648cf9eb 100644 --- a/example/shared_library/build.zig +++ b/example/shared_library/build.zig @@ -1,6 +1,6 @@ const Builder = @import("std").build.Builder; -pub fn build(b: &Builder) void { +pub fn build(b: *Builder) void { const lib = b.addSharedLibrary("mathtest", "mathtest.zig", b.version(1, 0, 0)); const exe = b.addCExecutable("test"); diff --git a/src-self-hosted/arg.zig b/src-self-hosted/arg.zig index fa2166e3a5..df2c04ef1f 100644 --- a/src-self-hosted/arg.zig +++ b/src-self-hosted/arg.zig @@ -30,7 +30,7 @@ fn argInAllowedSet(maybe_set: ?[]const []const u8, arg: []const u8) bool { } // Modifies the current argument index during iteration -fn readFlagArguments(allocator: &Allocator, args: []const []const u8, required: usize, allowed_set: ?[]const []const u8, index: &usize) !FlagArg { +fn readFlagArguments(allocator: *Allocator, args: []const []const u8, required: usize, allowed_set: ?[]const []const u8, index: *usize) !FlagArg { switch (required) { 0 => return FlagArg{ .None = undefined }, // TODO: Required to force non-tag but value? 1 => { @@ -79,7 +79,7 @@ pub const Args = struct { flags: HashMapFlags, positionals: ArrayList([]const u8), - pub fn parse(allocator: &Allocator, comptime spec: []const Flag, args: []const []const u8) !Args { + pub fn parse(allocator: *Allocator, comptime spec: []const Flag, args: []const []const u8) !Args { var parsed = Args{ .flags = HashMapFlags.init(allocator), .positionals = ArrayList([]const u8).init(allocator), @@ -143,18 +143,18 @@ pub const Args = struct { return parsed; } - pub fn deinit(self: &Args) void { + pub fn deinit(self: *Args) void { self.flags.deinit(); self.positionals.deinit(); } // e.g. --help - pub fn present(self: &Args, name: []const u8) bool { + pub fn present(self: *Args, name: []const u8) bool { return self.flags.contains(name); } // e.g. --name value - pub fn single(self: &Args, name: []const u8) ?[]const u8 { + pub fn single(self: *Args, name: []const u8) ?[]const u8 { if (self.flags.get(name)) |entry| { switch (entry.value) { FlagArg.Single => |inner| { @@ -168,7 +168,7 @@ pub const Args = struct { } // e.g. --names value1 value2 value3 - pub fn many(self: &Args, name: []const u8) ?[]const []const u8 { + pub fn many(self: *Args, name: []const u8) ?[]const []const u8 { if (self.flags.get(name)) |entry| { switch (entry.value) { FlagArg.Many => |inner| { diff --git a/src-self-hosted/errmsg.zig b/src-self-hosted/errmsg.zig index 9905b8e3a6..32d2450aac 100644 --- a/src-self-hosted/errmsg.zig +++ b/src-self-hosted/errmsg.zig @@ -16,18 +16,18 @@ pub const Msg = struct { text: []u8, first_token: TokenIndex, last_token: TokenIndex, - tree: &ast.Tree, + tree: *ast.Tree, }; /// `path` must outlive the returned Msg /// `tree` must outlive the returned Msg /// Caller owns returned Msg and must free with `allocator` pub fn createFromParseError( - allocator: &mem.Allocator, - parse_error: &const ast.Error, - tree: &ast.Tree, + allocator: *mem.Allocator, + parse_error: *const ast.Error, + tree: *ast.Tree, path: []const u8, -) !&Msg { +) !*Msg { const loc_token = parse_error.loc(); var text_buf = try std.Buffer.initSize(allocator, 0); defer text_buf.deinit(); @@ -47,7 +47,7 @@ pub fn createFromParseError( return msg; } -pub fn printToStream(stream: var, msg: &const Msg, color_on: bool) !void { +pub fn printToStream(stream: var, msg: *const Msg, color_on: bool) !void { const first_token = msg.tree.tokens.at(msg.first_token); const last_token = msg.tree.tokens.at(msg.last_token); const start_loc = msg.tree.tokenLocationPtr(0, first_token); @@ -76,7 +76,7 @@ pub fn printToStream(stream: var, msg: &const Msg, color_on: bool) !void { try stream.write("\n"); } -pub fn printToFile(file: &os.File, msg: &const Msg, color: Color) !void { +pub fn printToFile(file: *os.File, msg: *const Msg, color: Color) !void { const color_on = switch (color) { Color.Auto => file.isTty(), Color.On => true, diff --git a/src-self-hosted/introspect.zig b/src-self-hosted/introspect.zig index adab00286b..56b56c0c78 100644 --- a/src-self-hosted/introspect.zig +++ b/src-self-hosted/introspect.zig @@ -7,7 +7,7 @@ const os = std.os; const warn = std.debug.warn; /// Caller must free result -pub fn testZigInstallPrefix(allocator: &mem.Allocator, test_path: []const u8) ![]u8 { +pub fn testZigInstallPrefix(allocator: *mem.Allocator, test_path: []const u8) ![]u8 { const test_zig_dir = try os.path.join(allocator, test_path, "lib", "zig"); errdefer allocator.free(test_zig_dir); @@ -21,7 +21,7 @@ pub fn testZigInstallPrefix(allocator: &mem.Allocator, test_path: []const u8) ![ } /// Caller must free result -pub fn findZigLibDir(allocator: &mem.Allocator) ![]u8 { +pub fn findZigLibDir(allocator: *mem.Allocator) ![]u8 { const self_exe_path = try os.selfExeDirPath(allocator); defer allocator.free(self_exe_path); @@ -42,7 +42,7 @@ pub fn findZigLibDir(allocator: &mem.Allocator) ![]u8 { return error.FileNotFound; } -pub fn resolveZigLibDir(allocator: &mem.Allocator) ![]u8 { +pub fn resolveZigLibDir(allocator: *mem.Allocator) ![]u8 { return findZigLibDir(allocator) catch |err| { warn( \\Unable to find zig lib directory: {}. diff --git a/src-self-hosted/ir.zig b/src-self-hosted/ir.zig index c4550b5179..3334d9511b 100644 --- a/src-self-hosted/ir.zig +++ b/src-self-hosted/ir.zig @@ -2,7 +2,7 @@ const Scope = @import("scope.zig").Scope; pub const Instruction = struct { id: Id, - scope: &Scope, + scope: *Scope, pub const Id = enum { Br, diff --git a/src-self-hosted/main.zig b/src-self-hosted/main.zig index 71838503b7..80b1c3889a 100644 --- a/src-self-hosted/main.zig +++ b/src-self-hosted/main.zig @@ -18,8 +18,8 @@ const Target = @import("target.zig").Target; const errmsg = @import("errmsg.zig"); var stderr_file: os.File = undefined; -var stderr: &io.OutStream(io.FileOutStream.Error) = undefined; -var stdout: &io.OutStream(io.FileOutStream.Error) = undefined; +var stderr: *io.OutStream(io.FileOutStream.Error) = undefined; +var stdout: *io.OutStream(io.FileOutStream.Error) = undefined; const usage = \\usage: zig [command] [options] @@ -43,7 +43,7 @@ const usage = const Command = struct { name: []const u8, - exec: fn (&Allocator, []const []const u8) error!void, + exec: fn (*Allocator, []const []const u8) error!void, }; pub fn main() !void { @@ -191,7 +191,7 @@ const missing_build_file = \\ ; -fn cmdBuild(allocator: &Allocator, args: []const []const u8) !void { +fn cmdBuild(allocator: *Allocator, args: []const []const u8) !void { var flags = try Args.parse(allocator, args_build_spec, args); defer flags.deinit(); @@ -426,7 +426,7 @@ const args_build_generic = []Flag{ Flag.Arg1("--ver-patch"), }; -fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: Module.Kind) !void { +fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Module.Kind) !void { var flags = try Args.parse(allocator, args_build_generic, args); defer flags.deinit(); @@ -661,19 +661,19 @@ fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: Mo try stderr.print("building {}: {}\n", @tagName(out_type), in_file); } -fn cmdBuildExe(allocator: &Allocator, args: []const []const u8) !void { +fn cmdBuildExe(allocator: *Allocator, args: []const []const u8) !void { try buildOutputType(allocator, args, Module.Kind.Exe); } // cmd:build-lib /////////////////////////////////////////////////////////////////////////////////// -fn cmdBuildLib(allocator: &Allocator, args: []const []const u8) !void { +fn cmdBuildLib(allocator: *Allocator, args: []const []const u8) !void { try buildOutputType(allocator, args, Module.Kind.Lib); } // cmd:build-obj /////////////////////////////////////////////////////////////////////////////////// -fn cmdBuildObj(allocator: &Allocator, args: []const []const u8) !void { +fn cmdBuildObj(allocator: *Allocator, args: []const []const u8) !void { try buildOutputType(allocator, args, Module.Kind.Obj); } @@ -700,7 +700,7 @@ const args_fmt_spec = []Flag{ }), }; -fn cmdFmt(allocator: &Allocator, args: []const []const u8) !void { +fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void { var flags = try Args.parse(allocator, args_fmt_spec, args); defer flags.deinit(); @@ -768,7 +768,7 @@ fn cmdFmt(allocator: &Allocator, args: []const []const u8) !void { // cmd:targets ///////////////////////////////////////////////////////////////////////////////////// -fn cmdTargets(allocator: &Allocator, args: []const []const u8) !void { +fn cmdTargets(allocator: *Allocator, args: []const []const u8) !void { try stdout.write("Architectures:\n"); { comptime var i: usize = 0; @@ -810,7 +810,7 @@ fn cmdTargets(allocator: &Allocator, args: []const []const u8) !void { // cmd:version ///////////////////////////////////////////////////////////////////////////////////// -fn cmdVersion(allocator: &Allocator, args: []const []const u8) !void { +fn cmdVersion(allocator: *Allocator, args: []const []const u8) !void { try stdout.print("{}\n", std.cstr.toSliceConst(c.ZIG_VERSION_STRING)); } @@ -827,7 +827,7 @@ const usage_test = const args_test_spec = []Flag{Flag.Bool("--help")}; -fn cmdTest(allocator: &Allocator, args: []const []const u8) !void { +fn cmdTest(allocator: *Allocator, args: []const []const u8) !void { var flags = try Args.parse(allocator, args_build_spec, args); defer flags.deinit(); @@ -862,7 +862,7 @@ const usage_run = const args_run_spec = []Flag{Flag.Bool("--help")}; -fn cmdRun(allocator: &Allocator, args: []const []const u8) !void { +fn cmdRun(allocator: *Allocator, args: []const []const u8) !void { var compile_args = args; var runtime_args: []const []const u8 = []const []const u8{}; @@ -912,7 +912,7 @@ const args_translate_c_spec = []Flag{ Flag.Arg1("--output"), }; -fn cmdTranslateC(allocator: &Allocator, args: []const []const u8) !void { +fn cmdTranslateC(allocator: *Allocator, args: []const []const u8) !void { var flags = try Args.parse(allocator, args_translate_c_spec, args); defer flags.deinit(); @@ -958,7 +958,7 @@ fn cmdTranslateC(allocator: &Allocator, args: []const []const u8) !void { // cmd:help //////////////////////////////////////////////////////////////////////////////////////// -fn cmdHelp(allocator: &Allocator, args: []const []const u8) !void { +fn cmdHelp(allocator: *Allocator, args: []const []const u8) !void { try stderr.write(usage); } @@ -981,7 +981,7 @@ const info_zen = \\ ; -fn cmdZen(allocator: &Allocator, args: []const []const u8) !void { +fn cmdZen(allocator: *Allocator, args: []const []const u8) !void { try stdout.write(info_zen); } @@ -996,7 +996,7 @@ const usage_internal = \\ ; -fn cmdInternal(allocator: &Allocator, args: []const []const u8) !void { +fn cmdInternal(allocator: *Allocator, args: []const []const u8) !void { if (args.len == 0) { try stderr.write(usage_internal); os.exit(1); @@ -1018,7 +1018,7 @@ fn cmdInternal(allocator: &Allocator, args: []const []const u8) !void { try stderr.write(usage_internal); } -fn cmdInternalBuildInfo(allocator: &Allocator, args: []const []const u8) !void { +fn cmdInternalBuildInfo(allocator: *Allocator, args: []const []const u8) !void { try stdout.print( \\ZIG_CMAKE_BINARY_DIR {} \\ZIG_CXX_COMPILER {} diff --git a/src-self-hosted/module.zig b/src-self-hosted/module.zig index 61834eab66..a7ddf3f9e9 100644 --- a/src-self-hosted/module.zig +++ b/src-self-hosted/module.zig @@ -13,7 +13,7 @@ const ArrayList = std.ArrayList; const errmsg = @import("errmsg.zig"); pub const Module = struct { - allocator: &mem.Allocator, + allocator: *mem.Allocator, name: Buffer, root_src_path: ?[]const u8, module: llvm.ModuleRef, @@ -53,8 +53,8 @@ pub const Module = struct { windows_subsystem_windows: bool, windows_subsystem_console: bool, - link_libs_list: ArrayList(&LinkLib), - libc_link_lib: ?&LinkLib, + link_libs_list: ArrayList(*LinkLib), + libc_link_lib: ?*LinkLib, err_color: errmsg.Color, @@ -106,19 +106,19 @@ pub const Module = struct { pub const CliPkg = struct { name: []const u8, path: []const u8, - children: ArrayList(&CliPkg), - parent: ?&CliPkg, + children: ArrayList(*CliPkg), + parent: ?*CliPkg, - pub fn init(allocator: &mem.Allocator, name: []const u8, path: []const u8, parent: ?&CliPkg) !&CliPkg { + pub fn init(allocator: *mem.Allocator, name: []const u8, path: []const u8, parent: ?*CliPkg) !*CliPkg { var pkg = try allocator.create(CliPkg); pkg.name = name; pkg.path = path; - pkg.children = ArrayList(&CliPkg).init(allocator); + pkg.children = ArrayList(*CliPkg).init(allocator); pkg.parent = parent; return pkg; } - pub fn deinit(self: &CliPkg) void { + pub fn deinit(self: *CliPkg) void { for (self.children.toSliceConst()) |child| { child.deinit(); } @@ -126,7 +126,7 @@ pub const Module = struct { } }; - 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 { + 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 { var name_buffer = try Buffer.init(allocator, name); errdefer name_buffer.deinit(); @@ -188,7 +188,7 @@ pub const Module = struct { .link_objects = [][]const u8{}, .windows_subsystem_windows = false, .windows_subsystem_console = false, - .link_libs_list = ArrayList(&LinkLib).init(allocator), + .link_libs_list = ArrayList(*LinkLib).init(allocator), .libc_link_lib = null, .err_color = errmsg.Color.Auto, .darwin_frameworks = [][]const u8{}, @@ -200,11 +200,11 @@ pub const Module = struct { return module_ptr; } - fn dump(self: &Module) void { + fn dump(self: *Module) void { c.LLVMDumpModule(self.module); } - pub fn destroy(self: &Module) void { + pub fn destroy(self: *Module) void { c.LLVMDisposeBuilder(self.builder); c.LLVMDisposeModule(self.module); c.LLVMContextDispose(self.context); @@ -213,7 +213,7 @@ pub const Module = struct { self.allocator.destroy(self); } - pub fn build(self: &Module) !void { + pub fn build(self: *Module) !void { if (self.llvm_argv.len != 0) { var c_compatible_args = try std.cstr.NullTerminated2DArray.fromSlices(self.allocator, [][]const []const u8{ [][]const u8{"zig (LLVM option parsing)"}, @@ -259,12 +259,12 @@ pub const Module = struct { self.dump(); } - pub fn link(self: &Module, out_file: ?[]const u8) !void { + pub fn link(self: *Module, out_file: ?[]const u8) !void { warn("TODO link"); return error.Todo; } - pub fn addLinkLib(self: &Module, name: []const u8, provided_explicitly: bool) !&LinkLib { + pub fn addLinkLib(self: *Module, name: []const u8, provided_explicitly: bool) !*LinkLib { const is_libc = mem.eql(u8, name, "c"); if (is_libc) { diff --git a/src-self-hosted/scope.zig b/src-self-hosted/scope.zig index 05e586daae..b73dcb4ed3 100644 --- a/src-self-hosted/scope.zig +++ b/src-self-hosted/scope.zig @@ -1,6 +1,6 @@ pub const Scope = struct { id: Id, - parent: &Scope, + parent: *Scope, pub const Id = enum { Decls, diff --git a/src-self-hosted/target.zig b/src-self-hosted/target.zig index 7983a3ddec..724d99ea23 100644 --- a/src-self-hosted/target.zig +++ b/src-self-hosted/target.zig @@ -11,7 +11,7 @@ pub const Target = union(enum) { Native, Cross: CrossTarget, - pub fn oFileExt(self: &const Target) []const u8 { + pub fn oFileExt(self: *const Target) []const u8 { const environ = switch (self.*) { Target.Native => builtin.environ, Target.Cross => |t| t.environ, @@ -22,28 +22,28 @@ pub const Target = union(enum) { }; } - pub fn exeFileExt(self: &const Target) []const u8 { + pub fn exeFileExt(self: *const Target) []const u8 { return switch (self.getOs()) { builtin.Os.windows => ".exe", else => "", }; } - pub fn getOs(self: &const Target) builtin.Os { + pub fn getOs(self: *const Target) builtin.Os { return switch (self.*) { Target.Native => builtin.os, Target.Cross => |t| t.os, }; } - pub fn isDarwin(self: &const Target) bool { + pub fn isDarwin(self: *const Target) bool { return switch (self.getOs()) { builtin.Os.ios, builtin.Os.macosx => true, else => false, }; } - pub fn isWindows(self: &const Target) bool { + pub fn isWindows(self: *const Target) bool { return switch (self.getOs()) { builtin.Os.windows => true, else => false, diff --git a/src/all_types.hpp b/src/all_types.hpp index 9c156fb58b..b9199c2757 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -374,7 +374,7 @@ enum NodeType { NodeTypeCharLiteral, NodeTypeSymbol, NodeTypePrefixOpExpr, - NodeTypeAddrOfExpr, + NodeTypePointerType, NodeTypeFnCallExpr, NodeTypeArrayAccessExpr, NodeTypeSliceExpr, @@ -616,6 +616,7 @@ enum PrefixOp { PrefixOpNegationWrap, PrefixOpMaybe, PrefixOpUnwrapMaybe, + PrefixOpAddrOf, }; struct AstNodePrefixOpExpr { @@ -623,7 +624,7 @@ struct AstNodePrefixOpExpr { AstNode *primary_expr; }; -struct AstNodeAddrOfExpr { +struct AstNodePointerType { AstNode *align_expr; BigInt *bit_offset_start; BigInt *bit_offset_end; @@ -899,7 +900,7 @@ struct AstNode { AstNodeBinOpExpr bin_op_expr; AstNodeCatchExpr unwrap_err_expr; AstNodePrefixOpExpr prefix_op_expr; - AstNodeAddrOfExpr addr_of_expr; + AstNodePointerType pointer_type; AstNodeFnCallExpr fn_call_expr; AstNodeArrayAccessExpr array_access_expr; AstNodeSliceExpr slice_expr; @@ -2053,7 +2054,7 @@ enum IrInstructionId { IrInstructionIdTypeInfo, IrInstructionIdTypeId, IrInstructionIdSetEvalBranchQuota, - IrInstructionIdPtrTypeOf, + IrInstructionIdPtrType, IrInstructionIdAlignCast, IrInstructionIdOpaqueType, IrInstructionIdSetAlignStack, @@ -2412,6 +2413,17 @@ struct IrInstructionArrayType { IrInstruction *child_type; }; +struct IrInstructionPtrType { + IrInstruction base; + + IrInstruction *align_value; + IrInstruction *child_type; + uint32_t bit_offset_start; + uint32_t bit_offset_end; + bool is_const; + bool is_volatile; +}; + struct IrInstructionPromiseType { IrInstruction base; @@ -2891,17 +2903,6 @@ struct IrInstructionSetEvalBranchQuota { IrInstruction *new_quota; }; -struct IrInstructionPtrTypeOf { - IrInstruction base; - - IrInstruction *align_value; - IrInstruction *child_type; - uint32_t bit_offset_start; - uint32_t bit_offset_end; - bool is_const; - bool is_volatile; -}; - struct IrInstructionAlignCast { IrInstruction base; diff --git a/src/analyze.cpp b/src/analyze.cpp index b00e18a9a1..a5011035c5 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -418,12 +418,12 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type const char *volatile_str = is_volatile ? "volatile " : ""; buf_resize(&entry->name, 0); if (unaligned_bit_count == 0 && byte_alignment == abi_alignment) { - buf_appendf(&entry->name, "&%s%s%s", const_str, volatile_str, buf_ptr(&child_type->name)); + buf_appendf(&entry->name, "*%s%s%s", const_str, volatile_str, buf_ptr(&child_type->name)); } else if (unaligned_bit_count == 0) { - buf_appendf(&entry->name, "&align(%" PRIu32 ") %s%s%s", byte_alignment, + buf_appendf(&entry->name, "*align(%" PRIu32 ") %s%s%s", byte_alignment, const_str, volatile_str, buf_ptr(&child_type->name)); } else { - buf_appendf(&entry->name, "&align(%" PRIu32 ":%" PRIu32 ":%" PRIu32 ") %s%s%s", byte_alignment, + buf_appendf(&entry->name, "*align(%" PRIu32 ":%" PRIu32 ":%" PRIu32 ") %s%s%s", byte_alignment, bit_offset, bit_offset + unaligned_bit_count, const_str, volatile_str, buf_ptr(&child_type->name)); } @@ -3270,7 +3270,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) { case NodeTypeThisLiteral: case NodeTypeSymbol: case NodeTypePrefixOpExpr: - case NodeTypeAddrOfExpr: + case NodeTypePointerType: case NodeTypeIfBoolExpr: case NodeTypeWhileExpr: case NodeTypeForExpr: diff --git a/src/ast_render.cpp b/src/ast_render.cpp index 5a1e81b36d..f356f406b0 100644 --- a/src/ast_render.cpp +++ b/src/ast_render.cpp @@ -68,6 +68,7 @@ static const char *prefix_op_str(PrefixOp prefix_op) { case PrefixOpBinNot: return "~"; case PrefixOpMaybe: return "?"; case PrefixOpUnwrapMaybe: return "??"; + case PrefixOpAddrOf: return "&"; } zig_unreachable(); } @@ -185,8 +186,6 @@ static const char *node_type_str(NodeType node_type) { return "Symbol"; case NodeTypePrefixOpExpr: return "PrefixOpExpr"; - case NodeTypeAddrOfExpr: - return "AddrOfExpr"; case NodeTypeUse: return "Use"; case NodeTypeBoolLiteral: @@ -251,6 +250,8 @@ static const char *node_type_str(NodeType node_type) { return "Suspend"; case NodeTypePromiseType: return "PromiseType"; + case NodeTypePointerType: + return "PointerType"; } zig_unreachable(); } @@ -616,41 +617,41 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) { fprintf(ar->f, "%s", prefix_op_str(op)); AstNode *child_node = node->data.prefix_op_expr.primary_expr; - bool new_grouped = child_node->type == NodeTypePrefixOpExpr || child_node->type == NodeTypeAddrOfExpr; + bool new_grouped = child_node->type == NodeTypePrefixOpExpr || child_node->type == NodeTypePointerType; render_node_extra(ar, child_node, new_grouped); if (!grouped) fprintf(ar->f, ")"); break; } - case NodeTypeAddrOfExpr: + case NodeTypePointerType: { if (!grouped) fprintf(ar->f, "("); - fprintf(ar->f, "&"); - if (node->data.addr_of_expr.align_expr != nullptr) { + fprintf(ar->f, "*"); + if (node->data.pointer_type.align_expr != nullptr) { fprintf(ar->f, "align("); - render_node_grouped(ar, node->data.addr_of_expr.align_expr); - if (node->data.addr_of_expr.bit_offset_start != nullptr) { - assert(node->data.addr_of_expr.bit_offset_end != nullptr); + render_node_grouped(ar, node->data.pointer_type.align_expr); + if (node->data.pointer_type.bit_offset_start != nullptr) { + assert(node->data.pointer_type.bit_offset_end != nullptr); Buf offset_start_buf = BUF_INIT; buf_resize(&offset_start_buf, 0); - bigint_append_buf(&offset_start_buf, node->data.addr_of_expr.bit_offset_start, 10); + bigint_append_buf(&offset_start_buf, node->data.pointer_type.bit_offset_start, 10); Buf offset_end_buf = BUF_INIT; buf_resize(&offset_end_buf, 0); - bigint_append_buf(&offset_end_buf, node->data.addr_of_expr.bit_offset_end, 10); + bigint_append_buf(&offset_end_buf, node->data.pointer_type.bit_offset_end, 10); fprintf(ar->f, ":%s:%s ", buf_ptr(&offset_start_buf), buf_ptr(&offset_end_buf)); } fprintf(ar->f, ") "); } - if (node->data.addr_of_expr.is_const) { + if (node->data.pointer_type.is_const) { fprintf(ar->f, "const "); } - if (node->data.addr_of_expr.is_volatile) { + if (node->data.pointer_type.is_volatile) { fprintf(ar->f, "volatile "); } - render_node_ungrouped(ar, node->data.addr_of_expr.op_expr); + render_node_ungrouped(ar, node->data.pointer_type.op_expr); if (!grouped) fprintf(ar->f, ")"); break; } @@ -669,7 +670,7 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) { fprintf(ar->f, " "); } AstNode *fn_ref_node = node->data.fn_call_expr.fn_ref_expr; - bool grouped = (fn_ref_node->type != NodeTypePrefixOpExpr && fn_ref_node->type != NodeTypeAddrOfExpr); + bool grouped = (fn_ref_node->type != NodeTypePrefixOpExpr && fn_ref_node->type != NodeTypePointerType); render_node_extra(ar, fn_ref_node, grouped); fprintf(ar->f, "("); for (size_t i = 0; i < node->data.fn_call_expr.params.length; i += 1) { diff --git a/src/codegen.cpp b/src/codegen.cpp index 69542b3e67..d07d427729 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -4600,7 +4600,7 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable, case IrInstructionIdTypeInfo: case IrInstructionIdTypeId: case IrInstructionIdSetEvalBranchQuota: - case IrInstructionIdPtrTypeOf: + case IrInstructionIdPtrType: case IrInstructionIdOpaqueType: case IrInstructionIdSetAlignStack: case IrInstructionIdArgType: diff --git a/src/ir.cpp b/src/ir.cpp index 6e944a8976..b1fac9f485 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -41,10 +41,6 @@ struct IrAnalyze { static const LVal LVAL_NONE = { false, false, false }; static const LVal LVAL_PTR = { true, false, false }; -static LVal make_lval_addr(bool is_const, bool is_volatile) { - return { true, is_const, is_volatile }; -} - enum ConstCastResultId { ConstCastResultIdOk, ConstCastResultIdErrSet, @@ -629,8 +625,8 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionSetEvalBranchQuo return IrInstructionIdSetEvalBranchQuota; } -static constexpr IrInstructionId ir_instruction_id(IrInstructionPtrTypeOf *) { - return IrInstructionIdPtrTypeOf; +static constexpr IrInstructionId ir_instruction_id(IrInstructionPtrType *) { + return IrInstructionIdPtrType; } static constexpr IrInstructionId ir_instruction_id(IrInstructionAlignCast *) { @@ -1196,11 +1192,11 @@ static IrInstruction *ir_build_br_from(IrBuilder *irb, IrInstruction *old_instru return new_instruction; } -static IrInstruction *ir_build_ptr_type_of(IrBuilder *irb, Scope *scope, AstNode *source_node, +static IrInstruction *ir_build_ptr_type(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *child_type, bool is_const, bool is_volatile, IrInstruction *align_value, uint32_t bit_offset_start, uint32_t bit_offset_end) { - IrInstructionPtrTypeOf *ptr_type_of_instruction = ir_build_instruction(irb, scope, source_node); + IrInstructionPtrType *ptr_type_of_instruction = ir_build_instruction(irb, scope, source_node); ptr_type_of_instruction->align_value = align_value; ptr_type_of_instruction->child_type = child_type; ptr_type_of_instruction->is_const = is_const; @@ -4609,14 +4605,8 @@ static IrInstruction *ir_gen_if_bool_expr(IrBuilder *irb, Scope *scope, AstNode } static IrInstruction *ir_gen_prefix_op_id_lval(IrBuilder *irb, Scope *scope, AstNode *node, IrUnOp op_id, LVal lval) { - AstNode *expr_node; - if (node->type == NodeTypePrefixOpExpr) { - expr_node = node->data.prefix_op_expr.primary_expr; - } else if (node->type == NodeTypePtrDeref) { - expr_node = node->data.ptr_deref_expr.target; - } else { - zig_unreachable(); - } + assert(node->type == NodeTypePrefixOpExpr); + AstNode *expr_node = node->data.prefix_op_expr.primary_expr; IrInstruction *value = ir_gen_node_extra(irb, expr_node, scope, lval); if (value == irb->codegen->invalid_instruction) @@ -4640,16 +4630,12 @@ static IrInstruction *ir_lval_wrap(IrBuilder *irb, Scope *scope, IrInstruction * return ir_build_ref(irb, scope, value->source_node, value, lval.is_const, lval.is_volatile); } -static IrInstruction *ir_gen_address_of(IrBuilder *irb, Scope *scope, AstNode *node) { - assert(node->type == NodeTypeAddrOfExpr); - bool is_const = node->data.addr_of_expr.is_const; - bool is_volatile = node->data.addr_of_expr.is_volatile; - AstNode *expr_node = node->data.addr_of_expr.op_expr; - AstNode *align_expr = node->data.addr_of_expr.align_expr; - - if (align_expr == nullptr && !is_const && !is_volatile) { - return ir_gen_node_extra(irb, expr_node, scope, make_lval_addr(is_const, is_volatile)); - } +static IrInstruction *ir_gen_pointer_type(IrBuilder *irb, Scope *scope, AstNode *node) { + assert(node->type == NodeTypePointerType); + bool is_const = node->data.pointer_type.is_const; + bool is_volatile = node->data.pointer_type.is_volatile; + AstNode *expr_node = node->data.pointer_type.op_expr; + AstNode *align_expr = node->data.pointer_type.align_expr; IrInstruction *align_value; if (align_expr != nullptr) { @@ -4665,27 +4651,27 @@ static IrInstruction *ir_gen_address_of(IrBuilder *irb, Scope *scope, AstNode *n return child_type; uint32_t bit_offset_start = 0; - if (node->data.addr_of_expr.bit_offset_start != nullptr) { - if (!bigint_fits_in_bits(node->data.addr_of_expr.bit_offset_start, 32, false)) { + if (node->data.pointer_type.bit_offset_start != nullptr) { + if (!bigint_fits_in_bits(node->data.pointer_type.bit_offset_start, 32, false)) { Buf *val_buf = buf_alloc(); - bigint_append_buf(val_buf, node->data.addr_of_expr.bit_offset_start, 10); + bigint_append_buf(val_buf, node->data.pointer_type.bit_offset_start, 10); exec_add_error_node(irb->codegen, irb->exec, node, buf_sprintf("value %s too large for u32 bit offset", buf_ptr(val_buf))); return irb->codegen->invalid_instruction; } - bit_offset_start = bigint_as_unsigned(node->data.addr_of_expr.bit_offset_start); + bit_offset_start = bigint_as_unsigned(node->data.pointer_type.bit_offset_start); } uint32_t bit_offset_end = 0; - if (node->data.addr_of_expr.bit_offset_end != nullptr) { - if (!bigint_fits_in_bits(node->data.addr_of_expr.bit_offset_end, 32, false)) { + if (node->data.pointer_type.bit_offset_end != nullptr) { + if (!bigint_fits_in_bits(node->data.pointer_type.bit_offset_end, 32, false)) { Buf *val_buf = buf_alloc(); - bigint_append_buf(val_buf, node->data.addr_of_expr.bit_offset_end, 10); + bigint_append_buf(val_buf, node->data.pointer_type.bit_offset_end, 10); exec_add_error_node(irb->codegen, irb->exec, node, buf_sprintf("value %s too large for u32 bit offset", buf_ptr(val_buf))); return irb->codegen->invalid_instruction; } - bit_offset_end = bigint_as_unsigned(node->data.addr_of_expr.bit_offset_end); + bit_offset_end = bigint_as_unsigned(node->data.pointer_type.bit_offset_end); } if ((bit_offset_start != 0 || bit_offset_end != 0) && bit_offset_start >= bit_offset_end) { @@ -4694,7 +4680,7 @@ static IrInstruction *ir_gen_address_of(IrBuilder *irb, Scope *scope, AstNode *n return irb->codegen->invalid_instruction; } - return ir_build_ptr_type_of(irb, scope, node, child_type, is_const, is_volatile, + return ir_build_ptr_type(irb, scope, node, child_type, is_const, is_volatile, align_value, bit_offset_start, bit_offset_end); } @@ -4761,6 +4747,10 @@ static IrInstruction *ir_gen_prefix_op_expr(IrBuilder *irb, Scope *scope, AstNod return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpMaybe), lval); case PrefixOpUnwrapMaybe: return ir_gen_maybe_assert_ok(irb, scope, node, lval); + case PrefixOpAddrOf: { + AstNode *expr_node = node->data.prefix_op_expr.primary_expr; + return ir_lval_wrap(irb, scope, ir_gen_node_extra(irb, expr_node, scope, LVAL_PTR), lval); + } } zig_unreachable(); } @@ -6568,8 +6558,6 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop return ir_lval_wrap(irb, scope, ir_gen_if_bool_expr(irb, scope, node), lval); case NodeTypePrefixOpExpr: return ir_gen_prefix_op_expr(irb, scope, node, lval); - case NodeTypeAddrOfExpr: - return ir_lval_wrap(irb, scope, ir_gen_address_of(irb, scope, node), lval); case NodeTypeContainerInitExpr: return ir_lval_wrap(irb, scope, ir_gen_container_init_expr(irb, scope, node), lval); case NodeTypeVariableDeclaration: @@ -6592,14 +6580,23 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop return ir_build_load_ptr(irb, scope, node, ptr_instruction); } - case NodeTypePtrDeref: - return ir_gen_prefix_op_id_lval(irb, scope, node, IrUnOpDereference, lval); + case NodeTypePtrDeref: { + assert(node->type == NodeTypePtrDeref); + AstNode *expr_node = node->data.ptr_deref_expr.target; + IrInstruction *value = ir_gen_node_extra(irb, expr_node, scope, lval); + if (value == irb->codegen->invalid_instruction) + return value; + + return ir_build_un_op(irb, scope, node, IrUnOpDereference, value); + } case NodeTypeThisLiteral: return ir_lval_wrap(irb, scope, ir_gen_this_literal(irb, scope, node), lval); case NodeTypeBoolLiteral: return ir_lval_wrap(irb, scope, ir_gen_bool_literal(irb, scope, node), lval); case NodeTypeArrayType: return ir_lval_wrap(irb, scope, ir_gen_array_type(irb, scope, node), lval); + case NodeTypePointerType: + return ir_lval_wrap(irb, scope, ir_gen_pointer_type(irb, scope, node), lval); case NodeTypePromiseType: return ir_lval_wrap(irb, scope, ir_gen_promise_type(irb, scope, node), lval); case NodeTypeStringLiteral: @@ -8961,6 +8958,7 @@ static IrInstruction *ir_get_const_ptr(IrAnalyze *ira, IrInstruction *instructio ConstExprValue *pointee, TypeTableEntry *pointee_type, ConstPtrMut ptr_mut, bool ptr_is_const, bool ptr_is_volatile, uint32_t ptr_align) { + // TODO remove this special case for types if (pointee_type->id == TypeTableEntryIdMetaType) { TypeTableEntry *type_entry = pointee->data.x_type; if (type_entry->id == TypeTableEntryIdUnreachable) { @@ -18778,11 +18776,16 @@ static TypeTableEntry *ir_analyze_instruction_ptr_to_int(IrAnalyze *ira, IrInstr return usize; } -static TypeTableEntry *ir_analyze_instruction_ptr_type_of(IrAnalyze *ira, IrInstructionPtrTypeOf *instruction) { +static TypeTableEntry *ir_analyze_instruction_ptr_type(IrAnalyze *ira, IrInstructionPtrType *instruction) { TypeTableEntry *child_type = ir_resolve_type(ira, instruction->child_type->other); if (type_is_invalid(child_type)) return ira->codegen->builtin_types.entry_invalid; + if (child_type->id == TypeTableEntryIdUnreachable) { + ir_add_error(ira, &instruction->base, buf_sprintf("pointer to noreturn not allowed")); + return ira->codegen->builtin_types.entry_invalid; + } + uint32_t align_bytes; if (instruction->align_value != nullptr) { if (!ir_resolve_align(ira, instruction->align_value->other, &align_bytes)) @@ -19606,8 +19609,8 @@ static TypeTableEntry *ir_analyze_instruction_nocast(IrAnalyze *ira, IrInstructi return ir_analyze_instruction_type_id(ira, (IrInstructionTypeId *)instruction); case IrInstructionIdSetEvalBranchQuota: return ir_analyze_instruction_set_eval_branch_quota(ira, (IrInstructionSetEvalBranchQuota *)instruction); - case IrInstructionIdPtrTypeOf: - return ir_analyze_instruction_ptr_type_of(ira, (IrInstructionPtrTypeOf *)instruction); + case IrInstructionIdPtrType: + return ir_analyze_instruction_ptr_type(ira, (IrInstructionPtrType *)instruction); case IrInstructionIdAlignCast: return ir_analyze_instruction_align_cast(ira, (IrInstructionAlignCast *)instruction); case IrInstructionIdOpaqueType: @@ -19783,7 +19786,7 @@ bool ir_has_side_effects(IrInstruction *instruction) { case IrInstructionIdCheckStatementIsVoid: case IrInstructionIdPanic: case IrInstructionIdSetEvalBranchQuota: - case IrInstructionIdPtrTypeOf: + case IrInstructionIdPtrType: case IrInstructionIdSetAlignStack: case IrInstructionIdExport: case IrInstructionIdCancel: diff --git a/src/ir_print.cpp b/src/ir_print.cpp index 9678120f1d..3c177a8bbf 100644 --- a/src/ir_print.cpp +++ b/src/ir_print.cpp @@ -921,7 +921,7 @@ static void ir_print_can_implicit_cast(IrPrint *irp, IrInstructionCanImplicitCas fprintf(irp->f, ")"); } -static void ir_print_ptr_type_of(IrPrint *irp, IrInstructionPtrTypeOf *instruction) { +static void ir_print_ptr_type(IrPrint *irp, IrInstructionPtrType *instruction) { fprintf(irp->f, "&"); if (instruction->align_value != nullptr) { fprintf(irp->f, "align("); @@ -1527,8 +1527,8 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) { case IrInstructionIdCanImplicitCast: ir_print_can_implicit_cast(irp, (IrInstructionCanImplicitCast *)instruction); break; - case IrInstructionIdPtrTypeOf: - ir_print_ptr_type_of(irp, (IrInstructionPtrTypeOf *)instruction); + case IrInstructionIdPtrType: + ir_print_ptr_type(irp, (IrInstructionPtrType *)instruction); break; case IrInstructionIdDeclRef: ir_print_decl_ref(irp, (IrInstructionDeclRef *)instruction); diff --git a/src/parser.cpp b/src/parser.cpp index 4763d3b987..ef390a3a2e 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -1167,20 +1167,19 @@ static PrefixOp tok_to_prefix_op(Token *token) { case TokenIdTilde: return PrefixOpBinNot; case TokenIdMaybe: return PrefixOpMaybe; case TokenIdDoubleQuestion: return PrefixOpUnwrapMaybe; + case TokenIdAmpersand: return PrefixOpAddrOf; default: return PrefixOpInvalid; } } -static AstNode *ast_parse_addr_of(ParseContext *pc, size_t *token_index) { - Token *ampersand_tok = ast_eat_token(pc, token_index, TokenIdAmpersand); - - AstNode *node = ast_create_node(pc, NodeTypeAddrOfExpr, ampersand_tok); +static AstNode *ast_parse_pointer_type(ParseContext *pc, size_t *token_index, Token *star_tok) { + AstNode *node = ast_create_node(pc, NodeTypePointerType, star_tok); Token *token = &pc->tokens->at(*token_index); if (token->id == TokenIdKeywordAlign) { *token_index += 1; ast_eat_token(pc, token_index, TokenIdLParen); - node->data.addr_of_expr.align_expr = ast_parse_expression(pc, token_index, true); + node->data.pointer_type.align_expr = ast_parse_expression(pc, token_index, true); token = &pc->tokens->at(*token_index); if (token->id == TokenIdColon) { @@ -1189,24 +1188,24 @@ static AstNode *ast_parse_addr_of(ParseContext *pc, size_t *token_index) { ast_eat_token(pc, token_index, TokenIdColon); Token *bit_offset_end_tok = ast_eat_token(pc, token_index, TokenIdIntLiteral); - node->data.addr_of_expr.bit_offset_start = token_bigint(bit_offset_start_tok); - node->data.addr_of_expr.bit_offset_end = token_bigint(bit_offset_end_tok); + node->data.pointer_type.bit_offset_start = token_bigint(bit_offset_start_tok); + node->data.pointer_type.bit_offset_end = token_bigint(bit_offset_end_tok); } ast_eat_token(pc, token_index, TokenIdRParen); token = &pc->tokens->at(*token_index); } if (token->id == TokenIdKeywordConst) { *token_index += 1; - node->data.addr_of_expr.is_const = true; + node->data.pointer_type.is_const = true; token = &pc->tokens->at(*token_index); } if (token->id == TokenIdKeywordVolatile) { *token_index += 1; - node->data.addr_of_expr.is_volatile = true; + node->data.pointer_type.is_volatile = true; } - node->data.addr_of_expr.op_expr = ast_parse_prefix_op_expr(pc, token_index, true); + node->data.pointer_type.op_expr = ast_parse_prefix_op_expr(pc, token_index, true); return node; } @@ -1216,8 +1215,17 @@ PrefixOp = "!" | "-" | "~" | ("*" option("align" "(" Expression option(":" Integ */ static AstNode *ast_parse_prefix_op_expr(ParseContext *pc, size_t *token_index, bool mandatory) { Token *token = &pc->tokens->at(*token_index); - if (token->id == TokenIdAmpersand) { - return ast_parse_addr_of(pc, token_index); + if (token->id == TokenIdStar) { + *token_index += 1; + return ast_parse_pointer_type(pc, token_index, token); + } + if (token->id == TokenIdStarStar) { + *token_index += 1; + AstNode *child_node = ast_parse_pointer_type(pc, token_index, token); + child_node->column += 1; + AstNode *parent_node = ast_create_node(pc, NodeTypePointerType, token); + parent_node->data.pointer_type.op_expr = child_node; + return parent_node; } if (token->id == TokenIdKeywordTry) { return ast_parse_try_expr(pc, token_index); @@ -1234,13 +1242,12 @@ static AstNode *ast_parse_prefix_op_expr(ParseContext *pc, size_t *token_index, AstNode *node = ast_create_node(pc, NodeTypePrefixOpExpr, token); - AstNode *parent_node = node; AstNode *prefix_op_expr = ast_parse_error_set_expr(pc, token_index, true); node->data.prefix_op_expr.primary_expr = prefix_op_expr; node->data.prefix_op_expr.prefix_op = prefix_op; - return parent_node; + return node; } @@ -3121,9 +3128,9 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont case NodeTypeErrorType: // none break; - case NodeTypeAddrOfExpr: - visit_field(&node->data.addr_of_expr.align_expr, visit, context); - visit_field(&node->data.addr_of_expr.op_expr, visit, context); + case NodeTypePointerType: + visit_field(&node->data.pointer_type.align_expr, visit, context); + visit_field(&node->data.pointer_type.op_expr, visit, context); break; case NodeTypeErrorSetDecl: visit_node_list(&node->data.err_set_decl.decls, visit, context); diff --git a/src/translate_c.cpp b/src/translate_c.cpp index 50ff073008..db541d34f3 100644 --- a/src/translate_c.cpp +++ b/src/translate_c.cpp @@ -276,11 +276,18 @@ static AstNode *maybe_suppress_result(Context *c, ResultUsed result_used, AstNod node); } -static AstNode *trans_create_node_addr_of(Context *c, bool is_const, bool is_volatile, AstNode *child_node) { - AstNode *node = trans_create_node(c, NodeTypeAddrOfExpr); - node->data.addr_of_expr.is_const = is_const; - node->data.addr_of_expr.is_volatile = is_volatile; - node->data.addr_of_expr.op_expr = child_node; +static AstNode *trans_create_node_ptr_type(Context *c, bool is_const, bool is_volatile, AstNode *child_node) { + AstNode *node = trans_create_node(c, NodeTypePointerType); + node->data.pointer_type.is_const = is_const; + node->data.pointer_type.is_volatile = is_volatile; + node->data.pointer_type.op_expr = child_node; + return node; +} + +static AstNode *trans_create_node_addr_of(Context *c, AstNode *child_node) { + AstNode *node = trans_create_node(c, NodeTypePrefixOpExpr); + node->data.prefix_op_expr.prefix_op = PrefixOpAddrOf; + node->data.prefix_op_expr.primary_expr = child_node; return node; } @@ -848,7 +855,7 @@ static AstNode *trans_type(Context *c, const Type *ty, const SourceLocation &sou return trans_create_node_prefix_op(c, PrefixOpMaybe, child_node); } - AstNode *pointer_node = trans_create_node_addr_of(c, child_qt.isConstQualified(), + AstNode *pointer_node = trans_create_node_ptr_type(c, child_qt.isConstQualified(), child_qt.isVolatileQualified(), child_node); return trans_create_node_prefix_op(c, PrefixOpMaybe, pointer_node); } @@ -1033,7 +1040,7 @@ static AstNode *trans_type(Context *c, const Type *ty, const SourceLocation &sou emit_warning(c, source_loc, "unresolved array element type"); return nullptr; } - AstNode *pointer_node = trans_create_node_addr_of(c, child_qt.isConstQualified(), + AstNode *pointer_node = trans_create_node_ptr_type(c, child_qt.isConstQualified(), child_qt.isVolatileQualified(), child_type_node); return pointer_node; } @@ -1402,7 +1409,7 @@ static AstNode *trans_create_compound_assign_shift(Context *c, ResultUsed result // const _ref = &lhs; AstNode *lhs = trans_expr(c, ResultUsedYes, &child_scope->base, stmt->getLHS(), TransLValue); if (lhs == nullptr) return nullptr; - AstNode *addr_of_lhs = trans_create_node_addr_of(c, false, false, lhs); + AstNode *addr_of_lhs = trans_create_node_addr_of(c, lhs); // TODO: avoid name collisions with generated variable names Buf* tmp_var_name = buf_create_from_str("_ref"); AstNode *tmp_var_decl = trans_create_node_var_decl_local(c, true, tmp_var_name, nullptr, addr_of_lhs); @@ -1476,7 +1483,7 @@ static AstNode *trans_create_compound_assign(Context *c, ResultUsed result_used, // const _ref = &lhs; AstNode *lhs = trans_expr(c, ResultUsedYes, &child_scope->base, stmt->getLHS(), TransLValue); if (lhs == nullptr) return nullptr; - AstNode *addr_of_lhs = trans_create_node_addr_of(c, false, false, lhs); + AstNode *addr_of_lhs = trans_create_node_addr_of(c, lhs); // TODO: avoid name collisions with generated variable names Buf* tmp_var_name = buf_create_from_str("_ref"); AstNode *tmp_var_decl = trans_create_node_var_decl_local(c, true, tmp_var_name, nullptr, addr_of_lhs); @@ -1813,7 +1820,7 @@ static AstNode *trans_create_post_crement(Context *c, ResultUsed result_used, Tr // const _ref = &expr; AstNode *expr = trans_expr(c, ResultUsedYes, &child_scope->base, op_expr, TransLValue); if (expr == nullptr) return nullptr; - AstNode *addr_of_expr = trans_create_node_addr_of(c, false, false, expr); + AstNode *addr_of_expr = trans_create_node_addr_of(c, expr); // TODO: avoid name collisions with generated variable names Buf* ref_var_name = buf_create_from_str("_ref"); AstNode *ref_var_decl = trans_create_node_var_decl_local(c, true, ref_var_name, nullptr, addr_of_expr); @@ -1868,7 +1875,7 @@ static AstNode *trans_create_pre_crement(Context *c, ResultUsed result_used, Tra // const _ref = &expr; AstNode *expr = trans_expr(c, ResultUsedYes, &child_scope->base, op_expr, TransLValue); if (expr == nullptr) return nullptr; - AstNode *addr_of_expr = trans_create_node_addr_of(c, false, false, expr); + AstNode *addr_of_expr = trans_create_node_addr_of(c, expr); // TODO: avoid name collisions with generated variable names Buf* ref_var_name = buf_create_from_str("_ref"); AstNode *ref_var_decl = trans_create_node_var_decl_local(c, true, ref_var_name, nullptr, addr_of_expr); @@ -1917,7 +1924,7 @@ static AstNode *trans_unary_operator(Context *c, ResultUsed result_used, TransSc AstNode *value_node = trans_expr(c, result_used, scope, stmt->getSubExpr(), TransLValue); if (value_node == nullptr) return value_node; - return trans_create_node_addr_of(c, false, false, value_node); + return trans_create_node_addr_of(c, value_node); } case UO_Deref: { @@ -4441,7 +4448,7 @@ static AstNode *parse_ctok_suffix_op_expr(Context *c, CTokenize *ctok, size_t *t } else if (first_tok->id == CTokIdAsterisk) { *tok_i += 1; - node = trans_create_node_addr_of(c, false, false, node); + node = trans_create_node_ptr_type(c, false, false, node); } else { return node; } diff --git a/std/array_list.zig b/std/array_list.zig index b315194c33..07a1db6451 100644 --- a/std/array_list.zig +++ b/std/array_list.zig @@ -17,10 +17,10 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { /// you uninitialized memory. items: []align(A) T, len: usize, - allocator: &Allocator, + allocator: *Allocator, /// Deinitialize with `deinit` or use `toOwnedSlice`. - pub fn init(allocator: &Allocator) Self { + pub fn init(allocator: *Allocator) Self { return Self{ .items = []align(A) T{}, .len = 0, @@ -28,30 +28,30 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { }; } - pub fn deinit(l: &const Self) void { + pub fn deinit(l: *const Self) void { l.allocator.free(l.items); } - pub fn toSlice(l: &const Self) []align(A) T { + pub fn toSlice(l: *const Self) []align(A) T { return l.items[0..l.len]; } - pub fn toSliceConst(l: &const Self) []align(A) const T { + pub fn toSliceConst(l: *const Self) []align(A) const T { return l.items[0..l.len]; } - pub fn at(l: &const Self, n: usize) T { + pub fn at(l: *const Self, n: usize) T { return l.toSliceConst()[n]; } - pub fn count(self: &const Self) usize { + pub fn count(self: *const Self) usize { return self.len; } /// ArrayList takes ownership of the passed in slice. The slice must have been /// allocated with `allocator`. /// Deinitialize with `deinit` or use `toOwnedSlice`. - pub fn fromOwnedSlice(allocator: &Allocator, slice: []align(A) T) Self { + pub fn fromOwnedSlice(allocator: *Allocator, slice: []align(A) T) Self { return Self{ .items = slice, .len = slice.len, @@ -60,14 +60,14 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { } /// The caller owns the returned memory. ArrayList becomes empty. - pub fn toOwnedSlice(self: &Self) []align(A) T { + pub fn toOwnedSlice(self: *Self) []align(A) T { const allocator = self.allocator; const result = allocator.alignedShrink(T, A, self.items, self.len); self.* = init(allocator); return result; } - pub fn insert(l: &Self, n: usize, item: &const T) !void { + pub fn insert(l: *Self, n: usize, item: *const T) !void { try l.ensureCapacity(l.len + 1); l.len += 1; @@ -75,7 +75,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { l.items[n] = item.*; } - pub fn insertSlice(l: &Self, n: usize, items: []align(A) const T) !void { + pub fn insertSlice(l: *Self, n: usize, items: []align(A) const T) !void { try l.ensureCapacity(l.len + items.len); l.len += items.len; @@ -83,28 +83,28 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { mem.copy(T, l.items[n .. n + items.len], items); } - pub fn append(l: &Self, item: &const T) !void { + pub fn append(l: *Self, item: *const T) !void { const new_item_ptr = try l.addOne(); new_item_ptr.* = item.*; } - pub fn appendSlice(l: &Self, items: []align(A) const T) !void { + pub fn appendSlice(l: *Self, items: []align(A) const T) !void { try l.ensureCapacity(l.len + items.len); mem.copy(T, l.items[l.len..], items); l.len += items.len; } - pub fn resize(l: &Self, new_len: usize) !void { + pub fn resize(l: *Self, new_len: usize) !void { try l.ensureCapacity(new_len); l.len = new_len; } - pub fn shrink(l: &Self, new_len: usize) void { + pub fn shrink(l: *Self, new_len: usize) void { assert(new_len <= l.len); l.len = new_len; } - pub fn ensureCapacity(l: &Self, new_capacity: usize) !void { + pub fn ensureCapacity(l: *Self, new_capacity: usize) !void { var better_capacity = l.items.len; if (better_capacity >= new_capacity) return; while (true) { @@ -114,7 +114,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { l.items = try l.allocator.alignedRealloc(T, A, l.items, better_capacity); } - pub fn addOne(l: &Self) !&T { + pub fn addOne(l: *Self) !*T { const new_length = l.len + 1; try l.ensureCapacity(new_length); const result = &l.items[l.len]; @@ -122,34 +122,34 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { return result; } - pub fn pop(self: &Self) T { + pub fn pop(self: *Self) T { self.len -= 1; return self.items[self.len]; } - pub fn popOrNull(self: &Self) ?T { + pub fn popOrNull(self: *Self) ?T { if (self.len == 0) return null; return self.pop(); } pub const Iterator = struct { - list: &const Self, + list: *const Self, // how many items have we returned count: usize, - pub fn next(it: &Iterator) ?T { + pub fn next(it: *Iterator) ?T { if (it.count >= it.list.len) return null; const val = it.list.at(it.count); it.count += 1; return val; } - pub fn reset(it: &Iterator) void { + pub fn reset(it: *Iterator) void { it.count = 0; } }; - pub fn iterator(self: &const Self) Iterator { + pub fn iterator(self: *const Self) Iterator { return Iterator{ .list = self, .count = 0, diff --git a/std/atomic/queue.zig b/std/atomic/queue.zig index 35180da8d1..142c958173 100644 --- a/std/atomic/queue.zig +++ b/std/atomic/queue.zig @@ -5,36 +5,36 @@ const AtomicRmwOp = builtin.AtomicRmwOp; /// Many reader, many writer, non-allocating, thread-safe, lock-free pub fn Queue(comptime T: type) type { return struct { - head: &Node, - tail: &Node, + head: *Node, + tail: *Node, root: Node, pub const Self = this; pub const Node = struct { - next: ?&Node, + next: ?*Node, data: T, }; // TODO: well defined copy elision: https://github.com/ziglang/zig/issues/287 - pub fn init(self: &Self) void { + pub fn init(self: *Self) void { self.root.next = null; self.head = &self.root; self.tail = &self.root; } - pub fn put(self: &Self, node: &Node) void { + pub fn put(self: *Self, node: *Node) void { node.next = null; - const tail = @atomicRmw(&Node, &self.tail, AtomicRmwOp.Xchg, node, AtomicOrder.SeqCst); - _ = @atomicRmw(?&Node, &tail.next, AtomicRmwOp.Xchg, node, AtomicOrder.SeqCst); + const tail = @atomicRmw(*Node, &self.tail, AtomicRmwOp.Xchg, node, AtomicOrder.SeqCst); + _ = @atomicRmw(?*Node, &tail.next, AtomicRmwOp.Xchg, node, AtomicOrder.SeqCst); } - pub fn get(self: &Self) ?&Node { - var head = @atomicLoad(&Node, &self.head, AtomicOrder.SeqCst); + pub fn get(self: *Self) ?*Node { + var head = @atomicLoad(*Node, &self.head, AtomicOrder.SeqCst); while (true) { const node = head.next ?? return null; - head = @cmpxchgWeak(&Node, &self.head, head, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return node; + head = @cmpxchgWeak(*Node, &self.head, head, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return node; } } }; @@ -42,8 +42,8 @@ pub fn Queue(comptime T: type) type { const std = @import("std"); const Context = struct { - allocator: &std.mem.Allocator, - queue: &Queue(i32), + allocator: *std.mem.Allocator, + queue: *Queue(i32), put_sum: isize, get_sum: isize, get_count: usize, @@ -79,11 +79,11 @@ test "std.atomic.queue" { .get_count = 0, }; - var putters: [put_thread_count]&std.os.Thread = undefined; + var putters: [put_thread_count]*std.os.Thread = undefined; for (putters) |*t| { t.* = try std.os.spawnThread(&context, startPuts); } - var getters: [put_thread_count]&std.os.Thread = undefined; + var getters: [put_thread_count]*std.os.Thread = undefined; for (getters) |*t| { t.* = try std.os.spawnThread(&context, startGets); } @@ -98,7 +98,7 @@ test "std.atomic.queue" { std.debug.assert(context.get_count == puts_per_thread * put_thread_count); } -fn startPuts(ctx: &Context) u8 { +fn startPuts(ctx: *Context) u8 { var put_count: usize = puts_per_thread; var r = std.rand.DefaultPrng.init(0xdeadbeef); while (put_count != 0) : (put_count -= 1) { @@ -112,7 +112,7 @@ fn startPuts(ctx: &Context) u8 { return 0; } -fn startGets(ctx: &Context) u8 { +fn startGets(ctx: *Context) u8 { while (true) { while (ctx.queue.get()) |node| { std.os.time.sleep(0, 1); // let the os scheduler be our fuzz diff --git a/std/atomic/stack.zig b/std/atomic/stack.zig index 400a1a3c4f..15611188d2 100644 --- a/std/atomic/stack.zig +++ b/std/atomic/stack.zig @@ -4,12 +4,12 @@ const AtomicOrder = builtin.AtomicOrder; /// Many reader, many writer, non-allocating, thread-safe, lock-free pub fn Stack(comptime T: type) type { return struct { - root: ?&Node, + root: ?*Node, pub const Self = this; pub const Node = struct { - next: ?&Node, + next: ?*Node, data: T, }; @@ -19,36 +19,36 @@ pub fn Stack(comptime T: type) type { /// push operation, but only if you are the first item in the stack. if you did not succeed in /// being the first item in the stack, returns the other item that was there. - pub fn pushFirst(self: &Self, node: &Node) ?&Node { + pub fn pushFirst(self: *Self, node: *Node) ?*Node { node.next = null; - return @cmpxchgStrong(?&Node, &self.root, null, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst); + return @cmpxchgStrong(?*Node, &self.root, null, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst); } - pub fn push(self: &Self, node: &Node) void { - var root = @atomicLoad(?&Node, &self.root, AtomicOrder.SeqCst); + pub fn push(self: *Self, node: *Node) void { + var root = @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst); while (true) { node.next = root; - root = @cmpxchgWeak(?&Node, &self.root, root, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? break; + root = @cmpxchgWeak(?*Node, &self.root, root, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? break; } } - pub fn pop(self: &Self) ?&Node { - var root = @atomicLoad(?&Node, &self.root, AtomicOrder.SeqCst); + pub fn pop(self: *Self) ?*Node { + var root = @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst); while (true) { - root = @cmpxchgWeak(?&Node, &self.root, root, (root ?? return null).next, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return root; + root = @cmpxchgWeak(?*Node, &self.root, root, (root ?? return null).next, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return root; } } - pub fn isEmpty(self: &Self) bool { - return @atomicLoad(?&Node, &self.root, AtomicOrder.SeqCst) == null; + pub fn isEmpty(self: *Self) bool { + return @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst) == null; } }; } const std = @import("std"); const Context = struct { - allocator: &std.mem.Allocator, - stack: &Stack(i32), + allocator: *std.mem.Allocator, + stack: *Stack(i32), put_sum: isize, get_sum: isize, get_count: usize, @@ -82,11 +82,11 @@ test "std.atomic.stack" { .get_count = 0, }; - var putters: [put_thread_count]&std.os.Thread = undefined; + var putters: [put_thread_count]*std.os.Thread = undefined; for (putters) |*t| { t.* = try std.os.spawnThread(&context, startPuts); } - var getters: [put_thread_count]&std.os.Thread = undefined; + var getters: [put_thread_count]*std.os.Thread = undefined; for (getters) |*t| { t.* = try std.os.spawnThread(&context, startGets); } @@ -101,7 +101,7 @@ test "std.atomic.stack" { std.debug.assert(context.get_count == puts_per_thread * put_thread_count); } -fn startPuts(ctx: &Context) u8 { +fn startPuts(ctx: *Context) u8 { var put_count: usize = puts_per_thread; var r = std.rand.DefaultPrng.init(0xdeadbeef); while (put_count != 0) : (put_count -= 1) { @@ -115,7 +115,7 @@ fn startPuts(ctx: &Context) u8 { return 0; } -fn startGets(ctx: &Context) u8 { +fn startGets(ctx: *Context) u8 { while (true) { while (ctx.stack.pop()) |node| { std.os.time.sleep(0, 1); // let the os scheduler be our fuzz diff --git a/std/base64.zig b/std/base64.zig index 204628a405..d27bcbd201 100644 --- a/std/base64.zig +++ b/std/base64.zig @@ -32,7 +32,7 @@ pub const Base64Encoder = struct { } /// dest.len must be what you get from ::calcSize. - pub fn encode(encoder: &const Base64Encoder, dest: []u8, source: []const u8) void { + pub fn encode(encoder: *const Base64Encoder, dest: []u8, source: []const u8) void { assert(dest.len == Base64Encoder.calcSize(source.len)); var i: usize = 0; @@ -107,7 +107,7 @@ pub const Base64Decoder = struct { } /// If the encoded buffer is detected to be invalid, returns error.InvalidPadding. - pub fn calcSize(decoder: &const Base64Decoder, source: []const u8) !usize { + pub fn calcSize(decoder: *const Base64Decoder, source: []const u8) !usize { if (source.len % 4 != 0) return error.InvalidPadding; return calcDecodedSizeExactUnsafe(source, decoder.pad_char); } @@ -115,7 +115,7 @@ pub const Base64Decoder = struct { /// dest.len must be what you get from ::calcSize. /// invalid characters result in error.InvalidCharacter. /// invalid padding results in error.InvalidPadding. - pub fn decode(decoder: &const Base64Decoder, dest: []u8, source: []const u8) !void { + pub fn decode(decoder: *const Base64Decoder, dest: []u8, source: []const u8) !void { assert(dest.len == (decoder.calcSize(source) catch unreachable)); assert(source.len % 4 == 0); @@ -181,7 +181,7 @@ pub const Base64DecoderWithIgnore = struct { /// Invalid padding results in error.InvalidPadding. /// Decoding more data than can fit in dest results in error.OutputTooSmall. See also ::calcSizeUpperBound. /// Returns the number of bytes writen to dest. - pub fn decode(decoder_with_ignore: &const Base64DecoderWithIgnore, dest: []u8, source: []const u8) !usize { + pub fn decode(decoder_with_ignore: *const Base64DecoderWithIgnore, dest: []u8, source: []const u8) !usize { const decoder = &decoder_with_ignore.decoder; var src_cursor: usize = 0; @@ -290,13 +290,13 @@ pub const Base64DecoderUnsafe = struct { } /// The source buffer must be valid. - pub fn calcSize(decoder: &const Base64DecoderUnsafe, source: []const u8) usize { + pub fn calcSize(decoder: *const Base64DecoderUnsafe, source: []const u8) usize { return calcDecodedSizeExactUnsafe(source, decoder.pad_char); } /// dest.len must be what you get from ::calcDecodedSizeExactUnsafe. /// invalid characters or padding will result in undefined values. - pub fn decode(decoder: &const Base64DecoderUnsafe, dest: []u8, source: []const u8) void { + pub fn decode(decoder: *const Base64DecoderUnsafe, dest: []u8, source: []const u8) void { assert(dest.len == decoder.calcSize(source)); var src_index: usize = 0; diff --git a/std/buf_map.zig b/std/buf_map.zig index 930fc36a78..22d821ae7b 100644 --- a/std/buf_map.zig +++ b/std/buf_map.zig @@ -11,12 +11,12 @@ pub const BufMap = struct { const BufMapHashMap = HashMap([]const u8, []const u8, mem.hash_slice_u8, mem.eql_slice_u8); - pub fn init(allocator: &Allocator) BufMap { + pub fn init(allocator: *Allocator) BufMap { var self = BufMap{ .hash_map = BufMapHashMap.init(allocator) }; return self; } - pub fn deinit(self: &const BufMap) void { + pub fn deinit(self: *const BufMap) void { var it = self.hash_map.iterator(); while (true) { const entry = it.next() ?? break; @@ -27,7 +27,7 @@ pub const BufMap = struct { self.hash_map.deinit(); } - pub fn set(self: &BufMap, key: []const u8, value: []const u8) !void { + pub fn set(self: *BufMap, key: []const u8, value: []const u8) !void { self.delete(key); const key_copy = try self.copy(key); errdefer self.free(key_copy); @@ -36,30 +36,30 @@ pub const BufMap = struct { _ = try self.hash_map.put(key_copy, value_copy); } - pub fn get(self: &const BufMap, key: []const u8) ?[]const u8 { + pub fn get(self: *const BufMap, key: []const u8) ?[]const u8 { const entry = self.hash_map.get(key) ?? return null; return entry.value; } - pub fn delete(self: &BufMap, key: []const u8) void { + pub fn delete(self: *BufMap, key: []const u8) void { const entry = self.hash_map.remove(key) ?? return; self.free(entry.key); self.free(entry.value); } - pub fn count(self: &const BufMap) usize { + pub fn count(self: *const BufMap) usize { return self.hash_map.count(); } - pub fn iterator(self: &const BufMap) BufMapHashMap.Iterator { + pub fn iterator(self: *const BufMap) BufMapHashMap.Iterator { return self.hash_map.iterator(); } - fn free(self: &const BufMap, value: []const u8) void { + fn free(self: *const BufMap, value: []const u8) void { self.hash_map.allocator.free(value); } - fn copy(self: &const BufMap, value: []const u8) ![]const u8 { + fn copy(self: *const BufMap, value: []const u8) ![]const u8 { return mem.dupe(self.hash_map.allocator, u8, value); } }; diff --git a/std/buf_set.zig b/std/buf_set.zig index c5a80e16fb..03a050ed8b 100644 --- a/std/buf_set.zig +++ b/std/buf_set.zig @@ -9,12 +9,12 @@ pub const BufSet = struct { const BufSetHashMap = HashMap([]const u8, void, mem.hash_slice_u8, mem.eql_slice_u8); - pub fn init(a: &Allocator) BufSet { + pub fn init(a: *Allocator) BufSet { var self = BufSet{ .hash_map = BufSetHashMap.init(a) }; return self; } - pub fn deinit(self: &const BufSet) void { + pub fn deinit(self: *const BufSet) void { var it = self.hash_map.iterator(); while (true) { const entry = it.next() ?? break; @@ -24,7 +24,7 @@ pub const BufSet = struct { self.hash_map.deinit(); } - pub fn put(self: &BufSet, key: []const u8) !void { + pub fn put(self: *BufSet, key: []const u8) !void { if (self.hash_map.get(key) == null) { const key_copy = try self.copy(key); errdefer self.free(key_copy); @@ -32,28 +32,28 @@ pub const BufSet = struct { } } - pub fn delete(self: &BufSet, key: []const u8) void { + pub fn delete(self: *BufSet, key: []const u8) void { const entry = self.hash_map.remove(key) ?? return; self.free(entry.key); } - pub fn count(self: &const BufSet) usize { + pub fn count(self: *const BufSet) usize { return self.hash_map.count(); } - pub fn iterator(self: &const BufSet) BufSetHashMap.Iterator { + pub fn iterator(self: *const BufSet) BufSetHashMap.Iterator { return self.hash_map.iterator(); } - pub fn allocator(self: &const BufSet) &Allocator { + pub fn allocator(self: *const BufSet) *Allocator { return self.hash_map.allocator; } - fn free(self: &const BufSet, value: []const u8) void { + fn free(self: *const BufSet, value: []const u8) void { self.hash_map.allocator.free(value); } - fn copy(self: &const BufSet, value: []const u8) ![]const u8 { + fn copy(self: *const BufSet, value: []const u8) ![]const u8 { const result = try self.hash_map.allocator.alloc(u8, value.len); mem.copy(u8, result, value); return result; diff --git a/std/buffer.zig b/std/buffer.zig index 90d63719e3..305746e183 100644 --- a/std/buffer.zig +++ b/std/buffer.zig @@ -12,14 +12,14 @@ pub const Buffer = struct { list: ArrayList(u8), /// Must deinitialize with deinit. - pub fn init(allocator: &Allocator, m: []const u8) !Buffer { + pub fn init(allocator: *Allocator, m: []const u8) !Buffer { var self = try initSize(allocator, m.len); mem.copy(u8, self.list.items, m); return self; } /// Must deinitialize with deinit. - pub fn initSize(allocator: &Allocator, size: usize) !Buffer { + pub fn initSize(allocator: *Allocator, size: usize) !Buffer { var self = initNull(allocator); try self.resize(size); return self; @@ -30,19 +30,19 @@ pub const Buffer = struct { /// * ::replaceContents /// * ::replaceContentsBuffer /// * ::resize - pub fn initNull(allocator: &Allocator) Buffer { + pub fn initNull(allocator: *Allocator) Buffer { return Buffer{ .list = ArrayList(u8).init(allocator) }; } /// Must deinitialize with deinit. - pub fn initFromBuffer(buffer: &const Buffer) !Buffer { + pub fn initFromBuffer(buffer: *const Buffer) !Buffer { return Buffer.init(buffer.list.allocator, buffer.toSliceConst()); } /// Buffer takes ownership of the passed in slice. The slice must have been /// allocated with `allocator`. /// Must deinitialize with deinit. - pub fn fromOwnedSlice(allocator: &Allocator, slice: []u8) Buffer { + pub fn fromOwnedSlice(allocator: *Allocator, slice: []u8) Buffer { var self = Buffer{ .list = ArrayList(u8).fromOwnedSlice(allocator, slice) }; self.list.append(0); return self; @@ -50,79 +50,79 @@ pub const Buffer = struct { /// The caller owns the returned memory. The Buffer becomes null and /// is safe to `deinit`. - pub fn toOwnedSlice(self: &Buffer) []u8 { + pub fn toOwnedSlice(self: *Buffer) []u8 { const allocator = self.list.allocator; const result = allocator.shrink(u8, self.list.items, self.len()); self.* = initNull(allocator); return result; } - pub fn deinit(self: &Buffer) void { + pub fn deinit(self: *Buffer) void { self.list.deinit(); } - pub fn toSlice(self: &const Buffer) []u8 { + pub fn toSlice(self: *const Buffer) []u8 { return self.list.toSlice()[0..self.len()]; } - pub fn toSliceConst(self: &const Buffer) []const u8 { + pub fn toSliceConst(self: *const Buffer) []const u8 { return self.list.toSliceConst()[0..self.len()]; } - pub fn shrink(self: &Buffer, new_len: usize) void { + pub fn shrink(self: *Buffer, new_len: usize) void { assert(new_len <= self.len()); self.list.shrink(new_len + 1); self.list.items[self.len()] = 0; } - pub fn resize(self: &Buffer, new_len: usize) !void { + pub fn resize(self: *Buffer, new_len: usize) !void { try self.list.resize(new_len + 1); self.list.items[self.len()] = 0; } - pub fn isNull(self: &const Buffer) bool { + pub fn isNull(self: *const Buffer) bool { return self.list.len == 0; } - pub fn len(self: &const Buffer) usize { + pub fn len(self: *const Buffer) usize { return self.list.len - 1; } - pub fn append(self: &Buffer, m: []const u8) !void { + pub fn append(self: *Buffer, m: []const u8) !void { const old_len = self.len(); try self.resize(old_len + m.len); mem.copy(u8, self.list.toSlice()[old_len..], m); } - pub fn appendByte(self: &Buffer, byte: u8) !void { + pub fn appendByte(self: *Buffer, byte: u8) !void { const old_len = self.len(); try self.resize(old_len + 1); self.list.toSlice()[old_len] = byte; } - pub fn eql(self: &const Buffer, m: []const u8) bool { + pub fn eql(self: *const Buffer, m: []const u8) bool { return mem.eql(u8, self.toSliceConst(), m); } - pub fn startsWith(self: &const Buffer, m: []const u8) bool { + pub fn startsWith(self: *const Buffer, m: []const u8) bool { if (self.len() < m.len) return false; return mem.eql(u8, self.list.items[0..m.len], m); } - pub fn endsWith(self: &const Buffer, m: []const u8) bool { + pub fn endsWith(self: *const Buffer, m: []const u8) bool { const l = self.len(); if (l < m.len) return false; const start = l - m.len; return mem.eql(u8, self.list.items[start..l], m); } - pub fn replaceContents(self: &const Buffer, m: []const u8) !void { + pub fn replaceContents(self: *const Buffer, m: []const u8) !void { try self.resize(m.len); mem.copy(u8, self.list.toSlice(), m); } /// For passing to C functions. - pub fn ptr(self: &const Buffer) &u8 { + pub fn ptr(self: *const Buffer) *u8 { return self.list.items.ptr; } }; diff --git a/std/build.zig b/std/build.zig index 9a6e17f728..fed02e0815 100644 --- a/std/build.zig +++ b/std/build.zig @@ -20,7 +20,7 @@ pub const Builder = struct { install_tls: TopLevelStep, have_uninstall_step: bool, have_install_step: bool, - allocator: &Allocator, + allocator: *Allocator, lib_paths: ArrayList([]const u8), include_paths: ArrayList([]const u8), rpaths: ArrayList([]const u8), @@ -36,9 +36,9 @@ pub const Builder = struct { verbose_cimport: bool, invalid_user_input: bool, zig_exe: []const u8, - default_step: &Step, + default_step: *Step, env_map: BufMap, - top_level_steps: ArrayList(&TopLevelStep), + top_level_steps: ArrayList(*TopLevelStep), prefix: []const u8, search_prefixes: ArrayList([]const u8), lib_dir: []const u8, @@ -82,7 +82,7 @@ pub const Builder = struct { description: []const u8, }; - pub fn init(allocator: &Allocator, zig_exe: []const u8, build_root: []const u8, cache_root: []const u8) Builder { + pub fn init(allocator: *Allocator, zig_exe: []const u8, build_root: []const u8, cache_root: []const u8) Builder { var self = Builder{ .zig_exe = zig_exe, .build_root = build_root, @@ -102,7 +102,7 @@ pub const Builder = struct { .user_input_options = UserInputOptionsMap.init(allocator), .available_options_map = AvailableOptionsMap.init(allocator), .available_options_list = ArrayList(AvailableOption).init(allocator), - .top_level_steps = ArrayList(&TopLevelStep).init(allocator), + .top_level_steps = ArrayList(*TopLevelStep).init(allocator), .default_step = undefined, .env_map = os.getEnvMap(allocator) catch unreachable, .prefix = undefined, @@ -127,7 +127,7 @@ pub const Builder = struct { return self; } - pub fn deinit(self: &Builder) void { + pub fn deinit(self: *Builder) void { self.lib_paths.deinit(); self.include_paths.deinit(); self.rpaths.deinit(); @@ -135,81 +135,81 @@ pub const Builder = struct { self.top_level_steps.deinit(); } - pub fn setInstallPrefix(self: &Builder, maybe_prefix: ?[]const u8) void { + pub fn setInstallPrefix(self: *Builder, maybe_prefix: ?[]const u8) void { self.prefix = maybe_prefix ?? "/usr/local"; // TODO better default self.lib_dir = os.path.join(self.allocator, self.prefix, "lib") catch unreachable; self.exe_dir = os.path.join(self.allocator, self.prefix, "bin") catch unreachable; } - pub fn addExecutable(self: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep { + pub fn addExecutable(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep { return LibExeObjStep.createExecutable(self, name, root_src); } - pub fn addObject(self: &Builder, name: []const u8, root_src: []const u8) &LibExeObjStep { + pub fn addObject(self: *Builder, name: []const u8, root_src: []const u8) *LibExeObjStep { return LibExeObjStep.createObject(self, name, root_src); } - pub fn addSharedLibrary(self: &Builder, name: []const u8, root_src: ?[]const u8, ver: &const Version) &LibExeObjStep { + pub fn addSharedLibrary(self: *Builder, name: []const u8, root_src: ?[]const u8, ver: *const Version) *LibExeObjStep { return LibExeObjStep.createSharedLibrary(self, name, root_src, ver); } - pub fn addStaticLibrary(self: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep { + pub fn addStaticLibrary(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep { return LibExeObjStep.createStaticLibrary(self, name, root_src); } - pub fn addTest(self: &Builder, root_src: []const u8) &TestStep { + pub fn addTest(self: *Builder, root_src: []const u8) *TestStep { const test_step = self.allocator.create(TestStep) catch unreachable; test_step.* = TestStep.init(self, root_src); return test_step; } - pub fn addAssemble(self: &Builder, name: []const u8, src: []const u8) &LibExeObjStep { + pub fn addAssemble(self: *Builder, name: []const u8, src: []const u8) *LibExeObjStep { const obj_step = LibExeObjStep.createObject(self, name, null); obj_step.addAssemblyFile(src); return obj_step; } - pub fn addCStaticLibrary(self: &Builder, name: []const u8) &LibExeObjStep { + pub fn addCStaticLibrary(self: *Builder, name: []const u8) *LibExeObjStep { return LibExeObjStep.createCStaticLibrary(self, name); } - pub fn addCSharedLibrary(self: &Builder, name: []const u8, ver: &const Version) &LibExeObjStep { + pub fn addCSharedLibrary(self: *Builder, name: []const u8, ver: *const Version) *LibExeObjStep { return LibExeObjStep.createCSharedLibrary(self, name, ver); } - pub fn addCExecutable(self: &Builder, name: []const u8) &LibExeObjStep { + pub fn addCExecutable(self: *Builder, name: []const u8) *LibExeObjStep { return LibExeObjStep.createCExecutable(self, name); } - pub fn addCObject(self: &Builder, name: []const u8, src: []const u8) &LibExeObjStep { + pub fn addCObject(self: *Builder, name: []const u8, src: []const u8) *LibExeObjStep { return LibExeObjStep.createCObject(self, name, src); } /// ::argv is copied. - pub fn addCommand(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) &CommandStep { + pub fn addCommand(self: *Builder, cwd: ?[]const u8, env_map: *const BufMap, argv: []const []const u8) *CommandStep { return CommandStep.create(self, cwd, env_map, argv); } - pub fn addWriteFile(self: &Builder, file_path: []const u8, data: []const u8) &WriteFileStep { + pub fn addWriteFile(self: *Builder, file_path: []const u8, data: []const u8) *WriteFileStep { const write_file_step = self.allocator.create(WriteFileStep) catch unreachable; write_file_step.* = WriteFileStep.init(self, file_path, data); return write_file_step; } - pub fn addLog(self: &Builder, comptime format: []const u8, args: ...) &LogStep { + pub fn addLog(self: *Builder, comptime format: []const u8, args: ...) *LogStep { const data = self.fmt(format, args); const log_step = self.allocator.create(LogStep) catch unreachable; log_step.* = LogStep.init(self, data); return log_step; } - pub fn addRemoveDirTree(self: &Builder, dir_path: []const u8) &RemoveDirStep { + pub fn addRemoveDirTree(self: *Builder, dir_path: []const u8) *RemoveDirStep { const remove_dir_step = self.allocator.create(RemoveDirStep) catch unreachable; remove_dir_step.* = RemoveDirStep.init(self, dir_path); return remove_dir_step; } - pub fn version(self: &const Builder, major: u32, minor: u32, patch: u32) Version { + pub fn version(self: *const Builder, major: u32, minor: u32, patch: u32) Version { return Version{ .major = major, .minor = minor, @@ -217,20 +217,20 @@ pub const Builder = struct { }; } - pub fn addCIncludePath(self: &Builder, path: []const u8) void { + pub fn addCIncludePath(self: *Builder, path: []const u8) void { self.include_paths.append(path) catch unreachable; } - pub fn addRPath(self: &Builder, path: []const u8) void { + pub fn addRPath(self: *Builder, path: []const u8) void { self.rpaths.append(path) catch unreachable; } - pub fn addLibPath(self: &Builder, path: []const u8) void { + pub fn addLibPath(self: *Builder, path: []const u8) void { self.lib_paths.append(path) catch unreachable; } - pub fn make(self: &Builder, step_names: []const []const u8) !void { - var wanted_steps = ArrayList(&Step).init(self.allocator); + pub fn make(self: *Builder, step_names: []const []const u8) !void { + var wanted_steps = ArrayList(*Step).init(self.allocator); defer wanted_steps.deinit(); if (step_names.len == 0) { @@ -247,7 +247,7 @@ pub const Builder = struct { } } - pub fn getInstallStep(self: &Builder) &Step { + pub fn getInstallStep(self: *Builder) *Step { if (self.have_install_step) return &self.install_tls.step; self.top_level_steps.append(&self.install_tls) catch unreachable; @@ -255,7 +255,7 @@ pub const Builder = struct { return &self.install_tls.step; } - pub fn getUninstallStep(self: &Builder) &Step { + pub fn getUninstallStep(self: *Builder) *Step { if (self.have_uninstall_step) return &self.uninstall_tls.step; self.top_level_steps.append(&self.uninstall_tls) catch unreachable; @@ -263,7 +263,7 @@ pub const Builder = struct { return &self.uninstall_tls.step; } - fn makeUninstall(uninstall_step: &Step) error!void { + fn makeUninstall(uninstall_step: *Step) error!void { const uninstall_tls = @fieldParentPtr(TopLevelStep, "step", uninstall_step); const self = @fieldParentPtr(Builder, "uninstall_tls", uninstall_tls); @@ -277,7 +277,7 @@ pub const Builder = struct { // TODO remove empty directories } - fn makeOneStep(self: &Builder, s: &Step) error!void { + fn makeOneStep(self: *Builder, s: *Step) error!void { if (s.loop_flag) { warn("Dependency loop detected:\n {}\n", s.name); return error.DependencyLoopDetected; @@ -298,7 +298,7 @@ pub const Builder = struct { try s.make(); } - fn getTopLevelStepByName(self: &Builder, name: []const u8) !&Step { + fn getTopLevelStepByName(self: *Builder, name: []const u8) !*Step { for (self.top_level_steps.toSliceConst()) |top_level_step| { if (mem.eql(u8, top_level_step.step.name, name)) { return &top_level_step.step; @@ -308,7 +308,7 @@ pub const Builder = struct { return error.InvalidStepName; } - fn processNixOSEnvVars(self: &Builder) void { + fn processNixOSEnvVars(self: *Builder) void { if (os.getEnvVarOwned(self.allocator, "NIX_CFLAGS_COMPILE")) |nix_cflags_compile| { var it = mem.split(nix_cflags_compile, " "); while (true) { @@ -350,7 +350,7 @@ pub const Builder = struct { } } - pub fn option(self: &Builder, comptime T: type, name: []const u8, description: []const u8) ?T { + pub fn option(self: *Builder, comptime T: type, name: []const u8, description: []const u8) ?T { const type_id = comptime typeToEnum(T); const available_option = AvailableOption{ .name = name, @@ -403,7 +403,7 @@ pub const Builder = struct { } } - pub fn step(self: &Builder, name: []const u8, description: []const u8) &Step { + pub fn step(self: *Builder, name: []const u8, description: []const u8) *Step { const step_info = self.allocator.create(TopLevelStep) catch unreachable; step_info.* = TopLevelStep{ .step = Step.initNoOp(name, self.allocator), @@ -413,7 +413,7 @@ pub const Builder = struct { return &step_info.step; } - pub fn standardReleaseOptions(self: &Builder) builtin.Mode { + pub fn standardReleaseOptions(self: *Builder) builtin.Mode { if (self.release_mode) |mode| return mode; const release_safe = self.option(bool, "release-safe", "optimizations on and safety on") ?? false; @@ -429,7 +429,7 @@ pub const Builder = struct { return mode; } - pub fn addUserInputOption(self: &Builder, name: []const u8, value: []const u8) bool { + pub fn addUserInputOption(self: *Builder, name: []const u8, value: []const u8) bool { if (self.user_input_options.put(name, UserInputOption{ .name = name, .value = UserValue{ .Scalar = value }, @@ -466,7 +466,7 @@ pub const Builder = struct { return false; } - pub fn addUserInputFlag(self: &Builder, name: []const u8) bool { + pub fn addUserInputFlag(self: *Builder, name: []const u8) bool { if (self.user_input_options.put(name, UserInputOption{ .name = name, .value = UserValue{ .Flag = {} }, @@ -500,7 +500,7 @@ pub const Builder = struct { }; } - fn markInvalidUserInput(self: &Builder) void { + fn markInvalidUserInput(self: *Builder) void { self.invalid_user_input = true; } @@ -514,7 +514,7 @@ pub const Builder = struct { }; } - pub fn validateUserInputDidItFail(self: &Builder) bool { + pub fn validateUserInputDidItFail(self: *Builder) bool { // make sure all args are used var it = self.user_input_options.iterator(); while (true) { @@ -528,7 +528,7 @@ pub const Builder = struct { return self.invalid_user_input; } - fn spawnChild(self: &Builder, argv: []const []const u8) !void { + fn spawnChild(self: *Builder, argv: []const []const u8) !void { return self.spawnChildEnvMap(null, &self.env_map, argv); } @@ -540,7 +540,7 @@ pub const Builder = struct { warn("\n"); } - fn spawnChildEnvMap(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) !void { + fn spawnChildEnvMap(self: *Builder, cwd: ?[]const u8, env_map: *const BufMap, argv: []const []const u8) !void { if (self.verbose) { printCmd(cwd, argv); } @@ -573,28 +573,28 @@ pub const Builder = struct { } } - pub fn makePath(self: &Builder, path: []const u8) !void { + pub fn makePath(self: *Builder, path: []const u8) !void { os.makePath(self.allocator, self.pathFromRoot(path)) catch |err| { warn("Unable to create path {}: {}\n", path, @errorName(err)); return err; }; } - pub fn installArtifact(self: &Builder, artifact: &LibExeObjStep) void { + pub fn installArtifact(self: *Builder, artifact: *LibExeObjStep) void { self.getInstallStep().dependOn(&self.addInstallArtifact(artifact).step); } - pub fn addInstallArtifact(self: &Builder, artifact: &LibExeObjStep) &InstallArtifactStep { + pub fn addInstallArtifact(self: *Builder, artifact: *LibExeObjStep) *InstallArtifactStep { return InstallArtifactStep.create(self, artifact); } ///::dest_rel_path is relative to prefix path or it can be an absolute path - pub fn installFile(self: &Builder, src_path: []const u8, dest_rel_path: []const u8) void { + pub fn installFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) void { self.getInstallStep().dependOn(&self.addInstallFile(src_path, dest_rel_path).step); } ///::dest_rel_path is relative to prefix path or it can be an absolute path - pub fn addInstallFile(self: &Builder, src_path: []const u8, dest_rel_path: []const u8) &InstallFileStep { + pub fn addInstallFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) *InstallFileStep { const full_dest_path = os.path.resolve(self.allocator, self.prefix, dest_rel_path) catch unreachable; self.pushInstalledFile(full_dest_path); @@ -603,16 +603,16 @@ pub const Builder = struct { return install_step; } - pub fn pushInstalledFile(self: &Builder, full_path: []const u8) void { + pub fn pushInstalledFile(self: *Builder, full_path: []const u8) void { _ = self.getUninstallStep(); self.installed_files.append(full_path) catch unreachable; } - fn copyFile(self: &Builder, source_path: []const u8, dest_path: []const u8) !void { + fn copyFile(self: *Builder, source_path: []const u8, dest_path: []const u8) !void { return self.copyFileMode(source_path, dest_path, os.default_file_mode); } - fn copyFileMode(self: &Builder, source_path: []const u8, dest_path: []const u8, mode: os.FileMode) !void { + fn copyFileMode(self: *Builder, source_path: []const u8, dest_path: []const u8, mode: os.FileMode) !void { if (self.verbose) { warn("cp {} {}\n", source_path, dest_path); } @@ -629,15 +629,15 @@ pub const Builder = struct { }; } - fn pathFromRoot(self: &Builder, rel_path: []const u8) []u8 { + fn pathFromRoot(self: *Builder, rel_path: []const u8) []u8 { return os.path.resolve(self.allocator, self.build_root, rel_path) catch unreachable; } - pub fn fmt(self: &Builder, comptime format: []const u8, args: ...) []u8 { + pub fn fmt(self: *Builder, comptime format: []const u8, args: ...) []u8 { return fmt_lib.allocPrint(self.allocator, format, args) catch unreachable; } - fn getCCExe(self: &Builder) []const u8 { + fn getCCExe(self: *Builder) []const u8 { if (builtin.environ == builtin.Environ.msvc) { return "cl.exe"; } else { @@ -645,7 +645,7 @@ pub const Builder = struct { } } - pub fn findProgram(self: &Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 { + pub fn findProgram(self: *Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 { // TODO report error for ambiguous situations const exe_extension = (Target{ .Native = {} }).exeFileExt(); for (self.search_prefixes.toSliceConst()) |search_prefix| { @@ -693,7 +693,7 @@ pub const Builder = struct { return error.FileNotFound; } - pub fn exec(self: &Builder, argv: []const []const u8) ![]u8 { + pub fn exec(self: *Builder, argv: []const []const u8) ![]u8 { const max_output_size = 100 * 1024; const result = try os.ChildProcess.exec(self.allocator, argv, null, null, max_output_size); switch (result.term) { @@ -715,7 +715,7 @@ pub const Builder = struct { } } - pub fn addSearchPrefix(self: &Builder, search_prefix: []const u8) void { + pub fn addSearchPrefix(self: *Builder, search_prefix: []const u8) void { self.search_prefixes.append(search_prefix) catch unreachable; } }; @@ -736,7 +736,7 @@ pub const Target = union(enum) { Native: void, Cross: CrossTarget, - pub fn oFileExt(self: &const Target) []const u8 { + pub fn oFileExt(self: *const Target) []const u8 { const environ = switch (self.*) { Target.Native => builtin.environ, Target.Cross => |t| t.environ, @@ -747,49 +747,49 @@ pub const Target = union(enum) { }; } - pub fn exeFileExt(self: &const Target) []const u8 { + pub fn exeFileExt(self: *const Target) []const u8 { return switch (self.getOs()) { builtin.Os.windows => ".exe", else => "", }; } - pub fn libFileExt(self: &const Target) []const u8 { + pub fn libFileExt(self: *const Target) []const u8 { return switch (self.getOs()) { builtin.Os.windows => ".lib", else => ".a", }; } - pub fn getOs(self: &const Target) builtin.Os { + pub fn getOs(self: *const Target) builtin.Os { return switch (self.*) { Target.Native => builtin.os, Target.Cross => |t| t.os, }; } - pub fn isDarwin(self: &const Target) bool { + pub fn isDarwin(self: *const Target) bool { return switch (self.getOs()) { builtin.Os.ios, builtin.Os.macosx => true, else => false, }; } - pub fn isWindows(self: &const Target) bool { + pub fn isWindows(self: *const Target) bool { return switch (self.getOs()) { builtin.Os.windows => true, else => false, }; } - pub fn wantSharedLibSymLinks(self: &const Target) bool { + pub fn wantSharedLibSymLinks(self: *const Target) bool { return !self.isWindows(); } }; pub const LibExeObjStep = struct { step: Step, - builder: &Builder, + builder: *Builder, name: []const u8, target: Target, link_libs: BufSet, @@ -836,56 +836,56 @@ pub const LibExeObjStep = struct { Obj, }; - pub fn createSharedLibrary(builder: &Builder, name: []const u8, root_src: ?[]const u8, ver: &const Version) &LibExeObjStep { + pub fn createSharedLibrary(builder: *Builder, name: []const u8, root_src: ?[]const u8, ver: *const Version) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initExtraArgs(builder, name, root_src, Kind.Lib, false, ver); return self; } - pub fn createCSharedLibrary(builder: &Builder, name: []const u8, version: &const Version) &LibExeObjStep { + pub fn createCSharedLibrary(builder: *Builder, name: []const u8, version: *const Version) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initC(builder, name, Kind.Lib, version, false); return self; } - pub fn createStaticLibrary(builder: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep { + pub fn createStaticLibrary(builder: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initExtraArgs(builder, name, root_src, Kind.Lib, true, builder.version(0, 0, 0)); return self; } - pub fn createCStaticLibrary(builder: &Builder, name: []const u8) &LibExeObjStep { + pub fn createCStaticLibrary(builder: *Builder, name: []const u8) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initC(builder, name, Kind.Lib, builder.version(0, 0, 0), true); return self; } - pub fn createObject(builder: &Builder, name: []const u8, root_src: []const u8) &LibExeObjStep { + pub fn createObject(builder: *Builder, name: []const u8, root_src: []const u8) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initExtraArgs(builder, name, root_src, Kind.Obj, false, builder.version(0, 0, 0)); return self; } - pub fn createCObject(builder: &Builder, name: []const u8, src: []const u8) &LibExeObjStep { + pub fn createCObject(builder: *Builder, name: []const u8, src: []const u8) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initC(builder, name, Kind.Obj, builder.version(0, 0, 0), false); self.object_src = src; return self; } - pub fn createExecutable(builder: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep { + pub fn createExecutable(builder: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initExtraArgs(builder, name, root_src, Kind.Exe, false, builder.version(0, 0, 0)); return self; } - pub fn createCExecutable(builder: &Builder, name: []const u8) &LibExeObjStep { + pub fn createCExecutable(builder: *Builder, name: []const u8) *LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; self.* = initC(builder, name, Kind.Exe, builder.version(0, 0, 0), false); return self; } - fn initExtraArgs(builder: &Builder, name: []const u8, root_src: ?[]const u8, kind: Kind, static: bool, ver: &const Version) LibExeObjStep { + fn initExtraArgs(builder: *Builder, name: []const u8, root_src: ?[]const u8, kind: Kind, static: bool, ver: *const Version) LibExeObjStep { var self = LibExeObjStep{ .strip = false, .builder = builder, @@ -924,7 +924,7 @@ pub const LibExeObjStep = struct { return self; } - fn initC(builder: &Builder, name: []const u8, kind: Kind, version: &const Version, static: bool) LibExeObjStep { + fn initC(builder: *Builder, name: []const u8, kind: Kind, version: *const Version, static: bool) LibExeObjStep { var self = LibExeObjStep{ .builder = builder, .name = name, @@ -964,7 +964,7 @@ pub const LibExeObjStep = struct { return self; } - fn computeOutFileNames(self: &LibExeObjStep) void { + fn computeOutFileNames(self: *LibExeObjStep) void { switch (self.kind) { Kind.Obj => { self.out_filename = self.builder.fmt("{}{}", self.name, self.target.oFileExt()); @@ -996,7 +996,7 @@ pub const LibExeObjStep = struct { } } - pub fn setTarget(self: &LibExeObjStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void { + pub fn setTarget(self: *LibExeObjStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void { self.target = Target{ .Cross = CrossTarget{ .arch = target_arch, @@ -1008,16 +1008,16 @@ pub const LibExeObjStep = struct { } // TODO respect this in the C args - pub fn setLinkerScriptPath(self: &LibExeObjStep, path: []const u8) void { + pub fn setLinkerScriptPath(self: *LibExeObjStep, path: []const u8) void { self.linker_script = path; } - pub fn linkFramework(self: &LibExeObjStep, framework_name: []const u8) void { + pub fn linkFramework(self: *LibExeObjStep, framework_name: []const u8) void { assert(self.target.isDarwin()); self.frameworks.put(framework_name) catch unreachable; } - pub fn linkLibrary(self: &LibExeObjStep, lib: &LibExeObjStep) void { + pub fn linkLibrary(self: *LibExeObjStep, lib: *LibExeObjStep) void { assert(self.kind != Kind.Obj); assert(lib.kind == Kind.Lib); @@ -1038,26 +1038,26 @@ pub const LibExeObjStep = struct { } } - pub fn linkSystemLibrary(self: &LibExeObjStep, name: []const u8) void { + pub fn linkSystemLibrary(self: *LibExeObjStep, name: []const u8) void { assert(self.kind != Kind.Obj); self.link_libs.put(name) catch unreachable; } - pub fn addSourceFile(self: &LibExeObjStep, file: []const u8) void { + pub fn addSourceFile(self: *LibExeObjStep, file: []const u8) void { assert(self.kind != Kind.Obj); assert(!self.is_zig); self.source_files.append(file) catch unreachable; } - pub fn setVerboseLink(self: &LibExeObjStep, value: bool) void { + pub fn setVerboseLink(self: *LibExeObjStep, value: bool) void { self.verbose_link = value; } - pub fn setBuildMode(self: &LibExeObjStep, mode: builtin.Mode) void { + pub fn setBuildMode(self: *LibExeObjStep, mode: builtin.Mode) void { self.build_mode = mode; } - pub fn setOutputPath(self: &LibExeObjStep, file_path: []const u8) void { + pub fn setOutputPath(self: *LibExeObjStep, file_path: []const u8) void { self.output_path = file_path; // catch a common mistake @@ -1066,11 +1066,11 @@ pub const LibExeObjStep = struct { } } - pub fn getOutputPath(self: &LibExeObjStep) []const u8 { + pub fn getOutputPath(self: *LibExeObjStep) []const u8 { 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; } - pub fn setOutputHPath(self: &LibExeObjStep, file_path: []const u8) void { + pub fn setOutputHPath(self: *LibExeObjStep, file_path: []const u8) void { self.output_h_path = file_path; // catch a common mistake @@ -1079,21 +1079,21 @@ pub const LibExeObjStep = struct { } } - pub fn getOutputHPath(self: &LibExeObjStep) []const u8 { + pub fn getOutputHPath(self: *LibExeObjStep) []const u8 { 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; } - pub fn addAssemblyFile(self: &LibExeObjStep, path: []const u8) void { + pub fn addAssemblyFile(self: *LibExeObjStep, path: []const u8) void { self.assembly_files.append(path) catch unreachable; } - pub fn addObjectFile(self: &LibExeObjStep, path: []const u8) void { + pub fn addObjectFile(self: *LibExeObjStep, path: []const u8) void { assert(self.kind != Kind.Obj); self.object_files.append(path) catch unreachable; } - pub fn addObject(self: &LibExeObjStep, obj: &LibExeObjStep) void { + pub fn addObject(self: *LibExeObjStep, obj: *LibExeObjStep) void { assert(obj.kind == Kind.Obj); assert(self.kind != Kind.Obj); @@ -1110,15 +1110,15 @@ pub const LibExeObjStep = struct { self.include_dirs.append(self.builder.cache_root) catch unreachable; } - pub fn addIncludeDir(self: &LibExeObjStep, path: []const u8) void { + pub fn addIncludeDir(self: *LibExeObjStep, path: []const u8) void { self.include_dirs.append(path) catch unreachable; } - pub fn addLibPath(self: &LibExeObjStep, path: []const u8) void { + pub fn addLibPath(self: *LibExeObjStep, path: []const u8) void { self.lib_paths.append(path) catch unreachable; } - pub fn addPackagePath(self: &LibExeObjStep, name: []const u8, pkg_index_path: []const u8) void { + pub fn addPackagePath(self: *LibExeObjStep, name: []const u8, pkg_index_path: []const u8) void { assert(self.is_zig); self.packages.append(Pkg{ @@ -1127,23 +1127,23 @@ pub const LibExeObjStep = struct { }) catch unreachable; } - pub fn addCompileFlags(self: &LibExeObjStep, flags: []const []const u8) void { + pub fn addCompileFlags(self: *LibExeObjStep, flags: []const []const u8) void { for (flags) |flag| { self.cflags.append(flag) catch unreachable; } } - pub fn setNoStdLib(self: &LibExeObjStep, disable: bool) void { + pub fn setNoStdLib(self: *LibExeObjStep, disable: bool) void { assert(!self.is_zig); self.disable_libc = disable; } - fn make(step: &Step) !void { + fn make(step: *Step) !void { const self = @fieldParentPtr(LibExeObjStep, "step", step); return if (self.is_zig) self.makeZig() else self.makeC(); } - fn makeZig(self: &LibExeObjStep) !void { + fn makeZig(self: *LibExeObjStep) !void { const builder = self.builder; assert(self.is_zig); @@ -1309,7 +1309,7 @@ pub const LibExeObjStep = struct { } } - fn appendCompileFlags(self: &LibExeObjStep, args: &ArrayList([]const u8)) void { + fn appendCompileFlags(self: *LibExeObjStep, args: *ArrayList([]const u8)) void { if (!self.strip) { args.append("-g") catch unreachable; } @@ -1354,7 +1354,7 @@ pub const LibExeObjStep = struct { } } - fn makeC(self: &LibExeObjStep) !void { + fn makeC(self: *LibExeObjStep) !void { const builder = self.builder; const cc = builder.getCCExe(); @@ -1580,7 +1580,7 @@ pub const LibExeObjStep = struct { pub const TestStep = struct { step: Step, - builder: &Builder, + builder: *Builder, root_src: []const u8, build_mode: builtin.Mode, verbose: bool, @@ -1591,7 +1591,7 @@ pub const TestStep = struct { exec_cmd_args: ?[]const ?[]const u8, include_dirs: ArrayList([]const u8), - pub fn init(builder: &Builder, root_src: []const u8) TestStep { + pub fn init(builder: *Builder, root_src: []const u8) TestStep { const step_name = builder.fmt("test {}", root_src); return TestStep{ .step = Step.init(step_name, builder.allocator, make), @@ -1608,31 +1608,31 @@ pub const TestStep = struct { }; } - pub fn setVerbose(self: &TestStep, value: bool) void { + pub fn setVerbose(self: *TestStep, value: bool) void { self.verbose = value; } - pub fn addIncludeDir(self: &TestStep, path: []const u8) void { + pub fn addIncludeDir(self: *TestStep, path: []const u8) void { self.include_dirs.append(path) catch unreachable; } - pub fn setBuildMode(self: &TestStep, mode: builtin.Mode) void { + pub fn setBuildMode(self: *TestStep, mode: builtin.Mode) void { self.build_mode = mode; } - pub fn linkSystemLibrary(self: &TestStep, name: []const u8) void { + pub fn linkSystemLibrary(self: *TestStep, name: []const u8) void { self.link_libs.put(name) catch unreachable; } - pub fn setNamePrefix(self: &TestStep, text: []const u8) void { + pub fn setNamePrefix(self: *TestStep, text: []const u8) void { self.name_prefix = text; } - pub fn setFilter(self: &TestStep, text: ?[]const u8) void { + pub fn setFilter(self: *TestStep, text: ?[]const u8) void { self.filter = text; } - pub fn setTarget(self: &TestStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void { + pub fn setTarget(self: *TestStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void { self.target = Target{ .Cross = CrossTarget{ .arch = target_arch, @@ -1642,11 +1642,11 @@ pub const TestStep = struct { }; } - pub fn setExecCmd(self: &TestStep, args: []const ?[]const u8) void { + pub fn setExecCmd(self: *TestStep, args: []const ?[]const u8) void { self.exec_cmd_args = args; } - fn make(step: &Step) !void { + fn make(step: *Step) !void { const self = @fieldParentPtr(TestStep, "step", step); const builder = self.builder; @@ -1739,13 +1739,13 @@ pub const TestStep = struct { pub const CommandStep = struct { step: Step, - builder: &Builder, + builder: *Builder, argv: [][]const u8, cwd: ?[]const u8, - env_map: &const BufMap, + env_map: *const BufMap, /// ::argv is copied. - pub fn create(builder: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) &CommandStep { + pub fn create(builder: *Builder, cwd: ?[]const u8, env_map: *const BufMap, argv: []const []const u8) *CommandStep { const self = builder.allocator.create(CommandStep) catch unreachable; self.* = CommandStep{ .builder = builder, @@ -1759,7 +1759,7 @@ pub const CommandStep = struct { return self; } - fn make(step: &Step) !void { + fn make(step: *Step) !void { const self = @fieldParentPtr(CommandStep, "step", step); const cwd = if (self.cwd) |cwd| self.builder.pathFromRoot(cwd) else self.builder.build_root; @@ -1769,13 +1769,13 @@ pub const CommandStep = struct { const InstallArtifactStep = struct { step: Step, - builder: &Builder, - artifact: &LibExeObjStep, + builder: *Builder, + artifact: *LibExeObjStep, dest_file: []const u8, const Self = this; - pub fn create(builder: &Builder, artifact: &LibExeObjStep) &Self { + pub fn create(builder: *Builder, artifact: *LibExeObjStep) *Self { const self = builder.allocator.create(Self) catch unreachable; const dest_dir = switch (artifact.kind) { LibExeObjStep.Kind.Obj => unreachable, @@ -1797,7 +1797,7 @@ const InstallArtifactStep = struct { return self; } - fn make(step: &Step) !void { + fn make(step: *Step) !void { const self = @fieldParentPtr(Self, "step", step); const builder = self.builder; @@ -1818,11 +1818,11 @@ const InstallArtifactStep = struct { pub const InstallFileStep = struct { step: Step, - builder: &Builder, + builder: *Builder, src_path: []const u8, dest_path: []const u8, - pub fn init(builder: &Builder, src_path: []const u8, dest_path: []const u8) InstallFileStep { + pub fn init(builder: *Builder, src_path: []const u8, dest_path: []const u8) InstallFileStep { return InstallFileStep{ .builder = builder, .step = Step.init(builder.fmt("install {}", src_path), builder.allocator, make), @@ -1831,7 +1831,7 @@ pub const InstallFileStep = struct { }; } - fn make(step: &Step) !void { + fn make(step: *Step) !void { const self = @fieldParentPtr(InstallFileStep, "step", step); try self.builder.copyFile(self.src_path, self.dest_path); } @@ -1839,11 +1839,11 @@ pub const InstallFileStep = struct { pub const WriteFileStep = struct { step: Step, - builder: &Builder, + builder: *Builder, file_path: []const u8, data: []const u8, - pub fn init(builder: &Builder, file_path: []const u8, data: []const u8) WriteFileStep { + pub fn init(builder: *Builder, file_path: []const u8, data: []const u8) WriteFileStep { return WriteFileStep{ .builder = builder, .step = Step.init(builder.fmt("writefile {}", file_path), builder.allocator, make), @@ -1852,7 +1852,7 @@ pub const WriteFileStep = struct { }; } - fn make(step: &Step) !void { + fn make(step: *Step) !void { const self = @fieldParentPtr(WriteFileStep, "step", step); const full_path = self.builder.pathFromRoot(self.file_path); const full_path_dir = os.path.dirname(full_path); @@ -1869,10 +1869,10 @@ pub const WriteFileStep = struct { pub const LogStep = struct { step: Step, - builder: &Builder, + builder: *Builder, data: []const u8, - pub fn init(builder: &Builder, data: []const u8) LogStep { + pub fn init(builder: *Builder, data: []const u8) LogStep { return LogStep{ .builder = builder, .step = Step.init(builder.fmt("log {}", data), builder.allocator, make), @@ -1880,7 +1880,7 @@ pub const LogStep = struct { }; } - fn make(step: &Step) error!void { + fn make(step: *Step) error!void { const self = @fieldParentPtr(LogStep, "step", step); warn("{}", self.data); } @@ -1888,10 +1888,10 @@ pub const LogStep = struct { pub const RemoveDirStep = struct { step: Step, - builder: &Builder, + builder: *Builder, dir_path: []const u8, - pub fn init(builder: &Builder, dir_path: []const u8) RemoveDirStep { + pub fn init(builder: *Builder, dir_path: []const u8) RemoveDirStep { return RemoveDirStep{ .builder = builder, .step = Step.init(builder.fmt("RemoveDir {}", dir_path), builder.allocator, make), @@ -1899,7 +1899,7 @@ pub const RemoveDirStep = struct { }; } - fn make(step: &Step) !void { + fn make(step: *Step) !void { const self = @fieldParentPtr(RemoveDirStep, "step", step); const full_path = self.builder.pathFromRoot(self.dir_path); @@ -1912,39 +1912,39 @@ pub const RemoveDirStep = struct { pub const Step = struct { name: []const u8, - makeFn: fn (self: &Step) error!void, - dependencies: ArrayList(&Step), + makeFn: fn (self: *Step) error!void, + dependencies: ArrayList(*Step), loop_flag: bool, done_flag: bool, - pub fn init(name: []const u8, allocator: &Allocator, makeFn: fn (&Step) error!void) Step { + pub fn init(name: []const u8, allocator: *Allocator, makeFn: fn (*Step) error!void) Step { return Step{ .name = name, .makeFn = makeFn, - .dependencies = ArrayList(&Step).init(allocator), + .dependencies = ArrayList(*Step).init(allocator), .loop_flag = false, .done_flag = false, }; } - pub fn initNoOp(name: []const u8, allocator: &Allocator) Step { + pub fn initNoOp(name: []const u8, allocator: *Allocator) Step { return init(name, allocator, makeNoOp); } - pub fn make(self: &Step) !void { + pub fn make(self: *Step) !void { if (self.done_flag) return; try self.makeFn(self); self.done_flag = true; } - pub fn dependOn(self: &Step, other: &Step) void { + pub fn dependOn(self: *Step, other: *Step) void { self.dependencies.append(other) catch unreachable; } - fn makeNoOp(self: &Step) error!void {} + fn makeNoOp(self: *Step) error!void {} }; -fn doAtomicSymLinks(allocator: &Allocator, output_path: []const u8, filename_major_only: []const u8, filename_name_only: []const u8) !void { +fn doAtomicSymLinks(allocator: *Allocator, output_path: []const u8, filename_major_only: []const u8, filename_name_only: []const u8) !void { const out_dir = os.path.dirname(output_path); const out_basename = os.path.basename(output_path); // sym link for libfoo.so.1 to libfoo.so.1.2.3 diff --git a/std/c/darwin.zig b/std/c/darwin.zig index 6a33c994bf..69395e6b27 100644 --- a/std/c/darwin.zig +++ b/std/c/darwin.zig @@ -1,10 +1,10 @@ -extern "c" fn __error() &c_int; -pub extern "c" fn _NSGetExecutablePath(buf: &u8, bufsize: &u32) c_int; +extern "c" fn __error() *c_int; +pub extern "c" fn _NSGetExecutablePath(buf: *u8, bufsize: *u32) c_int; -pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: &u8, buf_len: usize, basep: &i64) usize; +pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: *u8, buf_len: usize, basep: *i64) usize; pub extern "c" fn mach_absolute_time() u64; -pub extern "c" fn mach_timebase_info(tinfo: ?&mach_timebase_info_data) void; +pub extern "c" fn mach_timebase_info(tinfo: ?*mach_timebase_info_data) void; pub use @import("../os/darwin_errno.zig"); diff --git a/std/c/index.zig b/std/c/index.zig index f9704f4738..114b79cdae 100644 --- a/std/c/index.zig +++ b/std/c/index.zig @@ -13,49 +13,49 @@ pub extern "c" fn abort() noreturn; pub extern "c" fn exit(code: c_int) noreturn; pub extern "c" fn isatty(fd: c_int) c_int; pub extern "c" fn close(fd: c_int) c_int; -pub extern "c" fn fstat(fd: c_int, buf: &Stat) c_int; -pub extern "c" fn @"fstat$INODE64"(fd: c_int, buf: &Stat) c_int; +pub extern "c" fn fstat(fd: c_int, buf: *Stat) c_int; +pub extern "c" fn @"fstat$INODE64"(fd: c_int, buf: *Stat) c_int; pub extern "c" fn lseek(fd: c_int, offset: isize, whence: c_int) isize; -pub extern "c" fn open(path: &const u8, oflag: c_int, ...) c_int; +pub extern "c" fn open(path: *const u8, oflag: c_int, ...) c_int; pub extern "c" fn raise(sig: c_int) c_int; -pub extern "c" fn read(fd: c_int, buf: &c_void, nbyte: usize) isize; -pub extern "c" fn stat(noalias path: &const u8, noalias buf: &Stat) c_int; -pub extern "c" fn write(fd: c_int, buf: &const c_void, nbyte: usize) isize; -pub extern "c" fn mmap(addr: ?&c_void, len: usize, prot: c_int, flags: c_int, fd: c_int, offset: isize) ?&c_void; -pub extern "c" fn munmap(addr: &c_void, len: usize) c_int; -pub extern "c" fn unlink(path: &const u8) c_int; -pub extern "c" fn getcwd(buf: &u8, size: usize) ?&u8; -pub extern "c" fn waitpid(pid: c_int, stat_loc: &c_int, options: c_int) c_int; +pub extern "c" fn read(fd: c_int, buf: *c_void, nbyte: usize) isize; +pub extern "c" fn stat(noalias path: *const u8, noalias buf: *Stat) c_int; +pub extern "c" fn write(fd: c_int, buf: *const c_void, nbyte: usize) isize; +pub extern "c" fn mmap(addr: ?*c_void, len: usize, prot: c_int, flags: c_int, fd: c_int, offset: isize) ?*c_void; +pub extern "c" fn munmap(addr: *c_void, len: usize) c_int; +pub extern "c" fn unlink(path: *const u8) c_int; +pub extern "c" fn getcwd(buf: *u8, size: usize) ?*u8; +pub extern "c" fn waitpid(pid: c_int, stat_loc: *c_int, options: c_int) c_int; pub extern "c" fn fork() c_int; -pub extern "c" fn access(path: &const u8, mode: c_uint) c_int; -pub extern "c" fn pipe(fds: &c_int) c_int; -pub extern "c" fn mkdir(path: &const u8, mode: c_uint) c_int; -pub extern "c" fn symlink(existing: &const u8, new: &const u8) c_int; -pub extern "c" fn rename(old: &const u8, new: &const u8) c_int; -pub extern "c" fn chdir(path: &const u8) c_int; -pub extern "c" fn execve(path: &const u8, argv: &const ?&const u8, envp: &const ?&const u8) c_int; +pub extern "c" fn access(path: *const u8, mode: c_uint) c_int; +pub extern "c" fn pipe(fds: *c_int) c_int; +pub extern "c" fn mkdir(path: *const u8, mode: c_uint) c_int; +pub extern "c" fn symlink(existing: *const u8, new: *const u8) c_int; +pub extern "c" fn rename(old: *const u8, new: *const u8) c_int; +pub extern "c" fn chdir(path: *const u8) c_int; +pub extern "c" fn execve(path: *const u8, argv: *const ?*const u8, envp: *const ?*const u8) c_int; pub extern "c" fn dup(fd: c_int) c_int; pub extern "c" fn dup2(old_fd: c_int, new_fd: c_int) c_int; -pub extern "c" fn readlink(noalias path: &const u8, noalias buf: &u8, bufsize: usize) isize; -pub extern "c" fn realpath(noalias file_name: &const u8, noalias resolved_name: &u8) ?&u8; -pub extern "c" fn sigprocmask(how: c_int, noalias set: &const sigset_t, noalias oset: ?&sigset_t) c_int; -pub extern "c" fn gettimeofday(tv: ?&timeval, tz: ?&timezone) c_int; -pub extern "c" fn sigaction(sig: c_int, noalias act: &const Sigaction, noalias oact: ?&Sigaction) c_int; -pub extern "c" fn nanosleep(rqtp: &const timespec, rmtp: ?×pec) c_int; +pub extern "c" fn readlink(noalias path: *const u8, noalias buf: *u8, bufsize: usize) isize; +pub extern "c" fn realpath(noalias file_name: *const u8, noalias resolved_name: *u8) ?*u8; +pub extern "c" fn sigprocmask(how: c_int, noalias set: *const sigset_t, noalias oset: ?*sigset_t) c_int; +pub extern "c" fn gettimeofday(tv: ?*timeval, tz: ?*timezone) c_int; +pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int; +pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int; pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int; pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) c_int; -pub extern "c" fn rmdir(path: &const u8) c_int; +pub extern "c" fn rmdir(path: *const u8) c_int; -pub extern "c" fn aligned_alloc(alignment: usize, size: usize) ?&c_void; -pub extern "c" fn malloc(usize) ?&c_void; -pub extern "c" fn realloc(&c_void, usize) ?&c_void; -pub extern "c" fn free(&c_void) void; -pub extern "c" fn posix_memalign(memptr: &&c_void, alignment: usize, size: usize) c_int; +pub extern "c" fn aligned_alloc(alignment: usize, size: usize) ?*c_void; +pub extern "c" fn malloc(usize) ?*c_void; +pub extern "c" fn realloc(*c_void, usize) ?*c_void; +pub extern "c" fn free(*c_void) void; +pub extern "c" fn posix_memalign(memptr: **c_void, alignment: usize, size: usize) c_int; -pub 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; -pub extern "pthread" fn pthread_attr_init(attr: &pthread_attr_t) c_int; -pub extern "pthread" fn pthread_attr_setstack(attr: &pthread_attr_t, stackaddr: &c_void, stacksize: usize) c_int; -pub extern "pthread" fn pthread_attr_destroy(attr: &pthread_attr_t) c_int; -pub extern "pthread" fn pthread_join(thread: pthread_t, arg_return: ?&?&c_void) c_int; +pub 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; +pub extern "pthread" fn pthread_attr_init(attr: *pthread_attr_t) c_int; +pub extern "pthread" fn pthread_attr_setstack(attr: *pthread_attr_t, stackaddr: *c_void, stacksize: usize) c_int; +pub extern "pthread" fn pthread_attr_destroy(attr: *pthread_attr_t) c_int; +pub extern "pthread" fn pthread_join(thread: pthread_t, arg_return: ?*?*c_void) c_int; -pub const pthread_t = &@OpaqueType(); +pub const pthread_t = *@OpaqueType(); diff --git a/std/c/linux.zig b/std/c/linux.zig index 7810fec130..0ab043533e 100644 --- a/std/c/linux.zig +++ b/std/c/linux.zig @@ -1,7 +1,7 @@ pub use @import("../os/linux/errno.zig"); -pub extern "c" fn getrandom(buf_ptr: &u8, buf_len: usize, flags: c_uint) c_int; -extern "c" fn __errno_location() &c_int; +pub extern "c" fn getrandom(buf_ptr: *u8, buf_len: usize, flags: c_uint) c_int; +extern "c" fn __errno_location() *c_int; pub const _errno = __errno_location; pub const pthread_attr_t = extern struct { diff --git a/std/c/windows.zig b/std/c/windows.zig index 6e8b17eda8..35ca217131 100644 --- a/std/c/windows.zig +++ b/std/c/windows.zig @@ -1 +1 @@ -pub extern "c" fn _errno() &c_int; +pub extern "c" fn _errno() *c_int; diff --git a/std/crypto/blake2.zig b/std/crypto/blake2.zig index bf3193b5d9..f0a9766c00 100644 --- a/std/crypto/blake2.zig +++ b/std/crypto/blake2.zig @@ -75,7 +75,7 @@ fn Blake2s(comptime out_len: usize) type { return s; } - pub fn reset(d: &Self) void { + pub fn reset(d: *Self) void { mem.copy(u32, d.h[0..], iv[0..]); // No key plus default parameters @@ -90,7 +90,7 @@ fn Blake2s(comptime out_len: usize) type { d.final(out); } - pub fn update(d: &Self, b: []const u8) void { + pub fn update(d: *Self, b: []const u8) void { var off: usize = 0; // Partial buffer exists from previous update. Copy into buffer then hash. @@ -113,7 +113,7 @@ fn Blake2s(comptime out_len: usize) type { d.buf_len += u8(b[off..].len); } - pub fn final(d: &Self, out: []u8) void { + pub fn final(d: *Self, out: []u8) void { debug.assert(out.len >= out_len / 8); mem.set(u8, d.buf[d.buf_len..], 0); @@ -127,7 +127,7 @@ fn Blake2s(comptime out_len: usize) type { } } - fn round(d: &Self, b: []const u8, last: bool) void { + fn round(d: *Self, b: []const u8, last: bool) void { debug.assert(b.len == 64); var m: [16]u32 = undefined; @@ -310,7 +310,7 @@ fn Blake2b(comptime out_len: usize) type { return s; } - pub fn reset(d: &Self) void { + pub fn reset(d: *Self) void { mem.copy(u64, d.h[0..], iv[0..]); // No key plus default parameters @@ -325,7 +325,7 @@ fn Blake2b(comptime out_len: usize) type { d.final(out); } - pub fn update(d: &Self, b: []const u8) void { + pub fn update(d: *Self, b: []const u8) void { var off: usize = 0; // Partial buffer exists from previous update. Copy into buffer then hash. @@ -348,7 +348,7 @@ fn Blake2b(comptime out_len: usize) type { d.buf_len += u8(b[off..].len); } - pub fn final(d: &Self, out: []u8) void { + pub fn final(d: *Self, out: []u8) void { mem.set(u8, d.buf[d.buf_len..], 0); d.t += d.buf_len; d.round(d.buf[0..], true); @@ -360,7 +360,7 @@ fn Blake2b(comptime out_len: usize) type { } } - fn round(d: &Self, b: []const u8, last: bool) void { + fn round(d: *Self, b: []const u8, last: bool) void { debug.assert(b.len == 128); var m: [16]u64 = undefined; diff --git a/std/crypto/md5.zig b/std/crypto/md5.zig index 3d05597273..c0d1732d37 100644 --- a/std/crypto/md5.zig +++ b/std/crypto/md5.zig @@ -44,7 +44,7 @@ pub const Md5 = struct { return d; } - pub fn reset(d: &Self) void { + pub fn reset(d: *Self) void { d.s[0] = 0x67452301; d.s[1] = 0xEFCDAB89; d.s[2] = 0x98BADCFE; @@ -59,7 +59,7 @@ pub const Md5 = struct { d.final(out); } - pub fn update(d: &Self, b: []const u8) void { + pub fn update(d: *Self, b: []const u8) void { var off: usize = 0; // Partial buffer exists from previous update. Copy into buffer then hash. @@ -84,7 +84,7 @@ pub const Md5 = struct { d.total_len +%= b.len; } - pub fn final(d: &Self, out: []u8) void { + pub fn final(d: *Self, out: []u8) void { debug.assert(out.len >= 16); // The buffer here will never be completely full. @@ -116,7 +116,7 @@ pub const Md5 = struct { } } - fn round(d: &Self, b: []const u8) void { + fn round(d: *Self, b: []const u8) void { debug.assert(b.len == 64); var s: [16]u32 = undefined; diff --git a/std/crypto/sha1.zig b/std/crypto/sha1.zig index e9d8e3e132..9e46fc9239 100644 --- a/std/crypto/sha1.zig +++ b/std/crypto/sha1.zig @@ -43,7 +43,7 @@ pub const Sha1 = struct { return d; } - pub fn reset(d: &Self) void { + pub fn reset(d: *Self) void { d.s[0] = 0x67452301; d.s[1] = 0xEFCDAB89; d.s[2] = 0x98BADCFE; @@ -59,7 +59,7 @@ pub const Sha1 = struct { d.final(out); } - pub fn update(d: &Self, b: []const u8) void { + pub fn update(d: *Self, b: []const u8) void { var off: usize = 0; // Partial buffer exists from previous update. Copy into buffer then hash. @@ -83,7 +83,7 @@ pub const Sha1 = struct { d.total_len += b.len; } - pub fn final(d: &Self, out: []u8) void { + pub fn final(d: *Self, out: []u8) void { debug.assert(out.len >= 20); // The buffer here will never be completely full. @@ -115,7 +115,7 @@ pub const Sha1 = struct { } } - fn round(d: &Self, b: []const u8) void { + fn round(d: *Self, b: []const u8) void { debug.assert(b.len == 64); var s: [16]u32 = undefined; diff --git a/std/crypto/sha2.zig b/std/crypto/sha2.zig index aedc820f44..d1375d73e8 100644 --- a/std/crypto/sha2.zig +++ b/std/crypto/sha2.zig @@ -93,7 +93,7 @@ fn Sha2_32(comptime params: Sha2Params32) type { return d; } - pub fn reset(d: &Self) void { + pub fn reset(d: *Self) void { d.s[0] = params.iv0; d.s[1] = params.iv1; d.s[2] = params.iv2; @@ -112,7 +112,7 @@ fn Sha2_32(comptime params: Sha2Params32) type { d.final(out); } - pub fn update(d: &Self, b: []const u8) void { + pub fn update(d: *Self, b: []const u8) void { var off: usize = 0; // Partial buffer exists from previous update. Copy into buffer then hash. @@ -136,7 +136,7 @@ fn Sha2_32(comptime params: Sha2Params32) type { d.total_len += b.len; } - pub fn final(d: &Self, out: []u8) void { + pub fn final(d: *Self, out: []u8) void { debug.assert(out.len >= params.out_len / 8); // The buffer here will never be completely full. @@ -171,7 +171,7 @@ fn Sha2_32(comptime params: Sha2Params32) type { } } - fn round(d: &Self, b: []const u8) void { + fn round(d: *Self, b: []const u8) void { debug.assert(b.len == 64); var s: [64]u32 = undefined; @@ -434,7 +434,7 @@ fn Sha2_64(comptime params: Sha2Params64) type { return d; } - pub fn reset(d: &Self) void { + pub fn reset(d: *Self) void { d.s[0] = params.iv0; d.s[1] = params.iv1; d.s[2] = params.iv2; @@ -453,7 +453,7 @@ fn Sha2_64(comptime params: Sha2Params64) type { d.final(out); } - pub fn update(d: &Self, b: []const u8) void { + pub fn update(d: *Self, b: []const u8) void { var off: usize = 0; // Partial buffer exists from previous update. Copy into buffer then hash. @@ -477,7 +477,7 @@ fn Sha2_64(comptime params: Sha2Params64) type { d.total_len += b.len; } - pub fn final(d: &Self, out: []u8) void { + pub fn final(d: *Self, out: []u8) void { debug.assert(out.len >= params.out_len / 8); // The buffer here will never be completely full. @@ -512,7 +512,7 @@ fn Sha2_64(comptime params: Sha2Params64) type { } } - fn round(d: &Self, b: []const u8) void { + fn round(d: *Self, b: []const u8) void { debug.assert(b.len == 128); var s: [80]u64 = undefined; diff --git a/std/crypto/sha3.zig b/std/crypto/sha3.zig index 75bec57a87..ae02d7a482 100644 --- a/std/crypto/sha3.zig +++ b/std/crypto/sha3.zig @@ -26,7 +26,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type { return d; } - pub fn reset(d: &Self) void { + pub fn reset(d: *Self) void { mem.set(u8, d.s[0..], 0); d.offset = 0; d.rate = 200 - (bits / 4); @@ -38,7 +38,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type { d.final(out); } - pub fn update(d: &Self, b: []const u8) void { + pub fn update(d: *Self, b: []const u8) void { var ip: usize = 0; var len = b.len; var rate = d.rate - d.offset; @@ -63,7 +63,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type { d.offset = offset + len; } - pub fn final(d: &Self, out: []u8) void { + pub fn final(d: *Self, out: []u8) void { // padding d.s[d.offset] ^= delim; d.s[d.rate - 1] ^= 0x80; diff --git a/std/crypto/throughput_test.zig b/std/crypto/throughput_test.zig index c5c4f9fe10..0ad6845d1a 100644 --- a/std/crypto/throughput_test.zig +++ b/std/crypto/throughput_test.zig @@ -15,8 +15,8 @@ const BytesToHash = 1024 * MiB; pub fn main() !void { var stdout_file = try std.io.getStdOut(); - var stdout_out_stream = std.io.FileOutStream.init(&stdout_file); - const stdout = &stdout_out_stream.stream; + var stdout_out_stream = std.io.FileOutStream.init(*stdout_file); + const stdout = *stdout_out_stream.stream; var block: [HashFunction.block_size]u8 = undefined; std.mem.set(u8, block[0..], 0); diff --git a/std/cstr.zig b/std/cstr.zig index c9f3026064..dfbfb8047f 100644 --- a/std/cstr.zig +++ b/std/cstr.zig @@ -9,13 +9,13 @@ pub const line_sep = switch (builtin.os) { else => "\n", }; -pub fn len(ptr: &const u8) usize { +pub fn len(ptr: *const u8) usize { var count: usize = 0; while (ptr[count] != 0) : (count += 1) {} return count; } -pub fn cmp(a: &const u8, b: &const u8) i8 { +pub fn cmp(a: *const u8, b: *const u8) i8 { var index: usize = 0; while (a[index] == b[index] and a[index] != 0) : (index += 1) {} if (a[index] > b[index]) { @@ -27,11 +27,11 @@ pub fn cmp(a: &const u8, b: &const u8) i8 { } } -pub fn toSliceConst(str: &const u8) []const u8 { +pub fn toSliceConst(str: *const u8) []const u8 { return str[0..len(str)]; } -pub fn toSlice(str: &u8) []u8 { +pub fn toSlice(str: *u8) []u8 { return str[0..len(str)]; } @@ -47,7 +47,7 @@ fn testCStrFnsImpl() void { /// Returns a mutable slice with 1 more byte of length which is a null byte. /// Caller owns the returned memory. -pub fn addNullByte(allocator: &mem.Allocator, slice: []const u8) ![]u8 { +pub fn addNullByte(allocator: *mem.Allocator, slice: []const u8) ![]u8 { const result = try allocator.alloc(u8, slice.len + 1); mem.copy(u8, result, slice); result[slice.len] = 0; @@ -55,13 +55,13 @@ pub fn addNullByte(allocator: &mem.Allocator, slice: []const u8) ![]u8 { } pub const NullTerminated2DArray = struct { - allocator: &mem.Allocator, + allocator: *mem.Allocator, byte_count: usize, - ptr: ?&?&u8, + ptr: ?*?*u8, /// Takes N lists of strings, concatenates the lists together, and adds a null terminator /// Caller must deinit result - pub fn fromSlices(allocator: &mem.Allocator, slices: []const []const []const u8) !NullTerminated2DArray { + pub fn fromSlices(allocator: *mem.Allocator, slices: []const []const []const u8) !NullTerminated2DArray { var new_len: usize = 1; // 1 for the list null var byte_count: usize = 0; for (slices) |slice| { @@ -75,11 +75,11 @@ pub const NullTerminated2DArray = struct { const index_size = @sizeOf(usize) * new_len; // size of the ptrs byte_count += index_size; - const buf = try allocator.alignedAlloc(u8, @alignOf(?&u8), byte_count); + const buf = try allocator.alignedAlloc(u8, @alignOf(?*u8), byte_count); errdefer allocator.free(buf); var write_index = index_size; - const index_buf = ([]?&u8)(buf); + const index_buf = ([]?*u8)(buf); var i: usize = 0; for (slices) |slice| { @@ -97,12 +97,12 @@ pub const NullTerminated2DArray = struct { return NullTerminated2DArray{ .allocator = allocator, .byte_count = byte_count, - .ptr = @ptrCast(?&?&u8, buf.ptr), + .ptr = @ptrCast(?*?*u8, buf.ptr), }; } - pub fn deinit(self: &NullTerminated2DArray) void { - const buf = @ptrCast(&u8, self.ptr); + pub fn deinit(self: *NullTerminated2DArray) void { + const buf = @ptrCast(*u8, self.ptr); self.allocator.free(buf[0..self.byte_count]); } }; diff --git a/std/debug/failing_allocator.zig b/std/debug/failing_allocator.zig index 6b5edff5bf..e16dd21db4 100644 --- a/std/debug/failing_allocator.zig +++ b/std/debug/failing_allocator.zig @@ -7,12 +7,12 @@ pub const FailingAllocator = struct { allocator: mem.Allocator, index: usize, fail_index: usize, - internal_allocator: &mem.Allocator, + internal_allocator: *mem.Allocator, allocated_bytes: usize, freed_bytes: usize, deallocations: usize, - pub fn init(allocator: &mem.Allocator, fail_index: usize) FailingAllocator { + pub fn init(allocator: *mem.Allocator, fail_index: usize) FailingAllocator { return FailingAllocator{ .internal_allocator = allocator, .fail_index = fail_index, @@ -28,7 +28,7 @@ pub const FailingAllocator = struct { }; } - fn alloc(allocator: &mem.Allocator, n: usize, alignment: u29) ![]u8 { + fn alloc(allocator: *mem.Allocator, n: usize, alignment: u29) ![]u8 { const self = @fieldParentPtr(FailingAllocator, "allocator", allocator); if (self.index == self.fail_index) { return error.OutOfMemory; @@ -39,7 +39,7 @@ pub const FailingAllocator = struct { return result; } - fn realloc(allocator: &mem.Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { + fn realloc(allocator: *mem.Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { const self = @fieldParentPtr(FailingAllocator, "allocator", allocator); if (new_size <= old_mem.len) { self.freed_bytes += old_mem.len - new_size; @@ -55,7 +55,7 @@ pub const FailingAllocator = struct { return result; } - fn free(allocator: &mem.Allocator, bytes: []u8) void { + fn free(allocator: *mem.Allocator, bytes: []u8) void { const self = @fieldParentPtr(FailingAllocator, "allocator", allocator); self.freed_bytes += bytes.len; self.deallocations += 1; diff --git a/std/debug/index.zig b/std/debug/index.zig index 92e565b391..00d9bef121 100644 --- a/std/debug/index.zig +++ b/std/debug/index.zig @@ -16,12 +16,12 @@ pub const FailingAllocator = @import("failing_allocator.zig").FailingAllocator; /// TODO atomic/multithread support var stderr_file: os.File = undefined; var stderr_file_out_stream: io.FileOutStream = undefined; -var stderr_stream: ?&io.OutStream(io.FileOutStream.Error) = null; +var stderr_stream: ?*io.OutStream(io.FileOutStream.Error) = null; pub fn warn(comptime fmt: []const u8, args: ...) void { const stderr = getStderrStream() catch return; stderr.print(fmt, args) catch return; } -fn getStderrStream() !&io.OutStream(io.FileOutStream.Error) { +fn getStderrStream() !*io.OutStream(io.FileOutStream.Error) { if (stderr_stream) |st| { return st; } else { @@ -33,8 +33,8 @@ fn getStderrStream() !&io.OutStream(io.FileOutStream.Error) { } } -var self_debug_info: ?&ElfStackTrace = null; -pub fn getSelfDebugInfo() !&ElfStackTrace { +var self_debug_info: ?*ElfStackTrace = null; +pub fn getSelfDebugInfo() !*ElfStackTrace { if (self_debug_info) |info| { return info; } else { @@ -58,7 +58,7 @@ pub fn dumpCurrentStackTrace(start_addr: ?usize) void { } /// Tries to print a stack trace to stderr, unbuffered, and ignores any error returned. -pub fn dumpStackTrace(stack_trace: &const builtin.StackTrace) void { +pub fn dumpStackTrace(stack_trace: *const builtin.StackTrace) void { const stderr = getStderrStream() catch return; const debug_info = getSelfDebugInfo() catch |err| { 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 { var panicking: u8 = 0; // TODO make this a bool -pub fn panicExtra(trace: ?&const builtin.StackTrace, first_trace_addr: ?usize, comptime format: []const u8, args: ...) noreturn { +pub fn panicExtra(trace: ?*const builtin.StackTrace, first_trace_addr: ?usize, comptime format: []const u8, args: ...) noreturn { @setCold(true); if (@atomicRmw(u8, &panicking, builtin.AtomicRmwOp.Xchg, 1, builtin.AtomicOrder.SeqCst) == 1) { @@ -130,7 +130,7 @@ const WHITE = "\x1b[37;1m"; const DIM = "\x1b[2m"; const RESET = "\x1b[0m"; -pub fn writeStackTrace(stack_trace: &const builtin.StackTrace, out_stream: var, allocator: &mem.Allocator, debug_info: &ElfStackTrace, tty_color: bool) !void { +pub fn writeStackTrace(stack_trace: *const builtin.StackTrace, out_stream: var, allocator: *mem.Allocator, debug_info: *ElfStackTrace, tty_color: bool) !void { var frame_index: usize = undefined; var frames_left: usize = undefined; if (stack_trace.index < stack_trace.instruction_addresses.len) { @@ -150,7 +150,7 @@ pub fn writeStackTrace(stack_trace: &const builtin.StackTrace, out_stream: var, } } -pub fn writeCurrentStackTrace(out_stream: var, allocator: &mem.Allocator, debug_info: &ElfStackTrace, tty_color: bool, start_addr: ?usize) !void { +pub fn writeCurrentStackTrace(out_stream: var, allocator: *mem.Allocator, debug_info: *ElfStackTrace, tty_color: bool, start_addr: ?usize) !void { const AddressState = union(enum) { NotLookingForStartAddress, LookingForStartAddress: usize, @@ -166,8 +166,8 @@ pub fn writeCurrentStackTrace(out_stream: var, allocator: &mem.Allocator, debug_ } var fp = @ptrToInt(@frameAddress()); - while (fp != 0) : (fp = @intToPtr(&const usize, fp).*) { - const return_address = @intToPtr(&const usize, fp + @sizeOf(usize)).*; + while (fp != 0) : (fp = @intToPtr(*const usize, fp).*) { + const return_address = @intToPtr(*const usize, fp + @sizeOf(usize)).*; switch (addr_state) { AddressState.NotLookingForStartAddress => {}, @@ -183,7 +183,7 @@ pub fn writeCurrentStackTrace(out_stream: var, allocator: &mem.Allocator, debug_ } } -fn printSourceAtAddress(debug_info: &ElfStackTrace, out_stream: var, address: usize) !void { +fn printSourceAtAddress(debug_info: *ElfStackTrace, out_stream: var, address: usize) !void { const ptr_hex = "0x{x}"; switch (builtin.os) { @@ -236,7 +236,7 @@ fn printSourceAtAddress(debug_info: &ElfStackTrace, out_stream: var, address: us } } -pub fn openSelfDebugInfo(allocator: &mem.Allocator) !&ElfStackTrace { +pub fn openSelfDebugInfo(allocator: *mem.Allocator) !*ElfStackTrace { switch (builtin.object_format) { builtin.ObjectFormat.elf => { const st = try allocator.create(ElfStackTrace); @@ -289,7 +289,7 @@ pub fn openSelfDebugInfo(allocator: &mem.Allocator) !&ElfStackTrace { } } -fn printLineFromFile(allocator: &mem.Allocator, out_stream: var, line_info: &const LineInfo) !void { +fn printLineFromFile(allocator: *mem.Allocator, out_stream: var, line_info: *const LineInfo) !void { var f = try os.File.openRead(allocator, line_info.file_name); defer f.close(); // TODO fstat and make sure that the file has the correct size @@ -325,32 +325,32 @@ pub const ElfStackTrace = switch (builtin.os) { builtin.Os.macosx => struct { symbol_table: macho.SymbolTable, - pub fn close(self: &ElfStackTrace) void { + pub fn close(self: *ElfStackTrace) void { self.symbol_table.deinit(); } }, else => struct { self_exe_file: os.File, elf: elf.Elf, - debug_info: &elf.SectionHeader, - debug_abbrev: &elf.SectionHeader, - debug_str: &elf.SectionHeader, - debug_line: &elf.SectionHeader, - debug_ranges: ?&elf.SectionHeader, + debug_info: *elf.SectionHeader, + debug_abbrev: *elf.SectionHeader, + debug_str: *elf.SectionHeader, + debug_line: *elf.SectionHeader, + debug_ranges: ?*elf.SectionHeader, abbrev_table_list: ArrayList(AbbrevTableHeader), compile_unit_list: ArrayList(CompileUnit), - pub fn allocator(self: &const ElfStackTrace) &mem.Allocator { + pub fn allocator(self: *const ElfStackTrace) *mem.Allocator { return self.abbrev_table_list.allocator; } - pub fn readString(self: &ElfStackTrace) ![]u8 { + pub fn readString(self: *ElfStackTrace) ![]u8 { var in_file_stream = io.FileInStream.init(&self.self_exe_file); const in_stream = &in_file_stream.stream; return readStringRaw(self.allocator(), in_stream); } - pub fn close(self: &ElfStackTrace) void { + pub fn close(self: *ElfStackTrace) void { self.self_exe_file.close(); self.elf.close(); } @@ -365,7 +365,7 @@ const PcRange = struct { const CompileUnit = struct { version: u16, is_64: bool, - die: &Die, + die: *Die, index: usize, pc_range: ?PcRange, }; @@ -408,7 +408,7 @@ const Constant = struct { payload: []u8, signed: bool, - fn asUnsignedLe(self: &const Constant) !u64 { + fn asUnsignedLe(self: *const Constant) !u64 { if (self.payload.len > @sizeOf(u64)) return error.InvalidDebugInfo; if (self.signed) return error.InvalidDebugInfo; return mem.readInt(self.payload, u64, builtin.Endian.Little); @@ -425,14 +425,14 @@ const Die = struct { value: FormValue, }; - fn getAttr(self: &const Die, id: u64) ?&const FormValue { + fn getAttr(self: *const Die, id: u64) ?*const FormValue { for (self.attrs.toSliceConst()) |*attr| { if (attr.id == id) return &attr.value; } return null; } - fn getAttrAddr(self: &const Die, id: u64) !u64 { + fn getAttrAddr(self: *const Die, id: u64) !u64 { const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Address => |value| value, @@ -440,7 +440,7 @@ const Die = struct { }; } - fn getAttrSecOffset(self: &const Die, id: u64) !u64 { + fn getAttrSecOffset(self: *const Die, id: u64) !u64 { const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Const => |value| value.asUnsignedLe(), @@ -449,7 +449,7 @@ const Die = struct { }; } - fn getAttrUnsignedLe(self: &const Die, id: u64) !u64 { + fn getAttrUnsignedLe(self: *const Die, id: u64) !u64 { const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Const => |value| value.asUnsignedLe(), @@ -457,7 +457,7 @@ const Die = struct { }; } - fn getAttrString(self: &const Die, st: &ElfStackTrace, id: u64) ![]u8 { + fn getAttrString(self: *const Die, st: *ElfStackTrace, id: u64) ![]u8 { const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; return switch (form_value.*) { FormValue.String => |value| value, @@ -478,9 +478,9 @@ const LineInfo = struct { line: usize, column: usize, file_name: []u8, - allocator: &mem.Allocator, + allocator: *mem.Allocator, - fn deinit(self: &const LineInfo) void { + fn deinit(self: *const LineInfo) void { self.allocator.free(self.file_name); } }; @@ -496,7 +496,7 @@ const LineNumberProgram = struct { target_address: usize, include_dirs: []const []const u8, - file_entries: &ArrayList(FileEntry), + file_entries: *ArrayList(FileEntry), prev_address: usize, prev_file: usize, @@ -506,7 +506,7 @@ const LineNumberProgram = struct { prev_basic_block: bool, prev_end_sequence: bool, - pub fn init(is_stmt: bool, include_dirs: []const []const u8, file_entries: &ArrayList(FileEntry), target_address: usize) LineNumberProgram { + pub fn init(is_stmt: bool, include_dirs: []const []const u8, file_entries: *ArrayList(FileEntry), target_address: usize) LineNumberProgram { return LineNumberProgram{ .address = 0, .file = 1, @@ -528,7 +528,7 @@ const LineNumberProgram = struct { }; } - pub fn checkLineMatch(self: &LineNumberProgram) !?LineInfo { + pub fn checkLineMatch(self: *LineNumberProgram) !?LineInfo { if (self.target_address >= self.prev_address and self.target_address < self.address) { const file_entry = if (self.prev_file == 0) { return error.MissingDebugInfo; @@ -562,7 +562,7 @@ const LineNumberProgram = struct { } }; -fn readStringRaw(allocator: &mem.Allocator, in_stream: var) ![]u8 { +fn readStringRaw(allocator: *mem.Allocator, in_stream: var) ![]u8 { var buf = ArrayList(u8).init(allocator); while (true) { const byte = try in_stream.readByte(); @@ -572,30 +572,30 @@ fn readStringRaw(allocator: &mem.Allocator, in_stream: var) ![]u8 { return buf.toSlice(); } -fn getString(st: &ElfStackTrace, offset: u64) ![]u8 { +fn getString(st: *ElfStackTrace, offset: u64) ![]u8 { const pos = st.debug_str.offset + offset; try st.self_exe_file.seekTo(pos); return st.readString(); } -fn readAllocBytes(allocator: &mem.Allocator, in_stream: var, size: usize) ![]u8 { +fn readAllocBytes(allocator: *mem.Allocator, in_stream: var, size: usize) ![]u8 { const buf = try allocator.alloc(u8, size); errdefer allocator.free(buf); if ((try in_stream.read(buf)) < size) return error.EndOfFile; return buf; } -fn parseFormValueBlockLen(allocator: &mem.Allocator, in_stream: var, size: usize) !FormValue { +fn parseFormValueBlockLen(allocator: *mem.Allocator, in_stream: var, size: usize) !FormValue { const buf = try readAllocBytes(allocator, in_stream, size); return FormValue{ .Block = buf }; } -fn parseFormValueBlock(allocator: &mem.Allocator, in_stream: var, size: usize) !FormValue { +fn parseFormValueBlock(allocator: *mem.Allocator, in_stream: var, size: usize) !FormValue { const block_len = try in_stream.readVarInt(builtin.Endian.Little, usize, size); return parseFormValueBlockLen(allocator, in_stream, block_len); } -fn parseFormValueConstant(allocator: &mem.Allocator, in_stream: var, signed: bool, size: usize) !FormValue { +fn parseFormValueConstant(allocator: *mem.Allocator, in_stream: var, signed: bool, size: usize) !FormValue { return FormValue{ .Const = Constant{ .signed = signed, @@ -612,12 +612,12 @@ fn parseFormValueTargetAddrSize(in_stream: var) !u64 { return if (@sizeOf(usize) == 4) u64(try in_stream.readIntLe(u32)) else if (@sizeOf(usize) == 8) try in_stream.readIntLe(u64) else unreachable; } -fn parseFormValueRefLen(allocator: &mem.Allocator, in_stream: var, size: usize) !FormValue { +fn parseFormValueRefLen(allocator: *mem.Allocator, in_stream: var, size: usize) !FormValue { const buf = try readAllocBytes(allocator, in_stream, size); return FormValue{ .Ref = buf }; } -fn parseFormValueRef(allocator: &mem.Allocator, in_stream: var, comptime T: type) !FormValue { +fn parseFormValueRef(allocator: *mem.Allocator, in_stream: var, comptime T: type) !FormValue { const block_len = try in_stream.readIntLe(T); return parseFormValueRefLen(allocator, in_stream, block_len); } @@ -632,7 +632,7 @@ const ParseFormValueError = error{ OutOfMemory, }; -fn parseFormValue(allocator: &mem.Allocator, in_stream: var, form_id: u64, is_64: bool) ParseFormValueError!FormValue { +fn parseFormValue(allocator: *mem.Allocator, in_stream: var, form_id: u64, is_64: bool) ParseFormValueError!FormValue { return switch (form_id) { DW.FORM_addr => FormValue{ .Address = try parseFormValueTargetAddrSize(in_stream) }, 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 }; } -fn parseAbbrevTable(st: &ElfStackTrace) !AbbrevTable { +fn parseAbbrevTable(st: *ElfStackTrace) !AbbrevTable { const in_file = &st.self_exe_file; var in_file_stream = io.FileInStream.init(in_file); const in_stream = &in_file_stream.stream; @@ -712,7 +712,7 @@ fn parseAbbrevTable(st: &ElfStackTrace) !AbbrevTable { /// Gets an already existing AbbrevTable given the abbrev_offset, or if not found, /// seeks in the stream and parses it. -fn getAbbrevTable(st: &ElfStackTrace, abbrev_offset: u64) !&const AbbrevTable { +fn getAbbrevTable(st: *ElfStackTrace, abbrev_offset: u64) !*const AbbrevTable { for (st.abbrev_table_list.toSlice()) |*header| { if (header.offset == abbrev_offset) { return &header.table; @@ -726,14 +726,14 @@ fn getAbbrevTable(st: &ElfStackTrace, abbrev_offset: u64) !&const AbbrevTable { return &st.abbrev_table_list.items[st.abbrev_table_list.len - 1].table; } -fn getAbbrevTableEntry(abbrev_table: &const AbbrevTable, abbrev_code: u64) ?&const AbbrevTableEntry { +fn getAbbrevTableEntry(abbrev_table: *const AbbrevTable, abbrev_code: u64) ?*const AbbrevTableEntry { for (abbrev_table.toSliceConst()) |*table_entry| { if (table_entry.abbrev_code == abbrev_code) return table_entry; } return null; } -fn parseDie(st: &ElfStackTrace, abbrev_table: &const AbbrevTable, is_64: bool) !Die { +fn parseDie(st: *ElfStackTrace, abbrev_table: *const AbbrevTable, is_64: bool) !Die { const in_file = &st.self_exe_file; var in_file_stream = io.FileInStream.init(in_file); const in_stream = &in_file_stream.stream; @@ -755,7 +755,7 @@ fn parseDie(st: &ElfStackTrace, abbrev_table: &const AbbrevTable, is_64: bool) ! return result; } -fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, target_address: usize) !LineInfo { +fn getLineNumberInfo(st: *ElfStackTrace, compile_unit: *const CompileUnit, target_address: usize) !LineInfo { const compile_unit_cwd = try compile_unit.die.getAttrString(st, DW.AT_comp_dir); const in_file = &st.self_exe_file; @@ -934,7 +934,7 @@ fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, targe return error.MissingDebugInfo; } -fn scanAllCompileUnits(st: &ElfStackTrace) !void { +fn scanAllCompileUnits(st: *ElfStackTrace) !void { const debug_info_end = st.debug_info.offset + st.debug_info.size; var this_unit_offset = st.debug_info.offset; var cu_index: usize = 0; @@ -1005,7 +1005,7 @@ fn scanAllCompileUnits(st: &ElfStackTrace) !void { } } -fn findCompileUnit(st: &ElfStackTrace, target_address: u64) !&const CompileUnit { +fn findCompileUnit(st: *ElfStackTrace, target_address: u64) !*const CompileUnit { var in_file_stream = io.FileInStream.init(&st.self_exe_file); const in_stream = &in_file_stream.stream; for (st.compile_unit_list.toSlice()) |*compile_unit| { @@ -1039,7 +1039,7 @@ fn findCompileUnit(st: &ElfStackTrace, target_address: u64) !&const CompileUnit return error.MissingDebugInfo; } -fn readInitialLength(comptime E: type, in_stream: &io.InStream(E), is_64: &bool) !u64 { +fn readInitialLength(comptime E: type, in_stream: *io.InStream(E), is_64: *bool) !u64 { const first_32_bits = try in_stream.readIntLe(u32); is_64.* = (first_32_bits == 0xffffffff); if (is_64.*) { @@ -1096,10 +1096,10 @@ var global_fixed_allocator = std.heap.FixedBufferAllocator.init(global_allocator var global_allocator_mem: [100 * 1024]u8 = undefined; // TODO make thread safe -var debug_info_allocator: ?&mem.Allocator = null; +var debug_info_allocator: ?*mem.Allocator = null; var debug_info_direct_allocator: std.heap.DirectAllocator = undefined; var debug_info_arena_allocator: std.heap.ArenaAllocator = undefined; -fn getDebugInfoAllocator() &mem.Allocator { +fn getDebugInfoAllocator() *mem.Allocator { if (debug_info_allocator) |a| return a; debug_info_direct_allocator = std.heap.DirectAllocator.init(); diff --git a/std/elf.zig b/std/elf.zig index 29b9473f98..50e97ab271 100644 --- a/std/elf.zig +++ b/std/elf.zig @@ -338,7 +338,7 @@ pub const SectionHeader = struct { }; pub const Elf = struct { - in_file: &os.File, + in_file: *os.File, auto_close_stream: bool, is_64: bool, endian: builtin.Endian, @@ -348,20 +348,20 @@ pub const Elf = struct { program_header_offset: u64, section_header_offset: u64, string_section_index: u64, - string_section: &SectionHeader, + string_section: *SectionHeader, section_headers: []SectionHeader, - allocator: &mem.Allocator, + allocator: *mem.Allocator, prealloc_file: os.File, /// Call close when done. - pub fn openPath(elf: &Elf, allocator: &mem.Allocator, path: []const u8) !void { + pub fn openPath(elf: *Elf, allocator: *mem.Allocator, path: []const u8) !void { try elf.prealloc_file.open(path); - try elf.openFile(allocator, &elf.prealloc_file); + try elf.openFile(allocator, *elf.prealloc_file); elf.auto_close_stream = true; } /// Call close when done. - pub fn openFile(elf: &Elf, allocator: &mem.Allocator, file: &os.File) !void { + pub fn openFile(elf: *Elf, allocator: *mem.Allocator, file: *os.File) !void { elf.allocator = allocator; elf.in_file = file; elf.auto_close_stream = false; @@ -503,13 +503,13 @@ pub const Elf = struct { } } - pub fn close(elf: &Elf) void { + pub fn close(elf: *Elf) void { elf.allocator.free(elf.section_headers); if (elf.auto_close_stream) elf.in_file.close(); } - pub fn findSection(elf: &Elf, name: []const u8) !?&SectionHeader { + pub fn findSection(elf: *Elf, name: []const u8) !?*SectionHeader { var file_stream = io.FileInStream.init(elf.in_file); const in = &file_stream.stream; @@ -533,7 +533,7 @@ pub const Elf = struct { return null; } - pub fn seekToSection(elf: &Elf, elf_section: &SectionHeader) !void { + pub fn seekToSection(elf: *Elf, elf_section: *SectionHeader) !void { try elf.in_file.seekTo(elf_section.offset); } }; diff --git a/std/event.zig b/std/event.zig index 4604eb8d02..89ab816bb6 100644 --- a/std/event.zig +++ b/std/event.zig @@ -6,9 +6,9 @@ const mem = std.mem; const posix = std.os.posix; pub const TcpServer = struct { - handleRequestFn: async<&mem.Allocator> fn (&TcpServer, &const std.net.Address, &const std.os.File) void, + handleRequestFn: async<*mem.Allocator> fn (*TcpServer, *const std.net.Address, *const std.os.File) void, - loop: &Loop, + loop: *Loop, sockfd: i32, accept_coro: ?promise, listen_address: std.net.Address, @@ -17,7 +17,7 @@ pub const TcpServer = struct { const PromiseNode = std.LinkedList(promise).Node; - pub fn init(loop: &Loop) !TcpServer { + pub fn init(loop: *Loop) !TcpServer { const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp); errdefer std.os.close(sockfd); @@ -32,7 +32,7 @@ pub const TcpServer = struct { }; } - 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 { + 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 { self.handleRequestFn = handleRequestFn; try std.os.posixBind(self.sockfd, &address.os_addr); @@ -46,13 +46,13 @@ pub const TcpServer = struct { errdefer self.loop.removeFd(self.sockfd); } - pub fn deinit(self: &TcpServer) void { + pub fn deinit(self: *TcpServer) void { self.loop.removeFd(self.sockfd); if (self.accept_coro) |accept_coro| cancel accept_coro; std.os.close(self.sockfd); } - pub async fn handler(self: &TcpServer) void { + pub async fn handler(self: *TcpServer) void { while (true) { var accepted_addr: std.net.Address = undefined; 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 { }; pub const Loop = struct { - allocator: &mem.Allocator, + allocator: *mem.Allocator, epollfd: i32, keep_running: bool, - fn init(allocator: &mem.Allocator) !Loop { + fn init(allocator: *mem.Allocator) !Loop { const epollfd = try std.os.linuxEpollCreate(std.os.linux.EPOLL_CLOEXEC); return Loop{ .keep_running = true, @@ -105,7 +105,7 @@ pub const Loop = struct { }; } - pub fn addFd(self: &Loop, fd: i32, prom: promise) !void { + pub fn addFd(self: *Loop, fd: i32, prom: promise) !void { var ev = std.os.linux.epoll_event{ .events = std.os.linux.EPOLLIN | std.os.linux.EPOLLOUT | std.os.linux.EPOLLET, .data = std.os.linux.epoll_data{ .ptr = @ptrToInt(prom) }, @@ -113,23 +113,23 @@ pub const Loop = struct { try std.os.linuxEpollCtl(self.epollfd, std.os.linux.EPOLL_CTL_ADD, fd, &ev); } - pub fn removeFd(self: &Loop, fd: i32) void { + pub fn removeFd(self: *Loop, fd: i32) void { std.os.linuxEpollCtl(self.epollfd, std.os.linux.EPOLL_CTL_DEL, fd, undefined) catch {}; } - async fn waitFd(self: &Loop, fd: i32) !void { + async fn waitFd(self: *Loop, fd: i32) !void { defer self.removeFd(fd); suspend |p| { try self.addFd(fd, p); } } - pub fn stop(self: &Loop) void { + pub fn stop(self: *Loop) void { // TODO make atomic self.keep_running = false; // TODO activate an fd in the epoll set } - pub fn run(self: &Loop) void { + pub fn run(self: *Loop) void { while (self.keep_running) { var events: [16]std.os.linux.epoll_event = undefined; const count = std.os.linuxEpollWait(self.epollfd, events[0..], -1); @@ -141,7 +141,7 @@ pub const Loop = struct { } }; -pub async fn connect(loop: &Loop, _address: &const std.net.Address) !std.os.File { +pub async fn connect(loop: *Loop, _address: *const std.net.Address) !std.os.File { var address = _address.*; // TODO https://github.com/ziglang/zig/issues/733 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" { tcp_server: TcpServer, const Self = this; - async<&mem.Allocator> fn handler(tcp_server: &TcpServer, _addr: &const std.net.Address, _socket: &const std.os.File) void { + async<*mem.Allocator> fn handler(tcp_server: *TcpServer, _addr: *const std.net.Address, _socket: *const std.os.File) void { const self = @fieldParentPtr(Self, "tcp_server", tcp_server); var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733 defer socket.close(); @@ -177,7 +177,7 @@ test "listen on a port, send bytes, receive bytes" { cancel p; } } - async fn errorableHandler(self: &Self, _addr: &const std.net.Address, _socket: &const std.os.File) !void { + async fn errorableHandler(self: *Self, _addr: *const std.net.Address, _socket: *const std.os.File) !void { const addr = _addr.*; // TODO https://github.com/ziglang/zig/issues/733 var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733 @@ -199,7 +199,7 @@ test "listen on a port, send bytes, receive bytes" { defer cancel p; loop.run(); } -async fn doAsyncTest(loop: &Loop, address: &const std.net.Address) void { +async fn doAsyncTest(loop: *Loop, address: *const std.net.Address) void { errdefer @panic("test failure"); var socket_file = try await try async event.connect(loop, address); diff --git a/std/fmt/errol/index.zig b/std/fmt/errol/index.zig index 65e8d448a8..933958ac18 100644 --- a/std/fmt/errol/index.zig +++ b/std/fmt/errol/index.zig @@ -21,7 +21,7 @@ pub const RoundMode = enum { /// Round a FloatDecimal as returned by errol3 to the specified fractional precision. /// All digits after the specified precision should be considered invalid. -pub fn roundToPrecision(float_decimal: &FloatDecimal, precision: usize, mode: RoundMode) void { +pub fn roundToPrecision(float_decimal: *FloatDecimal, precision: usize, mode: RoundMode) void { // The round digit refers to the index which we should look at to determine // whether we need to round to match the specified precision. var round_digit: usize = 0; @@ -59,7 +59,7 @@ pub fn roundToPrecision(float_decimal: &FloatDecimal, precision: usize, mode: Ro float_decimal.exp += 1; // Re-size the buffer to use the reserved leading byte. - const one_before = @intToPtr(&u8, @ptrToInt(&float_decimal.digits[0]) - 1); + const one_before = @intToPtr(*u8, @ptrToInt(&float_decimal.digits[0]) - 1); float_decimal.digits = one_before[0 .. float_decimal.digits.len + 1]; float_decimal.digits[0] = '1'; return; @@ -217,7 +217,7 @@ fn tableLowerBound(k: u64) usize { /// @in: The HP number. /// @val: The double. /// &returns: The HP number. -fn hpProd(in: &const HP, val: f64) HP { +fn hpProd(in: *const HP, val: f64) HP { var hi: f64 = undefined; var lo: f64 = undefined; split(in.val, &hi, &lo); @@ -239,7 +239,7 @@ fn hpProd(in: &const HP, val: f64) HP { /// @val: The double. /// @hi: The high bits. /// @lo: The low bits. -fn split(val: f64, hi: &f64, lo: &f64) void { +fn split(val: f64, hi: *f64, lo: *f64) void { hi.* = gethi(val); lo.* = val - hi.*; } @@ -252,7 +252,7 @@ fn gethi(in: f64) f64 { /// Normalize the number by factoring in the error. /// @hp: The float pair. -fn hpNormalize(hp: &HP) void { +fn hpNormalize(hp: *HP) void { // Required to avoid segfaults causing buffer overrun during errol3 digit output termination. @setFloatMode(this, @import("builtin").FloatMode.Strict); @@ -264,7 +264,7 @@ fn hpNormalize(hp: &HP) void { /// Divide the high-precision number by ten. /// @hp: The high-precision number -fn hpDiv10(hp: &HP) void { +fn hpDiv10(hp: *HP) void { var val = hp.val; hp.val /= 10.0; @@ -280,7 +280,7 @@ fn hpDiv10(hp: &HP) void { /// Multiply the high-precision number by ten. /// @hp: The high-precision number -fn hpMul10(hp: &HP) void { +fn hpMul10(hp: *HP) void { const val = hp.val; hp.val *= 10.0; diff --git a/std/fmt/index.zig b/std/fmt/index.zig index 0ffbc59895..b522d9d37d 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -679,7 +679,7 @@ const FormatIntBuf = struct { out_buf: []u8, index: usize, }; -fn formatIntCallback(context: &FormatIntBuf, bytes: []const u8) (error{}!void) { +fn formatIntCallback(context: *FormatIntBuf, bytes: []const u8) (error{}!void) { mem.copy(u8, context.out_buf[context.index..], bytes); context.index += bytes.len; } @@ -751,7 +751,7 @@ const BufPrintContext = struct { remaining: []u8, }; -fn bufPrintWrite(context: &BufPrintContext, bytes: []const u8) !void { +fn bufPrintWrite(context: *BufPrintContext, bytes: []const u8) !void { if (context.remaining.len < bytes.len) return error.BufferTooSmall; mem.copy(u8, context.remaining, bytes); context.remaining = context.remaining[bytes.len..]; @@ -763,14 +763,14 @@ pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: ...) ![]u8 { return buf[0 .. buf.len - context.remaining.len]; } -pub fn allocPrint(allocator: &mem.Allocator, comptime fmt: []const u8, args: ...) ![]u8 { +pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: ...) ![]u8 { var size: usize = 0; format(&size, error{}, countSize, fmt, args) catch |err| switch (err) {}; const buf = try allocator.alloc(u8, size); return bufPrint(buf, fmt, args); } -fn countSize(size: &usize, bytes: []const u8) (error{}!void) { +fn countSize(size: *usize, bytes: []const u8) (error{}!void) { size.* += bytes.len; } diff --git a/std/hash/adler.zig b/std/hash/adler.zig index 12dab1457c..9c5966f89b 100644 --- a/std/hash/adler.zig +++ b/std/hash/adler.zig @@ -18,7 +18,7 @@ pub const Adler32 = struct { // This fast variant is taken from zlib. It reduces the required modulos and unrolls longer // buffer inputs and should be much quicker. - pub fn update(self: &Adler32, input: []const u8) void { + pub fn update(self: *Adler32, input: []const u8) void { var s1 = self.adler & 0xffff; var s2 = (self.adler >> 16) & 0xffff; @@ -77,7 +77,7 @@ pub const Adler32 = struct { self.adler = s1 | (s2 << 16); } - pub fn final(self: &Adler32) u32 { + pub fn final(self: *Adler32) u32 { return self.adler; } diff --git a/std/hash/crc.zig b/std/hash/crc.zig index 45bcb70e8b..ec831cdc2e 100644 --- a/std/hash/crc.zig +++ b/std/hash/crc.zig @@ -58,7 +58,7 @@ pub fn Crc32WithPoly(comptime poly: u32) type { return Self{ .crc = 0xffffffff }; } - pub fn update(self: &Self, input: []const u8) void { + pub fn update(self: *Self, input: []const u8) void { var i: usize = 0; while (i + 8 <= input.len) : (i += 8) { const p = input[i .. i + 8]; @@ -86,7 +86,7 @@ pub fn Crc32WithPoly(comptime poly: u32) type { } } - pub fn final(self: &Self) u32 { + pub fn final(self: *Self) u32 { return ~self.crc; } @@ -143,14 +143,14 @@ pub fn Crc32SmallWithPoly(comptime poly: u32) type { return Self{ .crc = 0xffffffff }; } - pub fn update(self: &Self, input: []const u8) void { + pub fn update(self: *Self, input: []const u8) void { for (input) |b| { self.crc = lookup_table[@truncate(u4, self.crc ^ (b >> 0))] ^ (self.crc >> 4); self.crc = lookup_table[@truncate(u4, self.crc ^ (b >> 4))] ^ (self.crc >> 4); } } - pub fn final(self: &Self) u32 { + pub fn final(self: *Self) u32 { return ~self.crc; } diff --git a/std/hash/fnv.zig b/std/hash/fnv.zig index c2439e0ebc..447c996772 100644 --- a/std/hash/fnv.zig +++ b/std/hash/fnv.zig @@ -21,14 +21,14 @@ fn Fnv1a(comptime T: type, comptime prime: T, comptime offset: T) type { return Self{ .value = offset }; } - pub fn update(self: &Self, input: []const u8) void { + pub fn update(self: *Self, input: []const u8) void { for (input) |b| { self.value ^= b; self.value *%= prime; } } - pub fn final(self: &Self) T { + pub fn final(self: *Self) T { return self.value; } diff --git a/std/hash/siphash.zig b/std/hash/siphash.zig index 750e23d4c8..8a90308a46 100644 --- a/std/hash/siphash.zig +++ b/std/hash/siphash.zig @@ -63,7 +63,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) return d; } - pub fn update(d: &Self, b: []const u8) void { + pub fn update(d: *Self, b: []const u8) void { var off: usize = 0; // Partial from previous. @@ -85,7 +85,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) d.msg_len +%= @truncate(u8, b.len); } - pub fn final(d: &Self) T { + pub fn final(d: *Self) T { // Padding mem.set(u8, d.buf[d.buf_len..], 0); d.buf[7] = d.msg_len; @@ -118,7 +118,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) return (u128(b2) << 64) | b1; } - fn round(d: &Self, b: []const u8) void { + fn round(d: *Self, b: []const u8) void { debug.assert(b.len == 8); 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) d.v0 ^= m; } - fn sipRound(d: &Self) void { + fn sipRound(d: *Self) void { d.v0 +%= d.v1; d.v1 = math.rotl(u64, d.v1, u64(13)); d.v1 ^= d.v0; diff --git a/std/hash_map.zig b/std/hash_map.zig index f51b9c66ba..a323cdc197 100644 --- a/std/hash_map.zig +++ b/std/hash_map.zig @@ -14,7 +14,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 entries: []Entry, size: usize, max_distance_from_start_index: usize, - allocator: &Allocator, + allocator: *Allocator, // this is used to detect bugs where a hashtable is edited while an iterator is running. modification_count: debug_u32, @@ -28,7 +28,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 }; pub const Iterator = struct { - hm: &const Self, + hm: *const Self, // how many items have we returned count: usize, // iterator through the entry array @@ -36,7 +36,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 // used to detect concurrent modification initial_modification_count: debug_u32, - pub fn next(it: &Iterator) ?&Entry { + pub fn next(it: *Iterator) ?*Entry { if (want_modification_safety) { assert(it.initial_modification_count == it.hm.modification_count); // concurrent modification } @@ -53,7 +53,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 } // Reset the iterator to the initial index - pub fn reset(it: &Iterator) void { + pub fn reset(it: *Iterator) void { it.count = 0; it.index = 0; // Resetting the modification count too @@ -61,7 +61,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 } }; - pub fn init(allocator: &Allocator) Self { + pub fn init(allocator: *Allocator) Self { return Self{ .entries = []Entry{}, .allocator = allocator, @@ -71,11 +71,11 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 }; } - pub fn deinit(hm: &const Self) void { + pub fn deinit(hm: *const Self) void { hm.allocator.free(hm.entries); } - pub fn clear(hm: &Self) void { + pub fn clear(hm: *Self) void { for (hm.entries) |*entry| { entry.used = false; } @@ -84,12 +84,12 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 hm.incrementModificationCount(); } - pub fn count(hm: &const Self) usize { + pub fn count(hm: *const Self) usize { return hm.size; } /// Returns the value that was already there. - pub fn put(hm: &Self, key: K, value: &const V) !?V { + pub fn put(hm: *Self, key: K, value: *const V) !?V { if (hm.entries.len == 0) { try hm.initCapacity(16); } @@ -111,18 +111,18 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 return hm.internalPut(key, value); } - pub fn get(hm: &const Self, key: K) ?&Entry { + pub fn get(hm: *const Self, key: K) ?*Entry { if (hm.entries.len == 0) { return null; } return hm.internalGet(key); } - pub fn contains(hm: &const Self, key: K) bool { + pub fn contains(hm: *const Self, key: K) bool { return hm.get(key) != null; } - pub fn remove(hm: &Self, key: K) ?&Entry { + pub fn remove(hm: *Self, key: K) ?*Entry { if (hm.entries.len == 0) return null; hm.incrementModificationCount(); const start_index = hm.keyToIndex(key); @@ -154,7 +154,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 return null; } - pub fn iterator(hm: &const Self) Iterator { + pub fn iterator(hm: *const Self) Iterator { return Iterator{ .hm = hm, .count = 0, @@ -163,7 +163,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 }; } - fn initCapacity(hm: &Self, capacity: usize) !void { + fn initCapacity(hm: *Self, capacity: usize) !void { hm.entries = try hm.allocator.alloc(Entry, capacity); hm.size = 0; 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) u3 } } - fn incrementModificationCount(hm: &Self) void { + fn incrementModificationCount(hm: *Self) void { if (want_modification_safety) { hm.modification_count +%= 1; } } /// Returns the value that was already there. - fn internalPut(hm: &Self, orig_key: K, orig_value: &const V) ?V { + fn internalPut(hm: *Self, orig_key: K, orig_value: *const V) ?V { var key = orig_key; var value = orig_value.*; const start_index = hm.keyToIndex(key); @@ -231,7 +231,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 unreachable; // put into a full map } - fn internalGet(hm: &const Self, key: K) ?&Entry { + fn internalGet(hm: *const Self, key: K) ?*Entry { const start_index = hm.keyToIndex(key); { var roll_over: usize = 0; @@ -246,7 +246,7 @@ pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn (key: K) u3 return null; } - fn keyToIndex(hm: &const Self, key: K) usize { + fn keyToIndex(hm: *const Self, key: K) usize { return usize(hash(key)) % hm.entries.len; } }; diff --git a/std/heap.zig b/std/heap.zig index 8d4938a7c3..81d6f25282 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -16,15 +16,15 @@ var c_allocator_state = Allocator{ .freeFn = cFree, }; -fn cAlloc(self: &Allocator, n: usize, alignment: u29) ![]u8 { +fn cAlloc(self: *Allocator, n: usize, alignment: u29) ![]u8 { assert(alignment <= @alignOf(c_longdouble)); - return if (c.malloc(n)) |buf| @ptrCast(&u8, buf)[0..n] else error.OutOfMemory; + return if (c.malloc(n)) |buf| @ptrCast(*u8, buf)[0..n] else error.OutOfMemory; } -fn cRealloc(self: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { - const old_ptr = @ptrCast(&c_void, old_mem.ptr); +fn cRealloc(self: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { + const old_ptr = @ptrCast(*c_void, old_mem.ptr); if (c.realloc(old_ptr, new_size)) |buf| { - return @ptrCast(&u8, buf)[0..new_size]; + return @ptrCast(*u8, buf)[0..new_size]; } else if (new_size <= old_mem.len) { return old_mem[0..new_size]; } else { @@ -32,8 +32,8 @@ fn cRealloc(self: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![ } } -fn cFree(self: &Allocator, old_mem: []u8) void { - const old_ptr = @ptrCast(&c_void, old_mem.ptr); +fn cFree(self: *Allocator, old_mem: []u8) void { + const old_ptr = @ptrCast(*c_void, old_mem.ptr); c.free(old_ptr); } @@ -55,7 +55,7 @@ pub const DirectAllocator = struct { }; } - pub fn deinit(self: &DirectAllocator) void { + pub fn deinit(self: *DirectAllocator) void { switch (builtin.os) { Os.windows => if (self.heap_handle) |heap_handle| { _ = os.windows.HeapDestroy(heap_handle); @@ -64,7 +64,7 @@ pub const DirectAllocator = struct { } } - fn alloc(allocator: &Allocator, n: usize, alignment: u29) ![]u8 { + fn alloc(allocator: *Allocator, n: usize, alignment: u29) ![]u8 { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { @@ -74,7 +74,7 @@ pub const DirectAllocator = struct { const addr = p.mmap(null, alloc_size, p.PROT_READ | p.PROT_WRITE, p.MAP_PRIVATE | p.MAP_ANONYMOUS, -1, 0); if (addr == p.MAP_FAILED) return error.OutOfMemory; - if (alloc_size == n) return @intToPtr(&u8, addr)[0..n]; + if (alloc_size == n) return @intToPtr(*u8, addr)[0..n]; var aligned_addr = addr & ~usize(alignment - 1); aligned_addr += alignment; @@ -93,7 +93,7 @@ pub const DirectAllocator = struct { //It is impossible that there is an unoccupied page at the top of our // mmap. - return @intToPtr(&u8, aligned_addr)[0..n]; + return @intToPtr(*u8, aligned_addr)[0..n]; }, Os.windows => { const amt = n + alignment + @sizeOf(usize); @@ -108,14 +108,14 @@ pub const DirectAllocator = struct { const march_forward_bytes = if (rem == 0) 0 else (alignment - rem); const adjusted_addr = root_addr + march_forward_bytes; const record_addr = adjusted_addr + n; - @intToPtr(&align(1) usize, record_addr).* = root_addr; - return @intToPtr(&u8, adjusted_addr)[0..n]; + @intToPtr(*align(1) usize, record_addr).* = root_addr; + return @intToPtr(*u8, adjusted_addr)[0..n]; }, else => @compileError("Unsupported OS"), } } - fn realloc(allocator: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { + fn realloc(allocator: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { @@ -139,13 +139,13 @@ pub const DirectAllocator = struct { Os.windows => { const old_adjusted_addr = @ptrToInt(old_mem.ptr); const old_record_addr = old_adjusted_addr + old_mem.len; - const root_addr = @intToPtr(&align(1) usize, old_record_addr).*; + const root_addr = @intToPtr(*align(1) usize, old_record_addr).*; const old_ptr = @intToPtr(os.windows.LPVOID, root_addr); const amt = new_size + alignment + @sizeOf(usize); const new_ptr = os.windows.HeapReAlloc(??self.heap_handle, 0, old_ptr, amt) ?? blk: { if (new_size > old_mem.len) return error.OutOfMemory; const new_record_addr = old_record_addr - new_size + old_mem.len; - @intToPtr(&align(1) usize, new_record_addr).* = root_addr; + @intToPtr(*align(1) usize, new_record_addr).* = root_addr; return old_mem[0..new_size]; }; const offset = old_adjusted_addr - root_addr; @@ -153,14 +153,14 @@ pub const DirectAllocator = struct { const new_adjusted_addr = new_root_addr + offset; assert(new_adjusted_addr % alignment == 0); const new_record_addr = new_adjusted_addr + new_size; - @intToPtr(&align(1) usize, new_record_addr).* = new_root_addr; - return @intToPtr(&u8, new_adjusted_addr)[0..new_size]; + @intToPtr(*align(1) usize, new_record_addr).* = new_root_addr; + return @intToPtr(*u8, new_adjusted_addr)[0..new_size]; }, else => @compileError("Unsupported OS"), } } - fn free(allocator: &Allocator, bytes: []u8) void { + fn free(allocator: *Allocator, bytes: []u8) void { const self = @fieldParentPtr(DirectAllocator, "allocator", allocator); switch (builtin.os) { @@ -169,7 +169,7 @@ pub const DirectAllocator = struct { }, Os.windows => { const record_addr = @ptrToInt(bytes.ptr) + bytes.len; - const root_addr = @intToPtr(&align(1) usize, record_addr).*; + const root_addr = @intToPtr(*align(1) usize, record_addr).*; const ptr = @intToPtr(os.windows.LPVOID, root_addr); _ = os.windows.HeapFree(??self.heap_handle, 0, ptr); }, @@ -183,13 +183,13 @@ pub const DirectAllocator = struct { pub const ArenaAllocator = struct { pub allocator: Allocator, - child_allocator: &Allocator, + child_allocator: *Allocator, buffer_list: std.LinkedList([]u8), end_index: usize, const BufNode = std.LinkedList([]u8).Node; - pub fn init(child_allocator: &Allocator) ArenaAllocator { + pub fn init(child_allocator: *Allocator) ArenaAllocator { return ArenaAllocator{ .allocator = Allocator{ .allocFn = alloc, @@ -202,7 +202,7 @@ pub const ArenaAllocator = struct { }; } - pub fn deinit(self: &ArenaAllocator) void { + pub fn deinit(self: *ArenaAllocator) void { var it = self.buffer_list.first; while (it) |node| { // this has to occur before the free because the free frees node @@ -212,7 +212,7 @@ pub const ArenaAllocator = struct { } } - fn createNode(self: &ArenaAllocator, prev_len: usize, minimum_size: usize) !&BufNode { + fn createNode(self: *ArenaAllocator, prev_len: usize, minimum_size: usize) !*BufNode { const actual_min_size = minimum_size + @sizeOf(BufNode); var len = prev_len; while (true) { @@ -233,7 +233,7 @@ pub const ArenaAllocator = struct { return buf_node; } - fn alloc(allocator: &Allocator, n: usize, alignment: u29) ![]u8 { + fn alloc(allocator: *Allocator, n: usize, alignment: u29) ![]u8 { const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator); var cur_node = if (self.buffer_list.last) |last_node| last_node else try self.createNode(0, n + alignment); @@ -254,7 +254,7 @@ pub const ArenaAllocator = struct { } } - fn realloc(allocator: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { + fn realloc(allocator: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { if (new_size <= old_mem.len) { return old_mem[0..new_size]; } else { @@ -264,7 +264,7 @@ pub const ArenaAllocator = struct { } } - fn free(allocator: &Allocator, bytes: []u8) void {} + fn free(allocator: *Allocator, bytes: []u8) void {} }; pub const FixedBufferAllocator = struct { @@ -284,7 +284,7 @@ pub const FixedBufferAllocator = struct { }; } - fn alloc(allocator: &Allocator, n: usize, alignment: u29) ![]u8 { + fn alloc(allocator: *Allocator, n: usize, alignment: u29) ![]u8 { const self = @fieldParentPtr(FixedBufferAllocator, "allocator", allocator); const addr = @ptrToInt(self.buffer.ptr) + self.end_index; const rem = @rem(addr, alignment); @@ -300,7 +300,7 @@ pub const FixedBufferAllocator = struct { return result; } - fn realloc(allocator: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { + fn realloc(allocator: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { if (new_size <= old_mem.len) { return old_mem[0..new_size]; } else { @@ -310,7 +310,7 @@ pub const FixedBufferAllocator = struct { } } - fn free(allocator: &Allocator, bytes: []u8) void {} + fn free(allocator: *Allocator, bytes: []u8) void {} }; /// lock free @@ -331,7 +331,7 @@ pub const ThreadSafeFixedBufferAllocator = struct { }; } - fn alloc(allocator: &Allocator, n: usize, alignment: u29) ![]u8 { + fn alloc(allocator: *Allocator, n: usize, alignment: u29) ![]u8 { const self = @fieldParentPtr(ThreadSafeFixedBufferAllocator, "allocator", allocator); var end_index = @atomicLoad(usize, &self.end_index, builtin.AtomicOrder.SeqCst); while (true) { @@ -343,11 +343,11 @@ pub const ThreadSafeFixedBufferAllocator = struct { if (new_end_index > self.buffer.len) { return error.OutOfMemory; } - end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst) ?? return self.buffer[adjusted_index..new_end_index]; + end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst,) ?? return self.buffer[adjusted_index..new_end_index]; } } - fn realloc(allocator: &Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { + fn realloc(allocator: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { if (new_size <= old_mem.len) { return old_mem[0..new_size]; } else { @@ -357,7 +357,7 @@ pub const ThreadSafeFixedBufferAllocator = struct { } } - fn free(allocator: &Allocator, bytes: []u8) void {} + fn free(allocator: *Allocator, bytes: []u8) void {} }; test "c_allocator" { @@ -403,8 +403,8 @@ test "ThreadSafeFixedBufferAllocator" { try testAllocatorLargeAlignment(&fixed_buffer_allocator.allocator); } -fn testAllocator(allocator: &mem.Allocator) !void { - var slice = try allocator.alloc(&i32, 100); +fn testAllocator(allocator: *mem.Allocator) !void { + var slice = try allocator.alloc(*i32, 100); for (slice) |*item, i| { item.* = try allocator.create(i32); @@ -415,15 +415,15 @@ fn testAllocator(allocator: &mem.Allocator) !void { allocator.destroy(item); } - slice = try allocator.realloc(&i32, slice, 20000); - slice = try allocator.realloc(&i32, slice, 50); - slice = try allocator.realloc(&i32, slice, 25); - slice = try allocator.realloc(&i32, slice, 10); + slice = try allocator.realloc(*i32, slice, 20000); + slice = try allocator.realloc(*i32, slice, 50); + slice = try allocator.realloc(*i32, slice, 25); + slice = try allocator.realloc(*i32, slice, 10); allocator.free(slice); } -fn testAllocatorLargeAlignment(allocator: &mem.Allocator) mem.Allocator.Error!void { +fn testAllocatorLargeAlignment(allocator: *mem.Allocator) mem.Allocator.Error!void { //Maybe a platform's page_size is actually the same as or // very near usize? if (os.page_size << 2 > @maxValue(usize)) return; diff --git a/std/io.zig b/std/io.zig index 39d319159e..e20a284e4e 100644 --- a/std/io.zig +++ b/std/io.zig @@ -34,20 +34,20 @@ pub fn getStdIn() GetStdIoErrs!File { /// Implementation of InStream trait for File pub const FileInStream = struct { - file: &File, + file: *File, stream: Stream, pub const Error = @typeOf(File.read).ReturnType.ErrorSet; pub const Stream = InStream(Error); - pub fn init(file: &File) FileInStream { + pub fn init(file: *File) FileInStream { return FileInStream{ .file = file, .stream = Stream{ .readFn = readFn }, }; } - fn readFn(in_stream: &Stream, buffer: []u8) Error!usize { + fn readFn(in_stream: *Stream, buffer: []u8) Error!usize { const self = @fieldParentPtr(FileInStream, "stream", in_stream); return self.file.read(buffer); } @@ -55,20 +55,20 @@ pub const FileInStream = struct { /// Implementation of OutStream trait for File pub const FileOutStream = struct { - file: &File, + file: *File, stream: Stream, pub const Error = File.WriteError; pub const Stream = OutStream(Error); - pub fn init(file: &File) FileOutStream { + pub fn init(file: *File) FileOutStream { return FileOutStream{ .file = file, .stream = Stream{ .writeFn = writeFn }, }; } - fn writeFn(out_stream: &Stream, bytes: []const u8) !void { + fn writeFn(out_stream: *Stream, bytes: []const u8) !void { const self = @fieldParentPtr(FileOutStream, "stream", out_stream); return self.file.write(bytes); } @@ -82,12 +82,12 @@ pub fn InStream(comptime ReadError: type) type { /// Return the number of bytes read. If the number read is smaller than buf.len, it /// means the stream reached the end. Reaching the end of a stream is not an error /// condition. - readFn: fn (self: &Self, buffer: []u8) Error!usize, + readFn: fn (self: *Self, buffer: []u8) Error!usize, /// Replaces `buffer` contents by reading from the stream until it is finished. /// If `buffer.len()` would exceed `max_size`, `error.StreamTooLong` is returned and /// the contents read from the stream are lost. - pub fn readAllBuffer(self: &Self, buffer: &Buffer, max_size: usize) !void { + pub fn readAllBuffer(self: *Self, buffer: *Buffer, max_size: usize) !void { try buffer.resize(0); var actual_buf_len: usize = 0; @@ -111,7 +111,7 @@ pub fn InStream(comptime ReadError: type) type { /// memory would be greater than `max_size`, returns `error.StreamTooLong`. /// Caller owns returned memory. /// If this function returns an error, the contents from the stream read so far are lost. - pub fn readAllAlloc(self: &Self, allocator: &mem.Allocator, max_size: usize) ![]u8 { + pub fn readAllAlloc(self: *Self, allocator: *mem.Allocator, max_size: usize) ![]u8 { var buf = Buffer.initNull(allocator); defer buf.deinit(); @@ -123,7 +123,7 @@ pub fn InStream(comptime ReadError: type) type { /// Does not include the delimiter in the result. /// If `buffer.len()` would exceed `max_size`, `error.StreamTooLong` is returned and the contents /// read from the stream so far are lost. - pub fn readUntilDelimiterBuffer(self: &Self, buffer: &Buffer, delimiter: u8, max_size: usize) !void { + pub fn readUntilDelimiterBuffer(self: *Self, buffer: *Buffer, delimiter: u8, max_size: usize) !void { try buffer.resize(0); while (true) { @@ -145,7 +145,7 @@ pub fn InStream(comptime ReadError: type) type { /// memory would be greater than `max_size`, returns `error.StreamTooLong`. /// Caller owns returned memory. /// If this function returns an error, the contents from the stream read so far are lost. - pub fn readUntilDelimiterAlloc(self: &Self, allocator: &mem.Allocator, delimiter: u8, max_size: usize) ![]u8 { + pub fn readUntilDelimiterAlloc(self: *Self, allocator: *mem.Allocator, delimiter: u8, max_size: usize) ![]u8 { var buf = Buffer.initNull(allocator); defer buf.deinit(); @@ -156,43 +156,43 @@ pub fn InStream(comptime ReadError: type) type { /// Returns the number of bytes read. If the number read is smaller than buf.len, it /// means the stream reached the end. Reaching the end of a stream is not an error /// condition. - pub fn read(self: &Self, buffer: []u8) !usize { + pub fn read(self: *Self, buffer: []u8) !usize { return self.readFn(self, buffer); } /// Same as `read` but end of stream returns `error.EndOfStream`. - pub fn readNoEof(self: &Self, buf: []u8) !void { + pub fn readNoEof(self: *Self, buf: []u8) !void { const amt_read = try self.read(buf); if (amt_read < buf.len) return error.EndOfStream; } /// Reads 1 byte from the stream or returns `error.EndOfStream`. - pub fn readByte(self: &Self) !u8 { + pub fn readByte(self: *Self) !u8 { var result: [1]u8 = undefined; try self.readNoEof(result[0..]); return result[0]; } /// Same as `readByte` except the returned byte is signed. - pub fn readByteSigned(self: &Self) !i8 { + pub fn readByteSigned(self: *Self) !i8 { return @bitCast(i8, try self.readByte()); } - pub fn readIntLe(self: &Self, comptime T: type) !T { + pub fn readIntLe(self: *Self, comptime T: type) !T { return self.readInt(builtin.Endian.Little, T); } - pub fn readIntBe(self: &Self, comptime T: type) !T { + pub fn readIntBe(self: *Self, comptime T: type) !T { return self.readInt(builtin.Endian.Big, T); } - pub fn readInt(self: &Self, endian: builtin.Endian, comptime T: type) !T { + pub fn readInt(self: *Self, endian: builtin.Endian, comptime T: type) !T { var bytes: [@sizeOf(T)]u8 = undefined; try self.readNoEof(bytes[0..]); return mem.readInt(bytes, T, endian); } - pub fn readVarInt(self: &Self, endian: builtin.Endian, comptime T: type, size: usize) !T { + pub fn readVarInt(self: *Self, endian: builtin.Endian, comptime T: type, size: usize) !T { assert(size <= @sizeOf(T)); assert(size <= 8); var input_buf: [8]u8 = undefined; @@ -208,22 +208,22 @@ pub fn OutStream(comptime WriteError: type) type { const Self = this; pub const Error = WriteError; - writeFn: fn (self: &Self, bytes: []const u8) Error!void, + writeFn: fn (self: *Self, bytes: []const u8) Error!void, - pub fn print(self: &Self, comptime format: []const u8, args: ...) !void { + pub fn print(self: *Self, comptime format: []const u8, args: ...) !void { return std.fmt.format(self, Error, self.writeFn, format, args); } - pub fn write(self: &Self, bytes: []const u8) !void { + pub fn write(self: *Self, bytes: []const u8) !void { return self.writeFn(self, bytes); } - pub fn writeByte(self: &Self, byte: u8) !void { + pub fn writeByte(self: *Self, byte: u8) !void { const slice = (&byte)[0..1]; return self.writeFn(self, slice); } - pub fn writeByteNTimes(self: &Self, byte: u8, n: usize) !void { + pub fn writeByteNTimes(self: *Self, byte: u8, n: usize) !void { const slice = (&byte)[0..1]; var i: usize = 0; while (i < n) : (i += 1) { @@ -234,14 +234,14 @@ pub fn OutStream(comptime WriteError: type) type { } /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator. -pub fn writeFile(allocator: &mem.Allocator, path: []const u8, data: []const u8) !void { +pub fn writeFile(allocator: *mem.Allocator, path: []const u8, data: []const u8) !void { var file = try File.openWrite(allocator, path); defer file.close(); try file.write(data); } /// On success, caller owns returned buffer. -pub fn readFileAlloc(allocator: &mem.Allocator, path: []const u8) ![]u8 { +pub fn readFileAlloc(allocator: *mem.Allocator, path: []const u8) ![]u8 { var file = try File.openRead(allocator, path); defer file.close(); @@ -265,13 +265,13 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type) pub stream: Stream, - unbuffered_in_stream: &Stream, + unbuffered_in_stream: *Stream, buffer: [buffer_size]u8, start_index: usize, end_index: usize, - pub fn init(unbuffered_in_stream: &Stream) Self { + pub fn init(unbuffered_in_stream: *Stream) Self { return Self{ .unbuffered_in_stream = unbuffered_in_stream, .buffer = undefined, @@ -287,7 +287,7 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type) }; } - fn readFn(in_stream: &Stream, dest: []u8) !usize { + fn readFn(in_stream: *Stream, dest: []u8) !usize { const self = @fieldParentPtr(Self, "stream", in_stream); var dest_index: usize = 0; @@ -338,12 +338,12 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr pub stream: Stream, - unbuffered_out_stream: &Stream, + unbuffered_out_stream: *Stream, buffer: [buffer_size]u8, index: usize, - pub fn init(unbuffered_out_stream: &Stream) Self { + pub fn init(unbuffered_out_stream: *Stream) Self { return Self{ .unbuffered_out_stream = unbuffered_out_stream, .buffer = undefined, @@ -352,12 +352,12 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr }; } - pub fn flush(self: &Self) !void { + pub fn flush(self: *Self) !void { try self.unbuffered_out_stream.write(self.buffer[0..self.index]); self.index = 0; } - fn writeFn(out_stream: &Stream, bytes: []const u8) !void { + fn writeFn(out_stream: *Stream, bytes: []const u8) !void { const self = @fieldParentPtr(Self, "stream", out_stream); if (bytes.len >= self.buffer.len) { @@ -383,20 +383,20 @@ pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamEr /// Implementation of OutStream trait for Buffer pub const BufferOutStream = struct { - buffer: &Buffer, + buffer: *Buffer, stream: Stream, pub const Error = error{OutOfMemory}; pub const Stream = OutStream(Error); - pub fn init(buffer: &Buffer) BufferOutStream { + pub fn init(buffer: *Buffer) BufferOutStream { return BufferOutStream{ .buffer = buffer, .stream = Stream{ .writeFn = writeFn }, }; } - fn writeFn(out_stream: &Stream, bytes: []const u8) !void { + fn writeFn(out_stream: *Stream, bytes: []const u8) !void { const self = @fieldParentPtr(BufferOutStream, "stream", out_stream); return self.buffer.append(bytes); } @@ -407,7 +407,7 @@ pub const BufferedAtomicFile = struct { file_stream: FileOutStream, buffered_stream: BufferedOutStream(FileOutStream.Error), - pub fn create(allocator: &mem.Allocator, dest_path: []const u8) !&BufferedAtomicFile { + pub fn create(allocator: *mem.Allocator, dest_path: []const u8) !*BufferedAtomicFile { // TODO with well defined copy elision we don't need this allocation var self = try allocator.create(BufferedAtomicFile); errdefer allocator.destroy(self); @@ -427,18 +427,18 @@ pub const BufferedAtomicFile = struct { } /// always call destroy, even after successful finish() - pub fn destroy(self: &BufferedAtomicFile) void { + pub fn destroy(self: *BufferedAtomicFile) void { const allocator = self.atomic_file.allocator; self.atomic_file.deinit(); allocator.destroy(self); } - pub fn finish(self: &BufferedAtomicFile) !void { + pub fn finish(self: *BufferedAtomicFile) !void { try self.buffered_stream.flush(); try self.atomic_file.finish(); } - pub fn stream(self: &BufferedAtomicFile) &OutStream(FileOutStream.Error) { + pub fn stream(self: *BufferedAtomicFile) *OutStream(FileOutStream.Error) { return &self.buffered_stream.stream; } }; diff --git a/std/json.zig b/std/json.zig index 9de8f0b53e..c8aef7688b 100644 --- a/std/json.zig +++ b/std/json.zig @@ -76,7 +76,7 @@ pub const Token = struct { } // Slice into the underlying input string. - pub fn slice(self: &const Token, input: []const u8, i: usize) []const u8 { + pub fn slice(self: *const Token, input: []const u8, i: usize) []const u8 { return input[i + self.offset - self.count .. i + self.offset]; } }; @@ -115,7 +115,7 @@ pub const StreamingJsonParser = struct { return p; } - pub fn reset(p: &StreamingJsonParser) void { + pub fn reset(p: *StreamingJsonParser) void { p.state = State.TopLevelBegin; p.count = 0; // Set before ever read in main transition function @@ -205,7 +205,7 @@ pub const StreamingJsonParser = struct { // tokens. token2 is always null if token1 is null. // // There is currently no error recovery on a bad stream. - pub fn feed(p: &StreamingJsonParser, c: u8, token1: &?Token, token2: &?Token) Error!void { + pub fn feed(p: *StreamingJsonParser, c: u8, token1: *?Token, token2: *?Token) Error!void { token1.* = null; token2.* = null; p.count += 1; @@ -217,7 +217,7 @@ pub const StreamingJsonParser = struct { } // Perform a single transition on the state machine and return any possible token. - fn transition(p: &StreamingJsonParser, c: u8, token: &?Token) Error!bool { + fn transition(p: *StreamingJsonParser, c: u8, token: *?Token) Error!bool { switch (p.state) { State.TopLevelBegin => switch (c) { '{' => { @@ -861,7 +861,7 @@ pub fn validate(s: []const u8) bool { var token1: ?Token = undefined; var token2: ?Token = undefined; - p.feed(c, &token1, &token2) catch |err| { + p.feed(c, *token1, *token2) catch |err| { return false; }; } @@ -878,7 +878,7 @@ pub const ValueTree = struct { arena: ArenaAllocator, root: Value, - pub fn deinit(self: &ValueTree) void { + pub fn deinit(self: *ValueTree) void { self.arena.deinit(); } }; @@ -894,7 +894,7 @@ pub const Value = union(enum) { Array: ArrayList(Value), Object: ObjectMap, - pub fn dump(self: &const Value) void { + pub fn dump(self: *const Value) void { switch (self.*) { Value.Null => { std.debug.warn("null"); @@ -941,7 +941,7 @@ pub const Value = union(enum) { } } - pub fn dumpIndent(self: &const Value, indent: usize) void { + pub fn dumpIndent(self: *const Value, indent: usize) void { if (indent == 0) { self.dump(); } else { @@ -949,7 +949,7 @@ pub const Value = union(enum) { } } - fn dumpIndentLevel(self: &const Value, indent: usize, level: usize) void { + fn dumpIndentLevel(self: *const Value, indent: usize, level: usize) void { switch (self.*) { Value.Null => { std.debug.warn("null"); @@ -1013,7 +1013,7 @@ pub const Value = union(enum) { // A non-stream JSON parser which constructs a tree of Value's. pub const JsonParser = struct { - allocator: &Allocator, + allocator: *Allocator, state: State, copy_strings: bool, // Stores parent nodes and un-combined Values. @@ -1026,7 +1026,7 @@ pub const JsonParser = struct { Simple, }; - pub fn init(allocator: &Allocator, copy_strings: bool) JsonParser { + pub fn init(allocator: *Allocator, copy_strings: bool) JsonParser { return JsonParser{ .allocator = allocator, .state = State.Simple, @@ -1035,16 +1035,16 @@ pub const JsonParser = struct { }; } - pub fn deinit(p: &JsonParser) void { + pub fn deinit(p: *JsonParser) void { p.stack.deinit(); } - pub fn reset(p: &JsonParser) void { + pub fn reset(p: *JsonParser) void { p.state = State.Simple; p.stack.shrink(0); } - pub fn parse(p: &JsonParser, input: []const u8) !ValueTree { + pub fn parse(p: *JsonParser, input: []const u8) !ValueTree { var mp = StreamingJsonParser.init(); var arena = ArenaAllocator.init(p.allocator); @@ -1090,7 +1090,7 @@ pub const JsonParser = struct { // Even though p.allocator exists, we take an explicit allocator so that allocation state // can be cleaned up on error correctly during a `parse` on call. - fn transition(p: &JsonParser, allocator: &Allocator, input: []const u8, i: usize, token: &const Token) !void { + fn transition(p: *JsonParser, allocator: *Allocator, input: []const u8, i: usize, token: *const Token) !void { switch (p.state) { State.ObjectKey => switch (token.id) { Token.Id.ObjectEnd => { @@ -1223,7 +1223,7 @@ pub const JsonParser = struct { } } - fn pushToParent(p: &JsonParser, value: &const Value) !void { + fn pushToParent(p: *JsonParser, value: *const Value) !void { switch (p.stack.at(p.stack.len - 1)) { // Object Parent -> [ ..., object, , value ] Value.String => |key| { @@ -1244,14 +1244,14 @@ pub const JsonParser = struct { } } - fn parseString(p: &JsonParser, allocator: &Allocator, token: &const Token, input: []const u8, i: usize) !Value { + fn parseString(p: *JsonParser, allocator: *Allocator, token: *const Token, input: []const u8, i: usize) !Value { // TODO: We don't strictly have to copy values which do not contain any escape // characters if flagged with the option. const slice = token.slice(input, i); return Value{ .String = try mem.dupe(p.allocator, u8, slice) }; } - fn parseNumber(p: &JsonParser, token: &const Token, input: []const u8, i: usize) !Value { + fn parseNumber(p: *JsonParser, token: *const Token, input: []const u8, i: usize) !Value { return if (token.number_is_integer) Value{ .Integer = try std.fmt.parseInt(i64, token.slice(input, i), 10) } else diff --git a/std/linked_list.zig b/std/linked_list.zig index c6be08171e..fbc0a0c42a 100644 --- a/std/linked_list.zig +++ b/std/linked_list.zig @@ -21,11 +21,11 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// Node inside the linked list wrapping the actual data. pub const Node = struct { - prev: ?&Node, - next: ?&Node, + prev: ?*Node, + next: ?*Node, data: T, - pub fn init(value: &const T) Node { + pub fn init(value: *const T) Node { return Node{ .prev = null, .next = null, @@ -38,14 +38,14 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na return Node.init({}); } - pub fn toData(node: &Node) &ParentType { + pub fn toData(node: *Node) *ParentType { comptime assert(isIntrusive()); return @fieldParentPtr(ParentType, field_name, node); } }; - first: ?&Node, - last: ?&Node, + first: ?*Node, + last: ?*Node, len: usize, /// Initialize a linked list. @@ -69,7 +69,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// Arguments: /// node: Pointer to a node in the list. /// new_node: Pointer to the new node to insert. - pub fn insertAfter(list: &Self, node: &Node, new_node: &Node) void { + pub fn insertAfter(list: *Self, node: *Node, new_node: *Node) void { new_node.prev = node; if (node.next) |next_node| { // Intermediate node. @@ -90,7 +90,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// Arguments: /// node: Pointer to a node in the list. /// new_node: Pointer to the new node to insert. - pub fn insertBefore(list: &Self, node: &Node, new_node: &Node) void { + pub fn insertBefore(list: *Self, node: *Node, new_node: *Node) void { new_node.next = node; if (node.prev) |prev_node| { // Intermediate node. @@ -110,7 +110,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// /// Arguments: /// new_node: Pointer to the new node to insert. - pub fn append(list: &Self, new_node: &Node) void { + pub fn append(list: *Self, new_node: *Node) void { if (list.last) |last| { // Insert after last. list.insertAfter(last, new_node); @@ -124,7 +124,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// /// Arguments: /// new_node: Pointer to the new node to insert. - pub fn prepend(list: &Self, new_node: &Node) void { + pub fn prepend(list: *Self, new_node: *Node) void { if (list.first) |first| { // Insert before first. list.insertBefore(first, new_node); @@ -143,7 +143,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// /// Arguments: /// node: Pointer to the node to be removed. - pub fn remove(list: &Self, node: &Node) void { + pub fn remove(list: *Self, node: *Node) void { if (node.prev) |prev_node| { // Intermediate node. prev_node.next = node.next; @@ -168,7 +168,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// /// Returns: /// A pointer to the last node in the list. - pub fn pop(list: &Self) ?&Node { + pub fn pop(list: *Self) ?*Node { const last = list.last ?? return null; list.remove(last); return last; @@ -178,7 +178,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// /// Returns: /// A pointer to the first node in the list. - pub fn popFirst(list: &Self) ?&Node { + pub fn popFirst(list: *Self) ?*Node { const first = list.first ?? return null; list.remove(first); return first; @@ -191,7 +191,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// /// Returns: /// A pointer to the new node. - pub fn allocateNode(list: &Self, allocator: &Allocator) !&Node { + pub fn allocateNode(list: *Self, allocator: *Allocator) !*Node { comptime assert(!isIntrusive()); return allocator.create(Node); } @@ -201,7 +201,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// Arguments: /// node: Pointer to the node to deallocate. /// allocator: Dynamic memory allocator. - pub fn destroyNode(list: &Self, node: &Node, allocator: &Allocator) void { + pub fn destroyNode(list: *Self, node: *Node, allocator: *Allocator) void { comptime assert(!isIntrusive()); allocator.destroy(node); } @@ -214,7 +214,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// /// Returns: /// A pointer to the new node. - pub fn createNode(list: &Self, data: &const T, allocator: &Allocator) !&Node { + pub fn createNode(list: *Self, data: *const T, allocator: *Allocator) !*Node { comptime assert(!isIntrusive()); var node = try list.allocateNode(allocator); node.* = Node.init(data); diff --git a/std/macho.zig b/std/macho.zig index 615569e4b4..e71ac76b1a 100644 --- a/std/macho.zig +++ b/std/macho.zig @@ -42,13 +42,13 @@ pub const Symbol = struct { name: []const u8, address: u64, - fn addressLessThan(lhs: &const Symbol, rhs: &const Symbol) bool { + fn addressLessThan(lhs: *const Symbol, rhs: *const Symbol) bool { return lhs.address < rhs.address; } }; pub const SymbolTable = struct { - allocator: &mem.Allocator, + allocator: *mem.Allocator, symbols: []const Symbol, strings: []const u8, @@ -56,7 +56,7 @@ pub const SymbolTable = struct { // Ideally we'd use _mh_execute_header because it's always at 0x100000000 // in the image but as it's located in a different section than executable // code, its displacement is different. - pub fn deinit(self: &SymbolTable) void { + pub fn deinit(self: *SymbolTable) void { self.allocator.free(self.symbols); self.symbols = []const Symbol{}; @@ -64,7 +64,7 @@ pub const SymbolTable = struct { self.strings = []const u8{}; } - pub fn search(self: &const SymbolTable, address: usize) ?&const Symbol { + pub fn search(self: *const SymbolTable, address: usize) ?*const Symbol { var min: usize = 0; var max: usize = self.symbols.len - 1; // Exclude sentinel. while (min < max) { @@ -83,7 +83,7 @@ pub const SymbolTable = struct { } }; -pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable { +pub fn loadSymbols(allocator: *mem.Allocator, in: *io.FileInStream) !SymbolTable { var file = in.file; try file.seekTo(0); @@ -160,13 +160,13 @@ pub fn loadSymbols(allocator: &mem.Allocator, in: &io.FileInStream) !SymbolTable }; } -fn readNoEof(in: &io.FileInStream, comptime T: type, result: []T) !void { +fn readNoEof(in: *io.FileInStream, comptime T: type, result: []T) !void { return in.stream.readNoEof(([]u8)(result)); } -fn readOneNoEof(in: &io.FileInStream, comptime T: type, result: &T) !void { +fn readOneNoEof(in: *io.FileInStream, comptime T: type, result: *T) !void { return readNoEof(in, T, result[0..1]); } -fn isSymbol(sym: &const Nlist64) bool { +fn isSymbol(sym: *const Nlist64) bool { return sym.n_value != 0 and sym.n_desc == 0; } diff --git a/std/math/complex/atan.zig b/std/math/complex/atan.zig index b7bbf930eb..9bfe5fe724 100644 --- a/std/math/complex/atan.zig +++ b/std/math/complex/atan.zig @@ -29,7 +29,7 @@ fn redupif32(x: f32) f32 { return ((x - u * DP1) - u * DP2) - t * DP3; } -fn atan32(z: &const Complex(f32)) Complex(f32) { +fn atan32(z: *const Complex(f32)) Complex(f32) { const maxnum = 1.0e38; const x = z.re; @@ -78,7 +78,7 @@ fn redupif64(x: f64) f64 { return ((x - u * DP1) - u * DP2) - t * DP3; } -fn atan64(z: &const Complex(f64)) Complex(f64) { +fn atan64(z: *const Complex(f64)) Complex(f64) { const maxnum = 1.0e308; const x = z.re; diff --git a/std/math/complex/cosh.zig b/std/math/complex/cosh.zig index 96eac68556..c2f9a47b8d 100644 --- a/std/math/complex/cosh.zig +++ b/std/math/complex/cosh.zig @@ -15,7 +15,7 @@ pub fn cosh(z: var) Complex(@typeOf(z.re)) { }; } -fn cosh32(z: &const Complex(f32)) Complex(f32) { +fn cosh32(z: *const Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; @@ -78,7 +78,7 @@ fn cosh32(z: &const Complex(f32)) Complex(f32) { return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y)); } -fn cosh64(z: &const Complex(f64)) Complex(f64) { +fn cosh64(z: *const Complex(f64)) Complex(f64) { const x = z.re; const y = z.im; diff --git a/std/math/complex/exp.zig b/std/math/complex/exp.zig index 8fe069a43d..44c354f246 100644 --- a/std/math/complex/exp.zig +++ b/std/math/complex/exp.zig @@ -16,7 +16,7 @@ pub fn exp(z: var) Complex(@typeOf(z.re)) { }; } -fn exp32(z: &const Complex(f32)) Complex(f32) { +fn exp32(z: *const Complex(f32)) Complex(f32) { @setFloatMode(this, @import("builtin").FloatMode.Strict); const exp_overflow = 0x42b17218; // max_exp * ln2 ~= 88.72283955 @@ -63,7 +63,7 @@ fn exp32(z: &const Complex(f32)) Complex(f32) { } } -fn exp64(z: &const Complex(f64)) Complex(f64) { +fn exp64(z: *const Complex(f64)) Complex(f64) { const exp_overflow = 0x40862e42; // high bits of max_exp * ln2 ~= 710 const cexp_overflow = 0x4096b8e4; // (max_exp - min_denorm_exp) * ln2 diff --git a/std/math/complex/index.zig b/std/math/complex/index.zig index 5902ffaa19..b00296beda 100644 --- a/std/math/complex/index.zig +++ b/std/math/complex/index.zig @@ -37,28 +37,28 @@ pub fn Complex(comptime T: type) type { }; } - pub fn add(self: &const Self, other: &const Self) Self { + pub fn add(self: *const Self, other: *const Self) Self { return Self{ .re = self.re + other.re, .im = self.im + other.im, }; } - pub fn sub(self: &const Self, other: &const Self) Self { + pub fn sub(self: *const Self, other: *const Self) Self { return Self{ .re = self.re - other.re, .im = self.im - other.im, }; } - pub fn mul(self: &const Self, other: &const Self) Self { + pub fn mul(self: *const Self, other: *const Self) Self { return Self{ .re = self.re * other.re - self.im * other.im, .im = self.im * other.re + self.re * other.im, }; } - pub fn div(self: &const Self, other: &const Self) Self { + pub fn div(self: *const Self, other: *const Self) Self { const re_num = self.re * other.re + self.im * other.im; const im_num = self.im * other.re - self.re * other.im; const den = other.re * other.re + other.im * other.im; @@ -69,14 +69,14 @@ pub fn Complex(comptime T: type) type { }; } - pub fn conjugate(self: &const Self) Self { + pub fn conjugate(self: *const Self) Self { return Self{ .re = self.re, .im = -self.im, }; } - pub fn reciprocal(self: &const Self) Self { + pub fn reciprocal(self: *const Self) Self { const m = self.re * self.re + self.im * self.im; return Self{ .re = self.re / m, @@ -84,7 +84,7 @@ pub fn Complex(comptime T: type) type { }; } - pub fn magnitude(self: &const Self) T { + pub fn magnitude(self: *const Self) T { return math.sqrt(self.re * self.re + self.im * self.im); } }; diff --git a/std/math/complex/ldexp.zig b/std/math/complex/ldexp.zig index 7ebefff40c..a56c2ef2eb 100644 --- a/std/math/complex/ldexp.zig +++ b/std/math/complex/ldexp.zig @@ -14,7 +14,7 @@ pub fn ldexp_cexp(z: var, expt: i32) Complex(@typeOf(z.re)) { }; } -fn frexp_exp32(x: f32, expt: &i32) f32 { +fn frexp_exp32(x: f32, expt: *i32) f32 { const k = 235; // reduction constant const kln2 = 162.88958740; // k * ln2 @@ -24,7 +24,7 @@ fn frexp_exp32(x: f32, expt: &i32) f32 { return @bitCast(f32, (hx & 0x7fffff) | ((0x7f + 127) << 23)); } -fn ldexp_cexp32(z: &const Complex(f32), expt: i32) Complex(f32) { +fn ldexp_cexp32(z: *const Complex(f32), expt: i32) Complex(f32) { var ex_expt: i32 = undefined; const exp_x = frexp_exp32(z.re, &ex_expt); const exptf = expt + ex_expt; @@ -38,7 +38,7 @@ fn ldexp_cexp32(z: &const Complex(f32), expt: i32) Complex(f32) { return Complex(f32).new(math.cos(z.im) * exp_x * scale1 * scale2, math.sin(z.im) * exp_x * scale1 * scale2); } -fn frexp_exp64(x: f64, expt: &i32) f64 { +fn frexp_exp64(x: f64, expt: *i32) f64 { const k = 1799; // reduction constant const kln2 = 1246.97177782734161156; // k * ln2 @@ -54,7 +54,7 @@ fn frexp_exp64(x: f64, expt: &i32) f64 { return @bitCast(f64, (u64(high_word) << 32) | lx); } -fn ldexp_cexp64(z: &const Complex(f64), expt: i32) Complex(f64) { +fn ldexp_cexp64(z: *const Complex(f64), expt: i32) Complex(f64) { var ex_expt: i32 = undefined; const exp_x = frexp_exp64(z.re, &ex_expt); const exptf = i64(expt + ex_expt); diff --git a/std/math/complex/pow.zig b/std/math/complex/pow.zig index bef9fde542..4c2cd9cf34 100644 --- a/std/math/complex/pow.zig +++ b/std/math/complex/pow.zig @@ -4,7 +4,7 @@ const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; -pub fn pow(comptime T: type, z: &const T, c: &const T) T { +pub fn pow(comptime T: type, z: *const T, c: *const T) T { const p = cmath.log(z); const q = c.mul(p); return cmath.exp(q); diff --git a/std/math/complex/sinh.zig b/std/math/complex/sinh.zig index 09a62ca058..3d196bfd50 100644 --- a/std/math/complex/sinh.zig +++ b/std/math/complex/sinh.zig @@ -15,7 +15,7 @@ pub fn sinh(z: var) Complex(@typeOf(z.re)) { }; } -fn sinh32(z: &const Complex(f32)) Complex(f32) { +fn sinh32(z: *const Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; @@ -78,7 +78,7 @@ fn sinh32(z: &const Complex(f32)) Complex(f32) { return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y)); } -fn sinh64(z: &const Complex(f64)) Complex(f64) { +fn sinh64(z: *const Complex(f64)) Complex(f64) { const x = z.re; const y = z.im; diff --git a/std/math/complex/sqrt.zig b/std/math/complex/sqrt.zig index afda69f7c9..d4f5a67528 100644 --- a/std/math/complex/sqrt.zig +++ b/std/math/complex/sqrt.zig @@ -15,7 +15,7 @@ pub fn sqrt(z: var) Complex(@typeOf(z.re)) { }; } -fn sqrt32(z: &const Complex(f32)) Complex(f32) { +fn sqrt32(z: *const Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; @@ -57,7 +57,7 @@ fn sqrt32(z: &const Complex(f32)) Complex(f32) { } } -fn sqrt64(z: &const Complex(f64)) Complex(f64) { +fn sqrt64(z: *const Complex(f64)) Complex(f64) { // may encounter overflow for im,re >= DBL_MAX / (1 + sqrt(2)) const threshold = 0x1.a827999fcef32p+1022; diff --git a/std/math/complex/tanh.zig b/std/math/complex/tanh.zig index 34250b1b4a..1d754838a3 100644 --- a/std/math/complex/tanh.zig +++ b/std/math/complex/tanh.zig @@ -13,7 +13,7 @@ pub fn tanh(z: var) Complex(@typeOf(z.re)) { }; } -fn tanh32(z: &const Complex(f32)) Complex(f32) { +fn tanh32(z: *const Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; @@ -51,7 +51,7 @@ fn tanh32(z: &const Complex(f32)) Complex(f32) { return Complex(f32).new((beta * rho * s) / den, t / den); } -fn tanh64(z: &const Complex(f64)) Complex(f64) { +fn tanh64(z: *const Complex(f64)) Complex(f64) { const x = z.re; const y = z.im; diff --git a/std/math/hypot.zig b/std/math/hypot.zig index fe0de3a1ea..494df22ba6 100644 --- a/std/math/hypot.zig +++ b/std/math/hypot.zig @@ -52,7 +52,7 @@ fn hypot32(x: f32, y: f32) f32 { return z * math.sqrt(f32(f64(x) * x + f64(y) * y)); } -fn sq(hi: &f64, lo: &f64, x: f64) void { +fn sq(hi: *f64, lo: *f64, x: f64) void { const split: f64 = 0x1.0p27 + 1.0; const xc = x * split; const xh = x - xc + xc; diff --git a/std/math/index.zig b/std/math/index.zig index 847e972500..33bc1082f7 100644 --- a/std/math/index.zig +++ b/std/math/index.zig @@ -46,12 +46,12 @@ pub fn forceEval(value: var) void { switch (T) { f32 => { var x: f32 = undefined; - const p = @ptrCast(&volatile f32, &x); + const p = @ptrCast(*volatile f32, &x); p.* = x; }, f64 => { var x: f64 = undefined; - const p = @ptrCast(&volatile f64, &x); + const p = @ptrCast(*volatile f64, &x); p.* = x; }, else => { diff --git a/std/mem.zig b/std/mem.zig index f4696cff9f..aec24e8491 100644 --- a/std/mem.zig +++ b/std/mem.zig @@ -13,7 +13,7 @@ pub const Allocator = struct { /// The returned newly allocated memory is undefined. /// `alignment` is guaranteed to be >= 1 /// `alignment` is guaranteed to be a power of 2 - allocFn: fn (self: &Allocator, byte_count: usize, alignment: u29) Error![]u8, + allocFn: fn (self: *Allocator, byte_count: usize, alignment: u29) Error![]u8, /// If `new_byte_count > old_mem.len`: /// * `old_mem.len` is the same as what was returned from allocFn or reallocFn. @@ -26,22 +26,22 @@ pub const Allocator = struct { /// The returned newly allocated memory is undefined. /// `alignment` is guaranteed to be >= 1 /// `alignment` is guaranteed to be a power of 2 - reallocFn: fn (self: &Allocator, old_mem: []u8, new_byte_count: usize, alignment: u29) Error![]u8, + reallocFn: fn (self: *Allocator, old_mem: []u8, new_byte_count: usize, alignment: u29) Error![]u8, /// Guaranteed: `old_mem.len` is the same as what was returned from `allocFn` or `reallocFn` - freeFn: fn (self: &Allocator, old_mem: []u8) void, + freeFn: fn (self: *Allocator, old_mem: []u8) void, - fn create(self: &Allocator, comptime T: type) !&T { - if (@sizeOf(T) == 0) return &{}; + fn create(self: *Allocator, comptime T: type) !*T { + if (@sizeOf(T) == 0) return *{}; const slice = try self.alloc(T, 1); return &slice[0]; } // TODO once #733 is solved, this will replace create - fn construct(self: &Allocator, init: var) t: { + fn construct(self: *Allocator, init: var) t: { // TODO this is a workaround for type getting parsed as Error!&const T const T = @typeOf(init).Child; - break :t Error!&T; + break :t Error!*T; } { const T = @typeOf(init).Child; if (@sizeOf(T) == 0) return &{}; @@ -51,17 +51,17 @@ pub const Allocator = struct { return ptr; } - fn destroy(self: &Allocator, ptr: var) void { + fn destroy(self: *Allocator, ptr: var) void { self.free(ptr[0..1]); } - fn alloc(self: &Allocator, comptime T: type, n: usize) ![]T { + fn alloc(self: *Allocator, comptime T: type, n: usize) ![]T { return self.alignedAlloc(T, @alignOf(T), n); } - fn alignedAlloc(self: &Allocator, comptime T: type, comptime alignment: u29, n: usize) ![]align(alignment) T { + fn alignedAlloc(self: *Allocator, comptime T: type, comptime alignment: u29, n: usize) ![]align(alignment) T { if (n == 0) { - return (&align(alignment) T)(undefined)[0..0]; + return (*align(alignment) T)(undefined)[0..0]; } const byte_count = math.mul(usize, @sizeOf(T), n) catch return Error.OutOfMemory; const byte_slice = try self.allocFn(self, byte_count, alignment); @@ -73,17 +73,17 @@ pub const Allocator = struct { return ([]align(alignment) T)(@alignCast(alignment, byte_slice)); } - fn realloc(self: &Allocator, comptime T: type, old_mem: []T, n: usize) ![]T { + fn realloc(self: *Allocator, comptime T: type, old_mem: []T, n: usize) ![]T { return self.alignedRealloc(T, @alignOf(T), @alignCast(@alignOf(T), old_mem), n); } - fn alignedRealloc(self: &Allocator, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) ![]align(alignment) T { + fn alignedRealloc(self: *Allocator, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) ![]align(alignment) T { if (old_mem.len == 0) { return self.alloc(T, n); } if (n == 0) { self.free(old_mem); - return (&align(alignment) T)(undefined)[0..0]; + return (*align(alignment) T)(undefined)[0..0]; } const old_byte_slice = ([]u8)(old_mem); @@ -102,11 +102,11 @@ pub const Allocator = struct { /// Reallocate, but `n` must be less than or equal to `old_mem.len`. /// Unlike `realloc`, this function cannot fail. /// Shrinking to 0 is the same as calling `free`. - fn shrink(self: &Allocator, comptime T: type, old_mem: []T, n: usize) []T { + fn shrink(self: *Allocator, comptime T: type, old_mem: []T, n: usize) []T { return self.alignedShrink(T, @alignOf(T), @alignCast(@alignOf(T), old_mem), n); } - fn alignedShrink(self: &Allocator, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) []align(alignment) T { + fn alignedShrink(self: *Allocator, comptime T: type, comptime alignment: u29, old_mem: []align(alignment) T, n: usize) []align(alignment) T { if (n == 0) { self.free(old_mem); return old_mem[0..0]; @@ -123,10 +123,10 @@ pub const Allocator = struct { return ([]align(alignment) T)(@alignCast(alignment, byte_slice)); } - fn free(self: &Allocator, memory: var) void { + fn free(self: *Allocator, memory: var) void { const bytes = ([]const u8)(memory); if (bytes.len == 0) return; - const non_const_ptr = @intToPtr(&u8, @ptrToInt(bytes.ptr)); + const non_const_ptr = @intToPtr(*u8, @ptrToInt(bytes.ptr)); self.freeFn(self, non_const_ptr[0..bytes.len]); } }; @@ -186,7 +186,7 @@ pub fn allEqual(comptime T: type, slice: []const T, scalar: T) bool { } /// Copies ::m to newly allocated memory. Caller is responsible to free it. -pub fn dupe(allocator: &Allocator, comptime T: type, m: []const T) ![]T { +pub fn dupe(allocator: *Allocator, comptime T: type, m: []const T) ![]T { const new_buf = try allocator.alloc(T, m.len); copy(T, new_buf, m); return new_buf; @@ -457,7 +457,7 @@ pub const SplitIterator = struct { split_bytes: []const u8, index: usize, - pub fn next(self: &SplitIterator) ?[]const u8 { + pub fn next(self: *SplitIterator) ?[]const u8 { // move to beginning of token while (self.index < self.buffer.len and self.isSplitByte(self.buffer[self.index])) : (self.index += 1) {} const start = self.index; @@ -473,14 +473,14 @@ pub const SplitIterator = struct { } /// Returns a slice of the remaining bytes. Does not affect iterator state. - pub fn rest(self: &const SplitIterator) []const u8 { + pub fn rest(self: *const SplitIterator) []const u8 { // move to beginning of token var index: usize = self.index; while (index < self.buffer.len and self.isSplitByte(self.buffer[index])) : (index += 1) {} return self.buffer[index..]; } - fn isSplitByte(self: &const SplitIterator, byte: u8) bool { + fn isSplitByte(self: *const SplitIterator, byte: u8) bool { for (self.split_bytes) |split_byte| { if (byte == split_byte) { return true; @@ -492,7 +492,7 @@ pub const SplitIterator = struct { /// Naively combines a series of strings with a separator. /// Allocates memory for the result, which must be freed by the caller. -pub fn join(allocator: &Allocator, sep: u8, strings: ...) ![]u8 { +pub fn join(allocator: *Allocator, sep: u8, strings: ...) ![]u8 { comptime assert(strings.len >= 1); var total_strings_len: usize = strings.len; // 1 sep per string { @@ -649,7 +649,7 @@ test "mem.max" { assert(max(u8, "abcdefg") == 'g'); } -pub fn swap(comptime T: type, a: &T, b: &T) void { +pub fn swap(comptime T: type, a: *T, b: *T) void { const tmp = a.*; a.* = b.*; b.* = tmp; diff --git a/std/net.zig b/std/net.zig index 3af4e0b525..bfe4b1c2a0 100644 --- a/std/net.zig +++ b/std/net.zig @@ -31,7 +31,7 @@ pub const Address = struct { }; } - pub fn initIp6(ip6: &const Ip6Addr, port: u16) Address { + pub fn initIp6(ip6: *const Ip6Addr, port: u16) Address { return Address{ .family = posix.AF_INET6, .os_addr = posix.sockaddr{ @@ -46,15 +46,15 @@ pub const Address = struct { }; } - pub fn initPosix(addr: &const posix.sockaddr) Address { + pub fn initPosix(addr: *const posix.sockaddr) Address { return Address{ .os_addr = addr.* }; } - pub fn format(self: &const Address, out_stream: var) !void { + pub fn format(self: *const Address, out_stream: var) !void { switch (self.os_addr.in.family) { posix.AF_INET => { const native_endian_port = std.mem.endianSwapIfLe(u16, self.os_addr.in.port); - const bytes = ([]const u8)((&self.os_addr.in.addr)[0..1]); + const bytes = ([]const u8)((*self.os_addr.in.addr)[0..1]); try out_stream.print("{}.{}.{}.{}:{}", bytes[0], bytes[1], bytes[2], bytes[3], native_endian_port); }, posix.AF_INET6 => { diff --git a/std/os/child_process.zig b/std/os/child_process.zig index 51f1bd96e5..30a2fd1408 100644 --- a/std/os/child_process.zig +++ b/std/os/child_process.zig @@ -20,7 +20,7 @@ pub const ChildProcess = struct { pub handle: if (is_windows) windows.HANDLE else void, pub thread_handle: if (is_windows) windows.HANDLE else void, - pub allocator: &mem.Allocator, + pub allocator: *mem.Allocator, pub stdin: ?os.File, pub stdout: ?os.File, @@ -31,7 +31,7 @@ pub const ChildProcess = struct { pub argv: []const []const u8, /// Leave as null to use the current env map using the supplied allocator. - pub env_map: ?&const BufMap, + pub env_map: ?*const BufMap, pub stdin_behavior: StdIo, pub stdout_behavior: StdIo, @@ -47,7 +47,7 @@ pub const ChildProcess = struct { pub cwd: ?[]const u8, err_pipe: if (is_windows) void else [2]i32, - llnode: if (is_windows) void else LinkedList(&ChildProcess).Node, + llnode: if (is_windows) void else LinkedList(*ChildProcess).Node, pub const SpawnError = error{ ProcessFdQuotaExceeded, @@ -84,7 +84,7 @@ pub const ChildProcess = struct { /// First argument in argv is the executable. /// On success must call deinit. - pub fn init(argv: []const []const u8, allocator: &mem.Allocator) !&ChildProcess { + pub fn init(argv: []const []const u8, allocator: *mem.Allocator) !*ChildProcess { const child = try allocator.create(ChildProcess); errdefer allocator.destroy(child); @@ -114,14 +114,14 @@ pub const ChildProcess = struct { return child; } - pub fn setUserName(self: &ChildProcess, name: []const u8) !void { + pub fn setUserName(self: *ChildProcess, name: []const u8) !void { const user_info = try os.getUserInfo(name); self.uid = user_info.uid; self.gid = user_info.gid; } /// On success must call `kill` or `wait`. - pub fn spawn(self: &ChildProcess) !void { + pub fn spawn(self: *ChildProcess) !void { if (is_windows) { return self.spawnWindows(); } else { @@ -129,13 +129,13 @@ pub const ChildProcess = struct { } } - pub fn spawnAndWait(self: &ChildProcess) !Term { + pub fn spawnAndWait(self: *ChildProcess) !Term { try self.spawn(); return self.wait(); } /// Forcibly terminates child process and then cleans up all resources. - pub fn kill(self: &ChildProcess) !Term { + pub fn kill(self: *ChildProcess) !Term { if (is_windows) { return self.killWindows(1); } else { @@ -143,7 +143,7 @@ pub const ChildProcess = struct { } } - pub fn killWindows(self: &ChildProcess, exit_code: windows.UINT) !Term { + pub fn killWindows(self: *ChildProcess, exit_code: windows.UINT) !Term { if (self.term) |term| { self.cleanupStreams(); return term; @@ -159,7 +159,7 @@ pub const ChildProcess = struct { return ??self.term; } - pub fn killPosix(self: &ChildProcess) !Term { + pub fn killPosix(self: *ChildProcess) !Term { if (self.term) |term| { self.cleanupStreams(); return term; @@ -179,7 +179,7 @@ pub const ChildProcess = struct { } /// Blocks until child process terminates and then cleans up all resources. - pub fn wait(self: &ChildProcess) !Term { + pub fn wait(self: *ChildProcess) !Term { if (is_windows) { return self.waitWindows(); } else { @@ -195,7 +195,7 @@ pub const ChildProcess = struct { /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns. /// If it succeeds, the caller owns result.stdout and result.stderr memory. - pub fn exec(allocator: &mem.Allocator, argv: []const []const u8, cwd: ?[]const u8, env_map: ?&const BufMap, max_output_size: usize) !ExecResult { + pub fn exec(allocator: *mem.Allocator, argv: []const []const u8, cwd: ?[]const u8, env_map: ?*const BufMap, max_output_size: usize) !ExecResult { const child = try ChildProcess.init(argv, allocator); defer child.deinit(); @@ -225,7 +225,7 @@ pub const ChildProcess = struct { }; } - fn waitWindows(self: &ChildProcess) !Term { + fn waitWindows(self: *ChildProcess) !Term { if (self.term) |term| { self.cleanupStreams(); return term; @@ -235,7 +235,7 @@ pub const ChildProcess = struct { return ??self.term; } - fn waitPosix(self: &ChildProcess) !Term { + fn waitPosix(self: *ChildProcess) !Term { if (self.term) |term| { self.cleanupStreams(); return term; @@ -245,16 +245,16 @@ pub const ChildProcess = struct { return ??self.term; } - pub fn deinit(self: &ChildProcess) void { + pub fn deinit(self: *ChildProcess) void { self.allocator.destroy(self); } - fn waitUnwrappedWindows(self: &ChildProcess) !void { + fn waitUnwrappedWindows(self: *ChildProcess) !void { const result = os.windowsWaitSingle(self.handle, windows.INFINITE); self.term = (SpawnError!Term)(x: { var exit_code: windows.DWORD = undefined; - if (windows.GetExitCodeProcess(self.handle, &exit_code) == 0) { + if (windows.GetExitCodeProcess(self.handle, *exit_code) == 0) { break :x Term{ .Unknown = 0 }; } else { break :x Term{ .Exited = @bitCast(i32, exit_code) }; @@ -267,7 +267,7 @@ pub const ChildProcess = struct { return result; } - fn waitUnwrapped(self: &ChildProcess) void { + fn waitUnwrapped(self: *ChildProcess) void { var status: i32 = undefined; while (true) { const err = posix.getErrno(posix.waitpid(self.pid, &status, 0)); @@ -283,11 +283,11 @@ pub const ChildProcess = struct { } } - fn handleWaitResult(self: &ChildProcess, status: i32) void { + fn handleWaitResult(self: *ChildProcess, status: i32) void { self.term = self.cleanupAfterWait(status); } - fn cleanupStreams(self: &ChildProcess) void { + fn cleanupStreams(self: *ChildProcess) void { if (self.stdin) |*stdin| { stdin.close(); self.stdin = null; @@ -302,7 +302,7 @@ pub const ChildProcess = struct { } } - fn cleanupAfterWait(self: &ChildProcess, status: i32) !Term { + fn cleanupAfterWait(self: *ChildProcess, status: i32) !Term { defer { os.close(self.err_pipe[0]); os.close(self.err_pipe[1]); @@ -335,7 +335,7 @@ pub const ChildProcess = struct { Term{ .Unknown = status }; } - fn spawnPosix(self: &ChildProcess) !void { + fn spawnPosix(self: *ChildProcess) !void { const stdin_pipe = if (self.stdin_behavior == StdIo.Pipe) try makePipe() else undefined; errdefer if (self.stdin_behavior == StdIo.Pipe) { destroyPipe(stdin_pipe); @@ -432,7 +432,7 @@ pub const ChildProcess = struct { self.pid = pid; self.err_pipe = err_pipe; - self.llnode = LinkedList(&ChildProcess).Node.init(self); + self.llnode = LinkedList(*ChildProcess).Node.init(self); self.term = null; if (self.stdin_behavior == StdIo.Pipe) { @@ -446,7 +446,7 @@ pub const ChildProcess = struct { } } - fn spawnWindows(self: &ChildProcess) !void { + fn spawnWindows(self: *ChildProcess) !void { const saAttr = windows.SECURITY_ATTRIBUTES{ .nLength = @sizeOf(windows.SECURITY_ATTRIBUTES), .bInheritHandle = windows.TRUE, @@ -639,8 +639,8 @@ pub const ChildProcess = struct { } }; -fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ?&u8, lpStartupInfo: &windows.STARTUPINFOA, lpProcessInformation: &windows.PROCESS_INFORMATION) !void { - if (windows.CreateProcessA(app_name, cmd_line, null, null, windows.TRUE, 0, @ptrCast(?&c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation) == 0) { +fn windowsCreateProcess(app_name: *u8, cmd_line: *u8, envp_ptr: ?*u8, cwd_ptr: ?*u8, lpStartupInfo: *windows.STARTUPINFOA, lpProcessInformation: *windows.PROCESS_INFORMATION) !void { + if (windows.CreateProcessA(app_name, cmd_line, null, null, windows.TRUE, 0, @ptrCast(?*c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation) == 0) { const err = windows.GetLastError(); return switch (err) { windows.ERROR.FILE_NOT_FOUND, windows.ERROR.PATH_NOT_FOUND => error.FileNotFound, @@ -653,7 +653,7 @@ fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ? /// Caller must dealloc. /// Guarantees a null byte at result[result.len]. -fn windowsCreateCommandLine(allocator: &mem.Allocator, argv: []const []const u8) ![]u8 { +fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![]u8 { var buf = try Buffer.initSize(allocator, 0); defer buf.deinit(); @@ -698,7 +698,7 @@ fn windowsDestroyPipe(rd: ?windows.HANDLE, wr: ?windows.HANDLE) void { // a namespace field lookup const SECURITY_ATTRIBUTES = windows.SECURITY_ATTRIBUTES; -fn windowsMakePipe(rd: &windows.HANDLE, wr: &windows.HANDLE, sattr: &const SECURITY_ATTRIBUTES) !void { +fn windowsMakePipe(rd: *windows.HANDLE, wr: *windows.HANDLE, sattr: *const SECURITY_ATTRIBUTES) !void { if (windows.CreatePipe(rd, wr, sattr, 0) == 0) { const err = windows.GetLastError(); return switch (err) { @@ -716,7 +716,7 @@ fn windowsSetHandleInfo(h: windows.HANDLE, mask: windows.DWORD, flags: windows.D } } -fn windowsMakePipeIn(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const SECURITY_ATTRIBUTES) !void { +fn windowsMakePipeIn(rd: *?windows.HANDLE, wr: *?windows.HANDLE, sattr: *const SECURITY_ATTRIBUTES) !void { var rd_h: windows.HANDLE = undefined; var wr_h: windows.HANDLE = undefined; try windowsMakePipe(&rd_h, &wr_h, sattr); @@ -726,7 +726,7 @@ fn windowsMakePipeIn(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const S wr.* = wr_h; } -fn windowsMakePipeOut(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const SECURITY_ATTRIBUTES) !void { +fn windowsMakePipeOut(rd: *?windows.HANDLE, wr: *?windows.HANDLE, sattr: *const SECURITY_ATTRIBUTES) !void { var rd_h: windows.HANDLE = undefined; var wr_h: windows.HANDLE = undefined; try windowsMakePipe(&rd_h, &wr_h, sattr); @@ -748,7 +748,7 @@ fn makePipe() ![2]i32 { return fds; } -fn destroyPipe(pipe: &const [2]i32) void { +fn destroyPipe(pipe: *const [2]i32) void { os.close((pipe.*)[0]); os.close((pipe.*)[1]); } diff --git a/std/os/darwin.zig b/std/os/darwin.zig index a3fc230ac5..77e8b6bb6a 100644 --- a/std/os/darwin.zig +++ b/std/os/darwin.zig @@ -309,7 +309,7 @@ pub fn isatty(fd: i32) bool { return c.isatty(fd) != 0; } -pub fn fstat(fd: i32, buf: &c.Stat) usize { +pub fn fstat(fd: i32, buf: *c.Stat) usize { return errnoWrap(c.@"fstat$INODE64"(fd, buf)); } @@ -317,7 +317,7 @@ pub fn lseek(fd: i32, offset: isize, whence: c_int) usize { return errnoWrap(c.lseek(fd, offset, whence)); } -pub fn open(path: &const u8, flags: u32, mode: usize) usize { +pub fn open(path: *const u8, flags: u32, mode: usize) usize { return errnoWrap(c.open(path, @bitCast(c_int, flags), mode)); } @@ -325,79 +325,79 @@ pub fn raise(sig: i32) usize { return errnoWrap(c.raise(sig)); } -pub fn read(fd: i32, buf: &u8, nbyte: usize) usize { - return errnoWrap(c.read(fd, @ptrCast(&c_void, buf), nbyte)); +pub fn read(fd: i32, buf: *u8, nbyte: usize) usize { + return errnoWrap(c.read(fd, @ptrCast(*c_void, buf), nbyte)); } -pub fn stat(noalias path: &const u8, noalias buf: &stat) usize { +pub fn stat(noalias path: *const u8, noalias buf: *stat) usize { return errnoWrap(c.stat(path, buf)); } -pub fn write(fd: i32, buf: &const u8, nbyte: usize) usize { - return errnoWrap(c.write(fd, @ptrCast(&const c_void, buf), nbyte)); +pub fn write(fd: i32, buf: *const u8, nbyte: usize) usize { + return errnoWrap(c.write(fd, @ptrCast(*const c_void, buf), nbyte)); } -pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { - const ptr_result = c.mmap(@ptrCast(&c_void, address), length, @bitCast(c_int, c_uint(prot)), @bitCast(c_int, c_uint(flags)), fd, offset); +pub fn mmap(address: ?*u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { + const ptr_result = c.mmap(@ptrCast(*c_void, address), length, @bitCast(c_int, c_uint(prot)), @bitCast(c_int, c_uint(flags)), fd, offset); const isize_result = @bitCast(isize, @ptrToInt(ptr_result)); return errnoWrap(isize_result); } pub fn munmap(address: usize, length: usize) usize { - return errnoWrap(c.munmap(@intToPtr(&c_void, address), length)); + return errnoWrap(c.munmap(@intToPtr(*c_void, address), length)); } -pub fn unlink(path: &const u8) usize { +pub fn unlink(path: *const u8) usize { return errnoWrap(c.unlink(path)); } -pub fn getcwd(buf: &u8, size: usize) usize { +pub fn getcwd(buf: *u8, size: usize) usize { return if (c.getcwd(buf, size) == null) @bitCast(usize, -isize(c._errno().*)) else 0; } -pub fn waitpid(pid: i32, status: &i32, options: u32) usize { +pub fn waitpid(pid: i32, status: *i32, options: u32) usize { comptime assert(i32.bit_count == c_int.bit_count); - return errnoWrap(c.waitpid(pid, @ptrCast(&c_int, status), @bitCast(c_int, options))); + return errnoWrap(c.waitpid(pid, @ptrCast(*c_int, status), @bitCast(c_int, options))); } pub fn fork() usize { return errnoWrap(c.fork()); } -pub fn access(path: &const u8, mode: u32) usize { +pub fn access(path: *const u8, mode: u32) usize { return errnoWrap(c.access(path, mode)); } -pub fn pipe(fds: &[2]i32) usize { +pub fn pipe(fds: *[2]i32) usize { comptime assert(i32.bit_count == c_int.bit_count); - return errnoWrap(c.pipe(@ptrCast(&c_int, fds))); + return errnoWrap(c.pipe(@ptrCast(*c_int, fds))); } -pub fn getdirentries64(fd: i32, buf_ptr: &u8, buf_len: usize, basep: &i64) usize { +pub fn getdirentries64(fd: i32, buf_ptr: *u8, buf_len: usize, basep: *i64) usize { return errnoWrap(@bitCast(isize, c.__getdirentries64(fd, buf_ptr, buf_len, basep))); } -pub fn mkdir(path: &const u8, mode: u32) usize { +pub fn mkdir(path: *const u8, mode: u32) usize { return errnoWrap(c.mkdir(path, mode)); } -pub fn symlink(existing: &const u8, new: &const u8) usize { +pub fn symlink(existing: *const u8, new: *const u8) usize { return errnoWrap(c.symlink(existing, new)); } -pub fn rename(old: &const u8, new: &const u8) usize { +pub fn rename(old: *const u8, new: *const u8) usize { return errnoWrap(c.rename(old, new)); } -pub fn rmdir(path: &const u8) usize { +pub fn rmdir(path: *const u8) usize { return errnoWrap(c.rmdir(path)); } -pub fn chdir(path: &const u8) usize { +pub fn chdir(path: *const u8) usize { return errnoWrap(c.chdir(path)); } -pub fn execve(path: &const u8, argv: &const ?&const u8, envp: &const ?&const u8) usize { +pub fn execve(path: *const u8, argv: *const ?*const u8, envp: *const ?*const u8) usize { return errnoWrap(c.execve(path, argv, envp)); } @@ -405,19 +405,19 @@ pub fn dup2(old: i32, new: i32) usize { return errnoWrap(c.dup2(old, new)); } -pub fn readlink(noalias path: &const u8, noalias buf_ptr: &u8, buf_len: usize) usize { +pub fn readlink(noalias path: *const u8, noalias buf_ptr: *u8, buf_len: usize) usize { return errnoWrap(c.readlink(path, buf_ptr, buf_len)); } -pub fn gettimeofday(tv: ?&timeval, tz: ?&timezone) usize { +pub fn gettimeofday(tv: ?*timeval, tz: ?*timezone) usize { return errnoWrap(c.gettimeofday(tv, tz)); } -pub fn nanosleep(req: &const timespec, rem: ?×pec) usize { +pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize { return errnoWrap(c.nanosleep(req, rem)); } -pub fn realpath(noalias filename: &const u8, noalias resolved_name: &u8) usize { +pub fn realpath(noalias filename: *const u8, noalias resolved_name: *u8) usize { return if (c.realpath(filename, resolved_name) == null) @bitCast(usize, -isize(c._errno().*)) else 0; } @@ -429,11 +429,11 @@ pub fn setregid(rgid: u32, egid: u32) usize { return errnoWrap(c.setregid(rgid, egid)); } -pub fn sigprocmask(flags: u32, noalias set: &const sigset_t, noalias oldset: ?&sigset_t) usize { +pub fn sigprocmask(flags: u32, noalias set: *const sigset_t, noalias oldset: ?*sigset_t) usize { return errnoWrap(c.sigprocmask(@bitCast(c_int, flags), set, oldset)); } -pub fn sigaction(sig: u5, noalias act: &const Sigaction, noalias oact: ?&Sigaction) usize { +pub fn sigaction(sig: u5, noalias act: *const Sigaction, noalias oact: ?*Sigaction) usize { assert(sig != SIGKILL); assert(sig != SIGSTOP); var cact = c.Sigaction{ @@ -442,7 +442,7 @@ pub fn sigaction(sig: u5, noalias act: &const Sigaction, noalias oact: ?&Sigacti .sa_mask = act.mask, }; var coact: c.Sigaction = undefined; - const result = errnoWrap(c.sigaction(sig, &cact, &coact)); + const result = errnoWrap(c.sigaction(sig, *cact, *coact)); if (result != 0) { return result; } @@ -473,7 +473,7 @@ pub const Sigaction = struct { flags: u32, }; -pub fn sigaddset(set: &sigset_t, signo: u5) void { +pub fn sigaddset(set: *sigset_t, signo: u5) void { set.* |= u32(1) << (signo - 1); } diff --git a/std/os/file.zig b/std/os/file.zig index c07e2c5c8b..d943da30ca 100644 --- a/std/os/file.zig +++ b/std/os/file.zig @@ -19,7 +19,7 @@ pub const File = struct { /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator. /// Call close to clean up. - pub fn openRead(allocator: &mem.Allocator, path: []const u8) OpenError!File { + pub fn openRead(allocator: *mem.Allocator, path: []const u8) OpenError!File { if (is_posix) { const flags = posix.O_LARGEFILE | posix.O_RDONLY; const fd = try os.posixOpen(allocator, path, flags, 0); @@ -40,7 +40,7 @@ pub const File = struct { } /// Calls `openWriteMode` with os.default_file_mode for the mode. - pub fn openWrite(allocator: &mem.Allocator, path: []const u8) OpenError!File { + pub fn openWrite(allocator: *mem.Allocator, path: []const u8) OpenError!File { return openWriteMode(allocator, path, os.default_file_mode); } @@ -48,7 +48,7 @@ pub const File = struct { /// If a file already exists in the destination it will be truncated. /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator. /// Call close to clean up. - pub fn openWriteMode(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File { + pub fn openWriteMode(allocator: *mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File { if (is_posix) { const flags = posix.O_LARGEFILE | posix.O_WRONLY | posix.O_CREAT | posix.O_CLOEXEC | posix.O_TRUNC; const fd = try os.posixOpen(allocator, path, flags, file_mode); @@ -72,7 +72,7 @@ pub const File = struct { /// If a file already exists in the destination this returns OpenError.PathAlreadyExists /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator. /// Call close to clean up. - pub fn openWriteNoClobber(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File { + pub fn openWriteNoClobber(allocator: *mem.Allocator, path: []const u8, file_mode: os.FileMode) OpenError!File { if (is_posix) { const flags = posix.O_LARGEFILE | posix.O_WRONLY | posix.O_CREAT | posix.O_CLOEXEC | posix.O_EXCL; const fd = try os.posixOpen(allocator, path, flags, file_mode); @@ -96,7 +96,7 @@ pub const File = struct { return File{ .handle = handle }; } - pub fn access(allocator: &mem.Allocator, path: []const u8, file_mode: os.FileMode) !bool { + pub fn access(allocator: *mem.Allocator, path: []const u8, file_mode: os.FileMode) !bool { const path_with_null = try std.cstr.addNullByte(allocator, path); defer allocator.free(path_with_null); @@ -140,17 +140,17 @@ pub const File = struct { /// Upon success, the stream is in an uninitialized state. To continue using it, /// you must use the open() function. - pub fn close(self: &File) void { + pub fn close(self: *File) void { os.close(self.handle); self.handle = undefined; } /// Calls `os.isTty` on `self.handle`. - pub fn isTty(self: &File) bool { + pub fn isTty(self: *File) bool { return os.isTty(self.handle); } - pub fn seekForward(self: &File, amount: isize) !void { + pub fn seekForward(self: *File, amount: isize) !void { switch (builtin.os) { Os.linux, Os.macosx, Os.ios => { const result = posix.lseek(self.handle, amount, posix.SEEK_CUR); @@ -179,7 +179,7 @@ pub const File = struct { } } - pub fn seekTo(self: &File, pos: usize) !void { + pub fn seekTo(self: *File, pos: usize) !void { switch (builtin.os) { Os.linux, Os.macosx, Os.ios => { const ipos = try math.cast(isize, pos); @@ -210,7 +210,7 @@ pub const File = struct { } } - pub fn getPos(self: &File) !usize { + pub fn getPos(self: *File) !usize { switch (builtin.os) { Os.linux, Os.macosx, Os.ios => { const result = posix.lseek(self.handle, 0, posix.SEEK_CUR); @@ -229,7 +229,7 @@ pub const File = struct { }, Os.windows => { var pos: windows.LARGE_INTEGER = undefined; - if (windows.SetFilePointerEx(self.handle, 0, &pos, windows.FILE_CURRENT) == 0) { + if (windows.SetFilePointerEx(self.handle, 0, *pos, windows.FILE_CURRENT) == 0) { const err = windows.GetLastError(); return switch (err) { windows.ERROR.INVALID_PARAMETER => error.BadFd, @@ -250,7 +250,7 @@ pub const File = struct { } } - pub fn getEndPos(self: &File) !usize { + pub fn getEndPos(self: *File) !usize { if (is_posix) { var stat: posix.Stat = undefined; const err = posix.getErrno(posix.fstat(self.handle, &stat)); @@ -285,7 +285,7 @@ pub const File = struct { Unexpected, }; - fn mode(self: &File) ModeError!os.FileMode { + fn mode(self: *File) ModeError!os.FileMode { if (is_posix) { var stat: posix.Stat = undefined; const err = posix.getErrno(posix.fstat(self.handle, &stat)); @@ -309,7 +309,7 @@ pub const File = struct { pub const ReadError = error{}; - pub fn read(self: &File, buffer: []u8) !usize { + pub fn read(self: *File, buffer: []u8) !usize { if (is_posix) { var index: usize = 0; while (index < buffer.len) { @@ -334,7 +334,7 @@ pub const File = struct { while (index < buffer.len) { const want_read_count = windows.DWORD(math.min(windows.DWORD(@maxValue(windows.DWORD)), buffer.len - index)); var amt_read: windows.DWORD = undefined; - if (windows.ReadFile(self.handle, @ptrCast(&c_void, &buffer[index]), want_read_count, &amt_read, null) == 0) { + if (windows.ReadFile(self.handle, @ptrCast(*c_void, &buffer[index]), want_read_count, &amt_read, null) == 0) { const err = windows.GetLastError(); return switch (err) { windows.ERROR.OPERATION_ABORTED => continue, @@ -353,7 +353,7 @@ pub const File = struct { pub const WriteError = os.WindowsWriteError || os.PosixWriteError; - fn write(self: &File, bytes: []const u8) WriteError!void { + fn write(self: *File, bytes: []const u8) WriteError!void { if (is_posix) { try os.posixWrite(self.handle, bytes); } else if (is_windows) { diff --git a/std/os/get_user_id.zig b/std/os/get_user_id.zig index 2a15e1d495..c0c1b1cc4b 100644 --- a/std/os/get_user_id.zig +++ b/std/os/get_user_id.zig @@ -77,8 +77,8 @@ pub fn posixGetUserInfo(name: []const u8) !UserInfo { '0'...'9' => byte - '0', else => return error.CorruptPasswordFile, }; - if (@mulWithOverflow(u32, uid, 10, &uid)) return error.CorruptPasswordFile; - if (@addWithOverflow(u32, uid, digit, &uid)) return error.CorruptPasswordFile; + if (@mulWithOverflow(u32, uid, 10, *uid)) return error.CorruptPasswordFile; + if (@addWithOverflow(u32, uid, digit, *uid)) return error.CorruptPasswordFile; }, }, State.ReadGroupId => switch (byte) { @@ -93,8 +93,8 @@ pub fn posixGetUserInfo(name: []const u8) !UserInfo { '0'...'9' => byte - '0', else => return error.CorruptPasswordFile, }; - if (@mulWithOverflow(u32, gid, 10, &gid)) return error.CorruptPasswordFile; - if (@addWithOverflow(u32, gid, digit, &gid)) return error.CorruptPasswordFile; + if (@mulWithOverflow(u32, gid, 10, *gid)) return error.CorruptPasswordFile; + if (@addWithOverflow(u32, gid, digit, *gid)) return error.CorruptPasswordFile; }, }, } diff --git a/std/os/index.zig b/std/os/index.zig index 70e654bcd9..ff638c670b 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -321,14 +321,14 @@ pub const PosixOpenError = error{ /// ::file_path needs to be copied in memory to add a null terminating byte. /// Calls POSIX open, keeps trying if it gets interrupted, and translates /// the return value into zig errors. -pub fn posixOpen(allocator: &Allocator, file_path: []const u8, flags: u32, perm: usize) PosixOpenError!i32 { +pub fn posixOpen(allocator: *Allocator, file_path: []const u8, flags: u32, perm: usize) PosixOpenError!i32 { const path_with_null = try cstr.addNullByte(allocator, file_path); defer allocator.free(path_with_null); return posixOpenC(path_with_null.ptr, flags, perm); } -pub fn posixOpenC(file_path: &const u8, flags: u32, perm: usize) !i32 { +pub fn posixOpenC(file_path: *const u8, flags: u32, perm: usize) !i32 { while (true) { const result = posix.open(file_path, flags, perm); const err = posix.getErrno(result); @@ -374,10 +374,10 @@ pub fn posixDup2(old_fd: i32, new_fd: i32) !void { } } -pub fn createNullDelimitedEnvMap(allocator: &Allocator, env_map: &const BufMap) ![]?&u8 { +pub fn createNullDelimitedEnvMap(allocator: *Allocator, env_map: *const BufMap) ![]?*u8 { const envp_count = env_map.count(); - const envp_buf = try allocator.alloc(?&u8, envp_count + 1); - mem.set(?&u8, envp_buf, null); + const envp_buf = try allocator.alloc(?*u8, envp_count + 1); + mem.set(?*u8, envp_buf, null); errdefer freeNullDelimitedEnvMap(allocator, envp_buf); { var it = env_map.iterator(); @@ -397,7 +397,7 @@ pub fn createNullDelimitedEnvMap(allocator: &Allocator, env_map: &const BufMap) return envp_buf; } -pub fn freeNullDelimitedEnvMap(allocator: &Allocator, envp_buf: []?&u8) void { +pub fn freeNullDelimitedEnvMap(allocator: *Allocator, envp_buf: []?*u8) void { for (envp_buf) |env| { const env_buf = if (env) |ptr| ptr[0 .. cstr.len(ptr) + 1] else break; allocator.free(env_buf); @@ -410,9 +410,9 @@ pub fn freeNullDelimitedEnvMap(allocator: &Allocator, envp_buf: []?&u8) void { /// pointers after the args and after the environment variables. /// `argv[0]` is the executable path. /// This function also uses the PATH environment variable to get the full path to the executable. -pub fn posixExecve(argv: []const []const u8, env_map: &const BufMap, allocator: &Allocator) !void { - const argv_buf = try allocator.alloc(?&u8, argv.len + 1); - mem.set(?&u8, argv_buf, null); +pub fn posixExecve(argv: []const []const u8, env_map: *const BufMap, allocator: *Allocator) !void { + const argv_buf = try allocator.alloc(?*u8, argv.len + 1); + mem.set(?*u8, argv_buf, null); defer { for (argv_buf) |arg| { const arg_buf = if (arg) |ptr| cstr.toSlice(ptr) else break; @@ -494,10 +494,10 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError { } pub var linux_aux_raw = []usize{0} ** 38; -pub var posix_environ_raw: []&u8 = undefined; +pub var posix_environ_raw: []*u8 = undefined; /// Caller must free result when done. -pub fn getEnvMap(allocator: &Allocator) !BufMap { +pub fn getEnvMap(allocator: *Allocator) !BufMap { var result = BufMap.init(allocator); errdefer result.deinit(); @@ -557,7 +557,7 @@ pub fn getEnvPosix(key: []const u8) ?[]const u8 { } /// Caller must free returned memory. -pub fn getEnvVarOwned(allocator: &mem.Allocator, key: []const u8) ![]u8 { +pub fn getEnvVarOwned(allocator: *mem.Allocator, key: []const u8) ![]u8 { if (is_windows) { const key_with_null = try cstr.addNullByte(allocator, key); defer allocator.free(key_with_null); @@ -591,7 +591,7 @@ pub fn getEnvVarOwned(allocator: &mem.Allocator, key: []const u8) ![]u8 { } /// Caller must free the returned memory. -pub fn getCwd(allocator: &Allocator) ![]u8 { +pub fn getCwd(allocator: *Allocator) ![]u8 { switch (builtin.os) { Os.windows => { var buf = try allocator.alloc(u8, 256); @@ -640,7 +640,7 @@ test "os.getCwd" { pub const SymLinkError = PosixSymLinkError || WindowsSymLinkError; -pub fn symLink(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) SymLinkError!void { +pub fn symLink(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) SymLinkError!void { if (is_windows) { return symLinkWindows(allocator, existing_path, new_path); } else { @@ -653,7 +653,7 @@ pub const WindowsSymLinkError = error{ Unexpected, }; -pub fn symLinkWindows(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) WindowsSymLinkError!void { +pub fn symLinkWindows(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) WindowsSymLinkError!void { const existing_with_null = try cstr.addNullByte(allocator, existing_path); defer allocator.free(existing_with_null); const new_with_null = try cstr.addNullByte(allocator, new_path); @@ -683,7 +683,7 @@ pub const PosixSymLinkError = error{ Unexpected, }; -pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) PosixSymLinkError!void { +pub fn symLinkPosix(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) PosixSymLinkError!void { const full_buf = try allocator.alloc(u8, existing_path.len + new_path.len + 2); defer allocator.free(full_buf); @@ -718,7 +718,7 @@ pub fn symLinkPosix(allocator: &Allocator, existing_path: []const u8, new_path: // here we replace the standard +/ with -_ so that it can be used in a file name const b64_fs_encoder = base64.Base64Encoder.init("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", base64.standard_pad_char); -pub fn atomicSymLink(allocator: &Allocator, existing_path: []const u8, new_path: []const u8) !void { +pub fn atomicSymLink(allocator: *Allocator, existing_path: []const u8, new_path: []const u8) !void { if (symLink(allocator, existing_path, new_path)) { return; } else |err| switch (err) { @@ -746,7 +746,7 @@ pub fn atomicSymLink(allocator: &Allocator, existing_path: []const u8, new_path: } } -pub fn deleteFile(allocator: &Allocator, file_path: []const u8) !void { +pub fn deleteFile(allocator: *Allocator, file_path: []const u8) !void { if (builtin.os == Os.windows) { return deleteFileWindows(allocator, file_path); } else { @@ -754,7 +754,7 @@ pub fn deleteFile(allocator: &Allocator, file_path: []const u8) !void { } } -pub fn deleteFileWindows(allocator: &Allocator, file_path: []const u8) !void { +pub fn deleteFileWindows(allocator: *Allocator, file_path: []const u8) !void { const buf = try allocator.alloc(u8, file_path.len + 1); defer allocator.free(buf); @@ -772,7 +772,7 @@ pub fn deleteFileWindows(allocator: &Allocator, file_path: []const u8) !void { } } -pub fn deleteFilePosix(allocator: &Allocator, file_path: []const u8) !void { +pub fn deleteFilePosix(allocator: *Allocator, file_path: []const u8) !void { const buf = try allocator.alloc(u8, file_path.len + 1); defer allocator.free(buf); @@ -803,7 +803,7 @@ pub fn deleteFilePosix(allocator: &Allocator, file_path: []const u8) !void { /// there is a possibility of power loss or application termination leaving temporary files present /// in the same directory as dest_path. /// Destination file will have the same mode as the source file. -pub fn copyFile(allocator: &Allocator, source_path: []const u8, dest_path: []const u8) !void { +pub fn copyFile(allocator: *Allocator, source_path: []const u8, dest_path: []const u8) !void { var in_file = try os.File.openRead(allocator, source_path); defer in_file.close(); @@ -825,7 +825,7 @@ pub fn copyFile(allocator: &Allocator, source_path: []const u8, dest_path: []con /// Guaranteed to be atomic. However until https://patchwork.kernel.org/patch/9636735/ is /// merged and readily available, /// there is a possibility of power loss or application termination leaving temporary files present -pub fn copyFileMode(allocator: &Allocator, source_path: []const u8, dest_path: []const u8, mode: FileMode) !void { +pub fn copyFileMode(allocator: *Allocator, source_path: []const u8, dest_path: []const u8, mode: FileMode) !void { var in_file = try os.File.openRead(allocator, source_path); defer in_file.close(); @@ -843,7 +843,7 @@ pub fn copyFileMode(allocator: &Allocator, source_path: []const u8, dest_path: [ } pub const AtomicFile = struct { - allocator: &Allocator, + allocator: *Allocator, file: os.File, tmp_path: []u8, dest_path: []const u8, @@ -851,7 +851,7 @@ pub const AtomicFile = struct { /// dest_path must remain valid for the lifetime of AtomicFile /// call finish to atomically replace dest_path with contents - pub fn init(allocator: &Allocator, dest_path: []const u8, mode: FileMode) !AtomicFile { + pub fn init(allocator: *Allocator, dest_path: []const u8, mode: FileMode) !AtomicFile { const dirname = os.path.dirname(dest_path); var rand_buf: [12]u8 = undefined; @@ -888,7 +888,7 @@ pub const AtomicFile = struct { } /// always call deinit, even after successful finish() - pub fn deinit(self: &AtomicFile) void { + pub fn deinit(self: *AtomicFile) void { if (!self.finished) { self.file.close(); deleteFile(self.allocator, self.tmp_path) catch {}; @@ -897,7 +897,7 @@ pub const AtomicFile = struct { } } - pub fn finish(self: &AtomicFile) !void { + pub fn finish(self: *AtomicFile) !void { assert(!self.finished); self.file.close(); try rename(self.allocator, self.tmp_path, self.dest_path); @@ -906,7 +906,7 @@ pub const AtomicFile = struct { } }; -pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8) !void { +pub fn rename(allocator: *Allocator, old_path: []const u8, new_path: []const u8) !void { const full_buf = try allocator.alloc(u8, old_path.len + new_path.len + 2); defer allocator.free(full_buf); @@ -951,7 +951,7 @@ pub fn rename(allocator: &Allocator, old_path: []const u8, new_path: []const u8) } } -pub fn makeDir(allocator: &Allocator, dir_path: []const u8) !void { +pub fn makeDir(allocator: *Allocator, dir_path: []const u8) !void { if (is_windows) { return makeDirWindows(allocator, dir_path); } else { @@ -959,7 +959,7 @@ pub fn makeDir(allocator: &Allocator, dir_path: []const u8) !void { } } -pub fn makeDirWindows(allocator: &Allocator, dir_path: []const u8) !void { +pub fn makeDirWindows(allocator: *Allocator, dir_path: []const u8) !void { const path_buf = try cstr.addNullByte(allocator, dir_path); defer allocator.free(path_buf); @@ -973,7 +973,7 @@ pub fn makeDirWindows(allocator: &Allocator, dir_path: []const u8) !void { } } -pub fn makeDirPosix(allocator: &Allocator, dir_path: []const u8) !void { +pub fn makeDirPosix(allocator: *Allocator, dir_path: []const u8) !void { const path_buf = try cstr.addNullByte(allocator, dir_path); defer allocator.free(path_buf); @@ -999,7 +999,7 @@ pub fn makeDirPosix(allocator: &Allocator, dir_path: []const u8) !void { /// Calls makeDir recursively to make an entire path. Returns success if the path /// already exists and is a directory. -pub fn makePath(allocator: &Allocator, full_path: []const u8) !void { +pub fn makePath(allocator: *Allocator, full_path: []const u8) !void { const resolved_path = try path.resolve(allocator, full_path); defer allocator.free(resolved_path); @@ -1033,7 +1033,7 @@ pub fn makePath(allocator: &Allocator, full_path: []const u8) !void { /// Returns ::error.DirNotEmpty if the directory is not empty. /// To delete a directory recursively, see ::deleteTree -pub fn deleteDir(allocator: &Allocator, dir_path: []const u8) !void { +pub fn deleteDir(allocator: *Allocator, dir_path: []const u8) !void { const path_buf = try allocator.alloc(u8, dir_path.len + 1); defer allocator.free(path_buf); @@ -1084,7 +1084,7 @@ const DeleteTreeError = error{ DirNotEmpty, Unexpected, }; -pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError!void { +pub fn deleteTree(allocator: *Allocator, full_path: []const u8) DeleteTreeError!void { start_over: while (true) { var got_access_denied = false; // First, try deleting the item as a file. This way we don't follow sym links. @@ -1153,7 +1153,7 @@ pub fn deleteTree(allocator: &Allocator, full_path: []const u8) DeleteTreeError! pub const Dir = struct { fd: i32, darwin_seek: darwin_seek_t, - allocator: &Allocator, + allocator: *Allocator, buf: []u8, index: usize, end_index: usize, @@ -1180,7 +1180,7 @@ pub const Dir = struct { }; }; - pub fn open(allocator: &Allocator, dir_path: []const u8) !Dir { + pub fn open(allocator: *Allocator, dir_path: []const u8) !Dir { const fd = switch (builtin.os) { Os.windows => @compileError("TODO support Dir.open for windows"), Os.linux => try posixOpen(allocator, dir_path, posix.O_RDONLY | posix.O_DIRECTORY | posix.O_CLOEXEC, 0), @@ -1206,14 +1206,14 @@ pub const Dir = struct { }; } - pub fn close(self: &Dir) void { + pub fn close(self: *Dir) void { self.allocator.free(self.buf); os.close(self.fd); } /// Memory such as file names referenced in this returned entry becomes invalid /// with subsequent calls to next, as well as when this ::Dir is deinitialized. - pub fn next(self: &Dir) !?Entry { + pub fn next(self: *Dir) !?Entry { switch (builtin.os) { Os.linux => return self.nextLinux(), Os.macosx, Os.ios => return self.nextDarwin(), @@ -1222,7 +1222,7 @@ pub const Dir = struct { } } - fn nextDarwin(self: &Dir) !?Entry { + fn nextDarwin(self: *Dir) !?Entry { start_over: while (true) { if (self.index >= self.end_index) { if (self.buf.len == 0) { @@ -1248,7 +1248,7 @@ pub const Dir = struct { break; } } - const darwin_entry = @ptrCast(&align(1) posix.dirent, &self.buf[self.index]); + const darwin_entry = @ptrCast(*align(1) posix.dirent, &self.buf[self.index]); const next_index = self.index + darwin_entry.d_reclen; self.index = next_index; @@ -1277,11 +1277,11 @@ pub const Dir = struct { } } - fn nextWindows(self: &Dir) !?Entry { + fn nextWindows(self: *Dir) !?Entry { @compileError("TODO support Dir.next for windows"); } - fn nextLinux(self: &Dir) !?Entry { + fn nextLinux(self: *Dir) !?Entry { start_over: while (true) { if (self.index >= self.end_index) { if (self.buf.len == 0) { @@ -1307,7 +1307,7 @@ pub const Dir = struct { break; } } - const linux_entry = @ptrCast(&align(1) posix.dirent, &self.buf[self.index]); + const linux_entry = @ptrCast(*align(1) posix.dirent, &self.buf[self.index]); const next_index = self.index + linux_entry.d_reclen; self.index = next_index; @@ -1337,7 +1337,7 @@ pub const Dir = struct { } }; -pub fn changeCurDir(allocator: &Allocator, dir_path: []const u8) !void { +pub fn changeCurDir(allocator: *Allocator, dir_path: []const u8) !void { const path_buf = try allocator.alloc(u8, dir_path.len + 1); defer allocator.free(path_buf); @@ -1361,7 +1361,7 @@ pub fn changeCurDir(allocator: &Allocator, dir_path: []const u8) !void { } /// Read value of a symbolic link. -pub fn readLink(allocator: &Allocator, pathname: []const u8) ![]u8 { +pub fn readLink(allocator: *Allocator, pathname: []const u8) ![]u8 { const path_buf = try allocator.alloc(u8, pathname.len + 1); defer allocator.free(path_buf); @@ -1468,7 +1468,7 @@ pub const ArgIteratorPosix = struct { }; } - pub fn next(self: &ArgIteratorPosix) ?[]const u8 { + pub fn next(self: *ArgIteratorPosix) ?[]const u8 { if (self.index == self.count) return null; const s = raw[self.index]; @@ -1476,7 +1476,7 @@ pub const ArgIteratorPosix = struct { return cstr.toSlice(s); } - pub fn skip(self: &ArgIteratorPosix) bool { + pub fn skip(self: *ArgIteratorPosix) bool { if (self.index == self.count) return false; self.index += 1; @@ -1485,12 +1485,12 @@ pub const ArgIteratorPosix = struct { /// This is marked as public but actually it's only meant to be used /// internally by zig's startup code. - pub var raw: []&u8 = undefined; + pub var raw: []*u8 = undefined; }; pub const ArgIteratorWindows = struct { index: usize, - cmd_line: &const u8, + cmd_line: *const u8, in_quote: bool, quote_count: usize, seen_quote_count: usize, @@ -1501,7 +1501,7 @@ pub const ArgIteratorWindows = struct { return initWithCmdLine(windows.GetCommandLineA()); } - pub fn initWithCmdLine(cmd_line: &const u8) ArgIteratorWindows { + pub fn initWithCmdLine(cmd_line: *const u8) ArgIteratorWindows { return ArgIteratorWindows{ .index = 0, .cmd_line = cmd_line, @@ -1512,7 +1512,7 @@ pub const ArgIteratorWindows = struct { } /// You must free the returned memory when done. - pub fn next(self: &ArgIteratorWindows, allocator: &Allocator) ?(NextError![]u8) { + pub fn next(self: *ArgIteratorWindows, allocator: *Allocator) ?(NextError![]u8) { // march forward over whitespace while (true) : (self.index += 1) { const byte = self.cmd_line[self.index]; @@ -1526,7 +1526,7 @@ pub const ArgIteratorWindows = struct { return self.internalNext(allocator); } - pub fn skip(self: &ArgIteratorWindows) bool { + pub fn skip(self: *ArgIteratorWindows) bool { // march forward over whitespace while (true) : (self.index += 1) { const byte = self.cmd_line[self.index]; @@ -1565,7 +1565,7 @@ pub const ArgIteratorWindows = struct { } } - fn internalNext(self: &ArgIteratorWindows, allocator: &Allocator) NextError![]u8 { + fn internalNext(self: *ArgIteratorWindows, allocator: *Allocator) NextError![]u8 { var buf = try Buffer.initSize(allocator, 0); defer buf.deinit(); @@ -1609,14 +1609,14 @@ pub const ArgIteratorWindows = struct { } } - fn emitBackslashes(self: &ArgIteratorWindows, buf: &Buffer, emit_count: usize) !void { + fn emitBackslashes(self: *ArgIteratorWindows, buf: *Buffer, emit_count: usize) !void { var i: usize = 0; while (i < emit_count) : (i += 1) { try buf.appendByte('\\'); } } - fn countQuotes(cmd_line: &const u8) usize { + fn countQuotes(cmd_line: *const u8) usize { var result: usize = 0; var backslash_count: usize = 0; var index: usize = 0; @@ -1649,7 +1649,7 @@ pub const ArgIterator = struct { pub const NextError = ArgIteratorWindows.NextError; /// You must free the returned memory when done. - pub fn next(self: &ArgIterator, allocator: &Allocator) ?(NextError![]u8) { + pub fn next(self: *ArgIterator, allocator: *Allocator) ?(NextError![]u8) { if (builtin.os == Os.windows) { return self.inner.next(allocator); } else { @@ -1658,13 +1658,13 @@ pub const ArgIterator = struct { } /// If you only are targeting posix you can call this and not need an allocator. - pub fn nextPosix(self: &ArgIterator) ?[]const u8 { + pub fn nextPosix(self: *ArgIterator) ?[]const u8 { return self.inner.next(); } /// Parse past 1 argument without capturing it. /// Returns `true` if skipped an arg, `false` if we are at the end. - pub fn skip(self: &ArgIterator) bool { + pub fn skip(self: *ArgIterator) bool { return self.inner.skip(); } }; @@ -1674,7 +1674,7 @@ pub fn args() ArgIterator { } /// Caller must call freeArgs on result. -pub fn argsAlloc(allocator: &mem.Allocator) ![]const []u8 { +pub fn argsAlloc(allocator: *mem.Allocator) ![]const []u8 { // TODO refactor to only make 1 allocation. var it = args(); var contents = try Buffer.initSize(allocator, 0); @@ -1711,12 +1711,12 @@ pub fn argsAlloc(allocator: &mem.Allocator) ![]const []u8 { return result_slice_list; } -pub fn argsFree(allocator: &mem.Allocator, args_alloc: []const []u8) void { +pub fn argsFree(allocator: *mem.Allocator, args_alloc: []const []u8) void { var total_bytes: usize = 0; for (args_alloc) |arg| { total_bytes += @sizeOf([]u8) + arg.len; } - const unaligned_allocated_buf = @ptrCast(&const u8, args_alloc.ptr)[0..total_bytes]; + const unaligned_allocated_buf = @ptrCast(*const u8, args_alloc.ptr)[0..total_bytes]; const aligned_allocated_buf = @alignCast(@alignOf([]u8), unaligned_allocated_buf); return allocator.free(aligned_allocated_buf); } @@ -1765,7 +1765,7 @@ test "windows arg parsing" { }); } -fn testWindowsCmdLine(input_cmd_line: &const u8, expected_args: []const []const u8) void { +fn testWindowsCmdLine(input_cmd_line: *const u8, expected_args: []const []const u8) void { var it = ArgIteratorWindows.initWithCmdLine(input_cmd_line); for (expected_args) |expected_arg| { const arg = ??it.next(debug.global_allocator) catch unreachable; @@ -1832,7 +1832,7 @@ test "openSelfExe" { /// This function may return an error if the current executable /// was deleted after spawning. /// Caller owns returned memory. -pub fn selfExePath(allocator: &mem.Allocator) ![]u8 { +pub fn selfExePath(allocator: *mem.Allocator) ![]u8 { switch (builtin.os) { Os.linux => { // If the currently executing binary has been deleted, @@ -1875,7 +1875,7 @@ pub fn selfExePath(allocator: &mem.Allocator) ![]u8 { /// Get the directory path that contains the current executable. /// Caller owns returned memory. -pub fn selfExeDirPath(allocator: &mem.Allocator) ![]u8 { +pub fn selfExeDirPath(allocator: *mem.Allocator) ![]u8 { switch (builtin.os) { Os.linux => { // If the currently executing binary has been deleted, @@ -2001,7 +2001,7 @@ pub const PosixBindError = error{ }; /// addr is `&const T` where T is one of the sockaddr -pub fn posixBind(fd: i32, addr: &const posix.sockaddr) PosixBindError!void { +pub fn posixBind(fd: i32, addr: *const posix.sockaddr) PosixBindError!void { const rc = posix.bind(fd, addr, @sizeOf(posix.sockaddr)); const err = posix.getErrno(rc); switch (err) { @@ -2096,7 +2096,7 @@ pub const PosixAcceptError = error{ Unexpected, }; -pub fn posixAccept(fd: i32, addr: &posix.sockaddr, flags: u32) PosixAcceptError!i32 { +pub fn posixAccept(fd: i32, addr: *posix.sockaddr, flags: u32) PosixAcceptError!i32 { while (true) { var sockaddr_size = u32(@sizeOf(posix.sockaddr)); const rc = posix.accept4(fd, addr, &sockaddr_size, flags); @@ -2195,7 +2195,7 @@ pub const LinuxEpollCtlError = error{ Unexpected, }; -pub fn linuxEpollCtl(epfd: i32, op: u32, fd: i32, event: &linux.epoll_event) LinuxEpollCtlError!void { +pub fn linuxEpollCtl(epfd: i32, op: u32, fd: i32, event: *linux.epoll_event) LinuxEpollCtlError!void { const rc = posix.epoll_ctl(epfd, op, fd, event); const err = posix.getErrno(rc); switch (err) { @@ -2288,7 +2288,7 @@ pub const PosixConnectError = error{ Unexpected, }; -pub fn posixConnect(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConnectError!void { +pub fn posixConnect(sockfd: i32, sockaddr: *const posix.sockaddr) PosixConnectError!void { while (true) { const rc = posix.connect(sockfd, sockaddr, @sizeOf(posix.sockaddr)); const err = posix.getErrno(rc); @@ -2319,7 +2319,7 @@ pub fn posixConnect(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConnectEr /// Same as posixConnect except it is for blocking socket file descriptors. /// It expects to receive EINPROGRESS. -pub fn posixConnectAsync(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConnectError!void { +pub fn posixConnectAsync(sockfd: i32, sockaddr: *const posix.sockaddr) PosixConnectError!void { while (true) { const rc = posix.connect(sockfd, sockaddr, @sizeOf(posix.sockaddr)); const err = posix.getErrno(rc); @@ -2350,7 +2350,7 @@ pub fn posixConnectAsync(sockfd: i32, sockaddr: &const posix.sockaddr) PosixConn pub fn posixGetSockOptConnectError(sockfd: i32) PosixConnectError!void { var err_code: i32 = undefined; var size: u32 = @sizeOf(i32); - const rc = posix.getsockopt(sockfd, posix.SOL_SOCKET, posix.SO_ERROR, @ptrCast(&u8, &err_code), &size); + const rc = posix.getsockopt(sockfd, posix.SOL_SOCKET, posix.SO_ERROR, @ptrCast(*u8, &err_code), &size); assert(size == 4); const err = posix.getErrno(rc); switch (err) { @@ -2401,13 +2401,13 @@ pub const Thread = struct { }, builtin.Os.windows => struct { handle: windows.HANDLE, - alloc_start: &c_void, + alloc_start: *c_void, heap_handle: windows.HANDLE, }, else => @compileError("Unsupported OS"), }; - pub fn wait(self: &const Thread) void { + pub fn wait(self: *const Thread) void { if (use_pthreads) { const err = c.pthread_join(self.data.handle, null); switch (err) { @@ -2473,7 +2473,7 @@ pub const SpawnThreadError = error{ /// fn startFn(@typeOf(context)) T /// where T is u8, noreturn, void, or !void /// caller must call wait on the returned thread -pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread { +pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread { // TODO compile-time call graph analysis to determine stack upper bound // https://github.com/ziglang/zig/issues/157 const default_stack_size = 8 * 1024 * 1024; @@ -2491,7 +2491,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread if (@sizeOf(Context) == 0) { return startFn({}); } else { - return startFn(@ptrCast(&Context, @alignCast(@alignOf(Context), arg)).*); + return startFn(@ptrCast(*Context, @alignCast(@alignOf(Context), arg)).*); } } }; @@ -2500,13 +2500,13 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread const byte_count = @alignOf(WinThread.OuterContext) + @sizeOf(WinThread.OuterContext); const bytes_ptr = windows.HeapAlloc(heap_handle, 0, byte_count) ?? return SpawnThreadError.OutOfMemory; errdefer assert(windows.HeapFree(heap_handle, 0, bytes_ptr) != 0); - const bytes = @ptrCast(&u8, bytes_ptr)[0..byte_count]; + const bytes = @ptrCast(*u8, bytes_ptr)[0..byte_count]; const outer_context = std.heap.FixedBufferAllocator.init(bytes).allocator.create(WinThread.OuterContext) catch unreachable; outer_context.inner = context; outer_context.thread.data.heap_handle = heap_handle; outer_context.thread.data.alloc_start = bytes_ptr; - const parameter = if (@sizeOf(Context) == 0) null else @ptrCast(&c_void, &outer_context.inner); + const parameter = if (@sizeOf(Context) == 0) null else @ptrCast(*c_void, &outer_context.inner); outer_context.thread.data.handle = windows.CreateThread(null, default_stack_size, WinThread.threadMain, parameter, 0, null) ?? { const err = windows.GetLastError(); return switch (err) { @@ -2521,15 +2521,15 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread if (@sizeOf(Context) == 0) { return startFn({}); } else { - return startFn(@intToPtr(&const Context, ctx_addr).*); + return startFn(@intToPtr(*const Context, ctx_addr).*); } } - extern fn posixThreadMain(ctx: ?&c_void) ?&c_void { + extern fn posixThreadMain(ctx: ?*c_void) ?*c_void { if (@sizeOf(Context) == 0) { _ = startFn({}); return null; } else { - _ = startFn(@ptrCast(&const Context, @alignCast(@alignOf(Context), ctx)).*); + _ = startFn(@ptrCast(*const Context, @alignCast(@alignOf(Context), ctx)).*); return null; } } @@ -2548,7 +2548,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread stack_end -= @sizeOf(Context); stack_end -= stack_end % @alignOf(Context); assert(stack_end >= stack_addr); - const context_ptr = @alignCast(@alignOf(Context), @intToPtr(&Context, stack_end)); + const context_ptr = @alignCast(@alignOf(Context), @intToPtr(*Context, stack_end)); context_ptr.* = context; arg = stack_end; } @@ -2556,7 +2556,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread stack_end -= @sizeOf(Thread); stack_end -= stack_end % @alignOf(Thread); assert(stack_end >= stack_addr); - const thread_ptr = @alignCast(@alignOf(Thread), @intToPtr(&Thread, stack_end)); + const thread_ptr = @alignCast(@alignOf(Thread), @intToPtr(*Thread, stack_end)); thread_ptr.data.stack_addr = stack_addr; thread_ptr.data.stack_len = mmap_len; @@ -2572,9 +2572,9 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!&Thread // align to page stack_end -= stack_end % os.page_size; - assert(c.pthread_attr_setstack(&attr, @intToPtr(&c_void, stack_addr), stack_end - stack_addr) == 0); + assert(c.pthread_attr_setstack(&attr, @intToPtr(*c_void, stack_addr), stack_end - stack_addr) == 0); - const err = c.pthread_create(&thread_ptr.data.handle, &attr, MainFuncs.posixThreadMain, @intToPtr(&c_void, arg)); + const err = c.pthread_create(&thread_ptr.data.handle, &attr, MainFuncs.posixThreadMain, @intToPtr(*c_void, arg)); switch (err) { 0 => return thread_ptr, posix.EAGAIN => return SpawnThreadError.SystemResources, diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 5186ff32d3..3e7b836ac7 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -665,15 +665,15 @@ pub fn dup2(old: i32, new: i32) usize { return syscall2(SYS_dup2, usize(old), usize(new)); } -pub fn chdir(path: &const u8) usize { +pub fn chdir(path: *const u8) usize { return syscall1(SYS_chdir, @ptrToInt(path)); } -pub fn chroot(path: &const u8) usize { +pub fn chroot(path: *const u8) usize { return syscall1(SYS_chroot, @ptrToInt(path)); } -pub fn execve(path: &const u8, argv: &const ?&const u8, envp: &const ?&const u8) usize { +pub fn execve(path: *const u8, argv: *const ?*const u8, envp: *const ?*const u8) usize { return syscall3(SYS_execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp)); } @@ -681,15 +681,15 @@ pub fn fork() usize { return syscall0(SYS_fork); } -pub fn futex_wait(uaddr: usize, futex_op: u32, val: i32, timeout: ?×pec) usize { +pub fn futex_wait(uaddr: usize, futex_op: u32, val: i32, timeout: ?*timespec) usize { return syscall4(SYS_futex, uaddr, futex_op, @bitCast(u32, val), @ptrToInt(timeout)); } -pub fn getcwd(buf: &u8, size: usize) usize { +pub fn getcwd(buf: *u8, size: usize) usize { return syscall2(SYS_getcwd, @ptrToInt(buf), size); } -pub fn getdents(fd: i32, dirp: &u8, count: usize) usize { +pub fn getdents(fd: i32, dirp: *u8, count: usize) usize { return syscall3(SYS_getdents, usize(fd), @ptrToInt(dirp), count); } @@ -698,27 +698,27 @@ pub fn isatty(fd: i32) bool { return syscall3(SYS_ioctl, usize(fd), TIOCGWINSZ, @ptrToInt(&wsz)) == 0; } -pub fn readlink(noalias path: &const u8, noalias buf_ptr: &u8, buf_len: usize) usize { +pub fn readlink(noalias path: *const u8, noalias buf_ptr: *u8, buf_len: usize) usize { return syscall3(SYS_readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); } -pub fn mkdir(path: &const u8, mode: u32) usize { +pub fn mkdir(path: *const u8, mode: u32) usize { return syscall2(SYS_mkdir, @ptrToInt(path), mode); } -pub fn mount(special: &const u8, dir: &const u8, fstype: &const u8, flags: usize, data: usize) usize { +pub fn mount(special: *const u8, dir: *const u8, fstype: *const u8, flags: usize, data: usize) usize { return syscall5(SYS_mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data); } -pub fn umount(special: &const u8) usize { +pub fn umount(special: *const u8) usize { return syscall2(SYS_umount2, @ptrToInt(special), 0); } -pub fn umount2(special: &const u8, flags: u32) usize { +pub fn umount2(special: *const u8, flags: u32) usize { return syscall2(SYS_umount2, @ptrToInt(special), flags); } -pub fn mmap(address: ?&u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { +pub fn mmap(address: ?*u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), @bitCast(usize, offset)); } @@ -726,60 +726,60 @@ pub fn munmap(address: usize, length: usize) usize { return syscall2(SYS_munmap, address, length); } -pub fn read(fd: i32, buf: &u8, count: usize) usize { +pub fn read(fd: i32, buf: *u8, count: usize) usize { return syscall3(SYS_read, usize(fd), @ptrToInt(buf), count); } -pub fn rmdir(path: &const u8) usize { +pub fn rmdir(path: *const u8) usize { return syscall1(SYS_rmdir, @ptrToInt(path)); } -pub fn symlink(existing: &const u8, new: &const u8) usize { +pub fn symlink(existing: *const u8, new: *const u8) usize { return syscall2(SYS_symlink, @ptrToInt(existing), @ptrToInt(new)); } -pub fn pread(fd: i32, buf: &u8, count: usize, offset: usize) usize { +pub fn pread(fd: i32, buf: *u8, count: usize, offset: usize) usize { return syscall4(SYS_pread, usize(fd), @ptrToInt(buf), count, offset); } -pub fn access(path: &const u8, mode: u32) usize { +pub fn access(path: *const u8, mode: u32) usize { return syscall2(SYS_access, @ptrToInt(path), mode); } -pub fn pipe(fd: &[2]i32) usize { +pub fn pipe(fd: *[2]i32) usize { return pipe2(fd, 0); } -pub fn pipe2(fd: &[2]i32, flags: usize) usize { +pub fn pipe2(fd: *[2]i32, flags: usize) usize { return syscall2(SYS_pipe2, @ptrToInt(fd), flags); } -pub fn write(fd: i32, buf: &const u8, count: usize) usize { +pub fn write(fd: i32, buf: *const u8, count: usize) usize { return syscall3(SYS_write, usize(fd), @ptrToInt(buf), count); } -pub fn pwrite(fd: i32, buf: &const u8, count: usize, offset: usize) usize { +pub fn pwrite(fd: i32, buf: *const u8, count: usize, offset: usize) usize { return syscall4(SYS_pwrite, usize(fd), @ptrToInt(buf), count, offset); } -pub fn rename(old: &const u8, new: &const u8) usize { +pub fn rename(old: *const u8, new: *const u8) usize { return syscall2(SYS_rename, @ptrToInt(old), @ptrToInt(new)); } -pub fn open(path: &const u8, flags: u32, perm: usize) usize { +pub fn open(path: *const u8, flags: u32, perm: usize) usize { return syscall3(SYS_open, @ptrToInt(path), flags, perm); } -pub fn create(path: &const u8, perm: usize) usize { +pub fn create(path: *const u8, perm: usize) usize { return syscall2(SYS_creat, @ptrToInt(path), perm); } -pub fn openat(dirfd: i32, path: &const u8, flags: usize, mode: usize) usize { +pub fn openat(dirfd: i32, path: *const u8, flags: usize, mode: usize) usize { return syscall4(SYS_openat, usize(dirfd), @ptrToInt(path), flags, mode); } /// See also `clone` (from the arch-specific include) -pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: &i32, child_tid: &i32, newtls: usize) usize { +pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: *i32, child_tid: *i32, newtls: usize) usize { return syscall5(SYS_clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls); } @@ -801,7 +801,7 @@ pub fn exit(status: i32) noreturn { unreachable; } -pub fn getrandom(buf: &u8, count: usize, flags: u32) usize { +pub fn getrandom(buf: *u8, count: usize, flags: u32) usize { return syscall3(SYS_getrandom, @ptrToInt(buf), count, usize(flags)); } @@ -809,15 +809,15 @@ pub fn kill(pid: i32, sig: i32) usize { return syscall2(SYS_kill, @bitCast(usize, isize(pid)), usize(sig)); } -pub fn unlink(path: &const u8) usize { +pub fn unlink(path: *const u8) usize { return syscall1(SYS_unlink, @ptrToInt(path)); } -pub fn waitpid(pid: i32, status: &i32, options: i32) usize { +pub fn waitpid(pid: i32, status: *i32, options: i32) usize { return syscall4(SYS_wait4, @bitCast(usize, isize(pid)), @ptrToInt(status), @bitCast(usize, isize(options)), 0); } -pub fn clock_gettime(clk_id: i32, tp: ×pec) usize { +pub fn clock_gettime(clk_id: i32, tp: *timespec) usize { if (VDSO_CGT_SYM.len != 0) { const f = @atomicLoad(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, builtin.AtomicOrder.Unordered); if (@ptrToInt(f) != 0) { @@ -831,7 +831,7 @@ pub fn clock_gettime(clk_id: i32, tp: ×pec) usize { return syscall2(SYS_clock_gettime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp)); } var vdso_clock_gettime = init_vdso_clock_gettime; -extern fn init_vdso_clock_gettime(clk: i32, ts: ×pec) usize { +extern fn init_vdso_clock_gettime(clk: i32, ts: *timespec) usize { const addr = vdso.lookup(VDSO_CGT_VER, VDSO_CGT_SYM); var f = @intToPtr(@typeOf(init_vdso_clock_gettime), addr); _ = @cmpxchgStrong(@typeOf(init_vdso_clock_gettime), &vdso_clock_gettime, init_vdso_clock_gettime, f, builtin.AtomicOrder.Monotonic, builtin.AtomicOrder.Monotonic); @@ -839,23 +839,23 @@ extern fn init_vdso_clock_gettime(clk: i32, ts: ×pec) usize { return f(clk, ts); } -pub fn clock_getres(clk_id: i32, tp: ×pec) usize { +pub fn clock_getres(clk_id: i32, tp: *timespec) usize { return syscall2(SYS_clock_getres, @bitCast(usize, isize(clk_id)), @ptrToInt(tp)); } -pub fn clock_settime(clk_id: i32, tp: &const timespec) usize { +pub fn clock_settime(clk_id: i32, tp: *const timespec) usize { return syscall2(SYS_clock_settime, @bitCast(usize, isize(clk_id)), @ptrToInt(tp)); } -pub fn gettimeofday(tv: &timeval, tz: &timezone) usize { +pub fn gettimeofday(tv: *timeval, tz: *timezone) usize { return syscall2(SYS_gettimeofday, @ptrToInt(tv), @ptrToInt(tz)); } -pub fn settimeofday(tv: &const timeval, tz: &const timezone) usize { +pub fn settimeofday(tv: *const timeval, tz: *const timezone) usize { return syscall2(SYS_settimeofday, @ptrToInt(tv), @ptrToInt(tz)); } -pub fn nanosleep(req: &const timespec, rem: ?×pec) usize { +pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize { return syscall2(SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem)); } @@ -899,11 +899,11 @@ pub fn setegid(egid: u32) usize { return syscall1(SYS_setegid, egid); } -pub fn getresuid(ruid: &u32, euid: &u32, suid: &u32) usize { +pub fn getresuid(ruid: *u32, euid: *u32, suid: *u32) usize { return syscall3(SYS_getresuid, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid)); } -pub fn getresgid(rgid: &u32, egid: &u32, sgid: &u32) usize { +pub fn getresgid(rgid: *u32, egid: *u32, sgid: *u32) usize { return syscall3(SYS_getresgid, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid)); } @@ -915,11 +915,11 @@ pub fn setresgid(rgid: u32, egid: u32, sgid: u32) usize { return syscall3(SYS_setresgid, rgid, egid, sgid); } -pub fn getgroups(size: usize, list: &u32) usize { +pub fn getgroups(size: usize, list: *u32) usize { return syscall2(SYS_getgroups, size, @ptrToInt(list)); } -pub fn setgroups(size: usize, list: &const u32) usize { +pub fn setgroups(size: usize, list: *const u32) usize { return syscall2(SYS_setgroups, size, @ptrToInt(list)); } @@ -927,11 +927,11 @@ pub fn getpid() i32 { return @bitCast(i32, u32(syscall0(SYS_getpid))); } -pub fn sigprocmask(flags: u32, noalias set: &const sigset_t, noalias oldset: ?&sigset_t) usize { +pub fn sigprocmask(flags: u32, noalias set: *const sigset_t, noalias oldset: ?*sigset_t) usize { return syscall4(SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8); } -pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigaction) usize { +pub fn sigaction(sig: u6, noalias act: *const Sigaction, noalias oact: ?*Sigaction) usize { assert(sig >= 1); assert(sig != SIGKILL); assert(sig != SIGSTOP); @@ -942,8 +942,8 @@ pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigacti .restorer = @ptrCast(extern fn () void, restore_rt), }; var ksa_old: k_sigaction = undefined; - @memcpy(@ptrCast(&u8, &ksa.mask), @ptrCast(&const u8, &act.mask), 8); - const result = syscall4(SYS_rt_sigaction, sig, @ptrToInt(&ksa), @ptrToInt(&ksa_old), @sizeOf(@typeOf(ksa.mask))); + @memcpy(@ptrCast(*u8, *ksa.mask), @ptrCast(*const u8, *act.mask), 8); + const result = syscall4(SYS_rt_sigaction, sig, @ptrToInt(*ksa), @ptrToInt(*ksa_old), @sizeOf(@typeOf(ksa.mask))); const err = getErrno(result); if (err != 0) { return result; @@ -951,7 +951,7 @@ pub fn sigaction(sig: u6, noalias act: &const Sigaction, noalias oact: ?&Sigacti if (oact) |old| { old.handler = ksa_old.handler; old.flags = @truncate(u32, ksa_old.flags); - @memcpy(@ptrCast(&u8, &old.mask), @ptrCast(&const u8, &ksa_old.mask), @sizeOf(@typeOf(ksa_old.mask))); + @memcpy(@ptrCast(*u8, *old.mask), @ptrCast(*const u8, *ksa_old.mask), @sizeOf(@typeOf(ksa_old.mask))); } return 0; } @@ -989,24 +989,24 @@ pub fn raise(sig: i32) usize { return ret; } -fn blockAllSignals(set: &sigset_t) void { +fn blockAllSignals(set: *sigset_t) void { _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&all_mask), @ptrToInt(set), NSIG / 8); } -fn blockAppSignals(set: &sigset_t) void { +fn blockAppSignals(set: *sigset_t) void { _ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&app_mask), @ptrToInt(set), NSIG / 8); } -fn restoreSignals(set: &sigset_t) void { +fn restoreSignals(set: *sigset_t) void { _ = syscall4(SYS_rt_sigprocmask, SIG_SETMASK, @ptrToInt(set), 0, NSIG / 8); } -pub fn sigaddset(set: &sigset_t, sig: u6) void { +pub fn sigaddset(set: *sigset_t, sig: u6) void { const s = sig - 1; (set.*)[usize(s) / usize.bit_count] |= usize(1) << (s & (usize.bit_count - 1)); } -pub fn sigismember(set: &const sigset_t, sig: u6) bool { +pub fn sigismember(set: *const sigset_t, sig: u6) bool { const s = sig - 1; return ((set.*)[usize(s) / usize.bit_count] & (usize(1) << (s & (usize.bit_count - 1)))) != 0; } @@ -1036,15 +1036,15 @@ pub const sockaddr_in6 = extern struct { }; pub const iovec = extern struct { - iov_base: &u8, + iov_base: *u8, iov_len: usize, }; -pub fn getsockname(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t) usize { +pub fn getsockname(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { return syscall3(SYS_getsockname, usize(fd), @ptrToInt(addr), @ptrToInt(len)); } -pub fn getpeername(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t) usize { +pub fn getpeername(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { return syscall3(SYS_getpeername, usize(fd), @ptrToInt(addr), @ptrToInt(len)); } @@ -1052,27 +1052,27 @@ pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize { return syscall3(SYS_socket, domain, socket_type, protocol); } -pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: &const u8, optlen: socklen_t) usize { +pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: *const u8, optlen: socklen_t) usize { return syscall5(SYS_setsockopt, usize(fd), level, optname, usize(optval), @ptrToInt(optlen)); } -pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: &u8, noalias optlen: &socklen_t) usize { +pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: *u8, noalias optlen: *socklen_t) usize { return syscall5(SYS_getsockopt, usize(fd), level, optname, @ptrToInt(optval), @ptrToInt(optlen)); } -pub fn sendmsg(fd: i32, msg: &const msghdr, flags: u32) usize { +pub fn sendmsg(fd: i32, msg: *const msghdr, flags: u32) usize { return syscall3(SYS_sendmsg, usize(fd), @ptrToInt(msg), flags); } -pub fn connect(fd: i32, addr: &const sockaddr, len: socklen_t) usize { +pub fn connect(fd: i32, addr: *const sockaddr, len: socklen_t) usize { return syscall3(SYS_connect, usize(fd), @ptrToInt(addr), usize(len)); } -pub fn recvmsg(fd: i32, msg: &msghdr, flags: u32) usize { +pub fn recvmsg(fd: i32, msg: *msghdr, flags: u32) usize { return syscall3(SYS_recvmsg, usize(fd), @ptrToInt(msg), flags); } -pub fn recvfrom(fd: i32, noalias buf: &u8, len: usize, flags: u32, noalias addr: ?&sockaddr, noalias alen: ?&socklen_t) usize { +pub fn recvfrom(fd: i32, noalias buf: *u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize { return syscall6(SYS_recvfrom, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); } @@ -1080,7 +1080,7 @@ pub fn shutdown(fd: i32, how: i32) usize { return syscall2(SYS_shutdown, usize(fd), usize(how)); } -pub fn bind(fd: i32, addr: &const sockaddr, len: socklen_t) usize { +pub fn bind(fd: i32, addr: *const sockaddr, len: socklen_t) usize { return syscall3(SYS_bind, usize(fd), @ptrToInt(addr), usize(len)); } @@ -1088,79 +1088,79 @@ pub fn listen(fd: i32, backlog: u32) usize { return syscall2(SYS_listen, usize(fd), backlog); } -pub fn sendto(fd: i32, buf: &const u8, len: usize, flags: u32, addr: ?&const sockaddr, alen: socklen_t) usize { +pub fn sendto(fd: i32, buf: *const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize { return syscall6(SYS_sendto, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), usize(alen)); } pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usize { - return syscall4(SYS_socketpair, usize(domain), usize(socket_type), usize(protocol), @ptrToInt(&fd[0])); + return syscall4(SYS_socketpair, usize(domain), usize(socket_type), usize(protocol), @ptrToInt(*fd[0])); } -pub fn accept(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t) usize { +pub fn accept(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { return accept4(fd, addr, len, 0); } -pub fn accept4(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t, flags: u32) usize { +pub fn accept4(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t, flags: u32) usize { return syscall4(SYS_accept4, usize(fd), @ptrToInt(addr), @ptrToInt(len), flags); } -pub fn fstat(fd: i32, stat_buf: &Stat) usize { +pub fn fstat(fd: i32, stat_buf: *Stat) usize { return syscall2(SYS_fstat, usize(fd), @ptrToInt(stat_buf)); } -pub fn stat(pathname: &const u8, statbuf: &Stat) usize { +pub fn stat(pathname: *const u8, statbuf: *Stat) usize { return syscall2(SYS_stat, @ptrToInt(pathname), @ptrToInt(statbuf)); } -pub fn lstat(pathname: &const u8, statbuf: &Stat) usize { +pub fn lstat(pathname: *const u8, statbuf: *Stat) usize { return syscall2(SYS_lstat, @ptrToInt(pathname), @ptrToInt(statbuf)); } -pub fn listxattr(path: &const u8, list: &u8, size: usize) usize { +pub fn listxattr(path: *const u8, list: *u8, size: usize) usize { return syscall3(SYS_listxattr, @ptrToInt(path), @ptrToInt(list), size); } -pub fn llistxattr(path: &const u8, list: &u8, size: usize) usize { +pub fn llistxattr(path: *const u8, list: *u8, size: usize) usize { return syscall3(SYS_llistxattr, @ptrToInt(path), @ptrToInt(list), size); } -pub fn flistxattr(fd: usize, list: &u8, size: usize) usize { +pub fn flistxattr(fd: usize, list: *u8, size: usize) usize { return syscall3(SYS_flistxattr, fd, @ptrToInt(list), size); } -pub fn getxattr(path: &const u8, name: &const u8, value: &void, size: usize) usize { +pub fn getxattr(path: *const u8, name: *const u8, value: *void, size: usize) usize { return syscall4(SYS_getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); } -pub fn lgetxattr(path: &const u8, name: &const u8, value: &void, size: usize) usize { +pub fn lgetxattr(path: *const u8, name: *const u8, value: *void, size: usize) usize { return syscall4(SYS_lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); } -pub fn fgetxattr(fd: usize, name: &const u8, value: &void, size: usize) usize { +pub fn fgetxattr(fd: usize, name: *const u8, value: *void, size: usize) usize { return syscall4(SYS_lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size); } -pub fn setxattr(path: &const u8, name: &const u8, value: &const void, size: usize, flags: usize) usize { +pub fn setxattr(path: *const u8, name: *const u8, value: *const void, size: usize, flags: usize) usize { return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } -pub fn lsetxattr(path: &const u8, name: &const u8, value: &const void, size: usize, flags: usize) usize { +pub fn lsetxattr(path: *const u8, name: *const u8, value: *const void, size: usize, flags: usize) usize { return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } -pub fn fsetxattr(fd: usize, name: &const u8, value: &const void, size: usize, flags: usize) usize { +pub fn fsetxattr(fd: usize, name: *const u8, value: *const void, size: usize, flags: usize) usize { return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags); } -pub fn removexattr(path: &const u8, name: &const u8) usize { +pub fn removexattr(path: *const u8, name: *const u8) usize { return syscall2(SYS_removexattr, @ptrToInt(path), @ptrToInt(name)); } -pub fn lremovexattr(path: &const u8, name: &const u8) usize { +pub fn lremovexattr(path: *const u8, name: *const u8) usize { return syscall2(SYS_lremovexattr, @ptrToInt(path), @ptrToInt(name)); } -pub fn fremovexattr(fd: usize, name: &const u8) usize { +pub fn fremovexattr(fd: usize, name: *const u8) usize { return syscall2(SYS_fremovexattr, fd, @ptrToInt(name)); } @@ -1184,11 +1184,11 @@ pub fn epoll_create1(flags: usize) usize { return syscall1(SYS_epoll_create1, flags); } -pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: &epoll_event) usize { +pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: *epoll_event) usize { return syscall4(SYS_epoll_ctl, usize(epoll_fd), usize(op), usize(fd), @ptrToInt(ev)); } -pub fn epoll_wait(epoll_fd: i32, events: &epoll_event, maxevents: u32, timeout: i32) usize { +pub fn epoll_wait(epoll_fd: i32, events: *epoll_event, maxevents: u32, timeout: i32) usize { return syscall4(SYS_epoll_wait, usize(epoll_fd), @ptrToInt(events), usize(maxevents), usize(timeout)); } @@ -1201,11 +1201,11 @@ pub const itimerspec = extern struct { it_value: timespec, }; -pub fn timerfd_gettime(fd: i32, curr_value: &itimerspec) usize { +pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) usize { return syscall2(SYS_timerfd_gettime, usize(fd), @ptrToInt(curr_value)); } -pub fn timerfd_settime(fd: i32, flags: u32, new_value: &const itimerspec, old_value: ?&itimerspec) usize { +pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const itimerspec, old_value: ?*itimerspec) usize { return syscall4(SYS_timerfd_settime, usize(fd), usize(flags), @ptrToInt(new_value), @ptrToInt(old_value)); } @@ -1300,8 +1300,8 @@ pub fn CAP_TO_INDEX(cap: u8) u8 { } pub const cap_t = extern struct { - hdrp: &cap_user_header_t, - datap: &cap_user_data_t, + hdrp: *cap_user_header_t, + datap: *cap_user_data_t, }; pub const cap_user_header_t = extern struct { @@ -1319,11 +1319,11 @@ pub fn unshare(flags: usize) usize { return syscall1(SYS_unshare, usize(flags)); } -pub fn capget(hdrp: &cap_user_header_t, datap: &cap_user_data_t) usize { +pub fn capget(hdrp: *cap_user_header_t, datap: *cap_user_data_t) usize { return syscall2(SYS_capget, @ptrToInt(hdrp), @ptrToInt(datap)); } -pub fn capset(hdrp: &cap_user_header_t, datap: &const cap_user_data_t) usize { +pub fn capset(hdrp: *cap_user_header_t, datap: *const cap_user_data_t) usize { return syscall2(SYS_capset, @ptrToInt(hdrp), @ptrToInt(datap)); } diff --git a/std/os/linux/vdso.zig b/std/os/linux/vdso.zig index 8e0a285841..1317da6388 100644 --- a/std/os/linux/vdso.zig +++ b/std/os/linux/vdso.zig @@ -8,11 +8,11 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { const vdso_addr = std.os.linux_aux_raw[std.elf.AT_SYSINFO_EHDR]; if (vdso_addr == 0) return 0; - const eh = @intToPtr(&elf.Ehdr, vdso_addr); + const eh = @intToPtr(*elf.Ehdr, vdso_addr); var ph_addr: usize = vdso_addr + eh.e_phoff; - const ph = @intToPtr(&elf.Phdr, ph_addr); + const ph = @intToPtr(*elf.Phdr, ph_addr); - var maybe_dynv: ?&usize = null; + var maybe_dynv: ?*usize = null; var base: usize = @maxValue(usize); { var i: usize = 0; @@ -20,10 +20,10 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { i += 1; ph_addr += eh.e_phentsize; }) { - const this_ph = @intToPtr(&elf.Phdr, ph_addr); + const this_ph = @intToPtr(*elf.Phdr, ph_addr); switch (this_ph.p_type) { elf.PT_LOAD => base = vdso_addr + this_ph.p_offset - this_ph.p_vaddr, - elf.PT_DYNAMIC => maybe_dynv = @intToPtr(&usize, vdso_addr + this_ph.p_offset), + elf.PT_DYNAMIC => maybe_dynv = @intToPtr(*usize, vdso_addr + this_ph.p_offset), else => {}, } } @@ -31,22 +31,22 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { const dynv = maybe_dynv ?? return 0; if (base == @maxValue(usize)) return 0; - var maybe_strings: ?&u8 = null; - var maybe_syms: ?&elf.Sym = null; - var maybe_hashtab: ?&linux.Elf_Symndx = null; - var maybe_versym: ?&u16 = null; - var maybe_verdef: ?&elf.Verdef = null; + var maybe_strings: ?*u8 = null; + var maybe_syms: ?*elf.Sym = null; + var maybe_hashtab: ?*linux.Elf_Symndx = null; + var maybe_versym: ?*u16 = null; + var maybe_verdef: ?*elf.Verdef = null; { var i: usize = 0; while (dynv[i] != 0) : (i += 2) { const p = base + dynv[i + 1]; switch (dynv[i]) { - elf.DT_STRTAB => maybe_strings = @intToPtr(&u8, p), - elf.DT_SYMTAB => maybe_syms = @intToPtr(&elf.Sym, p), - elf.DT_HASH => maybe_hashtab = @intToPtr(&linux.Elf_Symndx, p), - elf.DT_VERSYM => maybe_versym = @intToPtr(&u16, p), - elf.DT_VERDEF => maybe_verdef = @intToPtr(&elf.Verdef, p), + elf.DT_STRTAB => maybe_strings = @intToPtr(*u8, p), + elf.DT_SYMTAB => maybe_syms = @intToPtr(*elf.Sym, p), + elf.DT_HASH => maybe_hashtab = @intToPtr(*linux.Elf_Symndx, p), + elf.DT_VERSYM => maybe_versym = @intToPtr(*u16, p), + elf.DT_VERDEF => maybe_verdef = @intToPtr(*elf.Verdef, p), else => {}, } } @@ -76,7 +76,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { return 0; } -fn checkver(def_arg: &elf.Verdef, vsym_arg: i32, vername: []const u8, strings: &u8) bool { +fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: *u8) bool { var def = def_arg; const vsym = @bitCast(u32, vsym_arg) & 0x7fff; while (true) { @@ -84,8 +84,8 @@ fn checkver(def_arg: &elf.Verdef, vsym_arg: i32, vername: []const u8, strings: & break; if (def.vd_next == 0) return false; - def = @intToPtr(&elf.Verdef, @ptrToInt(def) + def.vd_next); + def = @intToPtr(*elf.Verdef, @ptrToInt(def) + def.vd_next); } - const aux = @intToPtr(&elf.Verdaux, @ptrToInt(def) + def.vd_aux); + const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux); return mem.eql(u8, vername, cstr.toSliceConst(&strings[aux.vda_name])); } diff --git a/std/os/linux/x86_64.zig b/std/os/linux/x86_64.zig index b43a642038..9a90e64757 100644 --- a/std/os/linux/x86_64.zig +++ b/std/os/linux/x86_64.zig @@ -463,7 +463,7 @@ pub fn syscall6( } /// This matches the libc clone function. -pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: usize, arg: usize, ptid: &i32, tls: usize, ctid: &i32) usize; +pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: usize, arg: usize, ptid: *i32, tls: usize, ctid: *i32) usize; pub nakedcc fn restore_rt() void { return asm volatile ("syscall" @@ -474,12 +474,12 @@ pub nakedcc fn restore_rt() void { } pub const msghdr = extern struct { - msg_name: &u8, + msg_name: *u8, msg_namelen: socklen_t, - msg_iov: &iovec, + msg_iov: *iovec, msg_iovlen: i32, __pad1: i32, - msg_control: &u8, + msg_control: *u8, msg_controllen: socklen_t, __pad2: socklen_t, msg_flags: i32, diff --git a/std/os/path.zig b/std/os/path.zig index 162faffc42..4df6179bf5 100644 --- a/std/os/path.zig +++ b/std/os/path.zig @@ -32,7 +32,7 @@ pub fn isSep(byte: u8) bool { /// Naively combines a series of paths with the native path seperator. /// Allocates memory for the result, which must be freed by the caller. -pub fn join(allocator: &Allocator, paths: ...) ![]u8 { +pub fn join(allocator: *Allocator, paths: ...) ![]u8 { if (is_windows) { return joinWindows(allocator, paths); } else { @@ -40,11 +40,11 @@ pub fn join(allocator: &Allocator, paths: ...) ![]u8 { } } -pub fn joinWindows(allocator: &Allocator, paths: ...) ![]u8 { +pub fn joinWindows(allocator: *Allocator, paths: ...) ![]u8 { return mem.join(allocator, sep_windows, paths); } -pub fn joinPosix(allocator: &Allocator, paths: ...) ![]u8 { +pub fn joinPosix(allocator: *Allocator, paths: ...) ![]u8 { return mem.join(allocator, sep_posix, paths); } @@ -310,7 +310,7 @@ fn asciiEqlIgnoreCase(s1: []const u8, s2: []const u8) bool { } /// Converts the command line arguments into a slice and calls `resolveSlice`. -pub fn resolve(allocator: &Allocator, args: ...) ![]u8 { +pub fn resolve(allocator: *Allocator, args: ...) ![]u8 { var paths: [args.len][]const u8 = undefined; comptime var arg_i = 0; inline while (arg_i < args.len) : (arg_i += 1) { @@ -320,7 +320,7 @@ pub fn resolve(allocator: &Allocator, args: ...) ![]u8 { } /// On Windows, this calls `resolveWindows` and on POSIX it calls `resolvePosix`. -pub fn resolveSlice(allocator: &Allocator, paths: []const []const u8) ![]u8 { +pub fn resolveSlice(allocator: *Allocator, paths: []const []const u8) ![]u8 { if (is_windows) { return resolveWindows(allocator, paths); } else { @@ -334,7 +334,7 @@ pub fn resolveSlice(allocator: &Allocator, paths: []const []const u8) ![]u8 { /// If all paths are relative it uses the current working directory as a starting point. /// Each drive has its own current working directory. /// Path separators are canonicalized to '\\' and drives are canonicalized to capital letters. -pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 { +pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 { if (paths.len == 0) { assert(is_windows); // resolveWindows called on non windows can't use getCwd return os.getCwd(allocator); @@ -513,7 +513,7 @@ pub fn resolveWindows(allocator: &Allocator, paths: []const []const u8) ![]u8 { /// It resolves "." and "..". /// The result does not have a trailing path separator. /// If all paths are relative it uses the current working directory as a starting point. -pub fn resolvePosix(allocator: &Allocator, paths: []const []const u8) ![]u8 { +pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 { if (paths.len == 0) { assert(!is_windows); // resolvePosix called on windows can't use getCwd return os.getCwd(allocator); @@ -883,7 +883,7 @@ fn testBasenameWindows(input: []const u8, expected_output: []const u8) void { /// resolve to the same path (after calling `resolve` on each), a zero-length /// string is returned. /// On Windows this canonicalizes the drive to a capital letter and paths to `\\`. -pub fn relative(allocator: &Allocator, from: []const u8, to: []const u8) ![]u8 { +pub fn relative(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 { if (is_windows) { return relativeWindows(allocator, from, to); } else { @@ -891,7 +891,7 @@ pub fn relative(allocator: &Allocator, from: []const u8, to: []const u8) ![]u8 { } } -pub fn relativeWindows(allocator: &Allocator, from: []const u8, to: []const u8) ![]u8 { +pub fn relativeWindows(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 { const resolved_from = try resolveWindows(allocator, [][]const u8{from}); defer allocator.free(resolved_from); @@ -964,7 +964,7 @@ pub fn relativeWindows(allocator: &Allocator, from: []const u8, to: []const u8) return []u8{}; } -pub fn relativePosix(allocator: &Allocator, from: []const u8, to: []const u8) ![]u8 { +pub fn relativePosix(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 { const resolved_from = try resolvePosix(allocator, [][]const u8{from}); defer allocator.free(resolved_from); @@ -1063,7 +1063,7 @@ fn testRelativeWindows(from: []const u8, to: []const u8, expected_output: []cons /// Expands all symbolic links and resolves references to `.`, `..`, and /// extra `/` characters in ::pathname. /// Caller must deallocate result. -pub fn real(allocator: &Allocator, pathname: []const u8) ![]u8 { +pub fn real(allocator: *Allocator, pathname: []const u8) ![]u8 { switch (builtin.os) { Os.windows => { const pathname_buf = try allocator.alloc(u8, pathname.len + 1); diff --git a/std/os/test.zig b/std/os/test.zig index 4dfe76224a..4aa3535829 100644 --- a/std/os/test.zig +++ b/std/os/test.zig @@ -63,7 +63,7 @@ fn start1(ctx: void) u8 { return 0; } -fn start2(ctx: &i32) u8 { +fn start2(ctx: *i32) u8 { _ = @atomicRmw(i32, ctx, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); return 0; } diff --git a/std/os/time.zig b/std/os/time.zig index 9a7c682483..8629504323 100644 --- a/std/os/time.zig +++ b/std/os/time.zig @@ -200,7 +200,7 @@ pub const Timer = struct { } /// Reads the timer value since start or the last reset in nanoseconds - pub fn read(self: &Timer) u64 { + pub fn read(self: *Timer) u64 { var clock = clockNative() - self.start_time; return switch (builtin.os) { Os.windows => @divFloor(clock * ns_per_s, self.frequency), @@ -211,12 +211,12 @@ pub const Timer = struct { } /// Resets the timer value to 0/now. - pub fn reset(self: &Timer) void { + pub fn reset(self: *Timer) void { self.start_time = clockNative(); } /// Returns the current value of the timer in nanoseconds, then resets it - pub fn lap(self: &Timer) u64 { + pub fn lap(self: *Timer) u64 { var now = clockNative(); var lap_time = self.read(); self.start_time = now; diff --git a/std/os/windows/index.zig b/std/os/windows/index.zig index 264ea391c4..85f69836d5 100644 --- a/std/os/windows/index.zig +++ b/std/os/windows/index.zig @@ -1,7 +1,7 @@ pub const ERROR = @import("error.zig"); pub extern "advapi32" stdcallcc fn CryptAcquireContextA( - phProv: &HCRYPTPROV, + phProv: *HCRYPTPROV, pszContainer: ?LPCSTR, pszProvider: ?LPCSTR, dwProvType: DWORD, @@ -10,13 +10,13 @@ pub extern "advapi32" stdcallcc fn CryptAcquireContextA( pub extern "advapi32" stdcallcc fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) BOOL; -pub extern "advapi32" stdcallcc fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: &BYTE) BOOL; +pub extern "advapi32" stdcallcc fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *BYTE) BOOL; pub extern "kernel32" stdcallcc fn CloseHandle(hObject: HANDLE) BOOL; pub extern "kernel32" stdcallcc fn CreateDirectoryA( lpPathName: LPCSTR, - lpSecurityAttributes: ?&SECURITY_ATTRIBUTES, + lpSecurityAttributes: ?*SECURITY_ATTRIBUTES, ) BOOL; pub extern "kernel32" stdcallcc fn CreateFileA( @@ -30,23 +30,23 @@ pub extern "kernel32" stdcallcc fn CreateFileA( ) HANDLE; pub extern "kernel32" stdcallcc fn CreatePipe( - hReadPipe: &HANDLE, - hWritePipe: &HANDLE, - lpPipeAttributes: &const SECURITY_ATTRIBUTES, + hReadPipe: *HANDLE, + hWritePipe: *HANDLE, + lpPipeAttributes: *const SECURITY_ATTRIBUTES, nSize: DWORD, ) BOOL; pub extern "kernel32" stdcallcc fn CreateProcessA( lpApplicationName: ?LPCSTR, lpCommandLine: LPSTR, - lpProcessAttributes: ?&SECURITY_ATTRIBUTES, - lpThreadAttributes: ?&SECURITY_ATTRIBUTES, + lpProcessAttributes: ?*SECURITY_ATTRIBUTES, + lpThreadAttributes: ?*SECURITY_ATTRIBUTES, bInheritHandles: BOOL, dwCreationFlags: DWORD, - lpEnvironment: ?&c_void, + lpEnvironment: ?*c_void, lpCurrentDirectory: ?LPCSTR, - lpStartupInfo: &STARTUPINFOA, - lpProcessInformation: &PROCESS_INFORMATION, + lpStartupInfo: *STARTUPINFOA, + lpProcessInformation: *PROCESS_INFORMATION, ) BOOL; pub extern "kernel32" stdcallcc fn CreateSymbolicLinkA( @@ -65,7 +65,7 @@ pub extern "kernel32" stdcallcc fn FreeEnvironmentStringsA(penv: LPCH) BOOL; pub extern "kernel32" stdcallcc fn GetCommandLineA() LPSTR; -pub extern "kernel32" stdcallcc fn GetConsoleMode(in_hConsoleHandle: HANDLE, out_lpMode: &DWORD) BOOL; +pub extern "kernel32" stdcallcc fn GetConsoleMode(in_hConsoleHandle: HANDLE, out_lpMode: *DWORD) BOOL; pub extern "kernel32" stdcallcc fn GetCurrentDirectoryA(nBufferLength: WORD, lpBuffer: ?LPSTR) DWORD; @@ -73,9 +73,9 @@ pub extern "kernel32" stdcallcc fn GetEnvironmentStringsA() ?LPCH; pub extern "kernel32" stdcallcc fn GetEnvironmentVariableA(lpName: LPCSTR, lpBuffer: LPSTR, nSize: DWORD) DWORD; -pub extern "kernel32" stdcallcc fn GetExitCodeProcess(hProcess: HANDLE, lpExitCode: &DWORD) BOOL; +pub extern "kernel32" stdcallcc fn GetExitCodeProcess(hProcess: HANDLE, lpExitCode: *DWORD) BOOL; -pub extern "kernel32" stdcallcc fn GetFileSizeEx(hFile: HANDLE, lpFileSize: &LARGE_INTEGER) BOOL; +pub extern "kernel32" stdcallcc fn GetFileSizeEx(hFile: HANDLE, lpFileSize: *LARGE_INTEGER) BOOL; pub extern "kernel32" stdcallcc fn GetModuleFileNameA(hModule: ?HMODULE, lpFilename: LPSTR, nSize: DWORD) DWORD; @@ -84,7 +84,7 @@ pub extern "kernel32" stdcallcc fn GetLastError() DWORD; pub extern "kernel32" stdcallcc fn GetFileInformationByHandleEx( in_hFile: HANDLE, in_FileInformationClass: FILE_INFO_BY_HANDLE_CLASS, - out_lpFileInformation: &c_void, + out_lpFileInformation: *c_void, in_dwBufferSize: DWORD, ) BOOL; @@ -97,21 +97,21 @@ pub extern "kernel32" stdcallcc fn GetFinalPathNameByHandleA( pub extern "kernel32" stdcallcc fn GetProcessHeap() ?HANDLE; -pub extern "kernel32" stdcallcc fn GetSystemTimeAsFileTime(?&FILETIME) void; +pub extern "kernel32" stdcallcc fn GetSystemTimeAsFileTime(?*FILETIME) void; pub extern "kernel32" stdcallcc fn HeapCreate(flOptions: DWORD, dwInitialSize: SIZE_T, dwMaximumSize: SIZE_T) ?HANDLE; pub extern "kernel32" stdcallcc fn HeapDestroy(hHeap: HANDLE) BOOL; -pub extern "kernel32" stdcallcc fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: &c_void, dwBytes: SIZE_T) ?&c_void; -pub extern "kernel32" stdcallcc fn HeapSize(hHeap: HANDLE, dwFlags: DWORD, lpMem: &const c_void) SIZE_T; -pub extern "kernel32" stdcallcc fn HeapValidate(hHeap: HANDLE, dwFlags: DWORD, lpMem: &const c_void) BOOL; +pub extern "kernel32" stdcallcc fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: *c_void, dwBytes: SIZE_T) ?*c_void; +pub extern "kernel32" stdcallcc fn HeapSize(hHeap: HANDLE, dwFlags: DWORD, lpMem: *const c_void) SIZE_T; +pub extern "kernel32" stdcallcc fn HeapValidate(hHeap: HANDLE, dwFlags: DWORD, lpMem: *const c_void) BOOL; pub extern "kernel32" stdcallcc fn HeapCompact(hHeap: HANDLE, dwFlags: DWORD) SIZE_T; pub extern "kernel32" stdcallcc fn HeapSummary(hHeap: HANDLE, dwFlags: DWORD, lpSummary: LPHEAP_SUMMARY) BOOL; pub extern "kernel32" stdcallcc fn GetStdHandle(in_nStdHandle: DWORD) ?HANDLE; -pub extern "kernel32" stdcallcc fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) ?&c_void; +pub extern "kernel32" stdcallcc fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) ?*c_void; -pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: &c_void) BOOL; +pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: *c_void) BOOL; pub extern "kernel32" stdcallcc fn MoveFileExA( lpExistingFileName: LPCSTR, @@ -119,24 +119,24 @@ pub extern "kernel32" stdcallcc fn MoveFileExA( dwFlags: DWORD, ) BOOL; -pub extern "kernel32" stdcallcc fn QueryPerformanceCounter(lpPerformanceCount: &LARGE_INTEGER) BOOL; +pub extern "kernel32" stdcallcc fn QueryPerformanceCounter(lpPerformanceCount: *LARGE_INTEGER) BOOL; -pub extern "kernel32" stdcallcc fn QueryPerformanceFrequency(lpFrequency: &LARGE_INTEGER) BOOL; +pub extern "kernel32" stdcallcc fn QueryPerformanceFrequency(lpFrequency: *LARGE_INTEGER) BOOL; pub extern "kernel32" stdcallcc fn PathFileExists(pszPath: ?LPCTSTR) BOOL; pub extern "kernel32" stdcallcc fn ReadFile( in_hFile: HANDLE, - out_lpBuffer: &c_void, + out_lpBuffer: *c_void, in_nNumberOfBytesToRead: DWORD, - out_lpNumberOfBytesRead: &DWORD, - in_out_lpOverlapped: ?&OVERLAPPED, + out_lpNumberOfBytesRead: *DWORD, + in_out_lpOverlapped: ?*OVERLAPPED, ) BOOL; pub extern "kernel32" stdcallcc fn SetFilePointerEx( in_fFile: HANDLE, in_liDistanceToMove: LARGE_INTEGER, - out_opt_ldNewFilePointer: ?&LARGE_INTEGER, + out_opt_ldNewFilePointer: ?*LARGE_INTEGER, in_dwMoveMethod: DWORD, ) BOOL; @@ -150,10 +150,10 @@ pub extern "kernel32" stdcallcc fn WaitForSingleObject(hHandle: HANDLE, dwMillis pub extern "kernel32" stdcallcc fn WriteFile( in_hFile: HANDLE, - in_lpBuffer: &const c_void, + in_lpBuffer: *const c_void, in_nNumberOfBytesToWrite: DWORD, - out_lpNumberOfBytesWritten: ?&DWORD, - in_out_lpOverlapped: ?&OVERLAPPED, + out_lpNumberOfBytesWritten: ?*DWORD, + in_out_lpOverlapped: ?*OVERLAPPED, ) BOOL; //TODO: call unicode versions instead of relying on ANSI code page @@ -171,23 +171,23 @@ pub const BYTE = u8; pub const CHAR = u8; pub const DWORD = u32; pub const FLOAT = f32; -pub const HANDLE = &c_void; +pub const HANDLE = *c_void; pub const HCRYPTPROV = ULONG_PTR; -pub const HINSTANCE = &@OpaqueType(); -pub const HMODULE = &@OpaqueType(); +pub const HINSTANCE = *@OpaqueType(); +pub const HMODULE = *@OpaqueType(); pub const INT = c_int; -pub const LPBYTE = &BYTE; -pub const LPCH = &CHAR; -pub const LPCSTR = &const CHAR; -pub const LPCTSTR = &const TCHAR; -pub const LPCVOID = &const c_void; -pub const LPDWORD = &DWORD; -pub const LPSTR = &CHAR; +pub const LPBYTE = *BYTE; +pub const LPCH = *CHAR; +pub const LPCSTR = *const CHAR; +pub const LPCTSTR = *const TCHAR; +pub const LPCVOID = *const c_void; +pub const LPDWORD = *DWORD; +pub const LPSTR = *CHAR; pub const LPTSTR = if (UNICODE) LPWSTR else LPSTR; -pub const LPVOID = &c_void; -pub const LPWSTR = &WCHAR; -pub const PVOID = &c_void; -pub const PWSTR = &WCHAR; +pub const LPVOID = *c_void; +pub const LPWSTR = *WCHAR; +pub const PVOID = *c_void; +pub const PWSTR = *WCHAR; pub const SIZE_T = usize; pub const TCHAR = if (UNICODE) WCHAR else u8; pub const UINT = c_uint; @@ -218,7 +218,7 @@ pub const OVERLAPPED = extern struct { Pointer: PVOID, hEvent: HANDLE, }; -pub const LPOVERLAPPED = &OVERLAPPED; +pub const LPOVERLAPPED = *OVERLAPPED; pub const MAX_PATH = 260; @@ -271,11 +271,11 @@ pub const VOLUME_NAME_NT = 0x2; pub const SECURITY_ATTRIBUTES = extern struct { nLength: DWORD, - lpSecurityDescriptor: ?&c_void, + lpSecurityDescriptor: ?*c_void, bInheritHandle: BOOL, }; -pub const PSECURITY_ATTRIBUTES = &SECURITY_ATTRIBUTES; -pub const LPSECURITY_ATTRIBUTES = &SECURITY_ATTRIBUTES; +pub const PSECURITY_ATTRIBUTES = *SECURITY_ATTRIBUTES; +pub const LPSECURITY_ATTRIBUTES = *SECURITY_ATTRIBUTES; pub const GENERIC_READ = 0x80000000; pub const GENERIC_WRITE = 0x40000000; diff --git a/std/os/windows/util.zig b/std/os/windows/util.zig index 2bd8a157e4..7170346108 100644 --- a/std/os/windows/util.zig +++ b/std/os/windows/util.zig @@ -42,7 +42,7 @@ pub const WriteError = error{ }; pub fn windowsWrite(handle: windows.HANDLE, bytes: []const u8) WriteError!void { - if (windows.WriteFile(handle, @ptrCast(&const c_void, bytes.ptr), u32(bytes.len), null, null) == 0) { + if (windows.WriteFile(handle, @ptrCast(*const c_void, bytes.ptr), u32(bytes.len), null, null) == 0) { const err = windows.GetLastError(); return switch (err) { windows.ERROR.INVALID_USER_BUFFER => WriteError.SystemResources, @@ -68,11 +68,11 @@ pub fn windowsIsCygwinPty(handle: windows.HANDLE) bool { const size = @sizeOf(windows.FILE_NAME_INFO); var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = []u8{0} ** (size + windows.MAX_PATH); - if (windows.GetFileInformationByHandleEx(handle, windows.FileNameInfo, @ptrCast(&c_void, &name_info_bytes[0]), u32(name_info_bytes.len)) == 0) { + if (windows.GetFileInformationByHandleEx(handle, windows.FileNameInfo, @ptrCast(*c_void, &name_info_bytes[0]), u32(name_info_bytes.len)) == 0) { return true; } - const name_info = @ptrCast(&const windows.FILE_NAME_INFO, &name_info_bytes[0]); + const name_info = @ptrCast(*const windows.FILE_NAME_INFO, &name_info_bytes[0]); const name_bytes = name_info_bytes[size .. size + usize(name_info.FileNameLength)]; const name_wide = ([]u16)(name_bytes); return mem.indexOf(u16, name_wide, []u16{ 'm', 's', 'y', 's', '-' }) != null or @@ -91,7 +91,7 @@ pub const OpenError = error{ /// `file_path` needs to be copied in memory to add a null terminating byte, hence the allocator. pub fn windowsOpen( - allocator: &mem.Allocator, + allocator: *mem.Allocator, file_path: []const u8, desired_access: windows.DWORD, share_mode: windows.DWORD, @@ -119,7 +119,7 @@ pub fn windowsOpen( } /// Caller must free result. -pub fn createWindowsEnvBlock(allocator: &mem.Allocator, env_map: &const BufMap) ![]u8 { +pub fn createWindowsEnvBlock(allocator: *mem.Allocator, env_map: *const BufMap) ![]u8 { // count bytes needed const bytes_needed = x: { var bytes_needed: usize = 1; // 1 for the final null byte @@ -150,7 +150,7 @@ pub fn createWindowsEnvBlock(allocator: &mem.Allocator, env_map: &const BufMap) return result; } -pub fn windowsLoadDll(allocator: &mem.Allocator, dll_path: []const u8) !windows.HMODULE { +pub fn windowsLoadDll(allocator: *mem.Allocator, dll_path: []const u8) !windows.HMODULE { const padded_buff = try cstr.addNullByte(allocator, dll_path); defer allocator.free(padded_buff); return windows.LoadLibraryA(padded_buff.ptr) ?? error.DllNotFound; diff --git a/std/os/zen.zig b/std/os/zen.zig index 2411c5363e..2312b36dea 100644 --- a/std/os/zen.zig +++ b/std/os/zen.zig @@ -8,7 +8,7 @@ pub const Message = struct { type: usize, payload: usize, - pub fn from(mailbox_id: &const MailboxId) Message { + pub fn from(mailbox_id: *const MailboxId) Message { return Message{ .sender = MailboxId.Undefined, .receiver = *mailbox_id, @@ -17,7 +17,7 @@ pub const Message = struct { }; } - pub fn to(mailbox_id: &const MailboxId, msg_type: usize) Message { + pub fn to(mailbox_id: *const MailboxId, msg_type: usize) Message { return Message{ .sender = MailboxId.This, .receiver = *mailbox_id, @@ -26,7 +26,7 @@ pub const Message = struct { }; } - pub fn withData(mailbox_id: &const MailboxId, msg_type: usize, payload: usize) Message { + pub fn withData(mailbox_id: *const MailboxId, msg_type: usize, payload: usize) Message { return Message{ .sender = MailboxId.This, .receiver = *mailbox_id, @@ -67,7 +67,7 @@ pub const getErrno = @import("linux/index.zig").getErrno; use @import("linux/errno.zig"); // TODO: implement this correctly. -pub fn read(fd: i32, buf: &u8, count: usize) usize { +pub fn read(fd: i32, buf: *u8, count: usize) usize { switch (fd) { STDIN_FILENO => { var i: usize = 0; @@ -75,7 +75,7 @@ pub fn read(fd: i32, buf: &u8, count: usize) usize { send(Message.to(Server.Keyboard, 0)); var message = Message.from(MailboxId.This); - receive(&message); + receive(*message); buf[i] = u8(message.payload); } @@ -86,7 +86,7 @@ pub fn read(fd: i32, buf: &u8, count: usize) usize { } // TODO: implement this correctly. -pub fn write(fd: i32, buf: &const u8, count: usize) usize { +pub fn write(fd: i32, buf: *const u8, count: usize) usize { switch (fd) { STDOUT_FILENO, STDERR_FILENO => { var i: usize = 0; @@ -126,22 +126,22 @@ pub fn exit(status: i32) noreturn { unreachable; } -pub fn createPort(mailbox_id: &const MailboxId) void { +pub fn createPort(mailbox_id: *const MailboxId) void { _ = switch (*mailbox_id) { MailboxId.Port => |id| syscall1(Syscall.createPort, id), else => unreachable, }; } -pub fn send(message: &const Message) void { +pub fn send(message: *const Message) void { _ = syscall1(Syscall.send, @ptrToInt(message)); } -pub fn receive(destination: &Message) void { +pub fn receive(destination: *Message) void { _ = syscall1(Syscall.receive, @ptrToInt(destination)); } -pub fn subscribeIRQ(irq: u8, mailbox_id: &const MailboxId) void { +pub fn subscribeIRQ(irq: u8, mailbox_id: *const MailboxId) void { _ = syscall2(Syscall.subscribeIRQ, irq, @ptrToInt(mailbox_id)); } diff --git a/std/rand/index.zig b/std/rand/index.zig index c32309a0fd..3a1a559cd9 100644 --- a/std/rand/index.zig +++ b/std/rand/index.zig @@ -28,15 +28,15 @@ pub const DefaultPrng = Xoroshiro128; pub const DefaultCsprng = Isaac64; pub const Random = struct { - fillFn: fn (r: &Random, buf: []u8) void, + fillFn: fn (r: *Random, buf: []u8) void, /// Read random bytes into the specified buffer until fill. - pub fn bytes(r: &Random, buf: []u8) void { + pub fn bytes(r: *Random, buf: []u8) void { r.fillFn(r, buf); } /// Return a random integer/boolean type. - pub fn scalar(r: &Random, comptime T: type) T { + pub fn scalar(r: *Random, comptime T: type) T { var rand_bytes: [@sizeOf(T)]u8 = undefined; r.bytes(rand_bytes[0..]); @@ -50,7 +50,7 @@ pub const Random = struct { /// Get a random unsigned integer with even distribution between `start` /// inclusive and `end` exclusive. - pub fn range(r: &Random, comptime T: type, start: T, end: T) T { + pub fn range(r: *Random, comptime T: type, start: T, end: T) T { assert(start <= end); if (T.is_signed) { const uint = @IntType(false, T.bit_count); @@ -92,7 +92,7 @@ pub const Random = struct { } /// Return a floating point value evenly distributed in the range [0, 1). - pub fn float(r: &Random, comptime T: type) T { + pub fn float(r: *Random, comptime T: type) T { // Generate a uniform value between [1, 2) and scale down to [0, 1). // Note: The lowest mantissa bit is always set to 0 so we only use half the available range. switch (T) { @@ -113,7 +113,7 @@ pub const Random = struct { /// Return a floating point value normally distributed with mean = 0, stddev = 1. /// /// To use different parameters, use: floatNorm(...) * desiredStddev + desiredMean. - pub fn floatNorm(r: &Random, comptime T: type) T { + pub fn floatNorm(r: *Random, comptime T: type) T { const value = ziggurat.next_f64(r, ziggurat.NormDist); switch (T) { f32 => return f32(value), @@ -125,7 +125,7 @@ pub const Random = struct { /// Return an exponentially distributed float with a rate parameter of 1. /// /// To use a different rate parameter, use: floatExp(...) / desiredRate. - pub fn floatExp(r: &Random, comptime T: type) T { + pub fn floatExp(r: *Random, comptime T: type) T { const value = ziggurat.next_f64(r, ziggurat.ExpDist); switch (T) { f32 => return f32(value), @@ -135,7 +135,7 @@ pub const Random = struct { } /// Shuffle a slice into a random order. - pub fn shuffle(r: &Random, comptime T: type, buf: []T) void { + pub fn shuffle(r: *Random, comptime T: type, buf: []T) void { if (buf.len < 2) { return; } @@ -159,7 +159,7 @@ const SplitMix64 = struct { return SplitMix64{ .s = seed }; } - pub fn next(self: &SplitMix64) u64 { + pub fn next(self: *SplitMix64) u64 { self.s +%= 0x9e3779b97f4a7c15; var z = self.s; @@ -208,7 +208,7 @@ pub const Pcg = struct { return pcg; } - fn next(self: &Pcg) u32 { + fn next(self: *Pcg) u32 { const l = self.s; self.s = l *% default_multiplier +% (self.i | 1); @@ -218,13 +218,13 @@ pub const Pcg = struct { return (xor_s >> u5(rot)) | (xor_s << u5((0 -% rot) & 31)); } - fn seed(self: &Pcg, init_s: u64) void { + fn seed(self: *Pcg, init_s: u64) void { // Pcg requires 128-bits of seed. var gen = SplitMix64.init(init_s); self.seedTwo(gen.next(), gen.next()); } - fn seedTwo(self: &Pcg, init_s: u64, init_i: u64) void { + fn seedTwo(self: *Pcg, init_s: u64, init_i: u64) void { self.s = 0; self.i = (init_s << 1) | 1; self.s = self.s *% default_multiplier +% self.i; @@ -232,7 +232,7 @@ pub const Pcg = struct { self.s = self.s *% default_multiplier +% self.i; } - fn fill(r: &Random, buf: []u8) void { + fn fill(r: *Random, buf: []u8) void { const self = @fieldParentPtr(Pcg, "random", r); var i: usize = 0; @@ -297,7 +297,7 @@ pub const Xoroshiro128 = struct { return x; } - fn next(self: &Xoroshiro128) u64 { + fn next(self: *Xoroshiro128) u64 { const s0 = self.s[0]; var s1 = self.s[1]; const r = s0 +% s1; @@ -310,7 +310,7 @@ pub const Xoroshiro128 = struct { } // Skip 2^64 places ahead in the sequence - fn jump(self: &Xoroshiro128) void { + fn jump(self: *Xoroshiro128) void { var s0: u64 = 0; var s1: u64 = 0; @@ -334,7 +334,7 @@ pub const Xoroshiro128 = struct { self.s[1] = s1; } - fn seed(self: &Xoroshiro128, init_s: u64) void { + fn seed(self: *Xoroshiro128, init_s: u64) void { // Xoroshiro requires 128-bits of seed. var gen = SplitMix64.init(init_s); @@ -342,7 +342,7 @@ pub const Xoroshiro128 = struct { self.s[1] = gen.next(); } - fn fill(r: &Random, buf: []u8) void { + fn fill(r: *Random, buf: []u8) void { const self = @fieldParentPtr(Xoroshiro128, "random", r); var i: usize = 0; @@ -435,7 +435,7 @@ pub const Isaac64 = struct { return isaac; } - fn step(self: &Isaac64, mix: u64, base: usize, comptime m1: usize, comptime m2: usize) void { + fn step(self: *Isaac64, mix: u64, base: usize, comptime m1: usize, comptime m2: usize) void { const x = self.m[base + m1]; self.a = mix +% self.m[base + m2]; @@ -446,7 +446,7 @@ pub const Isaac64 = struct { self.r[self.r.len - 1 - base - m1] = self.b; } - fn refill(self: &Isaac64) void { + fn refill(self: *Isaac64) void { const midpoint = self.r.len / 2; self.c +%= 1; @@ -475,7 +475,7 @@ pub const Isaac64 = struct { self.i = 0; } - fn next(self: &Isaac64) u64 { + fn next(self: *Isaac64) u64 { if (self.i >= self.r.len) { self.refill(); } @@ -485,7 +485,7 @@ pub const Isaac64 = struct { return value; } - fn seed(self: &Isaac64, init_s: u64, comptime rounds: usize) void { + fn seed(self: *Isaac64, init_s: u64, comptime rounds: usize) void { // We ignore the multi-pass requirement since we don't currently expose full access to // seeding the self.m array completely. mem.set(u64, self.m[0..], 0); @@ -551,7 +551,7 @@ pub const Isaac64 = struct { self.i = self.r.len; // trigger refill on first value } - fn fill(r: &Random, buf: []u8) void { + fn fill(r: *Random, buf: []u8) void { const self = @fieldParentPtr(Isaac64, "random", r); var i: usize = 0; @@ -666,7 +666,7 @@ test "Random range" { testRange(&prng.random, 10, 14); } -fn testRange(r: &Random, start: i32, end: i32) void { +fn testRange(r: *Random, start: i32, end: i32) void { const count = usize(end - start); var values_buffer = []bool{false} ** 20; const values = values_buffer[0..count]; diff --git a/std/rand/ziggurat.zig b/std/rand/ziggurat.zig index 7daeb59165..774d3bd52a 100644 --- a/std/rand/ziggurat.zig +++ b/std/rand/ziggurat.zig @@ -12,7 +12,7 @@ const std = @import("../index.zig"); const math = std.math; const Random = std.rand.Random; -pub fn next_f64(random: &Random, comptime tables: &const ZigTable) f64 { +pub fn next_f64(random: *Random, comptime tables: *const ZigTable) f64 { while (true) { // We manually construct a float from parts as we can avoid an extra random lookup here by // using the unused exponent for the lookup table entry. @@ -60,7 +60,7 @@ pub const ZigTable = struct { // whether the distribution is symmetric is_symmetric: bool, // fallback calculation in the case we are in the 0 block - zero_case: fn (&Random, f64) f64, + zero_case: fn (*Random, f64) f64, }; // zigNorInit @@ -70,7 +70,7 @@ fn ZigTableGen( comptime v: f64, comptime f: fn (f64) f64, comptime f_inv: fn (f64) f64, - comptime zero_case: fn (&Random, f64) f64, + comptime zero_case: fn (*Random, f64) f64, ) ZigTable { var tables: ZigTable = undefined; @@ -110,7 +110,7 @@ fn norm_f(x: f64) f64 { fn norm_f_inv(y: f64) f64 { return math.sqrt(-2.0 * math.ln(y)); } -fn norm_zero_case(random: &Random, u: f64) f64 { +fn norm_zero_case(random: *Random, u: f64) f64 { var x: f64 = 1; var y: f64 = 0; @@ -149,7 +149,7 @@ fn exp_f(x: f64) f64 { fn exp_f_inv(y: f64) f64 { return -math.ln(y); } -fn exp_zero_case(random: &Random, _: f64) f64 { +fn exp_zero_case(random: *Random, _: f64) f64 { return exp_r - math.ln(random.float(f64)); } diff --git a/std/segmented_list.zig b/std/segmented_list.zig index d755135fe8..be9a2071a0 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -87,49 +87,49 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type const ShelfIndex = std.math.Log2Int(usize); prealloc_segment: [prealloc_item_count]T, - dynamic_segments: []&T, - allocator: &Allocator, + dynamic_segments: []*T, + allocator: *Allocator, len: usize, pub const prealloc_count = prealloc_item_count; /// Deinitialize with `deinit` - pub fn init(allocator: &Allocator) Self { + pub fn init(allocator: *Allocator) Self { return Self{ .allocator = allocator, .len = 0, .prealloc_segment = undefined, - .dynamic_segments = []&T{}, + .dynamic_segments = []*T{}, }; } - pub fn deinit(self: &Self) void { + pub fn deinit(self: *Self) void { self.freeShelves(ShelfIndex(self.dynamic_segments.len), 0); self.allocator.free(self.dynamic_segments); self.* = undefined; } - pub fn at(self: &Self, i: usize) &T { + pub fn at(self: *Self, i: usize) *T { assert(i < self.len); return self.uncheckedAt(i); } - pub fn count(self: &const Self) usize { + pub fn count(self: *const Self) usize { return self.len; } - pub fn push(self: &Self, item: &const T) !void { + pub fn push(self: *Self, item: *const T) !void { const new_item_ptr = try self.addOne(); new_item_ptr.* = item.*; } - pub fn pushMany(self: &Self, items: []const T) !void { + pub fn pushMany(self: *Self, items: []const T) !void { for (items) |item| { try self.push(item); } } - pub fn pop(self: &Self) ?T { + pub fn pop(self: *Self) ?T { if (self.len == 0) return null; const index = self.len - 1; @@ -138,7 +138,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type return result; } - pub fn addOne(self: &Self) !&T { + pub fn addOne(self: *Self) !*T { const new_length = self.len + 1; try self.growCapacity(new_length); const result = self.uncheckedAt(self.len); @@ -147,7 +147,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } /// Grows or shrinks capacity to match usage. - pub fn setCapacity(self: &Self, new_capacity: usize) !void { + pub fn setCapacity(self: *Self, new_capacity: usize) !void { if (new_capacity <= usize(1) << (prealloc_exp + self.dynamic_segments.len)) { return self.shrinkCapacity(new_capacity); } else { @@ -156,15 +156,15 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } /// Only grows capacity, or retains current capacity - pub fn growCapacity(self: &Self, new_capacity: usize) !void { + pub fn growCapacity(self: *Self, new_capacity: usize) !void { const new_cap_shelf_count = shelfCount(new_capacity); const old_shelf_count = ShelfIndex(self.dynamic_segments.len); if (new_cap_shelf_count > old_shelf_count) { - self.dynamic_segments = try self.allocator.realloc(&T, self.dynamic_segments, new_cap_shelf_count); + self.dynamic_segments = try self.allocator.realloc(*T, self.dynamic_segments, new_cap_shelf_count); var i = old_shelf_count; errdefer { self.freeShelves(i, old_shelf_count); - self.dynamic_segments = self.allocator.shrink(&T, self.dynamic_segments, old_shelf_count); + self.dynamic_segments = self.allocator.shrink(*T, self.dynamic_segments, old_shelf_count); } while (i < new_cap_shelf_count) : (i += 1) { self.dynamic_segments[i] = (try self.allocator.alloc(T, shelfSize(i))).ptr; @@ -173,12 +173,12 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } /// Only shrinks capacity or retains current capacity - pub fn shrinkCapacity(self: &Self, new_capacity: usize) void { + pub fn shrinkCapacity(self: *Self, new_capacity: usize) void { if (new_capacity <= prealloc_item_count) { const len = ShelfIndex(self.dynamic_segments.len); self.freeShelves(len, 0); self.allocator.free(self.dynamic_segments); - self.dynamic_segments = []&T{}; + self.dynamic_segments = []*T{}; return; } @@ -190,10 +190,10 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } self.freeShelves(old_shelf_count, new_cap_shelf_count); - self.dynamic_segments = self.allocator.shrink(&T, self.dynamic_segments, new_cap_shelf_count); + self.dynamic_segments = self.allocator.shrink(*T, self.dynamic_segments, new_cap_shelf_count); } - pub fn uncheckedAt(self: &Self, index: usize) &T { + pub fn uncheckedAt(self: *Self, index: usize) *T { if (index < prealloc_item_count) { return &self.prealloc_segment[index]; } @@ -230,7 +230,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type return list_index + prealloc_item_count - (usize(1) << ((prealloc_exp + 1) + shelf_index)); } - fn freeShelves(self: &Self, from_count: ShelfIndex, to_count: ShelfIndex) void { + fn freeShelves(self: *Self, from_count: ShelfIndex, to_count: ShelfIndex) void { var i = from_count; while (i != to_count) { i -= 1; @@ -239,13 +239,13 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } pub const Iterator = struct { - list: &Self, + list: *Self, index: usize, box_index: usize, shelf_index: ShelfIndex, shelf_size: usize, - pub fn next(it: &Iterator) ?&T { + pub fn next(it: *Iterator) ?*T { if (it.index >= it.list.len) return null; if (it.index < prealloc_item_count) { const ptr = &it.list.prealloc_segment[it.index]; @@ -269,7 +269,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type return ptr; } - pub fn prev(it: &Iterator) ?&T { + pub fn prev(it: *Iterator) ?*T { if (it.index == 0) return null; it.index -= 1; @@ -286,7 +286,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type return &it.list.dynamic_segments[it.shelf_index][it.box_index]; } - pub fn peek(it: &Iterator) ?&T { + pub fn peek(it: *Iterator) ?*T { if (it.index >= it.list.len) return null; if (it.index < prealloc_item_count) @@ -295,7 +295,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type return &it.list.dynamic_segments[it.shelf_index][it.box_index]; } - pub fn set(it: &Iterator, index: usize) void { + pub fn set(it: *Iterator, index: usize) void { it.index = index; if (index < prealloc_item_count) return; it.shelf_index = shelfIndex(index); @@ -304,7 +304,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } }; - pub fn iterator(self: &Self, start_index: usize) Iterator { + pub fn iterator(self: *Self, start_index: usize) Iterator { var it = Iterator{ .list = self, .index = undefined, @@ -331,7 +331,7 @@ test "std.SegmentedList" { try testSegmentedList(16, a); } -fn testSegmentedList(comptime prealloc: usize, allocator: &Allocator) !void { +fn testSegmentedList(comptime prealloc: usize, allocator: *Allocator) !void { var list = SegmentedList(i32, prealloc).init(allocator); defer list.deinit(); diff --git a/std/sort.zig b/std/sort.zig index 4e17718241..1b44c18dd9 100644 --- a/std/sort.zig +++ b/std/sort.zig @@ -5,7 +5,7 @@ const math = std.math; const builtin = @import("builtin"); /// Stable in-place sort. O(n) best case, O(pow(n, 2)) worst case. O(1) memory (no allocator required). -pub fn insertionSort(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &const T) bool) void { +pub fn insertionSort(comptime T: type, items: []T, lessThan: fn (lhs: *const T, rhs: *const T) bool) void { { var i: usize = 1; while (i < items.len) : (i += 1) { @@ -30,7 +30,7 @@ const Range = struct { }; } - fn length(self: &const Range) usize { + fn length(self: *const Range) usize { return self.end - self.start; } }; @@ -58,12 +58,12 @@ const Iterator = struct { }; } - fn begin(self: &Iterator) void { + fn begin(self: *Iterator) void { self.numerator = 0; self.decimal = 0; } - fn nextRange(self: &Iterator) Range { + fn nextRange(self: *Iterator) Range { const start = self.decimal; self.decimal += self.decimal_step; @@ -79,11 +79,11 @@ const Iterator = struct { }; } - fn finished(self: &Iterator) bool { + fn finished(self: *Iterator) bool { return self.decimal >= self.size; } - fn nextLevel(self: &Iterator) bool { + fn nextLevel(self: *Iterator) bool { self.decimal_step += self.decimal_step; self.numerator_step += self.numerator_step; if (self.numerator_step >= self.denominator) { @@ -94,7 +94,7 @@ const Iterator = struct { return (self.decimal_step < self.size); } - fn length(self: &Iterator) usize { + fn length(self: *Iterator) usize { return self.decimal_step; } }; @@ -108,7 +108,7 @@ const Pull = struct { /// Stable in-place sort. O(n) best case, O(n*log(n)) worst case and average case. O(1) memory (no allocator required). /// Currently implemented as block sort. -pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &const T) bool) void { +pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: *const T, rhs: *const T) bool) void { // Implementation ported from https://github.com/BonzaiThePenguin/WikiSort/blob/master/WikiSort.c var cache: [512]T = undefined; @@ -741,7 +741,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &con } // merge operation without a buffer -fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const Range, lessThan: fn (&const T, &const T) bool) void { +fn mergeInPlace(comptime T: type, items: []T, A_arg: *const Range, B_arg: *const Range, lessThan: fn (*const T, *const T) bool) void { if (A_arg.length() == 0 or B_arg.length() == 0) return; // this just repeatedly binary searches into B and rotates A into position. @@ -783,7 +783,7 @@ fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const } // merge operation using an internal buffer -fn mergeInternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn (&const T, &const T) bool, buffer: &const Range) void { +fn mergeInternal(comptime T: type, items: []T, A: *const Range, B: *const Range, lessThan: fn (*const T, *const T) bool, buffer: *const Range) void { // whenever we find a value to add to the final array, swap it with the value that's already in that spot // when this algorithm is finished, 'buffer' will contain its original contents, but in a different order var A_count: usize = 0; @@ -819,7 +819,7 @@ fn blockSwap(comptime T: type, items: []T, start1: usize, start2: usize, block_s // combine a linear search with a binary search to reduce the number of comparisons in situations // where have some idea as to how many unique values there are and where the next value might be -fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool, unique: usize) usize { +fn findFirstForward(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, usize(1)); @@ -833,7 +833,7 @@ fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const return binaryFirst(T, items, value, Range.init(index - skip, index), lessThan); } -fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool, unique: usize) usize { +fn findFirstBackward(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, usize(1)); @@ -847,7 +847,7 @@ fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &cons return binaryFirst(T, items, value, Range.init(index, index + skip), lessThan); } -fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool, unique: usize) usize { +fn findLastForward(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, usize(1)); @@ -861,7 +861,7 @@ fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const return binaryLast(T, items, value, Range.init(index - skip, index), lessThan); } -fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool, unique: usize) usize { +fn findLastBackward(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, usize(1)); @@ -875,7 +875,7 @@ fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const return binaryLast(T, items, value, Range.init(index, index + skip), lessThan); } -fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool) usize { +fn binaryFirst(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool) usize { var start = range.start; var end = range.end - 1; if (range.start >= range.end) return range.end; @@ -893,7 +893,7 @@ fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Rang return start; } -fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn (&const T, &const T) bool) usize { +fn binaryLast(comptime T: type, items: []T, value: *const T, range: *const Range, lessThan: fn (*const T, *const T) bool) usize { var start = range.start; var end = range.end - 1; if (range.start >= range.end) return range.end; @@ -911,7 +911,7 @@ fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range return start; } -fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, lessThan: fn (&const T, &const T) bool, into: []T) void { +fn mergeInto(comptime T: type, from: []T, A: *const Range, B: *const Range, lessThan: fn (*const T, *const T) bool, into: []T) void { var A_index: usize = A.start; var B_index: usize = B.start; const A_last = A.end; @@ -941,7 +941,7 @@ fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, less } } -fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn (&const T, &const T) bool, cache: []T) void { +fn mergeExternal(comptime T: type, items: []T, A: *const Range, B: *const Range, lessThan: fn (*const T, *const T) bool, cache: []T) void { // A fits into the cache, so use that instead of the internal buffer var A_index: usize = 0; var B_index: usize = B.start; @@ -969,26 +969,26 @@ fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, mem.copy(T, items[insert_index..], cache[A_index..A_last]); } -fn swap(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &const T) bool, order: &[8]u8, x: usize, y: usize) void { +fn swap(comptime T: type, items: []T, lessThan: fn (lhs: *const T, rhs: *const T) bool, order: *[8]u8, x: usize, y: usize) void { if (lessThan(items[y], items[x]) or ((order.*)[x] > (order.*)[y] and !lessThan(items[x], items[y]))) { mem.swap(T, &items[x], &items[y]); mem.swap(u8, &(order.*)[x], &(order.*)[y]); } } -fn i32asc(lhs: &const i32, rhs: &const i32) bool { +fn i32asc(lhs: *const i32, rhs: *const i32) bool { return lhs.* < rhs.*; } -fn i32desc(lhs: &const i32, rhs: &const i32) bool { +fn i32desc(lhs: *const i32, rhs: *const i32) bool { return rhs.* < lhs.*; } -fn u8asc(lhs: &const u8, rhs: &const u8) bool { +fn u8asc(lhs: *const u8, rhs: *const u8) bool { return lhs.* < rhs.*; } -fn u8desc(lhs: &const u8, rhs: &const u8) bool { +fn u8desc(lhs: *const u8, rhs: *const u8) bool { return rhs.* < lhs.*; } @@ -1125,7 +1125,7 @@ const IdAndValue = struct { id: usize, value: i32, }; -fn cmpByValue(a: &const IdAndValue, b: &const IdAndValue) bool { +fn cmpByValue(a: *const IdAndValue, b: *const IdAndValue) bool { return i32asc(a.value, b.value); } @@ -1324,7 +1324,7 @@ test "sort fuzz testing" { var fixed_buffer_mem: [100 * 1024]u8 = undefined; -fn fuzzTest(rng: &std.rand.Random) void { +fn fuzzTest(rng: *std.rand.Random) void { const array_size = rng.range(usize, 0, 1000); var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]); var array = fixed_allocator.allocator.alloc(IdAndValue, array_size) catch unreachable; @@ -1345,7 +1345,7 @@ fn fuzzTest(rng: &std.rand.Random) void { } } -pub fn min(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &const T) bool) T { +pub fn min(comptime T: type, items: []T, lessThan: fn (lhs: *const T, rhs: *const T) bool) T { var i: usize = 0; var smallest = items[0]; for (items[1..]) |item| { @@ -1356,7 +1356,7 @@ pub fn min(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &cons return smallest; } -pub fn max(comptime T: type, items: []T, lessThan: fn (lhs: &const T, rhs: &const T) bool) T { +pub fn max(comptime T: type, items: []T, lessThan: fn (lhs: *const T, rhs: *const T) bool) T { var i: usize = 0; var biggest = items[0]; for (items[1..]) |item| { diff --git a/std/special/bootstrap.zig b/std/special/bootstrap.zig index c10f4aa806..5ed7874ca5 100644 --- a/std/special/bootstrap.zig +++ b/std/special/bootstrap.zig @@ -5,7 +5,7 @@ const root = @import("@root"); const std = @import("std"); const builtin = @import("builtin"); -var argc_ptr: &usize = undefined; +var argc_ptr: *usize = undefined; comptime { const strong_linkage = builtin.GlobalLinkage.Strong; @@ -28,12 +28,12 @@ nakedcc fn _start() noreturn { switch (builtin.arch) { builtin.Arch.x86_64 => { argc_ptr = asm ("lea (%%rsp), %[argc]" - : [argc] "=r" (-> &usize) + : [argc] "=r" (-> *usize) ); }, builtin.Arch.i386 => { argc_ptr = asm ("lea (%%esp), %[argc]" - : [argc] "=r" (-> &usize) + : [argc] "=r" (-> *usize) ); }, else => @compileError("unsupported arch"), @@ -51,13 +51,13 @@ extern fn WinMainCRTStartup() noreturn { fn posixCallMainAndExit() noreturn { const argc = argc_ptr.*; - const argv = @ptrCast(&&u8, &argc_ptr[1]); - const envp_nullable = @ptrCast(&?&u8, &argv[argc + 1]); + const argv = @ptrCast(**u8, &argc_ptr[1]); + const envp_nullable = @ptrCast(*?*u8, &argv[argc + 1]); var envp_count: usize = 0; while (envp_nullable[envp_count]) |_| : (envp_count += 1) {} - const envp = @ptrCast(&&u8, envp_nullable)[0..envp_count]; + const envp = @ptrCast(**u8, envp_nullable)[0..envp_count]; if (builtin.os == builtin.Os.linux) { - const auxv = &@ptrCast(&usize, envp.ptr)[envp_count + 1]; + const auxv = &@ptrCast(*usize, envp.ptr)[envp_count + 1]; var i: usize = 0; while (auxv[i] != 0) : (i += 2) { if (auxv[i] < std.os.linux_aux_raw.len) std.os.linux_aux_raw[auxv[i]] = auxv[i + 1]; @@ -68,16 +68,16 @@ fn posixCallMainAndExit() noreturn { std.os.posix.exit(callMainWithArgs(argc, argv, envp)); } -fn callMainWithArgs(argc: usize, argv: &&u8, envp: []&u8) u8 { +fn callMainWithArgs(argc: usize, argv: **u8, envp: []*u8) u8 { std.os.ArgIteratorPosix.raw = argv[0..argc]; std.os.posix_environ_raw = envp; return callMain(); } -extern fn main(c_argc: i32, c_argv: &&u8, c_envp: &?&u8) i32 { +extern fn main(c_argc: i32, c_argv: **u8, c_envp: *?*u8) i32 { var env_count: usize = 0; while (c_envp[env_count] != null) : (env_count += 1) {} - const envp = @ptrCast(&&u8, c_envp)[0..env_count]; + const envp = @ptrCast(**u8, c_envp)[0..env_count]; return callMainWithArgs(usize(c_argc), c_argv, envp); } diff --git a/std/special/build_file_template.zig b/std/special/build_file_template.zig index 1c06c93cdc..1e3eb01136 100644 --- a/std/special/build_file_template.zig +++ b/std/special/build_file_template.zig @@ -1,10 +1,10 @@ const Builder = @import("std").build.Builder; -pub fn build(b: &Builder) void { +pub fn build(b: *Builder) void { const mode = b.standardReleaseOptions(); const exe = b.addExecutable("YOUR_NAME_HERE", "src/main.zig"); exe.setBuildMode(mode); - b.default_step.dependOn(&exe.step); + b.default_step.dependOn(*exe.step); b.installArtifact(exe); } diff --git a/std/special/build_runner.zig b/std/special/build_runner.zig index 3ff11bbee4..3471d6ed21 100644 --- a/std/special/build_runner.zig +++ b/std/special/build_runner.zig @@ -129,7 +129,7 @@ pub fn main() !void { }; } -fn runBuild(builder: &Builder) error!void { +fn runBuild(builder: *Builder) error!void { switch (@typeId(@typeOf(root.build).ReturnType)) { builtin.TypeId.Void => root.build(builder), builtin.TypeId.ErrorUnion => try root.build(builder), @@ -137,7 +137,7 @@ fn runBuild(builder: &Builder) error!void { } } -fn usage(builder: &Builder, already_ran_build: bool, out_stream: var) !void { +fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void { // run the build script to collect the options if (!already_ran_build) { builder.setInstallPrefix(null); @@ -195,7 +195,7 @@ fn usage(builder: &Builder, already_ran_build: bool, out_stream: var) !void { ); } -fn usageAndErr(builder: &Builder, already_ran_build: bool, out_stream: var) error { +fn usageAndErr(builder: *Builder, already_ran_build: bool, out_stream: var) error { usage(builder, already_ran_build, out_stream) catch {}; return error.InvalidArgs; } diff --git a/std/special/builtin.zig b/std/special/builtin.zig index 63149d5161..9c9cd35103 100644 --- a/std/special/builtin.zig +++ b/std/special/builtin.zig @@ -5,7 +5,7 @@ const builtin = @import("builtin"); // Avoid dragging in the runtime safety mechanisms into this .o file, // unless we're trying to test this file. -pub fn panic(msg: []const u8, error_return_trace: ?&builtin.StackTrace) noreturn { +pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { if (builtin.is_test) { @setCold(true); @import("std").debug.panic("{}", msg); @@ -14,7 +14,7 @@ pub fn panic(msg: []const u8, error_return_trace: ?&builtin.StackTrace) noreturn } } -export fn memset(dest: ?&u8, c: u8, n: usize) ?&u8 { +export fn memset(dest: ?*u8, c: u8, n: usize) ?*u8 { @setRuntimeSafety(false); var index: usize = 0; @@ -24,7 +24,7 @@ export fn memset(dest: ?&u8, c: u8, n: usize) ?&u8 { return dest; } -export fn memcpy(noalias dest: ?&u8, noalias src: ?&const u8, n: usize) ?&u8 { +export fn memcpy(noalias dest: ?*u8, noalias src: ?*const u8, n: usize) ?*u8 { @setRuntimeSafety(false); var index: usize = 0; @@ -34,7 +34,7 @@ export fn memcpy(noalias dest: ?&u8, noalias src: ?&const u8, n: usize) ?&u8 { return dest; } -export fn memmove(dest: ?&u8, src: ?&const u8, n: usize) ?&u8 { +export fn memmove(dest: ?*u8, src: ?*const u8, n: usize) ?*u8 { @setRuntimeSafety(false); if (@ptrToInt(dest) < @ptrToInt(src)) { diff --git a/std/special/compiler_rt/index.zig b/std/special/compiler_rt/index.zig index 3e014d4d16..d328324320 100644 --- a/std/special/compiler_rt/index.zig +++ b/std/special/compiler_rt/index.zig @@ -78,7 +78,7 @@ const __udivmoddi4 = @import("udivmoddi4.zig").__udivmoddi4; // Avoid dragging in the runtime safety mechanisms into this .o file, // unless we're trying to test this file. -pub fn panic(msg: []const u8, error_return_trace: ?&builtin.StackTrace) noreturn { +pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { @setCold(true); if (is_test) { std.debug.panic("{}", msg); @@ -284,7 +284,7 @@ nakedcc fn ___chkstk_ms() align(4) void { ); } -extern fn __udivmodsi4(a: u32, b: u32, rem: &u32) u32 { +extern fn __udivmodsi4(a: u32, b: u32, rem: *u32) u32 { @setRuntimeSafety(is_test); const d = __udivsi3(a, b); diff --git a/std/special/compiler_rt/udivmod.zig b/std/special/compiler_rt/udivmod.zig index 0dee5e45f6..894dd02239 100644 --- a/std/special/compiler_rt/udivmod.zig +++ b/std/special/compiler_rt/udivmod.zig @@ -7,15 +7,15 @@ const low = switch (builtin.endian) { }; const high = 1 - low; -pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: ?&DoubleInt) DoubleInt { +pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: ?*DoubleInt) DoubleInt { @setRuntimeSafety(is_test); const SingleInt = @IntType(false, @divExact(DoubleInt.bit_count, 2)); const SignedDoubleInt = @IntType(true, DoubleInt.bit_count); const Log2SingleInt = @import("std").math.Log2Int(SingleInt); - const n = @ptrCast(&const [2]SingleInt, &a).*; // TODO issue #421 - const d = @ptrCast(&const [2]SingleInt, &b).*; // TODO issue #421 + const n = @ptrCast(*const [2]SingleInt, &a).*; // TODO issue #421 + const d = @ptrCast(*const [2]SingleInt, &b).*; // TODO issue #421 var q: [2]SingleInt = undefined; var r: [2]SingleInt = undefined; var sr: c_uint = undefined; @@ -57,7 +57,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: if (maybe_rem) |rem| { r[high] = n[high] % d[high]; r[low] = 0; - rem.* = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 + rem.* = @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 } return n[high] / d[high]; } @@ -69,7 +69,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: if (maybe_rem) |rem| { r[low] = n[low]; r[high] = n[high] & (d[high] - 1); - rem.* = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 + rem.* = @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 } return n[high] >> Log2SingleInt(@ctz(d[high])); } @@ -109,7 +109,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: sr = @ctz(d[low]); q[high] = n[high] >> Log2SingleInt(sr); q[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr)); - return @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0]).*; // TODO issue #421 + return @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &q[0]).*; // TODO issue #421 } // K X // --- @@ -183,13 +183,13 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // r.all -= b; // carry = 1; // } - r_all = @ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 + r_all = @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 const s: SignedDoubleInt = SignedDoubleInt(b -% r_all -% 1) >> (DoubleInt.bit_count - 1); carry = u32(s & 1); r_all -= b & @bitCast(DoubleInt, s); - r = @ptrCast(&[2]SingleInt, &r_all).*; // TODO issue #421 + r = @ptrCast(*[2]SingleInt, &r_all).*; // TODO issue #421 } - const q_all = ((@ptrCast(&align(@alignOf(SingleInt)) DoubleInt, &q[0]).*) << 1) | carry; // TODO issue #421 + const q_all = ((@ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &q[0]).*) << 1) | carry; // TODO issue #421 if (maybe_rem) |rem| { rem.* = r_all; } diff --git a/std/special/compiler_rt/udivmoddi4.zig b/std/special/compiler_rt/udivmoddi4.zig index 6cc54bb6bf..de86c845e5 100644 --- a/std/special/compiler_rt/udivmoddi4.zig +++ b/std/special/compiler_rt/udivmoddi4.zig @@ -1,7 +1,7 @@ const udivmod = @import("udivmod.zig").udivmod; const builtin = @import("builtin"); -pub extern fn __udivmoddi4(a: u64, b: u64, maybe_rem: ?&u64) u64 { +pub extern fn __udivmoddi4(a: u64, b: u64, maybe_rem: ?*u64) u64 { @setRuntimeSafety(builtin.is_test); return udivmod(u64, a, b, maybe_rem); } diff --git a/std/special/compiler_rt/udivmodti4.zig b/std/special/compiler_rt/udivmodti4.zig index 816f82b900..3fa596442f 100644 --- a/std/special/compiler_rt/udivmodti4.zig +++ b/std/special/compiler_rt/udivmodti4.zig @@ -2,12 +2,12 @@ const udivmod = @import("udivmod.zig").udivmod; const builtin = @import("builtin"); const compiler_rt = @import("index.zig"); -pub extern fn __udivmodti4(a: u128, b: u128, maybe_rem: ?&u128) u128 { +pub extern fn __udivmodti4(a: u128, b: u128, maybe_rem: ?*u128) u128 { @setRuntimeSafety(builtin.is_test); return udivmod(u128, a, b, maybe_rem); } -pub extern fn __udivmodti4_windows_x86_64(a: &const u128, b: &const u128, maybe_rem: ?&u128) void { +pub extern fn __udivmodti4_windows_x86_64(a: *const u128, b: *const u128, maybe_rem: ?*u128) void { @setRuntimeSafety(builtin.is_test); compiler_rt.setXmm0(u128, udivmod(u128, a.*, b.*, maybe_rem)); } diff --git a/std/special/compiler_rt/udivti3.zig b/std/special/compiler_rt/udivti3.zig index ad0f09e733..510e21ac1d 100644 --- a/std/special/compiler_rt/udivti3.zig +++ b/std/special/compiler_rt/udivti3.zig @@ -6,7 +6,7 @@ pub extern fn __udivti3(a: u128, b: u128) u128 { return udivmodti4.__udivmodti4(a, b, null); } -pub extern fn __udivti3_windows_x86_64(a: &const u128, b: &const u128) void { +pub extern fn __udivti3_windows_x86_64(a: *const u128, b: *const u128) void { @setRuntimeSafety(builtin.is_test); udivmodti4.__udivmodti4_windows_x86_64(a, b, null); } diff --git a/std/special/compiler_rt/umodti3.zig b/std/special/compiler_rt/umodti3.zig index 11e2955bb3..9551e63a6f 100644 --- a/std/special/compiler_rt/umodti3.zig +++ b/std/special/compiler_rt/umodti3.zig @@ -9,7 +9,7 @@ pub extern fn __umodti3(a: u128, b: u128) u128 { return r; } -pub extern fn __umodti3_windows_x86_64(a: &const u128, b: &const u128) void { +pub extern fn __umodti3_windows_x86_64(a: *const u128, b: *const u128) void { @setRuntimeSafety(builtin.is_test); compiler_rt.setXmm0(u128, __umodti3(a.*, b.*)); } diff --git a/std/special/panic.zig b/std/special/panic.zig index 8f933ddd97..ca1caea73c 100644 --- a/std/special/panic.zig +++ b/std/special/panic.zig @@ -6,7 +6,7 @@ const builtin = @import("builtin"); const std = @import("std"); -pub fn panic(msg: []const u8, error_return_trace: ?&builtin.StackTrace) noreturn { +pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { @setCold(true); switch (builtin.os) { // TODO: fix panic in zen. diff --git a/std/unicode.zig b/std/unicode.zig index 36f04778f4..3d1bebdb55 100644 --- a/std/unicode.zig +++ b/std/unicode.zig @@ -196,7 +196,7 @@ pub const Utf8View = struct { } } - pub fn iterator(s: &const Utf8View) Utf8Iterator { + pub fn iterator(s: *const Utf8View) Utf8Iterator { return Utf8Iterator{ .bytes = s.bytes, .i = 0, @@ -208,7 +208,7 @@ const Utf8Iterator = struct { bytes: []const u8, i: usize, - pub fn nextCodepointSlice(it: &Utf8Iterator) ?[]const u8 { + pub fn nextCodepointSlice(it: *Utf8Iterator) ?[]const u8 { if (it.i >= it.bytes.len) { return null; } @@ -219,7 +219,7 @@ const Utf8Iterator = struct { return it.bytes[it.i - cp_len .. it.i]; } - pub fn nextCodepoint(it: &Utf8Iterator) ?u32 { + pub fn nextCodepoint(it: *Utf8Iterator) ?u32 { const slice = it.nextCodepointSlice() ?? return null; switch (slice.len) { diff --git a/std/zig/ast.zig b/std/zig/ast.zig index 56d4f9c393..4d25ceb7db 100644 --- a/std/zig/ast.zig +++ b/std/zig/ast.zig @@ -9,26 +9,26 @@ pub const TokenIndex = usize; pub const Tree = struct { source: []const u8, tokens: TokenList, - root_node: &Node.Root, + root_node: *Node.Root, arena_allocator: std.heap.ArenaAllocator, errors: ErrorList, pub const TokenList = SegmentedList(Token, 64); pub const ErrorList = SegmentedList(Error, 0); - pub fn deinit(self: &Tree) void { + pub fn deinit(self: *Tree) void { self.arena_allocator.deinit(); } - pub fn renderError(self: &Tree, parse_error: &Error, stream: var) !void { + pub fn renderError(self: *Tree, parse_error: *Error, stream: var) !void { return parse_error.render(&self.tokens, stream); } - pub fn tokenSlice(self: &Tree, token_index: TokenIndex) []const u8 { + pub fn tokenSlice(self: *Tree, token_index: TokenIndex) []const u8 { return self.tokenSlicePtr(self.tokens.at(token_index)); } - pub fn tokenSlicePtr(self: &Tree, token: &const Token) []const u8 { + pub fn tokenSlicePtr(self: *Tree, token: *const Token) []const u8 { return self.source[token.start..token.end]; } @@ -39,7 +39,7 @@ pub const Tree = struct { line_end: usize, }; - pub fn tokenLocationPtr(self: &Tree, start_index: usize, token: &const Token) Location { + pub fn tokenLocationPtr(self: *Tree, start_index: usize, token: *const Token) Location { var loc = Location{ .line = 0, .column = 0, @@ -64,24 +64,24 @@ pub const Tree = struct { return loc; } - pub fn tokenLocation(self: &Tree, start_index: usize, token_index: TokenIndex) Location { + pub fn tokenLocation(self: *Tree, start_index: usize, token_index: TokenIndex) Location { return self.tokenLocationPtr(start_index, self.tokens.at(token_index)); } - pub fn tokensOnSameLine(self: &Tree, token1_index: TokenIndex, token2_index: TokenIndex) bool { + pub fn tokensOnSameLine(self: *Tree, token1_index: TokenIndex, token2_index: TokenIndex) bool { return self.tokensOnSameLinePtr(self.tokens.at(token1_index), self.tokens.at(token2_index)); } - pub fn tokensOnSameLinePtr(self: &Tree, token1: &const Token, token2: &const Token) bool { + pub fn tokensOnSameLinePtr(self: *Tree, token1: *const Token, token2: *const Token) bool { return mem.indexOfScalar(u8, self.source[token1.end..token2.start], '\n') == null; } - pub fn dump(self: &Tree) void { + pub fn dump(self: *Tree) void { self.root_node.base.dump(0); } /// Skips over comments - pub fn prevToken(self: &Tree, token_index: TokenIndex) TokenIndex { + pub fn prevToken(self: *Tree, token_index: TokenIndex) TokenIndex { var index = token_index - 1; while (self.tokens.at(index).id == Token.Id.LineComment) { index -= 1; @@ -90,7 +90,7 @@ pub const Tree = struct { } /// Skips over comments - pub fn nextToken(self: &Tree, token_index: TokenIndex) TokenIndex { + pub fn nextToken(self: *Tree, token_index: TokenIndex) TokenIndex { var index = token_index + 1; while (self.tokens.at(index).id == Token.Id.LineComment) { index += 1; @@ -120,7 +120,7 @@ pub const Error = union(enum) { ExpectedToken: ExpectedToken, ExpectedCommaOrEnd: ExpectedCommaOrEnd, - pub fn render(self: &const Error, tokens: &Tree.TokenList, stream: var) !void { + pub fn render(self: *const Error, tokens: *Tree.TokenList, stream: var) !void { switch (self.*) { // TODO https://github.com/ziglang/zig/issues/683 @TagType(Error).InvalidToken => |*x| return x.render(tokens, stream), @@ -145,7 +145,7 @@ pub const Error = union(enum) { } } - pub fn loc(self: &const Error) TokenIndex { + pub fn loc(self: *const Error) TokenIndex { switch (self.*) { // TODO https://github.com/ziglang/zig/issues/683 @TagType(Error).InvalidToken => |x| return x.token, @@ -188,17 +188,17 @@ pub const Error = union(enum) { pub const ExtraVolatileQualifier = SimpleError("Extra volatile qualifier"); pub const ExpectedCall = struct { - node: &Node, + node: *Node, - pub fn render(self: &const ExpectedCall, tokens: &Tree.TokenList, stream: var) !void { + pub fn render(self: *const ExpectedCall, tokens: *Tree.TokenList, stream: var) !void { return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ ", found {}", @tagName(self.node.id)); } }; pub const ExpectedCallOrFnProto = struct { - node: &Node, + node: *Node, - pub fn render(self: &const ExpectedCallOrFnProto, tokens: &Tree.TokenList, stream: var) !void { + pub fn render(self: *const ExpectedCallOrFnProto, tokens: *Tree.TokenList, stream: var) !void { return stream.print("expected " ++ @tagName(@TagType(Node.SuffixOp.Op).Call) ++ " or " ++ @tagName(Node.Id.FnProto) ++ ", found {}", @tagName(self.node.id)); } }; @@ -207,7 +207,7 @@ pub const Error = union(enum) { token: TokenIndex, expected_id: @TagType(Token.Id), - pub fn render(self: &const ExpectedToken, tokens: &Tree.TokenList, stream: var) !void { + pub fn render(self: *const ExpectedToken, tokens: *Tree.TokenList, stream: var) !void { const token_name = @tagName(tokens.at(self.token).id); return stream.print("expected {}, found {}", @tagName(self.expected_id), token_name); } @@ -217,7 +217,7 @@ pub const Error = union(enum) { token: TokenIndex, end_id: @TagType(Token.Id), - pub fn render(self: &const ExpectedCommaOrEnd, tokens: &Tree.TokenList, stream: var) !void { + pub fn render(self: *const ExpectedCommaOrEnd, tokens: *Tree.TokenList, stream: var) !void { const token_name = @tagName(tokens.at(self.token).id); return stream.print("expected ',' or {}, found {}", @tagName(self.end_id), token_name); } @@ -229,7 +229,7 @@ pub const Error = union(enum) { token: TokenIndex, - pub fn render(self: &const ThisError, tokens: &Tree.TokenList, stream: var) !void { + pub fn render(self: *const ThisError, tokens: *Tree.TokenList, stream: var) !void { const token_name = @tagName(tokens.at(self.token).id); return stream.print(msg, token_name); } @@ -242,7 +242,7 @@ pub const Error = union(enum) { token: TokenIndex, - pub fn render(self: &const ThisError, tokens: &Tree.TokenList, stream: var) !void { + pub fn render(self: *const ThisError, tokens: *Tree.TokenList, stream: var) !void { return stream.write(msg); } }; @@ -320,14 +320,14 @@ pub const Node = struct { FieldInitializer, }; - pub fn cast(base: &Node, comptime T: type) ?&T { + pub fn cast(base: *Node, comptime T: type) ?*T { if (base.id == comptime typeToId(T)) { return @fieldParentPtr(T, "base", base); } return null; } - pub fn iterate(base: &Node, index: usize) ?&Node { + pub fn iterate(base: *Node, index: usize) ?*Node { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (base.id == @field(Id, @memberName(Id, i))) { @@ -338,7 +338,7 @@ pub const Node = struct { unreachable; } - pub fn firstToken(base: &Node) TokenIndex { + pub fn firstToken(base: *Node) TokenIndex { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (base.id == @field(Id, @memberName(Id, i))) { @@ -349,7 +349,7 @@ pub const Node = struct { unreachable; } - pub fn lastToken(base: &Node) TokenIndex { + pub fn lastToken(base: *Node) TokenIndex { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (base.id == @field(Id, @memberName(Id, i))) { @@ -370,7 +370,7 @@ pub const Node = struct { unreachable; } - pub fn requireSemiColon(base: &const Node) bool { + pub fn requireSemiColon(base: *const Node) bool { var n = base; while (true) { switch (n.id) { @@ -443,7 +443,7 @@ pub const Node = struct { } } - pub fn dump(self: &Node, indent: usize) void { + pub fn dump(self: *Node, indent: usize) void { { var i: usize = 0; while (i < indent) : (i += 1) { @@ -460,44 +460,44 @@ pub const Node = struct { pub const Root = struct { base: Node, - doc_comments: ?&DocComment, + doc_comments: ?*DocComment, decls: DeclList, eof_token: TokenIndex, - pub const DeclList = SegmentedList(&Node, 4); + pub const DeclList = SegmentedList(*Node, 4); - pub fn iterate(self: &Root, index: usize) ?&Node { + pub fn iterate(self: *Root, index: usize) ?*Node { if (index < self.decls.len) { return self.decls.at(index).*; } return null; } - pub fn firstToken(self: &Root) TokenIndex { + pub fn firstToken(self: *Root) TokenIndex { return if (self.decls.len == 0) self.eof_token else (self.decls.at(0).*).firstToken(); } - pub fn lastToken(self: &Root) TokenIndex { + pub fn lastToken(self: *Root) TokenIndex { return if (self.decls.len == 0) self.eof_token else (self.decls.at(self.decls.len - 1).*).lastToken(); } }; pub const VarDecl = struct { base: Node, - doc_comments: ?&DocComment, + doc_comments: ?*DocComment, visib_token: ?TokenIndex, name_token: TokenIndex, eq_token: TokenIndex, mut_token: TokenIndex, comptime_token: ?TokenIndex, extern_export_token: ?TokenIndex, - lib_name: ?&Node, - type_node: ?&Node, - align_node: ?&Node, - init_node: ?&Node, + lib_name: ?*Node, + type_node: ?*Node, + align_node: ?*Node, + init_node: ?*Node, semicolon_token: TokenIndex, - pub fn iterate(self: &VarDecl, index: usize) ?&Node { + pub fn iterate(self: *VarDecl, index: usize) ?*Node { var i = index; if (self.type_node) |type_node| { @@ -518,7 +518,7 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &VarDecl) TokenIndex { + pub fn firstToken(self: *VarDecl) TokenIndex { if (self.visib_token) |visib_token| return visib_token; if (self.comptime_token) |comptime_token| return comptime_token; if (self.extern_export_token) |extern_export_token| return extern_export_token; @@ -526,20 +526,20 @@ pub const Node = struct { return self.mut_token; } - pub fn lastToken(self: &VarDecl) TokenIndex { + pub fn lastToken(self: *VarDecl) TokenIndex { return self.semicolon_token; } }; pub const Use = struct { base: Node, - doc_comments: ?&DocComment, + doc_comments: ?*DocComment, visib_token: ?TokenIndex, use_token: TokenIndex, - expr: &Node, + expr: *Node, semicolon_token: TokenIndex, - pub fn iterate(self: &Use, index: usize) ?&Node { + pub fn iterate(self: *Use, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; @@ -548,12 +548,12 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &Use) TokenIndex { + pub fn firstToken(self: *Use) TokenIndex { if (self.visib_token) |visib_token| return visib_token; return self.use_token; } - pub fn lastToken(self: &Use) TokenIndex { + pub fn lastToken(self: *Use) TokenIndex { return self.semicolon_token; } }; @@ -564,9 +564,9 @@ pub const Node = struct { decls: DeclList, rbrace_token: TokenIndex, - pub const DeclList = SegmentedList(&Node, 2); + pub const DeclList = SegmentedList(*Node, 2); - pub fn iterate(self: &ErrorSetDecl, index: usize) ?&Node { + pub fn iterate(self: *ErrorSetDecl, index: usize) ?*Node { var i = index; if (i < self.decls.len) return self.decls.at(i).*; @@ -575,11 +575,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &ErrorSetDecl) TokenIndex { + pub fn firstToken(self: *ErrorSetDecl) TokenIndex { return self.error_token; } - pub fn lastToken(self: &ErrorSetDecl) TokenIndex { + pub fn lastToken(self: *ErrorSetDecl) TokenIndex { return self.rbrace_token; } }; @@ -597,11 +597,11 @@ pub const Node = struct { const InitArg = union(enum) { None, - Enum: ?&Node, - Type: &Node, + Enum: ?*Node, + Type: *Node, }; - pub fn iterate(self: &ContainerDecl, index: usize) ?&Node { + pub fn iterate(self: *ContainerDecl, index: usize) ?*Node { var i = index; switch (self.init_arg_expr) { @@ -618,26 +618,26 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &ContainerDecl) TokenIndex { + pub fn firstToken(self: *ContainerDecl) TokenIndex { if (self.layout_token) |layout_token| { return layout_token; } return self.kind_token; } - pub fn lastToken(self: &ContainerDecl) TokenIndex { + pub fn lastToken(self: *ContainerDecl) TokenIndex { return self.rbrace_token; } }; pub const StructField = struct { base: Node, - doc_comments: ?&DocComment, + doc_comments: ?*DocComment, visib_token: ?TokenIndex, name_token: TokenIndex, - type_expr: &Node, + type_expr: *Node, - pub fn iterate(self: &StructField, index: usize) ?&Node { + pub fn iterate(self: *StructField, index: usize) ?*Node { var i = index; if (i < 1) return self.type_expr; @@ -646,24 +646,24 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &StructField) TokenIndex { + pub fn firstToken(self: *StructField) TokenIndex { if (self.visib_token) |visib_token| return visib_token; return self.name_token; } - pub fn lastToken(self: &StructField) TokenIndex { + pub fn lastToken(self: *StructField) TokenIndex { return self.type_expr.lastToken(); } }; pub const UnionTag = struct { base: Node, - doc_comments: ?&DocComment, + doc_comments: ?*DocComment, name_token: TokenIndex, - type_expr: ?&Node, - value_expr: ?&Node, + type_expr: ?*Node, + value_expr: ?*Node, - pub fn iterate(self: &UnionTag, index: usize) ?&Node { + pub fn iterate(self: *UnionTag, index: usize) ?*Node { var i = index; if (self.type_expr) |type_expr| { @@ -679,11 +679,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &UnionTag) TokenIndex { + pub fn firstToken(self: *UnionTag) TokenIndex { return self.name_token; } - pub fn lastToken(self: &UnionTag) TokenIndex { + pub fn lastToken(self: *UnionTag) TokenIndex { if (self.value_expr) |value_expr| { return value_expr.lastToken(); } @@ -697,11 +697,11 @@ pub const Node = struct { pub const EnumTag = struct { base: Node, - doc_comments: ?&DocComment, + doc_comments: ?*DocComment, name_token: TokenIndex, - value: ?&Node, + value: ?*Node, - pub fn iterate(self: &EnumTag, index: usize) ?&Node { + pub fn iterate(self: *EnumTag, index: usize) ?*Node { var i = index; if (self.value) |value| { @@ -712,11 +712,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &EnumTag) TokenIndex { + pub fn firstToken(self: *EnumTag) TokenIndex { return self.name_token; } - pub fn lastToken(self: &EnumTag) TokenIndex { + pub fn lastToken(self: *EnumTag) TokenIndex { if (self.value) |value| { return value.lastToken(); } @@ -727,25 +727,25 @@ pub const Node = struct { pub const ErrorTag = struct { base: Node, - doc_comments: ?&DocComment, + doc_comments: ?*DocComment, name_token: TokenIndex, - pub fn iterate(self: &ErrorTag, index: usize) ?&Node { + pub fn iterate(self: *ErrorTag, index: usize) ?*Node { var i = index; if (self.doc_comments) |comments| { - if (i < 1) return &comments.base; + if (i < 1) return *comments.base; i -= 1; } return null; } - pub fn firstToken(self: &ErrorTag) TokenIndex { + pub fn firstToken(self: *ErrorTag) TokenIndex { return self.name_token; } - pub fn lastToken(self: &ErrorTag) TokenIndex { + pub fn lastToken(self: *ErrorTag) TokenIndex { return self.name_token; } }; @@ -754,15 +754,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &Identifier, index: usize) ?&Node { + pub fn iterate(self: *Identifier, index: usize) ?*Node { return null; } - pub fn firstToken(self: &Identifier) TokenIndex { + pub fn firstToken(self: *Identifier) TokenIndex { return self.token; } - pub fn lastToken(self: &Identifier) TokenIndex { + pub fn lastToken(self: *Identifier) TokenIndex { return self.token; } }; @@ -770,10 +770,10 @@ pub const Node = struct { pub const AsyncAttribute = struct { base: Node, async_token: TokenIndex, - allocator_type: ?&Node, + allocator_type: ?*Node, rangle_bracket: ?TokenIndex, - pub fn iterate(self: &AsyncAttribute, index: usize) ?&Node { + pub fn iterate(self: *AsyncAttribute, index: usize) ?*Node { var i = index; if (self.allocator_type) |allocator_type| { @@ -784,11 +784,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &AsyncAttribute) TokenIndex { + pub fn firstToken(self: *AsyncAttribute) TokenIndex { return self.async_token; } - pub fn lastToken(self: &AsyncAttribute) TokenIndex { + pub fn lastToken(self: *AsyncAttribute) TokenIndex { if (self.rangle_bracket) |rangle_bracket| { return rangle_bracket; } @@ -799,7 +799,7 @@ pub const Node = struct { pub const FnProto = struct { base: Node, - doc_comments: ?&DocComment, + doc_comments: ?*DocComment, visib_token: ?TokenIndex, fn_token: TokenIndex, name_token: ?TokenIndex, @@ -808,19 +808,19 @@ pub const Node = struct { var_args_token: ?TokenIndex, extern_export_inline_token: ?TokenIndex, cc_token: ?TokenIndex, - async_attr: ?&AsyncAttribute, - body_node: ?&Node, - lib_name: ?&Node, // populated if this is an extern declaration - align_expr: ?&Node, // populated if align(A) is present + async_attr: ?*AsyncAttribute, + body_node: ?*Node, + lib_name: ?*Node, // populated if this is an extern declaration + align_expr: ?*Node, // populated if align(A) is present - pub const ParamList = SegmentedList(&Node, 2); + pub const ParamList = SegmentedList(*Node, 2); pub const ReturnType = union(enum) { - Explicit: &Node, - InferErrorSet: &Node, + Explicit: *Node, + InferErrorSet: *Node, }; - pub fn iterate(self: &FnProto, index: usize) ?&Node { + pub fn iterate(self: *FnProto, index: usize) ?*Node { var i = index; if (self.lib_name) |lib_name| { @@ -856,7 +856,7 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &FnProto) TokenIndex { + pub fn firstToken(self: *FnProto) TokenIndex { if (self.visib_token) |visib_token| return visib_token; if (self.extern_export_inline_token) |extern_export_inline_token| return extern_export_inline_token; assert(self.lib_name == null); @@ -864,7 +864,7 @@ pub const Node = struct { return self.fn_token; } - pub fn lastToken(self: &FnProto) TokenIndex { + pub fn lastToken(self: *FnProto) TokenIndex { if (self.body_node) |body_node| return body_node.lastToken(); switch (self.return_type) { // TODO allow this and next prong to share bodies since the types are the same @@ -881,10 +881,10 @@ pub const Node = struct { pub const Result = struct { arrow_token: TokenIndex, - return_type: &Node, + return_type: *Node, }; - pub fn iterate(self: &PromiseType, index: usize) ?&Node { + pub fn iterate(self: *PromiseType, index: usize) ?*Node { var i = index; if (self.result) |result| { @@ -895,11 +895,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &PromiseType) TokenIndex { + pub fn firstToken(self: *PromiseType) TokenIndex { return self.promise_token; } - pub fn lastToken(self: &PromiseType) TokenIndex { + pub fn lastToken(self: *PromiseType) TokenIndex { if (self.result) |result| return result.return_type.lastToken(); return self.promise_token; } @@ -910,10 +910,10 @@ pub const Node = struct { comptime_token: ?TokenIndex, noalias_token: ?TokenIndex, name_token: ?TokenIndex, - type_node: &Node, + type_node: *Node, var_args_token: ?TokenIndex, - pub fn iterate(self: &ParamDecl, index: usize) ?&Node { + pub fn iterate(self: *ParamDecl, index: usize) ?*Node { var i = index; if (i < 1) return self.type_node; @@ -922,14 +922,14 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &ParamDecl) TokenIndex { + pub fn firstToken(self: *ParamDecl) TokenIndex { if (self.comptime_token) |comptime_token| return comptime_token; if (self.noalias_token) |noalias_token| return noalias_token; if (self.name_token) |name_token| return name_token; return self.type_node.firstToken(); } - pub fn lastToken(self: &ParamDecl) TokenIndex { + pub fn lastToken(self: *ParamDecl) TokenIndex { if (self.var_args_token) |var_args_token| return var_args_token; return self.type_node.lastToken(); } @@ -944,7 +944,7 @@ pub const Node = struct { pub const StatementList = Root.DeclList; - pub fn iterate(self: &Block, index: usize) ?&Node { + pub fn iterate(self: *Block, index: usize) ?*Node { var i = index; if (i < self.statements.len) return self.statements.at(i).*; @@ -953,7 +953,7 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &Block) TokenIndex { + pub fn firstToken(self: *Block) TokenIndex { if (self.label) |label| { return label; } @@ -961,7 +961,7 @@ pub const Node = struct { return self.lbrace; } - pub fn lastToken(self: &Block) TokenIndex { + pub fn lastToken(self: *Block) TokenIndex { return self.rbrace; } }; @@ -970,14 +970,14 @@ pub const Node = struct { base: Node, defer_token: TokenIndex, kind: Kind, - expr: &Node, + expr: *Node, const Kind = enum { Error, Unconditional, }; - pub fn iterate(self: &Defer, index: usize) ?&Node { + pub fn iterate(self: *Defer, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; @@ -986,22 +986,22 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &Defer) TokenIndex { + pub fn firstToken(self: *Defer) TokenIndex { return self.defer_token; } - pub fn lastToken(self: &Defer) TokenIndex { + pub fn lastToken(self: *Defer) TokenIndex { return self.expr.lastToken(); } }; pub const Comptime = struct { base: Node, - doc_comments: ?&DocComment, + doc_comments: ?*DocComment, comptime_token: TokenIndex, - expr: &Node, + expr: *Node, - pub fn iterate(self: &Comptime, index: usize) ?&Node { + pub fn iterate(self: *Comptime, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; @@ -1010,11 +1010,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &Comptime) TokenIndex { + pub fn firstToken(self: *Comptime) TokenIndex { return self.comptime_token; } - pub fn lastToken(self: &Comptime) TokenIndex { + pub fn lastToken(self: *Comptime) TokenIndex { return self.expr.lastToken(); } }; @@ -1022,10 +1022,10 @@ pub const Node = struct { pub const Payload = struct { base: Node, lpipe: TokenIndex, - error_symbol: &Node, + error_symbol: *Node, rpipe: TokenIndex, - pub fn iterate(self: &Payload, index: usize) ?&Node { + pub fn iterate(self: *Payload, index: usize) ?*Node { var i = index; if (i < 1) return self.error_symbol; @@ -1034,11 +1034,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &Payload) TokenIndex { + pub fn firstToken(self: *Payload) TokenIndex { return self.lpipe; } - pub fn lastToken(self: &Payload) TokenIndex { + pub fn lastToken(self: *Payload) TokenIndex { return self.rpipe; } }; @@ -1047,10 +1047,10 @@ pub const Node = struct { base: Node, lpipe: TokenIndex, ptr_token: ?TokenIndex, - value_symbol: &Node, + value_symbol: *Node, rpipe: TokenIndex, - pub fn iterate(self: &PointerPayload, index: usize) ?&Node { + pub fn iterate(self: *PointerPayload, index: usize) ?*Node { var i = index; if (i < 1) return self.value_symbol; @@ -1059,11 +1059,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &PointerPayload) TokenIndex { + pub fn firstToken(self: *PointerPayload) TokenIndex { return self.lpipe; } - pub fn lastToken(self: &PointerPayload) TokenIndex { + pub fn lastToken(self: *PointerPayload) TokenIndex { return self.rpipe; } }; @@ -1072,11 +1072,11 @@ pub const Node = struct { base: Node, lpipe: TokenIndex, ptr_token: ?TokenIndex, - value_symbol: &Node, - index_symbol: ?&Node, + value_symbol: *Node, + index_symbol: ?*Node, rpipe: TokenIndex, - pub fn iterate(self: &PointerIndexPayload, index: usize) ?&Node { + pub fn iterate(self: *PointerIndexPayload, index: usize) ?*Node { var i = index; if (i < 1) return self.value_symbol; @@ -1090,11 +1090,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &PointerIndexPayload) TokenIndex { + pub fn firstToken(self: *PointerIndexPayload) TokenIndex { return self.lpipe; } - pub fn lastToken(self: &PointerIndexPayload) TokenIndex { + pub fn lastToken(self: *PointerIndexPayload) TokenIndex { return self.rpipe; } }; @@ -1102,10 +1102,10 @@ pub const Node = struct { pub const Else = struct { base: Node, else_token: TokenIndex, - payload: ?&Node, - body: &Node, + payload: ?*Node, + body: *Node, - pub fn iterate(self: &Else, index: usize) ?&Node { + pub fn iterate(self: *Else, index: usize) ?*Node { var i = index; if (self.payload) |payload| { @@ -1119,11 +1119,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &Else) TokenIndex { + pub fn firstToken(self: *Else) TokenIndex { return self.else_token; } - pub fn lastToken(self: &Else) TokenIndex { + pub fn lastToken(self: *Else) TokenIndex { return self.body.lastToken(); } }; @@ -1131,15 +1131,15 @@ pub const Node = struct { pub const Switch = struct { base: Node, switch_token: TokenIndex, - expr: &Node, + expr: *Node, /// these must be SwitchCase nodes cases: CaseList, rbrace: TokenIndex, - pub const CaseList = SegmentedList(&Node, 2); + pub const CaseList = SegmentedList(*Node, 2); - pub fn iterate(self: &Switch, index: usize) ?&Node { + pub fn iterate(self: *Switch, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; @@ -1151,11 +1151,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &Switch) TokenIndex { + pub fn firstToken(self: *Switch) TokenIndex { return self.switch_token; } - pub fn lastToken(self: &Switch) TokenIndex { + pub fn lastToken(self: *Switch) TokenIndex { return self.rbrace; } }; @@ -1164,12 +1164,12 @@ pub const Node = struct { base: Node, items: ItemList, arrow_token: TokenIndex, - payload: ?&Node, - expr: &Node, + payload: ?*Node, + expr: *Node, - pub const ItemList = SegmentedList(&Node, 1); + pub const ItemList = SegmentedList(*Node, 1); - pub fn iterate(self: &SwitchCase, index: usize) ?&Node { + pub fn iterate(self: *SwitchCase, index: usize) ?*Node { var i = index; if (i < self.items.len) return self.items.at(i).*; @@ -1186,11 +1186,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &SwitchCase) TokenIndex { + pub fn firstToken(self: *SwitchCase) TokenIndex { return (self.items.at(0).*).firstToken(); } - pub fn lastToken(self: &SwitchCase) TokenIndex { + pub fn lastToken(self: *SwitchCase) TokenIndex { return self.expr.lastToken(); } }; @@ -1199,15 +1199,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &SwitchElse, index: usize) ?&Node { + pub fn iterate(self: *SwitchElse, index: usize) ?*Node { return null; } - pub fn firstToken(self: &SwitchElse) TokenIndex { + pub fn firstToken(self: *SwitchElse) TokenIndex { return self.token; } - pub fn lastToken(self: &SwitchElse) TokenIndex { + pub fn lastToken(self: *SwitchElse) TokenIndex { return self.token; } }; @@ -1217,13 +1217,13 @@ pub const Node = struct { label: ?TokenIndex, inline_token: ?TokenIndex, while_token: TokenIndex, - condition: &Node, - payload: ?&Node, - continue_expr: ?&Node, - body: &Node, - @"else": ?&Else, + condition: *Node, + payload: ?*Node, + continue_expr: ?*Node, + body: *Node, + @"else": ?*Else, - pub fn iterate(self: &While, index: usize) ?&Node { + pub fn iterate(self: *While, index: usize) ?*Node { var i = index; if (i < 1) return self.condition; @@ -1243,14 +1243,14 @@ pub const Node = struct { i -= 1; if (self.@"else") |@"else"| { - if (i < 1) return &@"else".base; + if (i < 1) return *@"else".base; i -= 1; } return null; } - pub fn firstToken(self: &While) TokenIndex { + pub fn firstToken(self: *While) TokenIndex { if (self.label) |label| { return label; } @@ -1262,7 +1262,7 @@ pub const Node = struct { return self.while_token; } - pub fn lastToken(self: &While) TokenIndex { + pub fn lastToken(self: *While) TokenIndex { if (self.@"else") |@"else"| { return @"else".body.lastToken(); } @@ -1276,12 +1276,12 @@ pub const Node = struct { label: ?TokenIndex, inline_token: ?TokenIndex, for_token: TokenIndex, - array_expr: &Node, - payload: ?&Node, - body: &Node, - @"else": ?&Else, + array_expr: *Node, + payload: ?*Node, + body: *Node, + @"else": ?*Else, - pub fn iterate(self: &For, index: usize) ?&Node { + pub fn iterate(self: *For, index: usize) ?*Node { var i = index; if (i < 1) return self.array_expr; @@ -1296,14 +1296,14 @@ pub const Node = struct { i -= 1; if (self.@"else") |@"else"| { - if (i < 1) return &@"else".base; + if (i < 1) return *@"else".base; i -= 1; } return null; } - pub fn firstToken(self: &For) TokenIndex { + pub fn firstToken(self: *For) TokenIndex { if (self.label) |label| { return label; } @@ -1315,7 +1315,7 @@ pub const Node = struct { return self.for_token; } - pub fn lastToken(self: &For) TokenIndex { + pub fn lastToken(self: *For) TokenIndex { if (self.@"else") |@"else"| { return @"else".body.lastToken(); } @@ -1327,12 +1327,12 @@ pub const Node = struct { pub const If = struct { base: Node, if_token: TokenIndex, - condition: &Node, - payload: ?&Node, - body: &Node, - @"else": ?&Else, + condition: *Node, + payload: ?*Node, + body: *Node, + @"else": ?*Else, - pub fn iterate(self: &If, index: usize) ?&Node { + pub fn iterate(self: *If, index: usize) ?*Node { var i = index; if (i < 1) return self.condition; @@ -1347,18 +1347,18 @@ pub const Node = struct { i -= 1; if (self.@"else") |@"else"| { - if (i < 1) return &@"else".base; + if (i < 1) return *@"else".base; i -= 1; } return null; } - pub fn firstToken(self: &If) TokenIndex { + pub fn firstToken(self: *If) TokenIndex { return self.if_token; } - pub fn lastToken(self: &If) TokenIndex { + pub fn lastToken(self: *If) TokenIndex { if (self.@"else") |@"else"| { return @"else".body.lastToken(); } @@ -1370,9 +1370,9 @@ pub const Node = struct { pub const InfixOp = struct { base: Node, op_token: TokenIndex, - lhs: &Node, + lhs: *Node, op: Op, - rhs: &Node, + rhs: *Node, pub const Op = union(enum) { Add, @@ -1401,7 +1401,7 @@ pub const Node = struct { BitXor, BoolAnd, BoolOr, - Catch: ?&Node, + Catch: ?*Node, Div, EqualEqual, ErrorUnion, @@ -1420,7 +1420,7 @@ pub const Node = struct { UnwrapMaybe, }; - pub fn iterate(self: &InfixOp, index: usize) ?&Node { + pub fn iterate(self: *InfixOp, index: usize) ?*Node { var i = index; if (i < 1) return self.lhs; @@ -1485,11 +1485,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &InfixOp) TokenIndex { + pub fn firstToken(self: *InfixOp) TokenIndex { return self.lhs.firstToken(); } - pub fn lastToken(self: &InfixOp) TokenIndex { + pub fn lastToken(self: *InfixOp) TokenIndex { return self.rhs.lastToken(); } }; @@ -1498,11 +1498,11 @@ pub const Node = struct { base: Node, op_token: TokenIndex, op: Op, - rhs: &Node, + rhs: *Node, pub const Op = union(enum) { AddrOf: AddrOfInfo, - ArrayType: &Node, + ArrayType: *Node, Await, BitNot, BoolNot, @@ -1523,17 +1523,17 @@ pub const Node = struct { volatile_token: ?TokenIndex, pub const Align = struct { - node: &Node, + node: *Node, bit_range: ?BitRange, pub const BitRange = struct { - start: &Node, - end: &Node, + start: *Node, + end: *Node, }; }; }; - pub fn iterate(self: &PrefixOp, index: usize) ?&Node { + pub fn iterate(self: *PrefixOp, index: usize) ?*Node { var i = index; switch (self.op) { @@ -1573,11 +1573,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &PrefixOp) TokenIndex { + pub fn firstToken(self: *PrefixOp) TokenIndex { return self.op_token; } - pub fn lastToken(self: &PrefixOp) TokenIndex { + pub fn lastToken(self: *PrefixOp) TokenIndex { return self.rhs.lastToken(); } }; @@ -1586,9 +1586,9 @@ pub const Node = struct { base: Node, period_token: TokenIndex, name_token: TokenIndex, - expr: &Node, + expr: *Node, - pub fn iterate(self: &FieldInitializer, index: usize) ?&Node { + pub fn iterate(self: *FieldInitializer, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; @@ -1597,45 +1597,45 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &FieldInitializer) TokenIndex { + pub fn firstToken(self: *FieldInitializer) TokenIndex { return self.period_token; } - pub fn lastToken(self: &FieldInitializer) TokenIndex { + pub fn lastToken(self: *FieldInitializer) TokenIndex { return self.expr.lastToken(); } }; pub const SuffixOp = struct { base: Node, - lhs: &Node, + lhs: *Node, op: Op, rtoken: TokenIndex, pub const Op = union(enum) { Call: Call, - ArrayAccess: &Node, + ArrayAccess: *Node, Slice: Slice, ArrayInitializer: InitList, StructInitializer: InitList, Deref, - pub const InitList = SegmentedList(&Node, 2); + pub const InitList = SegmentedList(*Node, 2); pub const Call = struct { params: ParamList, - async_attr: ?&AsyncAttribute, + async_attr: ?*AsyncAttribute, - pub const ParamList = SegmentedList(&Node, 2); + pub const ParamList = SegmentedList(*Node, 2); }; pub const Slice = struct { - start: &Node, - end: ?&Node, + start: *Node, + end: ?*Node, }; }; - pub fn iterate(self: &SuffixOp, index: usize) ?&Node { + pub fn iterate(self: *SuffixOp, index: usize) ?*Node { var i = index; if (i < 1) return self.lhs; @@ -1673,7 +1673,7 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &SuffixOp) TokenIndex { + pub fn firstToken(self: *SuffixOp) TokenIndex { switch (self.op) { @TagType(Op).Call => |*call_info| if (call_info.async_attr) |async_attr| return async_attr.firstToken(), else => {}, @@ -1681,7 +1681,7 @@ pub const Node = struct { return self.lhs.firstToken(); } - pub fn lastToken(self: &SuffixOp) TokenIndex { + pub fn lastToken(self: *SuffixOp) TokenIndex { return self.rtoken; } }; @@ -1689,10 +1689,10 @@ pub const Node = struct { pub const GroupedExpression = struct { base: Node, lparen: TokenIndex, - expr: &Node, + expr: *Node, rparen: TokenIndex, - pub fn iterate(self: &GroupedExpression, index: usize) ?&Node { + pub fn iterate(self: *GroupedExpression, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; @@ -1701,11 +1701,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &GroupedExpression) TokenIndex { + pub fn firstToken(self: *GroupedExpression) TokenIndex { return self.lparen; } - pub fn lastToken(self: &GroupedExpression) TokenIndex { + pub fn lastToken(self: *GroupedExpression) TokenIndex { return self.rparen; } }; @@ -1714,15 +1714,15 @@ pub const Node = struct { base: Node, ltoken: TokenIndex, kind: Kind, - rhs: ?&Node, + rhs: ?*Node, const Kind = union(enum) { - Break: ?&Node, - Continue: ?&Node, + Break: ?*Node, + Continue: ?*Node, Return, }; - pub fn iterate(self: &ControlFlowExpression, index: usize) ?&Node { + pub fn iterate(self: *ControlFlowExpression, index: usize) ?*Node { var i = index; switch (self.kind) { @@ -1749,11 +1749,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &ControlFlowExpression) TokenIndex { + pub fn firstToken(self: *ControlFlowExpression) TokenIndex { return self.ltoken; } - pub fn lastToken(self: &ControlFlowExpression) TokenIndex { + pub fn lastToken(self: *ControlFlowExpression) TokenIndex { if (self.rhs) |rhs| { return rhs.lastToken(); } @@ -1780,10 +1780,10 @@ pub const Node = struct { base: Node, label: ?TokenIndex, suspend_token: TokenIndex, - payload: ?&Node, - body: ?&Node, + payload: ?*Node, + body: ?*Node, - pub fn iterate(self: &Suspend, index: usize) ?&Node { + pub fn iterate(self: *Suspend, index: usize) ?*Node { var i = index; if (self.payload) |payload| { @@ -1799,12 +1799,12 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &Suspend) TokenIndex { + pub fn firstToken(self: *Suspend) TokenIndex { if (self.label) |label| return label; return self.suspend_token; } - pub fn lastToken(self: &Suspend) TokenIndex { + pub fn lastToken(self: *Suspend) TokenIndex { if (self.body) |body| { return body.lastToken(); } @@ -1821,15 +1821,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &IntegerLiteral, index: usize) ?&Node { + pub fn iterate(self: *IntegerLiteral, index: usize) ?*Node { return null; } - pub fn firstToken(self: &IntegerLiteral) TokenIndex { + pub fn firstToken(self: *IntegerLiteral) TokenIndex { return self.token; } - pub fn lastToken(self: &IntegerLiteral) TokenIndex { + pub fn lastToken(self: *IntegerLiteral) TokenIndex { return self.token; } }; @@ -1838,15 +1838,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &FloatLiteral, index: usize) ?&Node { + pub fn iterate(self: *FloatLiteral, index: usize) ?*Node { return null; } - pub fn firstToken(self: &FloatLiteral) TokenIndex { + pub fn firstToken(self: *FloatLiteral) TokenIndex { return self.token; } - pub fn lastToken(self: &FloatLiteral) TokenIndex { + pub fn lastToken(self: *FloatLiteral) TokenIndex { return self.token; } }; @@ -1857,9 +1857,9 @@ pub const Node = struct { params: ParamList, rparen_token: TokenIndex, - pub const ParamList = SegmentedList(&Node, 2); + pub const ParamList = SegmentedList(*Node, 2); - pub fn iterate(self: &BuiltinCall, index: usize) ?&Node { + pub fn iterate(self: *BuiltinCall, index: usize) ?*Node { var i = index; if (i < self.params.len) return self.params.at(i).*; @@ -1868,11 +1868,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &BuiltinCall) TokenIndex { + pub fn firstToken(self: *BuiltinCall) TokenIndex { return self.builtin_token; } - pub fn lastToken(self: &BuiltinCall) TokenIndex { + pub fn lastToken(self: *BuiltinCall) TokenIndex { return self.rparen_token; } }; @@ -1881,15 +1881,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &StringLiteral, index: usize) ?&Node { + pub fn iterate(self: *StringLiteral, index: usize) ?*Node { return null; } - pub fn firstToken(self: &StringLiteral) TokenIndex { + pub fn firstToken(self: *StringLiteral) TokenIndex { return self.token; } - pub fn lastToken(self: &StringLiteral) TokenIndex { + pub fn lastToken(self: *StringLiteral) TokenIndex { return self.token; } }; @@ -1900,15 +1900,15 @@ pub const Node = struct { pub const LineList = SegmentedList(TokenIndex, 4); - pub fn iterate(self: &MultilineStringLiteral, index: usize) ?&Node { + pub fn iterate(self: *MultilineStringLiteral, index: usize) ?*Node { return null; } - pub fn firstToken(self: &MultilineStringLiteral) TokenIndex { + pub fn firstToken(self: *MultilineStringLiteral) TokenIndex { return self.lines.at(0).*; } - pub fn lastToken(self: &MultilineStringLiteral) TokenIndex { + pub fn lastToken(self: *MultilineStringLiteral) TokenIndex { return self.lines.at(self.lines.len - 1).*; } }; @@ -1917,15 +1917,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &CharLiteral, index: usize) ?&Node { + pub fn iterate(self: *CharLiteral, index: usize) ?*Node { return null; } - pub fn firstToken(self: &CharLiteral) TokenIndex { + pub fn firstToken(self: *CharLiteral) TokenIndex { return self.token; } - pub fn lastToken(self: &CharLiteral) TokenIndex { + pub fn lastToken(self: *CharLiteral) TokenIndex { return self.token; } }; @@ -1934,15 +1934,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &BoolLiteral, index: usize) ?&Node { + pub fn iterate(self: *BoolLiteral, index: usize) ?*Node { return null; } - pub fn firstToken(self: &BoolLiteral) TokenIndex { + pub fn firstToken(self: *BoolLiteral) TokenIndex { return self.token; } - pub fn lastToken(self: &BoolLiteral) TokenIndex { + pub fn lastToken(self: *BoolLiteral) TokenIndex { return self.token; } }; @@ -1951,15 +1951,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &NullLiteral, index: usize) ?&Node { + pub fn iterate(self: *NullLiteral, index: usize) ?*Node { return null; } - pub fn firstToken(self: &NullLiteral) TokenIndex { + pub fn firstToken(self: *NullLiteral) TokenIndex { return self.token; } - pub fn lastToken(self: &NullLiteral) TokenIndex { + pub fn lastToken(self: *NullLiteral) TokenIndex { return self.token; } }; @@ -1968,15 +1968,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &UndefinedLiteral, index: usize) ?&Node { + pub fn iterate(self: *UndefinedLiteral, index: usize) ?*Node { return null; } - pub fn firstToken(self: &UndefinedLiteral) TokenIndex { + pub fn firstToken(self: *UndefinedLiteral) TokenIndex { return self.token; } - pub fn lastToken(self: &UndefinedLiteral) TokenIndex { + pub fn lastToken(self: *UndefinedLiteral) TokenIndex { return self.token; } }; @@ -1985,15 +1985,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &ThisLiteral, index: usize) ?&Node { + pub fn iterate(self: *ThisLiteral, index: usize) ?*Node { return null; } - pub fn firstToken(self: &ThisLiteral) TokenIndex { + pub fn firstToken(self: *ThisLiteral) TokenIndex { return self.token; } - pub fn lastToken(self: &ThisLiteral) TokenIndex { + pub fn lastToken(self: *ThisLiteral) TokenIndex { return self.token; } }; @@ -2001,17 +2001,17 @@ pub const Node = struct { pub const AsmOutput = struct { base: Node, lbracket: TokenIndex, - symbolic_name: &Node, - constraint: &Node, + symbolic_name: *Node, + constraint: *Node, kind: Kind, rparen: TokenIndex, const Kind = union(enum) { - Variable: &Identifier, - Return: &Node, + Variable: *Identifier, + Return: *Node, }; - pub fn iterate(self: &AsmOutput, index: usize) ?&Node { + pub fn iterate(self: *AsmOutput, index: usize) ?*Node { var i = index; if (i < 1) return self.symbolic_name; @@ -2022,7 +2022,7 @@ pub const Node = struct { switch (self.kind) { Kind.Variable => |variable_name| { - if (i < 1) return &variable_name.base; + if (i < 1) return *variable_name.base; i -= 1; }, Kind.Return => |return_type| { @@ -2034,11 +2034,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &AsmOutput) TokenIndex { + pub fn firstToken(self: *AsmOutput) TokenIndex { return self.lbracket; } - pub fn lastToken(self: &AsmOutput) TokenIndex { + pub fn lastToken(self: *AsmOutput) TokenIndex { return self.rparen; } }; @@ -2046,12 +2046,12 @@ pub const Node = struct { pub const AsmInput = struct { base: Node, lbracket: TokenIndex, - symbolic_name: &Node, - constraint: &Node, - expr: &Node, + symbolic_name: *Node, + constraint: *Node, + expr: *Node, rparen: TokenIndex, - pub fn iterate(self: &AsmInput, index: usize) ?&Node { + pub fn iterate(self: *AsmInput, index: usize) ?*Node { var i = index; if (i < 1) return self.symbolic_name; @@ -2066,11 +2066,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &AsmInput) TokenIndex { + pub fn firstToken(self: *AsmInput) TokenIndex { return self.lbracket; } - pub fn lastToken(self: &AsmInput) TokenIndex { + pub fn lastToken(self: *AsmInput) TokenIndex { return self.rparen; } }; @@ -2079,33 +2079,33 @@ pub const Node = struct { base: Node, asm_token: TokenIndex, volatile_token: ?TokenIndex, - template: &Node, + template: *Node, outputs: OutputList, inputs: InputList, clobbers: ClobberList, rparen: TokenIndex, - const OutputList = SegmentedList(&AsmOutput, 2); - const InputList = SegmentedList(&AsmInput, 2); + const OutputList = SegmentedList(*AsmOutput, 2); + const InputList = SegmentedList(*AsmInput, 2); const ClobberList = SegmentedList(TokenIndex, 2); - pub fn iterate(self: &Asm, index: usize) ?&Node { + pub fn iterate(self: *Asm, index: usize) ?*Node { var i = index; - if (i < self.outputs.len) return &(self.outputs.at(index).*).base; + if (i < self.outputs.len) return *(self.outputs.at(index).*).base; i -= self.outputs.len; - if (i < self.inputs.len) return &(self.inputs.at(index).*).base; + if (i < self.inputs.len) return *(self.inputs.at(index).*).base; i -= self.inputs.len; return null; } - pub fn firstToken(self: &Asm) TokenIndex { + pub fn firstToken(self: *Asm) TokenIndex { return self.asm_token; } - pub fn lastToken(self: &Asm) TokenIndex { + pub fn lastToken(self: *Asm) TokenIndex { return self.rparen; } }; @@ -2114,15 +2114,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &Unreachable, index: usize) ?&Node { + pub fn iterate(self: *Unreachable, index: usize) ?*Node { return null; } - pub fn firstToken(self: &Unreachable) TokenIndex { + pub fn firstToken(self: *Unreachable) TokenIndex { return self.token; } - pub fn lastToken(self: &Unreachable) TokenIndex { + pub fn lastToken(self: *Unreachable) TokenIndex { return self.token; } }; @@ -2131,15 +2131,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &ErrorType, index: usize) ?&Node { + pub fn iterate(self: *ErrorType, index: usize) ?*Node { return null; } - pub fn firstToken(self: &ErrorType) TokenIndex { + pub fn firstToken(self: *ErrorType) TokenIndex { return self.token; } - pub fn lastToken(self: &ErrorType) TokenIndex { + pub fn lastToken(self: *ErrorType) TokenIndex { return self.token; } }; @@ -2148,15 +2148,15 @@ pub const Node = struct { base: Node, token: TokenIndex, - pub fn iterate(self: &VarType, index: usize) ?&Node { + pub fn iterate(self: *VarType, index: usize) ?*Node { return null; } - pub fn firstToken(self: &VarType) TokenIndex { + pub fn firstToken(self: *VarType) TokenIndex { return self.token; } - pub fn lastToken(self: &VarType) TokenIndex { + pub fn lastToken(self: *VarType) TokenIndex { return self.token; } }; @@ -2167,27 +2167,27 @@ pub const Node = struct { pub const LineList = SegmentedList(TokenIndex, 4); - pub fn iterate(self: &DocComment, index: usize) ?&Node { + pub fn iterate(self: *DocComment, index: usize) ?*Node { return null; } - pub fn firstToken(self: &DocComment) TokenIndex { + pub fn firstToken(self: *DocComment) TokenIndex { return self.lines.at(0).*; } - pub fn lastToken(self: &DocComment) TokenIndex { + pub fn lastToken(self: *DocComment) TokenIndex { return self.lines.at(self.lines.len - 1).*; } }; pub const TestDecl = struct { base: Node, - doc_comments: ?&DocComment, + doc_comments: ?*DocComment, test_token: TokenIndex, - name: &Node, - body_node: &Node, + name: *Node, + body_node: *Node, - pub fn iterate(self: &TestDecl, index: usize) ?&Node { + pub fn iterate(self: *TestDecl, index: usize) ?*Node { var i = index; if (i < 1) return self.body_node; @@ -2196,11 +2196,11 @@ pub const Node = struct { return null; } - pub fn firstToken(self: &TestDecl) TokenIndex { + pub fn firstToken(self: *TestDecl) TokenIndex { return self.test_token; } - pub fn lastToken(self: &TestDecl) TokenIndex { + pub fn lastToken(self: *TestDecl) TokenIndex { return self.body_node.lastToken(); } }; diff --git a/std/zig/bench.zig b/std/zig/bench.zig index c3b6b0d3d3..59392889a6 100644 --- a/std/zig/bench.zig +++ b/std/zig/bench.zig @@ -24,15 +24,15 @@ pub fn main() !void { const mb_per_sec = bytes_per_sec / (1024 * 1024); var stdout_file = try std.io.getStdOut(); - const stdout = &std.io.FileOutStream.init(&stdout_file).stream; + const stdout = *std.io.FileOutStream.init(*stdout_file).stream; try stdout.print("{.3} MB/s, {} KB used \n", mb_per_sec, memory_used / 1024); } fn testOnce() usize { var fixed_buf_alloc = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]); - var allocator = &fixed_buf_alloc.allocator; + var allocator = *fixed_buf_alloc.allocator; var tokenizer = Tokenizer.init(source); - var parser = Parser.init(&tokenizer, allocator, "(memory buffer)"); + var parser = Parser.init(*tokenizer, allocator, "(memory buffer)"); _ = parser.parse() catch @panic("parse failure"); return fixed_buf_alloc.end_index; } diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 05554f5d34..6d29300aed 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -9,7 +9,7 @@ const Error = ast.Error; /// Result should be freed with tree.deinit() when there are /// no more references to any of the tokens or nodes. -pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { +pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { var tree_arena = std.heap.ArenaAllocator.init(allocator); errdefer tree_arena.deinit(); @@ -2754,16 +2754,16 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { } const AnnotatedToken = struct { - ptr: &Token, + ptr: *Token, index: TokenIndex, }; const TopLevelDeclCtx = struct { - decls: &ast.Node.Root.DeclList, + decls: *ast.Node.Root.DeclList, visib_token: ?TokenIndex, extern_export_inline_token: ?AnnotatedToken, - lib_name: ?&ast.Node, - comments: ?&ast.Node.DocComment, + lib_name: ?*ast.Node, + comments: ?*ast.Node.DocComment, }; const VarDeclCtx = struct { @@ -2771,21 +2771,21 @@ const VarDeclCtx = struct { visib_token: ?TokenIndex, comptime_token: ?TokenIndex, extern_export_token: ?TokenIndex, - lib_name: ?&ast.Node, - list: &ast.Node.Root.DeclList, - comments: ?&ast.Node.DocComment, + lib_name: ?*ast.Node, + list: *ast.Node.Root.DeclList, + comments: ?*ast.Node.DocComment, }; const TopLevelExternOrFieldCtx = struct { visib_token: TokenIndex, - container_decl: &ast.Node.ContainerDecl, - comments: ?&ast.Node.DocComment, + container_decl: *ast.Node.ContainerDecl, + comments: ?*ast.Node.DocComment, }; const ExternTypeCtx = struct { opt_ctx: OptionalCtx, extern_token: TokenIndex, - comments: ?&ast.Node.DocComment, + comments: ?*ast.Node.DocComment, }; const ContainerKindCtx = struct { @@ -2795,24 +2795,24 @@ const ContainerKindCtx = struct { const ExpectTokenSave = struct { id: @TagType(Token.Id), - ptr: &TokenIndex, + ptr: *TokenIndex, }; const OptionalTokenSave = struct { id: @TagType(Token.Id), - ptr: &?TokenIndex, + ptr: *?TokenIndex, }; const ExprListCtx = struct { - list: &ast.Node.SuffixOp.Op.InitList, + list: *ast.Node.SuffixOp.Op.InitList, end: Token.Id, - ptr: &TokenIndex, + ptr: *TokenIndex, }; fn ListSave(comptime List: type) type { return struct { - list: &List, - ptr: &TokenIndex, + list: *List, + ptr: *TokenIndex, }; } @@ -2841,7 +2841,7 @@ const LoopCtx = struct { const AsyncEndCtx = struct { ctx: OptionalCtx, - attribute: &ast.Node.AsyncAttribute, + attribute: *ast.Node.AsyncAttribute, }; const ErrorTypeOrSetDeclCtx = struct { @@ -2850,21 +2850,21 @@ const ErrorTypeOrSetDeclCtx = struct { }; const ParamDeclEndCtx = struct { - fn_proto: &ast.Node.FnProto, - param_decl: &ast.Node.ParamDecl, + fn_proto: *ast.Node.FnProto, + param_decl: *ast.Node.ParamDecl, }; const ComptimeStatementCtx = struct { comptime_token: TokenIndex, - block: &ast.Node.Block, + block: *ast.Node.Block, }; const OptionalCtx = union(enum) { - Optional: &?&ast.Node, - RequiredNull: &?&ast.Node, - Required: &&ast.Node, + Optional: *?*ast.Node, + RequiredNull: *?*ast.Node, + Required: **ast.Node, - pub fn store(self: &const OptionalCtx, value: &ast.Node) void { + pub fn store(self: *const OptionalCtx, value: *ast.Node) void { switch (self.*) { OptionalCtx.Optional => |ptr| ptr.* = value, OptionalCtx.RequiredNull => |ptr| ptr.* = value, @@ -2872,7 +2872,7 @@ const OptionalCtx = union(enum) { } } - pub fn get(self: &const OptionalCtx) ?&ast.Node { + pub fn get(self: *const OptionalCtx) ?*ast.Node { switch (self.*) { OptionalCtx.Optional => |ptr| return ptr.*, OptionalCtx.RequiredNull => |ptr| return ??ptr.*, @@ -2880,7 +2880,7 @@ const OptionalCtx = union(enum) { } } - pub fn toRequired(self: &const OptionalCtx) OptionalCtx { + pub fn toRequired(self: *const OptionalCtx) OptionalCtx { switch (self.*) { OptionalCtx.Optional => |ptr| { return OptionalCtx{ .RequiredNull = ptr }; @@ -2892,8 +2892,8 @@ const OptionalCtx = union(enum) { }; const AddCommentsCtx = struct { - node_ptr: &&ast.Node, - comments: ?&ast.Node.DocComment, + node_ptr: **ast.Node, + comments: ?*ast.Node.DocComment, }; const State = union(enum) { @@ -2904,67 +2904,67 @@ const State = union(enum) { TopLevelExternOrField: TopLevelExternOrFieldCtx, ContainerKind: ContainerKindCtx, - ContainerInitArgStart: &ast.Node.ContainerDecl, - ContainerInitArg: &ast.Node.ContainerDecl, - ContainerDecl: &ast.Node.ContainerDecl, + ContainerInitArgStart: *ast.Node.ContainerDecl, + ContainerInitArg: *ast.Node.ContainerDecl, + ContainerDecl: *ast.Node.ContainerDecl, VarDecl: VarDeclCtx, - VarDeclAlign: &ast.Node.VarDecl, - VarDeclEq: &ast.Node.VarDecl, - VarDeclSemiColon: &ast.Node.VarDecl, - - FnDef: &ast.Node.FnProto, - FnProto: &ast.Node.FnProto, - FnProtoAlign: &ast.Node.FnProto, - FnProtoReturnType: &ast.Node.FnProto, - - ParamDecl: &ast.Node.FnProto, - ParamDeclAliasOrComptime: &ast.Node.ParamDecl, - ParamDeclName: &ast.Node.ParamDecl, + VarDeclAlign: *ast.Node.VarDecl, + VarDeclEq: *ast.Node.VarDecl, + VarDeclSemiColon: *ast.Node.VarDecl, + + FnDef: *ast.Node.FnProto, + FnProto: *ast.Node.FnProto, + FnProtoAlign: *ast.Node.FnProto, + FnProtoReturnType: *ast.Node.FnProto, + + ParamDecl: *ast.Node.FnProto, + ParamDeclAliasOrComptime: *ast.Node.ParamDecl, + ParamDeclName: *ast.Node.ParamDecl, ParamDeclEnd: ParamDeclEndCtx, - ParamDeclComma: &ast.Node.FnProto, + ParamDeclComma: *ast.Node.FnProto, MaybeLabeledExpression: MaybeLabeledExpressionCtx, LabeledExpression: LabelCtx, Inline: InlineCtx, While: LoopCtx, - WhileContinueExpr: &?&ast.Node, + WhileContinueExpr: *?*ast.Node, For: LoopCtx, - Else: &?&ast.Node.Else, + Else: *?*ast.Node.Else, - Block: &ast.Node.Block, - Statement: &ast.Node.Block, + Block: *ast.Node.Block, + Statement: *ast.Node.Block, ComptimeStatement: ComptimeStatementCtx, - Semicolon: &&ast.Node, + Semicolon: **ast.Node, - AsmOutputItems: &ast.Node.Asm.OutputList, - AsmOutputReturnOrType: &ast.Node.AsmOutput, - AsmInputItems: &ast.Node.Asm.InputList, - AsmClobberItems: &ast.Node.Asm.ClobberList, + AsmOutputItems: *ast.Node.Asm.OutputList, + AsmOutputReturnOrType: *ast.Node.AsmOutput, + AsmInputItems: *ast.Node.Asm.InputList, + AsmClobberItems: *ast.Node.Asm.ClobberList, ExprListItemOrEnd: ExprListCtx, ExprListCommaOrEnd: ExprListCtx, FieldInitListItemOrEnd: ListSave(ast.Node.SuffixOp.Op.InitList), FieldInitListCommaOrEnd: ListSave(ast.Node.SuffixOp.Op.InitList), - FieldListCommaOrEnd: &ast.Node.ContainerDecl, + FieldListCommaOrEnd: *ast.Node.ContainerDecl, FieldInitValue: OptionalCtx, ErrorTagListItemOrEnd: ListSave(ast.Node.ErrorSetDecl.DeclList), ErrorTagListCommaOrEnd: ListSave(ast.Node.ErrorSetDecl.DeclList), SwitchCaseOrEnd: ListSave(ast.Node.Switch.CaseList), SwitchCaseCommaOrEnd: ListSave(ast.Node.Switch.CaseList), - SwitchCaseFirstItem: &ast.Node.SwitchCase, - SwitchCaseItemCommaOrEnd: &ast.Node.SwitchCase, - SwitchCaseItemOrEnd: &ast.Node.SwitchCase, + SwitchCaseFirstItem: *ast.Node.SwitchCase, + SwitchCaseItemCommaOrEnd: *ast.Node.SwitchCase, + SwitchCaseItemOrEnd: *ast.Node.SwitchCase, - SuspendBody: &ast.Node.Suspend, - AsyncAllocator: &ast.Node.AsyncAttribute, + SuspendBody: *ast.Node.Suspend, + AsyncAllocator: *ast.Node.AsyncAttribute, AsyncEnd: AsyncEndCtx, ExternType: ExternTypeCtx, - SliceOrArrayAccess: &ast.Node.SuffixOp, - SliceOrArrayType: &ast.Node.PrefixOp, - AddrOfModifiers: &ast.Node.PrefixOp.AddrOfInfo, - AlignBitRange: &ast.Node.PrefixOp.AddrOfInfo.Align, + SliceOrArrayAccess: *ast.Node.SuffixOp, + SliceOrArrayType: *ast.Node.PrefixOp, + AddrOfModifiers: *ast.Node.PrefixOp.AddrOfInfo, + AlignBitRange: *ast.Node.PrefixOp.AddrOfInfo.Align, Payload: OptionalCtx, PointerPayload: OptionalCtx, @@ -3007,7 +3007,7 @@ const State = union(enum) { ErrorTypeOrSetDecl: ErrorTypeOrSetDeclCtx, StringLiteral: OptionalCtx, Identifier: OptionalCtx, - ErrorTag: &&ast.Node, + ErrorTag: **ast.Node, IfToken: @TagType(Token.Id), IfTokenSave: ExpectTokenSave, @@ -3016,7 +3016,7 @@ const State = union(enum) { OptionalTokenSave: OptionalTokenSave, }; -fn pushDocComment(arena: &mem.Allocator, line_comment: TokenIndex, result: &?&ast.Node.DocComment) !void { +fn pushDocComment(arena: *mem.Allocator, line_comment: TokenIndex, result: *?*ast.Node.DocComment) !void { const node = blk: { if (result.*) |comment_node| { break :blk comment_node; @@ -3032,8 +3032,8 @@ fn pushDocComment(arena: &mem.Allocator, line_comment: TokenIndex, result: &?&as try node.lines.push(line_comment); } -fn eatDocComments(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) !?&ast.Node.DocComment { - var result: ?&ast.Node.DocComment = null; +fn eatDocComments(arena: *mem.Allocator, tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) !?*ast.Node.DocComment { + var result: ?*ast.Node.DocComment = null; while (true) { if (eatToken(tok_it, tree, Token.Id.DocComment)) |line_comment| { try pushDocComment(arena, line_comment, &result); @@ -3044,7 +3044,7 @@ fn eatDocComments(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, t return result; } -fn parseStringLiteral(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterator, token_ptr: &const Token, token_index: TokenIndex, tree: &ast.Tree) !?&ast.Node { +fn parseStringLiteral(arena: *mem.Allocator, tok_it: *ast.Tree.TokenList.Iterator, token_ptr: *const Token, token_index: TokenIndex, tree: *ast.Tree) !?*ast.Node { switch (token_ptr.id) { Token.Id.StringLiteral => { return &(try createLiteral(arena, ast.Node.StringLiteral, token_index)).base; @@ -3071,11 +3071,11 @@ fn parseStringLiteral(arena: &mem.Allocator, tok_it: &ast.Tree.TokenList.Iterato }, // TODO: We shouldn't need a cast, but: // 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. - else => return (?&ast.Node)(null), + else => return (?*ast.Node)(null), } } -fn parseBlockExpr(stack: &std.ArrayList(State), arena: &mem.Allocator, ctx: &const OptionalCtx, token_ptr: &const Token, token_index: TokenIndex) !bool { +fn parseBlockExpr(stack: *std.ArrayList(State), arena: *mem.Allocator, ctx: *const OptionalCtx, token_ptr: *const Token, token_index: TokenIndex) !bool { switch (token_ptr.id) { Token.Id.Keyword_suspend => { const node = try arena.construct(ast.Node.Suspend{ @@ -3189,7 +3189,7 @@ const ExpectCommaOrEndResult = union(enum) { parse_error: Error, }; -fn expectCommaOrEnd(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, end: @TagType(Token.Id)) ExpectCommaOrEndResult { +fn expectCommaOrEnd(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree, end: @TagType(Token.Id)) ExpectCommaOrEndResult { const token = nextToken(tok_it, tree); const token_index = token.index; const token_ptr = token.ptr; @@ -3212,7 +3212,7 @@ fn expectCommaOrEnd(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, end: } } -fn tokenIdToAssignment(id: &const Token.Id) ?ast.Node.InfixOp.Op { +fn tokenIdToAssignment(id: *const Token.Id) ?ast.Node.InfixOp.Op { // TODO: We have to cast all cases because of this: // error: expected type '?InfixOp', found '?@TagType(InfixOp)' return switch (id.*) { @@ -3307,21 +3307,21 @@ fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op { }; } -fn createLiteral(arena: &mem.Allocator, comptime T: type, token_index: TokenIndex) !&T { +fn createLiteral(arena: *mem.Allocator, comptime T: type, token_index: TokenIndex) !*T { return arena.construct(T{ .base = ast.Node{ .id = ast.Node.typeToId(T) }, .token = token_index, }); } -fn createToCtxLiteral(arena: &mem.Allocator, opt_ctx: &const OptionalCtx, comptime T: type, token_index: TokenIndex) !&T { +fn createToCtxLiteral(arena: *mem.Allocator, opt_ctx: *const OptionalCtx, comptime T: type, token_index: TokenIndex) !*T { const node = try createLiteral(arena, T, token_index); opt_ctx.store(&node.base); return node; } -fn eatToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, id: @TagType(Token.Id)) ?TokenIndex { +fn eatToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree, id: @TagType(Token.Id)) ?TokenIndex { const token = ??tok_it.peek(); if (token.id == id) { @@ -3331,7 +3331,7 @@ fn eatToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree, id: @TagType( return null; } -fn nextToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) AnnotatedToken { +fn nextToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) AnnotatedToken { const result = AnnotatedToken{ .index = tok_it.index, .ptr = ??tok_it.next(), @@ -3345,7 +3345,7 @@ fn nextToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) AnnotatedTok } } -fn prevToken(tok_it: &ast.Tree.TokenList.Iterator, tree: &ast.Tree) void { +fn prevToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) void { while (true) { const prev_tok = tok_it.prev() ?? return; if (prev_tok.id == Token.Id.LineComment) continue; diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 69903bc3fd..8507470bcc 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1803,7 +1803,7 @@ const io = std.io; var fixed_buffer_mem: [100 * 1024]u8 = undefined; -fn testParse(source: []const u8, allocator: &mem.Allocator, anything_changed: &bool) ![]u8 { +fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *bool) ![]u8 { var stderr_file = try io.getStdErr(); var stderr = &io.FileOutStream.init(&stderr_file).stream; diff --git a/std/zig/render.zig b/std/zig/render.zig index ac07917ff1..07e01241b7 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -13,7 +13,7 @@ pub const Error = error{ }; /// Returns whether anything changed -pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf(stream).Child.Error || Error)!bool { +pub fn render(allocator: *mem.Allocator, stream: var, tree: *ast.Tree) (@typeOf(stream).Child.Error || Error)!bool { comptime assert(@typeId(@typeOf(stream)) == builtin.TypeId.Pointer); var anything_changed: bool = false; @@ -24,13 +24,13 @@ pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf( const StreamError = @typeOf(stream).Child.Error; const Stream = std.io.OutStream(StreamError); - anything_changed_ptr: &bool, + anything_changed_ptr: *bool, child_stream: @typeOf(stream), stream: Stream, source_index: usize, source: []const u8, - fn write(iface_stream: &Stream, bytes: []const u8) StreamError!void { + fn write(iface_stream: *Stream, bytes: []const u8) StreamError!void { const self = @fieldParentPtr(MyStream, "stream", iface_stream); if (!self.anything_changed_ptr.*) { @@ -63,9 +63,9 @@ pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf( } fn renderRoot( - allocator: &mem.Allocator, + allocator: *mem.Allocator, stream: var, - tree: &ast.Tree, + tree: *ast.Tree, ) (@typeOf(stream).Child.Error || Error)!void { // render all the line comments at the beginning of the file var tok_it = tree.tokens.iterator(0); @@ -90,7 +90,7 @@ fn renderRoot( } } -fn renderExtraNewline(tree: &ast.Tree, stream: var, start_col: &usize, node: &ast.Node) !void { +fn renderExtraNewline(tree: *ast.Tree, stream: var, start_col: *usize, node: *ast.Node) !void { const first_token = node.firstToken(); var prev_token = first_token; while (tree.tokens.at(prev_token - 1).id == Token.Id.DocComment) { @@ -104,7 +104,7 @@ fn renderExtraNewline(tree: &ast.Tree, stream: var, start_col: &usize, node: &as } } -fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, indent: usize, start_col: &usize, decl: &ast.Node) (@typeOf(stream).Child.Error || Error)!void { +fn renderTopLevelDecl(allocator: *mem.Allocator, stream: var, tree: *ast.Tree, indent: usize, start_col: *usize, decl: *ast.Node) (@typeOf(stream).Child.Error || Error)!void { switch (decl.id) { ast.Node.Id.FnProto => { const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl); @@ -214,12 +214,12 @@ fn renderTopLevelDecl(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, i } fn renderExpression( - allocator: &mem.Allocator, + allocator: *mem.Allocator, stream: var, - tree: &ast.Tree, + tree: *ast.Tree, indent: usize, - start_col: &usize, - base: &ast.Node, + start_col: *usize, + base: *ast.Node, space: Space, ) (@typeOf(stream).Child.Error || Error)!void { switch (base.id) { @@ -1640,12 +1640,12 @@ fn renderExpression( } fn renderVarDecl( - allocator: &mem.Allocator, + allocator: *mem.Allocator, stream: var, - tree: &ast.Tree, + tree: *ast.Tree, indent: usize, - start_col: &usize, - var_decl: &ast.Node.VarDecl, + start_col: *usize, + var_decl: *ast.Node.VarDecl, ) (@typeOf(stream).Child.Error || Error)!void { if (var_decl.visib_token) |visib_token| { try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub @@ -1696,12 +1696,12 @@ fn renderVarDecl( } fn renderParamDecl( - allocator: &mem.Allocator, + allocator: *mem.Allocator, stream: var, - tree: &ast.Tree, + tree: *ast.Tree, indent: usize, - start_col: &usize, - base: &ast.Node, + start_col: *usize, + base: *ast.Node, space: Space, ) (@typeOf(stream).Child.Error || Error)!void { const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base); @@ -1724,12 +1724,12 @@ fn renderParamDecl( } fn renderStatement( - allocator: &mem.Allocator, + allocator: *mem.Allocator, stream: var, - tree: &ast.Tree, + tree: *ast.Tree, indent: usize, - start_col: &usize, - base: &ast.Node, + start_col: *usize, + base: *ast.Node, ) (@typeOf(stream).Child.Error || Error)!void { switch (base.id) { ast.Node.Id.VarDecl => { @@ -1761,7 +1761,7 @@ const Space = enum { BlockStart, }; -fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, start_col: &usize, space: Space) (@typeOf(stream).Child.Error || Error)!void { +fn renderToken(tree: *ast.Tree, stream: var, token_index: ast.TokenIndex, indent: usize, start_col: *usize, space: Space) (@typeOf(stream).Child.Error || Error)!void { if (space == Space.BlockStart) { if (start_col.* < indent + indent_delta) return renderToken(tree, stream, token_index, indent, start_col, Space.Space); @@ -1928,11 +1928,11 @@ fn renderToken(tree: &ast.Tree, stream: var, token_index: ast.TokenIndex, indent } fn renderDocComments( - tree: &ast.Tree, + tree: *ast.Tree, stream: var, node: var, indent: usize, - start_col: &usize, + start_col: *usize, ) (@typeOf(stream).Child.Error || Error)!void { const comment = node.doc_comments ?? return; var it = comment.lines.iterator(0); @@ -1949,7 +1949,7 @@ fn renderDocComments( } } -fn nodeIsBlock(base: &const ast.Node) bool { +fn nodeIsBlock(base: *const ast.Node) bool { return switch (base.id) { ast.Node.Id.Block, ast.Node.Id.If, @@ -1961,7 +1961,7 @@ fn nodeIsBlock(base: &const ast.Node) bool { }; } -fn nodeCausesSliceOpSpace(base: &ast.Node) bool { +fn nodeCausesSliceOpSpace(base: *ast.Node) bool { const infix_op = base.cast(ast.Node.InfixOp) ?? return false; return switch (infix_op.op) { ast.Node.InfixOp.Op.Period => false, diff --git a/std/zig/tokenizer.zig b/std/zig/tokenizer.zig index 7c3b3210fb..8378a9011d 100644 --- a/std/zig/tokenizer.zig +++ b/std/zig/tokenizer.zig @@ -200,7 +200,7 @@ pub const Tokenizer = struct { pending_invalid_token: ?Token, /// For debugging purposes - pub fn dump(self: &Tokenizer, token: &const Token) void { + pub fn dump(self: *Tokenizer, token: *const Token) void { std.debug.warn("{} \"{}\"\n", @tagName(token.id), self.buffer[token.start..token.end]); } @@ -265,7 +265,7 @@ pub const Tokenizer = struct { SawAtSign, }; - pub fn next(self: &Tokenizer) Token { + pub fn next(self: *Tokenizer) Token { if (self.pending_invalid_token) |token| { self.pending_invalid_token = null; return token; @@ -1089,7 +1089,7 @@ pub const Tokenizer = struct { return result; } - fn checkLiteralCharacter(self: &Tokenizer) void { + fn checkLiteralCharacter(self: *Tokenizer) void { if (self.pending_invalid_token != null) return; const invalid_length = self.getInvalidCharacterLength(); if (invalid_length == 0) return; @@ -1100,7 +1100,7 @@ pub const Tokenizer = struct { }; } - fn getInvalidCharacterLength(self: &Tokenizer) u3 { + fn getInvalidCharacterLength(self: *Tokenizer) u3 { const c0 = self.buffer[self.index]; if (c0 < 0x80) { if (c0 < 0x20 or c0 == 0x7f) { diff --git a/test/assemble_and_link.zig b/test/assemble_and_link.zig index 2593f3306a..8c727e87b5 100644 --- a/test/assemble_and_link.zig +++ b/test/assemble_and_link.zig @@ -1,7 +1,7 @@ const builtin = @import("builtin"); const tests = @import("tests.zig"); -pub fn addCases(cases: &tests.CompareOutputContext) void { +pub fn addCases(cases: *tests.CompareOutputContext) void { if (builtin.os == builtin.Os.linux and builtin.arch == builtin.Arch.x86_64) { cases.addAsm("hello world linux x86_64", \\.text diff --git a/test/build_examples.zig b/test/build_examples.zig index 7a4c0f35d9..1ba0ca46cf 100644 --- a/test/build_examples.zig +++ b/test/build_examples.zig @@ -2,7 +2,7 @@ const tests = @import("tests.zig"); const builtin = @import("builtin"); const is_windows = builtin.os == builtin.Os.windows; -pub fn addCases(cases: &tests.BuildExamplesContext) void { +pub fn addCases(cases: *tests.BuildExamplesContext) void { cases.add("example/hello_world/hello.zig"); cases.addC("example/hello_world/hello_libc.zig"); cases.add("example/cat/main.zig"); diff --git a/test/cases/align.zig b/test/cases/align.zig index 582063766f..99bdcdf940 100644 --- a/test/cases/align.zig +++ b/test/cases/align.zig @@ -5,7 +5,7 @@ var foo: u8 align(4) = 100; test "global variable alignment" { assert(@typeOf(&foo).alignment == 4); - assert(@typeOf(&foo) == &align(4) u8); + assert(@typeOf(&foo) == *align(4) u8); const slice = (&foo)[0..1]; assert(@typeOf(slice) == []align(4) u8); } @@ -30,7 +30,7 @@ var baz: packed struct { } = undefined; test "packed struct alignment" { - assert(@typeOf(&baz.b) == &align(1) u32); + assert(@typeOf(&baz.b) == *align(1) u32); } const blah: packed struct { @@ -40,11 +40,11 @@ const blah: packed struct { } = undefined; test "bit field alignment" { - assert(@typeOf(&blah.b) == &align(1:3:6) const u3); + assert(@typeOf(&blah.b) == *align(1:3:6) const u3); } test "default alignment allows unspecified in type syntax" { - assert(&u32 == &align(@alignOf(u32)) u32); + assert(*u32 == *align(@alignOf(u32)) u32); } test "implicitly decreasing pointer alignment" { @@ -53,7 +53,7 @@ test "implicitly decreasing pointer alignment" { assert(addUnaligned(&a, &b) == 7); } -fn addUnaligned(a: &align(1) const u32, b: &align(1) const u32) u32 { +fn addUnaligned(a: *align(1) const u32, b: *align(1) const u32) u32 { return a.* + b.*; } @@ -76,7 +76,7 @@ fn testBytesAlign(b: u8) void { b, b, }; - const ptr = @ptrCast(&u32, &bytes[0]); + const ptr = @ptrCast(*u32, &bytes[0]); assert(ptr.* == 0x33333333); } @@ -99,10 +99,10 @@ test "@alignCast pointers" { expectsOnly1(&x); assert(x == 2); } -fn expectsOnly1(x: &align(1) u32) void { +fn expectsOnly1(x: *align(1) u32) void { expects4(@alignCast(4, x)); } -fn expects4(x: &align(4) u32) void { +fn expects4(x: *align(4) u32) void { x.* += 1; } @@ -163,8 +163,8 @@ fn whyWouldYouEverDoThis(comptime align_bytes: u8) align(align_bytes) u8 { test "@ptrCast preserves alignment of bigger source" { var x: u32 align(16) = 1234; - const ptr = @ptrCast(&u8, &x); - assert(@typeOf(ptr) == &align(16) u8); + const ptr = @ptrCast(*u8, &x); + assert(@typeOf(ptr) == *align(16) u8); } test "compile-time known array index has best alignment possible" { @@ -175,10 +175,10 @@ test "compile-time known array index has best alignment possible" { 3, 4, }; - assert(@typeOf(&array[0]) == &align(4) u8); - assert(@typeOf(&array[1]) == &u8); - assert(@typeOf(&array[2]) == &align(2) u8); - assert(@typeOf(&array[3]) == &u8); + assert(@typeOf(&array[0]) == *align(4) u8); + assert(@typeOf(&array[1]) == *u8); + assert(@typeOf(&array[2]) == *align(2) u8); + assert(@typeOf(&array[3]) == *u8); // because align is too small but we still figure out to use 2 var bigger align(2) = []u64{ @@ -187,10 +187,10 @@ test "compile-time known array index has best alignment possible" { 3, 4, }; - assert(@typeOf(&bigger[0]) == &align(2) u64); - assert(@typeOf(&bigger[1]) == &align(2) u64); - assert(@typeOf(&bigger[2]) == &align(2) u64); - assert(@typeOf(&bigger[3]) == &align(2) u64); + assert(@typeOf(&bigger[0]) == *align(2) u64); + assert(@typeOf(&bigger[1]) == *align(2) u64); + assert(@typeOf(&bigger[2]) == *align(2) u64); + assert(@typeOf(&bigger[3]) == *align(2) u64); // because pointer is align 2 and u32 align % 2 == 0 we can assume align 2 var smaller align(2) = []u32{ @@ -199,21 +199,21 @@ test "compile-time known array index has best alignment possible" { 3, 4, }; - testIndex(&smaller[0], 0, &align(2) u32); - testIndex(&smaller[0], 1, &align(2) u32); - testIndex(&smaller[0], 2, &align(2) u32); - testIndex(&smaller[0], 3, &align(2) u32); + testIndex(&smaller[0], 0, *align(2) u32); + testIndex(&smaller[0], 1, *align(2) u32); + testIndex(&smaller[0], 2, *align(2) u32); + testIndex(&smaller[0], 3, *align(2) u32); // has to use ABI alignment because index known at runtime only - testIndex2(&array[0], 0, &u8); - testIndex2(&array[0], 1, &u8); - testIndex2(&array[0], 2, &u8); - testIndex2(&array[0], 3, &u8); + testIndex2(&array[0], 0, *u8); + testIndex2(&array[0], 1, *u8); + testIndex2(&array[0], 2, *u8); + testIndex2(&array[0], 3, *u8); } -fn testIndex(smaller: &align(2) u32, index: usize, comptime T: type) void { +fn testIndex(smaller: *align(2) u32, index: usize, comptime T: type) void { assert(@typeOf(&smaller[index]) == T); } -fn testIndex2(ptr: &align(4) u8, index: usize, comptime T: type) void { +fn testIndex2(ptr: *align(4) u8, index: usize, comptime T: type) void { assert(@typeOf(&ptr[index]) == T); } diff --git a/test/cases/atomics.zig b/test/cases/atomics.zig index d406285d29..67c9ab3dd1 100644 --- a/test/cases/atomics.zig +++ b/test/cases/atomics.zig @@ -34,7 +34,7 @@ test "atomicrmw and atomicload" { testAtomicLoad(&data); } -fn testAtomicRmw(ptr: &u8) void { +fn testAtomicRmw(ptr: *u8) void { const prev_value = @atomicRmw(u8, ptr, AtomicRmwOp.Xchg, 42, AtomicOrder.SeqCst); assert(prev_value == 200); comptime { @@ -45,7 +45,7 @@ fn testAtomicRmw(ptr: &u8) void { } } -fn testAtomicLoad(ptr: &u8) void { +fn testAtomicLoad(ptr: *u8) void { const x = @atomicLoad(u8, ptr, AtomicOrder.SeqCst); assert(x == 42); } @@ -54,18 +54,18 @@ test "cmpxchg with ptr" { var data1: i32 = 1234; var data2: i32 = 5678; var data3: i32 = 9101; - var x: &i32 = &data1; - if (@cmpxchgWeak(&i32, &x, &data2, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| { + var x: *i32 = &data1; + if (@cmpxchgWeak(*i32, &x, &data2, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| { assert(x1 == &data1); } else { @panic("cmpxchg should have failed"); } - while (@cmpxchgWeak(&i32, &x, &data1, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| { + while (@cmpxchgWeak(*i32, &x, &data1, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| { assert(x1 == &data1); } assert(x == &data3); - assert(@cmpxchgStrong(&i32, &x, &data3, &data2, AtomicOrder.SeqCst, AtomicOrder.SeqCst) == null); + assert(@cmpxchgStrong(*i32, &x, &data3, &data2, AtomicOrder.SeqCst, AtomicOrder.SeqCst) == null); assert(x == &data2); } diff --git a/test/cases/bugs/655.zig b/test/cases/bugs/655.zig index 4431767d5c..50374d4e6d 100644 --- a/test/cases/bugs/655.zig +++ b/test/cases/bugs/655.zig @@ -3,10 +3,10 @@ const other_file = @import("655_other_file.zig"); test "function with &const parameter with type dereferenced by namespace" { const x: other_file.Integer = 1234; - comptime std.debug.assert(@typeOf(&x) == &const other_file.Integer); + comptime std.debug.assert(@typeOf(&x) == *const other_file.Integer); foo(x); } -fn foo(x: &const other_file.Integer) void { +fn foo(x: *const other_file.Integer) void { std.debug.assert(x.* == 1234); } diff --git a/test/cases/bugs/828.zig b/test/cases/bugs/828.zig index 10d7370b90..50ae0fd279 100644 --- a/test/cases/bugs/828.zig +++ b/test/cases/bugs/828.zig @@ -3,7 +3,7 @@ const CountBy = struct { const One = CountBy{ .a = 1 }; - pub fn counter(self: &const CountBy) Counter { + pub fn counter(self: *const CountBy) Counter { return Counter{ .i = 0 }; } }; @@ -11,13 +11,13 @@ const CountBy = struct { const Counter = struct { i: usize, - pub fn count(self: &Counter) bool { + pub fn count(self: *Counter) bool { self.i += 1; return self.i <= 10; } }; -fn constCount(comptime cb: &const CountBy, comptime unused: u32) void { +fn constCount(comptime cb: *const CountBy, comptime unused: u32) void { comptime { var cnt = cb.counter(); if (cnt.i != 0) @compileError("Counter instance reused!"); diff --git a/test/cases/bugs/920.zig b/test/cases/bugs/920.zig index c315206072..2903f05a29 100644 --- a/test/cases/bugs/920.zig +++ b/test/cases/bugs/920.zig @@ -9,10 +9,10 @@ const ZigTable = struct { pdf: fn (f64) f64, is_symmetric: bool, - zero_case: fn (&Random, f64) f64, + zero_case: fn (*Random, f64) f64, }; -fn 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 { +fn 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 { var tables: ZigTable = undefined; tables.is_symmetric = is_symmetric; @@ -45,7 +45,7 @@ fn norm_f(x: f64) f64 { fn norm_f_inv(y: f64) f64 { return math.sqrt(-2.0 * math.ln(y)); } -fn norm_zero_case(random: &Random, u: f64) f64 { +fn norm_zero_case(random: *Random, u: f64) f64 { return 0.0; } diff --git a/test/cases/cast.zig b/test/cases/cast.zig index e37451ea93..7358a4ffd8 100644 --- a/test/cases/cast.zig +++ b/test/cases/cast.zig @@ -3,20 +3,20 @@ const mem = @import("std").mem; test "int to ptr cast" { const x = usize(13); - const y = @intToPtr(&u8, x); + const y = @intToPtr(*u8, x); const z = @ptrToInt(y); assert(z == 13); } test "integer literal to pointer cast" { - const vga_mem = @intToPtr(&u16, 0xB8000); + const vga_mem = @intToPtr(*u16, 0xB8000); assert(@ptrToInt(vga_mem) == 0xB8000); } test "pointer reinterpret const float to int" { const float: f64 = 5.99999999999994648725e-01; const float_ptr = &float; - const int_ptr = @ptrCast(&const i32, float_ptr); + const int_ptr = @ptrCast(*const i32, float_ptr); const int_val = int_ptr.*; assert(int_val == 858993411); } @@ -28,7 +28,7 @@ test "implicitly cast a pointer to a const pointer of it" { assert(x == 2); } -fn funcWithConstPtrPtr(x: &const &i32) void { +fn funcWithConstPtrPtr(x: *const *i32) void { x.*.* += 1; } @@ -66,11 +66,11 @@ fn Struct(comptime T: type) type { const Self = this; x: T, - fn pointer(self: &const Self) Self { + fn pointer(self: *const Self) Self { return self.*; } - fn maybePointer(self: ?&const Self) Self { + fn maybePointer(self: ?*const Self) Self { const none = Self{ .x = if (T == void) void{} else 0 }; return (self ?? &none).*; } @@ -80,11 +80,11 @@ fn Struct(comptime T: type) type { const Union = union { x: u8, - fn pointer(self: &const Union) Union { + fn pointer(self: *const Union) Union { return self.*; } - fn maybePointer(self: ?&const Union) Union { + fn maybePointer(self: ?*const Union) Union { const none = Union{ .x = 0 }; return (self ?? &none).*; } @@ -94,11 +94,11 @@ const Enum = enum { None, Some, - fn pointer(self: &const Enum) Enum { + fn pointer(self: *const Enum) Enum { return self.*; } - fn maybePointer(self: ?&const Enum) Enum { + fn maybePointer(self: ?*const Enum) Enum { return (self ?? &Enum.None).*; } }; @@ -107,16 +107,16 @@ test "implicitly cast indirect pointer to maybe-indirect pointer" { const S = struct { const Self = this; x: u8, - fn constConst(p: &const &const Self) u8 { + fn constConst(p: *const *const Self) u8 { return (p.*).x; } - fn maybeConstConst(p: ?&const &const Self) u8 { + fn maybeConstConst(p: ?*const *const Self) u8 { return ((??p).*).x; } - fn constConstConst(p: &const &const &const Self) u8 { + fn constConstConst(p: *const *const *const Self) u8 { return (p.*.*).x; } - fn maybeConstConstConst(p: ?&const &const &const Self) u8 { + fn maybeConstConstConst(p: ?*const *const *const Self) u8 { return ((??p).*.*).x; } }; @@ -166,12 +166,12 @@ fn testPeerResolveArrayConstSlice(b: bool) void { } test "integer literal to &const int" { - const x: &const i32 = 3; + const x: *const i32 = 3; assert(x.* == 3); } test "string literal to &const []const u8" { - const x: &const []const u8 = "hello"; + const x: *const []const u8 = "hello"; assert(mem.eql(u8, x.*, "hello")); } @@ -209,11 +209,11 @@ test "return null from fn() error!?&T" { const b = returnNullLitFromMaybeTypeErrorRef(); assert((try a) == null and (try b) == null); } -fn returnNullFromMaybeTypeErrorRef() error!?&A { - const a: ?&A = null; +fn returnNullFromMaybeTypeErrorRef() error!?*A { + const a: ?*A = null; return a; } -fn returnNullLitFromMaybeTypeErrorRef() error!?&A { +fn returnNullLitFromMaybeTypeErrorRef() error!?*A { return null; } @@ -312,7 +312,7 @@ test "implicit cast from &const [N]T to []const T" { fn testCastConstArrayRefToConstSlice() void { const blah = "aoeu"; const const_array_ref = &blah; - assert(@typeOf(const_array_ref) == &const [4]u8); + assert(@typeOf(const_array_ref) == *const [4]u8); const slice: []const u8 = const_array_ref; assert(mem.eql(u8, slice, "aoeu")); } @@ -322,7 +322,7 @@ test "var args implicitly casts by value arg to const ref" { } fn foo(args: ...) void { - assert(@typeOf(args[0]) == &const [5]u8); + assert(@typeOf(args[0]) == *const [5]u8); } test "peer type resolution: error and [N]T" { diff --git a/test/cases/const_slice_child.zig b/test/cases/const_slice_child.zig index a92c589186..e012c729a0 100644 --- a/test/cases/const_slice_child.zig +++ b/test/cases/const_slice_child.zig @@ -1,10 +1,10 @@ const debug = @import("std").debug; const assert = debug.assert; -var argv: &const &const u8 = undefined; +var argv: *const *const u8 = undefined; test "const slice child" { - const strs = ([]&const u8){ + const strs = ([]*const u8){ c"one", c"two", c"three", @@ -29,7 +29,7 @@ fn bar(argc: usize) void { foo(args); } -fn strlen(ptr: &const u8) usize { +fn strlen(ptr: *const u8) usize { var count: usize = 0; while (ptr[count] != 0) : (count += 1) {} return count; diff --git a/test/cases/coroutines.zig b/test/cases/coroutines.zig index 8a071c6aad..4d2aa54a69 100644 --- a/test/cases/coroutines.zig +++ b/test/cases/coroutines.zig @@ -154,7 +154,7 @@ test "async function with dot syntax" { test "async fn pointer in a struct field" { var data: i32 = 1; const Foo = struct { - bar: async<&std.mem.Allocator> fn (&i32) void, + bar: async<*std.mem.Allocator> fn (*i32) void, }; var foo = Foo{ .bar = simpleAsyncFn2 }; const p = (async foo.bar(&data)) catch unreachable; @@ -162,7 +162,7 @@ test "async fn pointer in a struct field" { cancel p; assert(data == 4); } -async<&std.mem.Allocator> fn simpleAsyncFn2(y: &i32) void { +async<*std.mem.Allocator> fn simpleAsyncFn2(y: *i32) void { defer y.* += 2; y.* += 1; suspend; @@ -220,7 +220,7 @@ test "break from suspend" { cancel p; std.debug.assert(my_result == 2); } -async fn testBreakFromSuspend(my_result: &i32) void { +async fn testBreakFromSuspend(my_result: *i32) void { s: suspend |p| { break :s; } diff --git a/test/cases/enum.zig b/test/cases/enum.zig index cbcbc5e306..ae9f04869b 100644 --- a/test/cases/enum.zig +++ b/test/cases/enum.zig @@ -56,14 +56,14 @@ test "constant enum with payload" { shouldBeNotEmpty(full); } -fn shouldBeEmpty(x: &const AnEnumWithPayload) void { +fn shouldBeEmpty(x: *const AnEnumWithPayload) void { switch (x.*) { AnEnumWithPayload.Empty => {}, else => unreachable, } } -fn shouldBeNotEmpty(x: &const AnEnumWithPayload) void { +fn shouldBeNotEmpty(x: *const AnEnumWithPayload) void { switch (x.*) { AnEnumWithPayload.Empty => unreachable, else => {}, @@ -750,15 +750,15 @@ test "bit field access with enum fields" { assert(data.b == B.Four3); } -fn getA(data: &const BitFieldOfEnums) A { +fn getA(data: *const BitFieldOfEnums) A { return data.a; } -fn getB(data: &const BitFieldOfEnums) B { +fn getB(data: *const BitFieldOfEnums) B { return data.b; } -fn getC(data: &const BitFieldOfEnums) C { +fn getC(data: *const BitFieldOfEnums) C { return data.c; } diff --git a/test/cases/enum_with_members.zig b/test/cases/enum_with_members.zig index 8fafa70b02..18174186a9 100644 --- a/test/cases/enum_with_members.zig +++ b/test/cases/enum_with_members.zig @@ -6,7 +6,7 @@ const ET = union(enum) { SINT: i32, UINT: u32, - pub fn print(a: &const ET, buf: []u8) error!usize { + pub fn print(a: *const ET, buf: []u8) error!usize { return switch (a.*) { ET.SINT => |x| fmt.formatIntBuf(buf, x, 10, false, 0), ET.UINT => |x| fmt.formatIntBuf(buf, x, 10, false, 0), diff --git a/test/cases/eval.zig b/test/cases/eval.zig index 8a6dc25bd8..6c8bcfdbab 100644 --- a/test/cases/eval.zig +++ b/test/cases/eval.zig @@ -282,7 +282,7 @@ fn fnWithFloatMode() f32 { const SimpleStruct = struct { field: i32, - fn method(self: &const SimpleStruct) i32 { + fn method(self: *const SimpleStruct) i32 { return self.field + 3; } }; @@ -367,7 +367,7 @@ test "const global shares pointer with other same one" { assertEqualPtrs(&hi1[0], &hi2[0]); comptime assert(&hi1[0] == &hi2[0]); } -fn assertEqualPtrs(ptr1: &const u8, ptr2: &const u8) void { +fn assertEqualPtrs(ptr1: *const u8, ptr2: *const u8) void { assert(ptr1 == ptr2); } @@ -418,9 +418,9 @@ test "string literal used as comptime slice is memoized" { } test "comptime slice of undefined pointer of length 0" { - const slice1 = (&i32)(undefined)[0..0]; + const slice1 = (*i32)(undefined)[0..0]; assert(slice1.len == 0); - const slice2 = (&i32)(undefined)[100..100]; + const slice2 = (*i32)(undefined)[100..100]; assert(slice2.len == 0); } @@ -472,7 +472,7 @@ test "comptime function with mutable pointer is not memoized" { } } -fn increment(value: &i32) void { +fn increment(value: *i32) void { value.* += 1; } @@ -517,7 +517,7 @@ test "comptime slice of pointer preserves comptime var" { const SingleFieldStruct = struct { x: i32, - fn read_x(self: &const SingleFieldStruct) i32 { + fn read_x(self: *const SingleFieldStruct) i32 { return self.x; } }; diff --git a/test/cases/field_parent_ptr.zig b/test/cases/field_parent_ptr.zig index 1a7de9ce35..00d4e0f367 100644 --- a/test/cases/field_parent_ptr.zig +++ b/test/cases/field_parent_ptr.zig @@ -24,7 +24,7 @@ const foo = Foo{ .d = -10, }; -fn testParentFieldPtr(c: &const i32) void { +fn testParentFieldPtr(c: *const i32) void { assert(c == &foo.c); const base = @fieldParentPtr(Foo, "c", c); @@ -32,7 +32,7 @@ fn testParentFieldPtr(c: &const i32) void { assert(&base.c == c); } -fn testParentFieldPtrFirst(a: &const bool) void { +fn testParentFieldPtrFirst(a: *const bool) void { assert(a == &foo.a); const base = @fieldParentPtr(Foo, "a", a); diff --git a/test/cases/fn_in_struct_in_comptime.zig b/test/cases/fn_in_struct_in_comptime.zig index c22da71940..fabb57e9cb 100644 --- a/test/cases/fn_in_struct_in_comptime.zig +++ b/test/cases/fn_in_struct_in_comptime.zig @@ -1,9 +1,9 @@ const assert = @import("std").debug.assert; -fn get_foo() fn (&u8) usize { +fn get_foo() fn (*u8) usize { comptime { return struct { - fn func(ptr: &u8) usize { + fn func(ptr: *u8) usize { var u = @ptrToInt(ptr); return u; } @@ -13,5 +13,5 @@ fn get_foo() fn (&u8) usize { test "define a function in an anonymous struct in comptime" { const foo = get_foo(); - assert(foo(@intToPtr(&u8, 12345)) == 12345); + assert(foo(@intToPtr(*u8, 12345)) == 12345); } diff --git a/test/cases/generics.zig b/test/cases/generics.zig index 37cd1b89e4..a76990e2a1 100644 --- a/test/cases/generics.zig +++ b/test/cases/generics.zig @@ -96,8 +96,8 @@ test "generic struct" { fn GenNode(comptime T: type) type { return struct { value: T, - next: ?&GenNode(T), - fn getVal(n: &const GenNode(T)) T { + next: ?*GenNode(T), + fn getVal(n: *const GenNode(T)) T { return n.value; } }; @@ -126,11 +126,11 @@ test "generic fn with implicit cast" { 13, }) == 0); } -fn getByte(ptr: ?&const u8) u8 { +fn getByte(ptr: ?*const u8) u8 { return (??ptr).*; } fn getFirstByte(comptime T: type, mem: []const T) u8 { - return getByte(@ptrCast(&const u8, &mem[0])); + return getByte(@ptrCast(*const u8, &mem[0])); } const foos = []fn (var) bool{ diff --git a/test/cases/incomplete_struct_param_tld.zig b/test/cases/incomplete_struct_param_tld.zig index a2f57743d0..552d6ef185 100644 --- a/test/cases/incomplete_struct_param_tld.zig +++ b/test/cases/incomplete_struct_param_tld.zig @@ -11,12 +11,12 @@ const B = struct { const C = struct { x: i32, - fn d(c: &const C) i32 { + fn d(c: *const C) i32 { return c.x; } }; -fn foo(a: &const A) i32 { +fn foo(a: *const A) i32 { return a.b.c.d(); } diff --git a/test/cases/math.zig b/test/cases/math.zig index 0b4622702f..5f16e903b2 100644 --- a/test/cases/math.zig +++ b/test/cases/math.zig @@ -28,13 +28,13 @@ fn testDivision() void { assert(divTrunc(f32, -5.0, 3.0) == -1.0); comptime { - assert(1194735857077236777412821811143690633098347576 % 508740759824825164163191790951174292733114988 == 177254337427586449086438229241342047632117600); - assert(@rem(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -177254337427586449086438229241342047632117600); - assert(1194735857077236777412821811143690633098347576 / 508740759824825164163191790951174292733114988 == 2); - assert(@divTrunc(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -2); - assert(@divTrunc(1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == -2); - assert(@divTrunc(-1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == 2); - assert(4126227191251978491697987544882340798050766755606969681711 % 10 == 1); + assert(1194735857077236777412821811143690633098347576 % 508740759824825164163191790951174292733114988 == 177254337427586449086438229241342047632117600,); + assert(@rem(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -177254337427586449086438229241342047632117600,); + assert(1194735857077236777412821811143690633098347576 / 508740759824825164163191790951174292733114988 == 2,); + assert(@divTrunc(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -2,); + assert(@divTrunc(1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == -2,); + assert(@divTrunc(-1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == 2,); + assert(4126227191251978491697987544882340798050766755606969681711 % 10 == 1,); } } fn div(comptime T: type, a: T, b: T) T { @@ -324,8 +324,8 @@ test "big number addition" { test "big number multiplication" { comptime { - assert(45960427431263824329884196484953148229 * 128339149605334697009938835852565949723 == 5898522172026096622534201617172456926982464453350084962781392314016180490567); - assert(594491908217841670578297176641415611445982232488944558774612 * 390603545391089362063884922208143568023166603618446395589768 == 232210647056203049913662402532976186578842425262306016094292237500303028346593132411865381225871291702600263463125370016); + assert(45960427431263824329884196484953148229 * 128339149605334697009938835852565949723 == 5898522172026096622534201617172456926982464453350084962781392314016180490567,); + assert(594491908217841670578297176641415611445982232488944558774612 * 390603545391089362063884922208143568023166603618446395589768 == 232210647056203049913662402532976186578842425262306016094292237500303028346593132411865381225871291702600263463125370016,); } } diff --git a/test/cases/misc.zig b/test/cases/misc.zig index b6b2da8de5..919b978f9f 100644 --- a/test/cases/misc.zig +++ b/test/cases/misc.zig @@ -252,20 +252,20 @@ test "multiline C string" { } test "type equality" { - assert(&const u8 != &u8); + assert(*const u8 != *u8); } const global_a: i32 = 1234; -const global_b: &const i32 = &global_a; -const global_c: &const f32 = @ptrCast(&const f32, global_b); +const global_b: *const i32 = &global_a; +const global_c: *const f32 = @ptrCast(*const f32, global_b); test "compile time global reinterpret" { - const d = @ptrCast(&const i32, global_c); + const d = @ptrCast(*const i32, global_c); assert(d.* == 1234); } test "explicit cast maybe pointers" { - const a: ?&i32 = undefined; - const b: ?&f32 = @ptrCast(?&f32, a); + const a: ?*i32 = undefined; + const b: ?*f32 = @ptrCast(?*f32, a); } test "generic malloc free" { @@ -274,7 +274,7 @@ test "generic malloc free" { } var some_mem: [100]u8 = undefined; fn memAlloc(comptime T: type, n: usize) error![]T { - return @ptrCast(&T, &some_mem[0])[0..n]; + return @ptrCast(*T, &some_mem[0])[0..n]; } fn memFree(comptime T: type, memory: []T) void {} @@ -357,7 +357,7 @@ const test3_foo = Test3Foo{ }, }; const test3_bar = Test3Foo{ .Two = 13 }; -fn test3_1(f: &const Test3Foo) void { +fn test3_1(f: *const Test3Foo) void { switch (f.*) { Test3Foo.Three => |pt| { assert(pt.x == 3); @@ -366,7 +366,7 @@ fn test3_1(f: &const Test3Foo) void { else => unreachable, } } -fn test3_2(f: &const Test3Foo) void { +fn test3_2(f: *const Test3Foo) void { switch (f.*) { Test3Foo.Two => |x| { assert(x == 13); @@ -393,7 +393,7 @@ test "pointer comparison" { const b = &a; assert(ptrEql(b, b)); } -fn ptrEql(a: &const []const u8, b: &const []const u8) bool { +fn ptrEql(a: *const []const u8, b: *const []const u8) bool { return a == b; } @@ -446,13 +446,13 @@ fn testPointerToVoidReturnType() error!void { return a.*; } const test_pointer_to_void_return_type_x = void{}; -fn testPointerToVoidReturnType2() &const void { +fn testPointerToVoidReturnType2() *const void { return &test_pointer_to_void_return_type_x; } test "non const ptr to aliased type" { const int = i32; - assert(?&int == ?&i32); + assert(?*int == ?*i32); } test "array 2D const double ptr" { @@ -463,7 +463,7 @@ test "array 2D const double ptr" { testArray2DConstDoublePtr(&rect_2d_vertexes[0][0]); } -fn testArray2DConstDoublePtr(ptr: &const f32) void { +fn testArray2DConstDoublePtr(ptr: *const f32) void { assert(ptr[0] == 1.0); assert(ptr[1] == 2.0); } @@ -497,7 +497,7 @@ test "@typeId" { assert(@typeId(u64) == Tid.Int); assert(@typeId(f32) == Tid.Float); assert(@typeId(f64) == Tid.Float); - assert(@typeId(&f32) == Tid.Pointer); + assert(@typeId(*f32) == Tid.Pointer); assert(@typeId([2]u8) == Tid.Array); assert(@typeId(AStruct) == Tid.Struct); assert(@typeId(@typeOf(1)) == Tid.IntLiteral); @@ -540,7 +540,7 @@ test "@typeName" { }; comptime { assert(mem.eql(u8, @typeName(i64), "i64")); - assert(mem.eql(u8, @typeName(&usize), "&usize")); + assert(mem.eql(u8, @typeName(*usize), "*usize")); // https://github.com/ziglang/zig/issues/675 assert(mem.eql(u8, @typeName(TypeFromFn(u8)), "TypeFromFn(u8)")); assert(mem.eql(u8, @typeName(Struct), "Struct")); @@ -555,7 +555,7 @@ fn TypeFromFn(comptime T: type) type { test "volatile load and store" { var number: i32 = 1234; - const ptr = (&volatile i32)(&number); + const ptr = (*volatile i32)(&number); ptr.* += 1; assert(ptr.* == 1235); } @@ -587,28 +587,28 @@ var global_ptr = &gdt[0]; // can't really run this test but we can make sure it has no compile error // and generates code -const vram = @intToPtr(&volatile u8, 0x20000000)[0..0x8000]; +const vram = @intToPtr(*volatile u8, 0x20000000)[0..0x8000]; export fn writeToVRam() void { vram[0] = 'X'; } test "pointer child field" { - assert((&u32).Child == u32); + assert((*u32).Child == u32); } const OpaqueA = @OpaqueType(); const OpaqueB = @OpaqueType(); test "@OpaqueType" { - assert(&OpaqueA != &OpaqueB); + assert(*OpaqueA != *OpaqueB); assert(mem.eql(u8, @typeName(OpaqueA), "OpaqueA")); assert(mem.eql(u8, @typeName(OpaqueB), "OpaqueB")); } test "variable is allowed to be a pointer to an opaque type" { var x: i32 = 1234; - _ = hereIsAnOpaqueType(@ptrCast(&OpaqueA, &x)); + _ = hereIsAnOpaqueType(@ptrCast(*OpaqueA, &x)); } -fn hereIsAnOpaqueType(ptr: &OpaqueA) &OpaqueA { +fn hereIsAnOpaqueType(ptr: *OpaqueA) *OpaqueA { var a = ptr; return a; } @@ -692,7 +692,7 @@ test "packed struct, enum, union parameters in extern function" { }, PackedUnion{ .a = 1 }, PackedEnum.A); } -export fn testPackedStuff(a: &const PackedStruct, b: &const PackedUnion, c: PackedEnum) void {} +export fn testPackedStuff(a: *const PackedStruct, b: *const PackedUnion, c: PackedEnum) void {} test "slicing zero length array" { const s1 = ""[0..]; @@ -703,8 +703,8 @@ test "slicing zero length array" { assert(mem.eql(u32, s2, []u32{})); } -const addr1 = @ptrCast(&const u8, emptyFn); +const addr1 = @ptrCast(*const u8, emptyFn); test "comptime cast fn to ptr" { - const addr2 = @ptrCast(&const u8, emptyFn); + const addr2 = @ptrCast(*const u8, emptyFn); comptime assert(addr1 == addr2); } diff --git a/test/cases/null.zig b/test/cases/null.zig index 936e5fafbd..bd78990ff4 100644 --- a/test/cases/null.zig +++ b/test/cases/null.zig @@ -65,7 +65,7 @@ test "if var maybe pointer" { .d = 1, }) == 15); } -fn shouldBeAPlus1(p: &const Particle) u64 { +fn shouldBeAPlus1(p: *const Particle) u64 { var maybe_particle: ?Particle = p.*; if (maybe_particle) |*particle| { particle.a += 1; diff --git a/test/cases/reflection.zig b/test/cases/reflection.zig index b82ce6340f..48fcc9ef03 100644 --- a/test/cases/reflection.zig +++ b/test/cases/reflection.zig @@ -5,7 +5,7 @@ const reflection = this; test "reflection: array, pointer, nullable, error union type child" { comptime { assert(([10]u8).Child == u8); - assert((&u8).Child == u8); + assert((*u8).Child == u8); assert((error!u8).Payload == u8); assert((?u8).Child == u8); } diff --git a/test/cases/slice.zig b/test/cases/slice.zig index eae6fa895e..24e5239e2d 100644 --- a/test/cases/slice.zig +++ b/test/cases/slice.zig @@ -1,7 +1,7 @@ const assert = @import("std").debug.assert; const mem = @import("std").mem; -const x = @intToPtr(&i32, 0x1000)[0..0x500]; +const x = @intToPtr(*i32, 0x1000)[0..0x500]; const y = x[0x100..]; test "compile time slice of pointer to hard coded address" { assert(@ptrToInt(x.ptr) == 0x1000); diff --git a/test/cases/struct.zig b/test/cases/struct.zig index d4a1c7fbe3..0712e508de 100644 --- a/test/cases/struct.zig +++ b/test/cases/struct.zig @@ -43,7 +43,7 @@ const VoidStructFieldsFoo = struct { test "structs" { var foo: StructFoo = undefined; - @memset(@ptrCast(&u8, &foo), 0, @sizeOf(StructFoo)); + @memset(@ptrCast(*u8, &foo), 0, @sizeOf(StructFoo)); foo.a += 1; foo.b = foo.a == 1; testFoo(foo); @@ -55,16 +55,16 @@ const StructFoo = struct { b: bool, c: f32, }; -fn testFoo(foo: &const StructFoo) void { +fn testFoo(foo: *const StructFoo) void { assert(foo.b); } -fn testMutation(foo: &StructFoo) void { +fn testMutation(foo: *StructFoo) void { foo.c = 100; } const Node = struct { val: Val, - next: &Node, + next: *Node, }; const Val = struct { @@ -112,7 +112,7 @@ fn aFunc() i32 { return 13; } -fn callStructField(foo: &const Foo) i32 { +fn callStructField(foo: *const Foo) i32 { return foo.ptr(); } @@ -124,7 +124,7 @@ test "store member function in variable" { } const MemberFnTestFoo = struct { x: i32, - fn member(foo: &const MemberFnTestFoo) i32 { + fn member(foo: *const MemberFnTestFoo) i32 { return foo.x; } }; @@ -141,7 +141,7 @@ test "member functions" { } const MemberFnRand = struct { seed: u32, - pub fn getSeed(r: &const MemberFnRand) u32 { + pub fn getSeed(r: *const MemberFnRand) u32 { return r.seed; } }; @@ -166,7 +166,7 @@ test "empty struct method call" { assert(es.method() == 1234); } const EmptyStruct = struct { - fn method(es: &const EmptyStruct) i32 { + fn method(es: *const EmptyStruct) i32 { return 1234; } }; @@ -228,15 +228,15 @@ test "bit field access" { assert(data.b == 3); } -fn getA(data: &const BitField1) u3 { +fn getA(data: *const BitField1) u3 { return data.a; } -fn getB(data: &const BitField1) u3 { +fn getB(data: *const BitField1) u3 { return data.b; } -fn getC(data: &const BitField1) u2 { +fn getC(data: *const BitField1) u2 { return data.c; } @@ -396,8 +396,8 @@ const Bitfields = packed struct { test "native bit field understands endianness" { var all: u64 = 0x7765443322221111; var bytes: [8]u8 = undefined; - @memcpy(&bytes[0], @ptrCast(&u8, &all), 8); - var bitfields = @ptrCast(&Bitfields, &bytes[0]).*; + @memcpy(&bytes[0], @ptrCast(*u8, &all), 8); + var bitfields = @ptrCast(*Bitfields, &bytes[0]).*; assert(bitfields.f1 == 0x1111); assert(bitfields.f2 == 0x2222); @@ -415,7 +415,7 @@ test "align 1 field before self referential align 8 field as slice return type" const Expr = union(enum) { Literal: u8, - Question: &Expr, + Question: *Expr, }; fn alloc(comptime T: type) []T { diff --git a/test/cases/struct_contains_null_ptr_itself.zig b/test/cases/struct_contains_null_ptr_itself.zig index b6cb1a94cc..21175974b3 100644 --- a/test/cases/struct_contains_null_ptr_itself.zig +++ b/test/cases/struct_contains_null_ptr_itself.zig @@ -2,13 +2,13 @@ const std = @import("std"); const assert = std.debug.assert; test "struct contains null pointer which contains original struct" { - var x: ?&NodeLineComment = null; + var x: ?*NodeLineComment = null; assert(x == null); } pub const Node = struct { id: Id, - comment: ?&NodeLineComment, + comment: ?*NodeLineComment, pub const Id = enum { Root, diff --git a/test/cases/switch.zig b/test/cases/switch.zig index 495fa9f3ed..c6a4b60f09 100644 --- a/test/cases/switch.zig +++ b/test/cases/switch.zig @@ -90,7 +90,7 @@ const SwitchProngWithVarEnum = union(enum) { Two: f32, Meh: void, }; -fn switchProngWithVarFn(a: &const SwitchProngWithVarEnum) void { +fn switchProngWithVarFn(a: *const SwitchProngWithVarEnum) void { switch (a.*) { SwitchProngWithVarEnum.One => |x| { assert(x == 13); diff --git a/test/cases/this.zig b/test/cases/this.zig index 5e433b5037..ba51d0ac90 100644 --- a/test/cases/this.zig +++ b/test/cases/this.zig @@ -8,7 +8,7 @@ fn Point(comptime T: type) type { x: T, y: T, - fn addOne(self: &Self) void { + fn addOne(self: *Self) void { self.x += 1; self.y += 1; } diff --git a/test/cases/type_info.zig b/test/cases/type_info.zig index 2561d70865..921ff785a7 100644 --- a/test/cases/type_info.zig +++ b/test/cases/type_info.zig @@ -37,7 +37,7 @@ test "type info: pointer type info" { } fn testPointer() void { - const u32_ptr_info = @typeInfo(&u32); + const u32_ptr_info = @typeInfo(*u32); assert(TypeId(u32_ptr_info) == TypeId.Pointer); assert(u32_ptr_info.Pointer.is_const == false); assert(u32_ptr_info.Pointer.is_volatile == false); @@ -169,14 +169,14 @@ fn testUnion() void { assert(notag_union_info.Union.fields[1].field_type == u32); const TestExternUnion = extern union { - foo: &c_void, + foo: *c_void, }; const extern_union_info = @typeInfo(TestExternUnion); assert(extern_union_info.Union.layout == TypeInfo.ContainerLayout.Extern); assert(extern_union_info.Union.tag_type == @typeOf(undefined)); assert(extern_union_info.Union.fields[0].enum_field == null); - assert(extern_union_info.Union.fields[0].field_type == &c_void); + assert(extern_union_info.Union.fields[0].field_type == *c_void); } test "type info: struct info" { @@ -190,13 +190,13 @@ fn testStruct() void { assert(struct_info.Struct.layout == TypeInfo.ContainerLayout.Packed); assert(struct_info.Struct.fields.len == 3); assert(struct_info.Struct.fields[1].offset == null); - assert(struct_info.Struct.fields[2].field_type == &TestStruct); + assert(struct_info.Struct.fields[2].field_type == *TestStruct); assert(struct_info.Struct.defs.len == 2); assert(struct_info.Struct.defs[0].is_pub); assert(!struct_info.Struct.defs[0].data.Fn.is_extern); assert(struct_info.Struct.defs[0].data.Fn.lib_name == null); assert(struct_info.Struct.defs[0].data.Fn.return_type == void); - assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn (&const TestStruct) void); + assert(struct_info.Struct.defs[0].data.Fn.fn_type == fn (*const TestStruct) void); } const TestStruct = packed struct { @@ -204,9 +204,9 @@ const TestStruct = packed struct { fieldA: usize, fieldB: void, - fieldC: &Self, + fieldC: *Self, - pub fn foo(self: &const Self) void {} + pub fn foo(self: *const Self) void {} }; test "type info: function type info" { @@ -227,7 +227,7 @@ fn testFunction() void { const test_instance: TestStruct = undefined; const bound_fn_info = @typeInfo(@typeOf(test_instance.foo)); assert(TypeId(bound_fn_info) == TypeId.BoundFn); - assert(bound_fn_info.BoundFn.args[0].arg_type == &const TestStruct); + assert(bound_fn_info.BoundFn.args[0].arg_type == *const TestStruct); } fn foo(comptime a: usize, b: bool, args: ...) usize { diff --git a/test/cases/undefined.zig b/test/cases/undefined.zig index f1af10e532..83c620d211 100644 --- a/test/cases/undefined.zig +++ b/test/cases/undefined.zig @@ -27,12 +27,12 @@ test "init static array to undefined" { const Foo = struct { x: i32, - fn setFooXMethod(foo: &Foo) void { + fn setFooXMethod(foo: *Foo) void { foo.x = 3; } }; -fn setFooX(foo: &Foo) void { +fn setFooX(foo: *Foo) void { foo.x = 2; } diff --git a/test/cases/union.zig b/test/cases/union.zig index 005ad08e6a..bdcbbdb452 100644 --- a/test/cases/union.zig +++ b/test/cases/union.zig @@ -68,11 +68,11 @@ test "init union with runtime value" { assert(foo.int == 42); } -fn setFloat(foo: &Foo, x: f64) void { +fn setFloat(foo: *Foo, x: f64) void { foo.* = Foo{ .float = x }; } -fn setInt(foo: &Foo, x: i32) void { +fn setInt(foo: *Foo, x: i32) void { foo.* = Foo{ .int = x }; } @@ -108,7 +108,7 @@ fn doTest() void { assert(bar(Payload{ .A = 1234 }) == -10); } -fn bar(value: &const Payload) i32 { +fn bar(value: *const Payload) i32 { assert(Letter(value.*) == Letter.A); return switch (value.*) { Payload.A => |x| return x - 1244, @@ -147,7 +147,7 @@ test "union(enum(u32)) with specified and unspecified tag values" { comptime testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2{ .C = 123 }); } -fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: &const MultipleChoice2) void { +fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: *const MultipleChoice2) void { assert(u32(@TagType(MultipleChoice2)(x.*)) == 60); assert(1123 == switch (x.*) { MultipleChoice2.A => 1, @@ -163,7 +163,7 @@ fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: &const MultipleChoice2) void } const ExternPtrOrInt = extern union { - ptr: &u8, + ptr: *u8, int: u64, }; test "extern union size" { @@ -171,7 +171,7 @@ test "extern union size" { } const PackedPtrOrInt = packed union { - ptr: &u8, + ptr: *u8, int: u64, }; test "extern union size" { @@ -206,7 +206,7 @@ test "cast union to tag type of union" { comptime testCastUnionToTagType(TheUnion{ .B = 1234 }); } -fn testCastUnionToTagType(x: &const TheUnion) void { +fn testCastUnionToTagType(x: *const TheUnion) void { assert(TheTag(x.*) == TheTag.B); } @@ -243,7 +243,7 @@ const TheUnion2 = union(enum) { Item2: i32, }; -fn assertIsTheUnion2Item1(value: &const TheUnion2) void { +fn assertIsTheUnion2Item1(value: *const TheUnion2) void { assert(value.* == TheUnion2.Item1); } diff --git a/test/compare_output.zig b/test/compare_output.zig index 0170477b8b..00ad4a709b 100644 --- a/test/compare_output.zig +++ b/test/compare_output.zig @@ -3,10 +3,10 @@ const std = @import("std"); const os = std.os; const tests = @import("tests.zig"); -pub fn addCases(cases: &tests.CompareOutputContext) void { +pub fn addCases(cases: *tests.CompareOutputContext) void { cases.addC("hello world with libc", \\const c = @cImport(@cInclude("stdio.h")); - \\export fn main(argc: c_int, argv: &&u8) c_int { + \\export fn main(argc: c_int, argv: **u8) c_int { \\ _ = c.puts(c"Hello, world!"); \\ return 0; \\} @@ -139,7 +139,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void { \\ @cInclude("stdio.h"); \\}); \\ - \\export fn main(argc: c_int, argv: &&u8) c_int { + \\export fn main(argc: c_int, argv: **u8) c_int { \\ if (is_windows) { \\ // we want actual \n, not \r\n \\ _ = c._setmode(1, c._O_BINARY); @@ -284,9 +284,9 @@ pub fn addCases(cases: &tests.CompareOutputContext) void { cases.addC("expose function pointer to C land", \\const c = @cImport(@cInclude("stdlib.h")); \\ - \\export fn compare_fn(a: ?&const c_void, b: ?&const c_void) c_int { - \\ const a_int = @ptrCast(&align(1) const i32, a ?? unreachable); - \\ const b_int = @ptrCast(&align(1) const i32, b ?? unreachable); + \\export fn compare_fn(a: ?*const c_void, b: ?*const c_void) c_int { + \\ const a_int = @ptrCast(*align(1) const i32, a ?? unreachable); + \\ const b_int = @ptrCast(*align(1) const i32, b ?? unreachable); \\ if (a_int.* < b_int.*) { \\ return -1; \\ } else if (a_int.* > b_int.*) { @@ -299,7 +299,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void { \\export fn main() c_int { \\ var array = []u32 { 1, 7, 3, 2, 0, 9, 4, 8, 6, 5 }; \\ - \\ c.qsort(@ptrCast(&c_void, &array[0]), c_ulong(array.len), @sizeOf(i32), compare_fn); + \\ c.qsort(@ptrCast(*c_void, &array[0]), c_ulong(array.len), @sizeOf(i32), compare_fn); \\ \\ for (array) |item, i| { \\ if (item != i) { @@ -324,7 +324,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) void { \\ @cInclude("stdio.h"); \\}); \\ - \\export fn main(argc: c_int, argv: &&u8) c_int { + \\export fn main(argc: c_int, argv: **u8) c_int { \\ if (is_windows) { \\ // we want actual \n, not \r\n \\ _ = c._setmode(1, c._O_BINARY); @@ -344,13 +344,13 @@ pub fn addCases(cases: &tests.CompareOutputContext) void { \\const Foo = struct { \\ field1: Bar, \\ - \\ fn method(a: &const Foo) bool { return true; } + \\ fn method(a: *const Foo) bool { return true; } \\}; \\ \\const Bar = struct { \\ field2: i32, \\ - \\ fn method(b: &const Bar) bool { return true; } + \\ fn method(b: *const Bar) bool { return true; } \\}; \\ \\pub fn main() void { diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 5215953d0a..1297ed29ab 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -1,6 +1,6 @@ const tests = @import("tests.zig"); -pub fn addCases(cases: &tests.CompileErrorContext) void { +pub fn addCases(cases: *tests.CompileErrorContext) void { cases.add( "invalid deref on switch target", \\comptime { @@ -109,7 +109,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { "@ptrCast discards const qualifier", \\export fn entry() void { \\ const x: i32 = 1234; - \\ const y = @ptrCast(&i32, &x); + \\ const y = @ptrCast(*i32, &x); \\} , ".tmp_source.zig:3:15: error: cast discards const qualifier", @@ -118,7 +118,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "comptime slice of undefined pointer non-zero len", \\export fn entry() void { - \\ const slice = (&i32)(undefined)[0..1]; + \\ const slice = (*i32)(undefined)[0..1]; \\} , ".tmp_source.zig:2:36: error: non-zero length slice of undefined pointer", @@ -126,7 +126,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "type checking function pointers", - \\fn a(b: fn (&const u8) void) void { + \\fn a(b: fn (*const u8) void) void { \\ b('a'); \\} \\fn c(d: u8) void { @@ -136,7 +136,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ a(c); \\} , - ".tmp_source.zig:8:7: error: expected type 'fn(&const u8) void', found 'fn(u8) void'", + ".tmp_source.zig:8:7: error: expected type 'fn(*const u8) void', found 'fn(u8) void'", ); cases.add( @@ -594,15 +594,15 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "attempt to use 0 bit type in extern fn", - \\extern fn foo(ptr: extern fn(&void) void) void; + \\extern fn foo(ptr: extern fn(*void) void) void; \\ \\export fn entry() void { \\ foo(bar); \\} \\ - \\extern fn bar(x: &void) void { } + \\extern fn bar(x: *void) void { } , - ".tmp_source.zig:7:18: error: parameter of type '&void' has 0 bits; not allowed in function with calling convention 'ccc'", + ".tmp_source.zig:7:18: error: parameter of type '*void' has 0 bits; not allowed in function with calling convention 'ccc'", ); cases.add( @@ -911,10 +911,10 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "pointer to noreturn", - \\fn a() &noreturn {} + \\fn a() *noreturn {} \\export fn entry() void { _ = a(); } , - ".tmp_source.zig:1:9: error: pointer to noreturn not allowed", + ".tmp_source.zig:1:8: error: pointer to noreturn not allowed", ); cases.add( @@ -985,7 +985,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ return a; \\} , - ".tmp_source.zig:3:12: error: expected type 'i32', found '&const u8'", + ".tmp_source.zig:3:12: error: expected type 'i32', found '*const u8'", ); cases.add( @@ -1446,7 +1446,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "switch expression - switch on pointer type with no else", - \\fn foo(x: &u8) void { + \\fn foo(x: *u8) void { \\ switch (x) { \\ &y => {}, \\ } @@ -1454,7 +1454,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\const y: u8 = 100; \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , - ".tmp_source.zig:2:5: error: else prong required when switching on type '&u8'", + ".tmp_source.zig:2:5: error: else prong required when switching on type '*u8'", ); cases.add( @@ -1501,10 +1501,10 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { "address of number literal", \\const x = 3; \\const y = &x; - \\fn foo() &const i32 { return y; } + \\fn foo() *const i32 { return y; } \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , - ".tmp_source.zig:3:30: error: expected type '&const i32', found '&const (integer literal)'", + ".tmp_source.zig:3:30: error: expected type '*const i32', found '*const (integer literal)'", ); cases.add( @@ -1529,10 +1529,10 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ a: i32, \\ b: i32, \\ - \\ fn member_a(foo: &const Foo) i32 { + \\ fn member_a(foo: *const Foo) i32 { \\ return foo.a; \\ } - \\ fn member_b(foo: &const Foo) i32 { + \\ fn member_b(foo: *const Foo) i32 { \\ return foo.b; \\ } \\}; @@ -1543,7 +1543,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ Foo.member_b, \\}; \\ - \\fn f(foo: &const Foo, index: usize) void { + \\fn f(foo: *const Foo, index: usize) void { \\ const result = members[index](); \\} \\ @@ -1692,11 +1692,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "assign null to non-nullable pointer", - \\const a: &u8 = null; + \\const a: *u8 = null; \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } , - ".tmp_source.zig:1:16: error: expected type '&u8', found '(null)'", + ".tmp_source.zig:1:16: error: expected type '*u8', found '(null)'", ); cases.add( @@ -1806,7 +1806,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ One: void, \\ Two: i32, \\}; - \\fn bad_eql_2(a: &const EnumWithData, b: &const EnumWithData) bool { + \\fn bad_eql_2(a: *const EnumWithData, b: *const EnumWithData) bool { \\ return a.* == b.*; \\} \\ @@ -2011,9 +2011,9 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "wrong number of arguments for method fn call", \\const Foo = struct { - \\ fn method(self: &const Foo, a: i32) void {} + \\ fn method(self: *const Foo, a: i32) void {} \\}; - \\fn f(foo: &const Foo) void { + \\fn f(foo: *const Foo) void { \\ \\ foo.method(1, 2); \\} @@ -2062,7 +2062,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "misspelled type with pointer only reference", \\const JasonHM = u8; - \\const JasonList = &JsonNode; + \\const JasonList = *JsonNode; \\ \\const JsonOA = union(enum) { \\ JSONArray: JsonList, @@ -2113,16 +2113,16 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ derp.init(); \\} , - ".tmp_source.zig:14:5: error: expected type 'i32', found '&const Foo'", + ".tmp_source.zig:14:5: error: expected type 'i32', found '*const Foo'", ); cases.add( "method call with first arg type wrong container", \\pub const List = struct { \\ len: usize, - \\ allocator: &Allocator, + \\ allocator: *Allocator, \\ - \\ pub fn init(allocator: &Allocator) List { + \\ pub fn init(allocator: *Allocator) List { \\ return List { \\ .len = 0, \\ .allocator = allocator, @@ -2143,7 +2143,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ x.init(); \\} , - ".tmp_source.zig:23:5: error: expected type '&Allocator', found '&List'", + ".tmp_source.zig:23:5: error: expected type '*Allocator', found '*List'", ); cases.add( @@ -2308,17 +2308,17 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ c: u2, \\}; \\ - \\fn foo(bit_field: &const BitField) u3 { + \\fn foo(bit_field: *const BitField) u3 { \\ return bar(&bit_field.b); \\} \\ - \\fn bar(x: &const u3) u3 { + \\fn bar(x: *const u3) u3 { \\ return x.*; \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , - ".tmp_source.zig:8:26: error: expected type '&const u3', found '&align(1:3:6) const u3'", + ".tmp_source.zig:8:26: error: expected type '*const u3', found '*align(1:3:6) const u3'", ); cases.add( @@ -2441,13 +2441,13 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const b = &a; \\ return ptrEql(b, b); \\} - \\fn ptrEql(a: &[]const u8, b: &[]const u8) bool { + \\fn ptrEql(a: *[]const u8, b: *[]const u8) bool { \\ return true; \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , - ".tmp_source.zig:4:19: error: expected type '&[]const u8', found '&const []const u8'", + ".tmp_source.zig:4:19: error: expected type '*[]const u8', found '*const []const u8'", ); cases.addCase(x: { @@ -2493,7 +2493,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "ptrcast to non-pointer", - \\export fn entry(a: &i32) usize { + \\export fn entry(a: *i32) usize { \\ return @ptrCast(usize, a); \\} , @@ -2542,16 +2542,16 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { "int to ptr of 0 bits", \\export fn foo() void { \\ var x: usize = 0x1000; - \\ var y: &void = @intToPtr(&void, x); + \\ var y: *void = @intToPtr(*void, x); \\} , - ".tmp_source.zig:3:31: error: type '&void' has 0 bits and cannot store information", + ".tmp_source.zig:3:30: error: type '*void' has 0 bits and cannot store information", ); cases.add( "@fieldParentPtr - non struct", \\const Foo = i32; - \\export fn foo(a: &i32) &Foo { + \\export fn foo(a: *i32) *Foo { \\ return @fieldParentPtr(Foo, "a", a); \\} , @@ -2563,7 +2563,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\const Foo = extern struct { \\ derp: i32, \\}; - \\export fn foo(a: &i32) &Foo { + \\export fn foo(a: *i32) *Foo { \\ return @fieldParentPtr(Foo, "a", a); \\} , @@ -2575,7 +2575,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\const Foo = extern struct { \\ a: i32, \\}; - \\export fn foo(a: i32) &Foo { + \\export fn foo(a: i32) *Foo { \\ return @fieldParentPtr(Foo, "a", a); \\} , @@ -2591,7 +2591,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\const foo = Foo { .a = 1, .b = 2, }; \\ \\comptime { - \\ const field_ptr = @intToPtr(&i32, 0x1234); + \\ const field_ptr = @intToPtr(*i32, 0x1234); \\ const another_foo_ptr = @fieldParentPtr(Foo, "b", field_ptr); \\} , @@ -2682,7 +2682,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "returning address of local variable - simple", - \\export fn foo() &i32 { + \\export fn foo() *i32 { \\ var a: i32 = undefined; \\ return &a; \\} @@ -2692,7 +2692,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "returning address of local variable - phi", - \\export fn foo(c: bool) &i32 { + \\export fn foo(c: bool) *i32 { \\ var a: i32 = undefined; \\ var b: i32 = undefined; \\ return if (c) &a else &b; @@ -3086,11 +3086,11 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ bar(&foo.b); \\} \\ - \\fn bar(x: &u32) void { + \\fn bar(x: *u32) void { \\ x.* += 1; \\} , - ".tmp_source.zig:8:13: error: expected type '&u32', found '&align(1) u32'", + ".tmp_source.zig:8:13: error: expected type '*u32', found '*align(1) u32'", ); cases.add( @@ -3117,13 +3117,13 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { "increase pointer alignment in @ptrCast", \\export fn entry() u32 { \\ var bytes: [4]u8 = []u8{0x01, 0x02, 0x03, 0x04}; - \\ const ptr = @ptrCast(&u32, &bytes[0]); + \\ const ptr = @ptrCast(*u32, &bytes[0]); \\ return ptr.*; \\} , ".tmp_source.zig:3:17: error: cast increases pointer alignment", - ".tmp_source.zig:3:38: note: '&u8' has alignment 1", - ".tmp_source.zig:3:27: note: '&u32' has alignment 4", + ".tmp_source.zig:3:38: note: '*u8' has alignment 1", + ".tmp_source.zig:3:26: note: '*u32' has alignment 4", ); cases.add( @@ -3169,7 +3169,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ return x == 5678; \\} , - ".tmp_source.zig:4:32: error: expected type '&i32', found '&align(1) i32'", + ".tmp_source.zig:4:32: error: expected type '*i32', found '*align(1) i32'", ); cases.add( @@ -3198,20 +3198,20 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { cases.add( "wrong pointer implicitly casted to pointer to @OpaqueType()", \\const Derp = @OpaqueType(); - \\extern fn bar(d: &Derp) void; + \\extern fn bar(d: *Derp) void; \\export fn foo() void { \\ var x = u8(1); - \\ bar(@ptrCast(&c_void, &x)); + \\ bar(@ptrCast(*c_void, &x)); \\} , - ".tmp_source.zig:5:9: error: expected type '&Derp', found '&c_void'", + ".tmp_source.zig:5:9: error: expected type '*Derp', found '*c_void'", ); cases.add( "non-const variables of things that require const variables", \\const Opaque = @OpaqueType(); \\ - \\export fn entry(opaque: &Opaque) void { + \\export fn entry(opaque: *Opaque) void { \\ var m2 = &2; \\ const y: u32 = m2.*; \\ @@ -3229,10 +3229,10 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\} \\ \\const Foo = struct { - \\ fn bar(self: &const Foo) void {} + \\ fn bar(self: *const Foo) void {} \\}; , - ".tmp_source.zig:4:4: error: variable of type '&const (integer literal)' must be const or comptime", + ".tmp_source.zig:4:4: error: variable of type '*const (integer literal)' must be const or comptime", ".tmp_source.zig:7:4: error: variable of type '(undefined)' must be const or comptime", ".tmp_source.zig:8:4: error: variable of type '(integer literal)' must be const or comptime", ".tmp_source.zig:9:4: error: variable of type '(float literal)' must be const or comptime", @@ -3241,7 +3241,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { ".tmp_source.zig:12:4: error: variable of type 'Opaque' must be const or comptime", ".tmp_source.zig:13:4: error: variable of type 'type' must be const or comptime", ".tmp_source.zig:14:4: error: variable of type '(namespace)' must be const or comptime", - ".tmp_source.zig:15:4: error: variable of type '(bound fn(&const Foo) void)' must be const or comptime", + ".tmp_source.zig:15:4: error: variable of type '(bound fn(*const Foo) void)' must be const or comptime", ".tmp_source.zig:17:4: error: unreachable code", ); @@ -3397,14 +3397,14 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ \\export fn entry() bool { \\ var x: i32 = 1; - \\ return bar(@ptrCast(&MyType, &x)); + \\ return bar(@ptrCast(*MyType, &x)); \\} \\ - \\fn bar(x: &MyType) bool { + \\fn bar(x: *MyType) bool { \\ return x.blah; \\} , - ".tmp_source.zig:9:13: error: type '&MyType' does not support field access", + ".tmp_source.zig:9:13: error: type '*MyType' does not support field access", ); cases.add( @@ -3535,9 +3535,9 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\export fn entry() void { \\ foo("hello",); \\} - \\pub extern fn foo(format: &const u8, ...) void; + \\pub extern fn foo(format: *const u8, ...) void; , - ".tmp_source.zig:2:9: error: expected type '&const u8', found '[5]u8'", + ".tmp_source.zig:2:9: error: expected type '*const u8', found '[5]u8'", ); cases.add( @@ -3902,7 +3902,7 @@ pub fn addCases(cases: &tests.CompileErrorContext) void { \\ const a = Payload { .A = 1234 }; \\ foo(a); \\} - \\fn foo(a: &const Payload) void { + \\fn foo(a: *const Payload) void { \\ switch (a.*) { \\ Payload.A => {}, \\ else => unreachable, diff --git a/test/gen_h.zig b/test/gen_h.zig index 2def39bed7..9559c3395c 100644 --- a/test/gen_h.zig +++ b/test/gen_h.zig @@ -1,6 +1,6 @@ const tests = @import("tests.zig"); -pub fn addCases(cases: &tests.GenHContext) void { +pub fn addCases(cases: *tests.GenHContext) void { cases.add("declare enum", \\const Foo = extern enum { A, B, C }; \\export fn entry(foo: Foo) void { } diff --git a/test/runtime_safety.zig b/test/runtime_safety.zig index 1fea6347ab..71d1d68764 100644 --- a/test/runtime_safety.zig +++ b/test/runtime_safety.zig @@ -1,6 +1,6 @@ const tests = @import("tests.zig"); -pub fn addCases(cases: &tests.CompareOutputContext) void { +pub fn addCases(cases: *tests.CompareOutputContext) void { cases.addRuntimeSafety("calling panic", \\pub fn panic(message: []const u8, stack_trace: ?&@import("builtin").StackTrace) noreturn { \\ @import("std").os.exit(126); diff --git a/test/standalone/brace_expansion/build.zig b/test/standalone/brace_expansion/build.zig index 7752f599df..64f3c08583 100644 --- a/test/standalone/brace_expansion/build.zig +++ b/test/standalone/brace_expansion/build.zig @@ -1,6 +1,6 @@ const Builder = @import("std").build.Builder; -pub fn build(b: &Builder) void { +pub fn build(b: *Builder) void { const main = b.addTest("main.zig"); main.setBuildMode(b.standardReleaseOptions()); diff --git a/test/standalone/brace_expansion/main.zig b/test/standalone/brace_expansion/main.zig index c96cc2cbb9..ccb4f6dd45 100644 --- a/test/standalone/brace_expansion/main.zig +++ b/test/standalone/brace_expansion/main.zig @@ -14,7 +14,7 @@ const Token = union(enum) { Eof, }; -var global_allocator: &mem.Allocator = undefined; +var global_allocator: *mem.Allocator = undefined; fn tokenize(input: []const u8) !ArrayList(Token) { const State = enum { @@ -73,7 +73,7 @@ const ParseError = error{ OutOfMemory, }; -fn parse(tokens: &const ArrayList(Token), token_index: &usize) ParseError!Node { +fn parse(tokens: *const ArrayList(Token), token_index: *usize) ParseError!Node { const first_token = tokens.items[token_index.*]; token_index.* += 1; @@ -109,7 +109,7 @@ fn parse(tokens: &const ArrayList(Token), token_index: &usize) ParseError!Node { } } -fn expandString(input: []const u8, output: &Buffer) !void { +fn expandString(input: []const u8, output: *Buffer) !void { const tokens = try tokenize(input); if (tokens.len == 1) { return output.resize(0); @@ -139,7 +139,7 @@ fn expandString(input: []const u8, output: &Buffer) !void { const ExpandNodeError = error{OutOfMemory}; -fn expandNode(node: &const Node, output: &ArrayList(Buffer)) ExpandNodeError!void { +fn expandNode(node: *const Node, output: *ArrayList(Buffer)) ExpandNodeError!void { assert(output.len == 0); switch (node.*) { Node.Scalar => |scalar| { diff --git a/test/standalone/issue_339/build.zig b/test/standalone/issue_339/build.zig index f3ab327006..733b3729c1 100644 --- a/test/standalone/issue_339/build.zig +++ b/test/standalone/issue_339/build.zig @@ -1,6 +1,6 @@ const Builder = @import("std").build.Builder; -pub fn build(b: &Builder) void { +pub fn build(b: *Builder) void { const obj = b.addObject("test", "test.zig"); const test_step = b.step("test", "Test the program"); diff --git a/test/standalone/issue_339/test.zig b/test/standalone/issue_339/test.zig index da0747b8e6..f4068dcfac 100644 --- a/test/standalone/issue_339/test.zig +++ b/test/standalone/issue_339/test.zig @@ -1,5 +1,5 @@ const StackTrace = @import("builtin").StackTrace; -pub fn panic(msg: []const u8, stack_trace: ?&StackTrace) noreturn { +pub fn panic(msg: []const u8, stack_trace: ?*StackTrace) noreturn { @breakpoint(); while (true) {} } diff --git a/test/standalone/issue_794/build.zig b/test/standalone/issue_794/build.zig index 4f5dcd7ff4..06c37a83a3 100644 --- a/test/standalone/issue_794/build.zig +++ b/test/standalone/issue_794/build.zig @@ -1,6 +1,6 @@ const Builder = @import("std").build.Builder; -pub fn build(b: &Builder) void { +pub fn build(b: *Builder) void { const test_artifact = b.addTest("main.zig"); test_artifact.addIncludeDir("a_directory"); diff --git a/test/standalone/pkg_import/build.zig b/test/standalone/pkg_import/build.zig index bb9416d3c4..e0b3885dc3 100644 --- a/test/standalone/pkg_import/build.zig +++ b/test/standalone/pkg_import/build.zig @@ -1,6 +1,6 @@ const Builder = @import("std").build.Builder; -pub fn build(b: &Builder) void { +pub fn build(b: *Builder) void { const exe = b.addExecutable("test", "test.zig"); exe.addPackagePath("my_pkg", "pkg.zig"); diff --git a/test/standalone/use_alias/build.zig b/test/standalone/use_alias/build.zig index ecbba297d8..c700d43db9 100644 --- a/test/standalone/use_alias/build.zig +++ b/test/standalone/use_alias/build.zig @@ -1,6 +1,6 @@ const Builder = @import("std").build.Builder; -pub fn build(b: &Builder) void { +pub fn build(b: *Builder) void { b.addCIncludePath("."); const main = b.addTest("main.zig"); diff --git a/test/tests.zig b/test/tests.zig index b59b954122..cc562331fe 100644 --- a/test/tests.zig +++ b/test/tests.zig @@ -47,7 +47,7 @@ const test_targets = []TestTarget{ const max_stdout_size = 1 * 1024 * 1024; // 1 MB -pub fn addCompareOutputTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { +pub fn addCompareOutputTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step { const cases = b.allocator.create(CompareOutputContext) catch unreachable; cases.* = CompareOutputContext{ .b = b, @@ -61,7 +61,7 @@ pub fn addCompareOutputTests(b: &build.Builder, test_filter: ?[]const u8) &build return cases.step; } -pub fn addRuntimeSafetyTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { +pub fn addRuntimeSafetyTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step { const cases = b.allocator.create(CompareOutputContext) catch unreachable; cases.* = CompareOutputContext{ .b = b, @@ -75,7 +75,7 @@ pub fn addRuntimeSafetyTests(b: &build.Builder, test_filter: ?[]const u8) &build return cases.step; } -pub fn addCompileErrorTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { +pub fn addCompileErrorTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step { const cases = b.allocator.create(CompileErrorContext) catch unreachable; cases.* = CompileErrorContext{ .b = b, @@ -89,7 +89,7 @@ pub fn addCompileErrorTests(b: &build.Builder, test_filter: ?[]const u8) &build. return cases.step; } -pub fn addBuildExampleTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { +pub fn addBuildExampleTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step { const cases = b.allocator.create(BuildExamplesContext) catch unreachable; cases.* = BuildExamplesContext{ .b = b, @@ -103,7 +103,7 @@ pub fn addBuildExampleTests(b: &build.Builder, test_filter: ?[]const u8) &build. return cases.step; } -pub fn addAssembleAndLinkTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { +pub fn addAssembleAndLinkTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step { const cases = b.allocator.create(CompareOutputContext) catch unreachable; cases.* = CompareOutputContext{ .b = b, @@ -117,7 +117,7 @@ pub fn addAssembleAndLinkTests(b: &build.Builder, test_filter: ?[]const u8) &bui return cases.step; } -pub fn addTranslateCTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { +pub fn addTranslateCTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step { const cases = b.allocator.create(TranslateCContext) catch unreachable; cases.* = TranslateCContext{ .b = b, @@ -131,7 +131,7 @@ pub fn addTranslateCTests(b: &build.Builder, test_filter: ?[]const u8) &build.St return cases.step; } -pub fn addGenHTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { +pub fn addGenHTests(b: *build.Builder, test_filter: ?[]const u8) *build.Step { const cases = b.allocator.create(GenHContext) catch unreachable; cases.* = GenHContext{ .b = b, @@ -145,7 +145,7 @@ pub fn addGenHTests(b: &build.Builder, test_filter: ?[]const u8) &build.Step { return cases.step; } -pub fn addPkgTests(b: &build.Builder, test_filter: ?[]const u8, root_src: []const u8, name: []const u8, desc: []const u8, with_lldb: bool) &build.Step { +pub fn addPkgTests(b: *build.Builder, test_filter: ?[]const u8, root_src: []const u8, name: []const u8, desc: []const u8, with_lldb: bool) *build.Step { const step = b.step(b.fmt("test-{}", name), desc); for (test_targets) |test_target| { 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 } pub const CompareOutputContext = struct { - b: &build.Builder, - step: &build.Step, + b: *build.Builder, + step: *build.Step, test_index: usize, test_filter: ?[]const u8, @@ -217,28 +217,28 @@ pub const CompareOutputContext = struct { source: []const u8, }; - pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void { + pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void { self.sources.append(SourceFile{ .filename = filename, .source = source, }) catch unreachable; } - pub fn setCommandLineArgs(self: &TestCase, args: []const []const u8) void { + pub fn setCommandLineArgs(self: *TestCase, args: []const []const u8) void { self.cli_args = args; } }; const RunCompareOutputStep = struct { step: build.Step, - context: &CompareOutputContext, + context: *CompareOutputContext, exe_path: []const u8, name: []const u8, expected_output: []const u8, test_index: usize, cli_args: []const []const u8, - pub fn create(context: &CompareOutputContext, exe_path: []const u8, name: []const u8, expected_output: []const u8, cli_args: []const []const u8) &RunCompareOutputStep { + pub fn create(context: *CompareOutputContext, exe_path: []const u8, name: []const u8, expected_output: []const u8, cli_args: []const []const u8) *RunCompareOutputStep { const allocator = context.b.allocator; const ptr = allocator.create(RunCompareOutputStep) catch unreachable; ptr.* = RunCompareOutputStep{ @@ -254,7 +254,7 @@ pub const CompareOutputContext = struct { return ptr; } - fn make(step: &build.Step) !void { + fn make(step: *build.Step) !void { const self = @fieldParentPtr(RunCompareOutputStep, "step", step); const b = self.context.b; @@ -321,12 +321,12 @@ pub const CompareOutputContext = struct { const RuntimeSafetyRunStep = struct { step: build.Step, - context: &CompareOutputContext, + context: *CompareOutputContext, exe_path: []const u8, name: []const u8, test_index: usize, - pub fn create(context: &CompareOutputContext, exe_path: []const u8, name: []const u8) &RuntimeSafetyRunStep { + pub fn create(context: *CompareOutputContext, exe_path: []const u8, name: []const u8) *RuntimeSafetyRunStep { const allocator = context.b.allocator; const ptr = allocator.create(RuntimeSafetyRunStep) catch unreachable; ptr.* = RuntimeSafetyRunStep{ @@ -340,7 +340,7 @@ pub const CompareOutputContext = struct { return ptr; } - fn make(step: &build.Step) !void { + fn make(step: *build.Step) !void { const self = @fieldParentPtr(RuntimeSafetyRunStep, "step", step); const b = self.context.b; @@ -382,7 +382,7 @@ pub const CompareOutputContext = struct { } }; - pub fn createExtra(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8, special: Special) TestCase { + pub fn createExtra(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8, special: Special) TestCase { var tc = TestCase{ .name = name, .sources = ArrayList(TestCase.SourceFile).init(self.b.allocator), @@ -396,32 +396,32 @@ pub const CompareOutputContext = struct { return tc; } - pub fn create(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) TestCase { + pub fn create(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) TestCase { return createExtra(self, name, source, expected_output, Special.None); } - pub fn addC(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void { + pub fn addC(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void { var tc = self.create(name, source, expected_output); tc.link_libc = true; self.addCase(tc); } - pub fn add(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void { + pub fn add(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void { const tc = self.create(name, source, expected_output); self.addCase(tc); } - pub fn addAsm(self: &CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void { + pub fn addAsm(self: *CompareOutputContext, name: []const u8, source: []const u8, expected_output: []const u8) void { const tc = self.createExtra(name, source, expected_output, Special.Asm); self.addCase(tc); } - pub fn addRuntimeSafety(self: &CompareOutputContext, name: []const u8, source: []const u8) void { + pub fn addRuntimeSafety(self: *CompareOutputContext, name: []const u8, source: []const u8) void { const tc = self.createExtra(name, source, undefined, Special.RuntimeSafety); self.addCase(tc); } - pub fn addCase(self: &CompareOutputContext, case: &const TestCase) void { + pub fn addCase(self: *CompareOutputContext, case: *const TestCase) void { const b = self.b; 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 { }; pub const CompileErrorContext = struct { - b: &build.Builder, - step: &build.Step, + b: *build.Builder, + step: *build.Step, test_index: usize, test_filter: ?[]const u8, @@ -521,27 +521,27 @@ pub const CompileErrorContext = struct { source: []const u8, }; - pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void { + pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void { self.sources.append(SourceFile{ .filename = filename, .source = source, }) catch unreachable; } - pub fn addExpectedError(self: &TestCase, text: []const u8) void { + pub fn addExpectedError(self: *TestCase, text: []const u8) void { self.expected_errors.append(text) catch unreachable; } }; const CompileCmpOutputStep = struct { step: build.Step, - context: &CompileErrorContext, + context: *CompileErrorContext, name: []const u8, test_index: usize, - case: &const TestCase, + case: *const TestCase, build_mode: Mode, - pub fn create(context: &CompileErrorContext, name: []const u8, case: &const TestCase, build_mode: Mode) &CompileCmpOutputStep { + pub fn create(context: *CompileErrorContext, name: []const u8, case: *const TestCase, build_mode: Mode) *CompileCmpOutputStep { const allocator = context.b.allocator; const ptr = allocator.create(CompileCmpOutputStep) catch unreachable; ptr.* = CompileCmpOutputStep{ @@ -556,7 +556,7 @@ pub const CompileErrorContext = struct { return ptr; } - fn make(step: &build.Step) !void { + fn make(step: *build.Step) !void { const self = @fieldParentPtr(CompileCmpOutputStep, "step", step); const b = self.context.b; @@ -661,7 +661,7 @@ pub const CompileErrorContext = struct { warn("\n"); } - pub fn create(self: &CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) &TestCase { + pub fn create(self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) *TestCase { const tc = self.b.allocator.create(TestCase) catch unreachable; tc.* = TestCase{ .name = name, @@ -678,24 +678,24 @@ pub const CompileErrorContext = struct { return tc; } - pub fn addC(self: &CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void { + pub fn addC(self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void { var tc = self.create(name, source, expected_lines); tc.link_libc = true; self.addCase(tc); } - pub fn addExe(self: &CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void { + pub fn addExe(self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void { var tc = self.create(name, source, expected_lines); tc.is_exe = true; self.addCase(tc); } - pub fn add(self: &CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void { + pub fn add(self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: ...) void { const tc = self.create(name, source, expected_lines); self.addCase(tc); } - pub fn addCase(self: &CompileErrorContext, case: &const TestCase) void { + pub fn addCase(self: *CompileErrorContext, case: *const TestCase) void { const b = self.b; for ([]Mode{ @@ -720,20 +720,20 @@ pub const CompileErrorContext = struct { }; pub const BuildExamplesContext = struct { - b: &build.Builder, - step: &build.Step, + b: *build.Builder, + step: *build.Step, test_index: usize, test_filter: ?[]const u8, - pub fn addC(self: &BuildExamplesContext, root_src: []const u8) void { + pub fn addC(self: *BuildExamplesContext, root_src: []const u8) void { self.addAllArgs(root_src, true); } - pub fn add(self: &BuildExamplesContext, root_src: []const u8) void { + pub fn add(self: *BuildExamplesContext, root_src: []const u8) void { self.addAllArgs(root_src, false); } - pub fn addBuildFile(self: &BuildExamplesContext, build_file: []const u8) void { + pub fn addBuildFile(self: *BuildExamplesContext, build_file: []const u8) void { const b = self.b; const annotated_case_name = b.fmt("build {} (Debug)", build_file); @@ -763,7 +763,7 @@ pub const BuildExamplesContext = struct { self.step.dependOn(&log_step.step); } - pub fn addAllArgs(self: &BuildExamplesContext, root_src: []const u8, link_libc: bool) void { + pub fn addAllArgs(self: *BuildExamplesContext, root_src: []const u8, link_libc: bool) void { const b = self.b; for ([]Mode{ @@ -792,8 +792,8 @@ pub const BuildExamplesContext = struct { }; pub const TranslateCContext = struct { - b: &build.Builder, - step: &build.Step, + b: *build.Builder, + step: *build.Step, test_index: usize, test_filter: ?[]const u8, @@ -808,26 +808,26 @@ pub const TranslateCContext = struct { source: []const u8, }; - pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void { + pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void { self.sources.append(SourceFile{ .filename = filename, .source = source, }) catch unreachable; } - pub fn addExpectedLine(self: &TestCase, text: []const u8) void { + pub fn addExpectedLine(self: *TestCase, text: []const u8) void { self.expected_lines.append(text) catch unreachable; } }; const TranslateCCmpOutputStep = struct { step: build.Step, - context: &TranslateCContext, + context: *TranslateCContext, name: []const u8, test_index: usize, - case: &const TestCase, + case: *const TestCase, - pub fn create(context: &TranslateCContext, name: []const u8, case: &const TestCase) &TranslateCCmpOutputStep { + pub fn create(context: *TranslateCContext, name: []const u8, case: *const TestCase) *TranslateCCmpOutputStep { const allocator = context.b.allocator; const ptr = allocator.create(TranslateCCmpOutputStep) catch unreachable; ptr.* = TranslateCCmpOutputStep{ @@ -841,7 +841,7 @@ pub const TranslateCContext = struct { return ptr; } - fn make(step: &build.Step) !void { + fn make(step: *build.Step) !void { const self = @fieldParentPtr(TranslateCCmpOutputStep, "step", step); const b = self.context.b; @@ -935,7 +935,7 @@ pub const TranslateCContext = struct { warn("\n"); } - pub fn create(self: &TranslateCContext, allow_warnings: bool, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) &TestCase { + pub fn create(self: *TranslateCContext, allow_warnings: bool, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) *TestCase { const tc = self.b.allocator.create(TestCase) catch unreachable; tc.* = TestCase{ .name = name, @@ -951,22 +951,22 @@ pub const TranslateCContext = struct { return tc; } - pub fn add(self: &TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void { + pub fn add(self: *TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void { const tc = self.create(false, "source.h", name, source, expected_lines); self.addCase(tc); } - pub fn addC(self: &TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void { + pub fn addC(self: *TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void { const tc = self.create(false, "source.c", name, source, expected_lines); self.addCase(tc); } - pub fn addAllowWarnings(self: &TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void { + pub fn addAllowWarnings(self: *TranslateCContext, name: []const u8, source: []const u8, expected_lines: ...) void { const tc = self.create(true, "source.h", name, source, expected_lines); self.addCase(tc); } - pub fn addCase(self: &TranslateCContext, case: &const TestCase) void { + pub fn addCase(self: *TranslateCContext, case: *const TestCase) void { const b = self.b; const annotated_case_name = fmt.allocPrint(self.b.allocator, "translate-c {}", case.name) catch unreachable; @@ -986,8 +986,8 @@ pub const TranslateCContext = struct { }; pub const GenHContext = struct { - b: &build.Builder, - step: &build.Step, + b: *build.Builder, + step: *build.Step, test_index: usize, test_filter: ?[]const u8, @@ -1001,27 +1001,27 @@ pub const GenHContext = struct { source: []const u8, }; - pub fn addSourceFile(self: &TestCase, filename: []const u8, source: []const u8) void { + pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void { self.sources.append(SourceFile{ .filename = filename, .source = source, }) catch unreachable; } - pub fn addExpectedLine(self: &TestCase, text: []const u8) void { + pub fn addExpectedLine(self: *TestCase, text: []const u8) void { self.expected_lines.append(text) catch unreachable; } }; const GenHCmpOutputStep = struct { step: build.Step, - context: &GenHContext, + context: *GenHContext, h_path: []const u8, name: []const u8, test_index: usize, - case: &const TestCase, + case: *const TestCase, - pub fn create(context: &GenHContext, h_path: []const u8, name: []const u8, case: &const TestCase) &GenHCmpOutputStep { + pub fn create(context: *GenHContext, h_path: []const u8, name: []const u8, case: *const TestCase) *GenHCmpOutputStep { const allocator = context.b.allocator; const ptr = allocator.create(GenHCmpOutputStep) catch unreachable; ptr.* = GenHCmpOutputStep{ @@ -1036,7 +1036,7 @@ pub const GenHContext = struct { return ptr; } - fn make(step: &build.Step) !void { + fn make(step: *build.Step) !void { const self = @fieldParentPtr(GenHCmpOutputStep, "step", step); const b = self.context.b; @@ -1069,7 +1069,7 @@ pub const GenHContext = struct { warn("\n"); } - pub fn create(self: &GenHContext, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) &TestCase { + pub fn create(self: *GenHContext, filename: []const u8, name: []const u8, source: []const u8, expected_lines: ...) *TestCase { const tc = self.b.allocator.create(TestCase) catch unreachable; tc.* = TestCase{ .name = name, @@ -1084,12 +1084,12 @@ pub const GenHContext = struct { return tc; } - pub fn add(self: &GenHContext, name: []const u8, source: []const u8, expected_lines: ...) void { + pub fn add(self: *GenHContext, name: []const u8, source: []const u8, expected_lines: ...) void { const tc = self.create("test.zig", name, source, expected_lines); self.addCase(tc); } - pub fn addCase(self: &GenHContext, case: &const TestCase) void { + pub fn addCase(self: *GenHContext, case: *const TestCase) void { const b = self.b; const root_src = os.path.join(b.allocator, b.cache_root, case.sources.items[0].filename) catch unreachable; diff --git a/test/translate_c.zig b/test/translate_c.zig index 4cf1e047fa..9a07bc343d 100644 --- a/test/translate_c.zig +++ b/test/translate_c.zig @@ -1,6 +1,6 @@ const tests = @import("tests.zig"); -pub fn addCases(cases: &tests.TranslateCContext) void { +pub fn addCases(cases: *tests.TranslateCContext) void { cases.add("double define struct", \\typedef struct Bar Bar; \\typedef struct Foo Foo; @@ -14,11 +14,11 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\}; , \\pub const struct_Foo = extern struct { - \\ a: ?&Foo, + \\ a: ?*Foo, \\}; \\pub const Foo = struct_Foo; \\pub const struct_Bar = extern struct { - \\ a: ?&Foo, + \\ a: ?*Foo, \\}; ); @@ -99,7 +99,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { cases.add("restrict -> noalias", \\void foo(void *restrict bar, void *restrict); , - \\pub extern fn foo(noalias bar: ?&c_void, noalias arg1: ?&c_void) void; + \\pub extern fn foo(noalias bar: ?*c_void, noalias arg1: ?*c_void) void; ); cases.add("simple struct", @@ -110,7 +110,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { , \\const struct_Foo = extern struct { \\ x: c_int, - \\ y: ?&u8, + \\ y: ?*u8, \\}; , \\pub const Foo = struct_Foo; @@ -141,7 +141,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { , \\pub const BarB = enum_Bar.B; , - \\pub extern fn func(a: ?&struct_Foo, b: ?&(?&enum_Bar)) void; + \\pub extern fn func(a: ?*struct_Foo, b: ?*(?*enum_Bar)) void; , \\pub const Foo = struct_Foo; , @@ -151,7 +151,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { cases.add("constant size array", \\void func(int array[20]); , - \\pub extern fn func(array: ?&c_int) void; + \\pub extern fn func(array: ?*c_int) void; ); cases.add("self referential struct with function pointer", @@ -160,7 +160,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\}; , \\pub const struct_Foo = extern struct { - \\ derp: ?extern fn(?&struct_Foo) void, + \\ derp: ?extern fn(?*struct_Foo) void, \\}; , \\pub const Foo = struct_Foo; @@ -172,7 +172,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { , \\pub const struct_Foo = @OpaqueType(); , - \\pub extern fn some_func(foo: ?&struct_Foo, x: c_int) ?&struct_Foo; + \\pub extern fn some_func(foo: ?*struct_Foo, x: c_int) ?*struct_Foo; , \\pub const Foo = struct_Foo; ); @@ -219,11 +219,11 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\}; , \\pub const struct_Bar = extern struct { - \\ next: ?&struct_Foo, + \\ next: ?*struct_Foo, \\}; , \\pub const struct_Foo = extern struct { - \\ next: ?&struct_Bar, + \\ next: ?*struct_Bar, \\}; ); @@ -233,7 +233,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { , \\pub const Foo = c_void; , - \\pub extern fn fun(a: ?&Foo) Foo; + \\pub extern fn fun(a: ?*Foo) Foo; ); cases.add("generate inline func for #define global extern fn", @@ -505,7 +505,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ return 6; \\} , - \\pub export fn and_or_none_bool(a: c_int, b: f32, c: ?&c_void) c_int { + \\pub export fn and_or_none_bool(a: c_int, b: f32, c: ?*c_void) c_int { \\ if ((a != 0) and (b != 0)) return 0; \\ if ((b != 0) and (c != null)) return 1; \\ if ((a != 0) and (c != null)) return 2; @@ -607,7 +607,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\pub const struct_Foo = extern struct { \\ field: c_int, \\}; - \\pub export fn read_field(foo: ?&struct_Foo) c_int { + \\pub export fn read_field(foo: ?*struct_Foo) c_int { \\ return (??foo).field; \\} ); @@ -653,8 +653,8 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ return x; \\} , - \\pub export fn foo(x: ?&c_ushort) ?&c_void { - \\ return @ptrCast(?&c_void, x); + \\pub export fn foo(x: ?*c_ushort) ?*c_void { + \\ return @ptrCast(?*c_void, x); \\} ); @@ -674,7 +674,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ return 0; \\} , - \\pub export fn foo() ?&c_int { + \\pub export fn foo() ?*c_int { \\ return null; \\} ); @@ -983,7 +983,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ *x = 1; \\} , - \\pub export fn foo(x: ?&c_int) void { + \\pub export fn foo(x: ?*c_int) void { \\ (??x).* = 1; \\} ); @@ -1011,7 +1011,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { , \\pub fn foo() c_int { \\ var x: c_int = 1234; - \\ var ptr: ?&c_int = &x; + \\ var ptr: ?*c_int = &x; \\ return (??ptr).*; \\} ); @@ -1021,7 +1021,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ return "bar"; \\} , - \\pub fn foo() ?&const u8 { + \\pub fn foo() ?*const u8 { \\ return c"bar"; \\} ); @@ -1150,8 +1150,8 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ return (float *)a; \\} , - \\fn ptrcast(a: ?&c_int) ?&f32 { - \\ return @ptrCast(?&f32, a); + \\fn ptrcast(a: ?*c_int) ?*f32 { + \\ return @ptrCast(?*f32, a); \\} ); @@ -1173,7 +1173,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ return !c; \\} , - \\pub fn foo(a: c_int, b: f32, c: ?&c_void) c_int { + \\pub fn foo(a: c_int, b: f32, c: ?*c_void) c_int { \\ return !(a == 0); \\ return !(a != 0); \\ return !(b != 0); @@ -1194,7 +1194,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { cases.add("const ptr initializer", \\static const char *v0 = "0.0.0"; , - \\pub var v0: ?&const u8 = c"0.0.0"; + \\pub var v0: ?*const u8 = c"0.0.0"; ); cases.add("static incomplete array inside function", @@ -1203,14 +1203,14 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\} , \\pub fn foo() void { - \\ const v2: &const u8 = c"2.2.2"; + \\ const v2: *const u8 = c"2.2.2"; \\} ); cases.add("macro pointer cast", \\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE) , - \\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); + \\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); ); cases.add("if on none bool", @@ -1231,7 +1231,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ B, \\ C, \\}; - \\pub fn if_none_bool(a: c_int, b: f32, c: ?&c_void, d: enum_SomeEnum) c_int { + \\pub fn if_none_bool(a: c_int, b: f32, c: ?*c_void, d: enum_SomeEnum) c_int { \\ if (a != 0) return 0; \\ if (b != 0) return 1; \\ if (c != null) return 2; @@ -1248,7 +1248,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ return 3; \\} , - \\pub fn while_none_bool(a: c_int, b: f32, c: ?&c_void) c_int { + \\pub fn while_none_bool(a: c_int, b: f32, c: ?*c_void) c_int { \\ while (a != 0) return 0; \\ while (b != 0) return 1; \\ while (c != null) return 2; @@ -1264,7 +1264,7 @@ pub fn addCases(cases: &tests.TranslateCContext) void { \\ return 3; \\} , - \\pub fn for_none_bool(a: c_int, b: f32, c: ?&c_void) c_int { + \\pub fn for_none_bool(a: c_int, b: f32, c: ?*c_void) c_int { \\ while (a != 0) return 0; \\ while (b != 0) return 1; \\ while (c != null) return 2; -- cgit v1.2.3 From 96164ce61377b36bcaf0c4087ca9b1ab822b9457 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 4 Jun 2018 01:09:15 -0400 Subject: disallow single-item pointer indexing add pointer arithmetic for unknown length pointer --- doc/langref.html.in | 48 ++++++----- src/all_types.hpp | 9 ++ src/analyze.cpp | 53 ++++++++---- src/analyze.hpp | 2 +- src/ast_render.cpp | 8 +- src/codegen.cpp | 49 +++++++---- src/ir.cpp | 177 ++++++++++++++++++++++++++++----------- src/parser.cpp | 1 + std/buffer.zig | 2 +- std/c/darwin.zig | 4 +- std/c/index.zig | 50 +++++------ std/c/linux.zig | 2 +- std/cstr.zig | 10 +-- std/heap.zig | 18 ++-- std/os/child_process.zig | 2 +- std/os/darwin.zig | 45 +++++----- std/os/file.zig | 4 +- std/os/index.zig | 101 +++++++--------------- std/os/linux/index.zig | 123 ++++++++++++++++----------- std/os/linux/test.zig | 3 +- std/os/linux/vdso.zig | 26 +++--- std/os/windows/index.zig | 30 +++---- std/os/windows/util.zig | 2 +- std/segmented_list.zig | 12 +-- std/special/bootstrap.zig | 22 ++--- std/special/builtin.zig | 6 +- test/cases/align.zig | 49 ++++------- test/cases/const_slice_child.zig | 9 +- test/cases/for.zig | 26 +----- test/cases/misc.zig | 11 +-- test/cases/pointers.zig | 30 +++++++ test/cases/struct.zig | 6 +- test/compare_output.zig | 16 ++-- test/compile_errors.zig | 15 +++- test/translate_c.zig | 56 ++++++------- 35 files changed, 584 insertions(+), 443 deletions(-) (limited to 'std/os/linux') diff --git a/doc/langref.html.in b/doc/langref.html.in index 217f02777f..32481ade50 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -458,7 +458,7 @@ test "string literals" { // A C string literal is a null terminated pointer. const null_terminated_bytes = c"hello"; - assert(@typeOf(null_terminated_bytes) == *const u8); + assert(@typeOf(null_terminated_bytes) == [*]const u8); assert(null_terminated_bytes[5] == 0); } {#code_end#} @@ -547,7 +547,7 @@ const c_string_literal = ; {#code_end#}

- In this example the variable c_string_literal has type *const char and + In this example the variable c_string_literal has type [*]const char and has a terminating null byte.

{#see_also|@embedFile#} @@ -1288,7 +1288,7 @@ const assert = @import("std").debug.assert; const mem = @import("std").mem; // array literal -const message = []u8{'h', 'e', 'l', 'l', 'o'}; +const message = []u8{ 'h', 'e', 'l', 'l', 'o' }; // get the size of an array comptime { @@ -1324,11 +1324,11 @@ test "modify an array" { // array concatenation works if the values are known // at compile time -const part_one = []i32{1, 2, 3, 4}; -const part_two = []i32{5, 6, 7, 8}; +const part_one = []i32{ 1, 2, 3, 4 }; +const part_two = []i32{ 5, 6, 7, 8 }; const all_of_it = part_one ++ part_two; comptime { - assert(mem.eql(i32, all_of_it, []i32{1,2,3,4,5,6,7,8})); + assert(mem.eql(i32, all_of_it, []i32{ 1, 2, 3, 4, 5, 6, 7, 8 })); } // remember that string literals are arrays @@ -1357,7 +1357,7 @@ comptime { var fancy_array = init: { var initial_value: [10]Point = undefined; for (initial_value) |*pt, i| { - pt.* = Point { + pt.* = Point{ .x = i32(i), .y = i32(i) * 2, }; @@ -1377,7 +1377,7 @@ test "compile-time array initalization" { // call a function to initialize an array var more_points = []Point{makePoint(3)} ** 10; fn makePoint(x: i32) Point { - return Point { + return Point{ .x = x, .y = x * 2, }; @@ -1414,25 +1414,24 @@ test "address of syntax" { } test "pointer array access" { - // Pointers do not support pointer arithmetic. If you - // need such a thing, use array index syntax: + // Taking an address of an individual element gives a + // pointer to a single item. This kind of pointer + // does not support pointer arithmetic. var array = []u8{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - const ptr = &array[1]; + const ptr = &array[2]; + assert(@typeOf(ptr) == *u8); assert(array[2] == 3); - ptr[1] += 1; + ptr.* += 1; assert(array[2] == 4); } test "pointer slicing" { // In Zig, we prefer using slices over null-terminated pointers. - // You can turn a pointer into a slice using slice syntax: + // You can turn an array into a slice using slice syntax: var array = []u8{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - const ptr = &array[1]; - const slice = ptr[1..3]; - - assert(slice.ptr == &ptr[1]); + const slice = array[2..4]; assert(slice.len == 2); // Slices have bounds checking and are therefore protected @@ -1622,18 +1621,27 @@ fn foo(bytes: []u8) u32 { const assert = @import("std").debug.assert; test "basic slices" { - var array = []i32{1, 2, 3, 4}; + var array = []i32{ 1, 2, 3, 4 }; // A slice is a pointer and a length. The difference between an array and // a slice is that the array's length is part of the type and known at // compile-time, whereas the slice's length is known at runtime. // Both can be accessed with the `len` field. const slice = array[0..array.len]; - assert(slice.ptr == &array[0]); + assert(&slice[0] == &array[0]); assert(slice.len == array.len); + // Using the address-of operator on a slice gives a pointer to a single + // item, while using the `ptr` field gives an unknown length pointer. + assert(@typeOf(slice.ptr) == [*]i32); + assert(@typeOf(&slice[0]) == *i32); + assert(@ptrToInt(slice.ptr) == @ptrToInt(&slice[0])); + // Slices have array bounds checking. If you try to access something out // of bounds, you'll get a safety check failure: slice[10] += 1; + + // Note that `slice.ptr` does not invoke safety checking, while `&slice[0]` + // asserts that the slice has len >= 1. } {#code_end#}

This is one reason we prefer slices to pointers.

@@ -5937,7 +5945,7 @@ pub const __zig_test_fn_slice = {}; // overwritten later {#header_open|C String Literals#} {#code_begin|exe#} {#link_libc#} -extern fn puts(*const u8) void; +extern fn puts([*]const u8) void; pub fn main() void { puts(c"this has a null terminator"); diff --git a/src/all_types.hpp b/src/all_types.hpp index 8e65cfc789..f1cf96238f 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -974,8 +974,14 @@ struct FnTypeId { uint32_t fn_type_id_hash(FnTypeId*); bool fn_type_id_eql(FnTypeId *a, FnTypeId *b); +enum PtrLen { + PtrLenUnknown, + PtrLenSingle, +}; + struct TypeTableEntryPointer { TypeTableEntry *child_type; + PtrLen ptr_len; bool is_const; bool is_volatile; uint32_t alignment; @@ -1397,6 +1403,7 @@ struct TypeId { union { struct { TypeTableEntry *child_type; + PtrLen ptr_len; bool is_const; bool is_volatile; uint32_t alignment; @@ -2268,6 +2275,7 @@ struct IrInstructionElemPtr { IrInstruction *array_ptr; IrInstruction *elem_index; + PtrLen ptr_len; bool is_const; bool safety_check_on; }; @@ -2419,6 +2427,7 @@ struct IrInstructionPtrType { IrInstruction *child_type; uint32_t bit_offset_start; uint32_t bit_offset_end; + PtrLen ptr_len; bool is_const; bool is_volatile; }; diff --git a/src/analyze.cpp b/src/analyze.cpp index a5011035c5..2b9d776e78 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -381,14 +381,14 @@ TypeTableEntry *get_promise_type(CodeGen *g, TypeTableEntry *result_type) { } TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type, bool is_const, - bool is_volatile, uint32_t byte_alignment, uint32_t bit_offset, uint32_t unaligned_bit_count) + bool is_volatile, PtrLen ptr_len, uint32_t byte_alignment, uint32_t bit_offset, uint32_t unaligned_bit_count) { assert(!type_is_invalid(child_type)); TypeId type_id = {}; TypeTableEntry **parent_pointer = nullptr; uint32_t abi_alignment = get_abi_alignment(g, child_type); - if (unaligned_bit_count != 0 || is_volatile || byte_alignment != abi_alignment) { + if (unaligned_bit_count != 0 || is_volatile || byte_alignment != abi_alignment || ptr_len != PtrLenSingle) { type_id.id = TypeTableEntryIdPointer; type_id.data.pointer.child_type = child_type; type_id.data.pointer.is_const = is_const; @@ -396,6 +396,7 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type type_id.data.pointer.alignment = byte_alignment; type_id.data.pointer.bit_offset = bit_offset; type_id.data.pointer.unaligned_bit_count = unaligned_bit_count; + type_id.data.pointer.ptr_len = ptr_len; auto existing_entry = g->type_table.maybe_get(type_id); if (existing_entry) @@ -414,16 +415,17 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdPointer); entry->is_copyable = true; + const char *star_str = ptr_len == PtrLenSingle ? "*" : "[*]"; const char *const_str = is_const ? "const " : ""; const char *volatile_str = is_volatile ? "volatile " : ""; buf_resize(&entry->name, 0); if (unaligned_bit_count == 0 && byte_alignment == abi_alignment) { - buf_appendf(&entry->name, "*%s%s%s", const_str, volatile_str, buf_ptr(&child_type->name)); + buf_appendf(&entry->name, "%s%s%s%s", star_str, const_str, volatile_str, buf_ptr(&child_type->name)); } else if (unaligned_bit_count == 0) { - buf_appendf(&entry->name, "*align(%" PRIu32 ") %s%s%s", byte_alignment, + buf_appendf(&entry->name, "%salign(%" PRIu32 ") %s%s%s", star_str, byte_alignment, const_str, volatile_str, buf_ptr(&child_type->name)); } else { - buf_appendf(&entry->name, "*align(%" PRIu32 ":%" PRIu32 ":%" PRIu32 ") %s%s%s", byte_alignment, + buf_appendf(&entry->name, "%salign(%" PRIu32 ":%" PRIu32 ":%" PRIu32 ") %s%s%s", star_str, byte_alignment, bit_offset, bit_offset + unaligned_bit_count, const_str, volatile_str, buf_ptr(&child_type->name)); } @@ -433,7 +435,9 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type if (!entry->zero_bits) { assert(byte_alignment > 0); - if (is_const || is_volatile || unaligned_bit_count != 0 || byte_alignment != abi_alignment) { + if (is_const || is_volatile || unaligned_bit_count != 0 || byte_alignment != abi_alignment || + ptr_len != PtrLenSingle) + { TypeTableEntry *peer_type = get_pointer_to_type(g, child_type, false); entry->type_ref = peer_type->type_ref; entry->di_type = peer_type->di_type; @@ -451,6 +455,7 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type entry->di_type = g->builtin_types.entry_void->di_type; } + entry->data.pointer.ptr_len = ptr_len; entry->data.pointer.child_type = child_type; entry->data.pointer.is_const = is_const; entry->data.pointer.is_volatile = is_volatile; @@ -467,7 +472,8 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type } TypeTableEntry *get_pointer_to_type(CodeGen *g, TypeTableEntry *child_type, bool is_const) { - return get_pointer_to_type_extra(g, child_type, is_const, false, get_abi_alignment(g, child_type), 0, 0); + return get_pointer_to_type_extra(g, child_type, is_const, false, PtrLenSingle, + get_abi_alignment(g, child_type), 0, 0); } TypeTableEntry *get_promise_frame_type(CodeGen *g, TypeTableEntry *return_type) { @@ -757,6 +763,7 @@ static void slice_type_common_init(CodeGen *g, TypeTableEntry *pointer_type, Typ TypeTableEntry *get_slice_type(CodeGen *g, TypeTableEntry *ptr_type) { assert(ptr_type->id == TypeTableEntryIdPointer); + assert(ptr_type->data.pointer.ptr_len == PtrLenUnknown); TypeTableEntry **parent_pointer = &ptr_type->data.pointer.slice_parent; if (*parent_pointer) { @@ -768,14 +775,16 @@ TypeTableEntry *get_slice_type(CodeGen *g, TypeTableEntry *ptr_type) { // replace the & with [] to go from a ptr type name to a slice type name buf_resize(&entry->name, 0); - buf_appendf(&entry->name, "[]%s", buf_ptr(&ptr_type->name) + 1); + size_t name_offset = (ptr_type->data.pointer.ptr_len == PtrLenSingle) ? 1 : 3; + buf_appendf(&entry->name, "[]%s", buf_ptr(&ptr_type->name) + name_offset); TypeTableEntry *child_type = ptr_type->data.pointer.child_type; - uint32_t abi_alignment; + uint32_t abi_alignment = get_abi_alignment(g, child_type); if (ptr_type->data.pointer.is_const || ptr_type->data.pointer.is_volatile || - ptr_type->data.pointer.alignment != (abi_alignment = get_abi_alignment(g, child_type))) + ptr_type->data.pointer.alignment != abi_alignment) { - TypeTableEntry *peer_ptr_type = get_pointer_to_type(g, child_type, false); + TypeTableEntry *peer_ptr_type = get_pointer_to_type_extra(g, child_type, false, false, + PtrLenUnknown, abi_alignment, 0, 0); TypeTableEntry *peer_slice_type = get_slice_type(g, peer_ptr_type); slice_type_common_init(g, ptr_type, entry); @@ -799,9 +808,11 @@ TypeTableEntry *get_slice_type(CodeGen *g, TypeTableEntry *ptr_type) { if (child_ptr_type->data.pointer.is_const || child_ptr_type->data.pointer.is_volatile || child_ptr_type->data.pointer.alignment != get_abi_alignment(g, grand_child_type)) { - TypeTableEntry *bland_child_ptr_type = get_pointer_to_type(g, grand_child_type, false); + TypeTableEntry *bland_child_ptr_type = get_pointer_to_type_extra(g, grand_child_type, false, false, + PtrLenUnknown, get_abi_alignment(g, grand_child_type), 0, 0); TypeTableEntry *bland_child_slice = get_slice_type(g, bland_child_ptr_type); - TypeTableEntry *peer_ptr_type = get_pointer_to_type(g, bland_child_slice, false); + TypeTableEntry *peer_ptr_type = get_pointer_to_type_extra(g, bland_child_slice, false, false, + PtrLenUnknown, get_abi_alignment(g, bland_child_slice), 0, 0); TypeTableEntry *peer_slice_type = get_slice_type(g, peer_ptr_type); entry->type_ref = peer_slice_type->type_ref; @@ -1284,7 +1295,8 @@ static bool analyze_const_align(CodeGen *g, Scope *scope, AstNode *node, uint32_ } static bool analyze_const_string(CodeGen *g, Scope *scope, AstNode *node, Buf **out_buffer) { - TypeTableEntry *ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true); + TypeTableEntry *ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false, + PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0); TypeTableEntry *str_type = get_slice_type(g, ptr_type); IrInstruction *instr = analyze_const_value(g, scope, node, str_type, nullptr); if (type_is_invalid(instr->value.type)) @@ -2954,7 +2966,8 @@ static void typecheck_panic_fn(CodeGen *g, FnTableEntry *panic_fn) { if (fn_type_id->param_count != 2) { return wrong_panic_prototype(g, proto_node, fn_type); } - TypeTableEntry *const_u8_ptr = get_pointer_to_type(g, g->builtin_types.entry_u8, true); + TypeTableEntry *const_u8_ptr = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false, + PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0); TypeTableEntry *const_u8_slice = get_slice_type(g, const_u8_ptr); if (fn_type_id->param_info[0].type != const_u8_slice) { return wrong_panic_prototype(g, proto_node, fn_type); @@ -4994,7 +5007,9 @@ void init_const_c_str_lit(CodeGen *g, ConstExprValue *const_val, Buf *str) { // then make the pointer point to it const_val->special = ConstValSpecialStatic; - const_val->type = get_pointer_to_type(g, g->builtin_types.entry_u8, true); + // TODO make this `[*]null u8` instead of `[*]u8` + const_val->type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false, + PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0); const_val->data.x_ptr.special = ConstPtrSpecialBaseArray; const_val->data.x_ptr.data.base_array.array_val = array_val; const_val->data.x_ptr.data.base_array.elem_index = 0; @@ -5135,7 +5150,9 @@ void init_const_slice(CodeGen *g, ConstExprValue *const_val, ConstExprValue *arr { assert(array_val->type->id == TypeTableEntryIdArray); - TypeTableEntry *ptr_type = get_pointer_to_type(g, array_val->type->data.array.child_type, is_const); + TypeTableEntry *ptr_type = get_pointer_to_type_extra(g, array_val->type->data.array.child_type, + is_const, false, PtrLenUnknown, get_abi_alignment(g, array_val->type->data.array.child_type), + 0, 0); const_val->special = ConstValSpecialStatic; const_val->type = get_slice_type(g, ptr_type); @@ -5759,6 +5776,7 @@ uint32_t type_id_hash(TypeId x) { return hash_ptr(x.data.error_union.err_set_type) ^ hash_ptr(x.data.error_union.payload_type); case TypeTableEntryIdPointer: return hash_ptr(x.data.pointer.child_type) + + ((x.data.pointer.ptr_len == PtrLenSingle) ? (uint32_t)1120226602 : (uint32_t)3200913342) + (x.data.pointer.is_const ? (uint32_t)2749109194 : (uint32_t)4047371087) + (x.data.pointer.is_volatile ? (uint32_t)536730450 : (uint32_t)1685612214) + (((uint32_t)x.data.pointer.alignment) ^ (uint32_t)0x777fbe0e) + @@ -5807,6 +5825,7 @@ bool type_id_eql(TypeId a, TypeId b) { case TypeTableEntryIdPointer: return a.data.pointer.child_type == b.data.pointer.child_type && + a.data.pointer.ptr_len == b.data.pointer.ptr_len && a.data.pointer.is_const == b.data.pointer.is_const && a.data.pointer.is_volatile == b.data.pointer.is_volatile && a.data.pointer.alignment == b.data.pointer.alignment && diff --git a/src/analyze.hpp b/src/analyze.hpp index d538f042ce..905bfa86dd 100644 --- a/src/analyze.hpp +++ b/src/analyze.hpp @@ -16,7 +16,7 @@ ErrorMsg *add_error_note(CodeGen *g, ErrorMsg *parent_msg, AstNode *node, Buf *m TypeTableEntry *new_type_table_entry(TypeTableEntryId id); TypeTableEntry *get_pointer_to_type(CodeGen *g, TypeTableEntry *child_type, bool is_const); TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type, bool is_const, - bool is_volatile, uint32_t byte_alignment, uint32_t bit_offset, uint32_t unaligned_bit_count); + bool is_volatile, PtrLen ptr_len, uint32_t byte_alignment, uint32_t bit_offset, uint32_t unaligned_bit_count); uint64_t type_size(CodeGen *g, TypeTableEntry *type_entry); uint64_t type_size_bits(CodeGen *g, TypeTableEntry *type_entry); TypeTableEntry **get_int_type_ptr(CodeGen *g, bool is_signed, uint32_t size_in_bits); diff --git a/src/ast_render.cpp b/src/ast_render.cpp index f356f406b0..3785cb6ca1 100644 --- a/src/ast_render.cpp +++ b/src/ast_render.cpp @@ -625,7 +625,13 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) { case NodeTypePointerType: { if (!grouped) fprintf(ar->f, "("); - fprintf(ar->f, "*"); + const char *star = "[*]"; + if (node->data.pointer_type.star_token != nullptr && + (node->data.pointer_type.star_token->id == TokenIdStar || node->data.pointer_type.star_token->id == TokenIdStarStar)) + { + star = "*"; + } + fprintf(ar->f, "%s", star); if (node->data.pointer_type.align_expr != nullptr) { fprintf(ar->f, "align("); render_node_grouped(ar, node->data.pointer_type.align_expr); diff --git a/src/codegen.cpp b/src/codegen.cpp index d07d427729..64e29a4da4 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -893,7 +893,8 @@ static LLVMValueRef get_panic_msg_ptr_val(CodeGen *g, PanicMsgId msg_id) { assert(val->global_refs->llvm_global); } - TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true); + TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false, + PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0); TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type); return LLVMConstBitCast(val->global_refs->llvm_global, LLVMPointerType(str_type->type_ref, 0)); } @@ -1461,7 +1462,8 @@ static LLVMValueRef get_safety_crash_err_fn(CodeGen *g) { LLVMValueRef full_buf_ptr = LLVMConstInBoundsGEP(global_array, full_buf_ptr_indices, 2); - TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true); + TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false, + PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0); TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type); LLVMValueRef global_slice_fields[] = { full_buf_ptr, @@ -2212,9 +2214,13 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable, IrInstruction *op2 = bin_op_instruction->op2; assert(op1->value.type == op2->value.type || op_id == IrBinOpBitShiftLeftLossy || - op_id == IrBinOpBitShiftLeftExact || op_id == IrBinOpBitShiftRightLossy || - op_id == IrBinOpBitShiftRightExact || - (op1->value.type->id == TypeTableEntryIdErrorSet && op2->value.type->id == TypeTableEntryIdErrorSet)); + op_id == IrBinOpBitShiftLeftExact || op_id == IrBinOpBitShiftRightLossy || + op_id == IrBinOpBitShiftRightExact || + (op1->value.type->id == TypeTableEntryIdErrorSet && op2->value.type->id == TypeTableEntryIdErrorSet) || + (op1->value.type->id == TypeTableEntryIdPointer && + (op_id == IrBinOpAdd || op_id == IrBinOpSub) && + op1->value.type->data.pointer.ptr_len == PtrLenUnknown) + ); TypeTableEntry *type_entry = op1->value.type; bool want_runtime_safety = bin_op_instruction->safety_check_on && @@ -2222,6 +2228,8 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable, LLVMValueRef op1_value = ir_llvm_value(g, op1); LLVMValueRef op2_value = ir_llvm_value(g, op2); + + switch (op_id) { case IrBinOpInvalid: case IrBinOpArrayCat: @@ -2260,7 +2268,11 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable, } case IrBinOpAdd: case IrBinOpAddWrap: - if (type_entry->id == TypeTableEntryIdFloat) { + if (type_entry->id == TypeTableEntryIdPointer) { + assert(type_entry->data.pointer.ptr_len == PtrLenUnknown); + // TODO runtime safety + return LLVMBuildInBoundsGEP(g->builder, op1_value, &op2_value, 1, ""); + } else if (type_entry->id == TypeTableEntryIdFloat) { ZigLLVMSetFastMath(g->builder, ir_want_fast_math(g, &bin_op_instruction->base)); return LLVMBuildFAdd(g->builder, op1_value, op2_value, ""); } else if (type_entry->id == TypeTableEntryIdInt) { @@ -2323,7 +2335,12 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable, } case IrBinOpSub: case IrBinOpSubWrap: - if (type_entry->id == TypeTableEntryIdFloat) { + if (type_entry->id == TypeTableEntryIdPointer) { + assert(type_entry->data.pointer.ptr_len == PtrLenUnknown); + // TODO runtime safety + LLVMValueRef subscript_value = LLVMBuildNeg(g->builder, op2_value, ""); + return LLVMBuildInBoundsGEP(g->builder, op1_value, &subscript_value, 1, ""); + } else if (type_entry->id == TypeTableEntryIdFloat) { ZigLLVMSetFastMath(g->builder, ir_want_fast_math(g, &bin_op_instruction->base)); return LLVMBuildFSub(g->builder, op1_value, op2_value, ""); } else if (type_entry->id == TypeTableEntryIdInt) { @@ -2770,7 +2787,7 @@ static LLVMValueRef ir_render_decl_var(CodeGen *g, IrExecutable *executable, if (have_init_expr) { assert(var->value->type == init_value->value.type); TypeTableEntry *var_ptr_type = get_pointer_to_type_extra(g, var->value->type, false, false, - var->align_bytes, 0, 0); + PtrLenSingle, var->align_bytes, 0, 0); gen_assign_raw(g, var->value_ref, var_ptr_type, ir_llvm_value(g, init_value)); } else { bool want_safe = ir_want_runtime_safety(g, &decl_var_instruction->base); @@ -4172,7 +4189,7 @@ static LLVMValueRef ir_render_struct_init(CodeGen *g, IrExecutable *executable, uint32_t field_align_bytes = get_abi_alignment(g, type_struct_field->type_entry); TypeTableEntry *ptr_type = get_pointer_to_type_extra(g, type_struct_field->type_entry, - false, false, field_align_bytes, + false, false, PtrLenSingle, field_align_bytes, (uint32_t)type_struct_field->packed_bits_offset, (uint32_t)type_struct_field->unaligned_bit_count); gen_assign_raw(g, field_ptr, ptr_type, value); @@ -4188,7 +4205,7 @@ static LLVMValueRef ir_render_union_init(CodeGen *g, IrExecutable *executable, I uint32_t field_align_bytes = get_abi_alignment(g, type_union_field->type_entry); TypeTableEntry *ptr_type = get_pointer_to_type_extra(g, type_union_field->type_entry, - false, false, field_align_bytes, + false, false, PtrLenSingle, field_align_bytes, 0, 0); LLVMValueRef uncasted_union_ptr; @@ -4435,7 +4452,8 @@ static LLVMValueRef get_coro_alloc_helper_fn_val(CodeGen *g, LLVMTypeRef alloc_f LLVMPositionBuilderAtEnd(g->builder, ok_block); LLVMValueRef payload_ptr = LLVMBuildStructGEP(g->builder, sret_ptr, err_union_payload_index, ""); - TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, false); + TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, false, false, + PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0); TypeTableEntry *slice_type = get_slice_type(g, u8_ptr_type); size_t ptr_field_index = slice_type->data.structure.fields[slice_ptr_index].gen_index; LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, payload_ptr, ptr_field_index, ""); @@ -5377,7 +5395,8 @@ static void generate_error_name_table(CodeGen *g) { assert(g->errors_by_index.length > 0); - TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true); + TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false, + PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0); TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type); LLVMValueRef *values = allocate(g->errors_by_index.length); @@ -5415,7 +5434,8 @@ static void generate_error_name_table(CodeGen *g) { } static void generate_enum_name_tables(CodeGen *g) { - TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true); + TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false, + PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0); TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type); TypeTableEntry *usize = g->builtin_types.entry_usize; @@ -6869,7 +6889,8 @@ static void create_test_compile_var_and_add_test_runner(CodeGen *g) { exit(0); } - TypeTableEntry *u8_ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true); + TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false, + PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0); TypeTableEntry *str_type = get_slice_type(g, u8_ptr_type); TypeTableEntry *fn_type = get_test_fn_type(g); diff --git a/src/ir.cpp b/src/ir.cpp index 5cada29076..a230c60456 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -1009,12 +1009,13 @@ static IrInstruction *ir_build_var_ptr(IrBuilder *irb, Scope *scope, AstNode *so } static IrInstruction *ir_build_elem_ptr(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *array_ptr, - IrInstruction *elem_index, bool safety_check_on) + IrInstruction *elem_index, bool safety_check_on, PtrLen ptr_len) { IrInstructionElemPtr *instruction = ir_build_instruction(irb, scope, source_node); instruction->array_ptr = array_ptr; instruction->elem_index = elem_index; instruction->safety_check_on = safety_check_on; + instruction->ptr_len = ptr_len; ir_ref_instruction(array_ptr, irb->current_basic_block); ir_ref_instruction(elem_index, irb->current_basic_block); @@ -1022,15 +1023,6 @@ static IrInstruction *ir_build_elem_ptr(IrBuilder *irb, Scope *scope, AstNode *s return &instruction->base; } -static IrInstruction *ir_build_elem_ptr_from(IrBuilder *irb, IrInstruction *old_instruction, - IrInstruction *array_ptr, IrInstruction *elem_index, bool safety_check_on) -{ - IrInstruction *new_instruction = ir_build_elem_ptr(irb, old_instruction->scope, - old_instruction->source_node, array_ptr, elem_index, safety_check_on); - ir_link_new_instruction(new_instruction, old_instruction); - return new_instruction; -} - static IrInstruction *ir_build_field_ptr_instruction(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *container_ptr, IrInstruction *field_name_expr) { @@ -1188,14 +1180,15 @@ static IrInstruction *ir_build_br_from(IrBuilder *irb, IrInstruction *old_instru } static IrInstruction *ir_build_ptr_type(IrBuilder *irb, Scope *scope, AstNode *source_node, - IrInstruction *child_type, bool is_const, bool is_volatile, IrInstruction *align_value, - uint32_t bit_offset_start, uint32_t bit_offset_end) + IrInstruction *child_type, bool is_const, bool is_volatile, PtrLen ptr_len, + IrInstruction *align_value, uint32_t bit_offset_start, uint32_t bit_offset_end) { IrInstructionPtrType *ptr_type_of_instruction = ir_build_instruction(irb, scope, source_node); ptr_type_of_instruction->align_value = align_value; ptr_type_of_instruction->child_type = child_type; ptr_type_of_instruction->is_const = is_const; ptr_type_of_instruction->is_volatile = is_volatile; + ptr_type_of_instruction->ptr_len = ptr_len; ptr_type_of_instruction->bit_offset_start = bit_offset_start; ptr_type_of_instruction->bit_offset_end = bit_offset_end; @@ -3547,7 +3540,7 @@ static IrInstruction *ir_gen_array_access(IrBuilder *irb, Scope *scope, AstNode return subscript_instruction; IrInstruction *ptr_instruction = ir_build_elem_ptr(irb, scope, node, array_ref_instruction, - subscript_instruction, true); + subscript_instruction, true, PtrLenSingle); if (lval.is_ptr) return ptr_instruction; @@ -4626,6 +4619,11 @@ static IrInstruction *ir_lval_wrap(IrBuilder *irb, Scope *scope, IrInstruction * static IrInstruction *ir_gen_pointer_type(IrBuilder *irb, Scope *scope, AstNode *node) { assert(node->type == NodeTypePointerType); + // The null check here is for C imports which don't set a token on the AST node. We could potentially + // update that code to create a fake token and then remove this check. + PtrLen ptr_len = (node->data.pointer_type.star_token != nullptr && + (node->data.pointer_type.star_token->id == TokenIdStar || + node->data.pointer_type.star_token->id == TokenIdStarStar)) ? PtrLenSingle : PtrLenUnknown; bool is_const = node->data.pointer_type.is_const; bool is_volatile = node->data.pointer_type.is_volatile; AstNode *expr_node = node->data.pointer_type.op_expr; @@ -4675,7 +4673,7 @@ static IrInstruction *ir_gen_pointer_type(IrBuilder *irb, Scope *scope, AstNode } return ir_build_ptr_type(irb, scope, node, child_type, is_const, is_volatile, - align_value, bit_offset_start, bit_offset_end); + ptr_len, align_value, bit_offset_start, bit_offset_end); } static IrInstruction *ir_gen_err_assert_ok(IrBuilder *irb, Scope *scope, AstNode *source_node, AstNode *expr_node, @@ -5172,7 +5170,7 @@ static IrInstruction *ir_gen_for_expr(IrBuilder *irb, Scope *parent_scope, AstNo ir_mark_gen(ir_build_cond_br(irb, child_scope, node, cond, body_block, else_block, is_comptime)); ir_set_cursor_at_end_and_append_block(irb, body_block); - IrInstruction *elem_ptr = ir_build_elem_ptr(irb, child_scope, node, array_val_ptr, index_val, false); + IrInstruction *elem_ptr = ir_build_elem_ptr(irb, child_scope, node, array_val_ptr, index_val, false, PtrLenSingle); IrInstruction *elem_val; if (node->data.for_expr.elem_is_ptr) { elem_val = elem_ptr; @@ -6811,9 +6809,13 @@ bool ir_gen(CodeGen *codegen, AstNode *node, Scope *scope, IrExecutable *ir_exec ir_set_cursor_at_end_and_append_block(irb, irb->exec->coro_normal_final); if (type_has_bits(return_type)) { + IrInstruction *u8_ptr_type_unknown_len = ir_build_const_type(irb, scope, node, + get_pointer_to_type_extra(irb->codegen, irb->codegen->builtin_types.entry_u8, + false, false, PtrLenUnknown, get_abi_alignment(irb->codegen, irb->codegen->builtin_types.entry_u8), + 0, 0)); IrInstruction *result_ptr = ir_build_load_ptr(irb, scope, node, irb->exec->coro_result_ptr_field_ptr); - IrInstruction *result_ptr_as_u8_ptr = ir_build_ptr_cast(irb, scope, node, u8_ptr_type, result_ptr); - IrInstruction *return_value_ptr_as_u8_ptr = ir_build_ptr_cast(irb, scope, node, u8_ptr_type, + IrInstruction *result_ptr_as_u8_ptr = ir_build_ptr_cast(irb, scope, node, u8_ptr_type_unknown_len, result_ptr); + IrInstruction *return_value_ptr_as_u8_ptr = ir_build_ptr_cast(irb, scope, node, u8_ptr_type_unknown_len, irb->exec->coro_result_field_ptr); IrInstruction *return_type_inst = ir_build_const_type(irb, scope, node, fn_entry->type_entry->data.fn.fn_type_id.return_type); @@ -7691,6 +7693,7 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, TypeTableEntry // pointer const if (expected_type->id == TypeTableEntryIdPointer && actual_type->id == TypeTableEntryIdPointer && + (actual_type->data.pointer.ptr_len == expected_type->data.pointer.ptr_len) && (!actual_type->data.pointer.is_const || expected_type->data.pointer.is_const) && (!actual_type->data.pointer.is_volatile || expected_type->data.pointer.is_volatile) && actual_type->data.pointer.bit_offset == expected_type->data.pointer.bit_offset && @@ -8644,7 +8647,11 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod if (convert_to_const_slice) { assert(prev_inst->value.type->id == TypeTableEntryIdArray); - TypeTableEntry *ptr_type = get_pointer_to_type(ira->codegen, prev_inst->value.type->data.array.child_type, true); + TypeTableEntry *ptr_type = get_pointer_to_type_extra( + ira->codegen, prev_inst->value.type->data.array.child_type, + true, false, PtrLenUnknown, + get_abi_alignment(ira->codegen, prev_inst->value.type->data.array.child_type), + 0, 0); TypeTableEntry *slice_type = get_slice_type(ira->codegen, ptr_type); if (err_set_type != nullptr) { return get_error_union_type(ira->codegen, err_set_type, slice_type); @@ -8961,7 +8968,7 @@ static IrInstruction *ir_get_const_ptr(IrAnalyze *ira, IrInstruction *instructio ConstPtrMut ptr_mut, bool ptr_is_const, bool ptr_is_volatile, uint32_t ptr_align) { TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, pointee_type, - ptr_is_const, ptr_is_volatile, ptr_align, 0, 0); + ptr_is_const, ptr_is_volatile, PtrLenSingle, ptr_align, 0, 0); IrInstruction *const_instr = ir_get_const(ira, instruction); ConstExprValue *const_val = &const_instr->value; const_val->type = ptr_type; @@ -9302,7 +9309,7 @@ static IrInstruction *ir_get_ref(IrAnalyze *ira, IrInstruction *source_instructi } TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, value->value.type, - is_const, is_volatile, get_abi_alignment(ira->codegen, value->value.type), 0, 0); + is_const, is_volatile, PtrLenSingle, get_abi_alignment(ira->codegen, value->value.type), 0, 0); IrInstruction *new_instruction = ir_build_ref(&ira->new_irb, source_instruction->scope, source_instruction->source_node, value, is_const, is_volatile); new_instruction->value.type = ptr_type; @@ -10399,7 +10406,9 @@ static Buf *ir_resolve_str(IrAnalyze *ira, IrInstruction *value) { if (type_is_invalid(value->value.type)) return nullptr; - TypeTableEntry *ptr_type = get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, true); + TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, ira->codegen->builtin_types.entry_u8, + true, false, PtrLenUnknown, + get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8), 0, 0); TypeTableEntry *str_type = get_slice_type(ira->codegen, ptr_type); IrInstruction *casted_value = ir_implicit_cast(ira, value, str_type); if (type_is_invalid(casted_value->value.type)) @@ -11054,11 +11063,27 @@ static TypeTableEntry *ir_analyze_bit_shift(IrAnalyze *ira, IrInstructionBinOp * static TypeTableEntry *ir_analyze_bin_op_math(IrAnalyze *ira, IrInstructionBinOp *bin_op_instruction) { IrInstruction *op1 = bin_op_instruction->op1->other; IrInstruction *op2 = bin_op_instruction->op2->other; + IrBinOp op_id = bin_op_instruction->op_id; + + // look for pointer math + if (op1->value.type->id == TypeTableEntryIdPointer && op1->value.type->data.pointer.ptr_len == PtrLenUnknown && + (op_id == IrBinOpAdd || op_id == IrBinOpSub)) + { + IrInstruction *casted_op2 = ir_implicit_cast(ira, op2, ira->codegen->builtin_types.entry_usize); + if (casted_op2 == ira->codegen->invalid_instruction) + return ira->codegen->builtin_types.entry_invalid; + + IrInstruction *result = ir_build_bin_op(&ira->new_irb, bin_op_instruction->base.scope, + bin_op_instruction->base.source_node, op_id, op1, casted_op2, true); + result->value.type = op1->value.type; + ir_link_new_instruction(result, &bin_op_instruction->base); + return result->value.type; + } + IrInstruction *instructions[] = {op1, op2}; TypeTableEntry *resolved_type = ir_resolve_peer_types(ira, bin_op_instruction->base.source_node, nullptr, instructions, 2); if (type_is_invalid(resolved_type)) return resolved_type; - IrBinOp op_id = bin_op_instruction->op_id; bool is_int = resolved_type->id == TypeTableEntryIdInt || resolved_type->id == TypeTableEntryIdNumLitInt; bool is_float = resolved_type->id == TypeTableEntryIdFloat || resolved_type->id == TypeTableEntryIdNumLitFloat; @@ -11331,7 +11356,8 @@ static TypeTableEntry *ir_analyze_array_cat(IrAnalyze *ira, IrInstructionBinOp * out_array_val = out_val; } else if (is_slice(op1_type) || is_slice(op2_type)) { - TypeTableEntry *ptr_type = get_pointer_to_type(ira->codegen, child_type, true); + TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, child_type, + true, false, PtrLenUnknown, get_abi_alignment(ira->codegen, child_type), 0, 0); result_type = get_slice_type(ira->codegen, ptr_type); out_array_val = create_const_vals(1); out_array_val->special = ConstValSpecialStatic; @@ -11351,7 +11377,9 @@ static TypeTableEntry *ir_analyze_array_cat(IrAnalyze *ira, IrInstructionBinOp * } else { new_len += 1; // null byte - result_type = get_pointer_to_type(ira->codegen, child_type, true); + // TODO make this `[*]null T` instead of `[*]T` + result_type = get_pointer_to_type_extra(ira->codegen, child_type, true, false, + PtrLenUnknown, get_abi_alignment(ira->codegen, child_type), 0, 0); out_array_val = create_const_vals(1); out_array_val->special = ConstValSpecialStatic; @@ -12173,7 +12201,7 @@ no_mem_slot: IrInstruction *var_ptr_instruction = ir_build_var_ptr(&ira->new_irb, instruction->scope, instruction->source_node, var); var_ptr_instruction->value.type = get_pointer_to_type_extra(ira->codegen, var->value->type, - var->src_is_const, is_volatile, var->align_bytes, 0, 0); + var->src_is_const, is_volatile, PtrLenSingle, var->align_bytes, 0, 0); type_ensure_zero_bits_known(ira->codegen, var->value->type); bool in_fn_scope = (scope_fn_entry(var->parent_scope) != nullptr); @@ -12352,7 +12380,9 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal IrInstruction *casted_new_stack = nullptr; if (call_instruction->new_stack != nullptr) { - TypeTableEntry *u8_ptr = get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, false); + TypeTableEntry *u8_ptr = get_pointer_to_type_extra(ira->codegen, ira->codegen->builtin_types.entry_u8, + false, false, PtrLenUnknown, + get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8), 0, 0); TypeTableEntry *u8_slice = get_slice_type(ira->codegen, u8_ptr); IrInstruction *new_stack = call_instruction->new_stack->other; if (type_is_invalid(new_stack->value.type)) @@ -13112,10 +13142,21 @@ static TypeTableEntry *adjust_ptr_align(CodeGen *g, TypeTableEntry *ptr_type, ui return get_pointer_to_type_extra(g, ptr_type->data.pointer.child_type, ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile, + ptr_type->data.pointer.ptr_len, new_align, ptr_type->data.pointer.bit_offset, ptr_type->data.pointer.unaligned_bit_count); } +static TypeTableEntry *adjust_ptr_len(CodeGen *g, TypeTableEntry *ptr_type, PtrLen ptr_len) { + assert(ptr_type->id == TypeTableEntryIdPointer); + return get_pointer_to_type_extra(g, + ptr_type->data.pointer.child_type, + ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile, + ptr_len, + ptr_type->data.pointer.alignment, + ptr_type->data.pointer.bit_offset, ptr_type->data.pointer.unaligned_bit_count); +} + static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstructionElemPtr *elem_ptr_instruction) { IrInstruction *array_ptr = elem_ptr_instruction->array_ptr->other; if (type_is_invalid(array_ptr->value.type)) @@ -13146,6 +13187,7 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc if (ptr_type->data.pointer.unaligned_bit_count == 0) { return_type = get_pointer_to_type_extra(ira->codegen, child_type, ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile, + elem_ptr_instruction->ptr_len, ptr_type->data.pointer.alignment, 0, 0); } else { uint64_t elem_val_scalar; @@ -13157,12 +13199,19 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc return_type = get_pointer_to_type_extra(ira->codegen, child_type, ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile, + elem_ptr_instruction->ptr_len, 1, (uint32_t)bit_offset, (uint32_t)bit_width); } } else if (array_type->id == TypeTableEntryIdPointer) { - return_type = array_type; + if (array_type->data.pointer.ptr_len == PtrLenSingle) { + ir_add_error_node(ira, elem_ptr_instruction->base.source_node, + buf_sprintf("indexing not allowed on pointer to single item")); + return ira->codegen->builtin_types.entry_invalid; + } + return_type = adjust_ptr_len(ira->codegen, array_type, elem_ptr_instruction->ptr_len); } else if (is_slice(array_type)) { - return_type = array_type->data.structure.fields[slice_ptr_index].type_entry; + return_type = adjust_ptr_len(ira->codegen, array_type->data.structure.fields[slice_ptr_index].type_entry, + elem_ptr_instruction->ptr_len); } else if (array_type->id == TypeTableEntryIdArgTuple) { ConstExprValue *ptr_val = ir_resolve_const(ira, array_ptr, UndefBad); if (!ptr_val) @@ -13304,8 +13353,10 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc } else if (is_slice(array_type)) { ConstExprValue *ptr_field = &array_ptr_val->data.x_struct.fields[slice_ptr_index]; if (ptr_field->data.x_ptr.special == ConstPtrSpecialHardCodedAddr) { - ir_build_elem_ptr_from(&ira->new_irb, &elem_ptr_instruction->base, array_ptr, - casted_elem_index, false); + IrInstruction *result = ir_build_elem_ptr(&ira->new_irb, elem_ptr_instruction->base.scope, elem_ptr_instruction->base.source_node, + array_ptr, casted_elem_index, false, elem_ptr_instruction->ptr_len); + result->value.type = return_type; + ir_link_new_instruction(result, &elem_ptr_instruction->base); return return_type; } ConstExprValue *len_field = &array_ptr_val->data.x_struct.fields[slice_len_index]; @@ -13373,8 +13424,10 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc } } - ir_build_elem_ptr_from(&ira->new_irb, &elem_ptr_instruction->base, array_ptr, - casted_elem_index, safety_check_on); + IrInstruction *result = ir_build_elem_ptr(&ira->new_irb, elem_ptr_instruction->base.scope, elem_ptr_instruction->base.source_node, + array_ptr, casted_elem_index, safety_check_on, elem_ptr_instruction->ptr_len); + result->value.type = return_type; + ir_link_new_instruction(result, &elem_ptr_instruction->base); return return_type; } @@ -13449,7 +13502,7 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_ return ira->codegen->invalid_instruction; ConstExprValue *field_val = &struct_val->data.x_struct.fields[field->src_index]; TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, field_val->type, - is_const, is_volatile, align_bytes, + is_const, is_volatile, PtrLenSingle, align_bytes, (uint32_t)(ptr_bit_offset + field->packed_bits_offset), (uint32_t)unaligned_bit_count_for_result_type); IrInstruction *result = ir_get_const(ira, source_instr); @@ -13465,6 +13518,7 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_ IrInstruction *result = ir_build_struct_field_ptr(&ira->new_irb, source_instr->scope, source_instr->source_node, container_ptr, field); result->value.type = get_pointer_to_type_extra(ira->codegen, field->type_entry, is_const, is_volatile, + PtrLenSingle, align_bytes, (uint32_t)(ptr_bit_offset + field->packed_bits_offset), (uint32_t)unaligned_bit_count_for_result_type); @@ -13511,7 +13565,9 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_ payload_val->type = field_type; } - TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, field_type, is_const, is_volatile, + TypeTableEntry *ptr_type = get_pointer_to_type_extra(ira->codegen, field_type, + is_const, is_volatile, + PtrLenSingle, get_abi_alignment(ira->codegen, field_type), 0, 0); IrInstruction *result = ir_get_const(ira, source_instr); @@ -13526,7 +13582,7 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_ IrInstruction *result = ir_build_union_field_ptr(&ira->new_irb, source_instr->scope, source_instr->source_node, container_ptr, field); result->value.type = get_pointer_to_type_extra(ira->codegen, field->type_entry, is_const, is_volatile, - get_abi_alignment(ira->codegen, field->type_entry), 0, 0); + PtrLenSingle, get_abi_alignment(ira->codegen, field->type_entry), 0, 0); return result; } else { return ir_analyze_container_member_access_inner(ira, bare_type, field_name, @@ -14119,7 +14175,7 @@ static TypeTableEntry *ir_analyze_instruction_to_ptr_type(IrAnalyze *ira, if (type_entry->id == TypeTableEntryIdArray) { ptr_type = get_pointer_to_type(ira->codegen, type_entry->data.array.child_type, false); } else if (is_slice(type_entry)) { - ptr_type = type_entry->data.structure.fields[0].type_entry; + ptr_type = adjust_ptr_len(ira->codegen, type_entry->data.structure.fields[0].type_entry, PtrLenSingle); } else if (type_entry->id == TypeTableEntryIdArgTuple) { ConstExprValue *arg_tuple_val = ir_resolve_const(ira, value, UndefBad); if (!arg_tuple_val) @@ -14367,7 +14423,7 @@ static TypeTableEntry *ir_analyze_instruction_slice_type(IrAnalyze *ira, { type_ensure_zero_bits_known(ira->codegen, child_type); TypeTableEntry *slice_ptr_type = get_pointer_to_type_extra(ira->codegen, child_type, - is_const, is_volatile, align_bytes, 0, 0); + is_const, is_volatile, PtrLenUnknown, align_bytes, 0, 0); TypeTableEntry *result_type = get_slice_type(ira->codegen, slice_ptr_type); ConstExprValue *out_val = ir_build_const_from(ira, &slice_type_instruction->base); out_val->data.x_type = result_type; @@ -14619,6 +14675,7 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_maybe(IrAnalyze *ira, TypeTableEntry *child_type = type_entry->data.maybe.child_type; TypeTableEntry *result_type = get_pointer_to_type_extra(ira->codegen, child_type, ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile, + PtrLenSingle, get_abi_alignment(ira->codegen, child_type), 0, 0); if (instr_is_comptime(value)) { @@ -15566,7 +15623,8 @@ static TypeTableEntry *ir_analyze_instruction_err_name(IrAnalyze *ira, IrInstruc if (type_is_invalid(casted_value->value.type)) return ira->codegen->builtin_types.entry_invalid; - TypeTableEntry *u8_ptr_type = get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, true); + TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(ira->codegen, ira->codegen->builtin_types.entry_u8, + true, false, PtrLenUnknown, get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8), 0, 0); TypeTableEntry *str_type = get_slice_type(ira->codegen, u8_ptr_type); if (casted_value->value.special == ConstValSpecialStatic) { ErrorTableEntry *err = casted_value->value.data.x_err_set; @@ -15607,7 +15665,11 @@ static TypeTableEntry *ir_analyze_instruction_enum_tag_name(IrAnalyze *ira, IrIn IrInstruction *result = ir_build_tag_name(&ira->new_irb, instruction->base.scope, instruction->base.source_node, target); ir_link_new_instruction(result, &instruction->base); - TypeTableEntry *u8_ptr_type = get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, true); + TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra( + ira->codegen, ira->codegen->builtin_types.entry_u8, + true, false, PtrLenUnknown, + get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8), + 0, 0); result->value.type = get_slice_type(ira->codegen, u8_ptr_type); return result->value.type; } @@ -15660,6 +15722,7 @@ static TypeTableEntry *ir_analyze_instruction_field_parent_ptr(IrAnalyze *ira, TypeTableEntry *field_ptr_type = get_pointer_to_type_extra(ira->codegen, field->type_entry, field_ptr->value.type->data.pointer.is_const, field_ptr->value.type->data.pointer.is_volatile, + PtrLenSingle, field_ptr_align, 0, 0); IrInstruction *casted_field_ptr = ir_implicit_cast(ira, field_ptr, field_ptr_type); if (type_is_invalid(casted_field_ptr->value.type)) @@ -15668,6 +15731,7 @@ static TypeTableEntry *ir_analyze_instruction_field_parent_ptr(IrAnalyze *ira, TypeTableEntry *result_type = get_pointer_to_type_extra(ira->codegen, container_type, casted_field_ptr->value.type->data.pointer.is_const, casted_field_ptr->value.type->data.pointer.is_volatile, + PtrLenSingle, parent_ptr_align, 0, 0); if (instr_is_comptime(casted_field_ptr)) { @@ -15983,11 +16047,13 @@ static bool ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop // lib_name: ?[]const u8 ensure_field_index(fn_def_val->type, "lib_name", 6); fn_def_fields[6].special = ConstValSpecialStatic; - fn_def_fields[6].type = get_maybe_type(ira->codegen, - get_slice_type(ira->codegen, get_pointer_to_type(ira->codegen, - ira->codegen->builtin_types.entry_u8, true))); - if (fn_node->is_extern && buf_len(fn_node->lib_name) > 0) - { + TypeTableEntry *u8_ptr = get_pointer_to_type_extra( + ira->codegen, ira->codegen->builtin_types.entry_u8, + true, false, PtrLenUnknown, + get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8), + 0, 0); + fn_def_fields[6].type = get_maybe_type(ira->codegen, get_slice_type(ira->codegen, u8_ptr)); + if (fn_node->is_extern && buf_len(fn_node->lib_name) > 0) { fn_def_fields[6].data.x_maybe = create_const_vals(1); ConstExprValue *lib_name = create_const_str_lit(ira->codegen, fn_node->lib_name); init_const_slice(ira->codegen, fn_def_fields[6].data.x_maybe, lib_name, 0, buf_len(fn_node->lib_name), true); @@ -16009,8 +16075,8 @@ static bool ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop size_t fn_arg_count = fn_entry->variable_list.length; ConstExprValue *fn_arg_name_array = create_const_vals(1); fn_arg_name_array->special = ConstValSpecialStatic; - fn_arg_name_array->type = get_array_type(ira->codegen, get_slice_type(ira->codegen, - get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, true)), fn_arg_count); + fn_arg_name_array->type = get_array_type(ira->codegen, + get_slice_type(ira->codegen, u8_ptr), fn_arg_count); fn_arg_name_array->data.x_array.special = ConstArraySpecialNone; fn_arg_name_array->data.x_array.s_none.parent.id = ConstParentIdNone; fn_arg_name_array->data.x_array.s_none.elements = create_const_vals(fn_arg_count); @@ -17088,7 +17154,8 @@ static TypeTableEntry *ir_analyze_instruction_memset(IrAnalyze *ira, IrInstructi TypeTableEntry *u8 = ira->codegen->builtin_types.entry_u8; uint32_t dest_align = (dest_uncasted_type->id == TypeTableEntryIdPointer) ? dest_uncasted_type->data.pointer.alignment : get_abi_alignment(ira->codegen, u8); - TypeTableEntry *u8_ptr = get_pointer_to_type_extra(ira->codegen, u8, false, dest_is_volatile, dest_align, 0, 0); + TypeTableEntry *u8_ptr = get_pointer_to_type_extra(ira->codegen, u8, false, dest_is_volatile, + PtrLenUnknown, dest_align, 0, 0); IrInstruction *casted_dest_ptr = ir_implicit_cast(ira, dest_ptr, u8_ptr); if (type_is_invalid(casted_dest_ptr->value.type)) @@ -17184,8 +17251,10 @@ static TypeTableEntry *ir_analyze_instruction_memcpy(IrAnalyze *ira, IrInstructi src_uncasted_type->data.pointer.alignment : get_abi_alignment(ira->codegen, u8); TypeTableEntry *usize = ira->codegen->builtin_types.entry_usize; - TypeTableEntry *u8_ptr_mut = get_pointer_to_type_extra(ira->codegen, u8, false, dest_is_volatile, dest_align, 0, 0); - TypeTableEntry *u8_ptr_const = get_pointer_to_type_extra(ira->codegen, u8, true, src_is_volatile, src_align, 0, 0); + TypeTableEntry *u8_ptr_mut = get_pointer_to_type_extra(ira->codegen, u8, false, dest_is_volatile, + PtrLenUnknown, dest_align, 0, 0); + TypeTableEntry *u8_ptr_const = get_pointer_to_type_extra(ira->codegen, u8, true, src_is_volatile, + PtrLenUnknown, src_align, 0, 0); IrInstruction *casted_dest_ptr = ir_implicit_cast(ira, dest_ptr, u8_ptr_mut); if (type_is_invalid(casted_dest_ptr->value.type)) @@ -17333,11 +17402,13 @@ static TypeTableEntry *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstructio TypeTableEntry *slice_ptr_type = get_pointer_to_type_extra(ira->codegen, array_type->data.array.child_type, ptr_type->data.pointer.is_const || is_comptime_const, ptr_type->data.pointer.is_volatile, + PtrLenUnknown, byte_alignment, 0, 0); return_type = get_slice_type(ira->codegen, slice_ptr_type); } else if (array_type->id == TypeTableEntryIdPointer) { TypeTableEntry *slice_ptr_type = get_pointer_to_type_extra(ira->codegen, array_type->data.pointer.child_type, array_type->data.pointer.is_const, array_type->data.pointer.is_volatile, + PtrLenUnknown, array_type->data.pointer.alignment, 0, 0); return_type = get_slice_type(ira->codegen, slice_ptr_type); if (!end) { @@ -17774,6 +17845,7 @@ static TypeTableEntry *ir_analyze_instruction_overflow_op(IrAnalyze *ira, IrInst if (result_ptr->value.type->id == TypeTableEntryIdPointer) { expected_ptr_type = get_pointer_to_type_extra(ira->codegen, dest_type, false, result_ptr->value.type->data.pointer.is_volatile, + PtrLenSingle, result_ptr->value.type->data.pointer.alignment, 0, 0); } else { expected_ptr_type = get_pointer_to_type(ira->codegen, dest_type, false); @@ -17929,6 +18001,7 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_err_payload(IrAnalyze *ira, TypeTableEntry *payload_type = type_entry->data.error_union.payload_type; TypeTableEntry *result_type = get_pointer_to_type_extra(ira->codegen, payload_type, ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile, + PtrLenSingle, get_abi_alignment(ira->codegen, payload_type), 0, 0); if (instr_is_comptime(value)) { ConstExprValue *ptr_val = ir_resolve_const(ira, value, UndefBad); @@ -18270,7 +18343,8 @@ static TypeTableEntry *ir_analyze_instruction_panic(IrAnalyze *ira, IrInstructio return ir_unreach_error(ira); } - TypeTableEntry *u8_ptr_type = get_pointer_to_type(ira->codegen, ira->codegen->builtin_types.entry_u8, true); + TypeTableEntry *u8_ptr_type = get_pointer_to_type_extra(ira->codegen, ira->codegen->builtin_types.entry_u8, + true, false, PtrLenUnknown, get_abi_alignment(ira->codegen, ira->codegen->builtin_types.entry_u8), 0, 0); TypeTableEntry *str_type = get_slice_type(ira->codegen, u8_ptr_type); IrInstruction *casted_msg = ir_implicit_cast(ira, msg, str_type); if (type_is_invalid(casted_msg->value.type)) @@ -18801,7 +18875,8 @@ static TypeTableEntry *ir_analyze_instruction_ptr_type(IrAnalyze *ira, IrInstruc ConstExprValue *out_val = ir_build_const_from(ira, &instruction->base); out_val->data.x_type = get_pointer_to_type_extra(ira->codegen, child_type, - instruction->is_const, instruction->is_volatile, align_bytes, + instruction->is_const, instruction->is_volatile, + instruction->ptr_len, align_bytes, instruction->bit_offset_start, instruction->bit_offset_end - instruction->bit_offset_start); return ira->codegen->builtin_types.entry_type; diff --git a/src/parser.cpp b/src/parser.cpp index 6c900c3bfa..3ad2de906b 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -1225,6 +1225,7 @@ static AstNode *ast_parse_prefix_op_expr(ParseContext *pc, size_t *token_index, AstNode *child_node = ast_parse_pointer_type(pc, token_index, token); child_node->column += 1; AstNode *parent_node = ast_create_node(pc, NodeTypePointerType, token); + parent_node->data.pointer_type.star_token = token; parent_node->data.pointer_type.op_expr = child_node; return parent_node; } diff --git a/std/buffer.zig b/std/buffer.zig index 305746e183..3b2936d223 100644 --- a/std/buffer.zig +++ b/std/buffer.zig @@ -122,7 +122,7 @@ pub const Buffer = struct { } /// For passing to C functions. - pub fn ptr(self: *const Buffer) *u8 { + pub fn ptr(self: *const Buffer) [*]u8 { return self.list.items.ptr; } }; diff --git a/std/c/darwin.zig b/std/c/darwin.zig index 69395e6b27..e3b53d9bea 100644 --- a/std/c/darwin.zig +++ b/std/c/darwin.zig @@ -1,7 +1,7 @@ extern "c" fn __error() *c_int; -pub extern "c" fn _NSGetExecutablePath(buf: *u8, bufsize: *u32) c_int; +pub extern "c" fn _NSGetExecutablePath(buf: [*]u8, bufsize: *u32) c_int; -pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: *u8, buf_len: usize, basep: *i64) usize; +pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: [*]u8, buf_len: usize, basep: *i64) usize; pub extern "c" fn mach_absolute_time() u64; pub extern "c" fn mach_timebase_info(tinfo: ?*mach_timebase_info_data) void; diff --git a/std/c/index.zig b/std/c/index.zig index 114b79cdae..ade37f36c1 100644 --- a/std/c/index.zig +++ b/std/c/index.zig @@ -9,6 +9,8 @@ pub use switch (builtin.os) { }; const empty_import = @import("../empty.zig"); +// TODO https://github.com/ziglang/zig/issues/265 on this whole file + pub extern "c" fn abort() noreturn; pub extern "c" fn exit(code: c_int) noreturn; pub extern "c" fn isatty(fd: c_int) c_int; @@ -16,45 +18,45 @@ pub extern "c" fn close(fd: c_int) c_int; pub extern "c" fn fstat(fd: c_int, buf: *Stat) c_int; pub extern "c" fn @"fstat$INODE64"(fd: c_int, buf: *Stat) c_int; pub extern "c" fn lseek(fd: c_int, offset: isize, whence: c_int) isize; -pub extern "c" fn open(path: *const u8, oflag: c_int, ...) c_int; +pub extern "c" fn open(path: [*]const u8, oflag: c_int, ...) c_int; pub extern "c" fn raise(sig: c_int) c_int; -pub extern "c" fn read(fd: c_int, buf: *c_void, nbyte: usize) isize; -pub extern "c" fn stat(noalias path: *const u8, noalias buf: *Stat) c_int; -pub extern "c" fn write(fd: c_int, buf: *const c_void, nbyte: usize) isize; -pub extern "c" fn mmap(addr: ?*c_void, len: usize, prot: c_int, flags: c_int, fd: c_int, offset: isize) ?*c_void; -pub extern "c" fn munmap(addr: *c_void, len: usize) c_int; -pub extern "c" fn unlink(path: *const u8) c_int; -pub extern "c" fn getcwd(buf: *u8, size: usize) ?*u8; +pub extern "c" fn read(fd: c_int, buf: [*]c_void, nbyte: usize) isize; +pub extern "c" fn stat(noalias path: [*]const u8, noalias buf: *Stat) c_int; +pub extern "c" fn write(fd: c_int, buf: [*]const c_void, nbyte: usize) isize; +pub extern "c" fn mmap(addr: ?[*]c_void, len: usize, prot: c_int, flags: c_int, fd: c_int, offset: isize) ?[*]c_void; +pub extern "c" fn munmap(addr: [*]c_void, len: usize) c_int; +pub extern "c" fn unlink(path: [*]const u8) c_int; +pub extern "c" fn getcwd(buf: [*]u8, size: usize) ?[*]u8; pub extern "c" fn waitpid(pid: c_int, stat_loc: *c_int, options: c_int) c_int; pub extern "c" fn fork() c_int; -pub extern "c" fn access(path: *const u8, mode: c_uint) c_int; -pub extern "c" fn pipe(fds: *c_int) c_int; -pub extern "c" fn mkdir(path: *const u8, mode: c_uint) c_int; -pub extern "c" fn symlink(existing: *const u8, new: *const u8) c_int; -pub extern "c" fn rename(old: *const u8, new: *const u8) c_int; -pub extern "c" fn chdir(path: *const u8) c_int; -pub extern "c" fn execve(path: *const u8, argv: *const ?*const u8, envp: *const ?*const u8) c_int; +pub extern "c" fn access(path: [*]const u8, mode: c_uint) c_int; +pub extern "c" fn pipe(fds: *[2]c_int) c_int; +pub extern "c" fn mkdir(path: [*]const u8, mode: c_uint) c_int; +pub extern "c" fn symlink(existing: [*]const u8, new: [*]const u8) c_int; +pub extern "c" fn rename(old: [*]const u8, new: [*]const u8) c_int; +pub extern "c" fn chdir(path: [*]const u8) c_int; +pub extern "c" fn execve(path: [*]const u8, argv: [*]const ?[*]const u8, envp: [*]const ?[*]const u8) c_int; pub extern "c" fn dup(fd: c_int) c_int; pub extern "c" fn dup2(old_fd: c_int, new_fd: c_int) c_int; -pub extern "c" fn readlink(noalias path: *const u8, noalias buf: *u8, bufsize: usize) isize; -pub extern "c" fn realpath(noalias file_name: *const u8, noalias resolved_name: *u8) ?*u8; +pub extern "c" fn readlink(noalias path: [*]const u8, noalias buf: [*]u8, bufsize: usize) isize; +pub extern "c" fn realpath(noalias file_name: [*]const u8, noalias resolved_name: [*]u8) ?[*]u8; pub extern "c" fn sigprocmask(how: c_int, noalias set: *const sigset_t, noalias oset: ?*sigset_t) c_int; pub extern "c" fn gettimeofday(tv: ?*timeval, tz: ?*timezone) c_int; pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int; pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int; pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int; pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) c_int; -pub extern "c" fn rmdir(path: *const u8) c_int; +pub extern "c" fn rmdir(path: [*]const u8) c_int; -pub extern "c" fn aligned_alloc(alignment: usize, size: usize) ?*c_void; -pub extern "c" fn malloc(usize) ?*c_void; -pub extern "c" fn realloc(*c_void, usize) ?*c_void; -pub extern "c" fn free(*c_void) void; -pub extern "c" fn posix_memalign(memptr: **c_void, alignment: usize, size: usize) c_int; +pub extern "c" fn aligned_alloc(alignment: usize, size: usize) ?[*]c_void; +pub extern "c" fn malloc(usize) ?[*]c_void; +pub extern "c" fn realloc([*]c_void, usize) ?[*]c_void; +pub extern "c" fn free([*]c_void) void; +pub extern "c" fn posix_memalign(memptr: *[*]c_void, alignment: usize, size: usize) c_int; pub 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; pub extern "pthread" fn pthread_attr_init(attr: *pthread_attr_t) c_int; -pub extern "pthread" fn pthread_attr_setstack(attr: *pthread_attr_t, stackaddr: *c_void, stacksize: usize) c_int; +pub extern "pthread" fn pthread_attr_setstack(attr: *pthread_attr_t, stackaddr: [*]c_void, stacksize: usize) c_int; pub extern "pthread" fn pthread_attr_destroy(attr: *pthread_attr_t) c_int; pub extern "pthread" fn pthread_join(thread: pthread_t, arg_return: ?*?*c_void) c_int; diff --git a/std/c/linux.zig b/std/c/linux.zig index 0ab043533e..2699e9bd09 100644 --- a/std/c/linux.zig +++ b/std/c/linux.zig @@ -1,6 +1,6 @@ pub use @import("../os/linux/errno.zig"); -pub extern "c" fn getrandom(buf_ptr: *u8, buf_len: usize, flags: c_uint) c_int; +pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) c_int; extern "c" fn __errno_location() *c_int; pub const _errno = __errno_location; diff --git a/std/cstr.zig b/std/cstr.zig index d60adf8faa..d9106769c1 100644 --- a/std/cstr.zig +++ b/std/cstr.zig @@ -57,7 +57,7 @@ pub fn addNullByte(allocator: *mem.Allocator, slice: []const u8) ![]u8 { pub const NullTerminated2DArray = struct { allocator: *mem.Allocator, byte_count: usize, - ptr: ?*?*u8, + ptr: ?[*]?[*]u8, /// Takes N lists of strings, concatenates the lists together, and adds a null terminator /// Caller must deinit result @@ -79,12 +79,12 @@ pub const NullTerminated2DArray = struct { errdefer allocator.free(buf); var write_index = index_size; - const index_buf = ([]?*u8)(buf); + const index_buf = ([]?[*]u8)(buf); var i: usize = 0; for (slices) |slice| { for (slice) |inner| { - index_buf[i] = &buf[write_index]; + index_buf[i] = buf.ptr + write_index; i += 1; mem.copy(u8, buf[write_index..], inner); write_index += inner.len; @@ -97,12 +97,12 @@ pub const NullTerminated2DArray = struct { return NullTerminated2DArray{ .allocator = allocator, .byte_count = byte_count, - .ptr = @ptrCast(?*?*u8, buf.ptr), + .ptr = @ptrCast(?[*]?[*]u8, buf.ptr), }; } pub fn deinit(self: *NullTerminated2DArray) void { - const buf = @ptrCast(*u8, self.ptr); + const buf = @ptrCast([*]u8, self.ptr); self.allocator.free(buf[0..self.byte_count]); } }; diff --git a/std/heap.zig b/std/heap.zig index d15a99a757..0b8f4aeb3f 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -18,11 +18,11 @@ var c_allocator_state = Allocator{ fn cAlloc(self: *Allocator, n: usize, alignment: u29) ![]u8 { assert(alignment <= @alignOf(c_longdouble)); - return if (c.malloc(n)) |buf| @ptrCast(*u8, buf)[0..n] else error.OutOfMemory; + return if (c.malloc(n)) |buf| @ptrCast([*]u8, buf)[0..n] else error.OutOfMemory; } fn cRealloc(self: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { - const old_ptr = @ptrCast(*c_void, old_mem.ptr); + const old_ptr = @ptrCast([*]c_void, old_mem.ptr); if (c.realloc(old_ptr, new_size)) |buf| { return @ptrCast(*u8, buf)[0..new_size]; } else if (new_size <= old_mem.len) { @@ -33,7 +33,7 @@ fn cRealloc(self: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![ } fn cFree(self: *Allocator, old_mem: []u8) void { - const old_ptr = @ptrCast(*c_void, old_mem.ptr); + const old_ptr = @ptrCast([*]c_void, old_mem.ptr); c.free(old_ptr); } @@ -74,7 +74,7 @@ pub const DirectAllocator = struct { const addr = p.mmap(null, alloc_size, p.PROT_READ | p.PROT_WRITE, p.MAP_PRIVATE | p.MAP_ANONYMOUS, -1, 0); if (addr == p.MAP_FAILED) return error.OutOfMemory; - if (alloc_size == n) return @intToPtr(*u8, addr)[0..n]; + if (alloc_size == n) return @intToPtr([*]u8, addr)[0..n]; var aligned_addr = addr & ~usize(alignment - 1); aligned_addr += alignment; @@ -93,7 +93,7 @@ pub const DirectAllocator = struct { //It is impossible that there is an unoccupied page at the top of our // mmap. - return @intToPtr(*u8, aligned_addr)[0..n]; + return @intToPtr([*]u8, aligned_addr)[0..n]; }, Os.windows => { const amt = n + alignment + @sizeOf(usize); @@ -109,7 +109,7 @@ pub const DirectAllocator = struct { const adjusted_addr = root_addr + march_forward_bytes; const record_addr = adjusted_addr + n; @intToPtr(*align(1) usize, record_addr).* = root_addr; - return @intToPtr(*u8, adjusted_addr)[0..n]; + return @intToPtr([*]u8, adjusted_addr)[0..n]; }, else => @compileError("Unsupported OS"), } @@ -140,7 +140,7 @@ pub const DirectAllocator = struct { const old_adjusted_addr = @ptrToInt(old_mem.ptr); const old_record_addr = old_adjusted_addr + old_mem.len; const root_addr = @intToPtr(*align(1) usize, old_record_addr).*; - const old_ptr = @intToPtr(os.windows.LPVOID, root_addr); + const old_ptr = @intToPtr([*]c_void, root_addr); const amt = new_size + alignment + @sizeOf(usize); const new_ptr = os.windows.HeapReAlloc(??self.heap_handle, 0, old_ptr, amt) ?? blk: { if (new_size > old_mem.len) return error.OutOfMemory; @@ -154,7 +154,7 @@ pub const DirectAllocator = struct { assert(new_adjusted_addr % alignment == 0); const new_record_addr = new_adjusted_addr + new_size; @intToPtr(*align(1) usize, new_record_addr).* = new_root_addr; - return @intToPtr(*u8, new_adjusted_addr)[0..new_size]; + return @intToPtr([*]u8, new_adjusted_addr)[0..new_size]; }, else => @compileError("Unsupported OS"), } @@ -170,7 +170,7 @@ pub const DirectAllocator = struct { Os.windows => { const record_addr = @ptrToInt(bytes.ptr) + bytes.len; const root_addr = @intToPtr(*align(1) usize, record_addr).*; - const ptr = @intToPtr(os.windows.LPVOID, root_addr); + const ptr = @intToPtr([*]c_void, root_addr); _ = os.windows.HeapFree(??self.heap_handle, 0, ptr); }, else => @compileError("Unsupported OS"), diff --git a/std/os/child_process.zig b/std/os/child_process.zig index 0e80ae09c1..822ade2eb8 100644 --- a/std/os/child_process.zig +++ b/std/os/child_process.zig @@ -639,7 +639,7 @@ pub const ChildProcess = struct { } }; -fn windowsCreateProcess(app_name: *u8, cmd_line: *u8, envp_ptr: ?*u8, cwd_ptr: ?*u8, lpStartupInfo: *windows.STARTUPINFOA, lpProcessInformation: *windows.PROCESS_INFORMATION) !void { +fn windowsCreateProcess(app_name: [*]u8, cmd_line: [*]u8, envp_ptr: ?[*]u8, cwd_ptr: ?[*]u8, lpStartupInfo: *windows.STARTUPINFOA, lpProcessInformation: *windows.PROCESS_INFORMATION) !void { if (windows.CreateProcessA(app_name, cmd_line, null, null, windows.TRUE, 0, @ptrCast(?*c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation) == 0) { const err = windows.GetLastError(); return switch (err) { diff --git a/std/os/darwin.zig b/std/os/darwin.zig index 77e8b6bb6a..b8e18561cc 100644 --- a/std/os/darwin.zig +++ b/std/os/darwin.zig @@ -317,7 +317,8 @@ pub fn lseek(fd: i32, offset: isize, whence: c_int) usize { return errnoWrap(c.lseek(fd, offset, whence)); } -pub fn open(path: *const u8, flags: u32, mode: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 on the whole file +pub fn open(path: [*]const u8, flags: u32, mode: usize) usize { return errnoWrap(c.open(path, @bitCast(c_int, flags), mode)); } @@ -325,33 +326,33 @@ pub fn raise(sig: i32) usize { return errnoWrap(c.raise(sig)); } -pub fn read(fd: i32, buf: *u8, nbyte: usize) usize { - return errnoWrap(c.read(fd, @ptrCast(*c_void, buf), nbyte)); +pub fn read(fd: i32, buf: [*]u8, nbyte: usize) usize { + return errnoWrap(c.read(fd, @ptrCast([*]c_void, buf), nbyte)); } -pub fn stat(noalias path: *const u8, noalias buf: *stat) usize { +pub fn stat(noalias path: [*]const u8, noalias buf: *stat) usize { return errnoWrap(c.stat(path, buf)); } -pub fn write(fd: i32, buf: *const u8, nbyte: usize) usize { - return errnoWrap(c.write(fd, @ptrCast(*const c_void, buf), nbyte)); +pub fn write(fd: i32, buf: [*]const u8, nbyte: usize) usize { + return errnoWrap(c.write(fd, @ptrCast([*]const c_void, buf), nbyte)); } -pub fn mmap(address: ?*u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { - const ptr_result = c.mmap(@ptrCast(*c_void, address), length, @bitCast(c_int, c_uint(prot)), @bitCast(c_int, c_uint(flags)), fd, offset); +pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { + const ptr_result = c.mmap(@ptrCast([*]c_void, address), length, @bitCast(c_int, c_uint(prot)), @bitCast(c_int, c_uint(flags)), fd, offset); const isize_result = @bitCast(isize, @ptrToInt(ptr_result)); return errnoWrap(isize_result); } pub fn munmap(address: usize, length: usize) usize { - return errnoWrap(c.munmap(@intToPtr(*c_void, address), length)); + return errnoWrap(c.munmap(@intToPtr([*]c_void, address), length)); } -pub fn unlink(path: *const u8) usize { +pub fn unlink(path: [*]const u8) usize { return errnoWrap(c.unlink(path)); } -pub fn getcwd(buf: *u8, size: usize) usize { +pub fn getcwd(buf: [*]u8, size: usize) usize { return if (c.getcwd(buf, size) == null) @bitCast(usize, -isize(c._errno().*)) else 0; } @@ -364,40 +365,40 @@ pub fn fork() usize { return errnoWrap(c.fork()); } -pub fn access(path: *const u8, mode: u32) usize { +pub fn access(path: [*]const u8, mode: u32) usize { return errnoWrap(c.access(path, mode)); } pub fn pipe(fds: *[2]i32) usize { comptime assert(i32.bit_count == c_int.bit_count); - return errnoWrap(c.pipe(@ptrCast(*c_int, fds))); + return errnoWrap(c.pipe(@ptrCast(*[2]c_int, fds))); } -pub fn getdirentries64(fd: i32, buf_ptr: *u8, buf_len: usize, basep: *i64) usize { +pub fn getdirentries64(fd: i32, buf_ptr: [*]u8, buf_len: usize, basep: *i64) usize { return errnoWrap(@bitCast(isize, c.__getdirentries64(fd, buf_ptr, buf_len, basep))); } -pub fn mkdir(path: *const u8, mode: u32) usize { +pub fn mkdir(path: [*]const u8, mode: u32) usize { return errnoWrap(c.mkdir(path, mode)); } -pub fn symlink(existing: *const u8, new: *const u8) usize { +pub fn symlink(existing: [*]const u8, new: [*]const u8) usize { return errnoWrap(c.symlink(existing, new)); } -pub fn rename(old: *const u8, new: *const u8) usize { +pub fn rename(old: [*]const u8, new: [*]const u8) usize { return errnoWrap(c.rename(old, new)); } -pub fn rmdir(path: *const u8) usize { +pub fn rmdir(path: [*]const u8) usize { return errnoWrap(c.rmdir(path)); } -pub fn chdir(path: *const u8) usize { +pub fn chdir(path: [*]const u8) usize { return errnoWrap(c.chdir(path)); } -pub fn execve(path: *const u8, argv: *const ?*const u8, envp: *const ?*const u8) usize { +pub fn execve(path: [*]const u8, argv: [*]const ?[*]const u8, envp: [*]const ?[*]const u8) usize { return errnoWrap(c.execve(path, argv, envp)); } @@ -405,7 +406,7 @@ pub fn dup2(old: i32, new: i32) usize { return errnoWrap(c.dup2(old, new)); } -pub fn readlink(noalias path: *const u8, noalias buf_ptr: *u8, buf_len: usize) usize { +pub fn readlink(noalias path: [*]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize { return errnoWrap(c.readlink(path, buf_ptr, buf_len)); } @@ -417,7 +418,7 @@ pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize { return errnoWrap(c.nanosleep(req, rem)); } -pub fn realpath(noalias filename: *const u8, noalias resolved_name: *u8) usize { +pub fn realpath(noalias filename: [*]const u8, noalias resolved_name: [*]u8) usize { return if (c.realpath(filename, resolved_name) == null) @bitCast(usize, -isize(c._errno().*)) else 0; } diff --git a/std/os/file.zig b/std/os/file.zig index d943da30ca..378782507b 100644 --- a/std/os/file.zig +++ b/std/os/file.zig @@ -313,7 +313,7 @@ pub const File = struct { if (is_posix) { var index: usize = 0; while (index < buffer.len) { - const amt_read = posix.read(self.handle, &buffer[index], buffer.len - index); + const amt_read = posix.read(self.handle, buffer.ptr + index, buffer.len - index); const read_err = posix.getErrno(amt_read); if (read_err > 0) { switch (read_err) { @@ -334,7 +334,7 @@ pub const File = struct { while (index < buffer.len) { const want_read_count = windows.DWORD(math.min(windows.DWORD(@maxValue(windows.DWORD)), buffer.len - index)); var amt_read: windows.DWORD = undefined; - if (windows.ReadFile(self.handle, @ptrCast(*c_void, &buffer[index]), want_read_count, &amt_read, null) == 0) { + if (windows.ReadFile(self.handle, @ptrCast([*]c_void, buffer.ptr + index), want_read_count, &amt_read, null) == 0) { const err = windows.GetLastError(); return switch (err) { windows.ERROR.OPERATION_ABORTED => continue, diff --git a/std/os/index.zig b/std/os/index.zig index ff638c670b..7e908af9eb 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -134,20 +134,7 @@ pub fn getRandomBytes(buf: []u8) !void { } }, Os.zen => { - const randomness = []u8{ - 42, - 1, - 7, - 12, - 22, - 17, - 99, - 16, - 26, - 87, - 41, - 45, - }; + const randomness = []u8{ 42, 1, 7, 12, 22, 17, 99, 16, 26, 87, 41, 45 }; var i: usize = 0; while (i < buf.len) : (i += 1) { if (i > randomness.len) return error.Unknown; @@ -238,7 +225,7 @@ pub fn posixRead(fd: i32, buf: []u8) !void { var index: usize = 0; while (index < buf.len) { const want_to_read = math.min(buf.len - index, usize(max_buf_len)); - const rc = posix.read(fd, &buf[index], want_to_read); + const rc = posix.read(fd, buf.ptr + index, want_to_read); const err = posix.getErrno(rc); if (err > 0) { return switch (err) { @@ -278,7 +265,7 @@ pub fn posixWrite(fd: i32, bytes: []const u8) !void { var index: usize = 0; while (index < bytes.len) { const amt_to_write = math.min(bytes.len - index, usize(max_bytes_len)); - const rc = posix.write(fd, &bytes[index], amt_to_write); + const rc = posix.write(fd, bytes.ptr + index, amt_to_write); const write_err = posix.getErrno(rc); if (write_err > 0) { return switch (write_err) { @@ -328,7 +315,8 @@ pub fn posixOpen(allocator: *Allocator, file_path: []const u8, flags: u32, perm: return posixOpenC(path_with_null.ptr, flags, perm); } -pub fn posixOpenC(file_path: *const u8, flags: u32, perm: usize) !i32 { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn posixOpenC(file_path: [*]const u8, flags: u32, perm: usize) !i32 { while (true) { const result = posix.open(file_path, flags, perm); const err = posix.getErrno(result); @@ -374,19 +362,19 @@ pub fn posixDup2(old_fd: i32, new_fd: i32) !void { } } -pub fn createNullDelimitedEnvMap(allocator: *Allocator, env_map: *const BufMap) ![]?*u8 { +pub fn createNullDelimitedEnvMap(allocator: *Allocator, env_map: *const BufMap) ![]?[*]u8 { const envp_count = env_map.count(); - const envp_buf = try allocator.alloc(?*u8, envp_count + 1); - mem.set(?*u8, envp_buf, null); + const envp_buf = try allocator.alloc(?[*]u8, envp_count + 1); + mem.set(?[*]u8, envp_buf, null); errdefer freeNullDelimitedEnvMap(allocator, envp_buf); { var it = env_map.iterator(); var i: usize = 0; while (it.next()) |pair| : (i += 1) { const env_buf = try allocator.alloc(u8, pair.key.len + pair.value.len + 2); - @memcpy(&env_buf[0], pair.key.ptr, pair.key.len); + @memcpy(env_buf.ptr, pair.key.ptr, pair.key.len); env_buf[pair.key.len] = '='; - @memcpy(&env_buf[pair.key.len + 1], pair.value.ptr, pair.value.len); + @memcpy(env_buf.ptr + pair.key.len + 1, pair.value.ptr, pair.value.len); env_buf[env_buf.len - 1] = 0; envp_buf[i] = env_buf.ptr; @@ -397,7 +385,7 @@ pub fn createNullDelimitedEnvMap(allocator: *Allocator, env_map: *const BufMap) return envp_buf; } -pub fn freeNullDelimitedEnvMap(allocator: *Allocator, envp_buf: []?*u8) void { +pub fn freeNullDelimitedEnvMap(allocator: *Allocator, envp_buf: []?[*]u8) void { for (envp_buf) |env| { const env_buf = if (env) |ptr| ptr[0 .. cstr.len(ptr) + 1] else break; allocator.free(env_buf); @@ -411,8 +399,8 @@ pub fn freeNullDelimitedEnvMap(allocator: *Allocator, envp_buf: []?*u8) void { /// `argv[0]` is the executable path. /// This function also uses the PATH environment variable to get the full path to the executable. pub fn posixExecve(argv: []const []const u8, env_map: *const BufMap, allocator: *Allocator) !void { - const argv_buf = try allocator.alloc(?*u8, argv.len + 1); - mem.set(?*u8, argv_buf, null); + const argv_buf = try allocator.alloc(?[*]u8, argv.len + 1); + mem.set(?[*]u8, argv_buf, null); defer { for (argv_buf) |arg| { const arg_buf = if (arg) |ptr| cstr.toSlice(ptr) else break; @@ -422,7 +410,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: *const BufMap, allocator: } for (argv) |arg, i| { const arg_buf = try allocator.alloc(u8, arg.len + 1); - @memcpy(&arg_buf[0], arg.ptr, arg.len); + @memcpy(arg_buf.ptr, arg.ptr, arg.len); arg_buf[arg.len] = 0; argv_buf[i] = arg_buf.ptr; @@ -494,7 +482,7 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError { } pub var linux_aux_raw = []usize{0} ** 38; -pub var posix_environ_raw: []*u8 = undefined; +pub var posix_environ_raw: [][*]u8 = undefined; /// Caller must free result when done. pub fn getEnvMap(allocator: *Allocator) !BufMap { @@ -1311,7 +1299,7 @@ pub const Dir = struct { const next_index = self.index + linux_entry.d_reclen; self.index = next_index; - const name = cstr.toSlice(&linux_entry.d_name); + const name = cstr.toSlice(@ptrCast([*]u8, &linux_entry.d_name)); // skip . and .. entries if (mem.eql(u8, name, ".") or mem.eql(u8, name, "..")) { @@ -1485,12 +1473,12 @@ pub const ArgIteratorPosix = struct { /// This is marked as public but actually it's only meant to be used /// internally by zig's startup code. - pub var raw: []*u8 = undefined; + pub var raw: [][*]u8 = undefined; }; pub const ArgIteratorWindows = struct { index: usize, - cmd_line: *const u8, + cmd_line: [*]const u8, in_quote: bool, quote_count: usize, seen_quote_count: usize, @@ -1501,7 +1489,7 @@ pub const ArgIteratorWindows = struct { return initWithCmdLine(windows.GetCommandLineA()); } - pub fn initWithCmdLine(cmd_line: *const u8) ArgIteratorWindows { + pub fn initWithCmdLine(cmd_line: [*]const u8) ArgIteratorWindows { return ArgIteratorWindows{ .index = 0, .cmd_line = cmd_line, @@ -1616,7 +1604,7 @@ pub const ArgIteratorWindows = struct { } } - fn countQuotes(cmd_line: *const u8) usize { + fn countQuotes(cmd_line: [*]const u8) usize { var result: usize = 0; var backslash_count: usize = 0; var index: usize = 0; @@ -1722,39 +1710,12 @@ pub fn argsFree(allocator: *mem.Allocator, args_alloc: []const []u8) void { } test "windows arg parsing" { - testWindowsCmdLine(c"a b\tc d", [][]const u8{ - "a", - "b", - "c", - "d", - }); - testWindowsCmdLine(c"\"abc\" d e", [][]const u8{ - "abc", - "d", - "e", - }); - testWindowsCmdLine(c"a\\\\\\b d\"e f\"g h", [][]const u8{ - "a\\\\\\b", - "de fg", - "h", - }); - testWindowsCmdLine(c"a\\\\\\\"b c d", [][]const u8{ - "a\\\"b", - "c", - "d", - }); - testWindowsCmdLine(c"a\\\\\\\\\"b c\" d e", [][]const u8{ - "a\\\\b c", - "d", - "e", - }); - testWindowsCmdLine(c"a b\tc \"d f", [][]const u8{ - "a", - "b", - "c", - "\"d", - "f", - }); + testWindowsCmdLine(c"a b\tc d", [][]const u8{ "a", "b", "c", "d" }); + testWindowsCmdLine(c"\"abc\" d e", [][]const u8{ "abc", "d", "e" }); + testWindowsCmdLine(c"a\\\\\\b d\"e f\"g h", [][]const u8{ "a\\\\\\b", "de fg", "h" }); + testWindowsCmdLine(c"a\\\\\\\"b c d", [][]const u8{ "a\\\"b", "c", "d" }); + testWindowsCmdLine(c"a\\\\\\\\\"b c\" d e", [][]const u8{ "a\\\\b c", "d", "e" }); + testWindowsCmdLine(c"a b\tc \"d f", [][]const u8{ "a", "b", "c", "\"d", "f" }); testWindowsCmdLine(c"\".\\..\\zig-cache\\build\" \"bin\\zig.exe\" \".\\..\" \".\\..\\zig-cache\" \"--help\"", [][]const u8{ ".\\..\\zig-cache\\build", @@ -1765,7 +1726,7 @@ test "windows arg parsing" { }); } -fn testWindowsCmdLine(input_cmd_line: *const u8, expected_args: []const []const u8) void { +fn testWindowsCmdLine(input_cmd_line: [*]const u8, expected_args: []const []const u8) void { var it = ArgIteratorWindows.initWithCmdLine(input_cmd_line); for (expected_args) |expected_arg| { const arg = ??it.next(debug.global_allocator) catch unreachable; @@ -2350,7 +2311,7 @@ pub fn posixConnectAsync(sockfd: i32, sockaddr: *const posix.sockaddr) PosixConn pub fn posixGetSockOptConnectError(sockfd: i32) PosixConnectError!void { var err_code: i32 = undefined; var size: u32 = @sizeOf(i32); - const rc = posix.getsockopt(sockfd, posix.SOL_SOCKET, posix.SO_ERROR, @ptrCast(*u8, &err_code), &size); + const rc = posix.getsockopt(sockfd, posix.SOL_SOCKET, posix.SO_ERROR, @ptrCast([*]u8, &err_code), &size); assert(size == 4); const err = posix.getErrno(rc); switch (err) { @@ -2401,7 +2362,7 @@ pub const Thread = struct { }, builtin.Os.windows => struct { handle: windows.HANDLE, - alloc_start: *c_void, + alloc_start: [*]c_void, heap_handle: windows.HANDLE, }, else => @compileError("Unsupported OS"), @@ -2500,7 +2461,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread const byte_count = @alignOf(WinThread.OuterContext) + @sizeOf(WinThread.OuterContext); const bytes_ptr = windows.HeapAlloc(heap_handle, 0, byte_count) ?? return SpawnThreadError.OutOfMemory; errdefer assert(windows.HeapFree(heap_handle, 0, bytes_ptr) != 0); - const bytes = @ptrCast(*u8, bytes_ptr)[0..byte_count]; + const bytes = @ptrCast([*]u8, bytes_ptr)[0..byte_count]; const outer_context = std.heap.FixedBufferAllocator.init(bytes).allocator.create(WinThread.OuterContext) catch unreachable; outer_context.inner = context; outer_context.thread.data.heap_handle = heap_handle; @@ -2572,7 +2533,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread // align to page stack_end -= stack_end % os.page_size; - assert(c.pthread_attr_setstack(&attr, @intToPtr(*c_void, stack_addr), stack_end - stack_addr) == 0); + assert(c.pthread_attr_setstack(&attr, @intToPtr([*]c_void, stack_addr), stack_end - stack_addr) == 0); const err = c.pthread_create(&thread_ptr.data.handle, &attr, MainFuncs.posixThreadMain, @intToPtr(*c_void, arg)); switch (err) { diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 3e7b836ac7..0e77371ec2 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -665,15 +665,18 @@ pub fn dup2(old: i32, new: i32) usize { return syscall2(SYS_dup2, usize(old), usize(new)); } -pub fn chdir(path: *const u8) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn chdir(path: [*]const u8) usize { return syscall1(SYS_chdir, @ptrToInt(path)); } -pub fn chroot(path: *const u8) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn chroot(path: [*]const u8) usize { return syscall1(SYS_chroot, @ptrToInt(path)); } -pub fn execve(path: *const u8, argv: *const ?*const u8, envp: *const ?*const u8) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn execve(path: [*]const u8, argv: [*]const ?[*]const u8, envp: [*]const ?[*]const u8) usize { return syscall3(SYS_execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp)); } @@ -685,11 +688,11 @@ pub fn futex_wait(uaddr: usize, futex_op: u32, val: i32, timeout: ?*timespec) us return syscall4(SYS_futex, uaddr, futex_op, @bitCast(u32, val), @ptrToInt(timeout)); } -pub fn getcwd(buf: *u8, size: usize) usize { +pub fn getcwd(buf: [*]u8, size: usize) usize { return syscall2(SYS_getcwd, @ptrToInt(buf), size); } -pub fn getdents(fd: i32, dirp: *u8, count: usize) usize { +pub fn getdents(fd: i32, dirp: [*]u8, count: usize) usize { return syscall3(SYS_getdents, usize(fd), @ptrToInt(dirp), count); } @@ -698,27 +701,32 @@ pub fn isatty(fd: i32) bool { return syscall3(SYS_ioctl, usize(fd), TIOCGWINSZ, @ptrToInt(&wsz)) == 0; } -pub fn readlink(noalias path: *const u8, noalias buf_ptr: *u8, buf_len: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn readlink(noalias path: [*]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize { return syscall3(SYS_readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); } -pub fn mkdir(path: *const u8, mode: u32) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn mkdir(path: [*]const u8, mode: u32) usize { return syscall2(SYS_mkdir, @ptrToInt(path), mode); } -pub fn mount(special: *const u8, dir: *const u8, fstype: *const u8, flags: usize, data: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn mount(special: [*]const u8, dir: [*]const u8, fstype: [*]const u8, flags: usize, data: usize) usize { return syscall5(SYS_mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data); } -pub fn umount(special: *const u8) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn umount(special: [*]const u8) usize { return syscall2(SYS_umount2, @ptrToInt(special), 0); } -pub fn umount2(special: *const u8, flags: u32) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn umount2(special: [*]const u8, flags: u32) usize { return syscall2(SYS_umount2, @ptrToInt(special), flags); } -pub fn mmap(address: ?*u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { +pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), @bitCast(usize, offset)); } @@ -726,23 +734,26 @@ pub fn munmap(address: usize, length: usize) usize { return syscall2(SYS_munmap, address, length); } -pub fn read(fd: i32, buf: *u8, count: usize) usize { +pub fn read(fd: i32, buf: [*]u8, count: usize) usize { return syscall3(SYS_read, usize(fd), @ptrToInt(buf), count); } -pub fn rmdir(path: *const u8) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn rmdir(path: [*]const u8) usize { return syscall1(SYS_rmdir, @ptrToInt(path)); } -pub fn symlink(existing: *const u8, new: *const u8) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn symlink(existing: [*]const u8, new: [*]const u8) usize { return syscall2(SYS_symlink, @ptrToInt(existing), @ptrToInt(new)); } -pub fn pread(fd: i32, buf: *u8, count: usize, offset: usize) usize { +pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: usize) usize { return syscall4(SYS_pread, usize(fd), @ptrToInt(buf), count, offset); } -pub fn access(path: *const u8, mode: u32) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn access(path: [*]const u8, mode: u32) usize { return syscall2(SYS_access, @ptrToInt(path), mode); } @@ -754,27 +765,31 @@ pub fn pipe2(fd: *[2]i32, flags: usize) usize { return syscall2(SYS_pipe2, @ptrToInt(fd), flags); } -pub fn write(fd: i32, buf: *const u8, count: usize) usize { +pub fn write(fd: i32, buf: [*]const u8, count: usize) usize { return syscall3(SYS_write, usize(fd), @ptrToInt(buf), count); } -pub fn pwrite(fd: i32, buf: *const u8, count: usize, offset: usize) usize { +pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize { return syscall4(SYS_pwrite, usize(fd), @ptrToInt(buf), count, offset); } -pub fn rename(old: *const u8, new: *const u8) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn rename(old: [*]const u8, new: [*]const u8) usize { return syscall2(SYS_rename, @ptrToInt(old), @ptrToInt(new)); } -pub fn open(path: *const u8, flags: u32, perm: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn open(path: [*]const u8, flags: u32, perm: usize) usize { return syscall3(SYS_open, @ptrToInt(path), flags, perm); } -pub fn create(path: *const u8, perm: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn create(path: [*]const u8, perm: usize) usize { return syscall2(SYS_creat, @ptrToInt(path), perm); } -pub fn openat(dirfd: i32, path: *const u8, flags: usize, mode: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn openat(dirfd: i32, path: [*]const u8, flags: usize, mode: usize) usize { return syscall4(SYS_openat, usize(dirfd), @ptrToInt(path), flags, mode); } @@ -801,7 +816,7 @@ pub fn exit(status: i32) noreturn { unreachable; } -pub fn getrandom(buf: *u8, count: usize, flags: u32) usize { +pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize { return syscall3(SYS_getrandom, @ptrToInt(buf), count, usize(flags)); } @@ -809,7 +824,8 @@ pub fn kill(pid: i32, sig: i32) usize { return syscall2(SYS_kill, @bitCast(usize, isize(pid)), usize(sig)); } -pub fn unlink(path: *const u8) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn unlink(path: [*]const u8) usize { return syscall1(SYS_unlink, @ptrToInt(path)); } @@ -942,8 +958,8 @@ pub fn sigaction(sig: u6, noalias act: *const Sigaction, noalias oact: ?*Sigacti .restorer = @ptrCast(extern fn () void, restore_rt), }; var ksa_old: k_sigaction = undefined; - @memcpy(@ptrCast(*u8, *ksa.mask), @ptrCast(*const u8, *act.mask), 8); - const result = syscall4(SYS_rt_sigaction, sig, @ptrToInt(*ksa), @ptrToInt(*ksa_old), @sizeOf(@typeOf(ksa.mask))); + @memcpy(@ptrCast([*]u8, &ksa.mask), @ptrCast([*]const u8, &act.mask), 8); + const result = syscall4(SYS_rt_sigaction, sig, @ptrToInt(&ksa), @ptrToInt(&ksa_old), @sizeOf(@typeOf(ksa.mask))); const err = getErrno(result); if (err != 0) { return result; @@ -951,7 +967,7 @@ pub fn sigaction(sig: u6, noalias act: *const Sigaction, noalias oact: ?*Sigacti if (oact) |old| { old.handler = ksa_old.handler; old.flags = @truncate(u32, ksa_old.flags); - @memcpy(@ptrCast(*u8, *old.mask), @ptrCast(*const u8, *ksa_old.mask), @sizeOf(@typeOf(ksa_old.mask))); + @memcpy(@ptrCast([*]u8, &old.mask), @ptrCast([*]const u8, &ksa_old.mask), @sizeOf(@typeOf(ksa_old.mask))); } return 0; } @@ -1036,7 +1052,7 @@ pub const sockaddr_in6 = extern struct { }; pub const iovec = extern struct { - iov_base: *u8, + iov_base: [*]u8, iov_len: usize, }; @@ -1052,11 +1068,11 @@ pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize { return syscall3(SYS_socket, domain, socket_type, protocol); } -pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: *const u8, optlen: socklen_t) usize { +pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: [*]const u8, optlen: socklen_t) usize { return syscall5(SYS_setsockopt, usize(fd), level, optname, usize(optval), @ptrToInt(optlen)); } -pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: *u8, noalias optlen: *socklen_t) usize { +pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: [*]u8, noalias optlen: *socklen_t) usize { return syscall5(SYS_getsockopt, usize(fd), level, optname, @ptrToInt(optval), @ptrToInt(optlen)); } @@ -1072,7 +1088,7 @@ pub fn recvmsg(fd: i32, msg: *msghdr, flags: u32) usize { return syscall3(SYS_recvmsg, usize(fd), @ptrToInt(msg), flags); } -pub fn recvfrom(fd: i32, noalias buf: *u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize { +pub fn recvfrom(fd: i32, noalias buf: [*]u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize { return syscall6(SYS_recvfrom, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); } @@ -1088,7 +1104,7 @@ pub fn listen(fd: i32, backlog: u32) usize { return syscall2(SYS_listen, usize(fd), backlog); } -pub fn sendto(fd: i32, buf: *const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize { +pub fn sendto(fd: i32, buf: [*]const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize { return syscall6(SYS_sendto, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), usize(alen)); } @@ -1108,59 +1124,72 @@ pub fn fstat(fd: i32, stat_buf: *Stat) usize { return syscall2(SYS_fstat, usize(fd), @ptrToInt(stat_buf)); } -pub fn stat(pathname: *const u8, statbuf: *Stat) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn stat(pathname: [*]const u8, statbuf: *Stat) usize { return syscall2(SYS_stat, @ptrToInt(pathname), @ptrToInt(statbuf)); } -pub fn lstat(pathname: *const u8, statbuf: *Stat) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn lstat(pathname: [*]const u8, statbuf: *Stat) usize { return syscall2(SYS_lstat, @ptrToInt(pathname), @ptrToInt(statbuf)); } -pub fn listxattr(path: *const u8, list: *u8, size: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn listxattr(path: [*]const u8, list: [*]u8, size: usize) usize { return syscall3(SYS_listxattr, @ptrToInt(path), @ptrToInt(list), size); } -pub fn llistxattr(path: *const u8, list: *u8, size: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn llistxattr(path: [*]const u8, list: [*]u8, size: usize) usize { return syscall3(SYS_llistxattr, @ptrToInt(path), @ptrToInt(list), size); } -pub fn flistxattr(fd: usize, list: *u8, size: usize) usize { +pub fn flistxattr(fd: usize, list: [*]u8, size: usize) usize { return syscall3(SYS_flistxattr, fd, @ptrToInt(list), size); } -pub fn getxattr(path: *const u8, name: *const u8, value: *void, size: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn getxattr(path: [*]const u8, name: [*]const u8, value: [*]u8, size: usize) usize { return syscall4(SYS_getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); } -pub fn lgetxattr(path: *const u8, name: *const u8, value: *void, size: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn lgetxattr(path: [*]const u8, name: [*]const u8, value: [*]u8, size: usize) usize { return syscall4(SYS_lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); } -pub fn fgetxattr(fd: usize, name: *const u8, value: *void, size: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn fgetxattr(fd: usize, name: [*]const u8, value: [*]u8, size: usize) usize { return syscall4(SYS_lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size); } -pub fn setxattr(path: *const u8, name: *const u8, value: *const void, size: usize, flags: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn setxattr(path: [*]const u8, name: [*]const u8, value: *const void, size: usize, flags: usize) usize { return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } -pub fn lsetxattr(path: *const u8, name: *const u8, value: *const void, size: usize, flags: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn lsetxattr(path: [*]const u8, name: [*]const u8, value: *const void, size: usize, flags: usize) usize { return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } -pub fn fsetxattr(fd: usize, name: *const u8, value: *const void, size: usize, flags: usize) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn fsetxattr(fd: usize, name: [*]const u8, value: *const void, size: usize, flags: usize) usize { return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags); } -pub fn removexattr(path: *const u8, name: *const u8) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn removexattr(path: [*]const u8, name: [*]const u8) usize { return syscall2(SYS_removexattr, @ptrToInt(path), @ptrToInt(name)); } -pub fn lremovexattr(path: *const u8, name: *const u8) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn lremovexattr(path: [*]const u8, name: [*]const u8) usize { return syscall2(SYS_lremovexattr, @ptrToInt(path), @ptrToInt(name)); } -pub fn fremovexattr(fd: usize, name: *const u8) usize { +// TODO https://github.com/ziglang/zig/issues/265 +pub fn fremovexattr(fd: usize, name: [*]const u8) usize { return syscall2(SYS_fremovexattr, fd, @ptrToInt(name)); } @@ -1188,7 +1217,7 @@ pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: *epoll_event) usize { return syscall4(SYS_epoll_ctl, usize(epoll_fd), usize(op), usize(fd), @ptrToInt(ev)); } -pub fn epoll_wait(epoll_fd: i32, events: *epoll_event, maxevents: u32, timeout: i32) usize { +pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32) usize { return syscall4(SYS_epoll_wait, usize(epoll_fd), @ptrToInt(events), usize(maxevents), usize(timeout)); } diff --git a/std/os/linux/test.zig b/std/os/linux/test.zig index 06aae1968f..948a3ac96b 100644 --- a/std/os/linux/test.zig +++ b/std/os/linux/test.zig @@ -35,5 +35,6 @@ test "timer" { const events_one: linux.epoll_event = undefined; var events = []linux.epoll_event{events_one} ** 8; - err = linux.epoll_wait(i32(epoll_fd), &events[0], 8, -1); + // TODO implicit cast from *[N]T to [*]T + err = linux.epoll_wait(i32(epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1); } diff --git a/std/os/linux/vdso.zig b/std/os/linux/vdso.zig index 1317da6388..2ab4d0cbc1 100644 --- a/std/os/linux/vdso.zig +++ b/std/os/linux/vdso.zig @@ -12,7 +12,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { var ph_addr: usize = vdso_addr + eh.e_phoff; const ph = @intToPtr(*elf.Phdr, ph_addr); - var maybe_dynv: ?*usize = null; + var maybe_dynv: ?[*]usize = null; var base: usize = @maxValue(usize); { var i: usize = 0; @@ -23,7 +23,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { const this_ph = @intToPtr(*elf.Phdr, ph_addr); switch (this_ph.p_type) { elf.PT_LOAD => base = vdso_addr + this_ph.p_offset - this_ph.p_vaddr, - elf.PT_DYNAMIC => maybe_dynv = @intToPtr(*usize, vdso_addr + this_ph.p_offset), + elf.PT_DYNAMIC => maybe_dynv = @intToPtr([*]usize, vdso_addr + this_ph.p_offset), else => {}, } } @@ -31,10 +31,10 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { const dynv = maybe_dynv ?? return 0; if (base == @maxValue(usize)) return 0; - var maybe_strings: ?*u8 = null; - var maybe_syms: ?*elf.Sym = null; - var maybe_hashtab: ?*linux.Elf_Symndx = null; - var maybe_versym: ?*u16 = null; + var maybe_strings: ?[*]u8 = null; + var maybe_syms: ?[*]elf.Sym = null; + var maybe_hashtab: ?[*]linux.Elf_Symndx = null; + var maybe_versym: ?[*]u16 = null; var maybe_verdef: ?*elf.Verdef = null; { @@ -42,10 +42,10 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { while (dynv[i] != 0) : (i += 2) { const p = base + dynv[i + 1]; switch (dynv[i]) { - elf.DT_STRTAB => maybe_strings = @intToPtr(*u8, p), - elf.DT_SYMTAB => maybe_syms = @intToPtr(*elf.Sym, p), - elf.DT_HASH => maybe_hashtab = @intToPtr(*linux.Elf_Symndx, p), - elf.DT_VERSYM => maybe_versym = @intToPtr(*u16, p), + elf.DT_STRTAB => maybe_strings = @intToPtr([*]u8, p), + elf.DT_SYMTAB => maybe_syms = @intToPtr([*]elf.Sym, p), + elf.DT_HASH => maybe_hashtab = @intToPtr([*]linux.Elf_Symndx, p), + elf.DT_VERSYM => maybe_versym = @intToPtr([*]u16, p), elf.DT_VERDEF => maybe_verdef = @intToPtr(*elf.Verdef, p), else => {}, } @@ -65,7 +65,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { if (0 == (u32(1) << u5(syms[i].st_info & 0xf) & OK_TYPES)) continue; if (0 == (u32(1) << u5(syms[i].st_info >> 4) & OK_BINDS)) continue; if (0 == syms[i].st_shndx) continue; - if (!mem.eql(u8, name, cstr.toSliceConst(&strings[syms[i].st_name]))) continue; + if (!mem.eql(u8, name, cstr.toSliceConst(strings + syms[i].st_name))) continue; if (maybe_versym) |versym| { if (!checkver(??maybe_verdef, versym[i], vername, strings)) continue; @@ -76,7 +76,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { return 0; } -fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: *u8) bool { +fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: [*]u8) bool { var def = def_arg; const vsym = @bitCast(u32, vsym_arg) & 0x7fff; while (true) { @@ -87,5 +87,5 @@ fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: * def = @intToPtr(*elf.Verdef, @ptrToInt(def) + def.vd_next); } const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux); - return mem.eql(u8, vername, cstr.toSliceConst(&strings[aux.vda_name])); + return mem.eql(u8, vername, cstr.toSliceConst(strings + aux.vda_name)); } diff --git a/std/os/windows/index.zig b/std/os/windows/index.zig index 85f69836d5..c491ae6538 100644 --- a/std/os/windows/index.zig +++ b/std/os/windows/index.zig @@ -10,7 +10,7 @@ pub extern "advapi32" stdcallcc fn CryptAcquireContextA( pub extern "advapi32" stdcallcc fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) BOOL; -pub extern "advapi32" stdcallcc fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *BYTE) BOOL; +pub extern "advapi32" stdcallcc fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: [*]BYTE) BOOL; pub extern "kernel32" stdcallcc fn CloseHandle(hObject: HANDLE) BOOL; @@ -61,7 +61,7 @@ pub extern "kernel32" stdcallcc fn DeleteFileA(lpFileName: LPCSTR) BOOL; pub extern "kernel32" stdcallcc fn ExitProcess(exit_code: UINT) noreturn; -pub extern "kernel32" stdcallcc fn FreeEnvironmentStringsA(penv: LPCH) BOOL; +pub extern "kernel32" stdcallcc fn FreeEnvironmentStringsA(penv: [*]u8) BOOL; pub extern "kernel32" stdcallcc fn GetCommandLineA() LPSTR; @@ -69,7 +69,7 @@ pub extern "kernel32" stdcallcc fn GetConsoleMode(in_hConsoleHandle: HANDLE, out pub extern "kernel32" stdcallcc fn GetCurrentDirectoryA(nBufferLength: WORD, lpBuffer: ?LPSTR) DWORD; -pub extern "kernel32" stdcallcc fn GetEnvironmentStringsA() ?LPCH; +pub extern "kernel32" stdcallcc fn GetEnvironmentStringsA() ?[*]u8; pub extern "kernel32" stdcallcc fn GetEnvironmentVariableA(lpName: LPCSTR, lpBuffer: LPSTR, nSize: DWORD) DWORD; @@ -101,17 +101,17 @@ pub extern "kernel32" stdcallcc fn GetSystemTimeAsFileTime(?*FILETIME) void; pub extern "kernel32" stdcallcc fn HeapCreate(flOptions: DWORD, dwInitialSize: SIZE_T, dwMaximumSize: SIZE_T) ?HANDLE; pub extern "kernel32" stdcallcc fn HeapDestroy(hHeap: HANDLE) BOOL; -pub extern "kernel32" stdcallcc fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: *c_void, dwBytes: SIZE_T) ?*c_void; -pub extern "kernel32" stdcallcc fn HeapSize(hHeap: HANDLE, dwFlags: DWORD, lpMem: *const c_void) SIZE_T; -pub extern "kernel32" stdcallcc fn HeapValidate(hHeap: HANDLE, dwFlags: DWORD, lpMem: *const c_void) BOOL; +pub extern "kernel32" stdcallcc fn HeapReAlloc(hHeap: HANDLE, dwFlags: DWORD, lpMem: [*]c_void, dwBytes: SIZE_T) ?[*]c_void; +pub extern "kernel32" stdcallcc fn HeapSize(hHeap: HANDLE, dwFlags: DWORD, lpMem: [*]const c_void) SIZE_T; +pub extern "kernel32" stdcallcc fn HeapValidate(hHeap: HANDLE, dwFlags: DWORD, lpMem: [*]const c_void) BOOL; pub extern "kernel32" stdcallcc fn HeapCompact(hHeap: HANDLE, dwFlags: DWORD) SIZE_T; pub extern "kernel32" stdcallcc fn HeapSummary(hHeap: HANDLE, dwFlags: DWORD, lpSummary: LPHEAP_SUMMARY) BOOL; pub extern "kernel32" stdcallcc fn GetStdHandle(in_nStdHandle: DWORD) ?HANDLE; -pub extern "kernel32" stdcallcc fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) ?*c_void; +pub extern "kernel32" stdcallcc fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) ?[*]c_void; -pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: *c_void) BOOL; +pub extern "kernel32" stdcallcc fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: [*]c_void) BOOL; pub extern "kernel32" stdcallcc fn MoveFileExA( lpExistingFileName: LPCSTR, @@ -127,7 +127,7 @@ pub extern "kernel32" stdcallcc fn PathFileExists(pszPath: ?LPCTSTR) BOOL; pub extern "kernel32" stdcallcc fn ReadFile( in_hFile: HANDLE, - out_lpBuffer: *c_void, + out_lpBuffer: [*]c_void, in_nNumberOfBytesToRead: DWORD, out_lpNumberOfBytesRead: *DWORD, in_out_lpOverlapped: ?*OVERLAPPED, @@ -150,7 +150,7 @@ pub extern "kernel32" stdcallcc fn WaitForSingleObject(hHandle: HANDLE, dwMillis pub extern "kernel32" stdcallcc fn WriteFile( in_hFile: HANDLE, - in_lpBuffer: *const c_void, + in_lpBuffer: [*]const c_void, in_nNumberOfBytesToWrite: DWORD, out_lpNumberOfBytesWritten: ?*DWORD, in_out_lpOverlapped: ?*OVERLAPPED, @@ -178,16 +178,16 @@ pub const HMODULE = *@OpaqueType(); pub const INT = c_int; pub const LPBYTE = *BYTE; pub const LPCH = *CHAR; -pub const LPCSTR = *const CHAR; -pub const LPCTSTR = *const TCHAR; +pub const LPCSTR = [*]const CHAR; +pub const LPCTSTR = [*]const TCHAR; pub const LPCVOID = *const c_void; pub const LPDWORD = *DWORD; -pub const LPSTR = *CHAR; +pub const LPSTR = [*]CHAR; pub const LPTSTR = if (UNICODE) LPWSTR else LPSTR; pub const LPVOID = *c_void; -pub const LPWSTR = *WCHAR; +pub const LPWSTR = [*]WCHAR; pub const PVOID = *c_void; -pub const PWSTR = *WCHAR; +pub const PWSTR = [*]WCHAR; pub const SIZE_T = usize; pub const TCHAR = if (UNICODE) WCHAR else u8; pub const UINT = c_uint; diff --git a/std/os/windows/util.zig b/std/os/windows/util.zig index 7170346108..5a40567310 100644 --- a/std/os/windows/util.zig +++ b/std/os/windows/util.zig @@ -42,7 +42,7 @@ pub const WriteError = error{ }; pub fn windowsWrite(handle: windows.HANDLE, bytes: []const u8) WriteError!void { - if (windows.WriteFile(handle, @ptrCast(*const c_void, bytes.ptr), u32(bytes.len), null, null) == 0) { + if (windows.WriteFile(handle, @ptrCast([*]const c_void, bytes.ptr), u32(bytes.len), null, null) == 0) { const err = windows.GetLastError(); return switch (err) { windows.ERROR.INVALID_USER_BUFFER => WriteError.SystemResources, diff --git a/std/segmented_list.zig b/std/segmented_list.zig index be9a2071a0..a2f3607ad8 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -87,7 +87,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type const ShelfIndex = std.math.Log2Int(usize); prealloc_segment: [prealloc_item_count]T, - dynamic_segments: []*T, + dynamic_segments: [][*]T, allocator: *Allocator, len: usize, @@ -99,7 +99,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type .allocator = allocator, .len = 0, .prealloc_segment = undefined, - .dynamic_segments = []*T{}, + .dynamic_segments = [][*]T{}, }; } @@ -160,11 +160,11 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type const new_cap_shelf_count = shelfCount(new_capacity); const old_shelf_count = ShelfIndex(self.dynamic_segments.len); if (new_cap_shelf_count > old_shelf_count) { - self.dynamic_segments = try self.allocator.realloc(*T, self.dynamic_segments, new_cap_shelf_count); + self.dynamic_segments = try self.allocator.realloc([*]T, self.dynamic_segments, new_cap_shelf_count); var i = old_shelf_count; errdefer { self.freeShelves(i, old_shelf_count); - self.dynamic_segments = self.allocator.shrink(*T, self.dynamic_segments, old_shelf_count); + self.dynamic_segments = self.allocator.shrink([*]T, self.dynamic_segments, old_shelf_count); } while (i < new_cap_shelf_count) : (i += 1) { self.dynamic_segments[i] = (try self.allocator.alloc(T, shelfSize(i))).ptr; @@ -178,7 +178,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type const len = ShelfIndex(self.dynamic_segments.len); self.freeShelves(len, 0); self.allocator.free(self.dynamic_segments); - self.dynamic_segments = []*T{}; + self.dynamic_segments = [][*]T{}; return; } @@ -190,7 +190,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } self.freeShelves(old_shelf_count, new_cap_shelf_count); - self.dynamic_segments = self.allocator.shrink(*T, self.dynamic_segments, new_cap_shelf_count); + self.dynamic_segments = self.allocator.shrink([*]T, self.dynamic_segments, new_cap_shelf_count); } pub fn uncheckedAt(self: *Self, index: usize) *T { diff --git a/std/special/bootstrap.zig b/std/special/bootstrap.zig index 5ed7874ca5..64eae79ce4 100644 --- a/std/special/bootstrap.zig +++ b/std/special/bootstrap.zig @@ -5,7 +5,7 @@ const root = @import("@root"); const std = @import("std"); const builtin = @import("builtin"); -var argc_ptr: *usize = undefined; +var argc_ptr: [*]usize = undefined; comptime { const strong_linkage = builtin.GlobalLinkage.Strong; @@ -28,12 +28,12 @@ nakedcc fn _start() noreturn { switch (builtin.arch) { builtin.Arch.x86_64 => { argc_ptr = asm ("lea (%%rsp), %[argc]" - : [argc] "=r" (-> *usize) + : [argc] "=r" (-> [*]usize) ); }, builtin.Arch.i386 => { argc_ptr = asm ("lea (%%esp), %[argc]" - : [argc] "=r" (-> *usize) + : [argc] "=r" (-> [*]usize) ); }, else => @compileError("unsupported arch"), @@ -49,15 +49,17 @@ extern fn WinMainCRTStartup() noreturn { std.os.windows.ExitProcess(callMain()); } +// TODO https://github.com/ziglang/zig/issues/265 fn posixCallMainAndExit() noreturn { const argc = argc_ptr.*; - const argv = @ptrCast(**u8, &argc_ptr[1]); - const envp_nullable = @ptrCast(*?*u8, &argv[argc + 1]); + const argv = @ptrCast([*][*]u8, argc_ptr + 1); + + const envp_nullable = @ptrCast([*]?[*]u8, argv + argc + 1); var envp_count: usize = 0; while (envp_nullable[envp_count]) |_| : (envp_count += 1) {} - const envp = @ptrCast(**u8, envp_nullable)[0..envp_count]; + const envp = @ptrCast([*][*]u8, envp_nullable)[0..envp_count]; if (builtin.os == builtin.Os.linux) { - const auxv = &@ptrCast(*usize, envp.ptr)[envp_count + 1]; + const auxv = @ptrCast([*]usize, envp.ptr + envp_count + 1); var i: usize = 0; while (auxv[i] != 0) : (i += 2) { if (auxv[i] < std.os.linux_aux_raw.len) std.os.linux_aux_raw[auxv[i]] = auxv[i + 1]; @@ -68,16 +70,16 @@ fn posixCallMainAndExit() noreturn { std.os.posix.exit(callMainWithArgs(argc, argv, envp)); } -fn callMainWithArgs(argc: usize, argv: **u8, envp: []*u8) u8 { +fn callMainWithArgs(argc: usize, argv: [*][*]u8, envp: [][*]u8) u8 { std.os.ArgIteratorPosix.raw = argv[0..argc]; std.os.posix_environ_raw = envp; return callMain(); } -extern fn main(c_argc: i32, c_argv: **u8, c_envp: *?*u8) i32 { +extern fn main(c_argc: i32, c_argv: [*][*]u8, c_envp: [*]?[*]u8) i32 { var env_count: usize = 0; while (c_envp[env_count] != null) : (env_count += 1) {} - const envp = @ptrCast(**u8, c_envp)[0..env_count]; + const envp = @ptrCast([*][*]u8, c_envp)[0..env_count]; return callMainWithArgs(usize(c_argc), c_argv, envp); } diff --git a/std/special/builtin.zig b/std/special/builtin.zig index 9c9cd35103..e537078924 100644 --- a/std/special/builtin.zig +++ b/std/special/builtin.zig @@ -14,7 +14,7 @@ pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn } } -export fn memset(dest: ?*u8, c: u8, n: usize) ?*u8 { +export fn memset(dest: ?[*]u8, c: u8, n: usize) ?[*]u8 { @setRuntimeSafety(false); var index: usize = 0; @@ -24,7 +24,7 @@ export fn memset(dest: ?*u8, c: u8, n: usize) ?*u8 { return dest; } -export fn memcpy(noalias dest: ?*u8, noalias src: ?*const u8, n: usize) ?*u8 { +export fn memcpy(noalias dest: ?[*]u8, noalias src: ?[*]const u8, n: usize) ?[*]u8 { @setRuntimeSafety(false); var index: usize = 0; @@ -34,7 +34,7 @@ export fn memcpy(noalias dest: ?*u8, noalias src: ?*const u8, n: usize) ?*u8 { return dest; } -export fn memmove(dest: ?*u8, src: ?*const u8, n: usize) ?*u8 { +export fn memmove(dest: ?[*]u8, src: ?[*]const u8, n: usize) ?[*]u8 { @setRuntimeSafety(false); if (@ptrToInt(dest) < @ptrToInt(src)) { diff --git a/test/cases/align.zig b/test/cases/align.zig index 99bdcdf940..b80727258e 100644 --- a/test/cases/align.zig +++ b/test/cases/align.zig @@ -167,54 +167,41 @@ test "@ptrCast preserves alignment of bigger source" { assert(@typeOf(ptr) == *align(16) u8); } -test "compile-time known array index has best alignment possible" { +test "runtime known array index has best alignment possible" { // take full advantage of over-alignment - var array align(4) = []u8{ - 1, - 2, - 3, - 4, - }; + var array align(4) = []u8{ 1, 2, 3, 4 }; assert(@typeOf(&array[0]) == *align(4) u8); assert(@typeOf(&array[1]) == *u8); assert(@typeOf(&array[2]) == *align(2) u8); assert(@typeOf(&array[3]) == *u8); // because align is too small but we still figure out to use 2 - var bigger align(2) = []u64{ - 1, - 2, - 3, - 4, - }; + var bigger align(2) = []u64{ 1, 2, 3, 4 }; assert(@typeOf(&bigger[0]) == *align(2) u64); assert(@typeOf(&bigger[1]) == *align(2) u64); assert(@typeOf(&bigger[2]) == *align(2) u64); assert(@typeOf(&bigger[3]) == *align(2) u64); // because pointer is align 2 and u32 align % 2 == 0 we can assume align 2 - var smaller align(2) = []u32{ - 1, - 2, - 3, - 4, - }; - testIndex(&smaller[0], 0, *align(2) u32); - testIndex(&smaller[0], 1, *align(2) u32); - testIndex(&smaller[0], 2, *align(2) u32); - testIndex(&smaller[0], 3, *align(2) u32); + var smaller align(2) = []u32{ 1, 2, 3, 4 }; + comptime assert(@typeOf(smaller[0..]) == []align(2) u32); + comptime assert(@typeOf(smaller[0..].ptr) == [*]align(2) u32); + testIndex(smaller[0..].ptr, 0, *align(2) u32); + testIndex(smaller[0..].ptr, 1, *align(2) u32); + testIndex(smaller[0..].ptr, 2, *align(2) u32); + testIndex(smaller[0..].ptr, 3, *align(2) u32); // has to use ABI alignment because index known at runtime only - testIndex2(&array[0], 0, *u8); - testIndex2(&array[0], 1, *u8); - testIndex2(&array[0], 2, *u8); - testIndex2(&array[0], 3, *u8); + testIndex2(array[0..].ptr, 0, *u8); + testIndex2(array[0..].ptr, 1, *u8); + testIndex2(array[0..].ptr, 2, *u8); + testIndex2(array[0..].ptr, 3, *u8); } -fn testIndex(smaller: *align(2) u32, index: usize, comptime T: type) void { - assert(@typeOf(&smaller[index]) == T); +fn testIndex(smaller: [*]align(2) u32, index: usize, comptime T: type) void { + comptime assert(@typeOf(&smaller[index]) == T); } -fn testIndex2(ptr: *align(4) u8, index: usize, comptime T: type) void { - assert(@typeOf(&ptr[index]) == T); +fn testIndex2(ptr: [*]align(4) u8, index: usize, comptime T: type) void { + comptime assert(@typeOf(&ptr[index]) == T); } test "alignstack" { diff --git a/test/cases/const_slice_child.zig b/test/cases/const_slice_child.zig index e012c729a0..07d02d5df0 100644 --- a/test/cases/const_slice_child.zig +++ b/test/cases/const_slice_child.zig @@ -1,15 +1,16 @@ const debug = @import("std").debug; const assert = debug.assert; -var argv: *const *const u8 = undefined; +var argv: [*]const [*]const u8 = undefined; test "const slice child" { - const strs = ([]*const u8){ + const strs = ([][*]const u8){ c"one", c"two", c"three", }; - argv = &strs[0]; + // TODO this should implicitly cast + argv = @ptrCast([*]const [*]const u8, &strs); bar(strs.len); } @@ -29,7 +30,7 @@ fn bar(argc: usize) void { foo(args); } -fn strlen(ptr: *const u8) usize { +fn strlen(ptr: [*]const u8) usize { var count: usize = 0; while (ptr[count] != 0) : (count += 1) {} return count; diff --git a/test/cases/for.zig b/test/cases/for.zig index c624035708..bdbab312f6 100644 --- a/test/cases/for.zig +++ b/test/cases/for.zig @@ -35,34 +35,12 @@ fn mangleString(s: []u8) void { } test "basic for loop" { - const expected_result = []u8{ - 9, - 8, - 7, - 6, - 0, - 1, - 2, - 3, - 9, - 8, - 7, - 6, - 0, - 1, - 2, - 3, - }; + const expected_result = []u8{ 9, 8, 7, 6, 0, 1, 2, 3, 9, 8, 7, 6, 0, 1, 2, 3 }; var buffer: [expected_result.len]u8 = undefined; var buf_index: usize = 0; - const array = []u8{ - 9, - 8, - 7, - 6, - }; + const array = []u8{ 9, 8, 7, 6 }; for (array) |item| { buffer[buf_index] = item; buf_index += 1; diff --git a/test/cases/misc.zig b/test/cases/misc.zig index 919b978f9f..5899f20f9c 100644 --- a/test/cases/misc.zig +++ b/test/cases/misc.zig @@ -171,8 +171,8 @@ test "memcpy and memset intrinsics" { var foo: [20]u8 = undefined; var bar: [20]u8 = undefined; - @memset(&foo[0], 'A', foo.len); - @memcpy(&bar[0], &foo[0], bar.len); + @memset(foo[0..].ptr, 'A', foo.len); + @memcpy(bar[0..].ptr, foo[0..].ptr, bar.len); if (bar[11] != 'A') unreachable; } @@ -194,7 +194,7 @@ test "slicing" { if (slice.len != 5) unreachable; const ptr = &slice[0]; - if (ptr[0] != 1234) unreachable; + if (ptr.* != 1234) unreachable; var slice_rest = array[10..]; if (slice_rest.len != 10) unreachable; @@ -464,8 +464,9 @@ test "array 2D const double ptr" { } fn testArray2DConstDoublePtr(ptr: *const f32) void { - assert(ptr[0] == 1.0); - assert(ptr[1] == 2.0); + const ptr2 = @ptrCast([*]const f32, ptr); + assert(ptr2[0] == 1.0); + assert(ptr2[1] == 2.0); } const Tid = builtin.TypeId; diff --git a/test/cases/pointers.zig b/test/cases/pointers.zig index 87b3d25a74..47afb60a2e 100644 --- a/test/cases/pointers.zig +++ b/test/cases/pointers.zig @@ -12,3 +12,33 @@ fn testDerefPtr() void { y.* += 1; assert(x == 1235); } + +test "pointer arithmetic" { + var ptr = c"abcd"; + + assert(ptr[0] == 'a'); + ptr += 1; + assert(ptr[0] == 'b'); + ptr += 1; + assert(ptr[0] == 'c'); + ptr += 1; + assert(ptr[0] == 'd'); + ptr += 1; + assert(ptr[0] == 0); + ptr -= 1; + assert(ptr[0] == 'd'); + ptr -= 1; + assert(ptr[0] == 'c'); + ptr -= 1; + assert(ptr[0] == 'b'); + ptr -= 1; + assert(ptr[0] == 'a'); +} + +test "double pointer parsing" { + comptime assert(PtrOf(PtrOf(i32)) == **i32); +} + +fn PtrOf(comptime T: type) type { + return *T; +} diff --git a/test/cases/struct.zig b/test/cases/struct.zig index 0712e508de..6f7d44e09b 100644 --- a/test/cases/struct.zig +++ b/test/cases/struct.zig @@ -43,7 +43,7 @@ const VoidStructFieldsFoo = struct { test "structs" { var foo: StructFoo = undefined; - @memset(@ptrCast(*u8, &foo), 0, @sizeOf(StructFoo)); + @memset(@ptrCast([*]u8, &foo), 0, @sizeOf(StructFoo)); foo.a += 1; foo.b = foo.a == 1; testFoo(foo); @@ -396,8 +396,8 @@ const Bitfields = packed struct { test "native bit field understands endianness" { var all: u64 = 0x7765443322221111; var bytes: [8]u8 = undefined; - @memcpy(&bytes[0], @ptrCast(*u8, &all), 8); - var bitfields = @ptrCast(*Bitfields, &bytes[0]).*; + @memcpy(bytes[0..].ptr, @ptrCast([*]u8, &all), 8); + var bitfields = @ptrCast(*Bitfields, bytes[0..].ptr).*; assert(bitfields.f1 == 0x1111); assert(bitfields.f2 == 0x2222); diff --git a/test/compare_output.zig b/test/compare_output.zig index 00ad4a709b..8d5dc68d45 100644 --- a/test/compare_output.zig +++ b/test/compare_output.zig @@ -6,7 +6,7 @@ const tests = @import("tests.zig"); pub fn addCases(cases: *tests.CompareOutputContext) void { cases.addC("hello world with libc", \\const c = @cImport(@cInclude("stdio.h")); - \\export fn main(argc: c_int, argv: **u8) c_int { + \\export fn main(argc: c_int, argv: [*][*]u8) c_int { \\ _ = c.puts(c"Hello, world!"); \\ return 0; \\} @@ -139,7 +139,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\ @cInclude("stdio.h"); \\}); \\ - \\export fn main(argc: c_int, argv: **u8) c_int { + \\export fn main(argc: c_int, argv: [*][*]u8) c_int { \\ if (is_windows) { \\ // we want actual \n, not \r\n \\ _ = c._setmode(1, c._O_BINARY); @@ -284,9 +284,9 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { cases.addC("expose function pointer to C land", \\const c = @cImport(@cInclude("stdlib.h")); \\ - \\export fn compare_fn(a: ?*const c_void, b: ?*const c_void) c_int { - \\ const a_int = @ptrCast(*align(1) const i32, a ?? unreachable); - \\ const b_int = @ptrCast(*align(1) const i32, b ?? unreachable); + \\export fn compare_fn(a: ?[*]const c_void, b: ?[*]const c_void) c_int { + \\ const a_int = @ptrCast(*const i32, @alignCast(@alignOf(i32), a)); + \\ const b_int = @ptrCast(*const i32, @alignCast(@alignOf(i32), b)); \\ if (a_int.* < b_int.*) { \\ return -1; \\ } else if (a_int.* > b_int.*) { @@ -297,9 +297,9 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\} \\ \\export fn main() c_int { - \\ var array = []u32 { 1, 7, 3, 2, 0, 9, 4, 8, 6, 5 }; + \\ var array = []u32{ 1, 7, 3, 2, 0, 9, 4, 8, 6, 5 }; \\ - \\ c.qsort(@ptrCast(*c_void, &array[0]), c_ulong(array.len), @sizeOf(i32), compare_fn); + \\ c.qsort(@ptrCast(?[*]c_void, array[0..].ptr), c_ulong(array.len), @sizeOf(i32), compare_fn); \\ \\ for (array) |item, i| { \\ if (item != i) { @@ -324,7 +324,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void { \\ @cInclude("stdio.h"); \\}); \\ - \\export fn main(argc: c_int, argv: **u8) c_int { + \\export fn main(argc: c_int, argv: [*][*]u8) c_int { \\ if (is_windows) { \\ // we want actual \n, not \r\n \\ _ = c._setmode(1, c._O_BINARY); diff --git a/test/compile_errors.zig b/test/compile_errors.zig index ea1357f5bb..7e9ef82e42 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -1,6 +1,15 @@ const tests = @import("tests.zig"); pub fn addCases(cases: *tests.CompileErrorContext) void { + cases.add( + "indexing single-item pointer", + \\export fn entry(ptr: *i32) i32 { + \\ return ptr[1]; + \\} + , + ".tmp_source.zig:2:15: error: indexing not allowed on pointer to single item", + ); + cases.add( "invalid deref on switch target", \\const NextError = error{NextError}; @@ -1002,7 +1011,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { \\ return a; \\} , - ".tmp_source.zig:3:12: error: expected type 'i32', found '*const u8'", + ".tmp_source.zig:3:12: error: expected type 'i32', found '[*]const u8'", ); cases.add( @@ -2442,13 +2451,13 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { \\var s_buffer: [10]u8 = undefined; \\pub fn pass(in: []u8) []u8 { \\ var out = &s_buffer; - \\ out[0].* = in[0]; + \\ out.*.* = in[0]; \\ return out.*[0..1]; \\} \\ \\export fn entry() usize { return @sizeOf(@typeOf(pass)); } , - ".tmp_source.zig:4:11: error: attempt to dereference non pointer type '[10]u8'", + ".tmp_source.zig:4:10: error: attempt to dereference non pointer type '[10]u8'", ); cases.add( diff --git a/test/translate_c.zig b/test/translate_c.zig index 9a07bc343d..ac0a98e6cc 100644 --- a/test/translate_c.zig +++ b/test/translate_c.zig @@ -14,11 +14,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\}; , \\pub const struct_Foo = extern struct { - \\ a: ?*Foo, + \\ a: ?[*]Foo, \\}; \\pub const Foo = struct_Foo; \\pub const struct_Bar = extern struct { - \\ a: ?*Foo, + \\ a: ?[*]Foo, \\}; ); @@ -99,7 +99,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { cases.add("restrict -> noalias", \\void foo(void *restrict bar, void *restrict); , - \\pub extern fn foo(noalias bar: ?*c_void, noalias arg1: ?*c_void) void; + \\pub extern fn foo(noalias bar: ?[*]c_void, noalias arg1: ?[*]c_void) void; ); cases.add("simple struct", @@ -110,7 +110,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , \\const struct_Foo = extern struct { \\ x: c_int, - \\ y: ?*u8, + \\ y: ?[*]u8, \\}; , \\pub const Foo = struct_Foo; @@ -141,7 +141,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , \\pub const BarB = enum_Bar.B; , - \\pub extern fn func(a: ?*struct_Foo, b: ?*(?*enum_Bar)) void; + \\pub extern fn func(a: ?[*]struct_Foo, b: ?[*](?[*]enum_Bar)) void; , \\pub const Foo = struct_Foo; , @@ -151,7 +151,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { cases.add("constant size array", \\void func(int array[20]); , - \\pub extern fn func(array: ?*c_int) void; + \\pub extern fn func(array: ?[*]c_int) void; ); cases.add("self referential struct with function pointer", @@ -160,7 +160,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\}; , \\pub const struct_Foo = extern struct { - \\ derp: ?extern fn(?*struct_Foo) void, + \\ derp: ?extern fn(?[*]struct_Foo) void, \\}; , \\pub const Foo = struct_Foo; @@ -172,7 +172,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , \\pub const struct_Foo = @OpaqueType(); , - \\pub extern fn some_func(foo: ?*struct_Foo, x: c_int) ?*struct_Foo; + \\pub extern fn some_func(foo: ?[*]struct_Foo, x: c_int) ?[*]struct_Foo; , \\pub const Foo = struct_Foo; ); @@ -219,11 +219,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\}; , \\pub const struct_Bar = extern struct { - \\ next: ?*struct_Foo, + \\ next: ?[*]struct_Foo, \\}; , \\pub const struct_Foo = extern struct { - \\ next: ?*struct_Bar, + \\ next: ?[*]struct_Bar, \\}; ); @@ -233,7 +233,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , \\pub const Foo = c_void; , - \\pub extern fn fun(a: ?*Foo) Foo; + \\pub extern fn fun(a: ?[*]Foo) Foo; ); cases.add("generate inline func for #define global extern fn", @@ -505,7 +505,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ return 6; \\} , - \\pub export fn and_or_none_bool(a: c_int, b: f32, c: ?*c_void) c_int { + \\pub export fn and_or_none_bool(a: c_int, b: f32, c: ?[*]c_void) c_int { \\ if ((a != 0) and (b != 0)) return 0; \\ if ((b != 0) and (c != null)) return 1; \\ if ((a != 0) and (c != null)) return 2; @@ -607,7 +607,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub const struct_Foo = extern struct { \\ field: c_int, \\}; - \\pub export fn read_field(foo: ?*struct_Foo) c_int { + \\pub export fn read_field(foo: ?[*]struct_Foo) c_int { \\ return (??foo).field; \\} ); @@ -653,8 +653,8 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ return x; \\} , - \\pub export fn foo(x: ?*c_ushort) ?*c_void { - \\ return @ptrCast(?*c_void, x); + \\pub export fn foo(x: ?[*]c_ushort) ?[*]c_void { + \\ return @ptrCast(?[*]c_void, x); \\} ); @@ -674,7 +674,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ return 0; \\} , - \\pub export fn foo() ?*c_int { + \\pub export fn foo() ?[*]c_int { \\ return null; \\} ); @@ -983,7 +983,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ *x = 1; \\} , - \\pub export fn foo(x: ?*c_int) void { + \\pub export fn foo(x: ?[*]c_int) void { \\ (??x).* = 1; \\} ); @@ -1011,7 +1011,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , \\pub fn foo() c_int { \\ var x: c_int = 1234; - \\ var ptr: ?*c_int = &x; + \\ var ptr: ?[*]c_int = &x; \\ return (??ptr).*; \\} ); @@ -1021,7 +1021,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ return "bar"; \\} , - \\pub fn foo() ?*const u8 { + \\pub fn foo() ?[*]const u8 { \\ return c"bar"; \\} ); @@ -1150,8 +1150,8 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ return (float *)a; \\} , - \\fn ptrcast(a: ?*c_int) ?*f32 { - \\ return @ptrCast(?*f32, a); + \\fn ptrcast(a: ?[*]c_int) ?[*]f32 { + \\ return @ptrCast(?[*]f32, a); \\} ); @@ -1173,7 +1173,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ return !c; \\} , - \\pub fn foo(a: c_int, b: f32, c: ?*c_void) c_int { + \\pub fn foo(a: c_int, b: f32, c: ?[*]c_void) c_int { \\ return !(a == 0); \\ return !(a != 0); \\ return !(b != 0); @@ -1194,7 +1194,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { cases.add("const ptr initializer", \\static const char *v0 = "0.0.0"; , - \\pub var v0: ?*const u8 = c"0.0.0"; + \\pub var v0: ?[*]const u8 = c"0.0.0"; ); cases.add("static incomplete array inside function", @@ -1203,14 +1203,14 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\} , \\pub fn foo() void { - \\ const v2: *const u8 = c"2.2.2"; + \\ const v2: [*]const u8 = c"2.2.2"; \\} ); cases.add("macro pointer cast", \\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE) , - \\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); + \\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); ); cases.add("if on none bool", @@ -1231,7 +1231,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ B, \\ C, \\}; - \\pub fn if_none_bool(a: c_int, b: f32, c: ?*c_void, d: enum_SomeEnum) c_int { + \\pub fn if_none_bool(a: c_int, b: f32, c: ?[*]c_void, d: enum_SomeEnum) c_int { \\ if (a != 0) return 0; \\ if (b != 0) return 1; \\ if (c != null) return 2; @@ -1248,7 +1248,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ return 3; \\} , - \\pub fn while_none_bool(a: c_int, b: f32, c: ?*c_void) c_int { + \\pub fn while_none_bool(a: c_int, b: f32, c: ?[*]c_void) c_int { \\ while (a != 0) return 0; \\ while (b != 0) return 1; \\ while (c != null) return 2; @@ -1264,7 +1264,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ return 3; \\} , - \\pub fn for_none_bool(a: c_int, b: f32, c: ?*c_void) c_int { + \\pub fn for_none_bool(a: c_int, b: f32, c: ?[*]c_void) c_int { \\ while (a != 0) return 0; \\ while (b != 0) return 1; \\ while (c != null) return 2; -- cgit v1.2.3 From ec1b6f66737f8c3cbc0420715c2c502c7e710081 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 9 Jun 2018 23:42:14 -0400 Subject: breaking syntax change: ??x to x.? (#1095) See #1023 This also renames Nullable/Maybe to Optional --- build.zig | 2 +- doc/codegen.md | 8 +- doc/langref.html.in | 122 ++++++++++++++-------------- example/cat/main.zig | 2 +- src-self-hosted/arg.zig | 10 +-- src-self-hosted/llvm.zig | 2 +- src-self-hosted/main.zig | 8 +- src/all_types.hpp | 44 +++++------ src/analyze.cpp | 70 ++++++++-------- src/ast_render.cpp | 6 +- src/codegen.cpp | 60 +++++++------- src/ir.cpp | 198 +++++++++++++++++++++++----------------------- src/ir_print.cpp | 16 ++-- src/parser.cpp | 21 +++-- src/tokenizer.cpp | 10 +-- src/tokenizer.hpp | 3 +- src/translate_c.cpp | 14 ++-- std/array_list.zig | 2 +- std/buf_map.zig | 6 +- std/event.zig | 4 +- std/fmt/index.zig | 6 +- std/hash_map.zig | 8 +- std/heap.zig | 4 +- std/json.zig | 12 +-- std/linked_list.zig | 8 +- std/macho.zig | 2 +- std/mem.zig | 22 +++--- std/os/child_process.zig | 18 ++--- std/os/index.zig | 4 +- std/os/linux/vdso.zig | 2 +- std/os/path.zig | 8 +- std/segmented_list.zig | 8 +- std/special/bootstrap.zig | 6 +- std/special/builtin.zig | 8 +- std/unicode.zig | 24 +++--- std/zig/ast.zig | 12 +-- std/zig/parse.zig | 35 +++++--- std/zig/parser_test.zig | 5 +- std/zig/render.zig | 25 +++--- test/cases/bugs/656.zig | 2 +- test/cases/cast.zig | 50 ++++++------ test/cases/error.zig | 2 +- test/cases/eval.zig | 2 +- test/cases/generics.zig | 2 +- test/cases/misc.zig | 2 +- test/cases/null.zig | 30 +++---- test/cases/reflection.zig | 2 +- test/cases/type_info.zig | 14 ++-- test/cases/while.zig | 12 +-- test/compile_errors.zig | 16 ++-- test/tests.zig | 12 +-- 51 files changed, 489 insertions(+), 482 deletions(-) (limited to 'std/os/linux') diff --git a/build.zig b/build.zig index 08a47570ef..eada37816c 100644 --- a/build.zig +++ b/build.zig @@ -75,7 +75,7 @@ pub fn build(b: *Builder) !void { cxx_compiler, "-print-file-name=libstdc++.a", }); - const libstdcxx_path = ??mem.split(libstdcxx_path_padded, "\r\n").next(); + const libstdcxx_path = mem.split(libstdcxx_path_padded, "\r\n").next().?; if (mem.eql(u8, libstdcxx_path, "libstdc++.a")) { warn( \\Unable to determine path to libstdc++.a diff --git a/doc/codegen.md b/doc/codegen.md index 02406fae82..65f12f4875 100644 --- a/doc/codegen.md +++ b/doc/codegen.md @@ -6,7 +6,7 @@ Every type has a "handle". If a type is a simple primitive type such as i32 or f64, the handle is "by value", meaning that we pass around the value itself when we refer to a value of that type. -If a type is a container, error union, maybe type, slice, or array, then its +If a type is a container, error union, optional type, slice, or array, then its handle is a pointer, and everywhere we refer to a value of this type we refer to a pointer. @@ -19,7 +19,7 @@ Error union types are represented as: payload: T, } -Maybe types are represented as: +Optional types are represented as: struct { payload: T, @@ -28,6 +28,6 @@ Maybe types are represented as: ## Data Optimizations -Maybe pointer types are special: the 0x0 pointer value is used to represent a -null pointer. Thus, instead of the struct above, maybe pointer types are +Optional pointer types are special: the 0x0 pointer value is used to represent a +null pointer. Thus, instead of the struct above, optional pointer types are represented as a `usize` in codegen and the handle is by value. diff --git a/doc/langref.html.in b/doc/langref.html.in index 6a1f1c3102..4c4a637095 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -156,18 +156,18 @@ pub fn main() void { true or false, !true); - // nullable - var nullable_value: ?[]const u8 = null; - assert(nullable_value == null); + // optional + var optional_value: ?[]const u8 = null; + assert(optional_value == null); - warn("\nnullable 1\ntype: {}\nvalue: {}\n", - @typeName(@typeOf(nullable_value)), nullable_value); + warn("\noptional 1\ntype: {}\nvalue: {}\n", + @typeName(@typeOf(optional_value)), optional_value); - nullable_value = "hi"; - assert(nullable_value != null); + optional_value = "hi"; + assert(optional_value != null); - warn("\nnullable 2\ntype: {}\nvalue: {}\n", - @typeName(@typeOf(nullable_value)), nullable_value); + warn("\noptional 2\ntype: {}\nvalue: {}\n", + @typeName(@typeOf(optional_value)), optional_value); // error union var number_or_error: error!i32 = error.ArgNotFound; @@ -428,7 +428,7 @@ pub fn main() void { null - used to set a nullable type to null + used to set an optional type to null undefined @@ -440,7 +440,7 @@ pub fn main() void { - {#see_also|Nullables|this#} + {#see_also|Optionals|this#} {#header_close#} {#header_open|String Literals#} {#code_begin|test#} @@ -988,7 +988,7 @@ a ^= b
a ?? b
    -
  • {#link|Nullables#}
  • +
  • {#link|Optionals#}
If a is null, @@ -1003,10 +1003,10 @@ unwrapped == 1234 -
??a
+
a.?
    -
  • {#link|Nullables#}
  • +
  • {#link|Optionals#}
@@ -1015,7 +1015,7 @@ unwrapped == 1234
const value: ?u32 = 5678;
-??value == 5678
+value.? == 5678 @@ -1103,7 +1103,7 @@ unwrapped == 1234
a == null
    -
  • {#link|Nullables#}
  • +
  • {#link|Optionals#}
@@ -1267,8 +1267,8 @@ x.* == 1234
{#header_open|Precedence#}
x() x[] x.y
 a!b
-!x -x -%x ~x &x ?x ??x
-x{} x.*
+!x -x -%x ~x &x ?x
+x{} x.* x.?
 ! * / % ** *%
 + - ++ +% -%
 << >>
@@ -1483,17 +1483,17 @@ test "volatile" {
     assert(@typeOf(mmio_ptr) == *volatile u8);
 }
 
-test "nullable pointers" {
-    // Pointers cannot be null. If you want a null pointer, use the nullable
-    // prefix `?` to make the pointer type nullable.
+test "optional pointers" {
+    // Pointers cannot be null. If you want a null pointer, use the optional
+    // prefix `?` to make the pointer type optional.
     var ptr: ?*i32 = null;
 
     var x: i32 = 1;
     ptr = &x;
 
-    assert((??ptr).* == 1);
+    assert(ptr.?.* == 1);
 
-    // Nullable pointers are the same size as normal pointers, because pointer
+    // Optional pointers are the same size as normal pointers, because pointer
     // value 0 is used as the null value.
     assert(@sizeOf(?*i32) == @sizeOf(*i32));
 }
@@ -1832,7 +1832,7 @@ test "linked list" {
         .last = &node,
         .len = 1,
     };
-    assert((??list2.first).data == 1234);
+    assert(list2.first.?.data == 1234);
 }
       {#code_end#}
       {#see_also|comptime|@fieldParentPtr#}
@@ -2270,7 +2270,7 @@ fn rangeHasNumber(begin: usize, end: usize, number: usize) bool {
 }
 
 test "while null capture" {
-    // Just like if expressions, while loops can take a nullable as the
+    // Just like if expressions, while loops can take an optional as the
     // condition and capture the payload. When null is encountered the loop
     // exits.
     var sum1: u32 = 0;
@@ -2280,7 +2280,7 @@ test "while null capture" {
     }
     assert(sum1 == 3);
 
-    // The else branch is allowed on nullable iteration. In this case, it will
+    // The else branch is allowed on optional iteration. In this case, it will
     // be executed on the first null value encountered.
     var sum2: u32 = 0;
     numbers_left = 3;
@@ -2340,7 +2340,7 @@ fn typeNameLength(comptime T: type) usize {
     return @typeName(T).len;
 }
       {#code_end#}
-      {#see_also|if|Nullables|Errors|comptime|unreachable#}
+      {#see_also|if|Optionals|Errors|comptime|unreachable#}
       {#header_close#}
       {#header_open|for#}
       {#code_begin|test|for#}
@@ -2400,7 +2400,7 @@ test "for else" {
         if (value == null) {
             break 9;
         } else {
-            sum += ??value;
+            sum += value.?;
         }
     } else blk: {
         assert(sum == 7);
@@ -2461,7 +2461,7 @@ test "if boolean" {
     assert(result == 47);
 }
 
-test "if nullable" {
+test "if optional" {
     // If expressions test for null.
 
     const a: ?u32 = 0;
@@ -2544,7 +2544,7 @@ test "if error union" {
     }
 }
       {#code_end#}
-      {#see_also|Nullables|Errors#}
+      {#see_also|Optionals|Errors#}
       {#header_close#}
       {#header_open|defer#}
       {#code_begin|test|defer#}
@@ -3167,24 +3167,24 @@ test "inferred error set" {
       

TODO

{#header_close#} {#header_close#} - {#header_open|Nullables#} + {#header_open|Optionals#}

One area that Zig provides safety without compromising efficiency or - readability is with the nullable type. + readability is with the optional type.

- The question mark symbolizes the nullable type. You can convert a type to a nullable + The question mark symbolizes the optional type. You can convert a type to an optional type by putting a question mark in front of it, like this:

{#code_begin|syntax#} // normal integer const normal_int: i32 = 1234; -// nullable integer -const nullable_int: ?i32 = 5678; +// optional integer +const optional_int: ?i32 = 5678; {#code_end#}

- Now the variable nullable_int could be an i32, or null. + Now the variable optional_int could be an i32, or null.

Instead of integers, let's talk about pointers. Null references are the source of many runtime @@ -3193,8 +3193,8 @@ const nullable_int: ?i32 = 5678;

Zig does not have them.

- Instead, you can use a nullable pointer. This secretly compiles down to a normal pointer, - since we know we can use 0 as the null value for the nullable type. But the compiler + Instead, you can use an optional pointer. This secretly compiles down to a normal pointer, + since we know we can use 0 as the null value for the optional type. But the compiler can check your work and make sure you don't assign null to something that can't be null.

@@ -3226,7 +3226,7 @@ fn doAThing() ?*Foo {

Here, Zig is at least as convenient, if not more, than C. And, the type of "ptr" is *u8 not ?*u8. The ?? operator - unwrapped the nullable type and therefore ptr is guaranteed to be non-null everywhere + unwrapped the optional type and therefore ptr is guaranteed to be non-null everywhere it is used in the function.

@@ -3245,10 +3245,10 @@ fn doAThing() ?*Foo { In Zig you can accomplish the same thing:

{#code_begin|syntax#} -fn doAThing(nullable_foo: ?*Foo) void { +fn doAThing(optional_foo: ?*Foo) void { // do some stuff - if (nullable_foo) |foo| { + if (optional_foo) |foo| { doSomethingWithFoo(foo); } @@ -3257,7 +3257,7 @@ fn doAThing(nullable_foo: ?*Foo) void { {#code_end#}

Once again, the notable thing here is that inside the if block, - foo is no longer a nullable pointer, it is a pointer, which + foo is no longer an optional pointer, it is a pointer, which cannot be null.

@@ -3267,20 +3267,20 @@ fn doAThing(nullable_foo: ?*Foo) void { The optimizer can sometimes make better decisions knowing that pointer arguments cannot be null.

- {#header_open|Nullable Type#} -

A nullable is created by putting ? in front of a type. You can use compile-time - reflection to access the child type of a nullable:

+ {#header_open|Optional Type#} +

An optional is created by putting ? in front of a type. You can use compile-time + reflection to access the child type of an optional:

{#code_begin|test#} const assert = @import("std").debug.assert; -test "nullable type" { - // Declare a nullable and implicitly cast from null: +test "optional type" { + // Declare an optional and implicitly cast from null: var foo: ?i32 = null; - // Implicitly cast from child type of a nullable + // Implicitly cast from child type of an optional foo = 1234; - // Use compile-time reflection to access the child type of the nullable: + // Use compile-time reflection to access the child type of the optional: comptime assert(@typeOf(foo).Child == i32); } {#code_end#} @@ -4888,7 +4888,7 @@ pub const TypeId = enum { ComptimeInt, Undefined, Null, - Nullable, + Optional, ErrorUnion, Error, Enum, @@ -4922,7 +4922,7 @@ pub const TypeInfo = union(TypeId) { ComptimeInt: void, Undefined: void, Null: void, - Nullable: Nullable, + Optional: Optional, ErrorUnion: ErrorUnion, ErrorSet: ErrorSet, Enum: Enum, @@ -4975,7 +4975,7 @@ pub const TypeInfo = union(TypeId) { defs: []Definition, }; - pub const Nullable = struct { + pub const Optional = struct { child: type, }; @@ -5366,8 +5366,8 @@ comptime {

At compile-time:

{#code_begin|test_err|unable to unwrap null#} comptime { - const nullable_number: ?i32 = null; - const number = ??nullable_number; + const optional_number: ?i32 = null; + const number = optional_number.?; } {#code_end#}

At runtime crashes with the message attempt to unwrap null and a stack trace.

@@ -5376,9 +5376,9 @@ comptime { {#code_begin|exe|test#} const warn = @import("std").debug.warn; pub fn main() void { - const nullable_number: ?i32 = null; + const optional_number: ?i32 = null; - if (nullable_number) |number| { + if (optional_number) |number| { warn("got number: {}\n", number); } else { warn("it's null\n"); @@ -5939,9 +5939,9 @@ AsmInputItem = "[" Symbol "]" String "(" Expression ")" AsmClobbers= ":" list(String, ",") -UnwrapExpression = BoolOrExpression (UnwrapNullable | UnwrapError) | BoolOrExpression +UnwrapExpression = BoolOrExpression (UnwrapOptional | UnwrapError) | BoolOrExpression -UnwrapNullable = "??" Expression +UnwrapOptional = "??" Expression UnwrapError = "catch" option("|" Symbol "|") Expression @@ -6015,12 +6015,10 @@ MultiplyOperator = "||" | "*" | "/" | "%" | "**" | "*%" PrefixOpExpression = PrefixOp TypeExpr | SuffixOpExpression -SuffixOpExpression = ("async" option("<" SuffixOpExpression ">") SuffixOpExpression FnCallExpression) | PrimaryExpression option(FnCallExpression | ArrayAccessExpression | FieldAccessExpression | SliceExpression | PtrDerefExpression) +SuffixOpExpression = ("async" option("<" SuffixOpExpression ">") SuffixOpExpression FnCallExpression) | PrimaryExpression option(FnCallExpression | ArrayAccessExpression | FieldAccessExpression | SliceExpression | ".*" | ".?") FieldAccessExpression = "." Symbol -PtrDerefExpression = ".*" - FnCallExpression = "(" list(Expression, ",") ")" ArrayAccessExpression = "[" Expression "]" @@ -6033,7 +6031,7 @@ ContainerInitBody = list(StructLiteralField, ",") | list(Expression, ",") StructLiteralField = "." Symbol "=" Expression -PrefixOp = "!" | "-" | "~" | (("*" | "[*]") option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "??" | "-%" | "try" | "await" +PrefixOp = "!" | "-" | "~" | (("*" | "[*]") option("align" "(" Expression option(":" Integer ":" Integer) ")" ) option("const") option("volatile")) | "?" | "-%" | "try" | "await" PrimaryExpression = Integer | Float | String | CharLiteral | KeywordLiteral | GroupedExpression | BlockExpression(BlockOrExpression) | Symbol | ("@" Symbol FnCallExpression) | ArrayType | FnProto | AsmExpression | ContainerDecl | ("continue" option(":" Symbol)) | ErrorSetDecl | PromiseType diff --git a/example/cat/main.zig b/example/cat/main.zig index 1b34cb22eb..27690d2695 100644 --- a/example/cat/main.zig +++ b/example/cat/main.zig @@ -7,7 +7,7 @@ const allocator = std.debug.global_allocator; pub fn main() !void { var args_it = os.args(); - const exe = try unwrapArg(??args_it.next(allocator)); + const exe = try unwrapArg(args_it.next(allocator).?); var catted_anything = false; var stdout_file = try io.getStdOut(); diff --git a/src-self-hosted/arg.zig b/src-self-hosted/arg.zig index df2c04ef1f..dc89483213 100644 --- a/src-self-hosted/arg.zig +++ b/src-self-hosted/arg.zig @@ -99,7 +99,7 @@ pub const Args = struct { error.ArgumentNotInAllowedSet => { std.debug.warn("argument '{}' is invalid for flag '{}'\n", args[i], arg); std.debug.warn("allowed options are "); - for (??flag.allowed_set) |possible| { + for (flag.allowed_set.?) |possible| { std.debug.warn("'{}' ", possible); } std.debug.warn("\n"); @@ -276,14 +276,14 @@ test "parse arguments" { debug.assert(!args.present("help2")); debug.assert(!args.present("init")); - debug.assert(mem.eql(u8, ??args.single("build-file"), "build.zig")); - debug.assert(mem.eql(u8, ??args.single("color"), "on")); + debug.assert(mem.eql(u8, args.single("build-file").?, "build.zig")); + debug.assert(mem.eql(u8, args.single("color").?, "on")); - const objects = ??args.many("object"); + const objects = args.many("object").?; debug.assert(mem.eql(u8, objects[0], "obj1")); debug.assert(mem.eql(u8, objects[1], "obj2")); - debug.assert(mem.eql(u8, ??args.single("library"), "lib2")); + debug.assert(mem.eql(u8, args.single("library").?, "lib2")); const pos = args.positionals.toSliceConst(); debug.assert(mem.eql(u8, pos[0], "build")); diff --git a/src-self-hosted/llvm.zig b/src-self-hosted/llvm.zig index 16c359adcf..391a92cd63 100644 --- a/src-self-hosted/llvm.zig +++ b/src-self-hosted/llvm.zig @@ -8,6 +8,6 @@ pub const ContextRef = removeNullability(c.LLVMContextRef); pub const BuilderRef = removeNullability(c.LLVMBuilderRef); fn removeNullability(comptime T: type) type { - comptime assert(@typeId(T) == builtin.TypeId.Nullable); + comptime assert(@typeId(T) == builtin.TypeId.Optional); return T.Child; } diff --git a/src-self-hosted/main.zig b/src-self-hosted/main.zig index a264b5484a..64734f077a 100644 --- a/src-self-hosted/main.zig +++ b/src-self-hosted/main.zig @@ -490,7 +490,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo try stderr.print("encountered --pkg-end with no matching --pkg-begin\n"); os.exit(1); } - cur_pkg = ??cur_pkg.parent; + cur_pkg = cur_pkg.parent.?; } } @@ -514,7 +514,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo }, } - const basename = os.path.basename(??in_file); + const basename = os.path.basename(in_file.?); var it = mem.split(basename, "."); const root_name = it.next() ?? { try stderr.write("file name cannot be empty\n"); @@ -523,12 +523,12 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo const asm_a = flags.many("assembly"); const obj_a = flags.many("object"); - if (in_file == null and (obj_a == null or (??obj_a).len == 0) and (asm_a == null or (??asm_a).len == 0)) { + if (in_file == null and (obj_a == null or obj_a.?.len == 0) and (asm_a == null or asm_a.?.len == 0)) { try stderr.write("Expected source file argument or at least one --object or --assembly argument\n"); os.exit(1); } - if (out_type == Module.Kind.Obj and (obj_a != null and (??obj_a).len != 0)) { + if (out_type == Module.Kind.Obj and (obj_a != null and obj_a.?.len != 0)) { try stderr.write("When building an object file, --object arguments are invalid\n"); os.exit(1); } diff --git a/src/all_types.hpp b/src/all_types.hpp index 14a44ea768..2a5a0ad740 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -145,8 +145,8 @@ enum ConstPtrSpecial { // emit a binary with a compile time known address. // In this case index is the numeric address value. // We also use this for null pointer. We need the data layout for ConstCastOnly == true - // types to be the same, so all nullables of pointer types use x_ptr - // instead of x_nullable + // types to be the same, so all optionals of pointer types use x_ptr + // instead of x_optional ConstPtrSpecialHardCodedAddr, // This means that the pointer represents memory of assigning to _. // That is, storing discards the data, and loading is invalid. @@ -222,10 +222,10 @@ enum RuntimeHintErrorUnion { RuntimeHintErrorUnionNonError, }; -enum RuntimeHintMaybe { - RuntimeHintMaybeUnknown, - RuntimeHintMaybeNull, // TODO is this value even possible? if this is the case it might mean the const value is compile time known. - RuntimeHintMaybeNonNull, +enum RuntimeHintOptional { + RuntimeHintOptionalUnknown, + RuntimeHintOptionalNull, // TODO is this value even possible? if this is the case it might mean the const value is compile time known. + RuntimeHintOptionalNonNull, }; enum RuntimeHintPtr { @@ -254,7 +254,7 @@ struct ConstExprValue { bool x_bool; ConstBoundFnValue x_bound_fn; TypeTableEntry *x_type; - ConstExprValue *x_nullable; + ConstExprValue *x_optional; ConstErrValue x_err_union; ErrorTableEntry *x_err_set; BigInt x_enum_tag; @@ -268,7 +268,7 @@ struct ConstExprValue { // populated if special == ConstValSpecialRuntime RuntimeHintErrorUnion rh_error_union; - RuntimeHintMaybe rh_maybe; + RuntimeHintOptional rh_maybe; RuntimeHintPtr rh_ptr; } data; }; @@ -556,7 +556,7 @@ enum BinOpType { BinOpTypeMultWrap, BinOpTypeDiv, BinOpTypeMod, - BinOpTypeUnwrapMaybe, + BinOpTypeUnwrapOptional, BinOpTypeArrayCat, BinOpTypeArrayMult, BinOpTypeErrorUnion, @@ -623,8 +623,8 @@ enum PrefixOp { PrefixOpBinNot, PrefixOpNegation, PrefixOpNegationWrap, - PrefixOpMaybe, - PrefixOpUnwrapMaybe, + PrefixOpOptional, + PrefixOpUnwrapOptional, PrefixOpAddrOf, }; @@ -1052,7 +1052,7 @@ struct TypeTableEntryStruct { HashMap fields_by_name; }; -struct TypeTableEntryMaybe { +struct TypeTableEntryOptional { TypeTableEntry *child_type; }; @@ -1175,7 +1175,7 @@ enum TypeTableEntryId { TypeTableEntryIdComptimeInt, TypeTableEntryIdUndefined, TypeTableEntryIdNull, - TypeTableEntryIdMaybe, + TypeTableEntryIdOptional, TypeTableEntryIdErrorUnion, TypeTableEntryIdErrorSet, TypeTableEntryIdEnum, @@ -1206,7 +1206,7 @@ struct TypeTableEntry { TypeTableEntryFloat floating; TypeTableEntryArray array; TypeTableEntryStruct structure; - TypeTableEntryMaybe maybe; + TypeTableEntryOptional maybe; TypeTableEntryErrorUnion error_union; TypeTableEntryErrorSet error_set; TypeTableEntryEnum enumeration; @@ -1402,7 +1402,7 @@ enum PanicMsgId { PanicMsgIdRemainderDivisionByZero, PanicMsgIdExactDivisionRemainder, PanicMsgIdSliceWidenRemainder, - PanicMsgIdUnwrapMaybeFail, + PanicMsgIdUnwrapOptionalFail, PanicMsgIdInvalidErrorCode, PanicMsgIdIncorrectAlignment, PanicMsgIdBadUnionField, @@ -2016,8 +2016,8 @@ enum IrInstructionId { IrInstructionIdAsm, IrInstructionIdSizeOf, IrInstructionIdTestNonNull, - IrInstructionIdUnwrapMaybe, - IrInstructionIdMaybeWrap, + IrInstructionIdUnwrapOptional, + IrInstructionIdOptionalWrap, IrInstructionIdUnionTag, IrInstructionIdClz, IrInstructionIdCtz, @@ -2184,7 +2184,7 @@ enum IrUnOp { IrUnOpNegation, IrUnOpNegationWrap, IrUnOpDereference, - IrUnOpMaybe, + IrUnOpOptional, }; struct IrInstructionUnOp { @@ -2487,7 +2487,7 @@ struct IrInstructionTestNonNull { IrInstruction *value; }; -struct IrInstructionUnwrapMaybe { +struct IrInstructionUnwrapOptional { IrInstruction base; IrInstruction *value; @@ -2745,7 +2745,7 @@ struct IrInstructionUnwrapErrPayload { bool safety_check_on; }; -struct IrInstructionMaybeWrap { +struct IrInstructionOptionalWrap { IrInstruction base; IrInstruction *value; @@ -2954,10 +2954,10 @@ struct IrInstructionExport { struct IrInstructionErrorReturnTrace { IrInstruction base; - enum Nullable { + enum Optional { Null, NonNull, - } nullable; + } optional; }; struct IrInstructionErrorUnion { diff --git a/src/analyze.cpp b/src/analyze.cpp index 16b2cb0590..ed261148ea 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -236,7 +236,7 @@ bool type_is_complete(TypeTableEntry *type_entry) { case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdFn: @@ -272,7 +272,7 @@ bool type_has_zero_bits_known(TypeTableEntry *type_entry) { case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdFn: @@ -520,7 +520,7 @@ TypeTableEntry *get_maybe_type(CodeGen *g, TypeTableEntry *child_type) { } else { ensure_complete_type(g, child_type); - TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdMaybe); + TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdOptional); assert(child_type->type_ref || child_type->zero_bits); assert(child_type->di_type); entry->is_copyable = type_is_copyable(g, child_type); @@ -1361,7 +1361,7 @@ static bool type_allowed_in_packed_struct(TypeTableEntry *type_entry) { return type_entry->data.structure.layout == ContainerLayoutPacked; case TypeTableEntryIdUnion: return type_entry->data.unionation.layout == ContainerLayoutPacked; - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: { TypeTableEntry *child_type = type_entry->data.maybe.child_type; return type_is_codegen_pointer(child_type); @@ -1415,7 +1415,7 @@ static bool type_allowed_in_extern(CodeGen *g, TypeTableEntry *type_entry) { return type_allowed_in_extern(g, type_entry->data.pointer.child_type); case TypeTableEntryIdStruct: return type_entry->data.structure.layout == ContainerLayoutExtern || type_entry->data.structure.layout == ContainerLayoutPacked; - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: { TypeTableEntry *child_type = type_entry->data.maybe.child_type; return child_type->id == TypeTableEntryIdPointer || child_type->id == TypeTableEntryIdFn; @@ -1538,7 +1538,7 @@ static TypeTableEntry *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *c case TypeTableEntryIdPointer: case TypeTableEntryIdArray: case TypeTableEntryIdStruct: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdEnum: @@ -1632,7 +1632,7 @@ static TypeTableEntry *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *c case TypeTableEntryIdPointer: case TypeTableEntryIdArray: case TypeTableEntryIdStruct: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdEnum: @@ -2985,8 +2985,8 @@ static void typecheck_panic_fn(CodeGen *g, FnTableEntry *panic_fn) { return wrong_panic_prototype(g, proto_node, fn_type); } - TypeTableEntry *nullable_ptr_to_stack_trace_type = get_maybe_type(g, get_ptr_to_stack_trace_type(g)); - if (fn_type_id->param_info[1].type != nullable_ptr_to_stack_trace_type) { + TypeTableEntry *optional_ptr_to_stack_trace_type = get_maybe_type(g, get_ptr_to_stack_trace_type(g)); + if (fn_type_id->param_info[1].type != optional_ptr_to_stack_trace_type) { return wrong_panic_prototype(g, proto_node, fn_type); } @@ -3368,7 +3368,7 @@ TypeTableEntry *validate_var_type(CodeGen *g, AstNode *source_node, TypeTableEnt case TypeTableEntryIdPointer: case TypeTableEntryIdArray: case TypeTableEntryIdStruct: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdEnum: @@ -3746,7 +3746,7 @@ static bool is_container(TypeTableEntry *type_entry) { case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdFn: @@ -3805,7 +3805,7 @@ void resolve_container_type(CodeGen *g, TypeTableEntry *type_entry) { case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdFn: @@ -3824,7 +3824,7 @@ TypeTableEntry *get_codegen_ptr_type(TypeTableEntry *type) { if (type->id == TypeTableEntryIdPointer) return type; if (type->id == TypeTableEntryIdFn) return type; if (type->id == TypeTableEntryIdPromise) return type; - if (type->id == TypeTableEntryIdMaybe) { + if (type->id == TypeTableEntryIdOptional) { if (type->data.maybe.child_type->id == TypeTableEntryIdPointer) return type->data.maybe.child_type; if (type->data.maybe.child_type->id == TypeTableEntryIdFn) return type->data.maybe.child_type; if (type->data.maybe.child_type->id == TypeTableEntryIdPromise) return type->data.maybe.child_type; @@ -4331,7 +4331,7 @@ bool handle_is_ptr(TypeTableEntry *type_entry) { return type_has_bits(type_entry); case TypeTableEntryIdErrorUnion: return type_has_bits(type_entry->data.error_union.payload_type); - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: return type_has_bits(type_entry->data.maybe.child_type) && !type_is_codegen_pointer(type_entry->data.maybe.child_type); case TypeTableEntryIdUnion: @@ -4709,12 +4709,12 @@ static uint32_t hash_const_val(ConstExprValue *const_val) { case TypeTableEntryIdUnion: // TODO better hashing algorithm return 2709806591; - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: if (get_codegen_ptr_type(const_val->type) != nullptr) { return hash_const_val(const_val) * 1992916303; } else { - if (const_val->data.x_nullable) { - return hash_const_val(const_val->data.x_nullable) * 1992916303; + if (const_val->data.x_optional) { + return hash_const_val(const_val->data.x_optional) * 1992916303; } else { return 4016830364; } @@ -4817,12 +4817,12 @@ static bool can_mutate_comptime_var_state(ConstExprValue *value) { } return false; - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: if (get_codegen_ptr_type(value->type) != nullptr) return value->data.x_ptr.mut == ConstPtrMutComptimeVar; - if (value->data.x_nullable == nullptr) + if (value->data.x_optional == nullptr) return false; - return can_mutate_comptime_var_state(value->data.x_nullable); + return can_mutate_comptime_var_state(value->data.x_optional); case TypeTableEntryIdErrorUnion: if (value->data.x_err_union.err != nullptr) @@ -4869,7 +4869,7 @@ static bool return_type_is_cacheable(TypeTableEntry *return_type) { case TypeTableEntryIdUnion: return false; - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: return return_type_is_cacheable(return_type->data.maybe.child_type); case TypeTableEntryIdErrorUnion: @@ -4978,7 +4978,7 @@ bool type_requires_comptime(TypeTableEntry *type_entry) { case TypeTableEntryIdUnion: assert(type_has_zero_bits_known(type_entry)); return type_entry->data.unionation.requires_comptime; - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: return type_requires_comptime(type_entry->data.maybe.child_type); case TypeTableEntryIdErrorUnion: return type_requires_comptime(type_entry->data.error_union.payload_type); @@ -5460,13 +5460,13 @@ bool const_values_equal(ConstExprValue *a, ConstExprValue *b) { zig_panic("TODO"); case TypeTableEntryIdNull: zig_panic("TODO"); - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: if (get_codegen_ptr_type(a->type) != nullptr) return const_values_equal_ptr(a, b); - if (a->data.x_nullable == nullptr || b->data.x_nullable == nullptr) { - return (a->data.x_nullable == nullptr && b->data.x_nullable == nullptr); + if (a->data.x_optional == nullptr || b->data.x_optional == nullptr) { + return (a->data.x_optional == nullptr && b->data.x_optional == nullptr); } else { - return const_values_equal(a->data.x_nullable, b->data.x_nullable); + return const_values_equal(a->data.x_optional, b->data.x_optional); } case TypeTableEntryIdErrorUnion: zig_panic("TODO"); @@ -5708,12 +5708,12 @@ void render_const_value(CodeGen *g, Buf *buf, ConstExprValue *const_val) { buf_appendf(buf, "undefined"); return; } - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: { if (get_codegen_ptr_type(const_val->type) != nullptr) return render_const_val_ptr(g, buf, const_val, type_entry->data.maybe.child_type); - if (const_val->data.x_nullable) { - render_const_value(g, buf, const_val->data.x_nullable); + if (const_val->data.x_optional) { + render_const_value(g, buf, const_val->data.x_optional); } else { buf_appendf(buf, "null"); } @@ -5819,7 +5819,7 @@ uint32_t type_id_hash(TypeId x) { case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorSet: case TypeTableEntryIdEnum: case TypeTableEntryIdUnion: @@ -5865,7 +5865,7 @@ bool type_id_eql(TypeId a, TypeId b) { case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdPromise: case TypeTableEntryIdErrorSet: case TypeTableEntryIdEnum: @@ -5987,7 +5987,7 @@ static const TypeTableEntryId all_type_ids[] = { TypeTableEntryIdComptimeInt, TypeTableEntryIdUndefined, TypeTableEntryIdNull, - TypeTableEntryIdMaybe, + TypeTableEntryIdOptional, TypeTableEntryIdErrorUnion, TypeTableEntryIdErrorSet, TypeTableEntryIdEnum, @@ -6042,7 +6042,7 @@ size_t type_id_index(TypeTableEntry *entry) { return 11; case TypeTableEntryIdNull: return 12; - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: return 13; case TypeTableEntryIdErrorUnion: return 14; @@ -6100,8 +6100,8 @@ const char *type_id_name(TypeTableEntryId id) { return "Undefined"; case TypeTableEntryIdNull: return "Null"; - case TypeTableEntryIdMaybe: - return "Nullable"; + case TypeTableEntryIdOptional: + return "Optional"; case TypeTableEntryIdErrorUnion: return "ErrorUnion"; case TypeTableEntryIdErrorSet: diff --git a/src/ast_render.cpp b/src/ast_render.cpp index 3785cb6ca1..2c8c03b226 100644 --- a/src/ast_render.cpp +++ b/src/ast_render.cpp @@ -50,7 +50,7 @@ static const char *bin_op_str(BinOpType bin_op) { case BinOpTypeAssignBitXor: return "^="; case BinOpTypeAssignBitOr: return "|="; case BinOpTypeAssignMergeErrorSets: return "||="; - case BinOpTypeUnwrapMaybe: return "??"; + case BinOpTypeUnwrapOptional: return "??"; case BinOpTypeArrayCat: return "++"; case BinOpTypeArrayMult: return "**"; case BinOpTypeErrorUnion: return "!"; @@ -66,8 +66,8 @@ static const char *prefix_op_str(PrefixOp prefix_op) { case PrefixOpNegationWrap: return "-%"; case PrefixOpBoolNot: return "!"; case PrefixOpBinNot: return "~"; - case PrefixOpMaybe: return "?"; - case PrefixOpUnwrapMaybe: return "??"; + case PrefixOpOptional: return "?"; + case PrefixOpUnwrapOptional: return "??"; case PrefixOpAddrOf: return "&"; } zig_unreachable(); diff --git a/src/codegen.cpp b/src/codegen.cpp index 65b465a519..da08ecfc9e 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -865,7 +865,7 @@ static Buf *panic_msg_buf(PanicMsgId msg_id) { return buf_create_from_str("exact division produced remainder"); case PanicMsgIdSliceWidenRemainder: return buf_create_from_str("slice widening size mismatch"); - case PanicMsgIdUnwrapMaybeFail: + case PanicMsgIdUnwrapOptionalFail: return buf_create_from_str("attempt to unwrap null"); case PanicMsgIdUnreachable: return buf_create_from_str("reached unreachable code"); @@ -2734,7 +2734,7 @@ static LLVMValueRef ir_render_un_op(CodeGen *g, IrExecutable *executable, IrInst switch (op_id) { case IrUnOpInvalid: - case IrUnOpMaybe: + case IrUnOpOptional: case IrUnOpDereference: zig_unreachable(); case IrUnOpNegation: @@ -3333,7 +3333,7 @@ static LLVMValueRef ir_render_asm(CodeGen *g, IrExecutable *executable, IrInstru } static LLVMValueRef gen_non_null_bit(CodeGen *g, TypeTableEntry *maybe_type, LLVMValueRef maybe_handle) { - assert(maybe_type->id == TypeTableEntryIdMaybe); + assert(maybe_type->id == TypeTableEntryIdOptional); TypeTableEntry *child_type = maybe_type->data.maybe.child_type; if (child_type->zero_bits) { return maybe_handle; @@ -3355,23 +3355,23 @@ static LLVMValueRef ir_render_test_non_null(CodeGen *g, IrExecutable *executable } static LLVMValueRef ir_render_unwrap_maybe(CodeGen *g, IrExecutable *executable, - IrInstructionUnwrapMaybe *instruction) + IrInstructionUnwrapOptional *instruction) { TypeTableEntry *ptr_type = instruction->value->value.type; assert(ptr_type->id == TypeTableEntryIdPointer); TypeTableEntry *maybe_type = ptr_type->data.pointer.child_type; - assert(maybe_type->id == TypeTableEntryIdMaybe); + assert(maybe_type->id == TypeTableEntryIdOptional); TypeTableEntry *child_type = maybe_type->data.maybe.child_type; LLVMValueRef maybe_ptr = ir_llvm_value(g, instruction->value); LLVMValueRef maybe_handle = get_handle_value(g, maybe_ptr, maybe_type, ptr_type); if (ir_want_runtime_safety(g, &instruction->base) && instruction->safety_check_on) { LLVMValueRef non_null_bit = gen_non_null_bit(g, maybe_type, maybe_handle); - LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "UnwrapMaybeOk"); - LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "UnwrapMaybeFail"); + LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "UnwrapOptionalOk"); + LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "UnwrapOptionalFail"); LLVMBuildCondBr(g->builder, non_null_bit, ok_block, fail_block); LLVMPositionBuilderAtEnd(g->builder, fail_block); - gen_safety_crash(g, PanicMsgIdUnwrapMaybeFail); + gen_safety_crash(g, PanicMsgIdUnwrapOptionalFail); LLVMPositionBuilderAtEnd(g->builder, ok_block); } @@ -3593,17 +3593,17 @@ static LLVMValueRef ir_render_align_cast(CodeGen *g, IrExecutable *executable, I } else if (target_type->id == TypeTableEntryIdFn) { align_bytes = target_type->data.fn.fn_type_id.alignment; ptr_val = target_val; - } else if (target_type->id == TypeTableEntryIdMaybe && + } else if (target_type->id == TypeTableEntryIdOptional && target_type->data.maybe.child_type->id == TypeTableEntryIdPointer) { align_bytes = target_type->data.maybe.child_type->data.pointer.alignment; ptr_val = target_val; - } else if (target_type->id == TypeTableEntryIdMaybe && + } else if (target_type->id == TypeTableEntryIdOptional && target_type->data.maybe.child_type->id == TypeTableEntryIdFn) { align_bytes = target_type->data.maybe.child_type->data.fn.fn_type_id.alignment; ptr_val = target_val; - } else if (target_type->id == TypeTableEntryIdMaybe && + } else if (target_type->id == TypeTableEntryIdOptional && target_type->data.maybe.child_type->id == TypeTableEntryIdPromise) { zig_panic("TODO audit this function"); @@ -3705,7 +3705,7 @@ static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutable *executable, IrIn success_order, failure_order, instruction->is_weak); TypeTableEntry *maybe_type = instruction->base.value.type; - assert(maybe_type->id == TypeTableEntryIdMaybe); + assert(maybe_type->id == TypeTableEntryIdOptional); TypeTableEntry *child_type = maybe_type->data.maybe.child_type; if (type_is_codegen_pointer(child_type)) { @@ -4115,10 +4115,10 @@ static LLVMValueRef ir_render_unwrap_err_payload(CodeGen *g, IrExecutable *execu } } -static LLVMValueRef ir_render_maybe_wrap(CodeGen *g, IrExecutable *executable, IrInstructionMaybeWrap *instruction) { +static LLVMValueRef ir_render_maybe_wrap(CodeGen *g, IrExecutable *executable, IrInstructionOptionalWrap *instruction) { TypeTableEntry *wanted_type = instruction->base.value.type; - assert(wanted_type->id == TypeTableEntryIdMaybe); + assert(wanted_type->id == TypeTableEntryIdOptional); TypeTableEntry *child_type = wanted_type->data.maybe.child_type; @@ -4699,8 +4699,8 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable, return ir_render_asm(g, executable, (IrInstructionAsm *)instruction); case IrInstructionIdTestNonNull: return ir_render_test_non_null(g, executable, (IrInstructionTestNonNull *)instruction); - case IrInstructionIdUnwrapMaybe: - return ir_render_unwrap_maybe(g, executable, (IrInstructionUnwrapMaybe *)instruction); + case IrInstructionIdUnwrapOptional: + return ir_render_unwrap_maybe(g, executable, (IrInstructionUnwrapOptional *)instruction); case IrInstructionIdClz: return ir_render_clz(g, executable, (IrInstructionClz *)instruction); case IrInstructionIdCtz: @@ -4741,8 +4741,8 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable, return ir_render_unwrap_err_code(g, executable, (IrInstructionUnwrapErrCode *)instruction); case IrInstructionIdUnwrapErrPayload: return ir_render_unwrap_err_payload(g, executable, (IrInstructionUnwrapErrPayload *)instruction); - case IrInstructionIdMaybeWrap: - return ir_render_maybe_wrap(g, executable, (IrInstructionMaybeWrap *)instruction); + case IrInstructionIdOptionalWrap: + return ir_render_maybe_wrap(g, executable, (IrInstructionOptionalWrap *)instruction); case IrInstructionIdErrWrapCode: return ir_render_err_wrap_code(g, executable, (IrInstructionErrWrapCode *)instruction); case IrInstructionIdErrWrapPayload: @@ -4972,7 +4972,7 @@ static LLVMValueRef pack_const_int(CodeGen *g, LLVMTypeRef big_int_type_ref, Con } case TypeTableEntryIdPointer: case TypeTableEntryIdFn: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdPromise: { LLVMValueRef ptr_val = gen_const_val(g, const_val, ""); @@ -5137,19 +5137,19 @@ static LLVMValueRef gen_const_val(CodeGen *g, ConstExprValue *const_val, const c } else { return LLVMConstNull(LLVMInt1Type()); } - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: { TypeTableEntry *child_type = type_entry->data.maybe.child_type; if (child_type->zero_bits) { - return LLVMConstInt(LLVMInt1Type(), const_val->data.x_nullable ? 1 : 0, false); + return LLVMConstInt(LLVMInt1Type(), const_val->data.x_optional ? 1 : 0, false); } else if (type_is_codegen_pointer(child_type)) { return gen_const_val_ptr(g, const_val, name); } else { LLVMValueRef child_val; LLVMValueRef maybe_val; bool make_unnamed_struct; - if (const_val->data.x_nullable) { - child_val = gen_const_val(g, const_val->data.x_nullable, ""); + if (const_val->data.x_optional) { + child_val = gen_const_val(g, const_val->data.x_optional, ""); maybe_val = LLVMConstAllOnes(LLVMInt1Type()); make_unnamed_struct = is_llvm_value_unnamed_type(const_val->type, child_val); @@ -5755,8 +5755,8 @@ static void do_code_gen(CodeGen *g) { } else if (instruction->id == IrInstructionIdSlice) { IrInstructionSlice *slice_instruction = (IrInstructionSlice *)instruction; slot = &slice_instruction->tmp_ptr; - } else if (instruction->id == IrInstructionIdMaybeWrap) { - IrInstructionMaybeWrap *maybe_wrap_instruction = (IrInstructionMaybeWrap *)instruction; + } else if (instruction->id == IrInstructionIdOptionalWrap) { + IrInstructionOptionalWrap *maybe_wrap_instruction = (IrInstructionOptionalWrap *)instruction; slot = &maybe_wrap_instruction->tmp_ptr; } else if (instruction->id == IrInstructionIdErrWrapPayload) { IrInstructionErrWrapPayload *err_wrap_payload_instruction = (IrInstructionErrWrapPayload *)instruction; @@ -6511,7 +6511,7 @@ Buf *codegen_generate_builtin_source(CodeGen *g) { " ComptimeInt: void,\n" " Undefined: void,\n" " Null: void,\n" - " Nullable: Nullable,\n" + " Optional: Optional,\n" " ErrorUnion: ErrorUnion,\n" " ErrorSet: ErrorSet,\n" " Enum: Enum,\n" @@ -6570,7 +6570,7 @@ Buf *codegen_generate_builtin_source(CodeGen *g) { " defs: []Definition,\n" " };\n" "\n" - " pub const Nullable = struct {\n" + " pub const Optional = struct {\n" " child: type,\n" " };\n" "\n" @@ -7145,7 +7145,7 @@ static void prepend_c_type_to_decl_list(CodeGen *g, GenH *gen_h, TypeTableEntry case TypeTableEntryIdArray: prepend_c_type_to_decl_list(g, gen_h, type_entry->data.array.child_type); return; - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: prepend_c_type_to_decl_list(g, gen_h, type_entry->data.maybe.child_type); return; case TypeTableEntryIdFn: @@ -7234,7 +7234,7 @@ static void get_c_type(CodeGen *g, GenH *gen_h, TypeTableEntry *type_entry, Buf buf_appendf(out_buf, "%s%s *", const_str, buf_ptr(&child_buf)); break; } - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: { TypeTableEntry *child_type = type_entry->data.maybe.child_type; if (child_type->zero_bits) { @@ -7448,7 +7448,7 @@ static void gen_h_file(CodeGen *g) { case TypeTableEntryIdBlock: case TypeTableEntryIdBoundFn: case TypeTableEntryIdArgTuple: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdFn: case TypeTableEntryIdPromise: zig_unreachable(); diff --git a/src/ir.cpp b/src/ir.cpp index 10098f3c32..02606fc4aa 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -47,7 +47,7 @@ enum ConstCastResultId { ConstCastResultIdErrSetGlobal, ConstCastResultIdPointerChild, ConstCastResultIdSliceChild, - ConstCastResultIdNullableChild, + ConstCastResultIdOptionalChild, ConstCastResultIdErrorUnionPayload, ConstCastResultIdErrorUnionErrorSet, ConstCastResultIdFnAlign, @@ -86,7 +86,7 @@ struct ConstCastOnly { ConstCastErrSetMismatch error_set; ConstCastOnly *pointer_child; ConstCastOnly *slice_child; - ConstCastOnly *nullable_child; + ConstCastOnly *optional_child; ConstCastOnly *error_union_payload; ConstCastOnly *error_union_error_set; ConstCastOnly *return_type; @@ -372,8 +372,8 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionTestNonNull *) { return IrInstructionIdTestNonNull; } -static constexpr IrInstructionId ir_instruction_id(IrInstructionUnwrapMaybe *) { - return IrInstructionIdUnwrapMaybe; +static constexpr IrInstructionId ir_instruction_id(IrInstructionUnwrapOptional *) { + return IrInstructionIdUnwrapOptional; } static constexpr IrInstructionId ir_instruction_id(IrInstructionClz *) { @@ -524,8 +524,8 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionUnwrapErrPayload return IrInstructionIdUnwrapErrPayload; } -static constexpr IrInstructionId ir_instruction_id(IrInstructionMaybeWrap *) { - return IrInstructionIdMaybeWrap; +static constexpr IrInstructionId ir_instruction_id(IrInstructionOptionalWrap *) { + return IrInstructionIdOptionalWrap; } static constexpr IrInstructionId ir_instruction_id(IrInstructionErrWrapPayload *) { @@ -1571,7 +1571,7 @@ static IrInstruction *ir_build_test_nonnull_from(IrBuilder *irb, IrInstruction * static IrInstruction *ir_build_unwrap_maybe(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *value, bool safety_check_on) { - IrInstructionUnwrapMaybe *instruction = ir_build_instruction(irb, scope, source_node); + IrInstructionUnwrapOptional *instruction = ir_build_instruction(irb, scope, source_node); instruction->value = value; instruction->safety_check_on = safety_check_on; @@ -1590,7 +1590,7 @@ static IrInstruction *ir_build_unwrap_maybe_from(IrBuilder *irb, IrInstruction * } static IrInstruction *ir_build_maybe_wrap(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *value) { - IrInstructionMaybeWrap *instruction = ir_build_instruction(irb, scope, source_node); + IrInstructionOptionalWrap *instruction = ir_build_instruction(irb, scope, source_node); instruction->value = value; ir_ref_instruction(value, irb->current_basic_block); @@ -2496,9 +2496,9 @@ static IrInstruction *ir_build_arg_type(IrBuilder *irb, Scope *scope, AstNode *s return &instruction->base; } -static IrInstruction *ir_build_error_return_trace(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstructionErrorReturnTrace::Nullable nullable) { +static IrInstruction *ir_build_error_return_trace(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstructionErrorReturnTrace::Optional optional) { IrInstructionErrorReturnTrace *instruction = ir_build_instruction(irb, scope, source_node); - instruction->nullable = nullable; + instruction->optional = optional; return &instruction->base; } @@ -3295,9 +3295,9 @@ static IrInstruction *ir_gen_maybe_ok_or(IrBuilder *irb, Scope *parent_scope, As is_comptime = ir_build_test_comptime(irb, parent_scope, node, is_non_null); } - IrBasicBlock *ok_block = ir_create_basic_block(irb, parent_scope, "MaybeNonNull"); - IrBasicBlock *null_block = ir_create_basic_block(irb, parent_scope, "MaybeNull"); - IrBasicBlock *end_block = ir_create_basic_block(irb, parent_scope, "MaybeEnd"); + IrBasicBlock *ok_block = ir_create_basic_block(irb, parent_scope, "OptionalNonNull"); + IrBasicBlock *null_block = ir_create_basic_block(irb, parent_scope, "OptionalNull"); + IrBasicBlock *end_block = ir_create_basic_block(irb, parent_scope, "OptionalEnd"); ir_build_cond_br(irb, parent_scope, node, is_non_null, ok_block, null_block, is_comptime); ir_set_cursor_at_end_and_append_block(irb, null_block); @@ -3426,7 +3426,7 @@ static IrInstruction *ir_gen_bin_op(IrBuilder *irb, Scope *scope, AstNode *node) return ir_gen_bin_op_id(irb, scope, node, IrBinOpArrayMult); case BinOpTypeMergeErrorSets: return ir_gen_bin_op_id(irb, scope, node, IrBinOpMergeErrorSets); - case BinOpTypeUnwrapMaybe: + case BinOpTypeUnwrapOptional: return ir_gen_maybe_ok_or(irb, scope, node); case BinOpTypeErrorUnion: return ir_gen_error_union(irb, scope, node); @@ -4703,9 +4703,9 @@ static IrInstruction *ir_gen_prefix_op_expr(IrBuilder *irb, Scope *scope, AstNod return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpNegation), lval); case PrefixOpNegationWrap: return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpNegationWrap), lval); - case PrefixOpMaybe: - return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpMaybe), lval); - case PrefixOpUnwrapMaybe: + case PrefixOpOptional: + return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpOptional), lval); + case PrefixOpUnwrapOptional: return ir_gen_maybe_assert_ok(irb, scope, node, lval); case PrefixOpAddrOf: { AstNode *expr_node = node->data.prefix_op_expr.primary_expr; @@ -5370,9 +5370,9 @@ static IrInstruction *ir_gen_test_expr(IrBuilder *irb, Scope *scope, AstNode *no IrInstruction *maybe_val = ir_build_load_ptr(irb, scope, node, maybe_val_ptr); IrInstruction *is_non_null = ir_build_test_nonnull(irb, scope, node, maybe_val); - IrBasicBlock *then_block = ir_create_basic_block(irb, scope, "MaybeThen"); - IrBasicBlock *else_block = ir_create_basic_block(irb, scope, "MaybeElse"); - IrBasicBlock *endif_block = ir_create_basic_block(irb, scope, "MaybeEndIf"); + IrBasicBlock *then_block = ir_create_basic_block(irb, scope, "OptionalThen"); + IrBasicBlock *else_block = ir_create_basic_block(irb, scope, "OptionalElse"); + IrBasicBlock *endif_block = ir_create_basic_block(irb, scope, "OptionalEndIf"); IrInstruction *is_comptime; if (ir_should_inline(irb->exec, scope)) { @@ -7519,7 +7519,7 @@ static bool ir_num_lit_fits_in_other_type(IrAnalyze *ira, IrInstruction *instruc } } else if (const_val_fits_in_num_lit(const_val, other_type)) { return true; - } else if (other_type->id == TypeTableEntryIdMaybe) { + } else if (other_type->id == TypeTableEntryIdOptional) { TypeTableEntry *child_type = other_type->data.maybe.child_type; if (const_val_fits_in_num_lit(const_val, child_type)) { return true; @@ -7663,7 +7663,7 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, TypeTableEntry return result; // * and [*] can do a const-cast-only to ?* and ?[*], respectively - if (expected_type->id == TypeTableEntryIdMaybe && + if (expected_type->id == TypeTableEntryIdOptional && expected_type->data.maybe.child_type->id == TypeTableEntryIdPointer && actual_type->id == TypeTableEntryIdPointer) { @@ -7718,12 +7718,12 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, TypeTableEntry } // maybe - if (expected_type->id == TypeTableEntryIdMaybe && actual_type->id == TypeTableEntryIdMaybe) { + if (expected_type->id == TypeTableEntryIdOptional && actual_type->id == TypeTableEntryIdOptional) { ConstCastOnly child = types_match_const_cast_only(ira, expected_type->data.maybe.child_type, actual_type->data.maybe.child_type, source_node); if (child.id != ConstCastResultIdOk) { - result.id = ConstCastResultIdNullableChild; - result.data.nullable_child = allocate_nonzero(1); - *result.data.nullable_child = child; + result.id = ConstCastResultIdOptionalChild; + result.data.optional_child = allocate_nonzero(1); + *result.data.optional_child = child; } return result; } @@ -7925,7 +7925,7 @@ static ImplicitCastMatchResult ir_types_match_with_implicit_cast(IrAnalyze *ira, } // implicit conversion from ?T to ?U - if (expected_type->id == TypeTableEntryIdMaybe && actual_type->id == TypeTableEntryIdMaybe) { + if (expected_type->id == TypeTableEntryIdOptional && actual_type->id == TypeTableEntryIdOptional) { ImplicitCastMatchResult res = ir_types_match_with_implicit_cast(ira, expected_type->data.maybe.child_type, actual_type->data.maybe.child_type, value); if (res != ImplicitCastMatchResultNo) @@ -7933,7 +7933,7 @@ static ImplicitCastMatchResult ir_types_match_with_implicit_cast(IrAnalyze *ira, } // implicit conversion from non maybe type to maybe type - if (expected_type->id == TypeTableEntryIdMaybe) { + if (expected_type->id == TypeTableEntryIdOptional) { ImplicitCastMatchResult res = ir_types_match_with_implicit_cast(ira, expected_type->data.maybe.child_type, actual_type, value); if (res != ImplicitCastMatchResultNo) @@ -7941,7 +7941,7 @@ static ImplicitCastMatchResult ir_types_match_with_implicit_cast(IrAnalyze *ira, } // implicit conversion from null literal to maybe type - if (expected_type->id == TypeTableEntryIdMaybe && + if (expected_type->id == TypeTableEntryIdOptional && actual_type->id == TypeTableEntryIdNull) { return ImplicitCastMatchResultYes; @@ -7963,7 +7963,7 @@ static ImplicitCastMatchResult ir_types_match_with_implicit_cast(IrAnalyze *ira, // implicit conversion from T to U!?T if (expected_type->id == TypeTableEntryIdErrorUnion && - expected_type->data.error_union.payload_type->id == TypeTableEntryIdMaybe && + expected_type->data.error_union.payload_type->id == TypeTableEntryIdOptional && ir_types_match_with_implicit_cast(ira, expected_type->data.error_union.payload_type->data.maybe.child_type, actual_type, value)) @@ -8072,7 +8072,7 @@ static ImplicitCastMatchResult ir_types_match_with_implicit_cast(IrAnalyze *ira, } // implicit [N]T to ?[]const T - if (expected_type->id == TypeTableEntryIdMaybe && + if (expected_type->id == TypeTableEntryIdOptional && is_slice(expected_type->data.maybe.child_type) && actual_type->id == TypeTableEntryIdArray) { @@ -8552,13 +8552,13 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod continue; } - if (prev_type->id == TypeTableEntryIdMaybe && + if (prev_type->id == TypeTableEntryIdOptional && types_match_const_cast_only(ira, prev_type->data.maybe.child_type, cur_type, source_node).id == ConstCastResultIdOk) { continue; } - if (cur_type->id == TypeTableEntryIdMaybe && + if (cur_type->id == TypeTableEntryIdOptional && types_match_const_cast_only(ira, cur_type->data.maybe.child_type, prev_type, source_node).id == ConstCastResultIdOk) { prev_inst = cur_inst; @@ -8711,7 +8711,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod ir_add_error_node(ira, source_node, buf_sprintf("unable to make maybe out of number literal")); return ira->codegen->builtin_types.entry_invalid; - } else if (prev_inst->value.type->id == TypeTableEntryIdMaybe) { + } else if (prev_inst->value.type->id == TypeTableEntryIdOptional) { return prev_inst->value.type; } else { return get_maybe_type(ira->codegen, prev_inst->value.type); @@ -9193,7 +9193,7 @@ static FnTableEntry *ir_resolve_fn(IrAnalyze *ira, IrInstruction *fn_value) { } static IrInstruction *ir_analyze_maybe_wrap(IrAnalyze *ira, IrInstruction *source_instr, IrInstruction *value, TypeTableEntry *wanted_type) { - assert(wanted_type->id == TypeTableEntryIdMaybe); + assert(wanted_type->id == TypeTableEntryIdOptional); if (instr_is_comptime(value)) { TypeTableEntry *payload_type = wanted_type->data.maybe.child_type; @@ -9211,7 +9211,7 @@ static IrInstruction *ir_analyze_maybe_wrap(IrAnalyze *ira, IrInstruction *sourc if (get_codegen_ptr_type(wanted_type) != nullptr) { copy_const_val(&const_instruction->base.value, val, val->data.x_ptr.mut == ConstPtrMutComptimeConst); } else { - const_instruction->base.value.data.x_nullable = val; + const_instruction->base.value.data.x_optional = val; } const_instruction->base.value.type = wanted_type; return &const_instruction->base; @@ -9219,7 +9219,7 @@ static IrInstruction *ir_analyze_maybe_wrap(IrAnalyze *ira, IrInstruction *sourc IrInstruction *result = ir_build_maybe_wrap(&ira->new_irb, source_instr->scope, source_instr->source_node, value); result->value.type = wanted_type; - result->value.data.rh_maybe = RuntimeHintMaybeNonNull; + result->value.data.rh_maybe = RuntimeHintOptionalNonNull; ir_add_alloca(ira, result, wanted_type); return result; } @@ -9361,7 +9361,7 @@ static IrInstruction *ir_analyze_cast_ref(IrAnalyze *ira, IrInstruction *source_ } static IrInstruction *ir_analyze_null_to_maybe(IrAnalyze *ira, IrInstruction *source_instr, IrInstruction *value, TypeTableEntry *wanted_type) { - assert(wanted_type->id == TypeTableEntryIdMaybe); + assert(wanted_type->id == TypeTableEntryIdOptional); assert(instr_is_comptime(value)); ConstExprValue *val = ir_resolve_const(ira, value, UndefBad); @@ -9373,7 +9373,7 @@ static IrInstruction *ir_analyze_null_to_maybe(IrAnalyze *ira, IrInstruction *so const_instruction->base.value.data.x_ptr.special = ConstPtrSpecialHardCodedAddr; const_instruction->base.value.data.x_ptr.data.hard_coded_addr.addr = 0; } else { - const_instruction->base.value.data.x_nullable = nullptr; + const_instruction->base.value.data.x_optional = nullptr; } const_instruction->base.value.type = wanted_type; return &const_instruction->base; @@ -9992,7 +9992,7 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst } // explicit cast from [N]T to ?[]const N - if (wanted_type->id == TypeTableEntryIdMaybe && + if (wanted_type->id == TypeTableEntryIdOptional && is_slice(wanted_type->data.maybe.child_type) && actual_type->id == TypeTableEntryIdArray) { @@ -10091,7 +10091,7 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst // explicit cast from T to ?T // note that the *T to ?*T case is handled via the "ConstCastOnly" mechanism - if (wanted_type->id == TypeTableEntryIdMaybe) { + if (wanted_type->id == TypeTableEntryIdOptional) { TypeTableEntry *wanted_child_type = wanted_type->data.maybe.child_type; if (types_match_const_cast_only(ira, wanted_child_type, actual_type, source_node).id == ConstCastResultIdOk) { return ir_analyze_maybe_wrap(ira, source_instr, value, wanted_type); @@ -10120,7 +10120,7 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst } // explicit cast from null literal to maybe type - if (wanted_type->id == TypeTableEntryIdMaybe && + if (wanted_type->id == TypeTableEntryIdOptional && actual_type->id == TypeTableEntryIdNull) { return ir_analyze_null_to_maybe(ira, source_instr, value, wanted_type); @@ -10173,8 +10173,8 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst // explicit cast from T to E!?T if (wanted_type->id == TypeTableEntryIdErrorUnion && - wanted_type->data.error_union.payload_type->id == TypeTableEntryIdMaybe && - actual_type->id != TypeTableEntryIdMaybe) + wanted_type->data.error_union.payload_type->id == TypeTableEntryIdOptional && + actual_type->id != TypeTableEntryIdOptional) { TypeTableEntry *wanted_child_type = wanted_type->data.error_union.payload_type->data.maybe.child_type; if (types_match_const_cast_only(ira, wanted_child_type, actual_type, source_node).id == ConstCastResultIdOk || @@ -10737,13 +10737,13 @@ static bool resolve_cmp_op_id(IrBinOp op_id, Cmp cmp) { } } -static bool nullable_value_is_null(ConstExprValue *val) { +static bool optional_value_is_null(ConstExprValue *val) { assert(val->special == ConstValSpecialStatic); if (get_codegen_ptr_type(val->type) != nullptr) { return val->data.x_ptr.special == ConstPtrSpecialHardCodedAddr && val->data.x_ptr.data.hard_coded_addr.addr == 0; } else { - return val->data.x_nullable == nullptr; + return val->data.x_optional == nullptr; } } @@ -10755,8 +10755,8 @@ static TypeTableEntry *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp IrBinOp op_id = bin_op_instruction->op_id; bool is_equality_cmp = (op_id == IrBinOpCmpEq || op_id == IrBinOpCmpNotEq); if (is_equality_cmp && - ((op1->value.type->id == TypeTableEntryIdNull && op2->value.type->id == TypeTableEntryIdMaybe) || - (op2->value.type->id == TypeTableEntryIdNull && op1->value.type->id == TypeTableEntryIdMaybe) || + ((op1->value.type->id == TypeTableEntryIdNull && op2->value.type->id == TypeTableEntryIdOptional) || + (op2->value.type->id == TypeTableEntryIdNull && op1->value.type->id == TypeTableEntryIdOptional) || (op1->value.type->id == TypeTableEntryIdNull && op2->value.type->id == TypeTableEntryIdNull))) { if (op1->value.type->id == TypeTableEntryIdNull && op2->value.type->id == TypeTableEntryIdNull) { @@ -10776,7 +10776,7 @@ static TypeTableEntry *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp ConstExprValue *maybe_val = ir_resolve_const(ira, maybe_op, UndefBad); if (!maybe_val) return ira->codegen->builtin_types.entry_invalid; - bool is_null = nullable_value_is_null(maybe_val); + bool is_null = optional_value_is_null(maybe_val); ConstExprValue *out_val = ir_build_const_from(ira, &bin_op_instruction->base); out_val->data.x_bool = (op_id == IrBinOpCmpEq) ? is_null : !is_null; return ira->codegen->builtin_types.entry_bool; @@ -10925,7 +10925,7 @@ static TypeTableEntry *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp case TypeTableEntryIdStruct: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdUnion: ir_add_error_node(ira, source_node, @@ -11998,7 +11998,7 @@ static TypeTableEntry *ir_analyze_instruction_export(IrAnalyze *ira, IrInstructi case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdNamespace: @@ -12022,7 +12022,7 @@ static TypeTableEntry *ir_analyze_instruction_export(IrAnalyze *ira, IrInstructi case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: zig_panic("TODO export const value of type %s", buf_ptr(&target->value.type->name)); @@ -12049,24 +12049,24 @@ static bool exec_has_err_ret_trace(CodeGen *g, IrExecutable *exec) { static TypeTableEntry *ir_analyze_instruction_error_return_trace(IrAnalyze *ira, IrInstructionErrorReturnTrace *instruction) { - if (instruction->nullable == IrInstructionErrorReturnTrace::Null) { + if (instruction->optional == IrInstructionErrorReturnTrace::Null) { TypeTableEntry *ptr_to_stack_trace_type = get_ptr_to_stack_trace_type(ira->codegen); - TypeTableEntry *nullable_type = get_maybe_type(ira->codegen, ptr_to_stack_trace_type); + TypeTableEntry *optional_type = get_maybe_type(ira->codegen, ptr_to_stack_trace_type); if (!exec_has_err_ret_trace(ira->codegen, ira->new_irb.exec)) { ConstExprValue *out_val = ir_build_const_from(ira, &instruction->base); - assert(get_codegen_ptr_type(nullable_type) != nullptr); + assert(get_codegen_ptr_type(optional_type) != nullptr); out_val->data.x_ptr.special = ConstPtrSpecialHardCodedAddr; out_val->data.x_ptr.data.hard_coded_addr.addr = 0; - return nullable_type; + return optional_type; } IrInstruction *new_instruction = ir_build_error_return_trace(&ira->new_irb, instruction->base.scope, - instruction->base.source_node, instruction->nullable); + instruction->base.source_node, instruction->optional); ir_link_new_instruction(new_instruction, &instruction->base); - return nullable_type; + return optional_type; } else { assert(ira->codegen->have_err_ret_tracing); IrInstruction *new_instruction = ir_build_error_return_trace(&ira->new_irb, instruction->base.scope, - instruction->base.source_node, instruction->nullable); + instruction->base.source_node, instruction->optional); ir_link_new_instruction(new_instruction, &instruction->base); return get_ptr_to_stack_trace_type(ira->codegen); } @@ -12998,7 +12998,7 @@ static TypeTableEntry *ir_analyze_maybe(IrAnalyze *ira, IrInstructionUnOp *un_op case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdEnum: @@ -13017,7 +13017,7 @@ static TypeTableEntry *ir_analyze_maybe(IrAnalyze *ira, IrInstructionUnOp *un_op case TypeTableEntryIdUnreachable: case TypeTableEntryIdOpaque: ir_add_error_node(ira, un_op_instruction->base.source_node, - buf_sprintf("type '%s' not nullable", buf_ptr(&type_entry->name))); + buf_sprintf("type '%s' not optional", buf_ptr(&type_entry->name))); return ira->codegen->builtin_types.entry_invalid; } zig_unreachable(); @@ -13109,7 +13109,7 @@ static TypeTableEntry *ir_analyze_instruction_un_op(IrAnalyze *ira, IrInstructio return ir_analyze_negation(ira, un_op_instruction); case IrUnOpDereference: return ir_analyze_dereference(ira, un_op_instruction); - case IrUnOpMaybe: + case IrUnOpOptional: return ir_analyze_maybe(ira, un_op_instruction); } zig_unreachable(); @@ -14155,7 +14155,7 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru buf_ptr(&child_type->name), buf_ptr(field_name))); return ira->codegen->builtin_types.entry_invalid; } - } else if (child_type->id == TypeTableEntryIdMaybe) { + } else if (child_type->id == TypeTableEntryIdOptional) { if (buf_eql_str(field_name, "Child")) { bool ptr_is_const = true; bool ptr_is_volatile = false; @@ -14339,7 +14339,7 @@ static TypeTableEntry *ir_analyze_instruction_typeof(IrAnalyze *ira, IrInstructi case TypeTableEntryIdPointer: case TypeTableEntryIdArray: case TypeTableEntryIdStruct: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdEnum: @@ -14607,7 +14607,7 @@ static TypeTableEntry *ir_analyze_instruction_slice_type(IrAnalyze *ira, case TypeTableEntryIdStruct: case TypeTableEntryIdComptimeFloat: case TypeTableEntryIdComptimeInt: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdEnum: @@ -14715,7 +14715,7 @@ static TypeTableEntry *ir_analyze_instruction_array_type(IrAnalyze *ira, case TypeTableEntryIdStruct: case TypeTableEntryIdComptimeFloat: case TypeTableEntryIdComptimeInt: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdEnum: @@ -14786,7 +14786,7 @@ static TypeTableEntry *ir_analyze_instruction_size_of(IrAnalyze *ira, case TypeTableEntryIdPointer: case TypeTableEntryIdArray: case TypeTableEntryIdStruct: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdEnum: @@ -14810,14 +14810,14 @@ static TypeTableEntry *ir_analyze_instruction_test_non_null(IrAnalyze *ira, IrIn TypeTableEntry *type_entry = value->value.type; - if (type_entry->id == TypeTableEntryIdMaybe) { + if (type_entry->id == TypeTableEntryIdOptional) { if (instr_is_comptime(value)) { ConstExprValue *maybe_val = ir_resolve_const(ira, value, UndefBad); if (!maybe_val) return ira->codegen->builtin_types.entry_invalid; ConstExprValue *out_val = ir_build_const_from(ira, &instruction->base); - out_val->data.x_bool = !nullable_value_is_null(maybe_val); + out_val->data.x_bool = !optional_value_is_null(maybe_val); return ira->codegen->builtin_types.entry_bool; } @@ -14835,7 +14835,7 @@ static TypeTableEntry *ir_analyze_instruction_test_non_null(IrAnalyze *ira, IrIn } static TypeTableEntry *ir_analyze_instruction_unwrap_maybe(IrAnalyze *ira, - IrInstructionUnwrapMaybe *unwrap_maybe_instruction) + IrInstructionUnwrapOptional *unwrap_maybe_instruction) { IrInstruction *value = unwrap_maybe_instruction->value->other; if (type_is_invalid(value->value.type)) @@ -14863,9 +14863,9 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_maybe(IrAnalyze *ira, ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile); ir_link_new_instruction(result_instr, &unwrap_maybe_instruction->base); return result_instr->value.type; - } else if (type_entry->id != TypeTableEntryIdMaybe) { + } else if (type_entry->id != TypeTableEntryIdOptional) { ir_add_error_node(ira, unwrap_maybe_instruction->value->source_node, - buf_sprintf("expected nullable type, found '%s'", buf_ptr(&type_entry->name))); + buf_sprintf("expected optional type, found '%s'", buf_ptr(&type_entry->name))); return ira->codegen->builtin_types.entry_invalid; } TypeTableEntry *child_type = type_entry->data.maybe.child_type; @@ -14881,7 +14881,7 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_maybe(IrAnalyze *ira, ConstExprValue *maybe_val = const_ptr_pointee(ira->codegen, val); if (val->data.x_ptr.mut != ConstPtrMutRuntimeVar) { - if (nullable_value_is_null(maybe_val)) { + if (optional_value_is_null(maybe_val)) { ir_add_error(ira, &unwrap_maybe_instruction->base, buf_sprintf("unable to unwrap null")); return ira->codegen->builtin_types.entry_invalid; } @@ -14891,7 +14891,7 @@ static TypeTableEntry *ir_analyze_instruction_unwrap_maybe(IrAnalyze *ira, if (type_is_codegen_pointer(child_type)) { out_val->data.x_ptr.data.ref.pointee = maybe_val; } else { - out_val->data.x_ptr.data.ref.pointee = maybe_val->data.x_nullable; + out_val->data.x_ptr.data.ref.pointee = maybe_val->data.x_optional; } return result_type; } @@ -15216,7 +15216,7 @@ static TypeTableEntry *ir_analyze_instruction_switch_target(IrAnalyze *ira, case TypeTableEntryIdStruct: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdBlock: case TypeTableEntryIdBoundFn: case TypeTableEntryIdArgTuple: @@ -15737,7 +15737,7 @@ static TypeTableEntry *ir_analyze_min_max(IrAnalyze *ira, IrInstruction *source_ case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefined: case TypeTableEntryIdNull: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdUnion: @@ -16255,11 +16255,11 @@ static bool ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop 0, 0); fn_def_fields[6].type = get_maybe_type(ira->codegen, get_slice_type(ira->codegen, u8_ptr)); if (fn_node->is_extern && buf_len(fn_node->lib_name) > 0) { - fn_def_fields[6].data.x_nullable = create_const_vals(1); + fn_def_fields[6].data.x_optional = create_const_vals(1); ConstExprValue *lib_name = create_const_str_lit(ira->codegen, fn_node->lib_name); - init_const_slice(ira->codegen, fn_def_fields[6].data.x_nullable, lib_name, 0, buf_len(fn_node->lib_name), true); + init_const_slice(ira->codegen, fn_def_fields[6].data.x_optional, lib_name, 0, buf_len(fn_node->lib_name), true); } else { - fn_def_fields[6].data.x_nullable = nullptr; + fn_def_fields[6].data.x_optional = nullptr; } // return_type: type ensure_field_index(fn_def_val->type, "return_type", 7); @@ -16507,11 +16507,11 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t break; } - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: { result = create_const_vals(1); result->special = ConstValSpecialStatic; - result->type = ir_type_info_get_type(ira, "Nullable"); + result->type = ir_type_info_get_type(ira, "Optional"); ConstExprValue *fields = create_const_vals(1); result->data.x_struct.fields = fields; @@ -16725,10 +16725,10 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t inner_fields[1].type = get_maybe_type(ira->codegen, type_info_enum_field_type); if (fields[1].data.x_type == ira->codegen->builtin_types.entry_undef) { - inner_fields[1].data.x_nullable = nullptr; + inner_fields[1].data.x_optional = nullptr; } else { - inner_fields[1].data.x_nullable = create_const_vals(1); - make_enum_field_val(inner_fields[1].data.x_nullable, union_field->enum_field, type_info_enum_field_type); + inner_fields[1].data.x_optional = create_const_vals(1); + make_enum_field_val(inner_fields[1].data.x_optional, union_field->enum_field, type_info_enum_field_type); } inner_fields[2].special = ConstValSpecialStatic; @@ -16796,13 +16796,13 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t inner_fields[1].type = get_maybe_type(ira->codegen, ira->codegen->builtin_types.entry_usize); if (!type_has_bits(struct_field->type_entry)) { - inner_fields[1].data.x_nullable = nullptr; + inner_fields[1].data.x_optional = nullptr; } else { size_t byte_offset = LLVMOffsetOfElement(ira->codegen->target_data_ref, type_entry->type_ref, struct_field->gen_index); - inner_fields[1].data.x_nullable = create_const_vals(1); - inner_fields[1].data.x_nullable->special = ConstValSpecialStatic; - inner_fields[1].data.x_nullable->type = ira->codegen->builtin_types.entry_usize; - bigint_init_unsigned(&inner_fields[1].data.x_nullable->data.x_bigint, byte_offset); + inner_fields[1].data.x_optional = create_const_vals(1); + inner_fields[1].data.x_optional->special = ConstValSpecialStatic; + inner_fields[1].data.x_optional->type = ira->codegen->builtin_types.entry_usize; + bigint_init_unsigned(&inner_fields[1].data.x_optional->data.x_bigint, byte_offset); } inner_fields[2].special = ConstValSpecialStatic; @@ -18027,7 +18027,7 @@ static TypeTableEntry *ir_analyze_instruction_align_of(IrAnalyze *ira, IrInstruc case TypeTableEntryIdPromise: case TypeTableEntryIdArray: case TypeTableEntryIdStruct: - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: case TypeTableEntryIdEnum: @@ -18591,7 +18591,7 @@ static IrInstruction *ir_align_cast(IrAnalyze *ira, IrInstruction *target, uint3 old_align_bytes = fn_type_id.alignment; fn_type_id.alignment = align_bytes; result_type = get_fn_type(ira->codegen, &fn_type_id); - } else if (target_type->id == TypeTableEntryIdMaybe && + } else if (target_type->id == TypeTableEntryIdOptional && target_type->data.maybe.child_type->id == TypeTableEntryIdPointer) { TypeTableEntry *ptr_type = target_type->data.maybe.child_type; @@ -18599,7 +18599,7 @@ static IrInstruction *ir_align_cast(IrAnalyze *ira, IrInstruction *target, uint3 TypeTableEntry *better_ptr_type = adjust_ptr_align(ira->codegen, ptr_type, align_bytes); result_type = get_maybe_type(ira->codegen, better_ptr_type); - } else if (target_type->id == TypeTableEntryIdMaybe && + } else if (target_type->id == TypeTableEntryIdOptional && target_type->data.maybe.child_type->id == TypeTableEntryIdFn) { FnTypeId fn_type_id = target_type->data.maybe.child_type->data.fn.fn_type_id; @@ -18757,7 +18757,7 @@ static void buf_write_value_bytes(CodeGen *codegen, uint8_t *buf, ConstExprValue return; case TypeTableEntryIdStruct: zig_panic("TODO buf_write_value_bytes struct type"); - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: zig_panic("TODO buf_write_value_bytes maybe type"); case TypeTableEntryIdErrorUnion: zig_panic("TODO buf_write_value_bytes error union"); @@ -18815,7 +18815,7 @@ static void buf_read_value_bytes(CodeGen *codegen, uint8_t *buf, ConstExprValue zig_panic("TODO buf_read_value_bytes array type"); case TypeTableEntryIdStruct: zig_panic("TODO buf_read_value_bytes struct type"); - case TypeTableEntryIdMaybe: + case TypeTableEntryIdOptional: zig_panic("TODO buf_read_value_bytes maybe type"); case TypeTableEntryIdErrorUnion: zig_panic("TODO buf_read_value_bytes error union"); @@ -19731,7 +19731,7 @@ static TypeTableEntry *ir_analyze_instruction_nocast(IrAnalyze *ira, IrInstructi case IrInstructionIdUnionInit: case IrInstructionIdStructFieldPtr: case IrInstructionIdUnionFieldPtr: - case IrInstructionIdMaybeWrap: + case IrInstructionIdOptionalWrap: case IrInstructionIdErrWrapCode: case IrInstructionIdErrWrapPayload: case IrInstructionIdCast: @@ -19791,8 +19791,8 @@ static TypeTableEntry *ir_analyze_instruction_nocast(IrAnalyze *ira, IrInstructi return ir_analyze_instruction_size_of(ira, (IrInstructionSizeOf *)instruction); case IrInstructionIdTestNonNull: return ir_analyze_instruction_test_non_null(ira, (IrInstructionTestNonNull *)instruction); - case IrInstructionIdUnwrapMaybe: - return ir_analyze_instruction_unwrap_maybe(ira, (IrInstructionUnwrapMaybe *)instruction); + case IrInstructionIdUnwrapOptional: + return ir_analyze_instruction_unwrap_maybe(ira, (IrInstructionUnwrapOptional *)instruction); case IrInstructionIdClz: return ir_analyze_instruction_clz(ira, (IrInstructionClz *)instruction); case IrInstructionIdCtz: @@ -20128,7 +20128,7 @@ bool ir_has_side_effects(IrInstruction *instruction) { case IrInstructionIdSliceType: case IrInstructionIdSizeOf: case IrInstructionIdTestNonNull: - case IrInstructionIdUnwrapMaybe: + case IrInstructionIdUnwrapOptional: case IrInstructionIdClz: case IrInstructionIdCtz: case IrInstructionIdSwitchVar: @@ -20150,7 +20150,7 @@ bool ir_has_side_effects(IrInstruction *instruction) { case IrInstructionIdFrameAddress: case IrInstructionIdTestErr: case IrInstructionIdUnwrapErrCode: - case IrInstructionIdMaybeWrap: + case IrInstructionIdOptionalWrap: case IrInstructionIdErrWrapCode: case IrInstructionIdErrWrapPayload: case IrInstructionIdFnProto: diff --git a/src/ir_print.cpp b/src/ir_print.cpp index 776ef64566..43907fa9d4 100644 --- a/src/ir_print.cpp +++ b/src/ir_print.cpp @@ -148,7 +148,7 @@ static const char *ir_un_op_id_str(IrUnOp op_id) { return "-%"; case IrUnOpDereference: return "*"; - case IrUnOpMaybe: + case IrUnOpOptional: return "?"; } zig_unreachable(); @@ -481,7 +481,7 @@ static void ir_print_test_null(IrPrint *irp, IrInstructionTestNonNull *instructi fprintf(irp->f, " != null"); } -static void ir_print_unwrap_maybe(IrPrint *irp, IrInstructionUnwrapMaybe *instruction) { +static void ir_print_unwrap_maybe(IrPrint *irp, IrInstructionUnwrapOptional *instruction) { fprintf(irp->f, "&??*"); ir_print_other_instruction(irp, instruction->value); if (!instruction->safety_check_on) { @@ -777,7 +777,7 @@ static void ir_print_unwrap_err_payload(IrPrint *irp, IrInstructionUnwrapErrPayl } } -static void ir_print_maybe_wrap(IrPrint *irp, IrInstructionMaybeWrap *instruction) { +static void ir_print_maybe_wrap(IrPrint *irp, IrInstructionOptionalWrap *instruction) { fprintf(irp->f, "@maybeWrap("); ir_print_other_instruction(irp, instruction->value); fprintf(irp->f, ")"); @@ -1032,7 +1032,7 @@ static void ir_print_export(IrPrint *irp, IrInstructionExport *instruction) { static void ir_print_error_return_trace(IrPrint *irp, IrInstructionErrorReturnTrace *instruction) { fprintf(irp->f, "@errorReturnTrace("); - switch (instruction->nullable) { + switch (instruction->optional) { case IrInstructionErrorReturnTrace::Null: fprintf(irp->f, "Null"); break; @@ -1348,8 +1348,8 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) { case IrInstructionIdTestNonNull: ir_print_test_null(irp, (IrInstructionTestNonNull *)instruction); break; - case IrInstructionIdUnwrapMaybe: - ir_print_unwrap_maybe(irp, (IrInstructionUnwrapMaybe *)instruction); + case IrInstructionIdUnwrapOptional: + ir_print_unwrap_maybe(irp, (IrInstructionUnwrapOptional *)instruction); break; case IrInstructionIdCtz: ir_print_ctz(irp, (IrInstructionCtz *)instruction); @@ -1465,8 +1465,8 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) { case IrInstructionIdUnwrapErrPayload: ir_print_unwrap_err_payload(irp, (IrInstructionUnwrapErrPayload *)instruction); break; - case IrInstructionIdMaybeWrap: - ir_print_maybe_wrap(irp, (IrInstructionMaybeWrap *)instruction); + case IrInstructionIdOptionalWrap: + ir_print_maybe_wrap(irp, (IrInstructionOptionalWrap *)instruction); break; case IrInstructionIdErrWrapCode: ir_print_err_wrap_code(irp, (IrInstructionErrWrapCode *)instruction); diff --git a/src/parser.cpp b/src/parser.cpp index 3ad2de906b..2ee69f81ab 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -1046,12 +1046,11 @@ static AstNode *ast_parse_fn_proto_partial(ParseContext *pc, size_t *token_index } /* -SuffixOpExpression = ("async" option("<" SuffixOpExpression ">") SuffixOpExpression FnCallExpression) | PrimaryExpression option(FnCallExpression | ArrayAccessExpression | FieldAccessExpression | PtrDerefExpression | SliceExpression) +SuffixOpExpression = ("async" option("<" SuffixOpExpression ">") SuffixOpExpression FnCallExpression) | PrimaryExpression option(FnCallExpression | ArrayAccessExpression | FieldAccessExpression | SliceExpression | ".*" | ".?") FnCallExpression : token(LParen) list(Expression, token(Comma)) token(RParen) ArrayAccessExpression : token(LBracket) Expression token(RBracket) SliceExpression = "[" Expression ".." option(Expression) "]" FieldAccessExpression : token(Dot) token(Symbol) -PtrDerefExpression = ".*" StructLiteralField : token(Dot) token(Symbol) token(Eq) Expression */ static AstNode *ast_parse_suffix_op_expr(ParseContext *pc, size_t *token_index, bool mandatory) { @@ -1148,6 +1147,14 @@ static AstNode *ast_parse_suffix_op_expr(ParseContext *pc, size_t *token_index, AstNode *node = ast_create_node(pc, NodeTypePtrDeref, first_token); node->data.ptr_deref_expr.target = primary_expr; + primary_expr = node; + } else if (token->id == TokenIdQuestion) { + *token_index += 1; + + AstNode *node = ast_create_node(pc, NodeTypePrefixOpExpr, first_token); + node->data.prefix_op_expr.prefix_op = PrefixOpUnwrapOptional; + node->data.prefix_op_expr.primary_expr = primary_expr; + primary_expr = node; } else { ast_invalid_token_error(pc, token); @@ -1165,8 +1172,8 @@ static PrefixOp tok_to_prefix_op(Token *token) { case TokenIdDash: return PrefixOpNegation; case TokenIdMinusPercent: return PrefixOpNegationWrap; case TokenIdTilde: return PrefixOpBinNot; - case TokenIdMaybe: return PrefixOpMaybe; - case TokenIdDoubleQuestion: return PrefixOpUnwrapMaybe; + case TokenIdQuestion: return PrefixOpOptional; + case TokenIdDoubleQuestion: return PrefixOpUnwrapOptional; case TokenIdAmpersand: return PrefixOpAddrOf; default: return PrefixOpInvalid; } @@ -2304,8 +2311,8 @@ static BinOpType ast_parse_ass_op(ParseContext *pc, size_t *token_index, bool ma } /* -UnwrapExpression : BoolOrExpression (UnwrapMaybe | UnwrapError) | BoolOrExpression -UnwrapMaybe : "??" BoolOrExpression +UnwrapExpression : BoolOrExpression (UnwrapOptional | UnwrapError) | BoolOrExpression +UnwrapOptional : "??" BoolOrExpression UnwrapError = "catch" option("|" Symbol "|") Expression */ static AstNode *ast_parse_unwrap_expr(ParseContext *pc, size_t *token_index, bool mandatory) { @@ -2322,7 +2329,7 @@ static AstNode *ast_parse_unwrap_expr(ParseContext *pc, size_t *token_index, boo AstNode *node = ast_create_node(pc, NodeTypeBinOpExpr, token); node->data.bin_op_expr.op1 = lhs; - node->data.bin_op_expr.bin_op = BinOpTypeUnwrapMaybe; + node->data.bin_op_expr.bin_op = BinOpTypeUnwrapOptional; node->data.bin_op_expr.op2 = rhs; return node; diff --git a/src/tokenizer.cpp b/src/tokenizer.cpp index badbd695ec..cfabdf11ad 100644 --- a/src/tokenizer.cpp +++ b/src/tokenizer.cpp @@ -625,7 +625,7 @@ void tokenize(Buf *buf, Tokenization *out) { t.state = TokenizeStateSawDot; break; case '?': - begin_token(&t, TokenIdMaybe); + begin_token(&t, TokenIdQuestion); t.state = TokenizeStateSawQuestionMark; break; default: @@ -639,11 +639,6 @@ void tokenize(Buf *buf, Tokenization *out) { end_token(&t); t.state = TokenizeStateStart; break; - case '=': - set_token_id(&t, t.cur_tok, TokenIdMaybeAssign); - end_token(&t); - t.state = TokenizeStateStart; - break; default: t.pos -= 1; end_token(&t); @@ -1609,8 +1604,7 @@ const char * token_name(TokenId id) { case TokenIdLBrace: return "{"; case TokenIdLBracket: return "["; case TokenIdLParen: return "("; - case TokenIdMaybe: return "?"; - case TokenIdMaybeAssign: return "?="; + case TokenIdQuestion: return "?"; case TokenIdMinusEq: return "-="; case TokenIdMinusPercent: return "-%"; case TokenIdMinusPercentEq: return "-%="; diff --git a/src/tokenizer.hpp b/src/tokenizer.hpp index d0089909cd..7c617f85c6 100644 --- a/src/tokenizer.hpp +++ b/src/tokenizer.hpp @@ -100,8 +100,7 @@ enum TokenId { TokenIdLBrace, TokenIdLBracket, TokenIdLParen, - TokenIdMaybe, - TokenIdMaybeAssign, + TokenIdQuestion, TokenIdMinusEq, TokenIdMinusPercent, TokenIdMinusPercentEq, diff --git a/src/translate_c.cpp b/src/translate_c.cpp index d78bd1fa70..aaaf5a1edb 100644 --- a/src/translate_c.cpp +++ b/src/translate_c.cpp @@ -382,7 +382,7 @@ static AstNode *trans_create_node_inline_fn(Context *c, Buf *fn_name, AstNode *r fn_def->data.fn_def.fn_proto = fn_proto; fn_proto->data.fn_proto.fn_def_node = fn_def; - AstNode *unwrap_node = trans_create_node_prefix_op(c, PrefixOpUnwrapMaybe, ref_node); + AstNode *unwrap_node = trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, ref_node); AstNode *fn_call_node = trans_create_node(c, NodeTypeFnCallExpr); fn_call_node->data.fn_call_expr.fn_ref_expr = unwrap_node; @@ -410,7 +410,7 @@ static AstNode *trans_create_node_inline_fn(Context *c, Buf *fn_name, AstNode *r } static AstNode *trans_create_node_unwrap_null(Context *c, AstNode *child) { - return trans_create_node_prefix_op(c, PrefixOpUnwrapMaybe, child); + return trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, child); } static AstNode *get_global(Context *c, Buf *name) { @@ -879,14 +879,14 @@ static AstNode *trans_type(Context *c, const Type *ty, const SourceLocation &sou } if (qual_type_child_is_fn_proto(child_qt)) { - return trans_create_node_prefix_op(c, PrefixOpMaybe, child_node); + return trans_create_node_prefix_op(c, PrefixOpOptional, child_node); } PtrLen ptr_len = type_is_opaque(c, child_qt.getTypePtr(), source_loc) ? PtrLenSingle : PtrLenUnknown; AstNode *pointer_node = trans_create_node_ptr_type(c, child_qt.isConstQualified(), child_qt.isVolatileQualified(), child_node, ptr_len); - return trans_create_node_prefix_op(c, PrefixOpMaybe, pointer_node); + return trans_create_node_prefix_op(c, PrefixOpOptional, pointer_node); } case Type::Typedef: { @@ -1963,7 +1963,7 @@ static AstNode *trans_unary_operator(Context *c, ResultUsed result_used, TransSc bool is_fn_ptr = qual_type_is_fn_ptr(stmt->getSubExpr()->getType()); if (is_fn_ptr) return value_node; - AstNode *unwrapped = trans_create_node_prefix_op(c, PrefixOpUnwrapMaybe, value_node); + AstNode *unwrapped = trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, value_node); return trans_create_node_ptr_deref(c, unwrapped); } case UO_Plus: @@ -2587,7 +2587,7 @@ static AstNode *trans_call_expr(Context *c, ResultUsed result_used, TransScope * } } if (callee_node == nullptr) { - callee_node = trans_create_node_prefix_op(c, PrefixOpUnwrapMaybe, callee_raw_node); + callee_node = trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, callee_raw_node); } } else { callee_node = callee_raw_node; @@ -4301,7 +4301,7 @@ static AstNode *trans_lookup_ast_maybe_fn(Context *c, AstNode *ref_node) { return nullptr; if (prefix_node->type != NodeTypePrefixOpExpr) return nullptr; - if (prefix_node->data.prefix_op_expr.prefix_op != PrefixOpMaybe) + if (prefix_node->data.prefix_op_expr.prefix_op != PrefixOpOptional) return nullptr; AstNode *fn_proto_node = prefix_node->data.prefix_op_expr.primary_expr; diff --git a/std/array_list.zig b/std/array_list.zig index 30715f4d6f..1a235d28a3 100644 --- a/std/array_list.zig +++ b/std/array_list.zig @@ -258,7 +258,7 @@ test "iterator ArrayList test" { } it.reset(); - assert(??it.next() == 1); + assert(it.next().? == 1); } test "insert ArrayList test" { diff --git a/std/buf_map.zig b/std/buf_map.zig index 22d821ae7b..0d4f3a6d5e 100644 --- a/std/buf_map.zig +++ b/std/buf_map.zig @@ -72,15 +72,15 @@ test "BufMap" { defer bufmap.deinit(); try bufmap.set("x", "1"); - assert(mem.eql(u8, ??bufmap.get("x"), "1")); + assert(mem.eql(u8, bufmap.get("x").?, "1")); assert(1 == bufmap.count()); try bufmap.set("x", "2"); - assert(mem.eql(u8, ??bufmap.get("x"), "2")); + assert(mem.eql(u8, bufmap.get("x").?, "2")); assert(1 == bufmap.count()); try bufmap.set("x", "3"); - assert(mem.eql(u8, ??bufmap.get("x"), "3")); + assert(mem.eql(u8, bufmap.get("x").?, "3")); assert(1 == bufmap.count()); bufmap.delete("x"); diff --git a/std/event.zig b/std/event.zig index 89ab816bb6..0821c789b7 100644 --- a/std/event.zig +++ b/std/event.zig @@ -40,9 +40,9 @@ pub const TcpServer = struct { self.listen_address = std.net.Address.initPosix(try std.os.posixGetSockName(self.sockfd)); self.accept_coro = try async TcpServer.handler(self); - errdefer cancel ??self.accept_coro; + errdefer cancel self.accept_coro.?; - try self.loop.addFd(self.sockfd, ??self.accept_coro); + try self.loop.addFd(self.sockfd, self.accept_coro.?); errdefer self.loop.removeFd(self.sockfd); } diff --git a/std/fmt/index.zig b/std/fmt/index.zig index 3844fbb10a..b52625e26e 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -111,7 +111,7 @@ pub fn formatType( builtin.TypeId.Bool => { return output(context, if (value) "true" else "false"); }, - builtin.TypeId.Nullable => { + builtin.TypeId.Optional => { if (value) |payload| { return formatType(payload, fmt, context, Errors, output); } else { @@ -819,11 +819,11 @@ test "parse unsigned comptime" { test "fmt.format" { { const value: ?i32 = 1234; - try testFmt("nullable: 1234\n", "nullable: {}\n", value); + try testFmt("optional: 1234\n", "optional: {}\n", value); } { const value: ?i32 = null; - try testFmt("nullable: null\n", "nullable: {}\n", value); + try testFmt("optional: null\n", "optional: {}\n", value); } { const value: error!i32 = 1234; diff --git a/std/hash_map.zig b/std/hash_map.zig index a323cdc197..3bd03d4f28 100644 --- a/std/hash_map.zig +++ b/std/hash_map.zig @@ -265,11 +265,11 @@ test "basic hash map usage" { assert((map.put(4, 44) catch unreachable) == null); assert((map.put(5, 55) catch unreachable) == null); - assert(??(map.put(5, 66) catch unreachable) == 55); - assert(??(map.put(5, 55) catch unreachable) == 66); + assert((map.put(5, 66) catch unreachable).? == 55); + assert((map.put(5, 55) catch unreachable).? == 66); assert(map.contains(2)); - assert((??map.get(2)).value == 22); + assert(map.get(2).?.value == 22); _ = map.remove(2); assert(map.remove(2) == null); assert(map.get(2) == null); @@ -317,7 +317,7 @@ test "iterator hash map" { } it.reset(); - var entry = ??it.next(); + var entry = it.next().?; assert(entry.key == keys[0]); assert(entry.value == values[0]); } diff --git a/std/heap.zig b/std/heap.zig index 5d430bc761..d1fbf9ca0a 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -142,7 +142,7 @@ pub const DirectAllocator = struct { const root_addr = @intToPtr(*align(1) usize, old_record_addr).*; const old_ptr = @intToPtr(*c_void, root_addr); const amt = new_size + alignment + @sizeOf(usize); - const new_ptr = os.windows.HeapReAlloc(??self.heap_handle, 0, old_ptr, amt) ?? blk: { + const new_ptr = os.windows.HeapReAlloc(self.heap_handle.?, 0, old_ptr, amt) ?? blk: { if (new_size > old_mem.len) return error.OutOfMemory; const new_record_addr = old_record_addr - new_size + old_mem.len; @intToPtr(*align(1) usize, new_record_addr).* = root_addr; @@ -171,7 +171,7 @@ pub const DirectAllocator = struct { const record_addr = @ptrToInt(bytes.ptr) + bytes.len; const root_addr = @intToPtr(*align(1) usize, record_addr).*; const ptr = @intToPtr(*c_void, root_addr); - _ = os.windows.HeapFree(??self.heap_handle, 0, ptr); + _ = os.windows.HeapFree(self.heap_handle.?, 0, ptr); }, else => @compileError("Unsupported OS"), } diff --git a/std/json.zig b/std/json.zig index 03b19a7fa4..75ea2eee1c 100644 --- a/std/json.zig +++ b/std/json.zig @@ -908,7 +908,7 @@ pub const TokenStream = struct { }; fn checkNext(p: *TokenStream, id: Token.Id) void { - const token = ??(p.next() catch unreachable); + const token = (p.next() catch unreachable).?; debug.assert(token.id == id); } @@ -1376,17 +1376,17 @@ test "json parser dynamic" { var root = tree.root; - var image = (??root.Object.get("Image")).value; + var image = root.Object.get("Image").?.value; - const width = (??image.Object.get("Width")).value; + const width = image.Object.get("Width").?.value; debug.assert(width.Integer == 800); - const height = (??image.Object.get("Height")).value; + const height = image.Object.get("Height").?.value; debug.assert(height.Integer == 600); - const title = (??image.Object.get("Title")).value; + const title = image.Object.get("Title").?.value; debug.assert(mem.eql(u8, title.String, "View from 15th Floor")); - const animated = (??image.Object.get("Animated")).value; + const animated = image.Object.get("Animated").?.value; debug.assert(animated.Bool == false); } diff --git a/std/linked_list.zig b/std/linked_list.zig index fbc0a0c42a..536c6d24d0 100644 --- a/std/linked_list.zig +++ b/std/linked_list.zig @@ -270,8 +270,8 @@ test "basic linked list test" { var last = list.pop(); // {2, 3, 4} list.remove(three); // {2, 4} - assert((??list.first).data == 2); - assert((??list.last).data == 4); + assert(list.first.?.data == 2); + assert(list.last.?.data == 4); assert(list.len == 2); } @@ -336,7 +336,7 @@ test "basic intrusive linked list test" { var last = list.pop(); // {2, 3, 4} list.remove(&three.link); // {2, 4} - assert((??list.first).toData().value == 2); - assert((??list.last).toData().value == 4); + assert(list.first.?.toData().value == 2); + assert(list.last.?.toData().value == 4); assert(list.len == 2); } diff --git a/std/macho.zig b/std/macho.zig index d6eef9a325..64f78ae4a3 100644 --- a/std/macho.zig +++ b/std/macho.zig @@ -130,7 +130,7 @@ pub fn loadSymbols(allocator: *mem.Allocator, in: *io.FileInStream) !SymbolTable for (syms) |sym| { if (!isSymbol(sym)) continue; const start = sym.n_strx; - const end = ??mem.indexOfScalarPos(u8, strings, start, 0); + const end = mem.indexOfScalarPos(u8, strings, start, 0).?; const name = strings[start..end]; const address = sym.n_value; symbols[nsym] = Symbol{ .name = name, .address = address }; diff --git a/std/mem.zig b/std/mem.zig index 423460e73b..f961c7862b 100644 --- a/std/mem.zig +++ b/std/mem.zig @@ -304,20 +304,20 @@ pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, nee } test "mem.indexOf" { - assert(??indexOf(u8, "one two three four", "four") == 14); - assert(??lastIndexOf(u8, "one two three two four", "two") == 14); + assert(indexOf(u8, "one two three four", "four").? == 14); + assert(lastIndexOf(u8, "one two three two four", "two").? == 14); assert(indexOf(u8, "one two three four", "gour") == null); assert(lastIndexOf(u8, "one two three four", "gour") == null); - assert(??indexOf(u8, "foo", "foo") == 0); - assert(??lastIndexOf(u8, "foo", "foo") == 0); + assert(indexOf(u8, "foo", "foo").? == 0); + assert(lastIndexOf(u8, "foo", "foo").? == 0); assert(indexOf(u8, "foo", "fool") == null); assert(lastIndexOf(u8, "foo", "lfoo") == null); assert(lastIndexOf(u8, "foo", "fool") == null); - assert(??indexOf(u8, "foo foo", "foo") == 0); - assert(??lastIndexOf(u8, "foo foo", "foo") == 4); - assert(??lastIndexOfAny(u8, "boo, cat", "abo") == 6); - assert(??lastIndexOfScalar(u8, "boo", 'o') == 2); + assert(indexOf(u8, "foo foo", "foo").? == 0); + assert(lastIndexOf(u8, "foo foo", "foo").? == 4); + assert(lastIndexOfAny(u8, "boo, cat", "abo").? == 6); + assert(lastIndexOfScalar(u8, "boo", 'o').? == 2); } /// Reads an integer from memory with size equal to bytes.len. @@ -432,9 +432,9 @@ pub fn split(buffer: []const u8, split_bytes: []const u8) SplitIterator { test "mem.split" { var it = split(" abc def ghi ", " "); - assert(eql(u8, ??it.next(), "abc")); - assert(eql(u8, ??it.next(), "def")); - assert(eql(u8, ??it.next(), "ghi")); + assert(eql(u8, it.next().?, "abc")); + assert(eql(u8, it.next().?, "def")); + assert(eql(u8, it.next().?, "ghi")); assert(it.next() == null); } diff --git a/std/os/child_process.zig b/std/os/child_process.zig index 822ade2eb8..1e3a732498 100644 --- a/std/os/child_process.zig +++ b/std/os/child_process.zig @@ -156,7 +156,7 @@ pub const ChildProcess = struct { }; } try self.waitUnwrappedWindows(); - return ??self.term; + return self.term.?; } pub fn killPosix(self: *ChildProcess) !Term { @@ -175,7 +175,7 @@ pub const ChildProcess = struct { }; } self.waitUnwrapped(); - return ??self.term; + return self.term.?; } /// Blocks until child process terminates and then cleans up all resources. @@ -212,8 +212,8 @@ pub const ChildProcess = struct { defer Buffer.deinit(&stdout); defer Buffer.deinit(&stderr); - var stdout_file_in_stream = io.FileInStream.init(&??child.stdout); - var stderr_file_in_stream = io.FileInStream.init(&??child.stderr); + var stdout_file_in_stream = io.FileInStream.init(&child.stdout.?); + var stderr_file_in_stream = io.FileInStream.init(&child.stderr.?); try stdout_file_in_stream.stream.readAllBuffer(&stdout, max_output_size); try stderr_file_in_stream.stream.readAllBuffer(&stderr, max_output_size); @@ -232,7 +232,7 @@ pub const ChildProcess = struct { } try self.waitUnwrappedWindows(); - return ??self.term; + return self.term.?; } fn waitPosix(self: *ChildProcess) !Term { @@ -242,7 +242,7 @@ pub const ChildProcess = struct { } self.waitUnwrapped(); - return ??self.term; + return self.term.?; } pub fn deinit(self: *ChildProcess) void { @@ -619,13 +619,13 @@ pub const ChildProcess = struct { self.term = null; if (self.stdin_behavior == StdIo.Pipe) { - os.close(??g_hChildStd_IN_Rd); + os.close(g_hChildStd_IN_Rd.?); } if (self.stderr_behavior == StdIo.Pipe) { - os.close(??g_hChildStd_ERR_Wr); + os.close(g_hChildStd_ERR_Wr.?); } if (self.stdout_behavior == StdIo.Pipe) { - os.close(??g_hChildStd_OUT_Wr); + os.close(g_hChildStd_OUT_Wr.?); } } diff --git a/std/os/index.zig b/std/os/index.zig index fe5ecc38ba..807b2c398b 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -422,7 +422,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: *const BufMap, allocator: const exe_path = argv[0]; if (mem.indexOfScalar(u8, exe_path, '/') != null) { - return posixExecveErrnoToErr(posix.getErrno(posix.execve(??argv_buf[0], argv_buf.ptr, envp_buf.ptr))); + return posixExecveErrnoToErr(posix.getErrno(posix.execve(argv_buf[0].?, argv_buf.ptr, envp_buf.ptr))); } const PATH = getEnvPosix("PATH") ?? "/usr/local/bin:/bin/:/usr/bin"; @@ -1729,7 +1729,7 @@ test "windows arg parsing" { fn testWindowsCmdLine(input_cmd_line: [*]const u8, expected_args: []const []const u8) void { var it = ArgIteratorWindows.initWithCmdLine(input_cmd_line); for (expected_args) |expected_arg| { - const arg = ??it.next(debug.global_allocator) catch unreachable; + const arg = it.next(debug.global_allocator).? catch unreachable; assert(mem.eql(u8, arg, expected_arg)); } assert(it.next(debug.global_allocator) == null); diff --git a/std/os/linux/vdso.zig b/std/os/linux/vdso.zig index 2ab4d0cbc1..1414b8185b 100644 --- a/std/os/linux/vdso.zig +++ b/std/os/linux/vdso.zig @@ -67,7 +67,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { if (0 == syms[i].st_shndx) continue; if (!mem.eql(u8, name, cstr.toSliceConst(strings + syms[i].st_name))) continue; if (maybe_versym) |versym| { - if (!checkver(??maybe_verdef, versym[i], vername, strings)) + if (!checkver(maybe_verdef.?, versym[i], vername, strings)) continue; } return base + syms[i].st_value; diff --git a/std/os/path.zig b/std/os/path.zig index 4df6179bf5..430dda2934 100644 --- a/std/os/path.zig +++ b/std/os/path.zig @@ -265,7 +265,7 @@ fn networkShareServersEql(ns1: []const u8, ns2: []const u8) bool { var it2 = mem.split(ns2, []u8{sep2}); // TODO ASCII is wrong, we actually need full unicode support to compare paths. - return asciiEqlIgnoreCase(??it1.next(), ??it2.next()); + return asciiEqlIgnoreCase(it1.next().?, it2.next().?); } fn compareDiskDesignators(kind: WindowsPath.Kind, p1: []const u8, p2: []const u8) bool { @@ -286,7 +286,7 @@ fn compareDiskDesignators(kind: WindowsPath.Kind, p1: []const u8, p2: []const u8 var it2 = mem.split(p2, []u8{sep2}); // TODO ASCII is wrong, we actually need full unicode support to compare paths. - return asciiEqlIgnoreCase(??it1.next(), ??it2.next()) and asciiEqlIgnoreCase(??it1.next(), ??it2.next()); + return asciiEqlIgnoreCase(it1.next().?, it2.next().?) and asciiEqlIgnoreCase(it1.next().?, it2.next().?); }, } } @@ -414,8 +414,8 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 { WindowsPath.Kind.NetworkShare => { result = try allocator.alloc(u8, max_size); var it = mem.split(paths[first_index], "/\\"); - const server_name = ??it.next(); - const other_name = ??it.next(); + const server_name = it.next().?; + const other_name = it.next().?; result[result_index] = '\\'; result_index += 1; diff --git a/std/segmented_list.zig b/std/segmented_list.zig index a2f3607ad8..9f10f4d44a 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -364,7 +364,7 @@ fn testSegmentedList(comptime prealloc: usize, allocator: *Allocator) !void { assert(x == 0); } - assert(??list.pop() == 100); + assert(list.pop().? == 100); assert(list.len == 99); try list.pushMany([]i32{ @@ -373,9 +373,9 @@ fn testSegmentedList(comptime prealloc: usize, allocator: *Allocator) !void { 3, }); assert(list.len == 102); - assert(??list.pop() == 3); - assert(??list.pop() == 2); - assert(??list.pop() == 1); + assert(list.pop().? == 3); + assert(list.pop().? == 2); + assert(list.pop().? == 1); assert(list.len == 99); try list.pushMany([]const i32{}); diff --git a/std/special/bootstrap.zig b/std/special/bootstrap.zig index 8aefe4751f..dd37f1edb6 100644 --- a/std/special/bootstrap.zig +++ b/std/special/bootstrap.zig @@ -54,10 +54,10 @@ fn posixCallMainAndExit() noreturn { const argc = argc_ptr[0]; const argv = @ptrCast([*][*]u8, argc_ptr + 1); - const envp_nullable = @ptrCast([*]?[*]u8, argv + argc + 1); + const envp_optional = @ptrCast([*]?[*]u8, argv + argc + 1); var envp_count: usize = 0; - while (envp_nullable[envp_count]) |_| : (envp_count += 1) {} - const envp = @ptrCast([*][*]u8, envp_nullable)[0..envp_count]; + while (envp_optional[envp_count]) |_| : (envp_count += 1) {} + const envp = @ptrCast([*][*]u8, envp_optional)[0..envp_count]; if (builtin.os == builtin.Os.linux) { const auxv = @ptrCast([*]usize, envp.ptr + envp_count + 1); var i: usize = 0; diff --git a/std/special/builtin.zig b/std/special/builtin.zig index e537078924..e97b0a89e4 100644 --- a/std/special/builtin.zig +++ b/std/special/builtin.zig @@ -19,7 +19,7 @@ export fn memset(dest: ?[*]u8, c: u8, n: usize) ?[*]u8 { var index: usize = 0; while (index != n) : (index += 1) - (??dest)[index] = c; + dest.?[index] = c; return dest; } @@ -29,7 +29,7 @@ export fn memcpy(noalias dest: ?[*]u8, noalias src: ?[*]const u8, n: usize) ?[*] var index: usize = 0; while (index != n) : (index += 1) - (??dest)[index] = (??src)[index]; + dest.?[index] = src.?[index]; return dest; } @@ -40,13 +40,13 @@ export fn memmove(dest: ?[*]u8, src: ?[*]const u8, n: usize) ?[*]u8 { if (@ptrToInt(dest) < @ptrToInt(src)) { var index: usize = 0; while (index != n) : (index += 1) { - (??dest)[index] = (??src)[index]; + dest.?[index] = src.?[index]; } } else { var index = n; while (index != 0) { index -= 1; - (??dest)[index] = (??src)[index]; + dest.?[index] = src.?[index]; } } diff --git a/std/unicode.zig b/std/unicode.zig index 3d1bebdb55..21ae12f59c 100644 --- a/std/unicode.zig +++ b/std/unicode.zig @@ -286,15 +286,15 @@ fn testUtf8IteratorOnAscii() void { const s = Utf8View.initComptime("abc"); var it1 = s.iterator(); - debug.assert(std.mem.eql(u8, "a", ??it1.nextCodepointSlice())); - debug.assert(std.mem.eql(u8, "b", ??it1.nextCodepointSlice())); - debug.assert(std.mem.eql(u8, "c", ??it1.nextCodepointSlice())); + debug.assert(std.mem.eql(u8, "a", it1.nextCodepointSlice().?)); + debug.assert(std.mem.eql(u8, "b", it1.nextCodepointSlice().?)); + debug.assert(std.mem.eql(u8, "c", it1.nextCodepointSlice().?)); debug.assert(it1.nextCodepointSlice() == null); var it2 = s.iterator(); - debug.assert(??it2.nextCodepoint() == 'a'); - debug.assert(??it2.nextCodepoint() == 'b'); - debug.assert(??it2.nextCodepoint() == 'c'); + debug.assert(it2.nextCodepoint().? == 'a'); + debug.assert(it2.nextCodepoint().? == 'b'); + debug.assert(it2.nextCodepoint().? == 'c'); debug.assert(it2.nextCodepoint() == null); } @@ -321,15 +321,15 @@ fn testUtf8ViewOk() void { const s = Utf8View.initComptime("東京市"); var it1 = s.iterator(); - debug.assert(std.mem.eql(u8, "東", ??it1.nextCodepointSlice())); - debug.assert(std.mem.eql(u8, "京", ??it1.nextCodepointSlice())); - debug.assert(std.mem.eql(u8, "市", ??it1.nextCodepointSlice())); + debug.assert(std.mem.eql(u8, "東", it1.nextCodepointSlice().?)); + debug.assert(std.mem.eql(u8, "京", it1.nextCodepointSlice().?)); + debug.assert(std.mem.eql(u8, "市", it1.nextCodepointSlice().?)); debug.assert(it1.nextCodepointSlice() == null); var it2 = s.iterator(); - debug.assert(??it2.nextCodepoint() == 0x6771); - debug.assert(??it2.nextCodepoint() == 0x4eac); - debug.assert(??it2.nextCodepoint() == 0x5e02); + debug.assert(it2.nextCodepoint().? == 0x6771); + debug.assert(it2.nextCodepoint().? == 0x4eac); + debug.assert(it2.nextCodepoint().? == 0x5e02); debug.assert(it2.nextCodepoint() == null); } diff --git a/std/zig/ast.zig b/std/zig/ast.zig index a4b64d5db2..defaded78a 100644 --- a/std/zig/ast.zig +++ b/std/zig/ast.zig @@ -1417,7 +1417,7 @@ pub const Node = struct { Range, Sub, SubWrap, - UnwrapMaybe, + UnwrapOptional, }; pub fn iterate(self: *InfixOp, index: usize) ?*Node { @@ -1475,7 +1475,7 @@ pub const Node = struct { Op.Range, Op.Sub, Op.SubWrap, - Op.UnwrapMaybe, + Op.UnwrapOptional, => {}, } @@ -1507,14 +1507,13 @@ pub const Node = struct { BitNot, BoolNot, Cancel, - MaybeType, + OptionalType, Negation, NegationWrap, Resume, PtrType: PtrInfo, SliceType: PtrInfo, Try, - UnwrapMaybe, }; pub const PtrInfo = struct { @@ -1557,12 +1556,12 @@ pub const Node = struct { Op.BitNot, Op.BoolNot, Op.Cancel, - Op.MaybeType, + Op.OptionalType, Op.Negation, Op.NegationWrap, Op.Try, Op.Resume, - Op.UnwrapMaybe, + Op.UnwrapOptional, Op.PointerType, => {}, } @@ -1619,6 +1618,7 @@ pub const Node = struct { ArrayInitializer: InitList, StructInitializer: InitList, Deref, + UnwrapOptional, pub const InitList = SegmentedList(*Node, 2); diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 7faca8e11b..9f8ef3c3d6 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -711,7 +711,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { else => { // TODO: this is a special case. Remove this when #760 is fixed if (token_ptr.id == Token.Id.Keyword_error) { - if ((??tok_it.peek()).id == Token.Id.LBrace) { + if (tok_it.peek().?.id == Token.Id.LBrace) { const error_type_node = try arena.construct(ast.Node.ErrorType{ .base = ast.Node{ .id = ast.Node.Id.ErrorType }, .token = token_index, @@ -1434,8 +1434,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ .id = Token.Id.AngleBracketRight, - .ptr = &??async_node.rangle_bracket, - }, + .ptr = &async_node.rangle_bracket.? }, }); try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &async_node.allocator_type } }); continue; @@ -1567,7 +1566,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { .bit_range = null, }; // TODO https://github.com/ziglang/zig/issues/1022 - const align_info = &??addr_of_info.align_info; + const align_info = &addr_of_info.align_info.?; try stack.append(State{ .AlignBitRange = align_info }); try stack.append(State{ .Expression = OptionalCtx{ .Required = &align_info.node } }); @@ -1604,7 +1603,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { switch (token.ptr.id) { Token.Id.Colon => { align_info.bit_range = ast.Node.PrefixOp.PtrInfo.Align.BitRange(undefined); - const bit_range = &??align_info.bit_range; + const bit_range = &align_info.bit_range.?; try stack.append(State{ .ExpectToken = Token.Id.RParen }); try stack.append(State{ .Expression = OptionalCtx{ .Required = &bit_range.end } }); @@ -2144,7 +2143,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { State.CurlySuffixExpressionEnd => |opt_ctx| { const lhs = opt_ctx.get() ?? continue; - if ((??tok_it.peek()).id == Token.Id.Period) { + if (tok_it.peek().?.id == Token.Id.Period) { const node = try arena.construct(ast.Node.SuffixOp{ .base = ast.Node{ .id = ast.Node.Id.SuffixOp }, .lhs = lhs, @@ -2326,6 +2325,17 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; continue; } + if (eatToken(&tok_it, &tree, Token.Id.QuestionMark)) |question_token| { + const node = try arena.construct(ast.Node.SuffixOp{ + .base = ast.Node{ .id = ast.Node.Id.SuffixOp }, + .lhs = lhs, + .op = ast.Node.SuffixOp.Op.UnwrapOptional, + .rtoken = question_token, + }); + opt_ctx.store(&node.base); + stack.append(State{ .SuffixOpExpressionEnd = opt_ctx.toRequired() }) catch unreachable; + continue; + } const node = try arena.construct(ast.Node.InfixOp{ .base = ast.Node{ .id = ast.Node.Id.InfixOp }, .lhs = lhs, @@ -2403,7 +2413,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { .arrow_token = next_token_index, .return_type = undefined, }; - const return_type_ptr = &((??node.result).return_type); + const return_type_ptr = &node.result.?.return_type; try stack.append(State{ .Expression = OptionalCtx{ .Required = return_type_ptr } }); continue; }, @@ -2875,7 +2885,7 @@ const OptionalCtx = union(enum) { pub fn get(self: *const OptionalCtx) ?*ast.Node { switch (self.*) { OptionalCtx.Optional => |ptr| return ptr.*, - OptionalCtx.RequiredNull => |ptr| return ??ptr.*, + OptionalCtx.RequiredNull => |ptr| return ptr.*.?, OptionalCtx.Required => |ptr| return ptr.*, } } @@ -3237,7 +3247,7 @@ fn tokenIdToAssignment(id: *const Token.Id) ?ast.Node.InfixOp.Op { fn tokenIdToUnwrapExpr(id: @TagType(Token.Id)) ?ast.Node.InfixOp.Op { return switch (id) { Token.Id.Keyword_catch => ast.Node.InfixOp.Op{ .Catch = null }, - Token.Id.QuestionMarkQuestionMark => ast.Node.InfixOp.Op{ .UnwrapMaybe = void{} }, + Token.Id.QuestionMarkQuestionMark => ast.Node.InfixOp.Op{ .UnwrapOptional = void{} }, else => null, }; } @@ -3299,8 +3309,7 @@ fn tokenIdToPrefixOp(id: @TagType(Token.Id)) ?ast.Node.PrefixOp.Op { .volatile_token = null, }, }, - Token.Id.QuestionMark => ast.Node.PrefixOp.Op{ .MaybeType = void{} }, - Token.Id.QuestionMarkQuestionMark => ast.Node.PrefixOp.Op{ .UnwrapMaybe = void{} }, + Token.Id.QuestionMark => ast.Node.PrefixOp.Op{ .OptionalType = void{} }, Token.Id.Keyword_await => ast.Node.PrefixOp.Op{ .Await = void{} }, Token.Id.Keyword_try => ast.Node.PrefixOp.Op{ .Try = void{} }, else => null, @@ -3322,7 +3331,7 @@ fn createToCtxLiteral(arena: *mem.Allocator, opt_ctx: *const OptionalCtx, compti } fn eatToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree, id: @TagType(Token.Id)) ?TokenIndex { - const token = ??tok_it.peek(); + const token = tok_it.peek().?; if (token.id == id) { return nextToken(tok_it, tree).index; @@ -3334,7 +3343,7 @@ fn eatToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree, id: @TagType( fn nextToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) AnnotatedToken { const result = AnnotatedToken{ .index = tok_it.index, - .ptr = ??tok_it.next(), + .ptr = tok_it.next().?, }; assert(result.ptr.id != Token.Id.LineComment); diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 91a56de827..ea3a4858b0 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -650,9 +650,10 @@ test "zig fmt: statements with empty line between" { ); } -test "zig fmt: ptr deref operator" { +test "zig fmt: ptr deref operator and unwrap optional operator" { try testCanonical( \\const a = b.*; + \\const a = b.?; \\ ); } @@ -1209,7 +1210,7 @@ test "zig fmt: precedence" { test "zig fmt: prefix operators" { try testCanonical( \\test "prefix operators" { - \\ try return --%~??!*&0; + \\ try return --%~!*&0; \\} \\ ); diff --git a/std/zig/render.zig b/std/zig/render.zig index 7c9b53b77a..0b8e4d1453 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -222,7 +222,7 @@ fn renderTopLevelDecl(allocator: *mem.Allocator, stream: var, tree: *ast.Tree, i } } - const value_expr = ??tag.value_expr; + const value_expr = tag.value_expr.?; try renderToken(tree, stream, tree.prevToken(value_expr.firstToken()), indent, start_col, Space.Space); // = try renderExpression(allocator, stream, tree, indent, start_col, value_expr, Space.Comma); // value, }, @@ -465,8 +465,7 @@ fn renderExpression( ast.Node.PrefixOp.Op.BoolNot, ast.Node.PrefixOp.Op.Negation, ast.Node.PrefixOp.Op.NegationWrap, - ast.Node.PrefixOp.Op.UnwrapMaybe, - ast.Node.PrefixOp.Op.MaybeType, + ast.Node.PrefixOp.Op.OptionalType, ast.Node.PrefixOp.Op.AddressOf, => { try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.None); @@ -513,7 +512,7 @@ fn renderExpression( var it = call_info.params.iterator(0); while (true) { - const param_node = ??it.next(); + const param_node = it.next().?; const param_node_new_indent = if (param_node.*.id == ast.Node.Id.MultilineStringLiteral) blk: { break :blk indent; @@ -559,10 +558,10 @@ fn renderExpression( return renderToken(tree, stream, rbracket, indent, start_col, space); // ] }, - ast.Node.SuffixOp.Op.Deref => { + ast.Node.SuffixOp.Op.Deref, ast.Node.SuffixOp.Op.UnwrapOptional => { try renderExpression(allocator, stream, tree, indent, start_col, suffix_op.lhs, Space.None); try renderToken(tree, stream, tree.prevToken(suffix_op.rtoken), indent, start_col, Space.None); // . - return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); // * + return renderToken(tree, stream, suffix_op.rtoken, indent, start_col, space); // * or ? }, @TagType(ast.Node.SuffixOp.Op).Slice => |range| { @@ -595,7 +594,7 @@ fn renderExpression( } if (field_inits.len == 1) blk: { - const field_init = ??field_inits.at(0).*.cast(ast.Node.FieldInitializer); + const field_init = field_inits.at(0).*.cast(ast.Node.FieldInitializer).?; if (field_init.expr.cast(ast.Node.SuffixOp)) |nested_suffix_op| { if (nested_suffix_op.op == ast.Node.SuffixOp.Op.StructInitializer) { @@ -688,7 +687,7 @@ fn renderExpression( var count: usize = 1; var it = exprs.iterator(0); while (true) { - const expr = (??it.next()).*; + const expr = it.next().?.*; if (it.peek()) |next_expr| { const expr_last_token = expr.*.lastToken() + 1; const loc = tree.tokenLocation(tree.tokens.at(expr_last_token).end, next_expr.*.firstToken()); @@ -806,7 +805,7 @@ fn renderExpression( }, } - return renderExpression(allocator, stream, tree, indent, start_col, ??flow_expr.rhs, space); + return renderExpression(allocator, stream, tree, indent, start_col, flow_expr.rhs.?, space); }, ast.Node.Id.Payload => { @@ -1245,7 +1244,7 @@ fn renderExpression( } else { var it = switch_case.items.iterator(0); while (true) { - const node = ??it.next(); + const node = it.next().?; if (it.peek()) |next_node| { try renderExpression(allocator, stream, tree, indent, start_col, node.*, Space.None); @@ -1550,7 +1549,7 @@ fn renderExpression( var it = asm_node.outputs.iterator(0); while (true) { - const asm_output = ??it.next(); + const asm_output = it.next().?; const node = &(asm_output.*).base; if (it.peek()) |next_asm_output| { @@ -1588,7 +1587,7 @@ fn renderExpression( var it = asm_node.inputs.iterator(0); while (true) { - const asm_input = ??it.next(); + const asm_input = it.next().?; const node = &(asm_input.*).base; if (it.peek()) |next_asm_input| { @@ -1620,7 +1619,7 @@ fn renderExpression( var it = asm_node.clobbers.iterator(0); while (true) { - const clobber_token = ??it.next(); + const clobber_token = it.next().?; if (it.peek() == null) { try renderToken(tree, stream, clobber_token.*, indent_once, start_col, Space.Newline); diff --git a/test/cases/bugs/656.zig b/test/cases/bugs/656.zig index a6035d51bb..f93f0ac4d5 100644 --- a/test/cases/bugs/656.zig +++ b/test/cases/bugs/656.zig @@ -9,7 +9,7 @@ const Value = struct { align_expr: ?u32, }; -test "nullable if after an if in a switch prong of a switch with 2 prongs in an else" { +test "optional if after an if in a switch prong of a switch with 2 prongs in an else" { foo(false, true); } diff --git a/test/cases/cast.zig b/test/cases/cast.zig index da3cba7d80..a56c470408 100644 --- a/test/cases/cast.zig +++ b/test/cases/cast.zig @@ -109,16 +109,16 @@ test "implicitly cast indirect pointer to maybe-indirect pointer" { const Self = this; x: u8, fn constConst(p: *const *const Self) u8 { - return (p.*).x; + return p.*.x; } fn maybeConstConst(p: ?*const *const Self) u8 { - return ((??p).*).x; + return p.?.*.x; } fn constConstConst(p: *const *const *const Self) u8 { - return (p.*.*).x; + return p.*.*.x; } fn maybeConstConstConst(p: ?*const *const *const Self) u8 { - return ((??p).*.*).x; + return p.?.*.*.x; } }; const s = S{ .x = 42 }; @@ -177,56 +177,56 @@ test "string literal to &const []const u8" { } test "implicitly cast from T to error!?T" { - castToMaybeTypeError(1); - comptime castToMaybeTypeError(1); + castToOptionalTypeError(1); + comptime castToOptionalTypeError(1); } const A = struct { a: i32, }; -fn castToMaybeTypeError(z: i32) void { +fn castToOptionalTypeError(z: i32) void { const x = i32(1); const y: error!?i32 = x; - assert(??(try y) == 1); + assert((try y).? == 1); const f = z; const g: error!?i32 = f; const a = A{ .a = z }; const b: error!?A = a; - assert((??(b catch unreachable)).a == 1); + assert((b catch unreachable).?.a == 1); } test "implicitly cast from int to error!?T" { - implicitIntLitToMaybe(); - comptime implicitIntLitToMaybe(); + implicitIntLitToOptional(); + comptime implicitIntLitToOptional(); } -fn implicitIntLitToMaybe() void { +fn implicitIntLitToOptional() void { const f: ?i32 = 1; const g: error!?i32 = 1; } test "return null from fn() error!?&T" { - const a = returnNullFromMaybeTypeErrorRef(); - const b = returnNullLitFromMaybeTypeErrorRef(); + const a = returnNullFromOptionalTypeErrorRef(); + const b = returnNullLitFromOptionalTypeErrorRef(); assert((try a) == null and (try b) == null); } -fn returnNullFromMaybeTypeErrorRef() error!?*A { +fn returnNullFromOptionalTypeErrorRef() error!?*A { const a: ?*A = null; return a; } -fn returnNullLitFromMaybeTypeErrorRef() error!?*A { +fn returnNullLitFromOptionalTypeErrorRef() error!?*A { return null; } test "peer type resolution: ?T and T" { - assert(??peerTypeTAndMaybeT(true, false) == 0); - assert(??peerTypeTAndMaybeT(false, false) == 3); + assert(peerTypeTAndOptionalT(true, false).? == 0); + assert(peerTypeTAndOptionalT(false, false).? == 3); comptime { - assert(??peerTypeTAndMaybeT(true, false) == 0); - assert(??peerTypeTAndMaybeT(false, false) == 3); + assert(peerTypeTAndOptionalT(true, false).? == 0); + assert(peerTypeTAndOptionalT(false, false).? == 3); } } -fn peerTypeTAndMaybeT(c: bool, b: bool) ?usize { +fn peerTypeTAndOptionalT(c: bool, b: bool) ?usize { if (c) { return if (b) null else usize(0); } @@ -251,11 +251,11 @@ fn peerTypeEmptyArrayAndSlice(a: bool, slice: []const u8) []const u8 { } test "implicitly cast from [N]T to ?[]const T" { - assert(mem.eql(u8, ??castToMaybeSlice(), "hi")); - comptime assert(mem.eql(u8, ??castToMaybeSlice(), "hi")); + assert(mem.eql(u8, castToOptionalSlice().?, "hi")); + comptime assert(mem.eql(u8, castToOptionalSlice().?, "hi")); } -fn castToMaybeSlice() ?[]const u8 { +fn castToOptionalSlice() ?[]const u8 { return "hi"; } @@ -404,5 +404,5 @@ fn testCastPtrOfArrayToSliceAndPtr() void { test "cast *[1][*]const u8 to [*]const ?[*]const u8" { const window_name = [1][*]const u8{c"window name"}; const x: [*]const ?[*]const u8 = &window_name; - assert(mem.eql(u8, std.cstr.toSliceConst(??x[0]), "window name")); + assert(mem.eql(u8, std.cstr.toSliceConst(x[0].?), "window name")); } diff --git a/test/cases/error.zig b/test/cases/error.zig index ced49419d5..693631fe2d 100644 --- a/test/cases/error.zig +++ b/test/cases/error.zig @@ -140,7 +140,7 @@ fn testComptimeTestErrorEmptySet(x: EmptyErrorSet!i32) void { if (x) |v| assert(v == 1234) else |err| @compileError("bad"); } -test "syntax: nullable operator in front of error union operator" { +test "syntax: optional operator in front of error union operator" { comptime { assert(?error!i32 == ?(error!i32)); } diff --git a/test/cases/eval.zig b/test/cases/eval.zig index 9612466a86..08d3f3a841 100644 --- a/test/cases/eval.zig +++ b/test/cases/eval.zig @@ -12,7 +12,7 @@ fn fibonacci(x: i32) i32 { } fn unwrapAndAddOne(blah: ?i32) i32 { - return ??blah + 1; + return blah.? + 1; } const should_be_1235 = unwrapAndAddOne(1234); test "static add one" { diff --git a/test/cases/generics.zig b/test/cases/generics.zig index a76990e2a1..52aa013989 100644 --- a/test/cases/generics.zig +++ b/test/cases/generics.zig @@ -127,7 +127,7 @@ test "generic fn with implicit cast" { }) == 0); } fn getByte(ptr: ?*const u8) u8 { - return (??ptr).*; + return ptr.?.*; } fn getFirstByte(comptime T: type, mem: []const T) u8 { return getByte(@ptrCast(*const u8, &mem[0])); diff --git a/test/cases/misc.zig b/test/cases/misc.zig index 369d8e5cf3..beb0d6d456 100644 --- a/test/cases/misc.zig +++ b/test/cases/misc.zig @@ -505,7 +505,7 @@ test "@typeId" { assert(@typeId(@typeOf(1.0)) == Tid.ComptimeFloat); assert(@typeId(@typeOf(undefined)) == Tid.Undefined); assert(@typeId(@typeOf(null)) == Tid.Null); - assert(@typeId(?i32) == Tid.Nullable); + assert(@typeId(?i32) == Tid.Optional); assert(@typeId(error!i32) == Tid.ErrorUnion); assert(@typeId(error) == Tid.ErrorSet); assert(@typeId(AnEnum) == Tid.Enum); diff --git a/test/cases/null.zig b/test/cases/null.zig index bd78990ff4..62565784ac 100644 --- a/test/cases/null.zig +++ b/test/cases/null.zig @@ -1,6 +1,6 @@ const assert = @import("std").debug.assert; -test "nullable type" { +test "optional type" { const x: ?bool = true; if (x) |y| { @@ -33,7 +33,7 @@ test "test maybe object and get a pointer to the inner value" { b.* = false; } - assert(??maybe_bool == false); + assert(maybe_bool.? == false); } test "rhs maybe unwrap return" { @@ -47,9 +47,9 @@ test "maybe return" { } fn maybeReturnImpl() void { - assert(??foo(1235)); + assert(foo(1235).?); if (foo(null) != null) unreachable; - assert(!??foo(1234)); + assert(!foo(1234).?); } fn foo(x: ?i32) ?bool { @@ -102,12 +102,12 @@ fn testTestNullRuntime(x: ?i32) void { assert(!(x != null)); } -test "nullable void" { - nullableVoidImpl(); - comptime nullableVoidImpl(); +test "optional void" { + optionalVoidImpl(); + comptime optionalVoidImpl(); } -fn nullableVoidImpl() void { +fn optionalVoidImpl() void { assert(bar(null) == null); assert(bar({}) != null); } @@ -120,19 +120,19 @@ fn bar(x: ?void) ?void { } } -const StructWithNullable = struct { +const StructWithOptional = struct { field: ?i32, }; -var struct_with_nullable: StructWithNullable = undefined; +var struct_with_optional: StructWithOptional = undefined; -test "unwrap nullable which is field of global var" { - struct_with_nullable.field = null; - if (struct_with_nullable.field) |payload| { +test "unwrap optional which is field of global var" { + struct_with_optional.field = null; + if (struct_with_optional.field) |payload| { unreachable; } - struct_with_nullable.field = 1234; - if (struct_with_nullable.field) |payload| { + struct_with_optional.field = 1234; + if (struct_with_optional.field) |payload| { assert(payload == 1234); } else { unreachable; diff --git a/test/cases/reflection.zig b/test/cases/reflection.zig index 48fcc9ef03..3d3af3c889 100644 --- a/test/cases/reflection.zig +++ b/test/cases/reflection.zig @@ -2,7 +2,7 @@ const assert = @import("std").debug.assert; const mem = @import("std").mem; const reflection = this; -test "reflection: array, pointer, nullable, error union type child" { +test "reflection: array, pointer, optional, error union type child" { comptime { assert(([10]u8).Child == u8); assert((*u8).Child == u8); diff --git a/test/cases/type_info.zig b/test/cases/type_info.zig index b452c8e9f6..1bc58b14e1 100644 --- a/test/cases/type_info.zig +++ b/test/cases/type_info.zig @@ -88,15 +88,15 @@ fn testArray() void { assert(arr_info.Array.child == bool); } -test "type info: nullable type info" { - testNullable(); - comptime testNullable(); +test "type info: optional type info" { + testOptional(); + comptime testOptional(); } -fn testNullable() void { +fn testOptional() void { const null_info = @typeInfo(?void); - assert(TypeId(null_info) == TypeId.Nullable); - assert(null_info.Nullable.child == void); + assert(TypeId(null_info) == TypeId.Optional); + assert(null_info.Optional.child == void); } test "type info: promise info" { @@ -168,7 +168,7 @@ fn testUnion() void { assert(typeinfo_info.Union.tag_type == TypeId); assert(typeinfo_info.Union.fields.len == 25); assert(typeinfo_info.Union.fields[4].enum_field != null); - assert((??typeinfo_info.Union.fields[4].enum_field).value == 4); + assert(typeinfo_info.Union.fields[4].enum_field.?.value == 4); assert(typeinfo_info.Union.fields[4].field_type == @typeOf(@typeInfo(u8).Int)); assert(typeinfo_info.Union.defs.len == 20); diff --git a/test/cases/while.zig b/test/cases/while.zig index a95481668d..fe53522ea6 100644 --- a/test/cases/while.zig +++ b/test/cases/while.zig @@ -81,7 +81,7 @@ test "while with else" { assert(got_else == 1); } -test "while with nullable as condition" { +test "while with optional as condition" { numbers_left = 10; var sum: i32 = 0; while (getNumberOrNull()) |value| { @@ -90,7 +90,7 @@ test "while with nullable as condition" { assert(sum == 45); } -test "while with nullable as condition with else" { +test "while with optional as condition with else" { numbers_left = 10; var sum: i32 = 0; var got_else: i32 = 0; @@ -132,7 +132,7 @@ fn getNumberOrNull() ?i32 { }; } -test "while on nullable with else result follow else prong" { +test "while on optional with else result follow else prong" { const result = while (returnNull()) |value| { break value; } else @@ -140,8 +140,8 @@ test "while on nullable with else result follow else prong" { assert(result == 2); } -test "while on nullable with else result follow break prong" { - const result = while (returnMaybe(10)) |value| { +test "while on optional with else result follow break prong" { + const result = while (returnOptional(10)) |value| { break value; } else i32(2); @@ -210,7 +210,7 @@ fn testContinueOuter() void { fn returnNull() ?i32 { return null; } -fn returnMaybe(x: i32) ?i32 { +fn returnOptional(x: i32) ?i32 { return x; } fn returnError() error!i32 { diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 102c4e428d..1c737a59e7 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -1341,7 +1341,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { \\ if (true) |x| { } \\} , - ".tmp_source.zig:2:9: error: expected nullable type, found 'bool'", + ".tmp_source.zig:2:9: error: expected optional type, found 'bool'", ); cases.add( @@ -1780,7 +1780,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { ); cases.add( - "assign null to non-nullable pointer", + "assign null to non-optional pointer", \\const a: *u8 = null; \\ \\export fn entry() usize { return @sizeOf(@typeOf(a)); } @@ -2817,7 +2817,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { ); cases.add( - "while expected bool, got nullable", + "while expected bool, got optional", \\export fn foo() void { \\ while (bar()) {} \\} @@ -2837,23 +2837,23 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { ); cases.add( - "while expected nullable, got bool", + "while expected optional, got bool", \\export fn foo() void { \\ while (bar()) |x| {} \\} \\fn bar() bool { return true; } , - ".tmp_source.zig:2:15: error: expected nullable type, found 'bool'", + ".tmp_source.zig:2:15: error: expected optional type, found 'bool'", ); cases.add( - "while expected nullable, got error union", + "while expected optional, got error union", \\export fn foo() void { \\ while (bar()) |x| {} \\} \\fn bar() error!i32 { return 1; } , - ".tmp_source.zig:2:15: error: expected nullable type, found 'error!i32'", + ".tmp_source.zig:2:15: error: expected optional type, found 'error!i32'", ); cases.add( @@ -2867,7 +2867,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { ); cases.add( - "while expected error union, got nullable", + "while expected error union, got optional", \\export fn foo() void { \\ while (bar()) |x| {} else |err| {} \\} diff --git a/test/tests.zig b/test/tests.zig index cc562331fe..b66441f628 100644 --- a/test/tests.zig +++ b/test/tests.zig @@ -282,8 +282,8 @@ pub const CompareOutputContext = struct { var stdout = Buffer.initNull(b.allocator); var stderr = Buffer.initNull(b.allocator); - var stdout_file_in_stream = io.FileInStream.init(&??child.stdout); - var stderr_file_in_stream = io.FileInStream.init(&??child.stderr); + var stdout_file_in_stream = io.FileInStream.init(&child.stdout.?); + var stderr_file_in_stream = io.FileInStream.init(&child.stderr.?); stdout_file_in_stream.stream.readAllBuffer(&stdout, max_stdout_size) catch unreachable; stderr_file_in_stream.stream.readAllBuffer(&stderr, max_stdout_size) catch unreachable; @@ -601,8 +601,8 @@ pub const CompileErrorContext = struct { var stdout_buf = Buffer.initNull(b.allocator); var stderr_buf = Buffer.initNull(b.allocator); - var stdout_file_in_stream = io.FileInStream.init(&??child.stdout); - var stderr_file_in_stream = io.FileInStream.init(&??child.stderr); + var stdout_file_in_stream = io.FileInStream.init(&child.stdout.?); + var stderr_file_in_stream = io.FileInStream.init(&child.stderr.?); stdout_file_in_stream.stream.readAllBuffer(&stdout_buf, max_stdout_size) catch unreachable; stderr_file_in_stream.stream.readAllBuffer(&stderr_buf, max_stdout_size) catch unreachable; @@ -872,8 +872,8 @@ pub const TranslateCContext = struct { var stdout_buf = Buffer.initNull(b.allocator); var stderr_buf = Buffer.initNull(b.allocator); - var stdout_file_in_stream = io.FileInStream.init(&??child.stdout); - var stderr_file_in_stream = io.FileInStream.init(&??child.stderr); + var stdout_file_in_stream = io.FileInStream.init(&child.stdout.?); + var stderr_file_in_stream = io.FileInStream.init(&child.stderr.?); stdout_file_in_stream.stream.readAllBuffer(&stdout_buf, max_stdout_size) catch unreachable; stderr_file_in_stream.stream.readAllBuffer(&stderr_buf, max_stdout_size) catch unreachable; -- cgit v1.2.3 From 77678b2cbc7ac9ba2d5d4725241f6a9f7ac64fa4 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 10 Jun 2018 01:13:51 -0400 Subject: breaking syntax change: orelse keyword instead of ?? (#1096) use the `zig-fmt-optional-default` branch to have zig fmt automatically do the changes. closes #1023 --- build.zig | 6 +++--- doc/docgen.zig | 6 +++--- doc/langref.html.in | 16 +++++++-------- src-self-hosted/main.zig | 14 ++++++------- src-self-hosted/module.zig | 8 ++++---- src/all_types.hpp | 7 ++++++- src/analyze.cpp | 1 + src/ast_render.cpp | 12 +++++++++-- src/ir.cpp | 31 ++++++++++++----------------- src/parser.cpp | 13 ++++++------ src/tokenizer.cpp | 27 ++++++------------------- src/tokenizer.hpp | 2 +- src/translate_c.cpp | 16 ++++++++------- std/atomic/queue.zig | 4 ++-- std/atomic/stack.zig | 4 ++-- std/buf_map.zig | 6 +++--- std/buf_set.zig | 4 ++-- std/build.zig | 24 +++++++++++----------- std/debug/index.zig | 20 +++++++++---------- std/heap.zig | 10 +++++----- std/linked_list.zig | 4 ++-- std/os/index.zig | 14 ++++++------- std/os/linux/vdso.zig | 8 ++++---- std/os/path.zig | 12 +++++------ std/os/windows/util.zig | 2 +- std/special/build_runner.zig | 10 +++++----- std/unicode.zig | 2 +- std/zig/parse.zig | 47 ++++++++++++++++++++++---------------------- std/zig/render.zig | 8 ++++---- test/cases/cast.zig | 6 +++--- test/cases/null.zig | 10 +++++----- test/compile_errors.zig | 2 +- test/translate_c.zig | 20 +++++++++---------- 33 files changed, 187 insertions(+), 189 deletions(-) (limited to 'std/os/linux') diff --git a/build.zig b/build.zig index eada37816c..fd154c7504 100644 --- a/build.zig +++ b/build.zig @@ -102,11 +102,11 @@ pub fn build(b: *Builder) !void { b.default_step.dependOn(&exe.step); - const skip_self_hosted = b.option(bool, "skip-self-hosted", "Main test suite skips building self hosted compiler") ?? false; + const skip_self_hosted = b.option(bool, "skip-self-hosted", "Main test suite skips building self hosted compiler") orelse false; if (!skip_self_hosted) { test_step.dependOn(&exe.step); } - const verbose_link_exe = b.option(bool, "verbose-link", "Print link command for self hosted compiler") ?? false; + const verbose_link_exe = b.option(bool, "verbose-link", "Print link command for self hosted compiler") orelse false; exe.setVerboseLink(verbose_link_exe); b.installArtifact(exe); @@ -114,7 +114,7 @@ pub fn build(b: *Builder) !void { installCHeaders(b, c_header_files); const test_filter = b.option([]const u8, "test-filter", "Skip tests that do not match filter"); - const with_lldb = b.option(bool, "with-lldb", "Run tests in LLDB to get a backtrace if one fails") ?? false; + const with_lldb = b.option(bool, "with-lldb", "Run tests in LLDB to get a backtrace if one fails") orelse false; test_step.dependOn(docs_step); diff --git a/doc/docgen.zig b/doc/docgen.zig index ed0e1be273..3283d146b0 100644 --- a/doc/docgen.zig +++ b/doc/docgen.zig @@ -25,13 +25,13 @@ pub fn main() !void { if (!args_it.skip()) @panic("expected self arg"); - const zig_exe = try (args_it.next(allocator) ?? @panic("expected zig exe arg")); + const zig_exe = try (args_it.next(allocator) orelse @panic("expected zig exe arg")); defer allocator.free(zig_exe); - const in_file_name = try (args_it.next(allocator) ?? @panic("expected input arg")); + const in_file_name = try (args_it.next(allocator) orelse @panic("expected input arg")); defer allocator.free(in_file_name); - const out_file_name = try (args_it.next(allocator) ?? @panic("expected output arg")); + const out_file_name = try (args_it.next(allocator) orelse @panic("expected output arg")); defer allocator.free(out_file_name); var in_file = try os.File.openRead(allocator, in_file_name); diff --git a/doc/langref.html.in b/doc/langref.html.in index 4c4a637095..0ada8a5196 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -985,7 +985,7 @@ a ^= b
-
a ?? b
+
a orelse b
  • {#link|Optionals#}
  • @@ -998,7 +998,7 @@ a ^= b
    const value: ?u32 = null;
    -const unwrapped = value ?? 1234;
    +const unwrapped = value orelse 1234;
     unwrapped == 1234
    @@ -1011,7 +1011,7 @@ unwrapped == 1234 Equivalent to: -
    a ?? unreachable
    +
    a orelse unreachable
    const value: ?u32 = 5678;
    @@ -1278,7 +1278,7 @@ x{} x.* x.?
     == != < > <= >=
     and
     or
    -?? catch
    +orelse catch
     = *= /= %= += -= <<= >>= &= ^= |=
    {#header_close#} {#header_close#} @@ -3062,7 +3062,7 @@ fn createFoo(param: i32) !Foo { // but we want to return it if the function succeeds. errdefer deallocateFoo(foo); - const tmp_buf = allocateTmpBuffer() ?? return error.OutOfMemory; + const tmp_buf = allocateTmpBuffer() orelse return error.OutOfMemory; // tmp_buf is truly a temporary resource, and we for sure want to clean it up // before this block leaves scope defer deallocateTmpBuffer(tmp_buf); @@ -3219,13 +3219,13 @@ struct Foo *do_a_thing(void) { extern fn malloc(size: size_t) ?*u8; fn doAThing() ?*Foo { - const ptr = malloc(1234) ?? return null; + const ptr = malloc(1234) orelse return null; // ... } {#code_end#}

    Here, Zig is at least as convenient, if not more, than C. And, the type of "ptr" - is *u8 not ?*u8. The ?? operator + is *u8 not ?*u8. The orelse keyword unwrapped the optional type and therefore ptr is guaranteed to be non-null everywhere it is used in the function.

    @@ -5941,7 +5941,7 @@ AsmClobbers= ":" list(String, ",") UnwrapExpression = BoolOrExpression (UnwrapOptional | UnwrapError) | BoolOrExpression -UnwrapOptional = "??" Expression +UnwrapOptional = "orelse" Expression UnwrapError = "catch" option("|" Symbol "|") Expression diff --git a/src-self-hosted/main.zig b/src-self-hosted/main.zig index 64734f077a..1c91ab9cbe 100644 --- a/src-self-hosted/main.zig +++ b/src-self-hosted/main.zig @@ -212,7 +212,7 @@ fn cmdBuild(allocator: *Allocator, args: []const []const u8) !void { const build_runner_path = try os.path.join(allocator, special_dir, "build_runner.zig"); defer allocator.free(build_runner_path); - const build_file = flags.single("build-file") ?? "build.zig"; + const build_file = flags.single("build-file") orelse "build.zig"; const build_file_abs = try os.path.resolve(allocator, ".", build_file); defer allocator.free(build_file_abs); @@ -516,7 +516,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo const basename = os.path.basename(in_file.?); var it = mem.split(basename, "."); - const root_name = it.next() ?? { + const root_name = it.next() orelse { try stderr.write("file name cannot be empty\n"); os.exit(1); }; @@ -535,7 +535,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo const zig_root_source_file = in_file; - const full_cache_dir = os.path.resolve(allocator, ".", flags.single("cache-dir") ?? "zig-cache"[0..]) catch { + const full_cache_dir = os.path.resolve(allocator, ".", flags.single("cache-dir") orelse "zig-cache"[0..]) catch { os.exit(1); }; defer allocator.free(full_cache_dir); @@ -555,9 +555,9 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo ); defer module.destroy(); - module.version_major = try std.fmt.parseUnsigned(u32, flags.single("ver-major") ?? "0", 10); - module.version_minor = try std.fmt.parseUnsigned(u32, flags.single("ver-minor") ?? "0", 10); - module.version_patch = try std.fmt.parseUnsigned(u32, flags.single("ver-patch") ?? "0", 10); + module.version_major = try std.fmt.parseUnsigned(u32, flags.single("ver-major") orelse "0", 10); + module.version_minor = try std.fmt.parseUnsigned(u32, flags.single("ver-minor") orelse "0", 10); + module.version_patch = try std.fmt.parseUnsigned(u32, flags.single("ver-patch") orelse "0", 10); module.is_test = false; @@ -652,7 +652,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo } try module.build(); - try module.link(flags.single("out-file") ?? null); + try module.link(flags.single("out-file") orelse null); if (flags.present("print-timing-info")) { // codegen_print_timing_info(g, stderr); diff --git a/src-self-hosted/module.zig b/src-self-hosted/module.zig index a7ddf3f9e9..575105f25f 100644 --- a/src-self-hosted/module.zig +++ b/src-self-hosted/module.zig @@ -130,13 +130,13 @@ pub const Module = struct { var name_buffer = try Buffer.init(allocator, name); errdefer name_buffer.deinit(); - const context = c.LLVMContextCreate() ?? return error.OutOfMemory; + const context = c.LLVMContextCreate() orelse return error.OutOfMemory; errdefer c.LLVMContextDispose(context); - const module = c.LLVMModuleCreateWithNameInContext(name_buffer.ptr(), context) ?? return error.OutOfMemory; + const module = c.LLVMModuleCreateWithNameInContext(name_buffer.ptr(), context) orelse return error.OutOfMemory; errdefer c.LLVMDisposeModule(module); - const builder = c.LLVMCreateBuilderInContext(context) ?? return error.OutOfMemory; + const builder = c.LLVMCreateBuilderInContext(context) orelse return error.OutOfMemory; errdefer c.LLVMDisposeBuilder(builder); const module_ptr = try allocator.create(Module); @@ -223,7 +223,7 @@ pub const Module = struct { c.ZigLLVMParseCommandLineOptions(self.llvm_argv.len + 1, c_compatible_args.ptr); } - const root_src_path = self.root_src_path ?? @panic("TODO handle null root src path"); + const root_src_path = self.root_src_path orelse @panic("TODO handle null root src path"); const root_src_real_path = os.path.real(self.allocator, root_src_path) catch |err| { try printError("unable to get real path '{}': {}", root_src_path, err); return err; diff --git a/src/all_types.hpp b/src/all_types.hpp index 2a5a0ad740..ab219e4e56 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -387,6 +387,7 @@ enum NodeType { NodeTypeSliceExpr, NodeTypeFieldAccessExpr, NodeTypePtrDeref, + NodeTypeUnwrapOptional, NodeTypeUse, NodeTypeBoolLiteral, NodeTypeNullLiteral, @@ -575,6 +576,10 @@ struct AstNodeCatchExpr { AstNode *op2; }; +struct AstNodeUnwrapOptional { + AstNode *expr; +}; + enum CastOp { CastOpNoCast, // signifies the function call expression is not a cast CastOpNoop, // fn call expr is a cast, but does nothing @@ -624,7 +629,6 @@ enum PrefixOp { PrefixOpNegation, PrefixOpNegationWrap, PrefixOpOptional, - PrefixOpUnwrapOptional, PrefixOpAddrOf, }; @@ -909,6 +913,7 @@ struct AstNode { AstNodeTestDecl test_decl; AstNodeBinOpExpr bin_op_expr; AstNodeCatchExpr unwrap_err_expr; + AstNodeUnwrapOptional unwrap_optional; AstNodePrefixOpExpr prefix_op_expr; AstNodePointerType pointer_type; AstNodeFnCallExpr fn_call_expr; diff --git a/src/analyze.cpp b/src/analyze.cpp index ed261148ea..0aa5ea5dcb 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -3308,6 +3308,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) { case NodeTypeAsmExpr: case NodeTypeFieldAccessExpr: case NodeTypePtrDeref: + case NodeTypeUnwrapOptional: case NodeTypeStructField: case NodeTypeContainerInitExpr: case NodeTypeStructValueField: diff --git a/src/ast_render.cpp b/src/ast_render.cpp index 2c8c03b226..2ace00885d 100644 --- a/src/ast_render.cpp +++ b/src/ast_render.cpp @@ -50,7 +50,7 @@ static const char *bin_op_str(BinOpType bin_op) { case BinOpTypeAssignBitXor: return "^="; case BinOpTypeAssignBitOr: return "|="; case BinOpTypeAssignMergeErrorSets: return "||="; - case BinOpTypeUnwrapOptional: return "??"; + case BinOpTypeUnwrapOptional: return "orelse"; case BinOpTypeArrayCat: return "++"; case BinOpTypeArrayMult: return "**"; case BinOpTypeErrorUnion: return "!"; @@ -67,7 +67,6 @@ static const char *prefix_op_str(PrefixOp prefix_op) { case PrefixOpBoolNot: return "!"; case PrefixOpBinNot: return "~"; case PrefixOpOptional: return "?"; - case PrefixOpUnwrapOptional: return "??"; case PrefixOpAddrOf: return "&"; } zig_unreachable(); @@ -222,6 +221,8 @@ static const char *node_type_str(NodeType node_type) { return "FieldAccessExpr"; case NodeTypePtrDeref: return "PtrDerefExpr"; + case NodeTypeUnwrapOptional: + return "UnwrapOptional"; case NodeTypeContainerDecl: return "ContainerDecl"; case NodeTypeStructField: @@ -711,6 +712,13 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) { fprintf(ar->f, ".*"); break; } + case NodeTypeUnwrapOptional: + { + AstNode *lhs = node->data.unwrap_optional.expr; + render_node_ungrouped(ar, lhs); + fprintf(ar->f, ".?"); + break; + } case NodeTypeUndefinedLiteral: fprintf(ar->f, "undefined"); break; diff --git a/src/ir.cpp b/src/ir.cpp index 02606fc4aa..96eb5f7434 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -4661,21 +4661,6 @@ static IrInstruction *ir_gen_err_assert_ok(IrBuilder *irb, Scope *scope, AstNode return ir_build_load_ptr(irb, scope, source_node, payload_ptr); } -static IrInstruction *ir_gen_maybe_assert_ok(IrBuilder *irb, Scope *scope, AstNode *node, LVal lval) { - assert(node->type == NodeTypePrefixOpExpr); - AstNode *expr_node = node->data.prefix_op_expr.primary_expr; - - IrInstruction *maybe_ptr = ir_gen_node_extra(irb, expr_node, scope, LVAL_PTR); - if (maybe_ptr == irb->codegen->invalid_instruction) - return irb->codegen->invalid_instruction; - - IrInstruction *unwrapped_ptr = ir_build_unwrap_maybe(irb, scope, node, maybe_ptr, true); - if (lval.is_ptr) - return unwrapped_ptr; - - return ir_build_load_ptr(irb, scope, node, unwrapped_ptr); -} - static IrInstruction *ir_gen_bool_not(IrBuilder *irb, Scope *scope, AstNode *node) { assert(node->type == NodeTypePrefixOpExpr); AstNode *expr_node = node->data.prefix_op_expr.primary_expr; @@ -4705,8 +4690,6 @@ static IrInstruction *ir_gen_prefix_op_expr(IrBuilder *irb, Scope *scope, AstNod return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpNegationWrap), lval); case PrefixOpOptional: return ir_lval_wrap(irb, scope, ir_gen_prefix_op_id(irb, scope, node, IrUnOpOptional), lval); - case PrefixOpUnwrapOptional: - return ir_gen_maybe_assert_ok(irb, scope, node, lval); case PrefixOpAddrOf: { AstNode *expr_node = node->data.prefix_op_expr.primary_expr; return ir_lval_wrap(irb, scope, ir_gen_node_extra(irb, expr_node, scope, LVAL_PTR), lval); @@ -6541,7 +6524,6 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop return ir_build_load_ptr(irb, scope, node, ptr_instruction); } case NodeTypePtrDeref: { - assert(node->type == NodeTypePtrDeref); AstNode *expr_node = node->data.ptr_deref_expr.target; IrInstruction *value = ir_gen_node_extra(irb, expr_node, scope, lval); if (value == irb->codegen->invalid_instruction) @@ -6549,6 +6531,19 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop return ir_build_un_op(irb, scope, node, IrUnOpDereference, value); } + case NodeTypeUnwrapOptional: { + AstNode *expr_node = node->data.unwrap_optional.expr; + + IrInstruction *maybe_ptr = ir_gen_node_extra(irb, expr_node, scope, LVAL_PTR); + if (maybe_ptr == irb->codegen->invalid_instruction) + return irb->codegen->invalid_instruction; + + IrInstruction *unwrapped_ptr = ir_build_unwrap_maybe(irb, scope, node, maybe_ptr, true); + if (lval.is_ptr) + return unwrapped_ptr; + + return ir_build_load_ptr(irb, scope, node, unwrapped_ptr); + } case NodeTypeThisLiteral: return ir_lval_wrap(irb, scope, ir_gen_this_literal(irb, scope, node), lval); case NodeTypeBoolLiteral: diff --git a/src/parser.cpp b/src/parser.cpp index 2ee69f81ab..adb1633f5d 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -1151,9 +1151,8 @@ static AstNode *ast_parse_suffix_op_expr(ParseContext *pc, size_t *token_index, } else if (token->id == TokenIdQuestion) { *token_index += 1; - AstNode *node = ast_create_node(pc, NodeTypePrefixOpExpr, first_token); - node->data.prefix_op_expr.prefix_op = PrefixOpUnwrapOptional; - node->data.prefix_op_expr.primary_expr = primary_expr; + AstNode *node = ast_create_node(pc, NodeTypeUnwrapOptional, first_token); + node->data.unwrap_optional.expr = primary_expr; primary_expr = node; } else { @@ -1173,7 +1172,6 @@ static PrefixOp tok_to_prefix_op(Token *token) { case TokenIdMinusPercent: return PrefixOpNegationWrap; case TokenIdTilde: return PrefixOpBinNot; case TokenIdQuestion: return PrefixOpOptional; - case TokenIdDoubleQuestion: return PrefixOpUnwrapOptional; case TokenIdAmpersand: return PrefixOpAddrOf; default: return PrefixOpInvalid; } @@ -2312,7 +2310,7 @@ static BinOpType ast_parse_ass_op(ParseContext *pc, size_t *token_index, bool ma /* UnwrapExpression : BoolOrExpression (UnwrapOptional | UnwrapError) | BoolOrExpression -UnwrapOptional : "??" BoolOrExpression +UnwrapOptional = "orelse" Expression UnwrapError = "catch" option("|" Symbol "|") Expression */ static AstNode *ast_parse_unwrap_expr(ParseContext *pc, size_t *token_index, bool mandatory) { @@ -2322,7 +2320,7 @@ static AstNode *ast_parse_unwrap_expr(ParseContext *pc, size_t *token_index, boo Token *token = &pc->tokens->at(*token_index); - if (token->id == TokenIdDoubleQuestion) { + if (token->id == TokenIdKeywordOrElse) { *token_index += 1; AstNode *rhs = ast_parse_expression(pc, token_index, true); @@ -3035,6 +3033,9 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont case NodeTypePtrDeref: visit_field(&node->data.ptr_deref_expr.target, visit, context); break; + case NodeTypeUnwrapOptional: + visit_field(&node->data.unwrap_optional.expr, visit, context); + break; case NodeTypeUse: visit_field(&node->data.use.expr, visit, context); break; diff --git a/src/tokenizer.cpp b/src/tokenizer.cpp index cfabdf11ad..2950b4eb49 100644 --- a/src/tokenizer.cpp +++ b/src/tokenizer.cpp @@ -134,6 +134,7 @@ static const struct ZigKeyword zig_keywords[] = { {"noalias", TokenIdKeywordNoAlias}, {"null", TokenIdKeywordNull}, {"or", TokenIdKeywordOr}, + {"orelse", TokenIdKeywordOrElse}, {"packed", TokenIdKeywordPacked}, {"promise", TokenIdKeywordPromise}, {"pub", TokenIdKeywordPub}, @@ -215,7 +216,6 @@ enum TokenizeState { TokenizeStateSawGreaterThanGreaterThan, TokenizeStateSawDot, TokenizeStateSawDotDot, - TokenizeStateSawQuestionMark, TokenizeStateSawAtSign, TokenizeStateCharCode, TokenizeStateError, @@ -532,6 +532,10 @@ void tokenize(Buf *buf, Tokenization *out) { begin_token(&t, TokenIdComma); end_token(&t); break; + case '?': + begin_token(&t, TokenIdQuestion); + end_token(&t); + break; case '{': begin_token(&t, TokenIdLBrace); end_token(&t); @@ -624,28 +628,10 @@ void tokenize(Buf *buf, Tokenization *out) { begin_token(&t, TokenIdDot); t.state = TokenizeStateSawDot; break; - case '?': - begin_token(&t, TokenIdQuestion); - t.state = TokenizeStateSawQuestionMark; - break; default: invalid_char_error(&t, c); } break; - case TokenizeStateSawQuestionMark: - switch (c) { - case '?': - set_token_id(&t, t.cur_tok, TokenIdDoubleQuestion); - end_token(&t); - t.state = TokenizeStateStart; - break; - default: - t.pos -= 1; - end_token(&t); - t.state = TokenizeStateStart; - continue; - } - break; case TokenizeStateSawDot: switch (c) { case '.': @@ -1480,7 +1466,6 @@ void tokenize(Buf *buf, Tokenization *out) { case TokenizeStateSawGreaterThan: case TokenizeStateSawGreaterThanGreaterThan: case TokenizeStateSawDot: - case TokenizeStateSawQuestionMark: case TokenizeStateSawAtSign: case TokenizeStateSawStarPercent: case TokenizeStateSawPlusPercent: @@ -1545,7 +1530,6 @@ const char * token_name(TokenId id) { case TokenIdDash: return "-"; case TokenIdDivEq: return "/="; case TokenIdDot: return "."; - case TokenIdDoubleQuestion: return "??"; case TokenIdEllipsis2: return ".."; case TokenIdEllipsis3: return "..."; case TokenIdEof: return "EOF"; @@ -1582,6 +1566,7 @@ const char * token_name(TokenId id) { case TokenIdKeywordNoAlias: return "noalias"; case TokenIdKeywordNull: return "null"; case TokenIdKeywordOr: return "or"; + case TokenIdKeywordOrElse: return "orelse"; case TokenIdKeywordPacked: return "packed"; case TokenIdKeywordPromise: return "promise"; case TokenIdKeywordPub: return "pub"; diff --git a/src/tokenizer.hpp b/src/tokenizer.hpp index 7c617f85c6..75c7feb476 100644 --- a/src/tokenizer.hpp +++ b/src/tokenizer.hpp @@ -41,7 +41,6 @@ enum TokenId { TokenIdDash, TokenIdDivEq, TokenIdDot, - TokenIdDoubleQuestion, TokenIdEllipsis2, TokenIdEllipsis3, TokenIdEof, @@ -76,6 +75,7 @@ enum TokenId { TokenIdKeywordNoAlias, TokenIdKeywordNull, TokenIdKeywordOr, + TokenIdKeywordOrElse, TokenIdKeywordPacked, TokenIdKeywordPromise, TokenIdKeywordPub, diff --git a/src/translate_c.cpp b/src/translate_c.cpp index aaaf5a1edb..db46d31c5b 100644 --- a/src/translate_c.cpp +++ b/src/translate_c.cpp @@ -260,6 +260,12 @@ static AstNode *trans_create_node_prefix_op(Context *c, PrefixOp op, AstNode *ch return node; } +static AstNode *trans_create_node_unwrap_null(Context *c, AstNode *child_node) { + AstNode *node = trans_create_node(c, NodeTypeUnwrapOptional); + node->data.unwrap_optional.expr = child_node; + return node; +} + static AstNode *trans_create_node_bin_op(Context *c, AstNode *lhs_node, BinOpType op, AstNode *rhs_node) { AstNode *node = trans_create_node(c, NodeTypeBinOpExpr); node->data.bin_op_expr.op1 = lhs_node; @@ -382,7 +388,7 @@ static AstNode *trans_create_node_inline_fn(Context *c, Buf *fn_name, AstNode *r fn_def->data.fn_def.fn_proto = fn_proto; fn_proto->data.fn_proto.fn_def_node = fn_def; - AstNode *unwrap_node = trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, ref_node); + AstNode *unwrap_node = trans_create_node_unwrap_null(c, ref_node); AstNode *fn_call_node = trans_create_node(c, NodeTypeFnCallExpr); fn_call_node->data.fn_call_expr.fn_ref_expr = unwrap_node; @@ -409,10 +415,6 @@ static AstNode *trans_create_node_inline_fn(Context *c, Buf *fn_name, AstNode *r return fn_def; } -static AstNode *trans_create_node_unwrap_null(Context *c, AstNode *child) { - return trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, child); -} - static AstNode *get_global(Context *c, Buf *name) { { auto entry = c->global_table.maybe_get(name); @@ -1963,7 +1965,7 @@ static AstNode *trans_unary_operator(Context *c, ResultUsed result_used, TransSc bool is_fn_ptr = qual_type_is_fn_ptr(stmt->getSubExpr()->getType()); if (is_fn_ptr) return value_node; - AstNode *unwrapped = trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, value_node); + AstNode *unwrapped = trans_create_node_unwrap_null(c, value_node); return trans_create_node_ptr_deref(c, unwrapped); } case UO_Plus: @@ -2587,7 +2589,7 @@ static AstNode *trans_call_expr(Context *c, ResultUsed result_used, TransScope * } } if (callee_node == nullptr) { - callee_node = trans_create_node_prefix_op(c, PrefixOpUnwrapOptional, callee_raw_node); + callee_node = trans_create_node_unwrap_null(c, callee_raw_node); } } else { callee_node = callee_raw_node; diff --git a/std/atomic/queue.zig b/std/atomic/queue.zig index 142c958173..4f856d9e01 100644 --- a/std/atomic/queue.zig +++ b/std/atomic/queue.zig @@ -33,8 +33,8 @@ pub fn Queue(comptime T: type) type { pub fn get(self: *Self) ?*Node { var head = @atomicLoad(*Node, &self.head, AtomicOrder.SeqCst); while (true) { - const node = head.next ?? return null; - head = @cmpxchgWeak(*Node, &self.head, head, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return node; + const node = head.next orelse return null; + head = @cmpxchgWeak(*Node, &self.head, head, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) orelse return node; } } }; diff --git a/std/atomic/stack.zig b/std/atomic/stack.zig index 15611188d2..77fa1a9100 100644 --- a/std/atomic/stack.zig +++ b/std/atomic/stack.zig @@ -28,14 +28,14 @@ pub fn Stack(comptime T: type) type { var root = @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst); while (true) { node.next = root; - root = @cmpxchgWeak(?*Node, &self.root, root, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? break; + root = @cmpxchgWeak(?*Node, &self.root, root, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst) orelse break; } } pub fn pop(self: *Self) ?*Node { var root = @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst); while (true) { - root = @cmpxchgWeak(?*Node, &self.root, root, (root ?? return null).next, AtomicOrder.SeqCst, AtomicOrder.SeqCst) ?? return root; + root = @cmpxchgWeak(?*Node, &self.root, root, (root orelse return null).next, AtomicOrder.SeqCst, AtomicOrder.SeqCst) orelse return root; } } diff --git a/std/buf_map.zig b/std/buf_map.zig index 0d4f3a6d5e..a82d1b731a 100644 --- a/std/buf_map.zig +++ b/std/buf_map.zig @@ -19,7 +19,7 @@ pub const BufMap = struct { pub fn deinit(self: *const BufMap) void { var it = self.hash_map.iterator(); while (true) { - const entry = it.next() ?? break; + const entry = it.next() orelse break; self.free(entry.key); self.free(entry.value); } @@ -37,12 +37,12 @@ pub const BufMap = struct { } pub fn get(self: *const BufMap, key: []const u8) ?[]const u8 { - const entry = self.hash_map.get(key) ?? return null; + const entry = self.hash_map.get(key) orelse return null; return entry.value; } pub fn delete(self: *BufMap, key: []const u8) void { - const entry = self.hash_map.remove(key) ?? return; + const entry = self.hash_map.remove(key) orelse return; self.free(entry.key); self.free(entry.value); } diff --git a/std/buf_set.zig b/std/buf_set.zig index 03a050ed8b..ab2d8e7c34 100644 --- a/std/buf_set.zig +++ b/std/buf_set.zig @@ -17,7 +17,7 @@ pub const BufSet = struct { pub fn deinit(self: *const BufSet) void { var it = self.hash_map.iterator(); while (true) { - const entry = it.next() ?? break; + const entry = it.next() orelse break; self.free(entry.key); } @@ -33,7 +33,7 @@ pub const BufSet = struct { } pub fn delete(self: *BufSet, key: []const u8) void { - const entry = self.hash_map.remove(key) ?? return; + const entry = self.hash_map.remove(key) orelse return; self.free(entry.key); } diff --git a/std/build.zig b/std/build.zig index fed02e0815..5733aec17d 100644 --- a/std/build.zig +++ b/std/build.zig @@ -136,7 +136,7 @@ pub const Builder = struct { } pub fn setInstallPrefix(self: *Builder, maybe_prefix: ?[]const u8) void { - self.prefix = maybe_prefix ?? "/usr/local"; // TODO better default + self.prefix = maybe_prefix orelse "/usr/local"; // TODO better default self.lib_dir = os.path.join(self.allocator, self.prefix, "lib") catch unreachable; self.exe_dir = os.path.join(self.allocator, self.prefix, "bin") catch unreachable; } @@ -312,9 +312,9 @@ pub const Builder = struct { if (os.getEnvVarOwned(self.allocator, "NIX_CFLAGS_COMPILE")) |nix_cflags_compile| { var it = mem.split(nix_cflags_compile, " "); while (true) { - const word = it.next() ?? break; + const word = it.next() orelse break; if (mem.eql(u8, word, "-isystem")) { - const include_path = it.next() ?? { + const include_path = it.next() orelse { warn("Expected argument after -isystem in NIX_CFLAGS_COMPILE\n"); break; }; @@ -330,9 +330,9 @@ pub const Builder = struct { if (os.getEnvVarOwned(self.allocator, "NIX_LDFLAGS")) |nix_ldflags| { var it = mem.split(nix_ldflags, " "); while (true) { - const word = it.next() ?? break; + const word = it.next() orelse break; if (mem.eql(u8, word, "-rpath")) { - const rpath = it.next() ?? { + const rpath = it.next() orelse { warn("Expected argument after -rpath in NIX_LDFLAGS\n"); break; }; @@ -362,7 +362,7 @@ pub const Builder = struct { } self.available_options_list.append(available_option) catch unreachable; - const entry = self.user_input_options.get(name) ?? return null; + const entry = self.user_input_options.get(name) orelse return null; entry.value.used = true; switch (type_id) { TypeId.Bool => switch (entry.value.value) { @@ -416,9 +416,9 @@ pub const Builder = struct { pub fn standardReleaseOptions(self: *Builder) builtin.Mode { if (self.release_mode) |mode| return mode; - const release_safe = self.option(bool, "release-safe", "optimizations on and safety on") ?? false; - const release_fast = self.option(bool, "release-fast", "optimizations on and safety off") ?? false; - const release_small = self.option(bool, "release-small", "size optimizations on and safety off") ?? false; + const release_safe = self.option(bool, "release-safe", "optimizations on and safety on") orelse false; + const release_fast = self.option(bool, "release-fast", "optimizations on and safety off") orelse false; + const release_small = self.option(bool, "release-small", "size optimizations on and safety off") orelse false; const mode = if (release_safe and !release_fast and !release_small) builtin.Mode.ReleaseSafe else if (release_fast and !release_safe and !release_small) builtin.Mode.ReleaseFast else if (release_small and !release_fast and !release_safe) builtin.Mode.ReleaseSmall else if (!release_fast and !release_safe and !release_small) builtin.Mode.Debug else x: { warn("Multiple release modes (of -Drelease-safe, -Drelease-fast and -Drelease-small)"); @@ -518,7 +518,7 @@ pub const Builder = struct { // make sure all args are used var it = self.user_input_options.iterator(); while (true) { - const entry = it.next() ?? break; + const entry = it.next() orelse break; if (!entry.value.used) { warn("Invalid option: -D{}\n\n", entry.key); self.markInvalidUserInput(); @@ -1246,7 +1246,7 @@ pub const LibExeObjStep = struct { { var it = self.link_libs.iterator(); while (true) { - const entry = it.next() ?? break; + const entry = it.next() orelse break; zig_args.append("--library") catch unreachable; zig_args.append(entry.key) catch unreachable; } @@ -1696,7 +1696,7 @@ pub const TestStep = struct { { var it = self.link_libs.iterator(); while (true) { - const entry = it.next() ?? break; + const entry = it.next() orelse break; try zig_args.append("--library"); try zig_args.append(entry.key); } diff --git a/std/debug/index.zig b/std/debug/index.zig index be47ab76bc..25f7a58b25 100644 --- a/std/debug/index.zig +++ b/std/debug/index.zig @@ -208,7 +208,7 @@ fn printSourceAtAddress(debug_info: *ElfStackTrace, out_stream: var, address: us .name = "???", .address = address, }; - const symbol = debug_info.symbol_table.search(address) ?? &unknown; + const symbol = debug_info.symbol_table.search(address) orelse &unknown; try out_stream.print(WHITE ++ "{}" ++ RESET ++ ": " ++ DIM ++ ptr_hex ++ " in ??? (???)" ++ RESET ++ "\n", symbol.name, address); }, else => { @@ -268,10 +268,10 @@ pub fn openSelfDebugInfo(allocator: *mem.Allocator) !*ElfStackTrace { try st.elf.openFile(allocator, &st.self_exe_file); errdefer st.elf.close(); - st.debug_info = (try st.elf.findSection(".debug_info")) ?? return error.MissingDebugInfo; - st.debug_abbrev = (try st.elf.findSection(".debug_abbrev")) ?? return error.MissingDebugInfo; - st.debug_str = (try st.elf.findSection(".debug_str")) ?? return error.MissingDebugInfo; - st.debug_line = (try st.elf.findSection(".debug_line")) ?? return error.MissingDebugInfo; + st.debug_info = (try st.elf.findSection(".debug_info")) orelse return error.MissingDebugInfo; + st.debug_abbrev = (try st.elf.findSection(".debug_abbrev")) orelse return error.MissingDebugInfo; + st.debug_str = (try st.elf.findSection(".debug_str")) orelse return error.MissingDebugInfo; + st.debug_line = (try st.elf.findSection(".debug_line")) orelse return error.MissingDebugInfo; st.debug_ranges = (try st.elf.findSection(".debug_ranges")); try scanAllCompileUnits(st); return st; @@ -443,7 +443,7 @@ const Die = struct { } fn getAttrAddr(self: *const Die, id: u64) !u64 { - const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; + const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Address => |value| value, else => error.InvalidDebugInfo, @@ -451,7 +451,7 @@ const Die = struct { } fn getAttrSecOffset(self: *const Die, id: u64) !u64 { - const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; + const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Const => |value| value.asUnsignedLe(), FormValue.SecOffset => |value| value, @@ -460,7 +460,7 @@ const Die = struct { } fn getAttrUnsignedLe(self: *const Die, id: u64) !u64 { - const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; + const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Const => |value| value.asUnsignedLe(), else => error.InvalidDebugInfo, @@ -468,7 +468,7 @@ const Die = struct { } fn getAttrString(self: *const Die, st: *ElfStackTrace, id: u64) ![]u8 { - const form_value = self.getAttr(id) ?? return error.MissingDebugInfo; + const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.String => |value| value, FormValue.StrPtr => |offset| getString(st, offset), @@ -748,7 +748,7 @@ fn parseDie(st: *ElfStackTrace, abbrev_table: *const AbbrevTable, is_64: bool) ! var in_file_stream = io.FileInStream.init(in_file); const in_stream = &in_file_stream.stream; const abbrev_code = try readULeb128(in_stream); - const table_entry = getAbbrevTableEntry(abbrev_table, abbrev_code) ?? return error.InvalidDebugInfo; + const table_entry = getAbbrevTableEntry(abbrev_table, abbrev_code) orelse return error.InvalidDebugInfo; var result = Die{ .tag_id = table_entry.tag_id, diff --git a/std/heap.zig b/std/heap.zig index d1fbf9ca0a..172bc24118 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -97,12 +97,12 @@ pub const DirectAllocator = struct { }, Os.windows => { const amt = n + alignment + @sizeOf(usize); - const heap_handle = self.heap_handle ?? blk: { - const hh = os.windows.HeapCreate(os.windows.HEAP_NO_SERIALIZE, amt, 0) ?? return error.OutOfMemory; + const heap_handle = self.heap_handle orelse blk: { + const hh = os.windows.HeapCreate(os.windows.HEAP_NO_SERIALIZE, amt, 0) orelse return error.OutOfMemory; self.heap_handle = hh; break :blk hh; }; - const ptr = os.windows.HeapAlloc(heap_handle, 0, amt) ?? return error.OutOfMemory; + const ptr = os.windows.HeapAlloc(heap_handle, 0, amt) orelse return error.OutOfMemory; const root_addr = @ptrToInt(ptr); const rem = @rem(root_addr, alignment); const march_forward_bytes = if (rem == 0) 0 else (alignment - rem); @@ -142,7 +142,7 @@ pub const DirectAllocator = struct { const root_addr = @intToPtr(*align(1) usize, old_record_addr).*; const old_ptr = @intToPtr(*c_void, root_addr); const amt = new_size + alignment + @sizeOf(usize); - const new_ptr = os.windows.HeapReAlloc(self.heap_handle.?, 0, old_ptr, amt) ?? blk: { + const new_ptr = os.windows.HeapReAlloc(self.heap_handle.?, 0, old_ptr, amt) orelse blk: { if (new_size > old_mem.len) return error.OutOfMemory; const new_record_addr = old_record_addr - new_size + old_mem.len; @intToPtr(*align(1) usize, new_record_addr).* = root_addr; @@ -343,7 +343,7 @@ pub const ThreadSafeFixedBufferAllocator = struct { if (new_end_index > self.buffer.len) { return error.OutOfMemory; } - end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst) ?? return self.buffer[adjusted_index..new_end_index]; + end_index = @cmpxchgWeak(usize, &self.end_index, end_index, new_end_index, builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst) orelse return self.buffer[adjusted_index..new_end_index]; } } diff --git a/std/linked_list.zig b/std/linked_list.zig index 536c6d24d0..9e32b7d9da 100644 --- a/std/linked_list.zig +++ b/std/linked_list.zig @@ -169,7 +169,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// Returns: /// A pointer to the last node in the list. pub fn pop(list: *Self) ?*Node { - const last = list.last ?? return null; + const last = list.last orelse return null; list.remove(last); return last; } @@ -179,7 +179,7 @@ fn BaseLinkedList(comptime T: type, comptime ParentType: type, comptime field_na /// Returns: /// A pointer to the first node in the list. pub fn popFirst(list: *Self) ?*Node { - const first = list.first ?? return null; + const first = list.first orelse return null; list.remove(first); return first; } diff --git a/std/os/index.zig b/std/os/index.zig index 807b2c398b..6a13ff94d4 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -425,7 +425,7 @@ pub fn posixExecve(argv: []const []const u8, env_map: *const BufMap, allocator: return posixExecveErrnoToErr(posix.getErrno(posix.execve(argv_buf[0].?, argv_buf.ptr, envp_buf.ptr))); } - const PATH = getEnvPosix("PATH") ?? "/usr/local/bin:/bin/:/usr/bin"; + const PATH = getEnvPosix("PATH") orelse "/usr/local/bin:/bin/:/usr/bin"; // PATH.len because it is >= the largest search_path // +1 for the / to join the search path and exe_path // +1 for the null terminating byte @@ -490,7 +490,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap { errdefer result.deinit(); if (is_windows) { - const ptr = windows.GetEnvironmentStringsA() ?? return error.OutOfMemory; + const ptr = windows.GetEnvironmentStringsA() orelse return error.OutOfMemory; defer assert(windows.FreeEnvironmentStringsA(ptr) != 0); var i: usize = 0; @@ -573,7 +573,7 @@ pub fn getEnvVarOwned(allocator: *mem.Allocator, key: []const u8) ![]u8 { return allocator.shrink(u8, buf, result); } } else { - const result = getEnvPosix(key) ?? return error.EnvironmentVariableNotFound; + const result = getEnvPosix(key) orelse return error.EnvironmentVariableNotFound; return mem.dupe(allocator, u8, result); } } @@ -1641,7 +1641,7 @@ pub const ArgIterator = struct { if (builtin.os == Os.windows) { return self.inner.next(allocator); } else { - return mem.dupe(allocator, u8, self.inner.next() ?? return null); + return mem.dupe(allocator, u8, self.inner.next() orelse return null); } } @@ -2457,9 +2457,9 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread } }; - const heap_handle = windows.GetProcessHeap() ?? return SpawnThreadError.OutOfMemory; + const heap_handle = windows.GetProcessHeap() orelse return SpawnThreadError.OutOfMemory; const byte_count = @alignOf(WinThread.OuterContext) + @sizeOf(WinThread.OuterContext); - const bytes_ptr = windows.HeapAlloc(heap_handle, 0, byte_count) ?? return SpawnThreadError.OutOfMemory; + const bytes_ptr = windows.HeapAlloc(heap_handle, 0, byte_count) orelse return SpawnThreadError.OutOfMemory; errdefer assert(windows.HeapFree(heap_handle, 0, bytes_ptr) != 0); const bytes = @ptrCast([*]u8, bytes_ptr)[0..byte_count]; const outer_context = std.heap.FixedBufferAllocator.init(bytes).allocator.create(WinThread.OuterContext) catch unreachable; @@ -2468,7 +2468,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread outer_context.thread.data.alloc_start = bytes_ptr; const parameter = if (@sizeOf(Context) == 0) null else @ptrCast(*c_void, &outer_context.inner); - outer_context.thread.data.handle = windows.CreateThread(null, default_stack_size, WinThread.threadMain, parameter, 0, null) ?? { + outer_context.thread.data.handle = windows.CreateThread(null, default_stack_size, WinThread.threadMain, parameter, 0, null) orelse { const err = windows.GetLastError(); return switch (err) { else => os.unexpectedErrorWindows(err), diff --git a/std/os/linux/vdso.zig b/std/os/linux/vdso.zig index 1414b8185b..cbd0cd1df5 100644 --- a/std/os/linux/vdso.zig +++ b/std/os/linux/vdso.zig @@ -28,7 +28,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { } } } - const dynv = maybe_dynv ?? return 0; + const dynv = maybe_dynv orelse return 0; if (base == @maxValue(usize)) return 0; var maybe_strings: ?[*]u8 = null; @@ -52,9 +52,9 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { } } - const strings = maybe_strings ?? return 0; - const syms = maybe_syms ?? return 0; - const hashtab = maybe_hashtab ?? return 0; + const strings = maybe_strings orelse return 0; + const syms = maybe_syms orelse return 0; + const hashtab = maybe_hashtab orelse return 0; if (maybe_verdef == null) maybe_versym = null; const OK_TYPES = (1 << elf.STT_NOTYPE | 1 << elf.STT_OBJECT | 1 << elf.STT_FUNC | 1 << elf.STT_COMMON); diff --git a/std/os/path.zig b/std/os/path.zig index 430dda2934..a3ad23b1a9 100644 --- a/std/os/path.zig +++ b/std/os/path.zig @@ -182,8 +182,8 @@ pub fn windowsParsePath(path: []const u8) WindowsPath { } var it = mem.split(path, []u8{this_sep}); - _ = (it.next() ?? return relative_path); - _ = (it.next() ?? return relative_path); + _ = (it.next() orelse return relative_path); + _ = (it.next() orelse return relative_path); return WindowsPath{ .is_abs = isAbsoluteWindows(path), .kind = WindowsPath.Kind.NetworkShare, @@ -200,8 +200,8 @@ pub fn windowsParsePath(path: []const u8) WindowsPath { } var it = mem.split(path, []u8{this_sep}); - _ = (it.next() ?? return relative_path); - _ = (it.next() ?? return relative_path); + _ = (it.next() orelse return relative_path); + _ = (it.next() orelse return relative_path); return WindowsPath{ .is_abs = isAbsoluteWindows(path), .kind = WindowsPath.Kind.NetworkShare, @@ -923,7 +923,7 @@ pub fn relativeWindows(allocator: *Allocator, from: []const u8, to: []const u8) var from_it = mem.split(resolved_from, "/\\"); var to_it = mem.split(resolved_to, "/\\"); while (true) { - const from_component = from_it.next() ?? return mem.dupe(allocator, u8, to_it.rest()); + const from_component = from_it.next() orelse return mem.dupe(allocator, u8, to_it.rest()); const to_rest = to_it.rest(); if (to_it.next()) |to_component| { // TODO ASCII is wrong, we actually need full unicode support to compare paths. @@ -974,7 +974,7 @@ pub fn relativePosix(allocator: *Allocator, from: []const u8, to: []const u8) ![ var from_it = mem.split(resolved_from, "/"); var to_it = mem.split(resolved_to, "/"); while (true) { - const from_component = from_it.next() ?? return mem.dupe(allocator, u8, to_it.rest()); + const from_component = from_it.next() orelse return mem.dupe(allocator, u8, to_it.rest()); const to_rest = to_it.rest(); if (to_it.next()) |to_component| { if (mem.eql(u8, from_component, to_component)) diff --git a/std/os/windows/util.zig b/std/os/windows/util.zig index 7170346108..f93a673be0 100644 --- a/std/os/windows/util.zig +++ b/std/os/windows/util.zig @@ -153,7 +153,7 @@ pub fn createWindowsEnvBlock(allocator: *mem.Allocator, env_map: *const BufMap) pub fn windowsLoadDll(allocator: *mem.Allocator, dll_path: []const u8) !windows.HMODULE { const padded_buff = try cstr.addNullByte(allocator, dll_path); defer allocator.free(padded_buff); - return windows.LoadLibraryA(padded_buff.ptr) ?? error.DllNotFound; + return windows.LoadLibraryA(padded_buff.ptr) orelse error.DllNotFound; } pub fn windowsUnloadDll(hModule: windows.HMODULE) void { diff --git a/std/special/build_runner.zig b/std/special/build_runner.zig index 3471d6ed21..e4f04df6d0 100644 --- a/std/special/build_runner.zig +++ b/std/special/build_runner.zig @@ -27,15 +27,15 @@ pub fn main() !void { // skip my own exe name _ = arg_it.skip(); - const zig_exe = try unwrapArg(arg_it.next(allocator) ?? { + const zig_exe = try unwrapArg(arg_it.next(allocator) orelse { warn("Expected first argument to be path to zig compiler\n"); return error.InvalidArgs; }); - const build_root = try unwrapArg(arg_it.next(allocator) ?? { + const build_root = try unwrapArg(arg_it.next(allocator) orelse { warn("Expected second argument to be build root directory path\n"); return error.InvalidArgs; }); - const cache_root = try unwrapArg(arg_it.next(allocator) ?? { + const cache_root = try unwrapArg(arg_it.next(allocator) orelse { warn("Expected third argument to be cache root directory path\n"); return error.InvalidArgs; }); @@ -84,12 +84,12 @@ pub fn main() !void { } else if (mem.eql(u8, arg, "--help")) { return usage(&builder, false, try stdout_stream); } else if (mem.eql(u8, arg, "--prefix")) { - prefix = try unwrapArg(arg_it.next(allocator) ?? { + prefix = try unwrapArg(arg_it.next(allocator) orelse { warn("Expected argument after --prefix\n\n"); return usageAndErr(&builder, false, try stderr_stream); }); } else if (mem.eql(u8, arg, "--search-prefix")) { - const search_prefix = try unwrapArg(arg_it.next(allocator) ?? { + const search_prefix = try unwrapArg(arg_it.next(allocator) orelse { warn("Expected argument after --search-prefix\n\n"); return usageAndErr(&builder, false, try stderr_stream); }); diff --git a/std/unicode.zig b/std/unicode.zig index 21ae12f59c..ec808ca4fe 100644 --- a/std/unicode.zig +++ b/std/unicode.zig @@ -220,7 +220,7 @@ const Utf8Iterator = struct { } pub fn nextCodepoint(it: *Utf8Iterator) ?u32 { - const slice = it.nextCodepointSlice() ?? return null; + const slice = it.nextCodepointSlice() orelse return null; switch (slice.len) { 1 => return u32(slice[0]), diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 9f8ef3c3d6..5752f69409 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -43,7 +43,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { // skip over line comments at the top of the file while (true) { - const next_tok = tok_it.peek() ?? break; + const next_tok = tok_it.peek() orelse break; if (next_tok.id != Token.Id.LineComment) break; _ = tok_it.next(); } @@ -197,7 +197,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { const lib_name_token = nextToken(&tok_it, &tree); const lib_name_token_index = lib_name_token.index; const lib_name_token_ptr = lib_name_token.ptr; - break :blk (try parseStringLiteral(arena, &tok_it, lib_name_token_ptr, lib_name_token_index, &tree)) ?? { + break :blk (try parseStringLiteral(arena, &tok_it, lib_name_token_ptr, lib_name_token_index, &tree)) orelse { prevToken(&tok_it, &tree); break :blk null; }; @@ -1434,13 +1434,14 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State{ .ExpectTokenSave = ExpectTokenSave{ .id = Token.Id.AngleBracketRight, - .ptr = &async_node.rangle_bracket.? }, + .ptr = &async_node.rangle_bracket.?, + }, }); try stack.append(State{ .TypeExprBegin = OptionalCtx{ .RequiredNull = &async_node.allocator_type } }); continue; }, State.AsyncEnd => |ctx| { - const node = ctx.ctx.get() ?? continue; + const node = ctx.ctx.get() orelse continue; switch (node.id) { ast.Node.Id.FnProto => { @@ -1813,7 +1814,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { continue; }, State.RangeExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; if (eatToken(&tok_it, &tree, Token.Id.Ellipsis3)) |ellipsis3| { const node = try arena.construct(ast.Node.InfixOp{ @@ -1835,7 +1836,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.AssignmentExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; const token = nextToken(&tok_it, &tree); const token_index = token.index; @@ -1865,7 +1866,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.UnwrapExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; const token = nextToken(&tok_it, &tree); const token_index = token.index; @@ -1900,7 +1901,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.BoolOrExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; if (eatToken(&tok_it, &tree, Token.Id.Keyword_or)) |or_token| { const node = try arena.construct(ast.Node.InfixOp{ @@ -1924,7 +1925,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.BoolAndExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; if (eatToken(&tok_it, &tree, Token.Id.Keyword_and)) |and_token| { const node = try arena.construct(ast.Node.InfixOp{ @@ -1948,7 +1949,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.ComparisonExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; const token = nextToken(&tok_it, &tree); const token_index = token.index; @@ -1978,7 +1979,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.BinaryOrExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; if (eatToken(&tok_it, &tree, Token.Id.Pipe)) |pipe| { const node = try arena.construct(ast.Node.InfixOp{ @@ -2002,7 +2003,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.BinaryXorExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; if (eatToken(&tok_it, &tree, Token.Id.Caret)) |caret| { const node = try arena.construct(ast.Node.InfixOp{ @@ -2026,7 +2027,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.BinaryAndExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; if (eatToken(&tok_it, &tree, Token.Id.Ampersand)) |ampersand| { const node = try arena.construct(ast.Node.InfixOp{ @@ -2050,7 +2051,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.BitShiftExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; const token = nextToken(&tok_it, &tree); const token_index = token.index; @@ -2080,7 +2081,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.AdditionExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; const token = nextToken(&tok_it, &tree); const token_index = token.index; @@ -2110,7 +2111,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.MultiplyExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; const token = nextToken(&tok_it, &tree); const token_index = token.index; @@ -2141,7 +2142,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.CurlySuffixExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; if (tok_it.peek().?.id == Token.Id.Period) { const node = try arena.construct(ast.Node.SuffixOp{ @@ -2189,7 +2190,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.TypeExprEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; if (eatToken(&tok_it, &tree, Token.Id.Bang)) |bang| { const node = try arena.construct(ast.Node.InfixOp{ @@ -2269,7 +2270,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { }, State.SuffixOpExpressionEnd => |opt_ctx| { - const lhs = opt_ctx.get() ?? continue; + const lhs = opt_ctx.get() orelse continue; const token = nextToken(&tok_it, &tree); const token_index = token.index; @@ -2418,7 +2419,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { continue; }, Token.Id.StringLiteral, Token.Id.MultilineStringLiteralLine => { - opt_ctx.store((try parseStringLiteral(arena, &tok_it, token.ptr, token.index, &tree)) ?? unreachable); + opt_ctx.store((try parseStringLiteral(arena, &tok_it, token.ptr, token.index, &tree)) orelse unreachable); continue; }, Token.Id.LParen => { @@ -2648,7 +2649,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree { const token = nextToken(&tok_it, &tree); const token_index = token.index; const token_ptr = token.ptr; - opt_ctx.store((try parseStringLiteral(arena, &tok_it, token_ptr, token_index, &tree)) ?? { + opt_ctx.store((try parseStringLiteral(arena, &tok_it, token_ptr, token_index, &tree)) orelse { prevToken(&tok_it, &tree); if (opt_ctx != OptionalCtx.Optional) { ((try tree.errors.addOne())).* = Error{ .ExpectedPrimaryExpr = Error.ExpectedPrimaryExpr{ .token = token_index } }; @@ -3348,7 +3349,7 @@ fn nextToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) AnnotatedTok assert(result.ptr.id != Token.Id.LineComment); while (true) { - const next_tok = tok_it.peek() ?? return result; + const next_tok = tok_it.peek() orelse return result; if (next_tok.id != Token.Id.LineComment) return result; _ = tok_it.next(); } @@ -3356,7 +3357,7 @@ fn nextToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) AnnotatedTok fn prevToken(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree) void { while (true) { - const prev_tok = tok_it.prev() ?? return; + const prev_tok = tok_it.prev() orelse return; if (prev_tok.id == Token.Id.LineComment) continue; return; } diff --git a/std/zig/render.zig b/std/zig/render.zig index 0b8e4d1453..bc45768fa3 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -83,7 +83,7 @@ fn renderRoot( var start_col: usize = 0; var it = tree.root_node.decls.iterator(0); while (true) { - var decl = (it.next() ?? return).*; + var decl = (it.next() orelse return).*; // look for zig fmt: off comment var start_token_index = decl.firstToken(); zig_fmt_loop: while (start_token_index != 0) { @@ -112,7 +112,7 @@ fn renderRoot( const start = tree.tokens.at(start_token_index + 1).start; try stream.print("{}\n", tree.source[start..end_token.end]); while (tree.tokens.at(decl.firstToken()).start < end_token.end) { - decl = (it.next() ?? return).*; + decl = (it.next() orelse return).*; } break :zig_fmt_loop; } @@ -1993,7 +1993,7 @@ fn renderDocComments( indent: usize, start_col: *usize, ) (@typeOf(stream).Child.Error || Error)!void { - const comment = node.doc_comments ?? return; + const comment = node.doc_comments orelse return; var it = comment.lines.iterator(0); const first_token = node.firstToken(); while (it.next()) |line_token_index| { @@ -2021,7 +2021,7 @@ fn nodeIsBlock(base: *const ast.Node) bool { } fn nodeCausesSliceOpSpace(base: *ast.Node) bool { - const infix_op = base.cast(ast.Node.InfixOp) ?? return false; + const infix_op = base.cast(ast.Node.InfixOp) orelse return false; return switch (infix_op.op) { ast.Node.InfixOp.Op.Period => false, else => true, diff --git a/test/cases/cast.zig b/test/cases/cast.zig index a56c470408..ade1cf78aa 100644 --- a/test/cases/cast.zig +++ b/test/cases/cast.zig @@ -73,7 +73,7 @@ fn Struct(comptime T: type) type { fn maybePointer(self: ?*const Self) Self { const none = Self{ .x = if (T == void) void{} else 0 }; - return (self ?? &none).*; + return (self orelse &none).*; } }; } @@ -87,7 +87,7 @@ const Union = union { fn maybePointer(self: ?*const Union) Union { const none = Union{ .x = 0 }; - return (self ?? &none).*; + return (self orelse &none).*; } }; @@ -100,7 +100,7 @@ const Enum = enum { } fn maybePointer(self: ?*const Enum) Enum { - return (self ?? &Enum.None).*; + return (self orelse &Enum.None).*; } }; diff --git a/test/cases/null.zig b/test/cases/null.zig index 62565784ac..cdcfd23efb 100644 --- a/test/cases/null.zig +++ b/test/cases/null.zig @@ -15,13 +15,13 @@ test "optional type" { const next_x: ?i32 = null; - const z = next_x ?? 1234; + const z = next_x orelse 1234; assert(z == 1234); const final_x: ?i32 = 13; - const num = final_x ?? unreachable; + const num = final_x orelse unreachable; assert(num == 13); } @@ -38,7 +38,7 @@ test "test maybe object and get a pointer to the inner value" { test "rhs maybe unwrap return" { const x: ?bool = true; - const y = x ?? return; + const y = x orelse return; } test "maybe return" { @@ -53,7 +53,7 @@ fn maybeReturnImpl() void { } fn foo(x: ?i32) ?bool { - const value = x ?? return null; + const value = x orelse return null; return value > 1234; } @@ -140,6 +140,6 @@ test "unwrap optional which is field of global var" { } test "null with default unwrap" { - const x: i32 = null ?? 1; + const x: i32 = null orelse 1; assert(x == 1); } diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 1c737a59e7..5ec2759032 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -2296,7 +2296,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { \\ \\ defer try canFail(); \\ - \\ const a = maybeInt() ?? return; + \\ const a = maybeInt() orelse return; \\} \\ \\fn canFail() error!void { } diff --git a/test/translate_c.zig b/test/translate_c.zig index 3489f9da21..417171d2c2 100644 --- a/test/translate_c.zig +++ b/test/translate_c.zig @@ -246,13 +246,13 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub extern var fn_ptr: ?extern fn() void; , \\pub inline fn foo() void { - \\ return (??fn_ptr)(); + \\ return fn_ptr.?(); \\} , \\pub extern var fn_ptr2: ?extern fn(c_int, f32) u8; , \\pub inline fn bar(arg0: c_int, arg1: f32) u8 { - \\ return (??fn_ptr2)(arg0, arg1); + \\ return fn_ptr2.?(arg0, arg1); \\} ); @@ -608,7 +608,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ field: c_int, \\}; \\pub export fn read_field(foo: ?[*]struct_Foo) c_int { - \\ return (??foo).field; + \\ return foo.?.field; \\} ); @@ -969,11 +969,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub export fn bar() void { \\ var f: ?extern fn() void = foo; \\ var b: ?extern fn() c_int = baz; - \\ (??f)(); - \\ (??f)(); + \\ f.?(); + \\ f.?(); \\ foo(); - \\ _ = (??b)(); - \\ _ = (??b)(); + \\ _ = b.?(); + \\ _ = b.?(); \\ _ = baz(); \\} ); @@ -984,7 +984,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\} , \\pub export fn foo(x: ?[*]c_int) void { - \\ (??x).* = 1; + \\ x.?.* = 1; \\} ); @@ -1012,7 +1012,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub fn foo() c_int { \\ var x: c_int = 1234; \\ var ptr: ?[*]c_int = &x; - \\ return (??ptr).*; + \\ return ptr.?.*; \\} ); @@ -1119,7 +1119,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub const glClearPFN = PFNGLCLEARPROC; , \\pub inline fn glClearUnion(arg0: GLbitfield) void { - \\ return (??glProcs.gl.Clear)(arg0); + \\ return glProcs.gl.Clear.?(arg0); \\} , \\pub const OpenGLProcs = union_OpenGLProcs; -- cgit v1.2.3 From 79120612267f55901029dd57290ee90c0a3ec987 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 17 Jun 2018 02:57:07 -0400 Subject: remove integer and float casting syntax * add `@intCast` * add `@floatCast` * add `@floatToInt` * add `@intToFloat` See #1061 --- doc/langref.html.in | 12 +- src/all_types.hpp | 36 +++++ src/codegen.cpp | 8 + src/ir.cpp | 290 +++++++++++++++++++++++++++++++++--- src/ir_print.cpp | 44 ++++++ src/main.cpp | 2 +- std/array_list.zig | 8 +- std/base64.zig | 4 +- std/crypto/blake2.zig | 10 +- std/crypto/md5.zig | 6 +- std/crypto/sha1.zig | 6 +- std/crypto/sha2.zig | 12 +- std/debug/index.zig | 8 +- std/fmt/errol/index.zig | 78 +++++----- std/fmt/index.zig | 19 +-- std/hash/crc.zig | 4 +- std/hash/siphash.zig | 6 +- std/heap.zig | 2 +- std/json.zig | 2 +- std/math/acos.zig | 4 +- std/math/asin.zig | 4 +- std/math/atan.zig | 4 +- std/math/atan2.zig | 8 +- std/math/atanh.zig | 2 +- std/math/big/int.zig | 22 +-- std/math/cbrt.zig | 6 +- std/math/ceil.zig | 4 +- std/math/complex/atan.zig | 10 +- std/math/complex/cosh.zig | 4 +- std/math/complex/exp.zig | 6 +- std/math/complex/ldexp.zig | 13 +- std/math/complex/sinh.zig | 10 +- std/math/complex/sqrt.zig | 10 +- std/math/complex/tanh.zig | 10 +- std/math/cos.zig | 4 +- std/math/cosh.zig | 2 +- std/math/exp.zig | 12 +- std/math/exp2.zig | 14 +- std/math/expm1.zig | 20 +-- std/math/floor.zig | 4 +- std/math/fma.zig | 6 +- std/math/frexp.zig | 4 +- std/math/hypot.zig | 2 +- std/math/ilogb.zig | 4 +- std/math/index.zig | 25 +++- std/math/ln.zig | 12 +- std/math/log.zig | 11 +- std/math/log10.zig | 14 +- std/math/log1p.zig | 12 +- std/math/log2.zig | 12 +- std/math/modf.zig | 8 +- std/math/pow.zig | 4 +- std/math/scalbn.zig | 4 +- std/math/sin.zig | 4 +- std/math/sinh.zig | 2 +- std/math/sqrt.zig | 2 +- std/math/tan.zig | 4 +- std/math/tanh.zig | 4 +- std/math/trunc.zig | 8 +- std/mem.zig | 2 +- std/os/child_process.zig | 2 +- std/os/darwin.zig | 11 +- std/os/file.zig | 6 +- std/os/index.zig | 16 +- std/os/linux/index.zig | 80 +++++----- std/os/linux/test.zig | 6 +- std/os/linux/vdso.zig | 4 +- std/os/time.zig | 24 +-- std/os/windows/util.zig | 9 +- std/rand/index.zig | 16 +- std/segmented_list.zig | 12 +- std/special/bootstrap.zig | 2 +- std/special/builtin.zig | 30 ++-- std/special/compiler_rt/divti3.zig | 2 +- std/special/compiler_rt/fixuint.zig | 8 +- std/special/compiler_rt/index.zig | 12 +- std/special/compiler_rt/udivmod.zig | 34 ++--- std/unicode.zig | 20 +-- std/zig/tokenizer.zig | 2 +- test/cases/cast.zig | 18 ++- test/cases/enum.zig | 2 +- test/cases/eval.zig | 8 +- test/cases/fn.zig | 2 +- test/cases/for.zig | 4 +- test/cases/struct.zig | 8 +- 85 files changed, 799 insertions(+), 413 deletions(-) (limited to 'std/os/linux') diff --git a/doc/langref.html.in b/doc/langref.html.in index 651629d8fb..35ca9a13b4 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -1355,7 +1355,7 @@ var some_integers: [100]i32 = undefined; test "modify an array" { for (some_integers) |*item, i| { - item.* = i32(i); + item.* = @intCast(i32, i); } assert(some_integers[10] == 10); assert(some_integers[99] == 99); @@ -1397,8 +1397,8 @@ var fancy_array = init: { var initial_value: [10]Point = undefined; for (initial_value) |*pt, i| { pt.* = Point{ - .x = i32(i), - .y = i32(i) * 2, + .x = @intCast(i32, i), + .y = @intCast(i32, i) * 2, }; } break :init initial_value; @@ -2410,7 +2410,7 @@ test "for basics" { var sum2: i32 = 0; for (items) |value, i| { assert(@typeOf(i) == usize); - sum2 += i32(i); + sum2 += @intCast(i32, i); } assert(sum2 == 10); } @@ -5730,7 +5730,7 @@ comptime { {#code_begin|test_err|attempt to cast negative value to unsigned integer#} comptime { const value: i32 = -1; - const unsigned = u32(value); + const unsigned = @intCast(u32, value); } {#code_end#}

    At runtime crashes with the message attempt to cast negative value to unsigned integer and a stack trace.

    @@ -5744,7 +5744,7 @@ comptime { {#code_begin|test_err|cast from 'u16' to 'u8' truncates bits#} comptime { const spartan_count: u16 = 300; - const byte = u8(spartan_count); + const byte = @intCast(u8, spartan_count); } {#code_end#}

    At runtime crashes with the message integer cast truncated bits and a stack trace.

    diff --git a/src/all_types.hpp b/src/all_types.hpp index 0d364915f9..bc2fe07c18 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -1357,6 +1357,10 @@ enum BuiltinFnId { BuiltinFnIdMod, BuiltinFnIdSqrt, BuiltinFnIdTruncate, + BuiltinFnIdIntCast, + BuiltinFnIdFloatCast, + BuiltinFnIdIntToFloat, + BuiltinFnIdFloatToInt, BuiltinFnIdIntType, BuiltinFnIdSetCold, BuiltinFnIdSetRuntimeSafety, @@ -2040,6 +2044,10 @@ enum IrInstructionId { IrInstructionIdCmpxchg, IrInstructionIdFence, IrInstructionIdTruncate, + IrInstructionIdIntCast, + IrInstructionIdFloatCast, + IrInstructionIdIntToFloat, + IrInstructionIdFloatToInt, IrInstructionIdIntType, IrInstructionIdBoolNot, IrInstructionIdMemset, @@ -2632,6 +2640,34 @@ struct IrInstructionTruncate { IrInstruction *target; }; +struct IrInstructionIntCast { + IrInstruction base; + + IrInstruction *dest_type; + IrInstruction *target; +}; + +struct IrInstructionFloatCast { + IrInstruction base; + + IrInstruction *dest_type; + IrInstruction *target; +}; + +struct IrInstructionIntToFloat { + IrInstruction base; + + IrInstruction *dest_type; + IrInstruction *target; +}; + +struct IrInstructionFloatToInt { + IrInstruction base; + + IrInstruction *dest_type; + IrInstruction *target; +}; + struct IrInstructionIntType { IrInstruction base; diff --git a/src/codegen.cpp b/src/codegen.cpp index 425cdac024..4108cbbd68 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -4722,6 +4722,10 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable, case IrInstructionIdPromiseResultType: case IrInstructionIdAwaitBookkeeping: case IrInstructionIdAddImplicitReturnType: + case IrInstructionIdIntCast: + case IrInstructionIdFloatCast: + case IrInstructionIdIntToFloat: + case IrInstructionIdFloatToInt: zig_unreachable(); case IrInstructionIdReturn: @@ -6310,6 +6314,10 @@ static void define_builtin_fns(CodeGen *g) { create_builtin_fn(g, BuiltinFnIdCmpxchgStrong, "cmpxchgStrong", 6); create_builtin_fn(g, BuiltinFnIdFence, "fence", 1); create_builtin_fn(g, BuiltinFnIdTruncate, "truncate", 2); + create_builtin_fn(g, BuiltinFnIdIntCast, "intCast", 2); + create_builtin_fn(g, BuiltinFnIdFloatCast, "floatCast", 2); + create_builtin_fn(g, BuiltinFnIdIntToFloat, "intToFloat", 2); + create_builtin_fn(g, BuiltinFnIdFloatToInt, "floatToInt", 2); create_builtin_fn(g, BuiltinFnIdCompileErr, "compileError", 1); create_builtin_fn(g, BuiltinFnIdCompileLog, "compileLog", SIZE_MAX); create_builtin_fn(g, BuiltinFnIdIntType, "IntType", 2); // TODO rename to Int diff --git a/src/ir.cpp b/src/ir.cpp index d008ead113..0b847fc4e4 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -460,6 +460,22 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionTruncate *) { return IrInstructionIdTruncate; } +static constexpr IrInstructionId ir_instruction_id(IrInstructionIntCast *) { + return IrInstructionIdIntCast; +} + +static constexpr IrInstructionId ir_instruction_id(IrInstructionFloatCast *) { + return IrInstructionIdFloatCast; +} + +static constexpr IrInstructionId ir_instruction_id(IrInstructionIntToFloat *) { + return IrInstructionIdIntToFloat; +} + +static constexpr IrInstructionId ir_instruction_id(IrInstructionFloatToInt *) { + return IrInstructionIdFloatToInt; +} + static constexpr IrInstructionId ir_instruction_id(IrInstructionIntType *) { return IrInstructionIdIntType; } @@ -1899,10 +1915,48 @@ static IrInstruction *ir_build_truncate(IrBuilder *irb, Scope *scope, AstNode *s return &instruction->base; } -static IrInstruction *ir_build_truncate_from(IrBuilder *irb, IrInstruction *old_instruction, IrInstruction *dest_type, IrInstruction *target) { - IrInstruction *new_instruction = ir_build_truncate(irb, old_instruction->scope, old_instruction->source_node, dest_type, target); - ir_link_new_instruction(new_instruction, old_instruction); - return new_instruction; +static IrInstruction *ir_build_int_cast(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *dest_type, IrInstruction *target) { + IrInstructionIntCast *instruction = ir_build_instruction(irb, scope, source_node); + instruction->dest_type = dest_type; + instruction->target = target; + + ir_ref_instruction(dest_type, irb->current_basic_block); + ir_ref_instruction(target, irb->current_basic_block); + + return &instruction->base; +} + +static IrInstruction *ir_build_float_cast(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *dest_type, IrInstruction *target) { + IrInstructionFloatCast *instruction = ir_build_instruction(irb, scope, source_node); + instruction->dest_type = dest_type; + instruction->target = target; + + ir_ref_instruction(dest_type, irb->current_basic_block); + ir_ref_instruction(target, irb->current_basic_block); + + return &instruction->base; +} + +static IrInstruction *ir_build_int_to_float(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *dest_type, IrInstruction *target) { + IrInstructionIntToFloat *instruction = ir_build_instruction(irb, scope, source_node); + instruction->dest_type = dest_type; + instruction->target = target; + + ir_ref_instruction(dest_type, irb->current_basic_block); + ir_ref_instruction(target, irb->current_basic_block); + + return &instruction->base; +} + +static IrInstruction *ir_build_float_to_int(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *dest_type, IrInstruction *target) { + IrInstructionFloatToInt *instruction = ir_build_instruction(irb, scope, source_node); + instruction->dest_type = dest_type; + instruction->target = target; + + ir_ref_instruction(dest_type, irb->current_basic_block); + ir_ref_instruction(target, irb->current_basic_block); + + return &instruction->base; } static IrInstruction *ir_build_int_type(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *is_signed, IrInstruction *bit_count) { @@ -3957,6 +4011,66 @@ static IrInstruction *ir_gen_builtin_fn_call(IrBuilder *irb, Scope *scope, AstNo IrInstruction *truncate = ir_build_truncate(irb, scope, node, arg0_value, arg1_value); return ir_lval_wrap(irb, scope, truncate, lval); } + case BuiltinFnIdIntCast: + { + AstNode *arg0_node = node->data.fn_call_expr.params.at(0); + IrInstruction *arg0_value = ir_gen_node(irb, arg0_node, scope); + if (arg0_value == irb->codegen->invalid_instruction) + return arg0_value; + + AstNode *arg1_node = node->data.fn_call_expr.params.at(1); + IrInstruction *arg1_value = ir_gen_node(irb, arg1_node, scope); + if (arg1_value == irb->codegen->invalid_instruction) + return arg1_value; + + IrInstruction *result = ir_build_int_cast(irb, scope, node, arg0_value, arg1_value); + return ir_lval_wrap(irb, scope, result, lval); + } + case BuiltinFnIdFloatCast: + { + AstNode *arg0_node = node->data.fn_call_expr.params.at(0); + IrInstruction *arg0_value = ir_gen_node(irb, arg0_node, scope); + if (arg0_value == irb->codegen->invalid_instruction) + return arg0_value; + + AstNode *arg1_node = node->data.fn_call_expr.params.at(1); + IrInstruction *arg1_value = ir_gen_node(irb, arg1_node, scope); + if (arg1_value == irb->codegen->invalid_instruction) + return arg1_value; + + IrInstruction *result = ir_build_float_cast(irb, scope, node, arg0_value, arg1_value); + return ir_lval_wrap(irb, scope, result, lval); + } + case BuiltinFnIdIntToFloat: + { + AstNode *arg0_node = node->data.fn_call_expr.params.at(0); + IrInstruction *arg0_value = ir_gen_node(irb, arg0_node, scope); + if (arg0_value == irb->codegen->invalid_instruction) + return arg0_value; + + AstNode *arg1_node = node->data.fn_call_expr.params.at(1); + IrInstruction *arg1_value = ir_gen_node(irb, arg1_node, scope); + if (arg1_value == irb->codegen->invalid_instruction) + return arg1_value; + + IrInstruction *result = ir_build_int_to_float(irb, scope, node, arg0_value, arg1_value); + return ir_lval_wrap(irb, scope, result, lval); + } + case BuiltinFnIdFloatToInt: + { + AstNode *arg0_node = node->data.fn_call_expr.params.at(0); + IrInstruction *arg0_value = ir_gen_node(irb, arg0_node, scope); + if (arg0_value == irb->codegen->invalid_instruction) + return arg0_value; + + AstNode *arg1_node = node->data.fn_call_expr.params.at(1); + IrInstruction *arg1_value = ir_gen_node(irb, arg1_node, scope); + if (arg1_value == irb->codegen->invalid_instruction) + return arg1_value; + + IrInstruction *result = ir_build_float_to_int(irb, scope, node, arg0_value, arg1_value); + return ir_lval_wrap(irb, scope, result, lval); + } case BuiltinFnIdIntType: { AstNode *arg0_node = node->data.fn_call_expr.params.at(0); @@ -9948,34 +10062,37 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst return ir_resolve_cast(ira, source_instr, value, wanted_type, CastOpBoolToInt, false); } - // explicit widening or shortening cast - if ((wanted_type->id == TypeTableEntryIdInt && - actual_type->id == TypeTableEntryIdInt) || - (wanted_type->id == TypeTableEntryIdFloat && - actual_type->id == TypeTableEntryIdFloat)) + // explicit widening conversion + if (wanted_type->id == TypeTableEntryIdInt && + actual_type->id == TypeTableEntryIdInt && + wanted_type->data.integral.is_signed == actual_type->data.integral.is_signed && + wanted_type->data.integral.bit_count >= actual_type->data.integral.bit_count) { return ir_analyze_widen_or_shorten(ira, source_instr, value, wanted_type); } - // explicit error set cast - if (wanted_type->id == TypeTableEntryIdErrorSet && - actual_type->id == TypeTableEntryIdErrorSet) + // small enough unsigned ints can get casted to large enough signed ints + if (wanted_type->id == TypeTableEntryIdInt && wanted_type->data.integral.is_signed && + actual_type->id == TypeTableEntryIdInt && !actual_type->data.integral.is_signed && + wanted_type->data.integral.bit_count > actual_type->data.integral.bit_count) { - return ir_analyze_err_set_cast(ira, source_instr, value, wanted_type); + return ir_analyze_widen_or_shorten(ira, source_instr, value, wanted_type); } - // explicit cast from int to float + // explicit float widening conversion if (wanted_type->id == TypeTableEntryIdFloat && - actual_type->id == TypeTableEntryIdInt) + actual_type->id == TypeTableEntryIdFloat && + wanted_type->data.floating.bit_count >= actual_type->data.floating.bit_count) { - return ir_resolve_cast(ira, source_instr, value, wanted_type, CastOpIntToFloat, false); + return ir_analyze_widen_or_shorten(ira, source_instr, value, wanted_type); } - // explicit cast from float to int - if (wanted_type->id == TypeTableEntryIdInt && - actual_type->id == TypeTableEntryIdFloat) + + // explicit error set cast + if (wanted_type->id == TypeTableEntryIdErrorSet && + actual_type->id == TypeTableEntryIdErrorSet) { - return ir_resolve_cast(ira, source_instr, value, wanted_type, CastOpFloatToInt, false); + return ir_analyze_err_set_cast(ira, source_instr, value, wanted_type); } // explicit cast from [N]T to []const T @@ -17365,7 +17482,126 @@ static TypeTableEntry *ir_analyze_instruction_truncate(IrAnalyze *ira, IrInstruc return dest_type; } - ir_build_truncate_from(&ira->new_irb, &instruction->base, dest_type_value, target); + IrInstruction *new_instruction = ir_build_truncate(&ira->new_irb, instruction->base.scope, + instruction->base.source_node, dest_type_value, target); + ir_link_new_instruction(new_instruction, &instruction->base); + return dest_type; +} + +static TypeTableEntry *ir_analyze_instruction_int_cast(IrAnalyze *ira, IrInstructionIntCast *instruction) { + TypeTableEntry *dest_type = ir_resolve_type(ira, instruction->dest_type->other); + if (type_is_invalid(dest_type)) + return ira->codegen->builtin_types.entry_invalid; + + if (dest_type->id != TypeTableEntryIdInt) { + ir_add_error(ira, instruction->dest_type, buf_sprintf("expected integer type, found '%s'", buf_ptr(&dest_type->name))); + return ira->codegen->builtin_types.entry_invalid; + } + + IrInstruction *target = instruction->target->other; + if (type_is_invalid(target->value.type)) + return ira->codegen->builtin_types.entry_invalid; + + if (target->value.type->id == TypeTableEntryIdComptimeInt) { + if (ir_num_lit_fits_in_other_type(ira, target, dest_type, true)) { + IrInstruction *result = ir_resolve_cast(ira, &instruction->base, target, dest_type, + CastOpNumLitToConcrete, false); + if (type_is_invalid(result->value.type)) + return ira->codegen->builtin_types.entry_invalid; + ir_link_new_instruction(result, &instruction->base); + return dest_type; + } else { + return ira->codegen->builtin_types.entry_invalid; + } + } + + if (target->value.type->id != TypeTableEntryIdInt) { + ir_add_error(ira, instruction->target, buf_sprintf("expected integer type, found '%s'", + buf_ptr(&target->value.type->name))); + return ira->codegen->builtin_types.entry_invalid; + } + + IrInstruction *result = ir_analyze_widen_or_shorten(ira, &instruction->base, target, dest_type); + if (type_is_invalid(result->value.type)) + return ira->codegen->builtin_types.entry_invalid; + + ir_link_new_instruction(result, &instruction->base); + return dest_type; +} + +static TypeTableEntry *ir_analyze_instruction_float_cast(IrAnalyze *ira, IrInstructionFloatCast *instruction) { + TypeTableEntry *dest_type = ir_resolve_type(ira, instruction->dest_type->other); + if (type_is_invalid(dest_type)) + return ira->codegen->builtin_types.entry_invalid; + + if (dest_type->id != TypeTableEntryIdFloat) { + ir_add_error(ira, instruction->dest_type, + buf_sprintf("expected float type, found '%s'", buf_ptr(&dest_type->name))); + return ira->codegen->builtin_types.entry_invalid; + } + + IrInstruction *target = instruction->target->other; + if (type_is_invalid(target->value.type)) + return ira->codegen->builtin_types.entry_invalid; + + if (target->value.type->id == TypeTableEntryIdComptimeInt || + target->value.type->id == TypeTableEntryIdComptimeFloat) + { + if (ir_num_lit_fits_in_other_type(ira, target, dest_type, true)) { + CastOp op; + if (target->value.type->id == TypeTableEntryIdComptimeInt) { + op = CastOpIntToFloat; + } else { + op = CastOpNumLitToConcrete; + } + IrInstruction *result = ir_resolve_cast(ira, &instruction->base, target, dest_type, op, false); + if (type_is_invalid(result->value.type)) + return ira->codegen->builtin_types.entry_invalid; + ir_link_new_instruction(result, &instruction->base); + return dest_type; + } else { + return ira->codegen->builtin_types.entry_invalid; + } + } + + if (target->value.type->id != TypeTableEntryIdFloat) { + ir_add_error(ira, instruction->target, buf_sprintf("expected float type, found '%s'", + buf_ptr(&target->value.type->name))); + return ira->codegen->builtin_types.entry_invalid; + } + + IrInstruction *result = ir_analyze_widen_or_shorten(ira, &instruction->base, target, dest_type); + if (type_is_invalid(result->value.type)) + return ira->codegen->builtin_types.entry_invalid; + ir_link_new_instruction(result, &instruction->base); + return dest_type; +} + +static TypeTableEntry *ir_analyze_instruction_int_to_float(IrAnalyze *ira, IrInstructionIntToFloat *instruction) { + TypeTableEntry *dest_type = ir_resolve_type(ira, instruction->dest_type->other); + if (type_is_invalid(dest_type)) + return ira->codegen->builtin_types.entry_invalid; + + IrInstruction *target = instruction->target->other; + if (type_is_invalid(target->value.type)) + return ira->codegen->builtin_types.entry_invalid; + + IrInstruction *result = ir_resolve_cast(ira, &instruction->base, target, dest_type, CastOpIntToFloat, false); + ir_link_new_instruction(result, &instruction->base); + return dest_type; +} + +static TypeTableEntry *ir_analyze_instruction_float_to_int(IrAnalyze *ira, IrInstructionFloatToInt *instruction) { + TypeTableEntry *dest_type = ir_resolve_type(ira, instruction->dest_type->other); + if (type_is_invalid(dest_type)) + return ira->codegen->builtin_types.entry_invalid; + + IrInstruction *target = instruction->target->other; + if (type_is_invalid(target->value.type)) + return ira->codegen->builtin_types.entry_invalid; + + IrInstruction *result = ir_resolve_cast(ira, &instruction->base, target, dest_type, CastOpFloatToInt, false); + ir_link_new_instruction(result, &instruction->base); return dest_type; } @@ -19899,6 +20135,14 @@ static TypeTableEntry *ir_analyze_instruction_nocast(IrAnalyze *ira, IrInstructi return ir_analyze_instruction_fence(ira, (IrInstructionFence *)instruction); case IrInstructionIdTruncate: return ir_analyze_instruction_truncate(ira, (IrInstructionTruncate *)instruction); + case IrInstructionIdIntCast: + return ir_analyze_instruction_int_cast(ira, (IrInstructionIntCast *)instruction); + case IrInstructionIdFloatCast: + return ir_analyze_instruction_float_cast(ira, (IrInstructionFloatCast *)instruction); + case IrInstructionIdIntToFloat: + return ir_analyze_instruction_int_to_float(ira, (IrInstructionIntToFloat *)instruction); + case IrInstructionIdFloatToInt: + return ir_analyze_instruction_float_to_int(ira, (IrInstructionFloatToInt *)instruction); case IrInstructionIdIntType: return ir_analyze_instruction_int_type(ira, (IrInstructionIntType *)instruction); case IrInstructionIdBoolNot: @@ -20242,6 +20486,10 @@ bool ir_has_side_effects(IrInstruction *instruction) { case IrInstructionIdPromiseResultType: case IrInstructionIdSqrt: case IrInstructionIdAtomicLoad: + case IrInstructionIdIntCast: + case IrInstructionIdFloatCast: + case IrInstructionIdIntToFloat: + case IrInstructionIdFloatToInt: return false; case IrInstructionIdAsm: diff --git a/src/ir_print.cpp b/src/ir_print.cpp index 43907fa9d4..b5722c52fa 100644 --- a/src/ir_print.cpp +++ b/src/ir_print.cpp @@ -648,6 +648,38 @@ static void ir_print_truncate(IrPrint *irp, IrInstructionTruncate *instruction) fprintf(irp->f, ")"); } +static void ir_print_int_cast(IrPrint *irp, IrInstructionIntCast *instruction) { + fprintf(irp->f, "@intCast("); + ir_print_other_instruction(irp, instruction->dest_type); + fprintf(irp->f, ", "); + ir_print_other_instruction(irp, instruction->target); + fprintf(irp->f, ")"); +} + +static void ir_print_float_cast(IrPrint *irp, IrInstructionFloatCast *instruction) { + fprintf(irp->f, "@floatCast("); + ir_print_other_instruction(irp, instruction->dest_type); + fprintf(irp->f, ", "); + ir_print_other_instruction(irp, instruction->target); + fprintf(irp->f, ")"); +} + +static void ir_print_int_to_float(IrPrint *irp, IrInstructionIntToFloat *instruction) { + fprintf(irp->f, "@intToFloat("); + ir_print_other_instruction(irp, instruction->dest_type); + fprintf(irp->f, ", "); + ir_print_other_instruction(irp, instruction->target); + fprintf(irp->f, ")"); +} + +static void ir_print_float_to_int(IrPrint *irp, IrInstructionFloatToInt *instruction) { + fprintf(irp->f, "@floatToInt("); + ir_print_other_instruction(irp, instruction->dest_type); + fprintf(irp->f, ", "); + ir_print_other_instruction(irp, instruction->target); + fprintf(irp->f, ")"); +} + static void ir_print_int_type(IrPrint *irp, IrInstructionIntType *instruction) { fprintf(irp->f, "@IntType("); ir_print_other_instruction(irp, instruction->is_signed); @@ -1417,6 +1449,18 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) { case IrInstructionIdTruncate: ir_print_truncate(irp, (IrInstructionTruncate *)instruction); break; + case IrInstructionIdIntCast: + ir_print_int_cast(irp, (IrInstructionIntCast *)instruction); + break; + case IrInstructionIdFloatCast: + ir_print_float_cast(irp, (IrInstructionFloatCast *)instruction); + break; + case IrInstructionIdIntToFloat: + ir_print_int_to_float(irp, (IrInstructionIntToFloat *)instruction); + break; + case IrInstructionIdFloatToInt: + ir_print_float_to_int(irp, (IrInstructionFloatToInt *)instruction); + break; case IrInstructionIdIntType: ir_print_int_type(irp, (IrInstructionIntType *)instruction); break; diff --git a/src/main.cpp b/src/main.cpp index c63a143bff..0fe12bb0cb 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -34,7 +34,7 @@ static int usage(const char *arg0) { " --assembly [source] add assembly file to build\n" " --cache-dir [path] override the cache directory\n" " --color [auto|off|on] enable or disable colored error messages\n" - " --emit [filetype] emit a specific file format as compilation output\n" + " --emit [asm|bin|llvm-ir] emit a specific file format as compilation output\n" " --enable-timing-info print timing diagnostics\n" " --libc-include-dir [path] directory where libc stdlib.h resides\n" " --name [name] override output name\n" diff --git a/std/array_list.zig b/std/array_list.zig index fd1d5cbe26..b71f5be6ab 100644 --- a/std/array_list.zig +++ b/std/array_list.zig @@ -185,23 +185,23 @@ test "basic ArrayList test" { { var i: usize = 0; while (i < 10) : (i += 1) { - list.append(i32(i + 1)) catch unreachable; + list.append(@intCast(i32, i + 1)) catch unreachable; } } { var i: usize = 0; while (i < 10) : (i += 1) { - assert(list.items[i] == i32(i + 1)); + assert(list.items[i] == @intCast(i32, i + 1)); } } for (list.toSlice()) |v, i| { - assert(v == i32(i + 1)); + assert(v == @intCast(i32, i + 1)); } for (list.toSliceConst()) |v, i| { - assert(v == i32(i + 1)); + assert(v == @intCast(i32, i + 1)); } assert(list.pop() == 10); diff --git a/std/base64.zig b/std/base64.zig index d27bcbd201..45c8e22c7e 100644 --- a/std/base64.zig +++ b/std/base64.zig @@ -99,7 +99,7 @@ pub const Base64Decoder = struct { assert(!result.char_in_alphabet[c]); assert(c != pad_char); - result.char_to_index[c] = u8(i); + result.char_to_index[c] = @intCast(u8, i); result.char_in_alphabet[c] = true; } @@ -284,7 +284,7 @@ pub const Base64DecoderUnsafe = struct { }; for (alphabet_chars) |c, i| { assert(c != pad_char); - result.char_to_index[c] = u8(i); + result.char_to_index[c] = @intCast(u8, i); } return result; } diff --git a/std/crypto/blake2.zig b/std/crypto/blake2.zig index f0a9766c00..947133e4cf 100644 --- a/std/crypto/blake2.zig +++ b/std/crypto/blake2.zig @@ -79,7 +79,7 @@ fn Blake2s(comptime out_len: usize) type { mem.copy(u32, d.h[0..], iv[0..]); // No key plus default parameters - d.h[0] ^= 0x01010000 ^ u32(out_len >> 3); + d.h[0] ^= 0x01010000 ^ @intCast(u32, out_len >> 3); d.t = 0; d.buf_len = 0; } @@ -110,7 +110,7 @@ fn Blake2s(comptime out_len: usize) type { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); } pub fn final(d: *Self, out: []u8) void { @@ -144,7 +144,7 @@ fn Blake2s(comptime out_len: usize) type { } v[12] ^= @truncate(u32, d.t); - v[13] ^= u32(d.t >> 32); + v[13] ^= @intCast(u32, d.t >> 32); if (last) v[14] = ~v[14]; const rounds = comptime []RoundParam{ @@ -345,7 +345,7 @@ fn Blake2b(comptime out_len: usize) type { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); } pub fn final(d: *Self, out: []u8) void { @@ -377,7 +377,7 @@ fn Blake2b(comptime out_len: usize) type { } v[12] ^= @truncate(u64, d.t); - v[13] ^= u64(d.t >> 64); + v[13] ^= @intCast(u64, d.t >> 64); if (last) v[14] = ~v[14]; const rounds = comptime []RoundParam{ diff --git a/std/crypto/md5.zig b/std/crypto/md5.zig index c0d1732d37..23fe2313a0 100644 --- a/std/crypto/md5.zig +++ b/std/crypto/md5.zig @@ -78,7 +78,7 @@ pub const Md5 = struct { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); // Md5 uses the bottom 64-bits for length padding d.total_len +%= b.len; @@ -103,9 +103,9 @@ pub const Md5 = struct { // Append message length. var i: usize = 1; var len = d.total_len >> 5; - d.buf[56] = u8(d.total_len & 0x1f) << 3; + d.buf[56] = @intCast(u8, d.total_len & 0x1f) << 3; while (i < 8) : (i += 1) { - d.buf[56 + i] = u8(len & 0xff); + d.buf[56 + i] = @intCast(u8, len & 0xff); len >>= 8; } diff --git a/std/crypto/sha1.zig b/std/crypto/sha1.zig index 9e46fc9239..5c91590c88 100644 --- a/std/crypto/sha1.zig +++ b/std/crypto/sha1.zig @@ -78,7 +78,7 @@ pub const Sha1 = struct { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); d.total_len += b.len; } @@ -102,9 +102,9 @@ pub const Sha1 = struct { // Append message length. var i: usize = 1; var len = d.total_len >> 5; - d.buf[63] = u8(d.total_len & 0x1f) << 3; + d.buf[63] = @intCast(u8, d.total_len & 0x1f) << 3; while (i < 8) : (i += 1) { - d.buf[63 - i] = u8(len & 0xff); + d.buf[63 - i] = @intCast(u8, len & 0xff); len >>= 8; } diff --git a/std/crypto/sha2.zig b/std/crypto/sha2.zig index d1375d73e8..d1b915835c 100644 --- a/std/crypto/sha2.zig +++ b/std/crypto/sha2.zig @@ -131,7 +131,7 @@ fn Sha2_32(comptime params: Sha2Params32) type { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); d.total_len += b.len; } @@ -155,9 +155,9 @@ fn Sha2_32(comptime params: Sha2Params32) type { // Append message length. var i: usize = 1; var len = d.total_len >> 5; - d.buf[63] = u8(d.total_len & 0x1f) << 3; + d.buf[63] = @intCast(u8, d.total_len & 0x1f) << 3; while (i < 8) : (i += 1) { - d.buf[63 - i] = u8(len & 0xff); + d.buf[63 - i] = @intCast(u8, len & 0xff); len >>= 8; } @@ -472,7 +472,7 @@ fn Sha2_64(comptime params: Sha2Params64) type { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); d.total_len += b.len; } @@ -496,9 +496,9 @@ fn Sha2_64(comptime params: Sha2Params64) type { // Append message length. var i: usize = 1; var len = d.total_len >> 5; - d.buf[127] = u8(d.total_len & 0x1f) << 3; + d.buf[127] = @intCast(u8, d.total_len & 0x1f) << 3; while (i < 16) : (i += 1) { - d.buf[127 - i] = u8(len & 0xff); + d.buf[127 - i] = @intCast(u8, len & 0xff); len >>= 8; } diff --git a/std/debug/index.zig b/std/debug/index.zig index fb1dac537c..198e0f90f6 100644 --- a/std/debug/index.zig +++ b/std/debug/index.zig @@ -554,7 +554,7 @@ const LineNumberProgram = struct { const file_name = try os.path.join(self.file_entries.allocator, dir_name, file_entry.file_name); errdefer self.file_entries.allocator.free(file_name); return LineInfo{ - .line = if (self.prev_line >= 0) usize(self.prev_line) else 0, + .line = if (self.prev_line >= 0) @intCast(usize, self.prev_line) else 0, .column = self.prev_column, .file_name = file_name, .allocator = self.file_entries.allocator, @@ -1070,7 +1070,7 @@ fn readULeb128(in_stream: var) !u64 { var operand: u64 = undefined; - if (@shlWithOverflow(u64, byte & 0b01111111, u6(shift), &operand)) return error.InvalidDebugInfo; + if (@shlWithOverflow(u64, byte & 0b01111111, @intCast(u6, shift), &operand)) return error.InvalidDebugInfo; result |= operand; @@ -1089,13 +1089,13 @@ fn readILeb128(in_stream: var) !i64 { var operand: i64 = undefined; - if (@shlWithOverflow(i64, byte & 0b01111111, u6(shift), &operand)) return error.InvalidDebugInfo; + if (@shlWithOverflow(i64, byte & 0b01111111, @intCast(u6, shift), &operand)) return error.InvalidDebugInfo; result |= operand; shift += 7; if ((byte & 0b10000000) == 0) { - if (shift < @sizeOf(i64) * 8 and (byte & 0b01000000) != 0) result |= -(i64(1) << u6(shift)); + if (shift < @sizeOf(i64) * 8 and (byte & 0b01000000) != 0) result |= -(i64(1) << @intCast(u6, shift)); return result; } } diff --git a/std/fmt/errol/index.zig b/std/fmt/errol/index.zig index a906b714ab..a5fb692857 100644 --- a/std/fmt/errol/index.zig +++ b/std/fmt/errol/index.zig @@ -29,11 +29,11 @@ pub fn roundToPrecision(float_decimal: *FloatDecimal, precision: usize, mode: Ro switch (mode) { RoundMode.Decimal => { if (float_decimal.exp >= 0) { - round_digit = precision + usize(float_decimal.exp); + round_digit = precision + @intCast(usize, float_decimal.exp); } else { // if a small negative exp, then adjust we need to offset by the number // of leading zeros that will occur. - const min_exp_required = usize(-float_decimal.exp); + const min_exp_required = @intCast(usize, -float_decimal.exp); if (precision > min_exp_required) { round_digit = precision - min_exp_required; } @@ -107,16 +107,16 @@ fn errol3u(val: f64, buffer: []u8) FloatDecimal { // normalize the midpoint const e = math.frexp(val).exponent; - var exp = i16(math.floor(307 + f64(e) * 0.30103)); + var exp = @floatToInt(i16, math.floor(307 + @intToFloat(f64, e) * 0.30103)); if (exp < 20) { exp = 20; - } else if (usize(exp) >= lookup_table.len) { - exp = i16(lookup_table.len - 1); + } else if (@intCast(usize, exp) >= lookup_table.len) { + exp = @intCast(i16, lookup_table.len - 1); } - var mid = lookup_table[usize(exp)]; + var mid = lookup_table[@intCast(usize, exp)]; mid = hpProd(mid, val); - const lten = lookup_table[usize(exp)].val; + const lten = lookup_table[@intCast(usize, exp)].val; exp -= 307; @@ -168,25 +168,25 @@ fn errol3u(val: f64, buffer: []u8) FloatDecimal { // the 0-index for this extra digit. var buf_index: usize = 1; while (true) { - var hdig = u8(math.floor(high.val)); - if ((high.val == f64(hdig)) and (high.off < 0)) hdig -= 1; + var hdig = @floatToInt(u8, math.floor(high.val)); + if ((high.val == @intToFloat(f64, hdig)) and (high.off < 0)) hdig -= 1; - var ldig = u8(math.floor(low.val)); - if ((low.val == f64(ldig)) and (low.off < 0)) ldig -= 1; + var ldig = @floatToInt(u8, math.floor(low.val)); + if ((low.val == @intToFloat(f64, ldig)) and (low.off < 0)) ldig -= 1; if (ldig != hdig) break; buffer[buf_index] = hdig + '0'; buf_index += 1; - high.val -= f64(hdig); - low.val -= f64(ldig); + high.val -= @intToFloat(f64, hdig); + low.val -= @intToFloat(f64, ldig); hpMul10(&high); hpMul10(&low); } const tmp = (high.val + low.val) / 2.0; - var mdig = u8(math.floor(tmp + 0.5)); - if ((f64(mdig) - tmp) == 0.5 and (mdig & 0x1) != 0) mdig -= 1; + var mdig = @floatToInt(u8, math.floor(tmp + 0.5)); + if ((@intToFloat(f64, mdig) - tmp) == 0.5 and (mdig & 0x1) != 0) mdig -= 1; buffer[buf_index] = mdig + '0'; buf_index += 1; @@ -304,7 +304,7 @@ fn errolInt(val: f64, buffer: []u8) FloatDecimal { assert((val > 9.007199254740992e15) and val < (3.40282366920938e38)); - var mid = u128(val); + var mid = @floatToInt(u128, val); var low: u128 = mid - fpeint((fpnext(val) - val) / 2.0); var high: u128 = mid + fpeint((val - fpprev(val)) / 2.0); @@ -314,11 +314,11 @@ fn errolInt(val: f64, buffer: []u8) FloatDecimal { low -= 1; } - var l64 = u64(low % pow19); - const lf = u64((low / pow19) % pow19); + var l64 = @intCast(u64, low % pow19); + const lf = @intCast(u64, (low / pow19) % pow19); - var h64 = u64(high % pow19); - const hf = u64((high / pow19) % pow19); + var h64 = @intCast(u64, high % pow19); + const hf = @intCast(u64, (high / pow19) % pow19); if (lf != hf) { l64 = lf; @@ -348,7 +348,7 @@ fn errolInt(val: f64, buffer: []u8) FloatDecimal { return FloatDecimal{ .digits = buffer[0..buf_index], - .exp = i32(buf_index) + mi, + .exp = @intCast(i32, buf_index) + mi, }; } @@ -359,33 +359,33 @@ fn errolInt(val: f64, buffer: []u8) FloatDecimal { fn errolFixed(val: f64, buffer: []u8) FloatDecimal { assert((val >= 16.0) and (val < 9.007199254740992e15)); - const u = u64(val); - const n = f64(u); + const u = @floatToInt(u64, val); + const n = @intToFloat(f64, u); var mid = val - n; var lo = ((fpprev(val) - n) + mid) / 2.0; var hi = ((fpnext(val) - n) + mid) / 2.0; var buf_index = u64toa(u, buffer); - var exp = i32(buf_index); + var exp = @intCast(i32, buf_index); var j = buf_index; buffer[j] = 0; if (mid != 0.0) { while (mid != 0.0) { lo *= 10.0; - const ldig = i32(lo); - lo -= f64(ldig); + const ldig = @floatToInt(i32, lo); + lo -= @intToFloat(f64, ldig); mid *= 10.0; - const mdig = i32(mid); - mid -= f64(mdig); + const mdig = @floatToInt(i32, mid); + mid -= @intToFloat(f64, mdig); hi *= 10.0; - const hdig = i32(hi); - hi -= f64(hdig); + const hdig = @floatToInt(i32, hi); + hi -= @intToFloat(f64, hdig); - buffer[j] = u8(mdig + '0'); + buffer[j] = @intCast(u8, mdig + '0'); j += 1; if (hdig != ldig or j > 50) break; @@ -452,7 +452,7 @@ fn u64toa(value_param: u64, buffer: []u8) usize { var buf_index: usize = 0; if (value < kTen8) { - const v = u32(value); + const v = @intCast(u32, value); if (v < 10000) { const d1: u32 = (v / 100) << 1; const d2: u32 = (v % 100) << 1; @@ -507,8 +507,8 @@ fn u64toa(value_param: u64, buffer: []u8) usize { buf_index += 1; } } else if (value < kTen16) { - const v0: u32 = u32(value / kTen8); - const v1: u32 = u32(value % kTen8); + const v0: u32 = @intCast(u32, value / kTen8); + const v1: u32 = @intCast(u32, value % kTen8); const b0: u32 = v0 / 10000; const c0: u32 = v0 % 10000; @@ -578,11 +578,11 @@ fn u64toa(value_param: u64, buffer: []u8) usize { buffer[buf_index] = c_digits_lut[d8 + 1]; buf_index += 1; } else { - const a = u32(value / kTen16); // 1 to 1844 + const a = @intCast(u32, value / kTen16); // 1 to 1844 value %= kTen16; if (a < 10) { - buffer[buf_index] = '0' + u8(a); + buffer[buf_index] = '0' + @intCast(u8, a); buf_index += 1; } else if (a < 100) { const i: u32 = a << 1; @@ -591,7 +591,7 @@ fn u64toa(value_param: u64, buffer: []u8) usize { buffer[buf_index] = c_digits_lut[i + 1]; buf_index += 1; } else if (a < 1000) { - buffer[buf_index] = '0' + u8(a / 100); + buffer[buf_index] = '0' + @intCast(u8, a / 100); buf_index += 1; const i: u32 = (a % 100) << 1; @@ -612,8 +612,8 @@ fn u64toa(value_param: u64, buffer: []u8) usize { buf_index += 1; } - const v0 = u32(value / kTen8); - const v1 = u32(value % kTen8); + const v0 = @intCast(u32, value / kTen8); + const v1 = @intCast(u32, value % kTen8); const b0: u32 = v0 / 10000; const c0: u32 = v0 % 10000; diff --git a/std/fmt/index.zig b/std/fmt/index.zig index 90d3a559c4..f4dfa0e324 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -5,6 +5,7 @@ const assert = debug.assert; const mem = std.mem; const builtin = @import("builtin"); const errol = @import("errol/index.zig"); +const lossyCast = std.math.lossyCast; const max_int_digits = 65; @@ -463,7 +464,7 @@ pub fn formatFloatDecimal( errol.roundToPrecision(&float_decimal, precision, errol.RoundMode.Decimal); // exp < 0 means the leading is always 0 as errol result is normalized. - var num_digits_whole = if (float_decimal.exp > 0) usize(float_decimal.exp) else 0; + var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0; // the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this. var num_digits_whole_no_pad = math.min(num_digits_whole, float_decimal.digits.len); @@ -492,7 +493,7 @@ pub fn formatFloatDecimal( // Zero-fill until we reach significant digits or run out of precision. if (float_decimal.exp <= 0) { - const zero_digit_count = usize(-float_decimal.exp); + const zero_digit_count = @intCast(usize, -float_decimal.exp); const zeros_to_print = math.min(zero_digit_count, precision); var i: usize = 0; @@ -521,7 +522,7 @@ pub fn formatFloatDecimal( } } else { // exp < 0 means the leading is always 0 as errol result is normalized. - var num_digits_whole = if (float_decimal.exp > 0) usize(float_decimal.exp) else 0; + var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0; // the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this. var num_digits_whole_no_pad = math.min(num_digits_whole, float_decimal.digits.len); @@ -547,7 +548,7 @@ pub fn formatFloatDecimal( // Zero-fill until we reach significant digits or run out of precision. if (float_decimal.exp < 0) { - const zero_digit_count = usize(-float_decimal.exp); + const zero_digit_count = @intCast(usize, -float_decimal.exp); var i: usize = 0; while (i < zero_digit_count) : (i += 1) { @@ -578,7 +579,7 @@ pub fn formatBytes( 1024 => math.min(math.log2(value) / 10, mags_iec.len - 1), else => unreachable, }; - const new_value = f64(value) / math.pow(f64, f64(radix), f64(magnitude)); + const new_value = lossyCast(f64, value) / math.pow(f64, lossyCast(f64, radix), lossyCast(f64, magnitude)); const suffix = switch (radix) { 1000 => mags_si[magnitude], 1024 => mags_iec[magnitude], @@ -628,15 +629,15 @@ fn formatIntSigned( if (value < 0) { const minus_sign: u8 = '-'; try output(context, (*[1]u8)(&minus_sign)[0..]); - const new_value = uint(-(value + 1)) + 1; + const new_value = @intCast(uint, -(value + 1)) + 1; const new_width = if (width == 0) 0 else (width - 1); return formatIntUnsigned(new_value, base, uppercase, new_width, context, Errors, output); } else if (width == 0) { - return formatIntUnsigned(uint(value), base, uppercase, width, context, Errors, output); + return formatIntUnsigned(@intCast(uint, value), base, uppercase, width, context, Errors, output); } else { const plus_sign: u8 = '+'; try output(context, (*[1]u8)(&plus_sign)[0..]); - const new_value = uint(value); + const new_value = @intCast(uint, value); const new_width = if (width == 0) 0 else (width - 1); return formatIntUnsigned(new_value, base, uppercase, new_width, context, Errors, output); } @@ -660,7 +661,7 @@ fn formatIntUnsigned( while (true) { const digit = a % base; index -= 1; - buf[index] = digitToChar(u8(digit), uppercase); + buf[index] = digitToChar(@intCast(u8, digit), uppercase); a /= base; if (a == 0) break; } diff --git a/std/hash/crc.zig b/std/hash/crc.zig index ec831cdc2e..c455140785 100644 --- a/std/hash/crc.zig +++ b/std/hash/crc.zig @@ -26,7 +26,7 @@ pub fn Crc32WithPoly(comptime poly: u32) type { var tables: [8][256]u32 = undefined; for (tables[0]) |*e, i| { - var crc = u32(i); + var crc = @intCast(u32, i); var j: usize = 0; while (j < 8) : (j += 1) { if (crc & 1 == 1) { @@ -122,7 +122,7 @@ pub fn Crc32SmallWithPoly(comptime poly: u32) type { var table: [16]u32 = undefined; for (table) |*e, i| { - var crc = u32(i * 16); + var crc = @intCast(u32, i * 16); var j: usize = 0; while (j < 8) : (j += 1) { if (crc & 1 == 1) { diff --git a/std/hash/siphash.zig b/std/hash/siphash.zig index 8a90308a46..cdad77e59e 100644 --- a/std/hash/siphash.zig +++ b/std/hash/siphash.zig @@ -81,7 +81,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) // Remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); d.msg_len +%= @truncate(u8, b.len); } @@ -233,7 +233,7 @@ test "siphash64-2-4 sanity" { var buffer: [64]u8 = undefined; for (vectors) |vector, i| { - buffer[i] = u8(i); + buffer[i] = @intCast(u8, i); const expected = mem.readInt(vector, u64, Endian.Little); debug.assert(siphash.hash(test_key, buffer[0..i]) == expected); @@ -312,7 +312,7 @@ test "siphash128-2-4 sanity" { var buffer: [64]u8 = undefined; for (vectors) |vector, i| { - buffer[i] = u8(i); + buffer[i] = @intCast(u8, i); const expected = mem.readInt(vector, u128, Endian.Little); debug.assert(siphash.hash(test_key, buffer[0..i]) == expected); diff --git a/std/heap.zig b/std/heap.zig index 172bc24118..2a2c8c0b59 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -408,7 +408,7 @@ fn testAllocator(allocator: *mem.Allocator) !void { for (slice) |*item, i| { item.* = try allocator.create(i32); - item.*.* = i32(i); + item.*.* = @intCast(i32, i); } for (slice) |item, i| { diff --git a/std/json.zig b/std/json.zig index 8bbee981e3..2930cd21bb 100644 --- a/std/json.zig +++ b/std/json.zig @@ -180,7 +180,7 @@ pub const StreamingParser = struct { pub fn fromInt(x: var) State { debug.assert(x == 0 or x == 1); const T = @TagType(State); - return State(T(x)); + return State(@intCast(T, x)); } }; diff --git a/std/math/acos.zig b/std/math/acos.zig index 284f73fc91..54844e8f6e 100644 --- a/std/math/acos.zig +++ b/std/math/acos.zig @@ -95,12 +95,12 @@ fn acos64(x: f64) f64 { const pio2_lo: f64 = 6.12323399573676603587e-17; const ux = @bitCast(u64, x); - const hx = u32(ux >> 32); + const hx = @intCast(u32, ux >> 32); const ix = hx & 0x7FFFFFFF; // |x| >= 1 or nan if (ix >= 0x3FF00000) { - const lx = u32(ux & 0xFFFFFFFF); + const lx = @intCast(u32, ux & 0xFFFFFFFF); // acos(1) = 0, acos(-1) = pi if ((ix - 0x3FF00000) | lx == 0) { diff --git a/std/math/asin.zig b/std/math/asin.zig index 2ee3aa6048..30b3a57e32 100644 --- a/std/math/asin.zig +++ b/std/math/asin.zig @@ -87,12 +87,12 @@ fn asin64(x: f64) f64 { const pio2_lo: f64 = 6.12323399573676603587e-17; const ux = @bitCast(u64, x); - const hx = u32(ux >> 32); + const hx = @intCast(u32, ux >> 32); const ix = hx & 0x7FFFFFFF; // |x| >= 1 or nan if (ix >= 0x3FF00000) { - const lx = u32(ux & 0xFFFFFFFF); + const lx = @intCast(u32, ux & 0xFFFFFFFF); // asin(1) = +-pi/2 with inexact if ((ix - 0x3FF00000) | lx == 0) { diff --git a/std/math/atan.zig b/std/math/atan.zig index 7eceef98e3..6ca94dd84a 100644 --- a/std/math/atan.zig +++ b/std/math/atan.zig @@ -138,7 +138,7 @@ fn atan64(x_: f64) f64 { var x = x_; var ux = @bitCast(u64, x); - var ix = u32(ux >> 32); + var ix = @intCast(u32, ux >> 32); const sign = ix >> 31; ix &= 0x7FFFFFFF; @@ -159,7 +159,7 @@ fn atan64(x_: f64) f64 { // |x| < 2^(-27) if (ix < 0x3E400000) { if (ix < 0x00100000) { - math.forceEval(f32(x)); + math.forceEval(@floatCast(f32, x)); } return x; } diff --git a/std/math/atan2.zig b/std/math/atan2.zig index f0a8e67c46..b3e45ba045 100644 --- a/std/math/atan2.zig +++ b/std/math/atan2.zig @@ -124,12 +124,12 @@ fn atan2_64(y: f64, x: f64) f64 { } var ux = @bitCast(u64, x); - var ix = u32(ux >> 32); - var lx = u32(ux & 0xFFFFFFFF); + var ix = @intCast(u32, ux >> 32); + var lx = @intCast(u32, ux & 0xFFFFFFFF); var uy = @bitCast(u64, y); - var iy = u32(uy >> 32); - var ly = u32(uy & 0xFFFFFFFF); + var iy = @intCast(u32, uy >> 32); + var ly = @intCast(u32, uy & 0xFFFFFFFF); // x = 1.0 if ((ix -% 0x3FF00000) | lx == 0) { diff --git a/std/math/atanh.zig b/std/math/atanh.zig index 8ca0cc85bc..4ae8a66bc0 100644 --- a/std/math/atanh.zig +++ b/std/math/atanh.zig @@ -62,7 +62,7 @@ fn atanh_64(x: f64) f64 { if (e < 0x3FF - 32) { // underflow if (e == 0) { - math.forceEval(f32(y)); + math.forceEval(@floatCast(f32, y)); } } // |x| < 0.5 diff --git a/std/math/big/int.zig b/std/math/big/int.zig index 5e15cfb895..21d9347c01 100644 --- a/std/math/big/int.zig +++ b/std/math/big/int.zig @@ -135,7 +135,7 @@ pub const Int = struct { self.positive = value >= 0; self.len = 0; - var w_value: UT = if (value < 0) UT(-value) else UT(value); + var w_value: UT = if (value < 0) @intCast(UT, -value) else @intCast(UT, value); if (info.bits <= Limb.bit_count) { self.limbs[0] = Limb(w_value); @@ -198,7 +198,7 @@ pub const Int = struct { var r: UT = 0; if (@sizeOf(UT) <= @sizeOf(Limb)) { - r = UT(self.limbs[0]); + r = @intCast(UT, self.limbs[0]); } else { for (self.limbs[0..self.len]) |_, ri| { const limb = self.limbs[self.len - ri - 1]; @@ -210,7 +210,7 @@ pub const Int = struct { if (!T.is_signed) { return if (self.positive) r else error.NegativeIntoUnsigned; } else { - return if (self.positive) T(r) else -T(r); + return if (self.positive) @intCast(T, r) else -@intCast(T, r); } }, else => { @@ -295,7 +295,7 @@ pub const Int = struct { for (self.limbs[0..self.len]) |limb| { var shift: usize = 0; while (shift < Limb.bit_count) : (shift += base_shift) { - const r = u8((limb >> Log2Limb(shift)) & Limb(base - 1)); + const r = @intCast(u8, (limb >> @intCast(Log2Limb, shift)) & Limb(base - 1)); const ch = try digitToChar(r, base); try digits.append(ch); } @@ -329,7 +329,7 @@ pub const Int = struct { var r_word = r.limbs[0]; var i: usize = 0; while (i < digits_per_limb) : (i += 1) { - const ch = try digitToChar(u8(r_word % base), base); + const ch = try digitToChar(@intCast(u8, r_word % base), base); r_word /= base; try digits.append(ch); } @@ -340,7 +340,7 @@ pub const Int = struct { var r_word = q.limbs[0]; while (r_word != 0) { - const ch = try digitToChar(u8(r_word % base), base); + const ch = try digitToChar(@intCast(u8, r_word % base), base); r_word /= base; try digits.append(ch); } @@ -801,7 +801,7 @@ pub const Int = struct { q.limbs[i - t - 1] = @maxValue(Limb); } else { const num = (DoubleLimb(x.limbs[i]) << Limb.bit_count) | DoubleLimb(x.limbs[i - 1]); - const z = Limb(num / DoubleLimb(y.limbs[t])); + const z = @intCast(Limb, num / DoubleLimb(y.limbs[t])); q.limbs[i - t - 1] = if (z > @maxValue(Limb)) @maxValue(Limb) else Limb(z); } @@ -860,7 +860,7 @@ pub const Int = struct { debug.assert(r.len >= a.len + (shift / Limb.bit_count) + 1); const limb_shift = shift / Limb.bit_count + 1; - const interior_limb_shift = Log2Limb(shift % Limb.bit_count); + const interior_limb_shift = @intCast(Log2Limb, shift % Limb.bit_count); var carry: Limb = 0; var i: usize = 0; @@ -869,7 +869,7 @@ pub const Int = struct { const dst_i = src_i + limb_shift; const src_digit = a[src_i]; - r[dst_i] = carry | @inlineCall(math.shr, Limb, src_digit, Limb.bit_count - Limb(interior_limb_shift)); + r[dst_i] = carry | @inlineCall(math.shr, Limb, src_digit, Limb.bit_count - @intCast(Limb, interior_limb_shift)); carry = (src_digit << interior_limb_shift); } @@ -898,7 +898,7 @@ pub const Int = struct { debug.assert(r.len >= a.len - (shift / Limb.bit_count)); const limb_shift = shift / Limb.bit_count; - const interior_limb_shift = Log2Limb(shift % Limb.bit_count); + const interior_limb_shift = @intCast(Log2Limb, shift % Limb.bit_count); var carry: Limb = 0; var i: usize = 0; @@ -908,7 +908,7 @@ pub const Int = struct { const src_digit = a[src_i]; r[dst_i] = carry | (src_digit >> interior_limb_shift); - carry = @inlineCall(math.shl, Limb, src_digit, Limb.bit_count - Limb(interior_limb_shift)); + carry = @inlineCall(math.shl, Limb, src_digit, Limb.bit_count - @intCast(Limb, interior_limb_shift)); } } diff --git a/std/math/cbrt.zig b/std/math/cbrt.zig index cd3b71ca8a..c067c5155a 100644 --- a/std/math/cbrt.zig +++ b/std/math/cbrt.zig @@ -54,7 +54,7 @@ fn cbrt32(x: f32) f32 { r = t * t * t; t = t * (f64(x) + x + r) / (x + r + r); - return f32(t); + return @floatCast(f32, t); } fn cbrt64(x: f64) f64 { @@ -69,7 +69,7 @@ fn cbrt64(x: f64) f64 { const P4: f64 = 0.145996192886612446982; var u = @bitCast(u64, x); - var hx = u32(u >> 32) & 0x7FFFFFFF; + var hx = @intCast(u32, u >> 32) & 0x7FFFFFFF; // cbrt(nan, inf) = itself if (hx >= 0x7FF00000) { @@ -79,7 +79,7 @@ fn cbrt64(x: f64) f64 { // cbrt to ~5bits if (hx < 0x00100000) { u = @bitCast(u64, x * 0x1.0p54); - hx = u32(u >> 32) & 0x7FFFFFFF; + hx = @intCast(u32, u >> 32) & 0x7FFFFFFF; // cbrt(0) is itself if (hx == 0) { diff --git a/std/math/ceil.zig b/std/math/ceil.zig index a189bb66d2..1c429504e8 100644 --- a/std/math/ceil.zig +++ b/std/math/ceil.zig @@ -20,7 +20,7 @@ pub fn ceil(x: var) @typeOf(x) { fn ceil32(x: f32) f32 { var u = @bitCast(u32, x); - var e = i32((u >> 23) & 0xFF) - 0x7F; + var e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F; var m: u32 = undefined; // TODO: Shouldn't need this explicit check. @@ -31,7 +31,7 @@ fn ceil32(x: f32) f32 { if (e >= 23) { return x; } else if (e >= 0) { - m = u32(0x007FFFFF) >> u5(e); + m = u32(0x007FFFFF) >> @intCast(u5, e); if (u & m == 0) { return x; } diff --git a/std/math/complex/atan.zig b/std/math/complex/atan.zig index 9bfe5fe724..de60f2546d 100644 --- a/std/math/complex/atan.zig +++ b/std/math/complex/atan.zig @@ -4,7 +4,7 @@ const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; -pub fn atan(z: var) Complex(@typeOf(z.re)) { +pub fn atan(z: var) @typeOf(z) { const T = @typeOf(z.re); return switch (T) { f32 => atan32(z), @@ -25,11 +25,11 @@ fn redupif32(x: f32) f32 { t -= 0.5; } - const u = f32(i32(t)); + const u = @intToFloat(f32, @floatToInt(i32, t)); return ((x - u * DP1) - u * DP2) - t * DP3; } -fn atan32(z: *const Complex(f32)) Complex(f32) { +fn atan32(z: Complex(f32)) Complex(f32) { const maxnum = 1.0e38; const x = z.re; @@ -74,11 +74,11 @@ fn redupif64(x: f64) f64 { t -= 0.5; } - const u = f64(i64(t)); + const u = @intToFloat(f64, @floatToInt(i64, t)); return ((x - u * DP1) - u * DP2) - t * DP3; } -fn atan64(z: *const Complex(f64)) Complex(f64) { +fn atan64(z: Complex(f64)) Complex(f64) { const maxnum = 1.0e308; const x = z.re; diff --git a/std/math/complex/cosh.zig b/std/math/complex/cosh.zig index c2f9a47b8d..a2e31631ea 100644 --- a/std/math/complex/cosh.zig +++ b/std/math/complex/cosh.zig @@ -83,12 +83,12 @@ fn cosh64(z: *const Complex(f64)) Complex(f64) { const y = z.im; const fx = @bitCast(u64, x); - const hx = u32(fx >> 32); + const hx = @intCast(u32, fx >> 32); const lx = @truncate(u32, fx); const ix = hx & 0x7fffffff; const fy = @bitCast(u64, y); - const hy = u32(fy >> 32); + const hy = @intCast(u32, fy >> 32); const ly = @truncate(u32, fy); const iy = hy & 0x7fffffff; diff --git a/std/math/complex/exp.zig b/std/math/complex/exp.zig index 44c354f246..48fb132d97 100644 --- a/std/math/complex/exp.zig +++ b/std/math/complex/exp.zig @@ -6,7 +6,7 @@ const Complex = cmath.Complex; const ldexp_cexp = @import("ldexp.zig").ldexp_cexp; -pub fn exp(z: var) Complex(@typeOf(z.re)) { +pub fn exp(z: var) @typeOf(z) { const T = @typeOf(z.re); return switch (T) { @@ -16,7 +16,7 @@ pub fn exp(z: var) Complex(@typeOf(z.re)) { }; } -fn exp32(z: *const Complex(f32)) Complex(f32) { +fn exp32(z: Complex(f32)) Complex(f32) { @setFloatMode(this, @import("builtin").FloatMode.Strict); const exp_overflow = 0x42b17218; // max_exp * ln2 ~= 88.72283955 @@ -63,7 +63,7 @@ fn exp32(z: *const Complex(f32)) Complex(f32) { } } -fn exp64(z: *const Complex(f64)) Complex(f64) { +fn exp64(z: Complex(f64)) Complex(f64) { const exp_overflow = 0x40862e42; // high bits of max_exp * ln2 ~= 710 const cexp_overflow = 0x4096b8e4; // (max_exp - min_denorm_exp) * ln2 diff --git a/std/math/complex/ldexp.zig b/std/math/complex/ldexp.zig index a56c2ef2eb..e919ef6bec 100644 --- a/std/math/complex/ldexp.zig +++ b/std/math/complex/ldexp.zig @@ -4,7 +4,7 @@ const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; -pub fn ldexp_cexp(z: var, expt: i32) Complex(@typeOf(z.re)) { +pub fn ldexp_cexp(z: var, expt: i32) @typeOf(z) { const T = @typeOf(z.re); return switch (T) { @@ -20,11 +20,12 @@ fn frexp_exp32(x: f32, expt: *i32) f32 { const exp_x = math.exp(x - kln2); const hx = @bitCast(u32, exp_x); - expt.* = i32(hx >> 23) - (0x7f + 127) + k; + // TODO zig should allow this cast implicitly because it should know the value is in range + expt.* = @intCast(i32, hx >> 23) - (0x7f + 127) + k; return @bitCast(f32, (hx & 0x7fffff) | ((0x7f + 127) << 23)); } -fn ldexp_cexp32(z: *const Complex(f32), expt: i32) Complex(f32) { +fn ldexp_cexp32(z: Complex(f32), expt: i32) Complex(f32) { var ex_expt: i32 = undefined; const exp_x = frexp_exp32(z.re, &ex_expt); const exptf = expt + ex_expt; @@ -45,16 +46,16 @@ fn frexp_exp64(x: f64, expt: *i32) f64 { const exp_x = math.exp(x - kln2); const fx = @bitCast(u64, x); - const hx = u32(fx >> 32); + const hx = @intCast(u32, fx >> 32); const lx = @truncate(u32, fx); - expt.* = i32(hx >> 20) - (0x3ff + 1023) + k; + expt.* = @intCast(i32, hx >> 20) - (0x3ff + 1023) + k; const high_word = (hx & 0xfffff) | ((0x3ff + 1023) << 20); return @bitCast(f64, (u64(high_word) << 32) | lx); } -fn ldexp_cexp64(z: *const Complex(f64), expt: i32) Complex(f64) { +fn ldexp_cexp64(z: Complex(f64), expt: i32) Complex(f64) { var ex_expt: i32 = undefined; const exp_x = frexp_exp64(z.re, &ex_expt); const exptf = i64(expt + ex_expt); diff --git a/std/math/complex/sinh.zig b/std/math/complex/sinh.zig index 3d196bfd50..ab23c5c74d 100644 --- a/std/math/complex/sinh.zig +++ b/std/math/complex/sinh.zig @@ -6,7 +6,7 @@ const Complex = cmath.Complex; const ldexp_cexp = @import("ldexp.zig").ldexp_cexp; -pub fn sinh(z: var) Complex(@typeOf(z.re)) { +pub fn sinh(z: var) @typeOf(z) { const T = @typeOf(z.re); return switch (T) { f32 => sinh32(z), @@ -15,7 +15,7 @@ pub fn sinh(z: var) Complex(@typeOf(z.re)) { }; } -fn sinh32(z: *const Complex(f32)) Complex(f32) { +fn sinh32(z: Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; @@ -78,17 +78,17 @@ fn sinh32(z: *const Complex(f32)) Complex(f32) { return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y)); } -fn sinh64(z: *const Complex(f64)) Complex(f64) { +fn sinh64(z: Complex(f64)) Complex(f64) { const x = z.re; const y = z.im; const fx = @bitCast(u64, x); - const hx = u32(fx >> 32); + const hx = @intCast(u32, fx >> 32); const lx = @truncate(u32, fx); const ix = hx & 0x7fffffff; const fy = @bitCast(u64, y); - const hy = u32(fy >> 32); + const hy = @intCast(u32, fy >> 32); const ly = @truncate(u32, fy); const iy = hy & 0x7fffffff; diff --git a/std/math/complex/sqrt.zig b/std/math/complex/sqrt.zig index caa3bd2868..47367816f7 100644 --- a/std/math/complex/sqrt.zig +++ b/std/math/complex/sqrt.zig @@ -49,10 +49,16 @@ fn sqrt32(z: Complex(f32)) Complex(f32) { if (dx >= 0) { const t = math.sqrt((dx + math.hypot(f64, dx, dy)) * 0.5); - return Complex(f32).new(f32(t), f32(dy / (2.0 * t))); + return Complex(f32).new( + @floatCast(f32, t), + @floatCast(f32, dy / (2.0 * t)), + ); } else { const t = math.sqrt((-dx + math.hypot(f64, dx, dy)) * 0.5); - return Complex(f32).new(f32(math.fabs(y) / (2.0 * t)), f32(math.copysign(f64, t, y))); + return Complex(f32).new( + @floatCast(f32, math.fabs(y) / (2.0 * t)), + @floatCast(f32, math.copysign(f64, t, y)), + ); } } diff --git a/std/math/complex/tanh.zig b/std/math/complex/tanh.zig index 1d754838a3..e48d438783 100644 --- a/std/math/complex/tanh.zig +++ b/std/math/complex/tanh.zig @@ -4,7 +4,7 @@ const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; -pub fn tanh(z: var) Complex(@typeOf(z.re)) { +pub fn tanh(z: var) @typeOf(z) { const T = @typeOf(z.re); return switch (T) { f32 => tanh32(z), @@ -13,7 +13,7 @@ pub fn tanh(z: var) Complex(@typeOf(z.re)) { }; } -fn tanh32(z: *const Complex(f32)) Complex(f32) { +fn tanh32(z: Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; @@ -51,12 +51,14 @@ fn tanh32(z: *const Complex(f32)) Complex(f32) { return Complex(f32).new((beta * rho * s) / den, t / den); } -fn tanh64(z: *const Complex(f64)) Complex(f64) { +fn tanh64(z: Complex(f64)) Complex(f64) { const x = z.re; const y = z.im; const fx = @bitCast(u64, x); - const hx = u32(fx >> 32); + // TODO: zig should allow this conversion implicitly because it can notice that the value necessarily + // fits in range. + const hx = @intCast(u32, fx >> 32); const lx = @truncate(u32, fx); const ix = hx & 0x7fffffff; diff --git a/std/math/cos.zig b/std/math/cos.zig index 5e5ec4f1cb..71d5e4a8f6 100644 --- a/std/math/cos.zig +++ b/std/math/cos.zig @@ -55,7 +55,7 @@ fn cos32(x_: f32) f32 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; @@ -106,7 +106,7 @@ fn cos64(x_: f64) f64 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; diff --git a/std/math/cosh.zig b/std/math/cosh.zig index fa46219986..52beafb642 100644 --- a/std/math/cosh.zig +++ b/std/math/cosh.zig @@ -49,7 +49,7 @@ fn cosh32(x: f32) f32 { fn cosh64(x: f64) f64 { const u = @bitCast(u64, x); - const w = u32(u >> 32); + const w = @intCast(u32, u >> 32); const ax = @bitCast(f64, u & (@maxValue(u64) >> 1)); // TODO: Shouldn't need this explicit check. diff --git a/std/math/exp.zig b/std/math/exp.zig index 76dc47d04b..d6185d4f0b 100644 --- a/std/math/exp.zig +++ b/std/math/exp.zig @@ -29,7 +29,7 @@ fn exp32(x_: f32) f32 { var x = x_; var hx = @bitCast(u32, x); - const sign = i32(hx >> 31); + const sign = @intCast(i32, hx >> 31); hx &= 0x7FFFFFFF; if (math.isNan(x)) { @@ -63,12 +63,12 @@ fn exp32(x_: f32) f32 { if (hx > 0x3EB17218) { // |x| > 1.5 * ln2 if (hx > 0x3F851592) { - k = i32(invln2 * x + half[usize(sign)]); + k = @floatToInt(i32, invln2 * x + half[@intCast(usize, sign)]); } else { k = 1 - sign - sign; } - const fk = f32(k); + const fk = @intToFloat(f32, k); hi = x - fk * ln2hi; lo = fk * ln2lo; x = hi - lo; @@ -110,7 +110,7 @@ fn exp64(x_: f64) f64 { var x = x_; var ux = @bitCast(u64, x); var hx = ux >> 32; - const sign = i32(hx >> 31); + const sign = @intCast(i32, hx >> 31); hx &= 0x7FFFFFFF; if (math.isNan(x)) { @@ -148,12 +148,12 @@ fn exp64(x_: f64) f64 { if (hx > 0x3EB17218) { // |x| >= 1.5 * ln2 if (hx > 0x3FF0A2B2) { - k = i32(invln2 * x + half[usize(sign)]); + k = @floatToInt(i32, invln2 * x + half[@intCast(usize, sign)]); } else { k = 1 - sign - sign; } - const dk = f64(k); + const dk = @intToFloat(f64, k); hi = x - dk * ln2hi; lo = dk * ln2lo; x = hi - lo; diff --git a/std/math/exp2.zig b/std/math/exp2.zig index 62a3eb85b6..90ea088181 100644 --- a/std/math/exp2.zig +++ b/std/math/exp2.zig @@ -38,8 +38,8 @@ const exp2ft = []const f64{ fn exp2_32(x: f32) f32 { @setFloatMode(this, @import("builtin").FloatMode.Strict); - const tblsiz = u32(exp2ft.len); - const redux: f32 = 0x1.8p23 / f32(tblsiz); + const tblsiz = @intCast(u32, exp2ft.len); + const redux: f32 = 0x1.8p23 / @intToFloat(f32, tblsiz); const P1: f32 = 0x1.62e430p-1; const P2: f32 = 0x1.ebfbe0p-3; const P3: f32 = 0x1.c6b348p-5; @@ -89,7 +89,7 @@ fn exp2_32(x: f32) f32 { var r: f64 = exp2ft[i0]; const t: f64 = r * z; r = r + t * (P1 + z * P2) + t * (z * z) * (P3 + z * P4); - return f32(r * uk); + return @floatCast(f32, r * uk); } const exp2dt = []f64{ @@ -355,8 +355,8 @@ const exp2dt = []f64{ fn exp2_64(x: f64) f64 { @setFloatMode(this, @import("builtin").FloatMode.Strict); - const tblsiz = u32(exp2dt.len / 2); - const redux: f64 = 0x1.8p52 / f64(tblsiz); + const tblsiz = @intCast(u32, exp2dt.len / 2); + const redux: f64 = 0x1.8p52 / @intToFloat(f64, tblsiz); const P1: f64 = 0x1.62e42fefa39efp-1; const P2: f64 = 0x1.ebfbdff82c575p-3; const P3: f64 = 0x1.c6b08d704a0a6p-5; @@ -364,7 +364,7 @@ fn exp2_64(x: f64) f64 { const P5: f64 = 0x1.5d88003875c74p-10; const ux = @bitCast(u64, x); - const ix = u32(ux >> 32) & 0x7FFFFFFF; + const ix = @intCast(u32, ux >> 32) & 0x7FFFFFFF; // TODO: This should be handled beneath. if (math.isNan(x)) { @@ -386,7 +386,7 @@ fn exp2_64(x: f64) f64 { if (ux >> 63 != 0) { // underflow if (x <= -1075 or x - 0x1.0p52 + 0x1.0p52 != x) { - math.forceEval(f32(-0x1.0p-149 / x)); + math.forceEval(@floatCast(f32, -0x1.0p-149 / x)); } if (x <= -1075) { return 0; diff --git a/std/math/expm1.zig b/std/math/expm1.zig index 11af1b215f..438e44ccce 100644 --- a/std/math/expm1.zig +++ b/std/math/expm1.zig @@ -78,8 +78,8 @@ fn expm1_32(x_: f32) f32 { kf += 0.5; } - k = i32(kf); - const t = f32(k); + k = @floatToInt(i32, kf); + const t = @intToFloat(f32, k); hi = x - t * ln2_hi; lo = t * ln2_lo; } @@ -123,7 +123,7 @@ fn expm1_32(x_: f32) f32 { } } - const twopk = @bitCast(f32, u32((0x7F +% k) << 23)); + const twopk = @bitCast(f32, @intCast(u32, (0x7F +% k) << 23)); if (k < 0 or k > 56) { var y = x - e + 1.0; @@ -136,7 +136,7 @@ fn expm1_32(x_: f32) f32 { return y - 1.0; } - const uf = @bitCast(f32, u32(0x7F -% k) << 23); + const uf = @bitCast(f32, @intCast(u32, 0x7F -% k) << 23); if (k < 23) { return (x - e + (1 - uf)) * twopk; } else { @@ -158,7 +158,7 @@ fn expm1_64(x_: f64) f64 { var x = x_; const ux = @bitCast(u64, x); - const hx = u32(ux >> 32) & 0x7FFFFFFF; + const hx = @intCast(u32, ux >> 32) & 0x7FFFFFFF; const sign = ux >> 63; if (math.isNegativeInf(x)) { @@ -207,8 +207,8 @@ fn expm1_64(x_: f64) f64 { kf += 0.5; } - k = i32(kf); - const t = f64(k); + k = @floatToInt(i32, kf); + const t = @intToFloat(f64, k); hi = x - t * ln2_hi; lo = t * ln2_lo; } @@ -219,7 +219,7 @@ fn expm1_64(x_: f64) f64 { // |x| < 2^(-54) else if (hx < 0x3C900000) { if (hx < 0x00100000) { - math.forceEval(f32(x)); + math.forceEval(@floatCast(f32, x)); } return x; } else { @@ -252,7 +252,7 @@ fn expm1_64(x_: f64) f64 { } } - const twopk = @bitCast(f64, u64(0x3FF +% k) << 52); + const twopk = @bitCast(f64, @intCast(u64, 0x3FF +% k) << 52); if (k < 0 or k > 56) { var y = x - e + 1.0; @@ -265,7 +265,7 @@ fn expm1_64(x_: f64) f64 { return y - 1.0; } - const uf = @bitCast(f64, u64(0x3FF -% k) << 52); + const uf = @bitCast(f64, @intCast(u64, 0x3FF -% k) << 52); if (k < 20) { return (x - e + (1 - uf)) * twopk; } else { diff --git a/std/math/floor.zig b/std/math/floor.zig index 7d5364787f..79d1097d08 100644 --- a/std/math/floor.zig +++ b/std/math/floor.zig @@ -20,7 +20,7 @@ pub fn floor(x: var) @typeOf(x) { fn floor32(x: f32) f32 { var u = @bitCast(u32, x); - const e = i32((u >> 23) & 0xFF) - 0x7F; + const e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F; var m: u32 = undefined; // TODO: Shouldn't need this explicit check. @@ -33,7 +33,7 @@ fn floor32(x: f32) f32 { } if (e >= 0) { - m = u32(0x007FFFFF) >> u5(e); + m = u32(0x007FFFFF) >> @intCast(u5, e); if (u & m == 0) { return x; } diff --git a/std/math/fma.zig b/std/math/fma.zig index 3e9214f35b..21faf4118d 100644 --- a/std/math/fma.zig +++ b/std/math/fma.zig @@ -17,10 +17,10 @@ fn fma32(x: f32, y: f32, z: f32) f32 { const e = (u >> 52) & 0x7FF; if ((u & 0x1FFFFFFF) != 0x10000000 or e == 0x7FF or xy_z - xy == z) { - return f32(xy_z); + return @floatCast(f32, xy_z); } else { // TODO: Handle inexact case with double-rounding - return f32(xy_z); + return @floatCast(f32, xy_z); } } @@ -124,7 +124,7 @@ fn add_and_denorm(a: f64, b: f64, scale: i32) f64 { var sum = dd_add(a, b); if (sum.lo != 0) { var uhii = @bitCast(u64, sum.hi); - const bits_lost = -i32((uhii >> 52) & 0x7FF) - scale + 1; + const bits_lost = -@intCast(i32, (uhii >> 52) & 0x7FF) - scale + 1; if ((bits_lost != 1) == (uhii & 1 != 0)) { const uloi = @bitCast(u64, sum.lo); uhii += 1 - (((uhii ^ uloi) >> 62) & 2); diff --git a/std/math/frexp.zig b/std/math/frexp.zig index b58af0a9bc..dfc790fdd9 100644 --- a/std/math/frexp.zig +++ b/std/math/frexp.zig @@ -30,7 +30,7 @@ fn frexp32(x: f32) frexp32_result { var result: frexp32_result = undefined; var y = @bitCast(u32, x); - const e = i32(y >> 23) & 0xFF; + const e = @intCast(i32, y >> 23) & 0xFF; if (e == 0) { if (x != 0) { @@ -67,7 +67,7 @@ fn frexp64(x: f64) frexp64_result { var result: frexp64_result = undefined; var y = @bitCast(u64, x); - const e = i32(y >> 52) & 0x7FF; + const e = @intCast(i32, y >> 52) & 0x7FF; if (e == 0) { if (x != 0) { diff --git a/std/math/hypot.zig b/std/math/hypot.zig index 494df22ba6..f834f422e6 100644 --- a/std/math/hypot.zig +++ b/std/math/hypot.zig @@ -49,7 +49,7 @@ fn hypot32(x: f32, y: f32) f32 { yy *= 0x1.0p-90; } - return z * math.sqrt(f32(f64(x) * x + f64(y) * y)); + return z * math.sqrt(@floatCast(f32, f64(x) * x + f64(y) * y)); } fn sq(hi: *f64, lo: *f64, x: f64) void { diff --git a/std/math/ilogb.zig b/std/math/ilogb.zig index f1f33aff55..a24f580a32 100644 --- a/std/math/ilogb.zig +++ b/std/math/ilogb.zig @@ -23,7 +23,7 @@ const fp_ilogb0 = fp_ilogbnan; fn ilogb32(x: f32) i32 { var u = @bitCast(u32, x); - var e = i32((u >> 23) & 0xFF); + var e = @intCast(i32, (u >> 23) & 0xFF); // TODO: We should be able to merge this with the lower check. if (math.isNan(x)) { @@ -59,7 +59,7 @@ fn ilogb32(x: f32) i32 { fn ilogb64(x: f64) i32 { var u = @bitCast(u64, x); - var e = i32((u >> 52) & 0x7FF); + var e = @intCast(i32, (u >> 52) & 0x7FF); if (math.isNan(x)) { return @maxValue(i32); diff --git a/std/math/index.zig b/std/math/index.zig index 99e5b4ecf1..176293be74 100644 --- a/std/math/index.zig +++ b/std/math/index.zig @@ -227,7 +227,7 @@ pub fn shlExact(comptime T: type, a: T, shift_amt: Log2Int(T)) !T { /// A negative shift amount results in a right shift. pub fn shl(comptime T: type, a: T, shift_amt: var) T { const abs_shift_amt = absCast(shift_amt); - const casted_shift_amt = if (abs_shift_amt >= T.bit_count) return 0 else Log2Int(T)(abs_shift_amt); + const casted_shift_amt = if (abs_shift_amt >= T.bit_count) return 0 else @intCast(Log2Int(T), abs_shift_amt); if (@typeOf(shift_amt).is_signed) { if (shift_amt >= 0) { @@ -251,7 +251,7 @@ test "math.shl" { /// A negative shift amount results in a lefft shift. pub fn shr(comptime T: type, a: T, shift_amt: var) T { const abs_shift_amt = absCast(shift_amt); - const casted_shift_amt = if (abs_shift_amt >= T.bit_count) return 0 else Log2Int(T)(abs_shift_amt); + const casted_shift_amt = if (abs_shift_amt >= T.bit_count) return 0 else @intCast(Log2Int(T), abs_shift_amt); if (@typeOf(shift_amt).is_signed) { if (shift_amt >= 0) { @@ -473,9 +473,9 @@ fn testRem() void { /// Result is an unsigned integer. pub fn absCast(x: var) @IntType(false, @typeOf(x).bit_count) { const uint = @IntType(false, @typeOf(x).bit_count); - if (x >= 0) return uint(x); + if (x >= 0) return @intCast(uint, x); - return uint(-(x + 1)) + 1; + return @intCast(uint, -(x + 1)) + 1; } test "math.absCast" { @@ -499,7 +499,7 @@ pub fn negateCast(x: var) !@IntType(true, @typeOf(x).bit_count) { if (x == -@minValue(int)) return @minValue(int); - return -int(x); + return -@intCast(int, x); } test "math.negateCast" { @@ -522,7 +522,7 @@ pub fn cast(comptime T: type, x: var) (error{Overflow}!T) { } else if (@minValue(@typeOf(x)) < @minValue(T) and x < @minValue(T)) { return error.Overflow; } else { - return T(x); + return @intCast(T, x); } } @@ -565,7 +565,7 @@ test "math.floorPowerOfTwo" { pub fn log2_int(comptime T: type, x: T) Log2Int(T) { assert(x != 0); - return Log2Int(T)(T.bit_count - 1 - @clz(x)); + return @intCast(Log2Int(T), T.bit_count - 1 - @clz(x)); } pub fn log2_int_ceil(comptime T: type, x: T) Log2Int(T) { @@ -597,3 +597,14 @@ fn testFloorPowerOfTwo() void { assert(floorPowerOfTwo(u4, 8) == 8); assert(floorPowerOfTwo(u4, 9) == 8); } + +pub fn lossyCast(comptime T: type, value: var) T { + switch (@typeInfo(@typeOf(value))) { + builtin.TypeId.Int => return @intToFloat(T, value), + builtin.TypeId.Float => return @floatCast(T, value), + builtin.TypeId.ComptimeInt => return T(value), + builtin.TypeId.ComptimeFloat => return T(value), + else => @compileError("bad type"), + } +} + diff --git a/std/math/ln.zig b/std/math/ln.zig index 3fd75977b9..e78cc379e0 100644 --- a/std/math/ln.zig +++ b/std/math/ln.zig @@ -71,7 +71,7 @@ pub fn ln_32(x_: f32) f32 { // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; - k += i32(ix >> 23) - 0x7F; + k += @intCast(i32, ix >> 23) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @bitCast(f32, ix); @@ -83,7 +83,7 @@ pub fn ln_32(x_: f32) f32 { const t2 = z * (Lg1 + w * Lg3); const R = t2 + t1; const hfsq = 0.5 * f * f; - const dk = f32(k); + const dk = @intToFloat(f32, k); return s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi; } @@ -103,7 +103,7 @@ pub fn ln_64(x_: f64) f64 { var x = x_; var ix = @bitCast(u64, x); - var hx = u32(ix >> 32); + var hx = @intCast(u32, ix >> 32); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { @@ -119,7 +119,7 @@ pub fn ln_64(x_: f64) f64 { // subnormal, scale x k -= 54; x *= 0x1.0p54; - hx = u32(@bitCast(u64, ix) >> 32); + hx = @intCast(u32, @bitCast(u64, ix) >> 32); } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { @@ -128,7 +128,7 @@ pub fn ln_64(x_: f64) f64 { // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; - k += i32(hx >> 20) - 0x3FF; + k += @intCast(i32, hx >> 20) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (u64(hx) << 32) | (ix & 0xFFFFFFFF); x = @bitCast(f64, ix); @@ -141,7 +141,7 @@ pub fn ln_64(x_: f64) f64 { const t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); const R = t2 + t1; - const dk = f64(k); + const dk = @intToFloat(f64, k); return s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi; } diff --git a/std/math/log.zig b/std/math/log.zig index 2c876081d8..20b6d055e8 100644 --- a/std/math/log.zig +++ b/std/math/log.zig @@ -13,22 +13,23 @@ pub fn log(comptime T: type, base: T, x: T) T { return math.ln(x); } + const float_base = math.lossyCast(f64, base); switch (@typeId(T)) { TypeId.ComptimeFloat => { - return @typeOf(1.0)(math.ln(f64(x)) / math.ln(f64(base))); + return @typeOf(1.0)(math.ln(f64(x)) / math.ln(float_base)); }, TypeId.ComptimeInt => { - return @typeOf(1)(math.floor(math.ln(f64(x)) / math.ln(f64(base)))); + return @typeOf(1)(math.floor(math.ln(f64(x)) / math.ln(float_base))); }, builtin.TypeId.Int => { // TODO implement integer log without using float math - return T(math.floor(math.ln(f64(x)) / math.ln(f64(base)))); + return @floatToInt(T, math.floor(math.ln(@intToFloat(f64, x)) / math.ln(float_base))); }, builtin.TypeId.Float => { switch (T) { - f32 => return f32(math.ln(f64(x)) / math.ln(f64(base))), - f64 => return math.ln(x) / math.ln(f64(base)), + f32 => return @floatCast(f32, math.ln(f64(x)) / math.ln(float_base)), + f64 => return math.ln(x) / math.ln(float_base), else => @compileError("log not implemented for " ++ @typeName(T)), } }, diff --git a/std/math/log10.zig b/std/math/log10.zig index c444add9ac..a93ce48fb7 100644 --- a/std/math/log10.zig +++ b/std/math/log10.zig @@ -28,7 +28,7 @@ pub fn log10(x: var) @typeOf(x) { return @typeOf(1)(math.floor(log10_64(f64(x)))); }, TypeId.Int => { - return T(math.floor(log10_64(f64(x)))); + return @floatToInt(T, math.floor(log10_64(@intToFloat(f64, x)))); }, else => @compileError("log10 not implemented for " ++ @typeName(T)), } @@ -71,7 +71,7 @@ pub fn log10_32(x_: f32) f32 { // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; - k += i32(ix >> 23) - 0x7F; + k += @intCast(i32, ix >> 23) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @bitCast(f32, ix); @@ -89,7 +89,7 @@ pub fn log10_32(x_: f32) f32 { u &= 0xFFFFF000; hi = @bitCast(f32, u); const lo = f - hi - hfsq + s * (hfsq + R); - const dk = f32(k); + const dk = @intToFloat(f32, k); return dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi + hi * ivln10hi + dk * log10_2hi; } @@ -109,7 +109,7 @@ pub fn log10_64(x_: f64) f64 { var x = x_; var ix = @bitCast(u64, x); - var hx = u32(ix >> 32); + var hx = @intCast(u32, ix >> 32); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { @@ -125,7 +125,7 @@ pub fn log10_64(x_: f64) f64 { // subnormal, scale x k -= 54; x *= 0x1.0p54; - hx = u32(@bitCast(u64, x) >> 32); + hx = @intCast(u32, @bitCast(u64, x) >> 32); } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { @@ -134,7 +134,7 @@ pub fn log10_64(x_: f64) f64 { // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; - k += i32(hx >> 20) - 0x3FF; + k += @intCast(i32, hx >> 20) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (u64(hx) << 32) | (ix & 0xFFFFFFFF); x = @bitCast(f64, ix); @@ -157,7 +157,7 @@ pub fn log10_64(x_: f64) f64 { // val_hi + val_lo ~ log10(1 + f) + k * log10(2) var val_hi = hi * ivln10hi; - const dk = f64(k); + const dk = @intToFloat(f64, k); const y = dk * log10_2hi; var val_lo = dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi; diff --git a/std/math/log1p.zig b/std/math/log1p.zig index 57efdaf51c..7d3be6bb49 100644 --- a/std/math/log1p.zig +++ b/std/math/log1p.zig @@ -68,7 +68,7 @@ fn log1p_32(x: f32) f32 { const uf = 1 + x; var iu = @bitCast(u32, uf); iu += 0x3F800000 - 0x3F3504F3; - k = i32(iu >> 23) - 0x7F; + k = @intCast(i32, iu >> 23) - 0x7F; // correction to avoid underflow in c / u if (k < 25) { @@ -90,7 +90,7 @@ fn log1p_32(x: f32) f32 { const t2 = z * (Lg1 + w * Lg3); const R = t2 + t1; const hfsq = 0.5 * f * f; - const dk = f32(k); + const dk = @intToFloat(f32, k); return s * (hfsq + R) + (dk * ln2_lo + c) - hfsq + f + dk * ln2_hi; } @@ -107,7 +107,7 @@ fn log1p_64(x: f64) f64 { const Lg7: f64 = 1.479819860511658591e-01; var ix = @bitCast(u64, x); - var hx = u32(ix >> 32); + var hx = @intCast(u32, ix >> 32); var k: i32 = 1; var c: f64 = undefined; var f: f64 = undefined; @@ -145,9 +145,9 @@ fn log1p_64(x: f64) f64 { if (k != 0) { const uf = 1 + x; const hu = @bitCast(u64, uf); - var iu = u32(hu >> 32); + var iu = @intCast(u32, hu >> 32); iu += 0x3FF00000 - 0x3FE6A09E; - k = i32(iu >> 20) - 0x3FF; + k = @intCast(i32, iu >> 20) - 0x3FF; // correction to avoid underflow in c / u if (k < 54) { @@ -170,7 +170,7 @@ fn log1p_64(x: f64) f64 { const t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); const R = t2 + t1; - const dk = f64(k); + const dk = @intToFloat(f64, k); return s * (hfsq + R) + (dk * ln2_lo + c) - hfsq + f + dk * ln2_hi; } diff --git a/std/math/log2.zig b/std/math/log2.zig index 2530519941..858f6ffa02 100644 --- a/std/math/log2.zig +++ b/std/math/log2.zig @@ -75,7 +75,7 @@ pub fn log2_32(x_: f32) f32 { // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; - k += i32(ix >> 23) - 0x7F; + k += @intCast(i32, ix >> 23) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @bitCast(f32, ix); @@ -93,7 +93,7 @@ pub fn log2_32(x_: f32) f32 { u &= 0xFFFFF000; hi = @bitCast(f32, u); const lo = f - hi - hfsq + s * (hfsq + R); - return (lo + hi) * ivln2lo + lo * ivln2hi + hi * ivln2hi + f32(k); + return (lo + hi) * ivln2lo + lo * ivln2hi + hi * ivln2hi + @intToFloat(f32, k); } pub fn log2_64(x_: f64) f64 { @@ -109,7 +109,7 @@ pub fn log2_64(x_: f64) f64 { var x = x_; var ix = @bitCast(u64, x); - var hx = u32(ix >> 32); + var hx = @intCast(u32, ix >> 32); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { @@ -125,7 +125,7 @@ pub fn log2_64(x_: f64) f64 { // subnormal, scale x k -= 54; x *= 0x1.0p54; - hx = u32(@bitCast(u64, x) >> 32); + hx = @intCast(u32, @bitCast(u64, x) >> 32); } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { @@ -134,7 +134,7 @@ pub fn log2_64(x_: f64) f64 { // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; - k += i32(hx >> 20) - 0x3FF; + k += @intCast(i32, hx >> 20) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (u64(hx) << 32) | (ix & 0xFFFFFFFF); x = @bitCast(f64, ix); @@ -159,7 +159,7 @@ pub fn log2_64(x_: f64) f64 { var val_lo = (lo + hi) * ivln2lo + lo * ivln2hi; // spadd(val_hi, val_lo, y) - const y = f64(k); + const y = @intToFloat(f64, k); const ww = y + val_hi; val_lo += (y - ww) + val_hi; val_hi = ww; diff --git a/std/math/modf.zig b/std/math/modf.zig index a6606ce34c..b6dd78f022 100644 --- a/std/math/modf.zig +++ b/std/math/modf.zig @@ -29,7 +29,7 @@ fn modf32(x: f32) modf32_result { var result: modf32_result = undefined; const u = @bitCast(u32, x); - const e = i32((u >> 23) & 0xFF) - 0x7F; + const e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F; const us = u & 0x80000000; // TODO: Shouldn't need this. @@ -57,7 +57,7 @@ fn modf32(x: f32) modf32_result { return result; } - const mask = u32(0x007FFFFF) >> u5(e); + const mask = u32(0x007FFFFF) >> @intCast(u5, e); if (u & mask == 0) { result.ipart = x; result.fpart = @bitCast(f32, us); @@ -74,7 +74,7 @@ fn modf64(x: f64) modf64_result { var result: modf64_result = undefined; const u = @bitCast(u64, x); - const e = i32((u >> 52) & 0x7FF) - 0x3FF; + const e = @intCast(i32, (u >> 52) & 0x7FF) - 0x3FF; const us = u & (1 << 63); if (math.isInf(x)) { @@ -101,7 +101,7 @@ fn modf64(x: f64) modf64_result { return result; } - const mask = u64(@maxValue(u64) >> 12) >> u6(e); + const mask = u64(@maxValue(u64) >> 12) >> @intCast(u6, e); if (u & mask == 0) { result.ipart = x; result.fpart = @bitCast(f64, us); diff --git a/std/math/pow.zig b/std/math/pow.zig index dfe4fc09d6..7fc334c06b 100644 --- a/std/math/pow.zig +++ b/std/math/pow.zig @@ -146,7 +146,7 @@ pub fn pow(comptime T: type, x: T, y: T) T { var xe = r2.exponent; var x1 = r2.significand; - var i = i32(yi); + var i = @floatToInt(i32, yi); while (i != 0) : (i >>= 1) { if (i & 1 == 1) { a1 *= x1; @@ -171,7 +171,7 @@ pub fn pow(comptime T: type, x: T, y: T) T { fn isOddInteger(x: f64) bool { const r = math.modf(x); - return r.fpart == 0.0 and i64(r.ipart) & 1 == 1; + return r.fpart == 0.0 and @floatToInt(i64, r.ipart) & 1 == 1; } test "math.pow" { diff --git a/std/math/scalbn.zig b/std/math/scalbn.zig index deb5d989d2..f72c7e866f 100644 --- a/std/math/scalbn.zig +++ b/std/math/scalbn.zig @@ -37,7 +37,7 @@ fn scalbn32(x: f32, n_: i32) f32 { } } - const u = u32(n +% 0x7F) << 23; + const u = @intCast(u32, n +% 0x7F) << 23; return y * @bitCast(f32, u); } @@ -67,7 +67,7 @@ fn scalbn64(x: f64, n_: i32) f64 { } } - const u = u64(n +% 0x3FF) << 52; + const u = @intCast(u64, n +% 0x3FF) << 52; return y * @bitCast(f64, u); } diff --git a/std/math/sin.zig b/std/math/sin.zig index 21c324e444..3796d74812 100644 --- a/std/math/sin.zig +++ b/std/math/sin.zig @@ -60,7 +60,7 @@ fn sin32(x_: f32) f32 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; @@ -112,7 +112,7 @@ fn sin64(x_: f64) f64 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; diff --git a/std/math/sinh.zig b/std/math/sinh.zig index 85c9ae979b..bb3af280ab 100644 --- a/std/math/sinh.zig +++ b/std/math/sinh.zig @@ -57,7 +57,7 @@ fn sinh64(x: f64) f64 { @setFloatMode(this, @import("builtin").FloatMode.Strict); const u = @bitCast(u64, x); - const w = u32(u >> 32); + const w = @intCast(u32, u >> 32); const ax = @bitCast(f64, u & (@maxValue(u64) >> 1)); if (x == 0.0 or math.isNan(x)) { diff --git a/std/math/sqrt.zig b/std/math/sqrt.zig index 7a3ddb3b96..599008acff 100644 --- a/std/math/sqrt.zig +++ b/std/math/sqrt.zig @@ -99,7 +99,7 @@ fn sqrt_int(comptime T: type, value: T) @IntType(false, T.bit_count / 2) { } const ResultType = @IntType(false, T.bit_count / 2); - return ResultType(res); + return @intCast(ResultType, res); } test "math.sqrt_int" { diff --git a/std/math/tan.zig b/std/math/tan.zig index f578cf8156..ff3ed06186 100644 --- a/std/math/tan.zig +++ b/std/math/tan.zig @@ -53,7 +53,7 @@ fn tan32(x_: f32) f32 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; @@ -102,7 +102,7 @@ fn tan64(x_: f64) f64 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; diff --git a/std/math/tanh.zig b/std/math/tanh.zig index c1f5a0ca46..6204b2a374 100644 --- a/std/math/tanh.zig +++ b/std/math/tanh.zig @@ -68,7 +68,7 @@ fn tanh32(x: f32) f32 { fn tanh64(x: f64) f64 { const u = @bitCast(u64, x); - const w = u32(u >> 32); + const w = @intCast(u32, u >> 32); const ax = @bitCast(f64, u & (@maxValue(u64) >> 1)); var t: f64 = undefined; @@ -100,7 +100,7 @@ fn tanh64(x: f64) f64 { } // |x| is subnormal else { - math.forceEval(f32(x)); + math.forceEval(@floatCast(f32, x)); t = x; } diff --git a/std/math/trunc.zig b/std/math/trunc.zig index 54aa6943f7..92d5bfebc5 100644 --- a/std/math/trunc.zig +++ b/std/math/trunc.zig @@ -19,7 +19,7 @@ pub fn trunc(x: var) @typeOf(x) { fn trunc32(x: f32) f32 { const u = @bitCast(u32, x); - var e = i32(((u >> 23) & 0xFF)) - 0x7F + 9; + var e = @intCast(i32, ((u >> 23) & 0xFF)) - 0x7F + 9; var m: u32 = undefined; if (e >= 23 + 9) { @@ -29,7 +29,7 @@ fn trunc32(x: f32) f32 { e = 1; } - m = u32(@maxValue(u32)) >> u5(e); + m = u32(@maxValue(u32)) >> @intCast(u5, e); if (u & m == 0) { return x; } else { @@ -40,7 +40,7 @@ fn trunc32(x: f32) f32 { fn trunc64(x: f64) f64 { const u = @bitCast(u64, x); - var e = i32(((u >> 52) & 0x7FF)) - 0x3FF + 12; + var e = @intCast(i32, ((u >> 52) & 0x7FF)) - 0x3FF + 12; var m: u64 = undefined; if (e >= 52 + 12) { @@ -50,7 +50,7 @@ fn trunc64(x: f64) f64 { e = 1; } - m = u64(@maxValue(u64)) >> u6(e); + m = u64(@maxValue(u64)) >> @intCast(u6, e); if (u & m == 0) { return x; } else { diff --git a/std/mem.zig b/std/mem.zig index 10b3eb8fef..b02589b0dd 100644 --- a/std/mem.zig +++ b/std/mem.zig @@ -334,7 +334,7 @@ pub fn readInt(bytes: []const u8, comptime T: type, endian: builtin.Endian) T { builtin.Endian.Little => { const ShiftType = math.Log2Int(T); for (bytes) |b, index| { - result = result | (T(b) << ShiftType(index * 8)); + result = result | (T(b) << @intCast(ShiftType, index * 8)); } }, } diff --git a/std/os/child_process.zig b/std/os/child_process.zig index 1e3a732498..3a0fa7f461 100644 --- a/std/os/child_process.zig +++ b/std/os/child_process.zig @@ -413,7 +413,7 @@ pub const ChildProcess = struct { } // we are the parent - const pid = i32(pid_result); + const pid = @intCast(i32, pid_result); if (self.stdin_behavior == StdIo.Pipe) { self.stdin = os.File.openHandle(stdin_pipe[1]); } else { diff --git a/std/os/darwin.zig b/std/os/darwin.zig index a835959103..15e5608343 100644 --- a/std/os/darwin.zig +++ b/std/os/darwin.zig @@ -290,7 +290,7 @@ pub fn WIFSIGNALED(x: i32) bool { /// Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: usize) usize { const signed_r = @bitCast(isize, r); - return if (signed_r > -4096 and signed_r < 0) usize(-signed_r) else 0; + return if (signed_r > -4096 and signed_r < 0) @intCast(usize, -signed_r) else 0; } pub fn close(fd: i32) usize { @@ -339,7 +339,14 @@ pub fn write(fd: i32, buf: [*]const u8, nbyte: usize) usize { } pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { - const ptr_result = c.mmap(@ptrCast(*c_void, address), length, @bitCast(c_int, c_uint(prot)), @bitCast(c_int, c_uint(flags)), fd, offset); + const ptr_result = c.mmap( + @ptrCast(*c_void, address), + length, + @bitCast(c_int, @intCast(c_uint, prot)), + @bitCast(c_int, c_uint(flags)), + fd, + offset, + ); const isize_result = @bitCast(isize, @ptrToInt(ptr_result)); return errnoWrap(isize_result); } diff --git a/std/os/file.zig b/std/os/file.zig index 7e05501831..055f185121 100644 --- a/std/os/file.zig +++ b/std/os/file.zig @@ -266,7 +266,7 @@ pub const File = struct { pub fn getEndPos(self: *File) !usize { if (is_posix) { const stat = try os.posixFStat(self.handle); - return usize(stat.size); + return @intCast(usize, stat.size); } else if (is_windows) { var file_size: windows.LARGE_INTEGER = undefined; if (windows.GetFileSizeEx(self.handle, &file_size) == 0) { @@ -277,7 +277,7 @@ pub const File = struct { } if (file_size < 0) return error.Overflow; - return math.cast(usize, u64(file_size)); + return math.cast(usize, @intCast(u64, file_size)); } else { @compileError("TODO support getEndPos on this OS"); } @@ -343,7 +343,7 @@ pub const File = struct { } else if (is_windows) { var index: usize = 0; while (index < buffer.len) { - const want_read_count = windows.DWORD(math.min(windows.DWORD(@maxValue(windows.DWORD)), buffer.len - index)); + const want_read_count = @intCast(windows.DWORD, math.min(windows.DWORD(@maxValue(windows.DWORD)), buffer.len - index)); var amt_read: windows.DWORD = undefined; if (windows.ReadFile(self.handle, @ptrCast(*c_void, buffer.ptr + index), want_read_count, &amt_read, null) == 0) { const err = windows.GetLastError(); diff --git a/std/os/index.zig b/std/os/index.zig index fb4605fce0..f1c3ab2128 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -126,7 +126,7 @@ pub fn getRandomBytes(buf: []u8) !void { } defer _ = windows.CryptReleaseContext(hCryptProv, 0); - if (windows.CryptGenRandom(hCryptProv, windows.DWORD(buf.len), buf.ptr) == 0) { + if (windows.CryptGenRandom(hCryptProv, @intCast(windows.DWORD, buf.len), buf.ptr) == 0) { const err = windows.GetLastError(); return switch (err) { else => unexpectedErrorWindows(err), @@ -343,7 +343,7 @@ pub fn posixOpenC(file_path: [*]const u8, flags: u32, perm: usize) !i32 { else => return unexpectedErrorPosix(err), } } - return i32(result); + return @intCast(i32, result); } } @@ -586,7 +586,7 @@ pub fn getCwd(allocator: *Allocator) ![]u8 { errdefer allocator.free(buf); while (true) { - const result = windows.GetCurrentDirectoryA(windows.WORD(buf.len), buf.ptr); + const result = windows.GetCurrentDirectoryA(@intCast(windows.WORD, buf.len), buf.ptr); if (result == 0) { const err = windows.GetLastError(); @@ -2019,7 +2019,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 { const rc = posix.socket(domain, socket_type, protocol); const err = posix.getErrno(rc); switch (err) { - 0 => return i32(rc), + 0 => return @intCast(i32, rc), posix.EACCES => return PosixSocketError.PermissionDenied, posix.EAFNOSUPPORT => return PosixSocketError.AddressFamilyNotSupported, posix.EINVAL => return PosixSocketError.ProtocolFamilyNotAvailable, @@ -2183,7 +2183,7 @@ pub fn posixAccept(fd: i32, addr: *posix.sockaddr, flags: u32) PosixAcceptError! const rc = posix.accept4(fd, addr, &sockaddr_size, flags); const err = posix.getErrno(rc); switch (err) { - 0 => return i32(rc), + 0 => return @intCast(i32, rc), posix.EINTR => continue, else => return unexpectedErrorPosix(err), @@ -2226,7 +2226,7 @@ pub fn linuxEpollCreate(flags: u32) LinuxEpollCreateError!i32 { const rc = posix.epoll_create1(flags); const err = posix.getErrno(rc); switch (err) { - 0 => return i32(rc), + 0 => return @intCast(i32, rc), else => return unexpectedErrorPosix(err), posix.EINVAL => return LinuxEpollCreateError.InvalidSyscall, @@ -2296,7 +2296,7 @@ pub fn linuxEpollCtl(epfd: i32, op: u32, fd: i32, event: *linux.epoll_event) Lin pub fn linuxEpollWait(epfd: i32, events: []linux.epoll_event, timeout: i32) usize { while (true) { - const rc = posix.epoll_wait(epfd, events.ptr, u32(events.len), timeout); + const rc = posix.epoll_wait(epfd, events.ptr, @intCast(u32, events.len), timeout); const err = posix.getErrno(rc); switch (err) { 0 => return rc, @@ -2661,7 +2661,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread posix.EAGAIN => return SpawnThreadError.SystemResources, posix.EPERM => unreachable, posix.EINVAL => unreachable, - else => return unexpectedErrorPosix(usize(err)), + else => return unexpectedErrorPosix(@intCast(usize, err)), } } else if (builtin.os == builtin.Os.linux) { // use linux API directly. TODO use posix.CLONE_SETTLS and initialize thread local storage correctly diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 0e77371ec2..65aa659c82 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -642,7 +642,7 @@ pub fn WIFEXITED(s: i32) bool { return WTERMSIG(s) == 0; } pub fn WIFSTOPPED(s: i32) bool { - return (u16)(((unsigned(s) & 0xffff) *% 0x10001) >> 8) > 0x7f00; + return @intCast(u16, ((unsigned(s) & 0xffff) *% 0x10001) >> 8) > 0x7f00; } pub fn WIFSIGNALED(s: i32) bool { return (unsigned(s) & 0xffff) -% 1 < 0xff; @@ -658,11 +658,11 @@ pub const winsize = extern struct { /// Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: usize) usize { const signed_r = @bitCast(isize, r); - return if (signed_r > -4096 and signed_r < 0) usize(-signed_r) else 0; + return if (signed_r > -4096 and signed_r < 0) @intCast(usize, -signed_r) else 0; } pub fn dup2(old: i32, new: i32) usize { - return syscall2(SYS_dup2, usize(old), usize(new)); + return syscall2(SYS_dup2, @intCast(usize, old), @intCast(usize, new)); } // TODO https://github.com/ziglang/zig/issues/265 @@ -693,12 +693,12 @@ pub fn getcwd(buf: [*]u8, size: usize) usize { } pub fn getdents(fd: i32, dirp: [*]u8, count: usize) usize { - return syscall3(SYS_getdents, usize(fd), @ptrToInt(dirp), count); + return syscall3(SYS_getdents, @intCast(usize, fd), @ptrToInt(dirp), count); } pub fn isatty(fd: i32) bool { var wsz: winsize = undefined; - return syscall3(SYS_ioctl, usize(fd), TIOCGWINSZ, @ptrToInt(&wsz)) == 0; + return syscall3(SYS_ioctl, @intCast(usize, fd), TIOCGWINSZ, @ptrToInt(&wsz)) == 0; } // TODO https://github.com/ziglang/zig/issues/265 @@ -727,7 +727,7 @@ pub fn umount2(special: [*]const u8, flags: u32) usize { } pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { - return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), @bitCast(usize, offset)); + return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, @intCast(usize, fd), @bitCast(usize, offset)); } pub fn munmap(address: usize, length: usize) usize { @@ -735,7 +735,7 @@ pub fn munmap(address: usize, length: usize) usize { } pub fn read(fd: i32, buf: [*]u8, count: usize) usize { - return syscall3(SYS_read, usize(fd), @ptrToInt(buf), count); + return syscall3(SYS_read, @intCast(usize, fd), @ptrToInt(buf), count); } // TODO https://github.com/ziglang/zig/issues/265 @@ -749,7 +749,7 @@ pub fn symlink(existing: [*]const u8, new: [*]const u8) usize { } pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: usize) usize { - return syscall4(SYS_pread, usize(fd), @ptrToInt(buf), count, offset); + return syscall4(SYS_pread, @intCast(usize, fd), @ptrToInt(buf), count, offset); } // TODO https://github.com/ziglang/zig/issues/265 @@ -766,11 +766,11 @@ pub fn pipe2(fd: *[2]i32, flags: usize) usize { } pub fn write(fd: i32, buf: [*]const u8, count: usize) usize { - return syscall3(SYS_write, usize(fd), @ptrToInt(buf), count); + return syscall3(SYS_write, @intCast(usize, fd), @ptrToInt(buf), count); } pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize { - return syscall4(SYS_pwrite, usize(fd), @ptrToInt(buf), count, offset); + return syscall4(SYS_pwrite, @intCast(usize, fd), @ptrToInt(buf), count, offset); } // TODO https://github.com/ziglang/zig/issues/265 @@ -790,7 +790,7 @@ pub fn create(path: [*]const u8, perm: usize) usize { // TODO https://github.com/ziglang/zig/issues/265 pub fn openat(dirfd: i32, path: [*]const u8, flags: usize, mode: usize) usize { - return syscall4(SYS_openat, usize(dirfd), @ptrToInt(path), flags, mode); + return syscall4(SYS_openat, @intCast(usize, dirfd), @ptrToInt(path), flags, mode); } /// See also `clone` (from the arch-specific include) @@ -804,11 +804,11 @@ pub fn clone2(flags: usize, child_stack_ptr: usize) usize { } pub fn close(fd: i32) usize { - return syscall1(SYS_close, usize(fd)); + return syscall1(SYS_close, @intCast(usize, fd)); } pub fn lseek(fd: i32, offset: isize, ref_pos: usize) usize { - return syscall3(SYS_lseek, usize(fd), @bitCast(usize, offset), ref_pos); + return syscall3(SYS_lseek, @intCast(usize, fd), @bitCast(usize, offset), ref_pos); } pub fn exit(status: i32) noreturn { @@ -817,11 +817,11 @@ pub fn exit(status: i32) noreturn { } pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize { - return syscall3(SYS_getrandom, @ptrToInt(buf), count, usize(flags)); + return syscall3(SYS_getrandom, @ptrToInt(buf), count, @intCast(usize, flags)); } pub fn kill(pid: i32, sig: i32) usize { - return syscall2(SYS_kill, @bitCast(usize, isize(pid)), usize(sig)); + return syscall2(SYS_kill, @bitCast(usize, isize(pid)), @intCast(usize, sig)); } // TODO https://github.com/ziglang/zig/issues/265 @@ -999,8 +999,8 @@ pub const empty_sigset = []usize{0} ** sigset_t.len; pub fn raise(sig: i32) usize { var set: sigset_t = undefined; blockAppSignals(&set); - const tid = i32(syscall0(SYS_gettid)); - const ret = syscall2(SYS_tkill, usize(tid), usize(sig)); + const tid = @intCast(i32, syscall0(SYS_gettid)); + const ret = syscall2(SYS_tkill, @intCast(usize, tid), @intCast(usize, sig)); restoreSignals(&set); return ret; } @@ -1019,12 +1019,12 @@ fn restoreSignals(set: *sigset_t) void { pub fn sigaddset(set: *sigset_t, sig: u6) void { const s = sig - 1; - (set.*)[usize(s) / usize.bit_count] |= usize(1) << (s & (usize.bit_count - 1)); + (set.*)[@intCast(usize, s) / usize.bit_count] |= @intCast(usize, 1) << (s & (usize.bit_count - 1)); } pub fn sigismember(set: *const sigset_t, sig: u6) bool { const s = sig - 1; - return ((set.*)[usize(s) / usize.bit_count] & (usize(1) << (s & (usize.bit_count - 1)))) != 0; + return ((set.*)[@intCast(usize, s) / usize.bit_count] & (@intCast(usize, 1) << (s & (usize.bit_count - 1)))) != 0; } pub const in_port_t = u16; @@ -1057,11 +1057,11 @@ pub const iovec = extern struct { }; pub fn getsockname(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { - return syscall3(SYS_getsockname, usize(fd), @ptrToInt(addr), @ptrToInt(len)); + return syscall3(SYS_getsockname, @intCast(usize, fd), @ptrToInt(addr), @ptrToInt(len)); } pub fn getpeername(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { - return syscall3(SYS_getpeername, usize(fd), @ptrToInt(addr), @ptrToInt(len)); + return syscall3(SYS_getpeername, @intCast(usize, fd), @ptrToInt(addr), @ptrToInt(len)); } pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize { @@ -1069,47 +1069,47 @@ pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize { } pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: [*]const u8, optlen: socklen_t) usize { - return syscall5(SYS_setsockopt, usize(fd), level, optname, usize(optval), @ptrToInt(optlen)); + return syscall5(SYS_setsockopt, @intCast(usize, fd), level, optname, @intCast(usize, optval), @ptrToInt(optlen)); } pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: [*]u8, noalias optlen: *socklen_t) usize { - return syscall5(SYS_getsockopt, usize(fd), level, optname, @ptrToInt(optval), @ptrToInt(optlen)); + return syscall5(SYS_getsockopt, @intCast(usize, fd), level, optname, @ptrToInt(optval), @ptrToInt(optlen)); } pub fn sendmsg(fd: i32, msg: *const msghdr, flags: u32) usize { - return syscall3(SYS_sendmsg, usize(fd), @ptrToInt(msg), flags); + return syscall3(SYS_sendmsg, @intCast(usize, fd), @ptrToInt(msg), flags); } pub fn connect(fd: i32, addr: *const sockaddr, len: socklen_t) usize { - return syscall3(SYS_connect, usize(fd), @ptrToInt(addr), usize(len)); + return syscall3(SYS_connect, @intCast(usize, fd), @ptrToInt(addr), @intCast(usize, len)); } pub fn recvmsg(fd: i32, msg: *msghdr, flags: u32) usize { - return syscall3(SYS_recvmsg, usize(fd), @ptrToInt(msg), flags); + return syscall3(SYS_recvmsg, @intCast(usize, fd), @ptrToInt(msg), flags); } pub fn recvfrom(fd: i32, noalias buf: [*]u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize { - return syscall6(SYS_recvfrom, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); + return syscall6(SYS_recvfrom, @intCast(usize, fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); } pub fn shutdown(fd: i32, how: i32) usize { - return syscall2(SYS_shutdown, usize(fd), usize(how)); + return syscall2(SYS_shutdown, @intCast(usize, fd), @intCast(usize, how)); } pub fn bind(fd: i32, addr: *const sockaddr, len: socklen_t) usize { - return syscall3(SYS_bind, usize(fd), @ptrToInt(addr), usize(len)); + return syscall3(SYS_bind, @intCast(usize, fd), @ptrToInt(addr), @intCast(usize, len)); } pub fn listen(fd: i32, backlog: u32) usize { - return syscall2(SYS_listen, usize(fd), backlog); + return syscall2(SYS_listen, @intCast(usize, fd), backlog); } pub fn sendto(fd: i32, buf: [*]const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize { - return syscall6(SYS_sendto, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), usize(alen)); + return syscall6(SYS_sendto, @intCast(usize, fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen)); } pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usize { - return syscall4(SYS_socketpair, usize(domain), usize(socket_type), usize(protocol), @ptrToInt(*fd[0])); + return syscall4(SYS_socketpair, @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(*fd[0])); } pub fn accept(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { @@ -1117,11 +1117,11 @@ pub fn accept(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { } pub fn accept4(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t, flags: u32) usize { - return syscall4(SYS_accept4, usize(fd), @ptrToInt(addr), @ptrToInt(len), flags); + return syscall4(SYS_accept4, @intCast(usize, fd), @ptrToInt(addr), @ptrToInt(len), flags); } pub fn fstat(fd: i32, stat_buf: *Stat) usize { - return syscall2(SYS_fstat, usize(fd), @ptrToInt(stat_buf)); + return syscall2(SYS_fstat, @intCast(usize, fd), @ptrToInt(stat_buf)); } // TODO https://github.com/ziglang/zig/issues/265 @@ -1214,15 +1214,15 @@ pub fn epoll_create1(flags: usize) usize { } pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: *epoll_event) usize { - return syscall4(SYS_epoll_ctl, usize(epoll_fd), usize(op), usize(fd), @ptrToInt(ev)); + return syscall4(SYS_epoll_ctl, @intCast(usize, epoll_fd), @intCast(usize, op), @intCast(usize, fd), @ptrToInt(ev)); } pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32) usize { - return syscall4(SYS_epoll_wait, usize(epoll_fd), @ptrToInt(events), usize(maxevents), usize(timeout)); + return syscall4(SYS_epoll_wait, @intCast(usize, epoll_fd), @ptrToInt(events), @intCast(usize, maxevents), @intCast(usize, timeout)); } pub fn timerfd_create(clockid: i32, flags: u32) usize { - return syscall2(SYS_timerfd_create, usize(clockid), usize(flags)); + return syscall2(SYS_timerfd_create, @intCast(usize, clockid), @intCast(usize, flags)); } pub const itimerspec = extern struct { @@ -1231,11 +1231,11 @@ pub const itimerspec = extern struct { }; pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) usize { - return syscall2(SYS_timerfd_gettime, usize(fd), @ptrToInt(curr_value)); + return syscall2(SYS_timerfd_gettime, @intCast(usize, fd), @ptrToInt(curr_value)); } pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const itimerspec, old_value: ?*itimerspec) usize { - return syscall4(SYS_timerfd_settime, usize(fd), usize(flags), @ptrToInt(new_value), @ptrToInt(old_value)); + return syscall4(SYS_timerfd_settime, @intCast(usize, fd), @intCast(usize, flags), @ptrToInt(new_value), @ptrToInt(old_value)); } pub const _LINUX_CAPABILITY_VERSION_1 = 0x19980330; @@ -1345,7 +1345,7 @@ pub const cap_user_data_t = extern struct { }; pub fn unshare(flags: usize) usize { - return syscall1(SYS_unshare, usize(flags)); + return syscall1(SYS_unshare, @intCast(usize, flags)); } pub fn capget(hdrp: *cap_user_header_t, datap: *cap_user_data_t) usize { diff --git a/std/os/linux/test.zig b/std/os/linux/test.zig index 948a3ac96b..e7dae3a584 100644 --- a/std/os/linux/test.zig +++ b/std/os/linux/test.zig @@ -21,7 +21,7 @@ test "timer" { .it_value = time_interval, }; - err = linux.timerfd_settime(i32(timer_fd), 0, &new_time, null); + err = linux.timerfd_settime(@intCast(i32, timer_fd), 0, &new_time, null); assert(err == 0); var event = linux.epoll_event{ @@ -29,12 +29,12 @@ test "timer" { .data = linux.epoll_data{ .ptr = 0 }, }; - err = linux.epoll_ctl(i32(epoll_fd), linux.EPOLL_CTL_ADD, i32(timer_fd), &event); + err = linux.epoll_ctl(@intCast(i32, epoll_fd), linux.EPOLL_CTL_ADD, @intCast(i32, timer_fd), &event); assert(err == 0); const events_one: linux.epoll_event = undefined; var events = []linux.epoll_event{events_one} ** 8; // TODO implicit cast from *[N]T to [*]T - err = linux.epoll_wait(i32(epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1); + err = linux.epoll_wait(@intCast(i32, epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1); } diff --git a/std/os/linux/vdso.zig b/std/os/linux/vdso.zig index cbd0cd1df5..a78e3370e6 100644 --- a/std/os/linux/vdso.zig +++ b/std/os/linux/vdso.zig @@ -62,8 +62,8 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { var i: usize = 0; while (i < hashtab[1]) : (i += 1) { - if (0 == (u32(1) << u5(syms[i].st_info & 0xf) & OK_TYPES)) continue; - if (0 == (u32(1) << u5(syms[i].st_info >> 4) & OK_BINDS)) continue; + if (0 == (u32(1) << @intCast(u5, syms[i].st_info & 0xf) & OK_TYPES)) continue; + if (0 == (u32(1) << @intCast(u5, syms[i].st_info >> 4) & OK_BINDS)) continue; if (0 == syms[i].st_shndx) continue; if (!mem.eql(u8, name, cstr.toSliceConst(strings + syms[i].st_name))) continue; if (maybe_versym) |versym| { diff --git a/std/os/time.zig b/std/os/time.zig index ffb506cd7d..73ba5bba82 100644 --- a/std/os/time.zig +++ b/std/os/time.zig @@ -14,12 +14,12 @@ pub const epoch = @import("epoch.zig"); pub fn sleep(seconds: usize, nanoseconds: usize) void { switch (builtin.os) { Os.linux, Os.macosx, Os.ios => { - posixSleep(u63(seconds), u63(nanoseconds)); + posixSleep(@intCast(u63, seconds), @intCast(u63, nanoseconds)); }, Os.windows => { const ns_per_ms = ns_per_s / ms_per_s; const milliseconds = seconds * ms_per_s + nanoseconds / ns_per_ms; - windows.Sleep(windows.DWORD(milliseconds)); + windows.Sleep(@intCast(windows.DWORD, milliseconds)); }, else => @compileError("Unsupported OS"), } @@ -83,8 +83,8 @@ fn milliTimestampDarwin() u64 { var tv: darwin.timeval = undefined; var err = darwin.gettimeofday(&tv, null); debug.assert(err == 0); - const sec_ms = u64(tv.tv_sec) * ms_per_s; - const usec_ms = @divFloor(u64(tv.tv_usec), us_per_s / ms_per_s); + const sec_ms = @intCast(u64, tv.tv_sec) * ms_per_s; + const usec_ms = @divFloor(@intCast(u64, tv.tv_usec), us_per_s / ms_per_s); return u64(sec_ms) + u64(usec_ms); } @@ -95,8 +95,8 @@ fn milliTimestampPosix() u64 { var ts: posix.timespec = undefined; const err = posix.clock_gettime(posix.CLOCK_REALTIME, &ts); debug.assert(err == 0); - const sec_ms = u64(ts.tv_sec) * ms_per_s; - const nsec_ms = @divFloor(u64(ts.tv_nsec), ns_per_s / ms_per_s); + const sec_ms = @intCast(u64, ts.tv_sec) * ms_per_s; + const nsec_ms = @divFloor(@intCast(u64, ts.tv_nsec), ns_per_s / ms_per_s); return sec_ms + nsec_ms; } @@ -162,13 +162,13 @@ pub const Timer = struct { var freq: i64 = undefined; var err = windows.QueryPerformanceFrequency(&freq); if (err == windows.FALSE) return error.TimerUnsupported; - self.frequency = u64(freq); + self.frequency = @intCast(u64, freq); self.resolution = @divFloor(ns_per_s, self.frequency); var start_time: i64 = undefined; err = windows.QueryPerformanceCounter(&start_time); debug.assert(err != windows.FALSE); - self.start_time = u64(start_time); + self.start_time = @intCast(u64, start_time); }, Os.linux => { //On Linux, seccomp can do arbitrary things to our ability to call @@ -184,12 +184,12 @@ pub const Timer = struct { posix.EINVAL => return error.TimerUnsupported, else => return std.os.unexpectedErrorPosix(errno), } - self.resolution = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec); + self.resolution = @intCast(u64, ts.tv_sec) * u64(ns_per_s) + @intCast(u64, ts.tv_nsec); result = posix.clock_gettime(monotonic_clock_id, &ts); errno = posix.getErrno(result); if (errno != 0) return std.os.unexpectedErrorPosix(errno); - self.start_time = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec); + self.start_time = @intCast(u64, ts.tv_sec) * u64(ns_per_s) + @intCast(u64, ts.tv_nsec); }, Os.macosx, Os.ios => { darwin.mach_timebase_info(&self.frequency); @@ -236,7 +236,7 @@ pub const Timer = struct { var result: i64 = undefined; var err = windows.QueryPerformanceCounter(&result); debug.assert(err != windows.FALSE); - return u64(result); + return @intCast(u64, result); } fn clockDarwin() u64 { @@ -247,7 +247,7 @@ pub const Timer = struct { var ts: posix.timespec = undefined; var result = posix.clock_gettime(monotonic_clock_id, &ts); debug.assert(posix.getErrno(result) == 0); - return u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec); + return @intCast(u64, ts.tv_sec) * u64(ns_per_s) + @intCast(u64, ts.tv_nsec); } }; diff --git a/std/os/windows/util.zig b/std/os/windows/util.zig index 88a9e7952e..cb4788ba17 100644 --- a/std/os/windows/util.zig +++ b/std/os/windows/util.zig @@ -42,7 +42,7 @@ pub const WriteError = error{ }; pub fn windowsWrite(handle: windows.HANDLE, bytes: []const u8) WriteError!void { - if (windows.WriteFile(handle, @ptrCast(*const c_void, bytes.ptr), u32(bytes.len), null, null) == 0) { + if (windows.WriteFile(handle, @ptrCast(*const c_void, bytes.ptr), @intCast(u32, bytes.len), null, null) == 0) { const err = windows.GetLastError(); return switch (err) { windows.ERROR.INVALID_USER_BUFFER => WriteError.SystemResources, @@ -68,7 +68,12 @@ pub fn windowsIsCygwinPty(handle: windows.HANDLE) bool { const size = @sizeOf(windows.FILE_NAME_INFO); var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = []u8{0} ** (size + windows.MAX_PATH); - if (windows.GetFileInformationByHandleEx(handle, windows.FileNameInfo, @ptrCast(*c_void, &name_info_bytes[0]), u32(name_info_bytes.len)) == 0) { + if (windows.GetFileInformationByHandleEx( + handle, + windows.FileNameInfo, + @ptrCast(*c_void, &name_info_bytes[0]), + @intCast(u32, name_info_bytes.len), + ) == 0) { return true; } diff --git a/std/rand/index.zig b/std/rand/index.zig index 3a1a559cd9..13694f4c09 100644 --- a/std/rand/index.zig +++ b/std/rand/index.zig @@ -55,16 +55,16 @@ pub const Random = struct { if (T.is_signed) { const uint = @IntType(false, T.bit_count); if (start >= 0 and end >= 0) { - return T(r.range(uint, uint(start), uint(end))); + return @intCast(T, r.range(uint, @intCast(uint, start), @intCast(uint, end))); } else if (start < 0 and end < 0) { // Can't overflow because the range is over signed ints return math.negateCast(r.range(uint, math.absCast(end), math.absCast(start)) + 1) catch unreachable; } else if (start < 0 and end >= 0) { - const end_uint = uint(end); + const end_uint = @intCast(uint, end); const total_range = math.absCast(start) + end_uint; const value = r.range(uint, 0, total_range); const result = if (value < end_uint) x: { - break :x T(value); + break :x @intCast(T, value); } else if (value == end_uint) x: { break :x start; } else x: { @@ -213,9 +213,9 @@ pub const Pcg = struct { self.s = l *% default_multiplier +% (self.i | 1); const xor_s = @truncate(u32, ((l >> 18) ^ l) >> 27); - const rot = u32(l >> 59); + const rot = @intCast(u32, l >> 59); - return (xor_s >> u5(rot)) | (xor_s << u5((0 -% rot) & 31)); + return (xor_s >> @intCast(u5, rot)) | (xor_s << @intCast(u5, (0 -% rot) & 31)); } fn seed(self: *Pcg, init_s: u64) void { @@ -322,7 +322,7 @@ pub const Xoroshiro128 = struct { inline for (table) |entry| { var b: usize = 0; while (b < 64) : (b += 1) { - if ((entry & (u64(1) << u6(b))) != 0) { + if ((entry & (u64(1) << @intCast(u6, b))) != 0) { s0 ^= self.s[0]; s1 ^= self.s[1]; } @@ -667,13 +667,13 @@ test "Random range" { } fn testRange(r: *Random, start: i32, end: i32) void { - const count = usize(end - start); + const count = @intCast(usize, end - start); var values_buffer = []bool{false} ** 20; const values = values_buffer[0..count]; var i: usize = 0; while (i < count) { const value = r.range(i32, start, end); - const index = usize(value - start); + const index = @intCast(usize, value - start); if (!values[index]) { i += 1; values[index] = true; diff --git a/std/segmented_list.zig b/std/segmented_list.zig index 9f10f4d44a..6e3f32e9d6 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -104,7 +104,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } pub fn deinit(self: *Self) void { - self.freeShelves(ShelfIndex(self.dynamic_segments.len), 0); + self.freeShelves(@intCast(ShelfIndex, self.dynamic_segments.len), 0); self.allocator.free(self.dynamic_segments); self.* = undefined; } @@ -158,7 +158,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type /// Only grows capacity, or retains current capacity pub fn growCapacity(self: *Self, new_capacity: usize) !void { const new_cap_shelf_count = shelfCount(new_capacity); - const old_shelf_count = ShelfIndex(self.dynamic_segments.len); + const old_shelf_count = @intCast(ShelfIndex, self.dynamic_segments.len); if (new_cap_shelf_count > old_shelf_count) { self.dynamic_segments = try self.allocator.realloc([*]T, self.dynamic_segments, new_cap_shelf_count); var i = old_shelf_count; @@ -175,7 +175,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type /// Only shrinks capacity or retains current capacity pub fn shrinkCapacity(self: *Self, new_capacity: usize) void { if (new_capacity <= prealloc_item_count) { - const len = ShelfIndex(self.dynamic_segments.len); + const len = @intCast(ShelfIndex, self.dynamic_segments.len); self.freeShelves(len, 0); self.allocator.free(self.dynamic_segments); self.dynamic_segments = [][*]T{}; @@ -183,7 +183,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } const new_cap_shelf_count = shelfCount(new_capacity); - const old_shelf_count = ShelfIndex(self.dynamic_segments.len); + const old_shelf_count = @intCast(ShelfIndex, self.dynamic_segments.len); assert(new_cap_shelf_count <= old_shelf_count); if (new_cap_shelf_count == old_shelf_count) { return; @@ -338,7 +338,7 @@ fn testSegmentedList(comptime prealloc: usize, allocator: *Allocator) !void { { var i: usize = 0; while (i < 100) : (i += 1) { - try list.push(i32(i + 1)); + try list.push(@intCast(i32, i + 1)); assert(list.len == i + 1); } } @@ -346,7 +346,7 @@ fn testSegmentedList(comptime prealloc: usize, allocator: *Allocator) !void { { var i: usize = 0; while (i < 100) : (i += 1) { - assert(list.at(i).* == i32(i + 1)); + assert(list.at(i).* == @intCast(i32, i + 1)); } } diff --git a/std/special/bootstrap.zig b/std/special/bootstrap.zig index dd37f1edb6..5c8a330a92 100644 --- a/std/special/bootstrap.zig +++ b/std/special/bootstrap.zig @@ -80,7 +80,7 @@ extern fn main(c_argc: i32, c_argv: [*][*]u8, c_envp: [*]?[*]u8) i32 { var env_count: usize = 0; while (c_envp[env_count] != null) : (env_count += 1) {} const envp = @ptrCast([*][*]u8, c_envp)[0..env_count]; - return callMainWithArgs(usize(c_argc), c_argv, envp); + return callMainWithArgs(@intCast(usize, c_argc), c_argv, envp); } fn callMain() u8 { diff --git a/std/special/builtin.zig b/std/special/builtin.zig index e97b0a89e4..07e735d931 100644 --- a/std/special/builtin.zig +++ b/std/special/builtin.zig @@ -135,9 +135,9 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { const mask = if (T == f32) 0xff else 0x7ff; var ux = @bitCast(uint, x); var uy = @bitCast(uint, y); - var ex = i32((ux >> digits) & mask); - var ey = i32((uy >> digits) & mask); - const sx = if (T == f32) u32(ux & 0x80000000) else i32(ux >> bits_minus_1); + var ex = @intCast(i32, (ux >> digits) & mask); + var ey = @intCast(i32, (uy >> digits) & mask); + const sx = if (T == f32) @intCast(u32, ux & 0x80000000) else @intCast(i32, ux >> bits_minus_1); var i: uint = undefined; if (uy << 1 == 0 or isNan(uint, uy) or ex == mask) @@ -156,7 +156,7 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { ex -= 1; i <<= 1; }) {} - ux <<= log2uint(@bitCast(u32, -ex + 1)); + ux <<= @intCast(log2uint, @bitCast(u32, -ex + 1)); } else { ux &= @maxValue(uint) >> exp_bits; ux |= 1 << digits; @@ -167,7 +167,7 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { ey -= 1; i <<= 1; }) {} - uy <<= log2uint(@bitCast(u32, -ey + 1)); + uy <<= @intCast(log2uint, @bitCast(u32, -ey + 1)); } else { uy &= @maxValue(uint) >> exp_bits; uy |= 1 << digits; @@ -199,12 +199,12 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { ux -%= 1 << digits; ux |= uint(@bitCast(u32, ex)) << digits; } else { - ux >>= log2uint(@bitCast(u32, -ex + 1)); + ux >>= @intCast(log2uint, @bitCast(u32, -ex + 1)); } if (T == f32) { ux |= sx; } else { - ux |= uint(sx) << bits_minus_1; + ux |= @intCast(uint, sx) << bits_minus_1; } return @bitCast(T, ux); } @@ -227,8 +227,8 @@ export fn sqrt(x: f64) f64 { const sign: u32 = 0x80000000; const u = @bitCast(u64, x); - var ix0 = u32(u >> 32); - var ix1 = u32(u & 0xFFFFFFFF); + var ix0 = @intCast(u32, u >> 32); + var ix1 = @intCast(u32, u & 0xFFFFFFFF); // sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = nan if (ix0 & 0x7FF00000 == 0x7FF00000) { @@ -245,7 +245,7 @@ export fn sqrt(x: f64) f64 { } // normalize x - var m = i32(ix0 >> 20); + var m = @intCast(i32, ix0 >> 20); if (m == 0) { // subnormal while (ix0 == 0) { @@ -259,9 +259,9 @@ export fn sqrt(x: f64) f64 { while (ix0 & 0x00100000 == 0) : (i += 1) { ix0 <<= 1; } - m -= i32(i) - 1; - ix0 |= ix1 >> u5(32 - i); - ix1 <<= u5(i); + m -= @intCast(i32, i) - 1; + ix0 |= ix1 >> @intCast(u5, 32 - i); + ix1 <<= @intCast(u5, i); } // unbias exponent @@ -345,10 +345,10 @@ export fn sqrt(x: f64) f64 { // NOTE: musl here appears to rely on signed twos-complement wraparound. +% has the same // behaviour at least. - var iix0 = i32(ix0); + var iix0 = @intCast(i32, ix0); iix0 = iix0 +% (m << 20); - const uz = (u64(iix0) << 32) | ix1; + const uz = (@intCast(u64, iix0) << 32) | ix1; return @bitCast(f64, uz); } diff --git a/std/special/compiler_rt/divti3.zig b/std/special/compiler_rt/divti3.zig index 60460ea62d..712cccba82 100644 --- a/std/special/compiler_rt/divti3.zig +++ b/std/special/compiler_rt/divti3.zig @@ -13,7 +13,7 @@ pub extern fn __divti3(a: i128, b: i128) i128 { const r = udivmod(u128, @bitCast(u128, an), @bitCast(u128, bn), null); const s = s_a ^ s_b; - return (i128(r) ^ s) -% s; + return (@bitCast(i128, r) ^ s) -% s; } pub extern fn __divti3_windows_x86_64(a: *const i128, b: *const i128) void { diff --git a/std/special/compiler_rt/fixuint.zig b/std/special/compiler_rt/fixuint.zig index bd9b2fc395..48d63ed914 100644 --- a/std/special/compiler_rt/fixuint.zig +++ b/std/special/compiler_rt/fixuint.zig @@ -32,14 +32,14 @@ pub fn fixuint(comptime fp_t: type, comptime fixuint_t: type, a: fp_t) fixuint_t const aAbs: rep_t = aRep & absMask; const sign = if ((aRep & signBit) != 0) i32(-1) else i32(1); - const exponent = i32(aAbs >> significandBits) - exponentBias; + const exponent = @intCast(i32, aAbs >> significandBits) - exponentBias; const significand: rep_t = (aAbs & significandMask) | implicitBit; // If either the value or the exponent is negative, the result is zero. if (sign == -1 or exponent < 0) return 0; // If the value is too large for the integer type, saturate. - if (c_uint(exponent) >= fixuint_t.bit_count) return ~fixuint_t(0); + if (@intCast(c_uint, exponent) >= fixuint_t.bit_count) return ~fixuint_t(0); // If 0 <= exponent < significandBits, right shift to get the result. // Otherwise, shift left. @@ -47,11 +47,11 @@ pub fn fixuint(comptime fp_t: type, comptime fixuint_t: type, a: fp_t) fixuint_t // TODO this is a workaround for the mysterious "integer cast truncated bits" // happening on the next line @setRuntimeSafety(false); - return fixuint_t(significand >> Log2Int(rep_t)(significandBits - exponent)); + return @intCast(fixuint_t, significand >> @intCast(Log2Int(rep_t), significandBits - exponent)); } else { // TODO this is a workaround for the mysterious "integer cast truncated bits" // happening on the next line @setRuntimeSafety(false); - return fixuint_t(significand) << Log2Int(fixuint_t)(exponent - significandBits); + return @intCast(fixuint_t, significand) << @intCast(Log2Int(fixuint_t), exponent - significandBits); } } diff --git a/std/special/compiler_rt/index.zig b/std/special/compiler_rt/index.zig index f952730353..dc95aa23f2 100644 --- a/std/special/compiler_rt/index.zig +++ b/std/special/compiler_rt/index.zig @@ -292,7 +292,7 @@ extern fn __udivmodsi4(a: u32, b: u32, rem: *u32) u32 { @setRuntimeSafety(is_test); const d = __udivsi3(a, b); - rem.* = u32(i32(a) -% (i32(d) * i32(b))); + rem.* = @bitCast(u32, @bitCast(i32, a) -% (@bitCast(i32, d) * @bitCast(i32, b))); return d; } @@ -316,12 +316,12 @@ extern fn __udivsi3(n: u32, d: u32) u32 { sr += 1; // 1 <= sr <= n_uword_bits - 1 // Not a special case - var q: u32 = n << u5(n_uword_bits - sr); - var r: u32 = n >> u5(sr); + var q: u32 = n << @intCast(u5, n_uword_bits - sr); + var r: u32 = n >> @intCast(u5, sr); var carry: u32 = 0; while (sr > 0) : (sr -= 1) { // r:q = ((r:q) << 1) | carry - r = (r << 1) | (q >> u5(n_uword_bits - 1)); + r = (r << 1) | (q >> @intCast(u5, n_uword_bits - 1)); q = (q << 1) | carry; // carry = 0; // if (r.all >= d.all) @@ -329,8 +329,8 @@ extern fn __udivsi3(n: u32, d: u32) u32 { // r.all -= d.all; // carry = 1; // } - const s = i32(d -% r -% 1) >> u5(n_uword_bits - 1); - carry = u32(s & 1); + const s = @intCast(i32, d -% r -% 1) >> @intCast(u5, n_uword_bits - 1); + carry = @intCast(u32, s & 1); r -= d & @bitCast(u32, s); } q = (q << 1) | carry; diff --git a/std/special/compiler_rt/udivmod.zig b/std/special/compiler_rt/udivmod.zig index 894dd02239..e6b4ee0482 100644 --- a/std/special/compiler_rt/udivmod.zig +++ b/std/special/compiler_rt/udivmod.zig @@ -71,7 +71,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: r[high] = n[high] & (d[high] - 1); rem.* = @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 } - return n[high] >> Log2SingleInt(@ctz(d[high])); + return n[high] >> @intCast(Log2SingleInt, @ctz(d[high])); } // K K // --- @@ -88,10 +88,10 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // 1 <= sr <= SingleInt.bit_count - 1 // q.all = a << (DoubleInt.bit_count - sr); q[low] = 0; - q[high] = n[low] << Log2SingleInt(SingleInt.bit_count - sr); + q[high] = n[low] << @intCast(Log2SingleInt, SingleInt.bit_count - sr); // r.all = a >> sr; - r[high] = n[high] >> Log2SingleInt(sr); - r[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr)); + r[high] = n[high] >> @intCast(Log2SingleInt, sr); + r[low] = (n[high] << @intCast(Log2SingleInt, SingleInt.bit_count - sr)) | (n[low] >> @intCast(Log2SingleInt, sr)); } else { // d[low] != 0 if (d[high] == 0) { @@ -107,8 +107,8 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: return a; } sr = @ctz(d[low]); - q[high] = n[high] >> Log2SingleInt(sr); - q[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr)); + q[high] = n[high] >> @intCast(Log2SingleInt, sr); + q[low] = (n[high] << @intCast(Log2SingleInt, SingleInt.bit_count - sr)) | (n[low] >> @intCast(Log2SingleInt, sr)); return @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &q[0]).*; // TODO issue #421 } // K X @@ -126,15 +126,15 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: } else if (sr < SingleInt.bit_count) { // 2 <= sr <= SingleInt.bit_count - 1 q[low] = 0; - q[high] = n[low] << Log2SingleInt(SingleInt.bit_count - sr); - r[high] = n[high] >> Log2SingleInt(sr); - r[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr)); + q[high] = n[low] << @intCast(Log2SingleInt, SingleInt.bit_count - sr); + r[high] = n[high] >> @intCast(Log2SingleInt, sr); + r[low] = (n[high] << @intCast(Log2SingleInt, SingleInt.bit_count - sr)) | (n[low] >> @intCast(Log2SingleInt, sr)); } else { // SingleInt.bit_count + 1 <= sr <= DoubleInt.bit_count - 1 - q[low] = n[low] << Log2SingleInt(DoubleInt.bit_count - sr); - q[high] = (n[high] << Log2SingleInt(DoubleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr - SingleInt.bit_count)); + q[low] = n[low] << @intCast(Log2SingleInt, DoubleInt.bit_count - sr); + q[high] = (n[high] << @intCast(Log2SingleInt, DoubleInt.bit_count - sr)) | (n[low] >> @intCast(Log2SingleInt, sr - SingleInt.bit_count)); r[high] = 0; - r[low] = n[high] >> Log2SingleInt(sr - SingleInt.bit_count); + r[low] = n[high] >> @intCast(Log2SingleInt, sr - SingleInt.bit_count); } } else { // K X @@ -158,9 +158,9 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: r[high] = 0; r[low] = n[high]; } else { - r[high] = n[high] >> Log2SingleInt(sr); - r[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr)); - q[high] = n[low] << Log2SingleInt(SingleInt.bit_count - sr); + r[high] = n[high] >> @intCast(Log2SingleInt, sr); + r[low] = (n[high] << @intCast(Log2SingleInt, SingleInt.bit_count - sr)) | (n[low] >> @intCast(Log2SingleInt, sr)); + q[high] = n[low] << @intCast(Log2SingleInt, SingleInt.bit_count - sr); } } } @@ -184,8 +184,8 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // carry = 1; // } r_all = @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 - const s: SignedDoubleInt = SignedDoubleInt(b -% r_all -% 1) >> (DoubleInt.bit_count - 1); - carry = u32(s & 1); + const s: SignedDoubleInt = @intCast(SignedDoubleInt, b -% r_all -% 1) >> (DoubleInt.bit_count - 1); + carry = @intCast(u32, s & 1); r_all -= b & @bitCast(DoubleInt, s); r = @ptrCast(*[2]SingleInt, &r_all).*; // TODO issue #421 } diff --git a/std/unicode.zig b/std/unicode.zig index ec808ca4fe..9c329acc68 100644 --- a/std/unicode.zig +++ b/std/unicode.zig @@ -35,22 +35,22 @@ pub fn utf8Encode(c: u32, out: []u8) !u3 { // - Increasing the initial shift by 6 each time // - Each time after the first shorten the shifted // value to a max of 0b111111 (63) - 1 => out[0] = u8(c), // Can just do 0 + codepoint for initial range + 1 => out[0] = @intCast(u8, c), // Can just do 0 + codepoint for initial range 2 => { - out[0] = u8(0b11000000 | (c >> 6)); - out[1] = u8(0b10000000 | (c & 0b111111)); + out[0] = @intCast(u8, 0b11000000 | (c >> 6)); + out[1] = @intCast(u8, 0b10000000 | (c & 0b111111)); }, 3 => { if (0xd800 <= c and c <= 0xdfff) return error.Utf8CannotEncodeSurrogateHalf; - out[0] = u8(0b11100000 | (c >> 12)); - out[1] = u8(0b10000000 | ((c >> 6) & 0b111111)); - out[2] = u8(0b10000000 | (c & 0b111111)); + out[0] = @intCast(u8, 0b11100000 | (c >> 12)); + out[1] = @intCast(u8, 0b10000000 | ((c >> 6) & 0b111111)); + out[2] = @intCast(u8, 0b10000000 | (c & 0b111111)); }, 4 => { - out[0] = u8(0b11110000 | (c >> 18)); - out[1] = u8(0b10000000 | ((c >> 12) & 0b111111)); - out[2] = u8(0b10000000 | ((c >> 6) & 0b111111)); - out[3] = u8(0b10000000 | (c & 0b111111)); + out[0] = @intCast(u8, 0b11110000 | (c >> 18)); + out[1] = @intCast(u8, 0b10000000 | ((c >> 12) & 0b111111)); + out[2] = @intCast(u8, 0b10000000 | ((c >> 6) & 0b111111)); + out[3] = @intCast(u8, 0b10000000 | (c & 0b111111)); }, else => unreachable, } diff --git a/std/zig/tokenizer.zig b/std/zig/tokenizer.zig index 4534529f36..79f1871b64 100644 --- a/std/zig/tokenizer.zig +++ b/std/zig/tokenizer.zig @@ -1128,7 +1128,7 @@ pub const Tokenizer = struct { // check utf8-encoded character. const length = std.unicode.utf8ByteSequenceLength(c0) catch return 1; if (self.index + length > self.buffer.len) { - return u3(self.buffer.len - self.index); + return @intCast(u3, self.buffer.len - self.index); } const bytes = self.buffer[self.index .. self.index + length]; switch (length) { diff --git a/test/cases/cast.zig b/test/cases/cast.zig index 4c216010eb..7035740c54 100644 --- a/test/cases/cast.zig +++ b/test/cases/cast.zig @@ -343,7 +343,7 @@ fn testPeerErrorAndArray2(x: u8) error![]const u8 { test "explicit cast float number literal to integer if no fraction component" { const x = i32(1e4); assert(x == 10000); - const y = i32(f32(1e4)); + const y = @floatToInt(i32, f32(1e4)); assert(y == 10000); } @@ -398,3 +398,19 @@ test "cast *[1][*]const u8 to [*]const ?[*]const u8" { const x: [*]const ?[*]const u8 = &window_name; assert(mem.eql(u8, std.cstr.toSliceConst(x[0].?), "window name")); } + +test "@intCast comptime_int" { + const result = @intCast(i32, 1234); + assert(@typeOf(result) == i32); + assert(result == 1234); +} + +test "@floatCast comptime_int and comptime_float" { + const result = @floatCast(f32, 1234); + assert(@typeOf(result) == f32); + assert(result == 1234.0); + + const result2 = @floatCast(f32, 1234.0); + assert(@typeOf(result) == f32); + assert(result == 1234.0); +} diff --git a/test/cases/enum.zig b/test/cases/enum.zig index 5c78d73092..6a02a47784 100644 --- a/test/cases/enum.zig +++ b/test/cases/enum.zig @@ -99,7 +99,7 @@ test "int to enum" { testIntToEnumEval(3); } fn testIntToEnumEval(x: i32) void { - assert(IntToEnumNumber(u3(x)) == IntToEnumNumber.Three); + assert(IntToEnumNumber(@intCast(u3, x)) == IntToEnumNumber.Three); } const IntToEnumNumber = enum { Zero, diff --git a/test/cases/eval.zig b/test/cases/eval.zig index 08d3f3a841..6c919e17a6 100644 --- a/test/cases/eval.zig +++ b/test/cases/eval.zig @@ -5,7 +5,7 @@ const builtin = @import("builtin"); test "compile time recursion" { assert(some_data.len == 21); } -var some_data: [usize(fibonacci(7))]u8 = undefined; +var some_data: [@intCast(usize, fibonacci(7))]u8 = undefined; fn fibonacci(x: i32) i32 { if (x <= 1) return 1; return fibonacci(x - 1) + fibonacci(x - 2); @@ -356,7 +356,7 @@ const global_array = x: { test "compile-time downcast when the bits fit" { comptime { const spartan_count: u16 = 255; - const byte = u8(spartan_count); + const byte = @intCast(u8, spartan_count); assert(byte == 255); } } @@ -440,7 +440,7 @@ test "binary math operator in partially inlined function" { var b: [16]u8 = undefined; for (b) |*r, i| - r.* = u8(i + 1); + r.* = @intCast(u8, i + 1); copyWithPartialInline(s[0..], b[0..]); assert(s[0] == 0x1020304); @@ -480,7 +480,7 @@ fn generateTable(comptime T: type) [1010]T { var res: [1010]T = undefined; var i: usize = 0; while (i < 1010) : (i += 1) { - res[i] = T(i); + res[i] = @intCast(T, i); } return res; } diff --git a/test/cases/fn.zig b/test/cases/fn.zig index 12f22bfc35..47f7d5e688 100644 --- a/test/cases/fn.zig +++ b/test/cases/fn.zig @@ -80,7 +80,7 @@ test "function pointers" { fn4, }; for (fns) |f, i| { - assert(f() == u32(i) + 5); + assert(f() == @intCast(u32, i) + 5); } } fn fn1() u32 { diff --git a/test/cases/for.zig b/test/cases/for.zig index bdbab312f6..59d90c1b85 100644 --- a/test/cases/for.zig +++ b/test/cases/for.zig @@ -46,7 +46,7 @@ test "basic for loop" { buf_index += 1; } for (array) |item, index| { - buffer[buf_index] = u8(index); + buffer[buf_index] = @intCast(u8, index); buf_index += 1; } const unknown_size: []const u8 = array; @@ -55,7 +55,7 @@ test "basic for loop" { buf_index += 1; } for (unknown_size) |item, index| { - buffer[buf_index] = u8(index); + buffer[buf_index] = @intCast(u8, index); buf_index += 1; } diff --git a/test/cases/struct.zig b/test/cases/struct.zig index 6952611a8c..94a2ba6336 100644 --- a/test/cases/struct.zig +++ b/test/cases/struct.zig @@ -365,14 +365,14 @@ test "runtime struct initialization of bitfield" { .y = x1, }; const s2 = Nibbles{ - .x = u4(x2), - .y = u4(x2), + .x = @intCast(u4, x2), + .y = @intCast(u4, x2), }; assert(s1.x == x1); assert(s1.y == x1); - assert(s2.x == u4(x2)); - assert(s2.y == u4(x2)); + assert(s2.x == @intCast(u4, x2)); + assert(s2.y == @intCast(u4, x2)); } var x1 = u4(1); -- cgit v1.2.3 From eb326e15530dd6dca4ccbe7dbfde7bf048de813e Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 5 Jul 2018 15:09:02 -0400 Subject: M:N threading * add std.atomic.QueueMpsc.isEmpty * make std.debug.global_allocator thread-safe * std.event.Loop: now you have to choose between - initSingleThreaded - initMultiThreaded * std.event.Loop multiplexes coroutines onto kernel threads * Remove std.event.Loop.stop. Instead the event loop run() function returns once there are no pending coroutines. * fix crash in ir.cpp for calling methods under some conditions * small progress self-hosted compiler, analyzing top level declarations * Introduce std.event.Lock for synchronizing coroutines * introduce std.event.Locked(T) for data that only 1 coroutine should modify at once. * make the self hosted compiler use multi threaded event loop * make std.heap.DirectAllocator thread-safe See #174 TODO: * call sched_getaffinity instead of hard coding thread pool size 4 * support for Windows and MacOS * #1194 * #1197 --- src-self-hosted/main.zig | 5 +- src-self-hosted/module.zig | 257 ++++++++++++++++++-- src/ir.cpp | 2 +- std/atomic/queue_mpsc.zig | 17 ++ std/debug/index.zig | 7 +- std/event.zig | 580 +++++++++++++++++++++++++++++++++++++++------ std/heap.zig | 30 +-- std/mem.zig | 2 +- std/os/index.zig | 39 ++- std/os/linux/index.zig | 8 + 10 files changed, 833 insertions(+), 114 deletions(-) (limited to 'std/os/linux') diff --git a/src-self-hosted/main.zig b/src-self-hosted/main.zig index d17fc94c82..fe94a4460a 100644 --- a/src-self-hosted/main.zig +++ b/src-self-hosted/main.zig @@ -384,7 +384,8 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Mo const zig_lib_dir = introspect.resolveZigLibDir(allocator) catch os.exit(1); defer allocator.free(zig_lib_dir); - var loop = try event.Loop.init(allocator); + var loop: event.Loop = undefined; + try loop.initMultiThreaded(allocator); var module = try Module.create( &loop, @@ -493,8 +494,6 @@ async fn processBuildEvents(module: *Module, watch: bool) void { switch (build_event) { Module.Event.Ok => { std.debug.warn("Build succeeded\n"); - // for now we stop after 1 - module.loop.stop(); return; }, Module.Event.Error => |err| { diff --git a/src-self-hosted/module.zig b/src-self-hosted/module.zig index cf27c826c8..5ce1a7965a 100644 --- a/src-self-hosted/module.zig +++ b/src-self-hosted/module.zig @@ -2,6 +2,7 @@ const std = @import("std"); const os = std.os; const io = std.io; const mem = std.mem; +const Allocator = mem.Allocator; const Buffer = std.Buffer; const llvm = @import("llvm.zig"); const c = @import("c.zig"); @@ -13,6 +14,7 @@ const ArrayList = std.ArrayList; const errmsg = @import("errmsg.zig"); const ast = std.zig.ast; const event = std.event; +const assert = std.debug.assert; pub const Module = struct { loop: *event.Loop, @@ -81,6 +83,8 @@ pub const Module = struct { link_out_file: ?[]const u8, events: *event.Channel(Event), + exported_symbol_names: event.Locked(Decl.Table), + // TODO handle some of these earlier and report them in a way other than error codes pub const BuildError = error{ OutOfMemory, @@ -232,6 +236,7 @@ pub const Module = struct { .test_name_prefix = null, .emit_file_type = Emit.Binary, .link_out_file = null, + .exported_symbol_names = event.Locked(Decl.Table).init(loop, Decl.Table.init(loop.allocator)), }); } @@ -272,38 +277,91 @@ pub const Module = struct { return; }; await (async self.events.put(Event.Ok) catch unreachable); + // for now we stop after 1 + return; } } async fn addRootSrc(self: *Module) !void { const root_src_path = self.root_src_path orelse @panic("TODO handle null root src path"); + // TODO async/await os.path.real const root_src_real_path = os.path.real(self.a(), root_src_path) catch |err| { try printError("unable to get real path '{}': {}", root_src_path, err); return err; }; errdefer self.a().free(root_src_real_path); + // TODO async/await readFileAlloc() const source_code = io.readFileAlloc(self.a(), root_src_real_path) catch |err| { try printError("unable to open '{}': {}", root_src_real_path, err); return err; }; errdefer self.a().free(source_code); - var tree = try std.zig.parse(self.a(), source_code); - defer tree.deinit(); - - //var it = tree.root_node.decls.iterator(); - //while (it.next()) |decl_ptr| { - // const decl = decl_ptr.*; - // switch (decl.id) { - // ast.Node.Comptime => @panic("TODO"), - // ast.Node.VarDecl => @panic("TODO"), - // ast.Node.UseDecl => @panic("TODO"), - // ast.Node.FnDef => @panic("TODO"), - // ast.Node.TestDecl => @panic("TODO"), - // else => unreachable, - // } - //} + var parsed_file = ParsedFile{ + .tree = try std.zig.parse(self.a(), source_code), + .realpath = root_src_real_path, + }; + errdefer parsed_file.tree.deinit(); + + const tree = &parsed_file.tree; + + // create empty struct for it + const decls = try Scope.Decls.create(self.a(), null); + errdefer decls.destroy(); + + var it = tree.root_node.decls.iterator(0); + while (it.next()) |decl_ptr| { + const decl = decl_ptr.*; + switch (decl.id) { + ast.Node.Id.Comptime => @panic("TODO"), + ast.Node.Id.VarDecl => @panic("TODO"), + ast.Node.Id.FnProto => { + const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl); + + const name = if (fn_proto.name_token) |name_token| tree.tokenSlice(name_token) else { + @panic("TODO add compile error"); + //try self.addCompileError( + // &parsed_file, + // fn_proto.fn_token, + // fn_proto.fn_token + 1, + // "missing function name", + //); + continue; + }; + + const fn_decl = try self.a().create(Decl.Fn{ + .base = Decl{ + .id = Decl.Id.Fn, + .name = name, + .visib = parseVisibToken(tree, fn_proto.visib_token), + .resolution = Decl.Resolution.Unresolved, + }, + .value = Decl.Fn.Val{ .Unresolved = {} }, + .fn_proto = fn_proto, + }); + errdefer self.a().destroy(fn_decl); + + // TODO make this parallel + try await try async self.addTopLevelDecl(tree, &fn_decl.base); + }, + ast.Node.Id.TestDecl => @panic("TODO"), + else => unreachable, + } + } + } + + async fn addTopLevelDecl(self: *Module, tree: *ast.Tree, decl: *Decl) !void { + const is_export = decl.isExported(tree); + + { + const exported_symbol_names = await try async self.exported_symbol_names.acquire(); + defer exported_symbol_names.release(); + + if (try exported_symbol_names.value.put(decl.name, decl)) |other_decl| { + @panic("TODO report compile error"); + } + } } pub fn link(self: *Module, out_file: ?[]const u8) !void { @@ -350,3 +408,172 @@ fn printError(comptime format: []const u8, args: ...) !void { const out_stream = &stderr_file_out_stream.stream; try out_stream.print(format, args); } + +fn parseVisibToken(tree: *ast.Tree, optional_token_index: ?ast.TokenIndex) Visib { + if (optional_token_index) |token_index| { + const token = tree.tokens.at(token_index); + assert(token.id == Token.Id.Keyword_pub); + return Visib.Pub; + } else { + return Visib.Private; + } +} + +pub const Scope = struct { + id: Id, + parent: ?*Scope, + + pub const Id = enum { + Decls, + Block, + }; + + pub const Decls = struct { + base: Scope, + table: Decl.Table, + + pub fn create(a: *Allocator, parent: ?*Scope) !*Decls { + const self = try a.create(Decls{ + .base = Scope{ + .id = Id.Decls, + .parent = parent, + }, + .table = undefined, + }); + errdefer a.destroy(self); + + self.table = Decl.Table.init(a); + errdefer self.table.deinit(); + + return self; + } + + pub fn destroy(self: *Decls) void { + self.table.deinit(); + self.table.allocator.destroy(self); + self.* = undefined; + } + }; + + pub const Block = struct { + base: Scope, + }; +}; + +pub const Visib = enum { + Private, + Pub, +}; + +pub const Decl = struct { + id: Id, + name: []const u8, + visib: Visib, + resolution: Resolution, + + pub const Table = std.HashMap([]const u8, *Decl, mem.hash_slice_u8, mem.eql_slice_u8); + + pub fn isExported(base: *const Decl, tree: *ast.Tree) bool { + switch (base.id) { + Id.Fn => { + const fn_decl = @fieldParentPtr(Fn, "base", base); + return fn_decl.isExported(tree); + }, + else => return false, + } + } + + pub const Resolution = enum { + Unresolved, + InProgress, + Invalid, + Ok, + }; + + pub const Id = enum { + Var, + Fn, + CompTime, + }; + + pub const Var = struct { + base: Decl, + }; + + pub const Fn = struct { + base: Decl, + value: Val, + fn_proto: *const ast.Node.FnProto, + + // TODO https://github.com/ziglang/zig/issues/683 and then make this anonymous + pub const Val = union { + Unresolved: void, + Ok: *Value.Fn, + }; + + pub fn externLibName(self: Fn, tree: *ast.Tree) ?[]const u8 { + return if (self.fn_proto.extern_export_inline_token) |tok_index| x: { + const token = tree.tokens.at(tok_index); + break :x switch (token.id) { + Token.Id.Extern => tree.tokenSlicePtr(token), + else => null, + }; + } else null; + } + + pub fn isExported(self: Fn, tree: *ast.Tree) bool { + if (self.fn_proto.extern_export_inline_token) |tok_index| { + const token = tree.tokens.at(tok_index); + return token.id == Token.Id.Keyword_export; + } else { + return false; + } + } + }; + + pub const CompTime = struct { + base: Decl, + }; +}; + +pub const Value = struct { + pub const Fn = struct {}; +}; + +pub const Type = struct { + id: Id, + + pub const Id = enum { + Type, + Void, + Bool, + NoReturn, + Int, + Float, + Pointer, + Array, + Struct, + ComptimeFloat, + ComptimeInt, + Undefined, + Null, + Optional, + ErrorUnion, + ErrorSet, + Enum, + Union, + Fn, + Opaque, + Promise, + }; + + pub const Struct = struct { + base: Type, + decls: *Scope.Decls, + }; +}; + +pub const ParsedFile = struct { + tree: ast.Tree, + realpath: []const u8, +}; diff --git a/src/ir.cpp b/src/ir.cpp index 98b1bd85ad..3fc8306339 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -13278,7 +13278,7 @@ static TypeTableEntry *ir_analyze_instruction_call(IrAnalyze *ira, IrInstruction FnTableEntry *fn_table_entry = fn_ref->value.data.x_bound_fn.fn; IrInstruction *first_arg_ptr = fn_ref->value.data.x_bound_fn.first_arg; return ir_analyze_fn_call(ira, call_instruction, fn_table_entry, fn_table_entry->type_entry, - nullptr, first_arg_ptr, is_comptime, call_instruction->fn_inline); + fn_ref, first_arg_ptr, is_comptime, call_instruction->fn_inline); } else { ir_add_error_node(ira, fn_ref->source_node, buf_sprintf("type '%s' not a function", buf_ptr(&fn_ref->value.type->name))); diff --git a/std/atomic/queue_mpsc.zig b/std/atomic/queue_mpsc.zig index 8030565d7a..bc0a94258b 100644 --- a/std/atomic/queue_mpsc.zig +++ b/std/atomic/queue_mpsc.zig @@ -15,6 +15,8 @@ pub fn QueueMpsc(comptime T: type) type { pub const Node = std.atomic.Stack(T).Node; + /// Not thread-safe. The call to init() must complete before any other functions are called. + /// No deinitialization required. pub fn init() Self { return Self{ .inboxes = []std.atomic.Stack(T){ @@ -26,12 +28,15 @@ pub fn QueueMpsc(comptime T: type) type { }; } + /// Fully thread-safe. put() may be called from any thread at any time. pub fn put(self: *Self, node: *Node) void { const inbox_index = @atomicLoad(usize, &self.inbox_index, AtomicOrder.SeqCst); const inbox = &self.inboxes[inbox_index]; inbox.push(node); } + /// Must be called by only 1 consumer at a time. Every call to get() and isEmpty() must complete before + /// the next call to get(). pub fn get(self: *Self) ?*Node { if (self.outbox.pop()) |node| { return node; @@ -43,6 +48,18 @@ pub fn QueueMpsc(comptime T: type) type { } return self.outbox.pop(); } + + /// Must be called by only 1 consumer at a time. Every call to get() and isEmpty() must complete before + /// the next call to isEmpty(). + pub fn isEmpty(self: *Self) bool { + if (!self.outbox.isEmpty()) return false; + const prev_inbox_index = @atomicRmw(usize, &self.inbox_index, AtomicRmwOp.Xor, 0x1, AtomicOrder.SeqCst); + const prev_inbox = &self.inboxes[prev_inbox_index]; + while (prev_inbox.pop()) |node| { + self.outbox.push(node); + } + return self.outbox.isEmpty(); + } }; } diff --git a/std/debug/index.zig b/std/debug/index.zig index 57b2dfc300..a5e1c313f0 100644 --- a/std/debug/index.zig +++ b/std/debug/index.zig @@ -11,6 +11,11 @@ const builtin = @import("builtin"); pub const FailingAllocator = @import("failing_allocator.zig").FailingAllocator; +pub const runtime_safety = switch (builtin.mode) { + builtin.Mode.Debug, builtin.Mode.ReleaseSafe => true, + builtin.Mode.ReleaseFast, builtin.Mode.ReleaseSmall => false, +}; + /// Tries to write to stderr, unbuffered, and ignores any error returned. /// Does not append a newline. /// TODO atomic/multithread support @@ -1098,7 +1103,7 @@ fn readILeb128(in_stream: var) !i64 { /// This should only be used in temporary test programs. pub const global_allocator = &global_fixed_allocator.allocator; -var global_fixed_allocator = std.heap.FixedBufferAllocator.init(global_allocator_mem[0..]); +var global_fixed_allocator = std.heap.ThreadSafeFixedBufferAllocator.init(global_allocator_mem[0..]); var global_allocator_mem: [100 * 1024]u8 = undefined; // TODO make thread safe diff --git a/std/event.zig b/std/event.zig index c6ac04a9d0..2d69d0cb16 100644 --- a/std/event.zig +++ b/std/event.zig @@ -11,53 +11,69 @@ pub const TcpServer = struct { handleRequestFn: async<*mem.Allocator> fn (*TcpServer, *const std.net.Address, *const std.os.File) void, loop: *Loop, - sockfd: i32, + sockfd: ?i32, accept_coro: ?promise, listen_address: std.net.Address, waiting_for_emfile_node: PromiseNode, + listen_resume_node: event.Loop.ResumeNode, const PromiseNode = std.LinkedList(promise).Node; - pub fn init(loop: *Loop) !TcpServer { - const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp); - errdefer std.os.close(sockfd); - + pub fn init(loop: *Loop) TcpServer { // TODO can't initialize handler coroutine here because we need well defined copy elision return TcpServer{ .loop = loop, - .sockfd = sockfd, + .sockfd = null, .accept_coro = null, .handleRequestFn = undefined, .waiting_for_emfile_node = undefined, .listen_address = undefined, + .listen_resume_node = event.Loop.ResumeNode{ + .id = event.Loop.ResumeNode.Id.Basic, + .handle = undefined, + }, }; } - 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 { + 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 { self.handleRequestFn = handleRequestFn; - try std.os.posixBind(self.sockfd, &address.os_addr); - try std.os.posixListen(self.sockfd, posix.SOMAXCONN); - self.listen_address = std.net.Address.initPosix(try std.os.posixGetSockName(self.sockfd)); + const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp); + errdefer std.os.close(sockfd); + self.sockfd = sockfd; + + try std.os.posixBind(sockfd, &address.os_addr); + try std.os.posixListen(sockfd, posix.SOMAXCONN); + self.listen_address = std.net.Address.initPosix(try std.os.posixGetSockName(sockfd)); self.accept_coro = try async TcpServer.handler(self); errdefer cancel self.accept_coro.?; - try self.loop.addFd(self.sockfd, self.accept_coro.?); - errdefer self.loop.removeFd(self.sockfd); + self.listen_resume_node.handle = self.accept_coro.?; + try self.loop.addFd(sockfd, &self.listen_resume_node); + errdefer self.loop.removeFd(sockfd); + } + + /// Stop listening + pub fn close(self: *TcpServer) void { + self.loop.removeFd(self.sockfd.?); + std.os.close(self.sockfd.?); } pub fn deinit(self: *TcpServer) void { - self.loop.removeFd(self.sockfd); if (self.accept_coro) |accept_coro| cancel accept_coro; - std.os.close(self.sockfd); + if (self.sockfd) |sockfd| std.os.close(sockfd); } pub async fn handler(self: *TcpServer) void { while (true) { var accepted_addr: std.net.Address = undefined; - if (std.os.posixAccept(self.sockfd, &accepted_addr.os_addr, posix.SOCK_NONBLOCK | posix.SOCK_CLOEXEC)) |accepted_fd| { + if (std.os.posixAccept(self.sockfd.?, &accepted_addr.os_addr, posix.SOCK_NONBLOCK | posix.SOCK_CLOEXEC)) |accepted_fd| { var socket = std.os.File.openHandle(accepted_fd); _ = async self.handleRequestFn(self, accepted_addr, socket) catch |err| switch (err) { error.OutOfMemory => { @@ -95,32 +111,65 @@ pub const TcpServer = struct { pub const Loop = struct { allocator: *mem.Allocator, - keep_running: bool, next_tick_queue: std.atomic.QueueMpsc(promise), os_data: OsData, + dispatch_lock: u8, // TODO make this a bool + pending_event_count: usize, + extra_threads: []*std.os.Thread, + final_resume_node: ResumeNode, - const OsData = switch (builtin.os) { - builtin.Os.linux => struct { - epollfd: i32, - }, - else => struct {}, + pub const NextTickNode = std.atomic.QueueMpsc(promise).Node; + + pub const ResumeNode = struct { + id: Id, + handle: promise, + + pub const Id = enum { + Basic, + Stop, + EventFd, + }; + + pub const EventFd = struct { + base: ResumeNode, + eventfd: i32, + }; }; - pub const NextTickNode = std.atomic.QueueMpsc(promise).Node; + /// After initialization, call run(). + /// TODO copy elision / named return values so that the threads referencing *Loop + /// have the correct pointer value. + fn initSingleThreaded(self: *Loop, allocator: *mem.Allocator) !void { + return self.initInternal(allocator, 1); + } /// The allocator must be thread-safe because we use it for multiplexing /// coroutines onto kernel threads. - pub fn init(allocator: *mem.Allocator) !Loop { - var self = Loop{ - .keep_running = true, + /// After initialization, call run(). + /// TODO copy elision / named return values so that the threads referencing *Loop + /// have the correct pointer value. + fn initMultiThreaded(self: *Loop, allocator: *mem.Allocator) !void { + // TODO check the actual cpu core count + return self.initInternal(allocator, 4); + } + + /// Thread count is the total thread count. The thread pool size will be + /// max(thread_count - 1, 0) + fn initInternal(self: *Loop, allocator: *mem.Allocator, thread_count: usize) !void { + self.* = Loop{ + .pending_event_count = 0, .allocator = allocator, .os_data = undefined, .next_tick_queue = std.atomic.QueueMpsc(promise).init(), + .dispatch_lock = 1, // start locked so threads go directly into epoll wait + .extra_threads = undefined, + .final_resume_node = ResumeNode{ + .id = ResumeNode.Id.Stop, + .handle = undefined, + }, }; - try self.initOsData(); + try self.initOsData(thread_count); errdefer self.deinitOsData(); - - return self; } /// must call stop before deinit @@ -128,13 +177,70 @@ pub const Loop = struct { self.deinitOsData(); } - const InitOsDataError = std.os.LinuxEpollCreateError; + const InitOsDataError = std.os.LinuxEpollCreateError || mem.Allocator.Error || std.os.LinuxEventFdError || + std.os.SpawnThreadError || std.os.LinuxEpollCtlError; + + const wakeup_bytes = []u8{0x1} ** 8; - fn initOsData(self: *Loop) InitOsDataError!void { + fn initOsData(self: *Loop, thread_count: usize) InitOsDataError!void { switch (builtin.os) { builtin.Os.linux => { - self.os_data.epollfd = try std.os.linuxEpollCreate(std.os.linux.EPOLL_CLOEXEC); + const extra_thread_count = thread_count - 1; + self.os_data.available_eventfd_resume_nodes = std.atomic.Stack(ResumeNode.EventFd).init(); + self.os_data.eventfd_resume_nodes = try self.allocator.alloc( + std.atomic.Stack(ResumeNode.EventFd).Node, + extra_thread_count, + ); + errdefer self.allocator.free(self.os_data.eventfd_resume_nodes); + + errdefer { + while (self.os_data.available_eventfd_resume_nodes.pop()) |node| std.os.close(node.data.eventfd); + } + for (self.os_data.eventfd_resume_nodes) |*eventfd_node| { + eventfd_node.* = std.atomic.Stack(ResumeNode.EventFd).Node{ + .data = ResumeNode.EventFd{ + .base = ResumeNode{ + .id = ResumeNode.Id.EventFd, + .handle = undefined, + }, + .eventfd = try std.os.linuxEventFd(1, posix.EFD_CLOEXEC | posix.EFD_NONBLOCK), + }, + .next = undefined, + }; + self.os_data.available_eventfd_resume_nodes.push(eventfd_node); + } + + self.os_data.epollfd = try std.os.linuxEpollCreate(posix.EPOLL_CLOEXEC); errdefer std.os.close(self.os_data.epollfd); + + self.os_data.final_eventfd = try std.os.linuxEventFd(0, posix.EFD_CLOEXEC | posix.EFD_NONBLOCK); + errdefer std.os.close(self.os_data.final_eventfd); + + self.os_data.final_eventfd_event = posix.epoll_event{ + .events = posix.EPOLLIN, + .data = posix.epoll_data{ .ptr = @ptrToInt(&self.final_resume_node) }, + }; + try std.os.linuxEpollCtl( + self.os_data.epollfd, + posix.EPOLL_CTL_ADD, + self.os_data.final_eventfd, + &self.os_data.final_eventfd_event, + ); + self.extra_threads = try self.allocator.alloc(*std.os.Thread, extra_thread_count); + errdefer self.allocator.free(self.extra_threads); + + var extra_thread_index: usize = 0; + errdefer { + while (extra_thread_index != 0) { + extra_thread_index -= 1; + // writing 8 bytes to an eventfd cannot fail + std.os.posixWrite(self.os_data.final_eventfd, wakeup_bytes) catch unreachable; + self.extra_threads[extra_thread_index].wait(); + } + } + while (extra_thread_index < extra_thread_count) : (extra_thread_index += 1) { + self.extra_threads[extra_thread_index] = try std.os.spawnThread(self, workerRun); + } }, else => {}, } @@ -142,65 +248,154 @@ pub const Loop = struct { fn deinitOsData(self: *Loop) void { switch (builtin.os) { - builtin.Os.linux => std.os.close(self.os_data.epollfd), + builtin.Os.linux => { + std.os.close(self.os_data.final_eventfd); + while (self.os_data.available_eventfd_resume_nodes.pop()) |node| std.os.close(node.data.eventfd); + std.os.close(self.os_data.epollfd); + self.allocator.free(self.os_data.eventfd_resume_nodes); + self.allocator.free(self.extra_threads); + }, else => {}, } } - pub fn addFd(self: *Loop, fd: i32, prom: promise) !void { + /// resume_node must live longer than the promise that it holds a reference to. + pub fn addFd(self: *Loop, fd: i32, resume_node: *ResumeNode) !void { + _ = @atomicRmw(usize, &self.pending_event_count, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); + errdefer { + _ = @atomicRmw(usize, &self.pending_event_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); + } + try self.addFdNoCounter(fd, resume_node); + } + + fn addFdNoCounter(self: *Loop, fd: i32, resume_node: *ResumeNode) !void { var ev = std.os.linux.epoll_event{ .events = std.os.linux.EPOLLIN | std.os.linux.EPOLLOUT | std.os.linux.EPOLLET, - .data = std.os.linux.epoll_data{ .ptr = @ptrToInt(prom) }, + .data = std.os.linux.epoll_data{ .ptr = @ptrToInt(resume_node) }, }; try std.os.linuxEpollCtl(self.os_data.epollfd, std.os.linux.EPOLL_CTL_ADD, fd, &ev); } pub fn removeFd(self: *Loop, fd: i32) void { + self.removeFdNoCounter(fd); + _ = @atomicRmw(usize, &self.pending_event_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); + } + + fn removeFdNoCounter(self: *Loop, fd: i32) void { std.os.linuxEpollCtl(self.os_data.epollfd, std.os.linux.EPOLL_CTL_DEL, fd, undefined) catch {}; } - async fn waitFd(self: *Loop, fd: i32) !void { + + pub async fn waitFd(self: *Loop, fd: i32) !void { defer self.removeFd(fd); + var resume_node = ResumeNode{ + .id = ResumeNode.Id.Basic, + .handle = undefined, + }; suspend |p| { - try self.addFd(fd, p); + resume_node.handle = p; + try self.addFd(fd, &resume_node); } + var a = &resume_node; // TODO better way to explicitly put memory in coro frame } - pub fn stop(self: *Loop) void { - // TODO make atomic - self.keep_running = false; - // TODO activate an fd in the epoll set which should cancel all the promises - } - - /// bring your own linked list node. this means it can't fail. + /// Bring your own linked list node. This means it can't fail. pub fn onNextTick(self: *Loop, node: *NextTickNode) void { + _ = @atomicRmw(usize, &self.pending_event_count, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); self.next_tick_queue.put(node); } pub fn run(self: *Loop) void { - while (self.keep_running) { - // TODO multiplex the next tick queue and the epoll event results onto a thread pool - while (self.next_tick_queue.get()) |node| { - resume node.data; - } - if (!self.keep_running) break; - - self.dispatchOsEvents(); + _ = @atomicRmw(u8, &self.dispatch_lock, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); + self.workerRun(); + for (self.extra_threads) |extra_thread| { + extra_thread.wait(); } } - fn dispatchOsEvents(self: *Loop) void { - switch (builtin.os) { - builtin.Os.linux => { - var events: [16]std.os.linux.epoll_event = undefined; - const count = std.os.linuxEpollWait(self.os_data.epollfd, events[0..], -1); - for (events[0..count]) |ev| { - const p = @intToPtr(promise, ev.data.ptr); - resume p; + fn workerRun(self: *Loop) void { + start_over: while (true) { + if (@atomicRmw(u8, &self.dispatch_lock, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst) == 0) { + while (self.next_tick_queue.get()) |next_tick_node| { + const handle = next_tick_node.data; + if (self.next_tick_queue.isEmpty()) { + // last node, just resume it + _ = @atomicRmw(u8, &self.dispatch_lock, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); + resume handle; + _ = @atomicRmw(usize, &self.pending_event_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); + continue :start_over; + } + + // non-last node, stick it in the epoll set so that + // other threads can get to it + if (self.os_data.available_eventfd_resume_nodes.pop()) |resume_stack_node| { + const eventfd_node = &resume_stack_node.data; + eventfd_node.base.handle = handle; + // the pending count is already accounted for + self.addFdNoCounter(eventfd_node.eventfd, &eventfd_node.base) catch |_| { + // fine, we didn't need it anyway + _ = @atomicRmw(u8, &self.dispatch_lock, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); + self.os_data.available_eventfd_resume_nodes.push(resume_stack_node); + resume handle; + _ = @atomicRmw(usize, &self.pending_event_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); + continue :start_over; + }; + } else { + // threads are too busy, can't add another eventfd to wake one up + _ = @atomicRmw(u8, &self.dispatch_lock, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); + resume handle; + _ = @atomicRmw(usize, &self.pending_event_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); + continue :start_over; + } } - }, - else => {}, + + const pending_event_count = @atomicLoad(usize, &self.pending_event_count, AtomicOrder.SeqCst); + if (pending_event_count == 0) { + // cause all the threads to stop + // writing 8 bytes to an eventfd cannot fail + std.os.posixWrite(self.os_data.final_eventfd, wakeup_bytes) catch unreachable; + return; + } + + _ = @atomicRmw(u8, &self.dispatch_lock, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); + } + + // only process 1 event so we don't steal from other threads + var events: [1]std.os.linux.epoll_event = undefined; + const count = std.os.linuxEpollWait(self.os_data.epollfd, events[0..], -1); + for (events[0..count]) |ev| { + const resume_node = @intToPtr(*ResumeNode, ev.data.ptr); + const handle = resume_node.handle; + const resume_node_id = resume_node.id; + switch (resume_node_id) { + ResumeNode.Id.Basic => {}, + ResumeNode.Id.Stop => return, + ResumeNode.Id.EventFd => { + const event_fd_node = @fieldParentPtr(ResumeNode.EventFd, "base", resume_node); + self.removeFdNoCounter(event_fd_node.eventfd); + const stack_node = @fieldParentPtr(std.atomic.Stack(ResumeNode.EventFd).Node, "data", event_fd_node); + self.os_data.available_eventfd_resume_nodes.push(stack_node); + }, + } + resume handle; + if (resume_node_id == ResumeNode.Id.EventFd) { + _ = @atomicRmw(usize, &self.pending_event_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst); + } + } } } + + const OsData = switch (builtin.os) { + builtin.Os.linux => struct { + epollfd: i32, + // pre-allocated eventfds. all permanently active. + // this is how we send promises to be resumed on other threads. + available_eventfd_resume_nodes: std.atomic.Stack(ResumeNode.EventFd), + eventfd_resume_nodes: []std.atomic.Stack(ResumeNode.EventFd).Node, + final_eventfd: i32, + final_eventfd_event: posix.epoll_event, + }, + else => struct {}, + }; }; /// many producer, many consumer, thread-safe, lock-free, runtime configurable buffer size @@ -304,9 +499,7 @@ pub fn Channel(comptime T: type) type { // TODO integrate this function with named return values // so we can get rid of this extra result copy var result: T = undefined; - var debug_handle: usize = undefined; suspend |handle| { - debug_handle = @ptrToInt(handle); var my_tick_node = Loop.NextTickNode{ .next = undefined, .data = handle, @@ -438,9 +631,8 @@ test "listen on a port, send bytes, receive bytes" { const self = @fieldParentPtr(Self, "tcp_server", tcp_server); var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/733 defer socket.close(); - const next_handler = async errorableHandler(self, _addr, socket) catch |err| switch (err) { - error.OutOfMemory => @panic("unable to handle connection: out of memory"), - }; + // TODO guarantee elision of this allocation + const next_handler = async errorableHandler(self, _addr, socket) catch unreachable; (await next_handler) catch |err| { std.debug.panic("unable to handle connection: {}\n", err); }; @@ -461,17 +653,18 @@ test "listen on a port, send bytes, receive bytes" { const ip4addr = std.net.parseIp4("127.0.0.1") catch unreachable; const addr = std.net.Address.initIp4(ip4addr, 0); - var loop = try Loop.init(std.debug.global_allocator); - var server = MyServer{ .tcp_server = try TcpServer.init(&loop) }; + var loop: Loop = undefined; + try loop.initSingleThreaded(std.debug.global_allocator); + var server = MyServer{ .tcp_server = TcpServer.init(&loop) }; defer server.tcp_server.deinit(); try server.tcp_server.listen(addr, MyServer.handler); - const p = try async doAsyncTest(&loop, server.tcp_server.listen_address); + const p = try async doAsyncTest(&loop, server.tcp_server.listen_address, &server.tcp_server); defer cancel p; loop.run(); } -async fn doAsyncTest(loop: *Loop, address: *const std.net.Address) void { +async fn doAsyncTest(loop: *Loop, address: *const std.net.Address, server: *TcpServer) void { errdefer @panic("test failure"); var socket_file = try await try async event.connect(loop, address); @@ -481,7 +674,7 @@ async fn doAsyncTest(loop: *Loop, address: *const std.net.Address) void { const amt_read = try socket_file.read(buf[0..]); const msg = buf[0..amt_read]; assert(mem.eql(u8, msg, "hello from server\n")); - loop.stop(); + server.close(); } test "std.event.Channel" { @@ -490,7 +683,9 @@ test "std.event.Channel" { const allocator = &da.allocator; - var loop = try Loop.init(allocator); + var loop: Loop = undefined; + // TODO make a multi threaded test + try loop.initSingleThreaded(allocator); defer loop.deinit(); const channel = try Channel(i32).create(&loop, 0); @@ -515,11 +710,248 @@ async fn testChannelGetter(loop: *Loop, channel: *Channel(i32)) void { const value2_promise = try async channel.get(); const value2 = await value2_promise; assert(value2 == 4567); - - loop.stop(); } async fn testChannelPutter(channel: *Channel(i32)) void { await (async channel.put(1234) catch @panic("out of memory")); await (async channel.put(4567) catch @panic("out of memory")); } + +/// Thread-safe async/await lock. +/// Does not make any syscalls - coroutines which are waiting for the lock are suspended, and +/// are resumed when the lock is released, in order. +pub const Lock = struct { + loop: *Loop, + shared_bit: u8, // TODO make this a bool + queue: Queue, + queue_empty_bit: u8, // TODO make this a bool + + const Queue = std.atomic.QueueMpsc(promise); + + pub const Held = struct { + lock: *Lock, + + pub fn release(self: Held) void { + // Resume the next item from the queue. + if (self.lock.queue.get()) |node| { + self.lock.loop.onNextTick(node); + return; + } + + // We need to release the lock. + _ = @atomicRmw(u8, &self.lock.queue_empty_bit, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst); + _ = @atomicRmw(u8, &self.lock.shared_bit, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); + + // There might be a queue item. If we know the queue is empty, we can be done, + // because the other actor will try to obtain the lock. + // But if there's a queue item, we are the actor which must loop and attempt + // to grab the lock again. + if (@atomicLoad(u8, &self.lock.queue_empty_bit, AtomicOrder.SeqCst) == 1) { + return; + } + + while (true) { + const old_bit = @atomicRmw(u8, &self.lock.shared_bit, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst); + if (old_bit != 0) { + // We did not obtain the lock. Great, the queue is someone else's problem. + return; + } + + // Resume the next item from the queue. + if (self.lock.queue.get()) |node| { + self.lock.loop.onNextTick(node); + return; + } + + // Release the lock again. + _ = @atomicRmw(u8, &self.lock.queue_empty_bit, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst); + _ = @atomicRmw(u8, &self.lock.shared_bit, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); + + // Find out if we can be done. + if (@atomicLoad(u8, &self.lock.queue_empty_bit, AtomicOrder.SeqCst) == 1) { + return; + } + } + } + }; + + pub fn init(loop: *Loop) Lock { + return Lock{ + .loop = loop, + .shared_bit = 0, + .queue = Queue.init(), + .queue_empty_bit = 1, + }; + } + + /// Must be called when not locked. Not thread safe. + /// All calls to acquire() and release() must complete before calling deinit(). + pub fn deinit(self: *Lock) void { + assert(self.shared_bit == 0); + while (self.queue.get()) |node| cancel node.data; + } + + pub async fn acquire(self: *Lock) Held { + var my_tick_node: Loop.NextTickNode = undefined; + + s: suspend |handle| { + my_tick_node.data = handle; + self.queue.put(&my_tick_node); + + // At this point, we are in the queue, so we might have already been resumed and this coroutine + // frame might be destroyed. For the rest of the suspend block we cannot access the coroutine frame. + + // We set this bit so that later we can rely on the fact, that if queue_empty_bit is 1, some actor + // will attempt to grab the lock. + _ = @atomicRmw(u8, &self.queue_empty_bit, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); + + while (true) { + const old_bit = @atomicRmw(u8, &self.shared_bit, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst); + if (old_bit != 0) { + // We did not obtain the lock. Trust that our queue entry will resume us, and allow + // suspend to complete. + break; + } + // We got the lock. However we might have already been resumed from the queue. + if (self.queue.get()) |node| { + // Whether this node is us or someone else, we tail resume it. + resume node.data; + break; + } else { + // We already got resumed, and there are none left in the queue, which means that + // we aren't even supposed to hold the lock right now. + _ = @atomicRmw(u8, &self.queue_empty_bit, AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst); + _ = @atomicRmw(u8, &self.shared_bit, AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst); + + // There might be a queue item. If we know the queue is empty, we can be done, + // because the other actor will try to obtain the lock. + // But if there's a queue item, we are the actor which must loop and attempt + // to grab the lock again. + if (@atomicLoad(u8, &self.queue_empty_bit, AtomicOrder.SeqCst) == 1) { + break; + } else { + continue; + } + } + unreachable; + } + } + + // TODO this workaround to force my_tick_node to be in the coroutine frame should + // not be necessary + var trash1 = &my_tick_node; + + return Held{ .lock = self }; + } +}; + +/// Thread-safe async/await lock that protects one piece of data. +/// Does not make any syscalls - coroutines which are waiting for the lock are suspended, and +/// are resumed when the lock is released, in order. +pub fn Locked(comptime T: type) type { + return struct { + lock: Lock, + private_data: T, + + const Self = this; + + pub const HeldLock = struct { + value: *T, + held: Lock.Held, + + pub fn release(self: HeldLock) void { + self.held.release(); + } + }; + + pub fn init(loop: *Loop, data: T) Self { + return Self{ + .lock = Lock.init(loop), + .private_data = data, + }; + } + + pub fn deinit(self: *Self) void { + self.lock.deinit(); + } + + pub async fn acquire(self: *Self) HeldLock { + return HeldLock{ + // TODO guaranteed allocation elision + .held = await (async self.lock.acquire() catch unreachable), + .value = &self.private_data, + }; + } + }; +} + +test "std.event.Lock" { + var da = std.heap.DirectAllocator.init(); + defer da.deinit(); + + const allocator = &da.allocator; + + var loop: Loop = undefined; + try loop.initMultiThreaded(allocator); + defer loop.deinit(); + + var lock = Lock.init(&loop); + defer lock.deinit(); + + const handle = try async testLock(&loop, &lock); + defer cancel handle; + loop.run(); + + assert(mem.eql(i32, shared_test_data, [1]i32{3 * 10} ** 10)); +} + +async fn testLock(loop: *Loop, lock: *Lock) void { + const handle1 = async lockRunner(lock) catch @panic("out of memory"); + var tick_node1 = Loop.NextTickNode{ + .next = undefined, + .data = handle1, + }; + loop.onNextTick(&tick_node1); + + const handle2 = async lockRunner(lock) catch @panic("out of memory"); + var tick_node2 = Loop.NextTickNode{ + .next = undefined, + .data = handle2, + }; + loop.onNextTick(&tick_node2); + + const handle3 = async lockRunner(lock) catch @panic("out of memory"); + var tick_node3 = Loop.NextTickNode{ + .next = undefined, + .data = handle3, + }; + loop.onNextTick(&tick_node3); + + await handle1; + await handle2; + await handle3; + + // TODO this is to force tick node memory to be in the coro frame + // there should be a way to make it explicit where the memory is + var a = &tick_node1; + var b = &tick_node2; + var c = &tick_node3; +} + +var shared_test_data = [1]i32{0} ** 10; +var shared_test_index: usize = 0; + +async fn lockRunner(lock: *Lock) void { + suspend; // resumed by onNextTick + + var i: usize = 0; + while (i < 10) : (i += 1) { + const handle = await (async lock.acquire() catch @panic("out of memory")); + defer handle.release(); + + shared_test_index = 0; + while (shared_test_index < shared_test_data.len) : (shared_test_index += 1) { + shared_test_data[shared_test_index] = shared_test_data[shared_test_index] + 1; + } + } +} diff --git a/std/heap.zig b/std/heap.zig index 2e02733da1..bcace34afe 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -38,7 +38,7 @@ fn cFree(self: *Allocator, old_mem: []u8) void { } /// This allocator makes a syscall directly for every allocation and free. -/// TODO make this thread-safe. The windows implementation will need some atomics. +/// Thread-safe and lock-free. pub const DirectAllocator = struct { allocator: Allocator, heap_handle: ?HeapHandle, @@ -74,34 +74,34 @@ pub const DirectAllocator = struct { const alloc_size = if (alignment <= os.page_size) n else n + alignment; const addr = p.mmap(null, alloc_size, p.PROT_READ | p.PROT_WRITE, p.MAP_PRIVATE | p.MAP_ANONYMOUS, -1, 0); if (addr == p.MAP_FAILED) return error.OutOfMemory; - if (alloc_size == n) return @intToPtr([*]u8, addr)[0..n]; - var aligned_addr = addr & ~usize(alignment - 1); - aligned_addr += alignment; + const aligned_addr = (addr & ~usize(alignment - 1)) + alignment; - //We can unmap the unused portions of our mmap, but we must only - // pass munmap bytes that exist outside our allocated pages or it - // will happily eat us too + // We can unmap the unused portions of our mmap, but we must only + // pass munmap bytes that exist outside our allocated pages or it + // will happily eat us too. - //Since alignment > page_size, we are by definition on a page boundry + // Since alignment > page_size, we are by definition on a page boundary. const unused_start = addr; const unused_len = aligned_addr - 1 - unused_start; - var err = p.munmap(unused_start, unused_len); - debug.assert(p.getErrno(err) == 0); + const err = p.munmap(unused_start, unused_len); + assert(p.getErrno(err) == 0); - //It is impossible that there is an unoccupied page at the top of our - // mmap. + // It is impossible that there is an unoccupied page at the top of our + // mmap. return @intToPtr([*]u8, aligned_addr)[0..n]; }, Os.windows => { const amt = n + alignment + @sizeOf(usize); - const heap_handle = self.heap_handle orelse blk: { + const optional_heap_handle = @atomicLoad(?HeapHandle, ?self.heap_handle, builtin.AtomicOrder.SeqCst); + const heap_handle = optional_heap_handle orelse blk: { const hh = os.windows.HeapCreate(os.windows.HEAP_NO_SERIALIZE, amt, 0) orelse return error.OutOfMemory; - self.heap_handle = hh; - break :blk hh; + const other_hh = @cmpxchgStrong(?HeapHandle, &self.heap_handle, null, hh, builtin.AtomicOrder.SeqCst, builtin.AtomicOrder.SeqCst) orelse break :blk hh; + _ = os.windows.HeapDestroy(hh); + break :blk other_hh; }; const ptr = os.windows.HeapAlloc(heap_handle, 0, amt) orelse return error.OutOfMemory; const root_addr = @ptrToInt(ptr); diff --git a/std/mem.zig b/std/mem.zig index b52d3e9f68..555e1e249d 100644 --- a/std/mem.zig +++ b/std/mem.zig @@ -6,7 +6,7 @@ const builtin = @import("builtin"); const mem = this; pub const Allocator = struct { - const Error = error{OutOfMemory}; + pub const Error = error{OutOfMemory}; /// Allocate byte_count bytes and return them in a slice, with the /// slice's pointer aligned at least to alignment bytes. diff --git a/std/os/index.zig b/std/os/index.zig index 52b36c351c..74a1b64f6e 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -2309,6 +2309,30 @@ pub fn linuxEpollWait(epfd: i32, events: []linux.epoll_event, timeout: i32) usiz } } +pub const LinuxEventFdError = error{ + InvalidFlagValue, + SystemResources, + ProcessFdQuotaExceeded, + SystemFdQuotaExceeded, + + Unexpected, +}; + +pub fn linuxEventFd(initval: u32, flags: u32) LinuxEventFdError!i32 { + const rc = posix.eventfd(initval, flags); + const err = posix.getErrno(rc); + switch (err) { + 0 => return @intCast(i32, rc), + else => return unexpectedErrorPosix(err), + + posix.EINVAL => return LinuxEventFdError.InvalidFlagValue, + posix.EMFILE => return LinuxEventFdError.ProcessFdQuotaExceeded, + posix.ENFILE => return LinuxEventFdError.SystemFdQuotaExceeded, + posix.ENODEV => return LinuxEventFdError.SystemResources, + posix.ENOMEM => return LinuxEventFdError.SystemResources, + } +} + pub const PosixGetSockNameError = error{ /// Insufficient resources were available in the system to perform the operation. SystemResources, @@ -2605,10 +2629,17 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread const MainFuncs = struct { extern fn linuxThreadMain(ctx_addr: usize) u8 { - if (@sizeOf(Context) == 0) { - return startFn({}); - } else { - return startFn(@intToPtr(*const Context, ctx_addr).*); + const arg = if (@sizeOf(Context) == 0) {} else @intToPtr(*const Context, ctx_addr).*; + + switch (@typeId(@typeOf(startFn).ReturnType)) { + builtin.TypeId.Int => { + return startFn(arg); + }, + builtin.TypeId.Void => { + startFn(arg); + return 0; + }, + else => @compileError("expected return type of startFn to be 'u8', 'noreturn', 'void', or '!void'"), } } extern fn posixThreadMain(ctx: ?*c_void) ?*c_void { diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 65aa659c82..1c15be4887 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -523,6 +523,10 @@ pub const CLONE_NEWPID = 0x20000000; pub const CLONE_NEWNET = 0x40000000; pub const CLONE_IO = 0x80000000; +pub const EFD_SEMAPHORE = 1; +pub const EFD_CLOEXEC = O_CLOEXEC; +pub const EFD_NONBLOCK = O_NONBLOCK; + pub const MS_RDONLY = 1; pub const MS_NOSUID = 2; pub const MS_NODEV = 4; @@ -1221,6 +1225,10 @@ pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout return syscall4(SYS_epoll_wait, @intCast(usize, epoll_fd), @ptrToInt(events), @intCast(usize, maxevents), @intCast(usize, timeout)); } +pub fn eventfd(count: u32, flags: u32) usize { + return syscall2(SYS_eventfd2, count, flags); +} + pub fn timerfd_create(clockid: i32, flags: u32) usize { return syscall2(SYS_timerfd_create, @intCast(usize, clockid), @intCast(usize, flags)); } -- cgit v1.2.3 From c15a6fa9d0e11398f65e8ecc1903e07f4c57add6 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 7 Jul 2018 01:23:18 -0400 Subject: add std.os.cpuCount and have std.event.Loop use it for thread pool size --- std/event.zig | 4 +-- std/heap.zig | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ std/os/index.zig | 39 +++++++++++++++++++++++++++++ std/os/linux/index.zig | 4 +++ std/os/test.zig | 5 ++++ 5 files changed, 117 insertions(+), 2 deletions(-) (limited to 'std/os/linux') diff --git a/std/event.zig b/std/event.zig index 5fd87b8fdd..f0c45f61bc 100644 --- a/std/event.zig +++ b/std/event.zig @@ -150,8 +150,8 @@ pub const Loop = struct { /// TODO copy elision / named return values so that the threads referencing *Loop /// have the correct pointer value. fn initMultiThreaded(self: *Loop, allocator: *mem.Allocator) !void { - // TODO check the actual cpu core count - return self.initInternal(allocator, 4); + const core_count = try std.os.cpuCount(allocator); + return self.initInternal(allocator, core_count); } /// Thread count is the total thread count. The thread pool size will be diff --git a/std/heap.zig b/std/heap.zig index bcace34afe..6d3fd05cdb 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -361,6 +361,73 @@ pub const ThreadSafeFixedBufferAllocator = struct { fn free(allocator: *Allocator, bytes: []u8) void {} }; +pub fn stackFallback(comptime size: usize, fallback_allocator: *Allocator) StackFallbackAllocator(size) { + return StackFallbackAllocator(size){ + .buffer = undefined, + .fallback_allocator = fallback_allocator, + .fixed_buffer_allocator = undefined, + .allocator = Allocator{ + .allocFn = StackFallbackAllocator(size).alloc, + .reallocFn = StackFallbackAllocator(size).realloc, + .freeFn = StackFallbackAllocator(size).free, + }, + }; +} + +pub fn StackFallbackAllocator(comptime size: usize) type { + return struct { + const Self = this; + + buffer: [size]u8, + allocator: Allocator, + fallback_allocator: *Allocator, + fixed_buffer_allocator: FixedBufferAllocator, + + pub fn get(self: *Self) *Allocator { + self.fixed_buffer_allocator = FixedBufferAllocator.init(self.buffer[0..]); + return &self.allocator; + } + + fn alloc(allocator: *Allocator, n: usize, alignment: u29) ![]u8 { + const self = @fieldParentPtr(Self, "allocator", allocator); + return FixedBufferAllocator.alloc(&self.fixed_buffer_allocator.allocator, n, alignment) catch + self.fallback_allocator.allocFn(self.fallback_allocator, n, alignment); + } + + fn realloc(allocator: *Allocator, old_mem: []u8, new_size: usize, alignment: u29) ![]u8 { + const self = @fieldParentPtr(Self, "allocator", allocator); + const in_buffer = @ptrToInt(old_mem.ptr) >= @ptrToInt(&self.buffer) and + @ptrToInt(old_mem.ptr) < @ptrToInt(&self.buffer) + self.buffer.len; + if (in_buffer) { + return FixedBufferAllocator.realloc( + &self.fixed_buffer_allocator.allocator, + old_mem, + new_size, + alignment, + ) catch { + const result = try self.fallback_allocator.allocFn( + self.fallback_allocator, + new_size, + alignment, + ); + mem.copy(u8, result, old_mem); + return result; + }; + } + return self.fallback_allocator.reallocFn(self.fallback_allocator, old_mem, new_size, alignment); + } + + fn free(allocator: *Allocator, bytes: []u8) void { + const self = @fieldParentPtr(Self, "allocator", allocator); + const in_buffer = @ptrToInt(bytes.ptr) >= @ptrToInt(&self.buffer) and + @ptrToInt(bytes.ptr) < @ptrToInt(&self.buffer) + self.buffer.len; + if (!in_buffer) { + return self.fallback_allocator.freeFn(self.fallback_allocator, bytes); + } + } + }; +} + test "c_allocator" { if (builtin.link_libc) { var slice = c_allocator.alloc(u8, 50) catch return; diff --git a/std/os/index.zig b/std/os/index.zig index 74a1b64f6e..c36aae91da 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -2748,3 +2748,42 @@ pub fn posixFStat(fd: i32) !posix.Stat { return stat; } + +pub const CpuCountError = error{ + OutOfMemory, + PermissionDenied, + Unexpected, +}; + +pub fn cpuCount(fallback_allocator: *mem.Allocator) CpuCountError!usize { + const usize_count = 16; + const allocator = std.heap.stackFallback(usize_count * @sizeOf(usize), fallback_allocator).get(); + + var set = try allocator.alloc(usize, usize_count); + defer allocator.free(set); + + while (true) { + const rc = posix.sched_getaffinity(0, set); + const err = posix.getErrno(rc); + switch (err) { + 0 => { + if (rc < set.len * @sizeOf(usize)) { + const result = set[0 .. rc / @sizeOf(usize)]; + var sum: usize = 0; + for (result) |x| { + sum += @popCount(x); + } + return sum; + } else { + set = try allocator.realloc(usize, set, set.len * 2); + continue; + } + }, + posix.EFAULT => unreachable, + posix.EINVAL => unreachable, + posix.EPERM => return CpuCountError.PermissionDenied, + posix.ESRCH => unreachable, + else => return os.unexpectedErrorPosix(err), + } + } +} diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 1c15be4887..69bc30bad0 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -1197,6 +1197,10 @@ pub fn fremovexattr(fd: usize, name: [*]const u8) usize { return syscall2(SYS_fremovexattr, fd, @ptrToInt(name)); } +pub fn sched_getaffinity(pid: i32, set: []usize) usize { + return syscall3(SYS_sched_getaffinity, @bitCast(usize, isize(pid)), set.len * @sizeOf(usize), @ptrToInt(set.ptr)); +} + pub const epoll_data = packed union { ptr: usize, fd: i32, diff --git a/std/os/test.zig b/std/os/test.zig index 5a977a569a..52e6ffdc1c 100644 --- a/std/os/test.zig +++ b/std/os/test.zig @@ -58,3 +58,8 @@ fn start2(ctx: *i32) u8 { _ = @atomicRmw(i32, ctx, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); return 0; } + +test "cpu count" { + const cpu_count = try std.os.cpuCount(a); + assert(cpu_count >= 1); +} -- cgit v1.2.3 From dcaaa241dfb7ce77b7070df8d6a939a9f0749e2c Mon Sep 17 00:00:00 2001 From: "Matthew D. Steele" Date: Fri, 3 Aug 2018 11:45:23 -0400 Subject: Fix a type error in std.os.linux.getpid() (#1326) syscall0() returns usize, but we were trying to @bitCast to i32. --- std/os/linux/index.zig | 2 +- std/os/linux/test.zig | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) (limited to 'std/os/linux') diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 69bc30bad0..15607ea6c0 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -944,7 +944,7 @@ pub fn setgroups(size: usize, list: *const u32) usize { } pub fn getpid() i32 { - return @bitCast(i32, u32(syscall0(SYS_getpid))); + return @bitCast(i32, @truncate(u32, syscall0(SYS_getpid))); } pub fn sigprocmask(flags: u32, noalias set: *const sigset_t, noalias oldset: ?*sigset_t) usize { diff --git a/std/os/linux/test.zig b/std/os/linux/test.zig index e7dae3a584..4de26012c7 100644 --- a/std/os/linux/test.zig +++ b/std/os/linux/test.zig @@ -3,6 +3,10 @@ const builtin = @import("builtin"); const linux = std.os.linux; const assert = std.debug.assert; +test "getpid" { + assert(linux.getpid() != 0); +} + test "timer" { const epoll_fd = linux.epoll_create(); var err = linux.getErrno(epoll_fd); -- cgit v1.2.3