From fb474251855f1ac34879d1b989a681ad71574998 Mon Sep 17 00:00:00 2001 From: Mateusz Poliwczak Date: Tue, 18 Nov 2025 16:06:49 +0100 Subject: [PATCH] Add unwrapped optional assignment tests Zig supports: foo.? = val assignment, currently there are no much tests for them, so lets add few. --- test/behavior/optional.zig | 14 ++++++++++++++ .../optional unwrap assign comptime.zig | 9 +++++++++ test/cases/safety/optional unwrap assign.zig | 16 ++++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 test/cases/compile_errors/optional unwrap assign comptime.zig create mode 100644 test/cases/safety/optional unwrap assign.zig diff --git a/test/behavior/optional.zig b/test/behavior/optional.zig index 7c70101c57..11bebf018f 100644 --- a/test/behavior/optional.zig +++ b/test/behavior/optional.zig @@ -304,6 +304,20 @@ test "self-referential struct through a slice of optional" { try expect(n.data == null); } +test "assigning to an unwrapped optional" { + var foo: ?u8 = 10; + foo.? = 12; + try expect(foo.? == 12); +} + +test "assigning to an unwrapped optional in comptime context" { + comptime { + var foo: ?u8 = 10; + foo.? = 12; + try expect(foo.? == 12); + } +} + test "assigning to an unwrapped optional field in an inline loop" { comptime var maybe_pos_arg: ?comptime_int = null; inline for ("ab") |x| { diff --git a/test/cases/compile_errors/optional unwrap assign comptime.zig b/test/cases/compile_errors/optional unwrap assign comptime.zig new file mode 100644 index 0000000000..bc5e0be12b --- /dev/null +++ b/test/cases/compile_errors/optional unwrap assign comptime.zig @@ -0,0 +1,9 @@ +pub fn main() !void { + comptime { + var foo: ?u8 = null; + foo.? = 10; + } +} +// error +// +// 4:12: error: unable to unwrap null diff --git a/test/cases/safety/optional unwrap assign.zig b/test/cases/safety/optional unwrap assign.zig new file mode 100644 index 0000000000..ba1d9b80c0 --- /dev/null +++ b/test/cases/safety/optional unwrap assign.zig @@ -0,0 +1,16 @@ +const std = @import("std"); + +pub fn panic(message: []const u8, _: ?*std.builtin.StackTrace, _: ?usize) noreturn { + if (std.mem.eql(u8, message, "attempt to use null value")) { + std.process.exit(0); + } + std.process.exit(1); +} +pub fn main() !void { + var foo: ?u8 = null; + foo.? = 10; // should fail, since foo is null. + return error.TestFailed; +} +// run +// backend=selfhosted,llvm +// target=x86_64-linux