RFC-011a: Interface Implementation and Dynamic Dispatch
Parent RFC: RFC-011: Generic Type System Design
This RFC supplements and supersedes the interface-constraint portion of RFC-011 §2.1-2.4.
Abstract
RFC-011 defined the generic type system but did not specify the interface implementation mechanism in detail. This document supplements it with:
- Interface declaration: An interface is a parameterized type—
(Self: Type) -> Type; a concrete type is passed in during implementation - Method implementation: Both internal and external declarations are supported
- Overloading rules: Different signatures may be overloaded; identical signatures produce an error (overriding is prohibited)
- Default values: Write
= valuedirectly after a field - Dynamic dispatch: Compile-time type collection + interface matching, with no vtable
Core design:
# Interface definition (parameterized type; Self is an explicit type parameter)
Animal: (Self: Type) -> Type = {
speak: (self: &Self) -> String,
}
# Type definition (internal declaration)
Dog: Type = {
x: Int = 10,
Animal(Dog), # Interface instantiation, Self ↦ Dog
speak: (self: &Dog) -> String = "Woof",
}
# External declaration (overload)
Dog.speak: (self: &Dog, volume: Int) -> String = "WOOF"
# Heterogeneous container (dynamic dispatch)
animals: List(Animal) = [Dog.new(), Cat.new()]
animals[0].speak() # "Woof"Receiver spelling conventions (aligned with RFC-009 ownership semantics):
- A method receiver follows the semantics of its signature:
&Self= borrow (the interface's default convention—method calls do not consume the receiver),&mut Self= mutable borrow, and by-valueSelf= consume the receiver (Move, RFC-009). Selfin an impl-side signature is an alias for the impl type: interfacespeak: (self: &Self)and impl(self: &Dog)/(self: &Self)both match (they are identical after replacing Self with the impl type, §3).- By-value receiver spellings in historical examples (
(self: Self)) meant borrowing; this document has uniformly migrated them to explicit&Self. From now on, by-value spelling consistently retains the "consume" semantics and is no longer mixed with borrowing.
Complexities eliminated:
- ❌ No
implkeyword - ❌ No
Selfmagic keyword (Selfis an explicit type parameter, no different fromT) - ❌ No
dyn Trait + 'aannotation - ❌ No vtable (compile-time type collection + enum wrapping)
- ❌ No overriding (unified overload rules)
Motivation
Limitations of RFC-011
RFC-011 defined the generic type system but did not specify the following in detail:
| Issue | Explanation |
|---|---|
| Interface declaration syntax | How to declare that a type implements an interface? |
| Method implementation location | Internal declaration or external declaration? |
| Overloading rules | How are methods with the same name handled? |
| Default value syntax | How are default values assigned to fields? |
| Dynamic dispatch | How is a heterogeneous container implemented? |
Design goals
- Simplicity: No
implkeyword is required - Flexibility: Method implementations may be internal or external
- Consistency: Uniform overloading rules
- Convenience: Simple default-value syntax
- Zero overhead: No vtable; compile-time type collection
Comparison with Rust
| Feature | Rust | YaoXiang |
|---|---|---|
| Interface declaration | impl Animal for Dog { ... } | Dog: Type = { Animal(Dog), ... } |
| Method implementation | In an impl block | Internal or external |
| Overloading | Not supported | Supported (different signatures) |
| Default values | Requires #[default] | Write = value directly |
| Heterogeneous container | Vec<Box<dyn Animal + 'a>> | List(Animal) |
| Dynamic dispatch | Vtable lookup | Compile-time type collection |
| Self keyword | Magic keyword, implicitly quantified | Explicit type parameter, on equal footing with T |
Proposal
1. Interface declaration
Core rule: An interface is a parameterized type (Self: Type) -> Type; Self is an explicit type parameter, not a magic keyword. During implementation, the interface is called with a concrete type.
# Interface definition (fully consistent with RFC-011 generics)
Animal: (Self: Type) -> Type = {
speak: (self: &Self) -> String,
}
# Type declaration implements the interface
Dog: Type = {
x: Int,
Animal(Dog), # Interface instantiation, Self ↦ Dog
}Compiler processing:
- Recognize that
Animal(Dog)is an instantiation of(Self: Type) -> Type - Perform the
Self ↦ Dogsubstitution: expandAnimal(Dog)into{ speak: (self: &Dog) -> String } - Check whether
Dogprovides all required methods (signature matching) - If it passes → generate an implementation proof
- If it fails → compilation error
Equivalent expansion:
Dog: Type = {
x: Int,
Animal(Dog), # Expands to Animal's methods, preserving source markers
}
# Equivalent to (preserving source information)
Dog: Type = {
x: Int,
speak: (self: &Dog) -> String, # From Animal; Self has been replaced with Dog
}Why source markers are needed:
- Direct expansion loses source information
- Source markers are used to generate implementation proofs
- At runtime, the proof locates the correct method
1.1 Self type parameter and type-checking timing
Self is an explicit type parameter of the interface, not a magic keyword. Animal: (Self: Type) -> Type and List: (T: Type) -> Type are the same kind of thing—(Type) -> Type type constructors.
Type-checking timing:
- At interface definition:
Selfin{ speak: (self: &Self) -> String }is an abstract type parameter, and only a syntactic check is performed. - At the instantiation point: When
Animal(Dog)is evaluated,Self ↦ Dogis applied, followed by a full type check (signature matching and method existence).
This avoids the problem of Self acting as an implicit magic keyword in RFC-011—Self does not appear in type definitions; it appears only once in the interface parameter list and is exactly equal in status to T.
1.2 Namespace for field and method names
A type's field names and method names share the same namespace. After an interface is expanded, if an interface method name conflicts with a type field name, compilation fails:
Drawable: (Self: Type) -> Type = {
x: (self: &Self) -> Int, // Method named x
}
Point: Type = {
x: Int, // Field also named x
Drawable(Point), // ❌ Compilation error: Drawable requires method x, which conflicts with field x
}Field access point.x and method call point.x() cannot be distinguished syntactically. A unified namespace avoids ambiguity.
2. Method implementation
Core rule: Both internal and external method declarations are supported.
2.1 Internal declaration
Dog: Type = {
x: Int = 10,
Animal(Dog),
speak: (self: &Dog) -> String = "Woof", # Method implementation is internal
}2.2 External declaration
Dog: Type = {
x: Int,
Animal(Dog),
}
# Method implementation is external
Dog.speak: (self: &Dog) -> String = "Woof"2.3 Mixed declarations
Dog: Type = {
x: Int = 10,
Animal(Dog),
speak: (self: &Dog) -> String = "Woof", # Some methods are internal
}
# Some methods are external
Dog.play: (self: &Dog) -> Void = { ... }Compiler processing:
- Collect all definitions (internal and external)
- Group them by signature (overloading)
- Check for overrides (report an error)
- Check interface completeness
- Generate an implementation proof
3. Overloading and overriding
Core rule:
- Different signatures → overload → allowed
- Identical signatures → override → error
3.1 Overloading (allowed)
# Different parameter types; overloading is allowed
Dog.speak: (self: &Dog) -> String = "Woof"
Dog.speak: (self: &Dog, volume: Int) -> String = "WOOF"3.2 Overriding (prohibited)
# Identical signatures; overriding is prohibited
Dog.speak: (self: &Dog) -> String = "Woof"
Dog.speak: (self: &Dog) -> String = "Bark" # ❌ Error: overriding is not allowedError message:
错误:Dog.speak(self: &Dog) -> String 重复定义
--> 文件2:5:1
|
5 | Dog.speak: (self: &Dog) -> String = "Bark"
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 重复定义
|
--> 文件1:3:1
|
3 | Dog.speak: (self: &Dog) -> String = "Woof"
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 第一个定义3.3 Unified rules
Internal and external declarations follow the same overloading/overriding rules:
# Internal declaration
Dog: Type = {
x: Int,
Animal(Dog),
speak: (self: &Dog) -> String = "Woof",
}
# External declaration (overload, allowed)
Dog.speak: (self: &Dog, volume: Int) -> String = "WOOF"
# External declaration (override, prohibited)
Dog.speak: (self: &Dog) -> String = "Bark" # ❌ Error4. Default values
Core rule: Write = value directly after a field, eliminating the need to write constructors.
Dog: Type = {
x: Int = 10, # Default value
y: Int = 20, # Default value
Animal(Dog),
}Compiler-generated constructors:
# All fields have default values → generate a no-argument constructor
Dog.new: () -> Dog = { x: 10, y: 20 }
# Some fields have default values → generate a partially parameterized constructor
Dog.new: (x: Int) -> Dog = { x: x, y: 20 }
Dog.new: (y: Int) -> Dog = { x: 10, y: y }
# Fully parameterized constructor
Dog.new: (x: Int, y: Int) -> Dog = { x: x, y: y }Default values for external declarations:
Dog: Type = {
x: Int,
y: Int,
Animal(Dog),
}
# External declaration default values
Dog.x: Int = 10
Dog.y: Int = 20Equivalent to internal declarations.
5. Compiler implementation
5.1 Interface descriptor
// Compiler internals: interface descriptor
struct InterfaceDescriptor {
name: String,
self_param: TypeParam, // Self type parameter
methods: Vec<MethodSignature>,
}5.2 Type definition
// Compiler internals: type definition
struct TypeDefinition {
name: String,
fields: Vec<Field>,
interface_instantiations: Vec<InterfaceInstantiation>,
}
// Interface instantiation (Self ↦ ConcreteType)
struct InterfaceInstantiation {
interface: InterfaceId,
self_type: TypeId, // Concrete type substituted for Self
methods: HashMap<MethodId, FunctionBody>,
}5.3 Implementation proof
// Compiler internals: implementation proof
struct ImplementationProof {
type_id: TypeId,
interface_id: InterfaceId,
methods: Vec<MethodPointer>,
}5.4 Compilation pipeline
1. 解析类型定义,收集接口实例化声明(Animal(Dog))
2. 对每个接口实例化执行 Self ↦ ConcreteType 替换
3. 展开接口方法签名,检查签名匹配
4. 收集所有方法定义(内部和外部)
5. 按签名分组(重载)
6. 检查覆盖(报错)
7. 检查接口完整性
8. 生成实现证明6. Dynamic dispatch
Core design: Compile-time type collection + interface matching, with no vtable.
6.1 Heterogeneous containers
Animal is a (Self: Type) -> Type. List(Animal) uses an uninstantiated interface type constructor as an existential type: ∃S. Animal(S)—"there exists some type S such that S implements Animal(S)."
# Interface definition
Animal: (Self: Type) -> Type = {
speak: (self: &Self) -> String,
}
# Type definition
Dog: Type = {
x: Int,
Animal(Dog),
speak: (self: &Dog) -> String = "Woof",
}
Cat: Type = {
y: Int,
Animal(Cat),
speak: (self: &Cat) -> String = "Meow",
}
# Heterogeneous container — Animal is uninstantiated = existential type
animals: List(Animal) = [Dog.new(), Cat.new()]
animals[0].speak() # "Woof"
animals[1].speak() # "Meow"Ownership semantics: Inserting a value into a heterogeneous container uses Move semantics (RFC-009). Dog.new() is moved into the AnimalGroup::Dog enum variant, and the original variable is no longer usable.
dog = Dog.new()
animals: List(Animal) = [dog]
# dog.speak() ← ❌ Compilation error: dog has been moved6.2 Compile-time type collection
Core strategy: ownership tracking with incremental construction. Rather than scanning every type that implements the interface at compile time, types are collected incrementally at each ownership operation point of every List(Animal):
// Construction point
animals: List(Animal) = [Dog.new()] // AnimalGroup = { Dog(Dog) }
// append point
animals.append(Cat.new()) // The compiler sees Cat at append → expands to { Dog, Cat }
animals.append(Bird.new()) // Expand again to { Dog, Cat, Bird }Compiler processing (incremental):
- When a
List(Animal)is first constructed → generate an initial enum (all construction types known within the current compilation unit) - On every
append/push/ index assignment → check whether the value's type is already present in the enum; if not, add an enum variant - Generate monomorphized
matchdispatch code for the final enum - Across compilation units: depend on LTO (link-time optimization) to merge enum variants. When
Animalis passed as an existential type across compilation-unit boundaries, each unit generates a partial set of enum variants, which are merged into a complete enum during the link stage.
Automatically generated enum:
# Automatically generated by the compiler (invisible to the user)
AnimalGroup: Type = {
Dog(Dog),
Cat(Cat),
Bird(Bird), # ← append(Bird.new()) triggers incremental expansion
}
# List(Animal) is internally equivalent to List(AnimalGroup)6.3 Interface matching checks
Key insight: Interface matching is checked at compile time, even when the type comes from a dynamically loaded plugin.
# Plugin system
plugin = load_plugin("bird.so")
# Compiler check: the return type of plugin.create_bird() must implement Animal
bird: Animal = plugin.create_bird() # Compile-time check, existential type
# Put into a heterogeneous container — the append point triggers enum expansion
animals: List(Animal) = [Dog.new(), Cat.new()]
animals.append(bird) # Compiler: (1) verify bird implements Animal (2) extend the enumCompiler processing:
- Check the return type of the
appendargument - Verify that the type implements the target interface
- If it passes → extend the enum and permit insertion
- If it fails → compilation error
6.4 Runtime dispatch
Call flow (compile-time enum match; ImplementationProof has been erased):
animals[0].speak()
↓
编译器生成的 match:
match animals[0] {
AnimalGroup.Dog(d) => d.speak(),
AnimalGroup.Cat(c) => c.speak(),
AnimalGroup.Bird(b) => b.speak(),
}Brand projection (interaction with RFC-009a): The match pattern binding AnimalGroup.Dog(d) produces a #animals[0].Dog child brand in the brand tree, equivalent to a field projection (#42.field_x). The ReadToken(d) brand chain created by d.speak() is animals → animals[0] → d → ReadToken(d), and the borrow checker validates conflicts through prefix matching in the brand tree.
Subscript access type: animals[0] returns &AnimalGroup (the compiler-generated enum type); users cannot directly obtain &mut Animal. Mutable access is implemented indirectly through interface methods (for example, animals[0].mutate() expands internally to AnimalGroup::Dog(d) => d.mutate()).
Comparison with vtables:
| Vtable (Rust) | Compile-time enum (YaoXiang) | |
|---|---|---|
| Lookup method | Vtable pointer → method pointer | Enum match → direct call |
| Runtime overhead | One indirect lookup | Branch (may be optimized by CPU branch prediction) |
| Compile-time generation | Vtable | Enum + match |
| User annotation | Requires dyn Trait + 'a | Not required |
| ImplementationProof | Not applicable | Erased at compile time; absent at runtime |
YaoXiang advantages:
- No brand annotations are required
- Compile-time type safety
- Transparent to users (no need to write
dyn Animal) - ImplementationProof is a pure compile-time concept with zero runtime overhead
6.5 Limitations and scope
Within the current phase (a single compilation unit): Full support. Ownership tracking covers every append/construction point, and the enum is built incrementally.
Across compilation units: Depends on LTO (link-time optimization) to merge enum variants. Animal is passed as an existential type (∃S. Animal(S)) across compilation-unit boundaries. Each unit generates a partial set of enum variants, which are merged during the link stage.
Not supported: Runtime dynamic types (full duck typing). The type set is completely known at compile time.
6.6 Implementation notes (Phase 3, implemented in v1)
The semantics of §6 (heterogeneous containers, compile-time membership checks, dispatch by actual type, and a compile-time closed type set) have all been implemented. At the mechanism level, the implementation makes the following concrete refinements:
- Type collection: Collect the set of implementing types across the entire compilation unit in one pass according to
ImplementationProof, replacing §6.2's "incremental collection at each ownership operation point". The two are semantically equivalent within a single compilation unit (the additional dead variants are harmless); the value of incremental collection lies in cross-unit scenarios, which are deferred to v2. - Representation: The compiler synthesizes an
Animal$Groupvariant type as a pure IR/bytecode/runtime artifact (instructionsCreateVariant/VariantTag/VariantPayload, runtime valueRuntimeValue::Enum). MonoType is unaware of it—the user-visible type at the typecheck layer remains the interface name. Every concrete value entering an existential type position is automatically wrapped as a variant value (a uniform opaque representation, §6.4 semantics). - Wrapping points: Typecheck performs targeted traversal at locations where the "concrete vs. existential" distinction is made (annotated let/call argument/return/list literal element), producing a span-keyed enforcement table; IR generation injects wrappers according to the span. A missed wrapper is loudly rejected by a runtime guard (
VariantTag/VariantPayloadvalidates that the value must be a variant value of the named group); at worst, this produces an explicit runtime error during testing, and incorrect data is never silently emitted. - Dispatch: A variant-number comparison jump chain unpacks the payload in each arm and then makes a static call to the concrete method; the RFC-004 rebinding form (
Type.method = fn[n]) is reordered according to binding position and likewise participates in dispatch. - Isolation: Legacy trait constraints (the
Drawable: Type = {..}form, with no generic parameters) do not use variant dispatch, and their behavior is unchanged.
v1 boundaries (later phases): Cross-unit LTO variant merging (§6.5); pattern matching on Group values (dependent on IR support for match with variant patterns); reflection interaction; Move-into-container semantics; Any/type-variable forwarding flows and inferred-type lambda boundaries (fallback = runtime guard).
Use-case analysis
Basic interface implementation
# Interface definition
Animal: (Self: Type) -> Type = {
speak: (self: &Self) -> String,
}
# Type definition
Dog: Type = {
x: Int = 10,
Animal(Dog),
speak: (self: &Dog) -> String = "Woof",
}
# Usage
dog = Dog.new()
dog.speak() # "Woof"Multiple interface implementations
# Multiple interfaces
Animal: (Self: Type) -> Type = {
speak: (self: &Self) -> String,
}
Pet: (Self: Type) -> Type = {
name: (self: &Self) -> String,
}
# The type implements multiple interfaces
Dog: Type = {
x: Int = 10,
Animal(Dog),
Pet(Dog),
speak: (self: &Dog) -> String = "Woof",
name: (self: &Dog) -> String = "Buddy",
}
# Usage
dog = Dog.new()
dog.speak() # "Woof"
dog.name() # "Buddy"Generic interface
# Generic interface
Container: (Self: Type, T: Type) -> Type = {
add: (self: &mut Self, item: T) -> Void,
get: (self: &Self, index: Int) -> T,
}
# Implement the generic interface
IntList: Type = {
data: Array(Int),
Container(IntList, Int),
add: (self: &mut IntList, item: Int) -> Void = ...,
get: (self: &IntList, index: Int) -> Int = ...,
}Heterogeneous container
# Interface definition
Animal: (Self: Type) -> Type = {
speak: (self: &Self) -> String,
}
# Type definition
Dog: Type = {
x: Int,
Animal(Dog),
speak: (self: &Dog) -> String = "Woof",
}
Cat: Type = {
y: Int,
Animal(Cat),
speak: (self: &Cat) -> String = "Meow",
}
# Heterogeneous container
animals: List(Animal) = [Dog.new(), Cat.new()]
# Usage
for animal in animals {
print(animal.speak())
}
# Output:
# Woof
# MeowPlugin system
# Interface definition
Plugin: (Self: Type) -> Type = {
name: (self: &Self) -> String,
execute: (self: &Self) -> Void,
}
# Main program
main: () -> Void = {
# Load plugins
plugin1 = load_plugin("plugin1.so")
plugin2 = load_plugin("plugin2.so")
# Compiler check: plugin1 and plugin2 must implement the Plugin interface
plugins: List(Plugin) = [plugin1, plugin2]
# Execute all plugins
for plugin in plugins {
print(plugin.name())
plugin.execute()
}
}Trade-offs
Advantages
- Simplicity: No
implkeyword is required - Flexibility: Method implementations may be internal or external
- Consistency: Uniform overloading rules
- Convenience: Simple default-value syntax
- Zero overhead: No vtable; compile-time type collection
- Type safety: Interface matching is checked at compile time
- Transparent to users: No need to write
dyn Animal + 'a
Disadvantages
- Restriction: Runtime dynamic types (full duck typing) are not supported
- Compile-time overhead: Enum variants and match dispatch code must be generated for every interface
- Type set: The type set must be completely known at compile time (within a single compilation unit)
Mitigations
- Plugin systems: Supported through compile-time interface matching checks
- Type set: Ownership tracking with incremental construction—collection occurs at each
append/construction point rather than through a global scan - Across compilation units: Enum variant sets are merged during linking, sharing the mechanism used for link-time monomorphization
Alternatives
| Alternative | Why it was not chosen |
|---|---|
impl keyword | Adds syntactic complexity |
Vtable (dyn Trait) | Requires brand annotations ('a) |
| Full duck typing | Runtime overhead; not type-safe |
| Manual enum wrapping | Heavy burden on users |
Relationship with RFC-009
Brands and interface implementation:
- Interface implementations operate at the type layer and do not involve brands
- Brands operate at the borrow-proof layer (RFC-009a)
- The two are orthogonal and do not affect each other
Dynamic dispatch and brands:
- Dynamic dispatch uses implementation proofs and requires no brand annotations
- Implementation proofs are generated at compile time, with zero runtime lookups
- This avoids the complexity of
dyn Trait + 'a
Ownership of heterogeneous containers:
- Inserting into
List(Animal)uses Move semantics (RFC-009), and the original variable can no longer be accessed - Subscript access
animals[0]returns&AnimalGroup(a compiler-generated enum), with the brand projection chainanimals → animals[0] → enum_variant → field - Mutable access is implemented indirectly through interface methods and does not expose
&mut AnimalGroupto users
Interface inheritance
An interface may contain another interface. No new syntax is introduced—it uses exactly the same syntactic position as a type declaring an interface:
# Interface definition
Animal: (Self: Type) -> Type = {
speak: (self: &Self) -> String,
}
Pet: (Self: Type) -> Type = {
Animal(Self), # Pet inherits Animal — no new keyword
name: (self: &Self) -> String,
}
# When Dog implements Pet, it must satisfy all methods of both Animal and Pet
Dog: Type = {
x: Int,
Pet(Dog),
speak: (self: &Dog) -> String = "Woof", # From Animal
name: (self: &Dog) -> String = "Buddy", # From Pet
}Design principles: Inheritance exists, but its abuse is discouraged. The primary composition mechanism is multiple interface instantiation (Dog: Type = { Animal(Dog), Pet(Dog), ... }). A type may directly declare every interface it satisfies without expressing this through an inheritance tree. Interface inheritance should be used only where there is a clear "is-a" hierarchy.
Compiler processing: Expand the inheritance chain. Pet(Self) expands into { all methods of Animal(Self), name: ... }. When Dog declares Pet(Dog), Self ↦ Dog is applied, and the compiler verifies that Dog satisfies all methods of both Animal(Dog) and Pet(Dog).
Self substitution in interface inheritance: In Pet: (Self: Type) -> Type = { Animal(Self), ... }, the Self in Animal(Self) is the Self parameter of Pet—it is substituted lazily. When Dog implements Pet(Dog), Self ↦ Dog, and Animal(Self) becomes Animal(Dog). This is exactly consistent with the parameter-passing semantics of generic functions.
Default method implementations
An interface may provide default implementations of methods. An implementing type may choose to override or inherit the default implementation:
fmt: (Self: Type) -> Type = {
display: (self: &Self) -> String, # Must be implemented
debug: (self: &Self) -> String = self.display(), # ✅ References a method in the same interface
summary: (self: &Self) -> String = f"<{self.name}>", # ❌ Compilation error: self.name is not in fmt
}Core constraint: An interface cannot assume that a parent implementation exists. A default method may reference only methods already declared in the same interface. Fields of the concrete type and methods from other interfaces are not visible to default methods—an interface is a closed contract and cannot reach into the implementing type's pockets. Violating this constraint produces an error immediately at interface definition time.
Inheritance can rely on inherited methods: When interface Pet(Self) inherits Animal(Self), a default method of Pet may use methods declared by Animal because inheritance guarantees their availability.
Animal: (Self: Type) -> Type = {
speak: (self: &Self) -> String,
}
Pet: (Self: Type) -> Type = {
Animal(Self), # Inheritance
name: (self: &Self) -> String,
introduce: (self: &Self) -> String = self.name() + " says " + self.speak(), # ✅ speak comes from inherited Animal
}Compile-time behavior: When a type implements an interface, the compiler processes each method as follows:
- The type provides it → use the type's method
- The type does not provide it, but the interface has a default → inline the default implementation into the type (zero vtable overhead)
- The type does not provide it, and the interface has no default → compilation error
Design principles: Default methods are similar to the automatic derivation of Copy/Clone—the compiler generates them when needed, and users may override them. No virtual/override/super keywords are introduced.
Implementation phases
| Phase | Content | Dependencies |
|---|---|---|
| Phase 1 | Interface declaration syntax ((Self: Type) -> Type) + Self type parameter | RFC-011 |
| Phase 2 | Interface instantiation (Animal(Dog)) + Self ↦ ConcreteType substitution | Phase 1 |
| Phase 3 | Internal/external method implementation declarations | Phase 2 |
| Phase 4 | Overloading and overriding rules | Phase 3 |
| Phase 5 | Default value syntax | Phase 3 |
| Phase 6 | Interface inheritance | Phase 4 |
| Phase 7 | Default method implementations | Phase 6 |
| Phase 8 | Implementation proof generation | Phase 7 |
| Phase 9 | Compile-time type collection | Phase 8 |
| Phase 10 | Dynamic dispatch implementation | Phase 9 |
Design decision record
| Decision | Resolution | Rationale | Date |
|---|---|---|---|
| Interface declaration syntax | Interfaces are parameterized types (Self: Type) -> Type, instantiated during implementation | Eliminates the Self magic keyword and is fully unified with the RFC-011 generic type system | 2026-06-14 |
| Self type parameter | Explicit type parameter; only a syntactic check at interface definition and a full check at the instantiation point | Avoids free type variables in HM inference | 2026-06-14 |
| Dynamic dispatch | Compile-time type collection + automatic enum generation | No vtable, zero runtime lookups, transparent to users | 2026-06-14 |
| External method declarations | Supported | As flexible as internal declarations; the compiler collects definitions across files | 2026-06-14 |
| Overriding | Prohibited (identical signatures produce an error) | Overriding leads to unpredictable behavior; the overloading rules cover all cases | 2026-06-14 |
| Interface inheritance | Supported, with no new syntax | Uses the same syntactic position as type-declared interfaces. Favors composition (multiple interface instantiations) and discourages deep inheritance trees | 2026-07-03 |
| Default method implementations | Supported, similar to automatic Copy/Clone derivation | The interface provides a default body and the compiler inlines it into the implementing type; users may override it. No virtual/override keywords | 2026-07-03 |
| Default method constraints | Validated at interface definition: only same-interface methods may be referenced; parent implementations cannot be assumed | An interface is a closed contract. Inheritance can rely on inherited implementations, but an interface cannot rely on fields/methods of the implementing type | 2026-07-03 |
| Type collection strategy | Ownership tracking with incremental construction—collection at each append/construction point | Not a global scan of all implementors; the enum is expanded incrementally at ownership operation points | 2026-07-03 |
| ImplementationProof | Pure compile-time concept, erased at runtime | Runtime dispatch uses an enum match; the proof is used only for compile-time verification | 2026-07-03 |
| Across compilation units | LTO merges enum variants | Existential types pass across compilation-unit boundaries; each unit generates a partial enum, merged during LTO | 2026-07-03 |
| Field/method namespace | Unified namespace; conflicts produce errors | Field access point.x and method call point.x() cannot be distinguished syntactically; unification avoids ambiguity | 2026-07-03 |
| Heterogeneous container ownership | Move semantics; the original variable is unavailable after insertion | Consistent with the RFC-009 ownership model | 2026-07-03 |
| Brand projection | A match pattern binding produces a child brand, equivalent to a field projection | Consistent with the RFC-009a brand tree mechanism; enum variant projection is a valid brand tree path | 2026-07-03 |
| Receiver spelling convention | &Self borrow / &mut Self mutable borrow / by value = Move | The receiver follows signature semantics (RFC-009), and interfaces default to borrowing; historical by-value spellings have been migrated to &Self | 2026-08-30 |
Open questions
- [x]
Interface inheritance (an interface may inherit other interfaces)→ Supported, with no new syntax.Pet: (Self: Type) -> Type = { Animal(Self), ... } - [x]
Default method implementations (an interface may provide default implementations)→ Supported, similar to automatic Copy derivation. The interface provides a body, and the compiler inlines it as needed - [x]
Self as an implicit magic keyword→ Eliminated.Selfis an explicit type parameter, and an interface is(Self: Type) -> Type - [ ] Advanced uses of interface constraints (associated types, GAT)—associated types are implemented through generic interface parameters (
Container: (Self: Type, T: Type) -> Type), while GAT requires further design - [ ] Interaction with closures (closures implementing interfaces)—the initial strategy is for closures not to implement interfaces directly and to require a wrapper type. Anonymous-type interface implementations are deferred to a future RFC
References
- RFC-011: Generic Type System Design — Parent RFC
- RFC-009: Ownership Model Design — Ownership system
- RFC-009a: Borrow Proof Pipeline — Brand mechanism
- RFC-010: Unified Type Syntax — Unified syntax
Lifecycle and final destination
| Status | Location | Description |
|---|---|---|
| Accepted | docs/design/rfc/accepted/ | Formal design document |
