Files
sx/examples/0900-optionals-optionals.sx
agra d8076b9333 lang: rename signed integer types sN -> iN
Surface rename of the signed integer family: s1..s64 become i1..i64
(u1..u64, usize, isize unchanged). 'string' keeps the s-prefix arm in
name classification; width parsing moves to the i-prefix arm next to
isize.

Internal TypeId tags follow the surface (.s8/.s16/.s32/.s64 ->
.i8/.i16/.i32/.i64), as do mono-key mangle fragments (ptr_i64,
tu_i64_bool) and all display/diagnostic formatting (i{d}).

Migrated in the same sweep: stdlib + examples + issue repros + FFI C
companions (shared symbol names like ffi_id_i64), expected
stdout/stderr/ir snapshots, specs.md, readme.md, CLAUDE.md/AGENTS.md,
implementation_plan.md, docs/, issue writeups. Vendored stb_image and
historical flow state left untouched.

zig build test: 426/426; examples suite: 595/595.
2026-06-12 09:31:53 +03:00

98 lines
2.2 KiB
Plaintext

#import "modules/std.sx";
// --- Type declarations ---
OptNode :: struct { value: i32; next: ?i32; }
OptInner :: struct { val: i32; }
OptOuter :: struct { inner: ?OptInner; }
// --- Comptime optionals ---
ct_sum :: () -> i32 {
x: ?i32 = 42;
y: ?i32 = null;
return (x ?? 0) + (y ?? 99);
}
CT_RESULT :: #run ct_sum();
main :: () -> i32 {
// Basic optional creation
x: ?i32 = 42;
y: ?i32 = null;
print("x = {}\n", x);
print("y = {}\n", y);
// Force unwrap
print("x! = {}\n", x!);
// Null coalescing
print("x ?? 0 = {}\n", x ?? 0);
print("y ?? 99 = {}\n", y ?? 99);
// If-binding (safe unwrap)
if val := x {
print("if-bind x: {}\n", val);
}
if val := y {
print("should not print\n");
} else {
print("if-bind y: none\n");
}
// Pattern matching
check :: (v: ?i32) -> i32 {
return if v == {
case .some: (val) { val }
case .none: { 0 }
};
}
print("match some: {}\n", check(42));
print("match none: {}\n", check(null));
// Optional chaining
p: ?OptNode = OptNode.{ value = 10, next = 20 };
q: ?OptNode = null;
print("p?.value = {}\n", p?.value ?? 0);
print("q?.value = {}\n", q?.value ?? 0);
// Deep chaining
o1 := OptOuter.{ inner = OptInner.{ val = 99 } };
o2 := OptOuter.{ inner = null };
print("o1.inner?.val = {}\n", o1.inner?.val ?? 0);
print("o2.inner?.val = {}\n", o2.inner?.val ?? 0);
// Flow-sensitive narrowing
a: ?i32 = 10;
b: ?i32 = 20;
if a != null {
print("narrowed a: {}\n", a);
}
// Guard narrowing
guard :: (v: ?i32) -> i32 {
if v == null { return 0; }
return v;
}
print("guard 42: {}\n", guard(42));
print("guard null: {}\n", guard(null));
// Compound narrowing
if a != null and b != null {
print("both: {} {}\n", a, b);
}
// Compound guard
guard2 :: (a: ?i32, b: ?i32) -> i32 {
if a == null or b == null { return 0; }
return a + b;
}
print("guard2: {}\n", guard2(3, 4));
// Struct field defaults
n := OptNode.{ value = 10 };
print("default next: {}\n", n.next);
// Comptime result
print("comptime: {}\n", CT_RESULT);
return 0;
}