Files
sx/examples/0905-optionals-unwrap-field-chain.sx
agra 6f2a1dc3dc fix(types): type force-unwrap so opt!.field chains resolve [0101]
ExprTyper.inferType had no `.force_unwrap` arm, so `mk()!` typed as
`.unresolved`. The bind-first form (`v := mk()!; v.field`) worked because
lowerForceUnwrap produces a correctly typed value stored in a slot, but the
chained `mk()!.field` re-derives the receiver type via inferExprType and got
`.unresolved` — the struct-field lookup failed, the field read emitted as
`undef` (garbage), and `mk()!.method()` failed to resolve the method.

Add a `.force_unwrap` arm resolving the operand's optional child type. One
arm fixes every chained form — field, nested `opt!.a.b`, `opt!.method()`
(pointer + value receiver), and `opt![i]` all route receiver typing through
inferExprType.

Regression: examples/0905-optionals-unwrap-field-chain.sx — garbage / compile
error pre-fix, all correct after.
2026-06-06 07:42:17 +03:00

52 lines
1.6 KiB
Plaintext

// Postfix `!` (optional force-unwrap) chained directly with a member access.
// `opt!.field`, `opt!.method()`, `opt!.a.b`, and `opt![i]` must read the same
// value the bind-first form (`v := opt!; v.field`) produces — the unwrapped
// value's type has to flow into the chained access.
//
// Regression (issue 0101): chained `opt!.field` typed its receiver as
// `.unresolved` (inferExprType had no force_unwrap arm), so a string field read
// as garbage and `opt!.method()` failed to resolve at all.
#import "modules/std.sx";
Inner :: struct { tag: string; k: s64; }
S :: struct {
id: string;
n: s64;
inner: Inner;
greet :: (self: *S) -> string { return self.id; } // pointer receiver
bump :: (self: S, extra: s64) -> s64 { return self.n + extra; } // value receiver
}
mk :: () -> ?S {
return S.{ id = "hello", n = 42, inner = Inner.{ tag = "deep", k = 7 } };
}
arr :: () -> ?[3]s64 {
v : [3]s64 = .[10, 20, 30];
return v;
}
main :: () -> void {
// opt!.field — string and int field, chained vs bind-first.
print("chain id: {}\n", mk()!.id); // hello
print("chain n: {}\n", mk()!.n); // 42
v := mk()!;
print("bind id: {}\n", v.id); // hello
print("bind n: {}\n", v.n); // 42
// opt!.method()
print("meth ptr: {}\n", mk()!.greet()); // hello
print("meth val: {}\n", mk()!.bump(8)); // 50
// nested opt!.a.b
print("nest tag: {}\n", mk()!.inner.tag); // deep
print("nest k: {}\n", mk()!.inner.k); // 7
// opt![i]
print("index 0: {}\n", arr()![0]); // 10
print("index 2: {}\n", arr()![2]); // 30
}