Skip to content

Conversation

@nilslice
Copy link
Owner

@nilslice nilslice commented Oct 19, 2025

Add VTable generation for runtime polymorphism

This PR adds automatic VTable generation to the Interface library, enabling runtime polymorphism through type erasure. Interfaces can now generate VTable-based wrappers that allow heterogeneous collections of implementations.

Example

// Define an interface
const AIProvider = Interface(.{
    .generate = fn ([]const u8) anyerror![]const u8,
    .embed = fn ([]const u8) anyerror![]f16,
    .query = fn ([]const u8) anyerror![][]const u8,
}, null);

// Create implementations (structs w/ interface methods defined above)
var openai = OpenAIMock.init(allocator);
var anthropic = AnthropicMock.init(allocator);

// Convert to VTable-based interface types
var providers = [_]AIProvider{
    AIProvider.from(&openai),      // Auto-generates VTable wrappers
    AIProvider.from(&anthropic),   // Different concrete type, same interface type
};

// NOTE: `.from()` is generated from `Interface({...})`, and provides the `.ptr` field on the output struct.

// demo generic function taking interface type arg
fn generate(provider: AIProvider, prompt: []const u8) ![]const u8 {
    return provider.vtable.generate(provider.ptr, prompt);
}

// Runtime polymorphism - call the implementation through the vtable
const response = try generate(providers[0].ptr, "prompt");

@nilslice nilslice merged commit 19f2c93 into main Oct 28, 2025
3 checks passed
@nilslice nilslice deleted the updated-interface branch October 28, 2025 19:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants