Files
sx/examples/0416-protocols-auto-type-erasure.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

93 lines
2.2 KiB
Plaintext

#import "modules/std.sx";
#import "modules/math";
#import "modules/build.sx";
#import "modules/std/test.sx";
pkg :: #import "tests/fixtures/testpkg";
Point :: struct { x, y: i32; }
add :: (a: i32, b: i32) -> i32 { a + b }
Counter :: protocol {
inc :: ();
get :: () -> i32;
}
Summable :: protocol {
sum :: () -> i32;
}
SimpleCounter :: struct { val: i32; }
impl Counter for SimpleCounter {
inc :: (self: *SimpleCounter) { self.val += 1; }
get :: (self: *SimpleCounter) -> i32 { self.val }
}
impl Summable for Point {
sum :: (self: *Point) -> i32 { self.x + self.y }
}
// Phase 2: #inline protocol for dynamic dispatch
// Phase 2: #inline protocol for dynamic dispatch
Adder :: protocol #inline {
add :: (n: i32);
value :: () -> i32;
}
Accumulator :: struct {
total: i32;
}
impl Adder for Accumulator {
add :: (self: *Accumulator, n: i32) { self.total += n; }
value :: (self: *Accumulator) -> i32 { self.total }
}
main :: () {
// --- Auto type erasure (AE) ---
print("=== Auto Type Erasure ===\n");
// AE1: function argument — concrete passed where protocol expected (no xx)
{
use_counter :: (c: Counter) -> i32 { c.inc(); c.inc(); c.get() }
sc := SimpleCounter.{ val = 10 };
result := use_counter(sc);
print("AE1: {}\n", result);
}
// AE2: variable assignment — concrete to protocol variable (no xx)
{
acc := Accumulator.{ total = 0 };
a: Adder = acc;
a.add(5);
a.add(3);
print("AE2: {}\n", a.value());
}
// AE3: struct literal passed directly (no xx)
{
use_counter :: (c: Counter) -> i32 { c.inc(); c.inc(); c.get() }
result := use_counter(SimpleCounter.{ val = 100 });
print("AE3: {}\n", result);
}
// AE4: explicit xx still works (not broken)
{
use_counter :: (c: Counter) -> i32 { c.inc(); c.get() }
result := use_counter(xx SimpleCounter.{ val = 50 });
print("AE4: {}\n", result);
}
// AE5: pointer auto-erasure — *ConcreteType to protocol
{
use_adder :: (a: Adder) { a.add(10); }
acc := Accumulator.{ total = 5 };
p := @acc;
use_adder(p);
print("AE5: {}\n", acc.total);
}
}