auto type erasure for protocols & struct literal init bloc

This commit is contained in:
agra
2026-02-25 12:25:06 +02:00
parent bfc784734c
commit 4abc7abb54
5 changed files with 196 additions and 1 deletions

View File

@@ -277,6 +277,17 @@ SumBox :: struct ($T: Type/Summable) {
}
// ============================================================
// Init block test struct
Builder :: struct {
total: s32;
count: s32;
add :: (self: *Builder, val: s32) {
self.total += val;
self.count += 1;
}
}
main :: () {
// ========================================================
@@ -2848,5 +2859,100 @@ END;
print("P3.3: {}\n", result);
}
// --- Auto type erasure (AE) ---
print("=== Auto Type Erasure ===\n");
// AE1: function argument — concrete passed where protocol expected (no xx)
{
use_counter :: (c: Counter) -> s32 { 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) -> s32 { 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) -> s32 { 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);
}
// --- Init Blocks (IB) ---
print("=== Init Blocks ===\n");
// IB1: basic init block with struct methods
{
b := Builder.{ total = 0, count = 0 } {
self.add(10);
self.add(20);
self.add(30);
};
print("IB1: {} {}\n", b.total, b.count);
}
// IB2: nested init blocks (self shadows correctly)
{
b1 := Builder.{ total = 0, count = 0 } {
self.add(100);
b2 := Builder.{ total = 0, count = 0 } {
self.add(42);
};
self.add(b2.total);
};
print("IB2: {} {}\n", b1.total, b1.count);
}
// IB3: empty init block
{
b := Builder.{ total = 5, count = 1 } {};
print("IB3: {} {}\n", b.total, b.count);
}
// IB4: conditional inside init block
{
add_extra := true;
b := Builder.{ total = 0, count = 0 } {
self.add(10);
if add_extra {
self.add(90);
}
};
print("IB4: {}\n", b.total);
}
// IB5: init block + auto type erasure combined
{
use_counter :: (c: Counter) -> s32 { c.inc(); c.inc(); c.get(); }
result := use_counter(SimpleCounter.{ val = 0 } {
self.val = 50;
});
print("IB5: {}\n", result);
}
print("=== DONE ===\n");
}

View File

@@ -306,6 +306,7 @@ pub const StructLiteral = struct {
struct_name: ?[]const u8, // null for anonymous `.{ ... }`
type_expr: ?*Node = null, // for GenericType(args).{ ... }
field_inits: []const StructFieldInit,
init_block: ?*Node = null, // optional `{ stmts }` block after struct literal
};
pub const Lambda = struct {

View File

@@ -5933,6 +5933,22 @@ pub const CodeGen = struct {
}
}
// Init block: T.{ ... } { self.method(); }
if (sl.init_block) |ib| {
if (ib.data == .block) {
try self.pushScope();
const self_ty = Type{ .pointer_type = .{ .pointee_name = sname } };
// self is a *T — store the struct alloca address into a ptr-sized alloca
const self_alloca = self.buildEntryBlockAlloca(self.ptrType(), "self");
_ = c.LLVMBuildStore(self.builder, alloca, self_alloca);
try self.registerVariable("self", self_alloca, self_ty);
for (ib.data.block.stmts) |stmt| {
_ = try self.genStmt(stmt);
}
try self.popScope();
}
}
return alloca;
}
@@ -6213,6 +6229,29 @@ pub const CodeGen = struct {
}
}
// Struct literal targeting protocol type: auto type erasure
if (node.data == .struct_literal and target_ty.isStruct()) {
if (self.protocol_decls.get(target_ty.struct_type)) |pd| {
const sl = node.data.struct_literal;
const concrete_name = sl.struct_name orelse if (sl.type_expr) |te| blk: {
const ty = self.resolveType(te);
if (ty.isStruct()) break :blk ty.struct_type;
break :blk null;
} else null;
if (concrete_name) |cn| {
const key = try std.fmt.allocPrint(self.allocator, "{s}\x00{s}", .{ pd.name, cn });
if (self.impl_blocks.contains(key)) {
const alloca = try self.genStructLiteral(sl, cn);
const sname = self.resolveAlias(cn);
if (self.lookupStructInfo(sname)) |si| {
const loaded = c.LLVMBuildLoad2(self.builder, si.llvm_type.?, alloca, "auto_erase_load");
return self.buildProtocolValue(loaded, Type{ .struct_type = cn }, pd) catch return loaded;
}
}
}
}
}
// Struct literal targeting struct type: pass struct name context
if (node.data == .struct_literal and target_ty.isStruct()) {
const alloca = try self.genStructLiteral(node.data.struct_literal, target_ty.struct_type);
@@ -6369,6 +6408,26 @@ pub const CodeGen = struct {
}
}
// Auto type erasure: concrete type → protocol (implicit xx)
if (target_ty.isStruct()) {
if (self.protocol_decls.get(target_ty.struct_type)) |pd| {
const concrete_name = if (src_ty.isStruct())
src_ty.struct_type
else if (src_ty.isPointer())
src_ty.pointer_type.pointee_name
else if (src_ty.isManyPointer())
src_ty.many_pointer_type.element_name
else
null;
if (concrete_name) |cn| {
const key = try std.fmt.allocPrint(self.allocator, "{s}\x00{s}", .{ pd.name, cn });
if (self.impl_blocks.contains(key)) {
return self.buildProtocolValue(val, src_ty, pd) catch return val;
}
}
}
}
// Scalar to vector broadcast
if (target_ty.isVector() and !src_ty.isVector()) {
const elem_ty = target_ty.vectorElementType() orelse return self.emitError("cannot determine vector element type");

View File

@@ -1034,10 +1034,17 @@ pub const Parser = struct {
}
try self.expect(.r_brace);
// Optional init block: T.{ fields } { stmts }
const init_block: ?*Node = if (self.current.tag == .l_brace)
try self.parseBlock()
else
null;
return try self.createNode(start_pos, .{ .struct_literal = .{
.struct_name = struct_name,
.type_expr = type_expr,
.field_inits = try field_inits.toOwnedSlice(self.allocator),
.init_block = init_block,
} });
}
@@ -2017,7 +2024,17 @@ pub const Parser = struct {
self.advance(); // skip 'push'
const context_expr = try self.parseExpr();
const body = try self.parseBlock();
// push Context.{ ... } { body } — if parseExpr consumed the push body
// as a struct init block, steal it back as the push body.
// (if/while don't have this issue — they require bool/optional conditions)
const body = if (context_expr.data == .struct_literal and
context_expr.data.struct_literal.init_block != null)
body_blk: {
const ib = context_expr.data.struct_literal.init_block.?;
context_expr.data.struct_literal.init_block = null;
break :body_blk ib;
} else try self.parseBlock();
return try self.createNode(start, .{ .push_stmt = .{
.context_expr = context_expr,

View File

@@ -563,4 +563,16 @@ P7.2: 10 300
P2.6: 5 10
P2.7: 15
P3.3: 102
=== Auto Type Erasure ===
AE1: 12
AE2: 8
AE3: 102
AE4: 51
AE5: 15
=== Init Blocks ===
IB1: 60 3
IB2: 142 2
IB3: 5 1
IB4: 100
IB5: 52
=== DONE ===