Skip to content

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:

  1. Interface declaration: An interface is a parameterized type—(Self: Type) -> Type; a concrete type is passed in during implementation
  2. Method implementation: Both internal and external declarations are supported
  3. Overloading rules: Different signatures may be overloaded; identical signatures produce an error (overriding is prohibited)
  4. Default values: Write = value directly after a field
  5. Dynamic dispatch: Compile-time type collection + interface matching, with no vtable

Core design:

yaoxiang
# 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-value Self = consume the receiver (Move, RFC-009).
  • Self in an impl-side signature is an alias for the impl type: interface speak: (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 impl keyword
  • ❌ No Self magic keyword (Self is an explicit type parameter, no different from T)
  • ❌ No dyn Trait + 'a annotation
  • ❌ 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:

IssueExplanation
Interface declaration syntaxHow to declare that a type implements an interface?
Method implementation locationInternal declaration or external declaration?
Overloading rulesHow are methods with the same name handled?
Default value syntaxHow are default values assigned to fields?
Dynamic dispatchHow is a heterogeneous container implemented?

Design goals ​

  1. Simplicity: No impl keyword is required
  2. Flexibility: Method implementations may be internal or external
  3. Consistency: Uniform overloading rules
  4. Convenience: Simple default-value syntax
  5. Zero overhead: No vtable; compile-time type collection

Comparison with Rust ​

FeatureRustYaoXiang
Interface declarationimpl Animal for Dog { ... }Dog: Type = { Animal(Dog), ... }
Method implementationIn an impl blockInternal or external
OverloadingNot supportedSupported (different signatures)
Default valuesRequires #[default]Write = value directly
Heterogeneous containerVec<Box<dyn Animal + 'a>>List(Animal)
Dynamic dispatchVtable lookupCompile-time type collection
Self keywordMagic keyword, implicitly quantifiedExplicit 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.

yaoxiang
# 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:

  1. Recognize that Animal(Dog) is an instantiation of (Self: Type) -> Type
  2. Perform the Self ↦ Dog substitution: expand Animal(Dog) into { speak: (self: &Dog) -> String }
  3. Check whether Dog provides all required methods (signature matching)
  4. If it passes → generate an implementation proof
  5. If it fails → compilation error

Equivalent expansion:

yaoxiang
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: Self in { 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 ↦ Dog is 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:

yaoxiang
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 ​

yaoxiang
Dog: Type = {
    x: Int = 10,
    Animal(Dog),
    speak: (self: &Dog) -> String = "Woof",  # Method implementation is internal
}

2.2 External declaration ​

yaoxiang
Dog: Type = {
    x: Int,
    Animal(Dog),
}

# Method implementation is external
Dog.speak: (self: &Dog) -> String = "Woof"

2.3 Mixed declarations ​

yaoxiang
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:

  1. Collect all definitions (internal and external)
  2. Group them by signature (overloading)
  3. Check for overrides (report an error)
  4. Check interface completeness
  5. Generate an implementation proof

3. Overloading and overriding ​

Core rule:

  • Different signatures → overload → allowed
  • Identical signatures → override → error

3.1 Overloading (allowed) ​

yaoxiang
# Different parameter types; overloading is allowed
Dog.speak: (self: &Dog) -> String = "Woof"
Dog.speak: (self: &Dog, volume: Int) -> String = "WOOF"

3.2 Overriding (prohibited) ​

yaoxiang
# Identical signatures; overriding is prohibited
Dog.speak: (self: &Dog) -> String = "Woof"
Dog.speak: (self: &Dog) -> String = "Bark"  # ❌ Error: overriding is not allowed

Error 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:

yaoxiang
# 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"  # ❌ Error

4. Default values ​

Core rule: Write = value directly after a field, eliminating the need to write constructors.

yaoxiang
Dog: Type = {
    x: Int = 10,  # Default value
    y: Int = 20,  # Default value
    Animal(Dog),
}

Compiler-generated constructors:

yaoxiang
# 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:

yaoxiang
Dog: Type = {
    x: Int,
    y: Int,
    Animal(Dog),
}

# External declaration default values
Dog.x: Int = 10
Dog.y: Int = 20

Equivalent to internal declarations.

5. Compiler implementation ​

5.1 Interface descriptor ​

rust
// Compiler internals: interface descriptor
struct InterfaceDescriptor {
    name: String,
    self_param: TypeParam,     // Self type parameter
    methods: Vec<MethodSignature>,
}

5.2 Type definition ​

rust
// 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 ​

rust
// 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)."

yaoxiang
# 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.

yaoxiang
dog = Dog.new()
animals: List(Animal) = [dog]
# dog.speak()  ← ❌ Compilation error: dog has been moved

6.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):

yaoxiang
// 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):

  1. When a List(Animal) is first constructed → generate an initial enum (all construction types known within the current compilation unit)
  2. On every append / push / index assignment → check whether the value's type is already present in the enum; if not, add an enum variant
  3. Generate monomorphized match dispatch code for the final enum
  4. Across compilation units: depend on LTO (link-time optimization) to merge enum variants. When Animal is 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:

yaoxiang
# 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.

yaoxiang
# 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 enum

Compiler processing:

  1. Check the return type of the append argument
  2. Verify that the type implements the target interface
  3. If it passes → extend the enum and permit insertion
  4. 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 methodVtable pointer → method pointerEnum match → direct call
Runtime overheadOne indirect lookupBranch (may be optimized by CPU branch prediction)
Compile-time generationVtableEnum + match
User annotationRequires dyn Trait + 'aNot required
ImplementationProofNot applicableErased 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$Group variant type as a pure IR/bytecode/runtime artifact (instructions CreateVariant/VariantTag/VariantPayload, runtime value RuntimeValue::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/VariantPayload validates 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 ​

yaoxiang
# 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 ​

yaoxiang
# 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 ​

yaoxiang
# 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 ​

yaoxiang
# 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
# Meow

Plugin system ​

yaoxiang
# 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 ​

  1. Simplicity: No impl keyword is required
  2. Flexibility: Method implementations may be internal or external
  3. Consistency: Uniform overloading rules
  4. Convenience: Simple default-value syntax
  5. Zero overhead: No vtable; compile-time type collection
  6. Type safety: Interface matching is checked at compile time
  7. Transparent to users: No need to write dyn Animal + 'a

Disadvantages ​

  1. Restriction: Runtime dynamic types (full duck typing) are not supported
  2. Compile-time overhead: Enum variants and match dispatch code must be generated for every interface
  3. Type set: The type set must be completely known at compile time (within a single compilation unit)

Mitigations ​

  1. Plugin systems: Supported through compile-time interface matching checks
  2. Type set: Ownership tracking with incremental construction—collection occurs at each append/construction point rather than through a global scan
  3. Across compilation units: Enum variant sets are merged during linking, sharing the mechanism used for link-time monomorphization

Alternatives ​

AlternativeWhy it was not chosen
impl keywordAdds syntactic complexity
Vtable (dyn Trait)Requires brand annotations ('a)
Full duck typingRuntime overhead; not type-safe
Manual enum wrappingHeavy 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 chain animals → animals[0] → enum_variant → field
  • Mutable access is implemented indirectly through interface methods and does not expose &mut AnimalGroup to 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:

yaoxiang
# 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:

yaoxiang
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.

yaoxiang
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:

  1. The type provides it → use the type's method
  2. The type does not provide it, but the interface has a default → inline the default implementation into the type (zero vtable overhead)
  3. 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 ​

PhaseContentDependencies
Phase 1Interface declaration syntax ((Self: Type) -> Type) + Self type parameterRFC-011
Phase 2Interface instantiation (Animal(Dog)) + Self ↦ ConcreteType substitutionPhase 1
Phase 3Internal/external method implementation declarationsPhase 2
Phase 4Overloading and overriding rulesPhase 3
Phase 5Default value syntaxPhase 3
Phase 6Interface inheritancePhase 4
Phase 7Default method implementationsPhase 6
Phase 8Implementation proof generationPhase 7
Phase 9Compile-time type collectionPhase 8
Phase 10Dynamic dispatch implementationPhase 9

Design decision record ​

DecisionResolutionRationaleDate
Interface declaration syntaxInterfaces are parameterized types (Self: Type) -> Type, instantiated during implementationEliminates the Self magic keyword and is fully unified with the RFC-011 generic type system2026-06-14
Self type parameterExplicit type parameter; only a syntactic check at interface definition and a full check at the instantiation pointAvoids free type variables in HM inference2026-06-14
Dynamic dispatchCompile-time type collection + automatic enum generationNo vtable, zero runtime lookups, transparent to users2026-06-14
External method declarationsSupportedAs flexible as internal declarations; the compiler collects definitions across files2026-06-14
OverridingProhibited (identical signatures produce an error)Overriding leads to unpredictable behavior; the overloading rules cover all cases2026-06-14
Interface inheritanceSupported, with no new syntaxUses the same syntactic position as type-declared interfaces. Favors composition (multiple interface instantiations) and discourages deep inheritance trees2026-07-03
Default method implementationsSupported, similar to automatic Copy/Clone derivationThe interface provides a default body and the compiler inlines it into the implementing type; users may override it. No virtual/override keywords2026-07-03
Default method constraintsValidated at interface definition: only same-interface methods may be referenced; parent implementations cannot be assumedAn interface is a closed contract. Inheritance can rely on inherited implementations, but an interface cannot rely on fields/methods of the implementing type2026-07-03
Type collection strategyOwnership tracking with incremental construction—collection at each append/construction pointNot a global scan of all implementors; the enum is expanded incrementally at ownership operation points2026-07-03
ImplementationProofPure compile-time concept, erased at runtimeRuntime dispatch uses an enum match; the proof is used only for compile-time verification2026-07-03
Across compilation unitsLTO merges enum variantsExistential types pass across compilation-unit boundaries; each unit generates a partial enum, merged during LTO2026-07-03
Field/method namespaceUnified namespace; conflicts produce errorsField access point.x and method call point.x() cannot be distinguished syntactically; unification avoids ambiguity2026-07-03
Heterogeneous container ownershipMove semantics; the original variable is unavailable after insertionConsistent with the RFC-009 ownership model2026-07-03
Brand projectionA match pattern binding produces a child brand, equivalent to a field projectionConsistent with the RFC-009a brand tree mechanism; enum variant projection is a valid brand tree path2026-07-03
Receiver spelling convention&Self borrow / &mut Self mutable borrow / by value = MoveThe receiver follows signature semantics (RFC-009), and interfaces default to borrowing; historical by-value spellings have been migrated to &Self2026-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. Self is 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 ​


Lifecycle and final destination ​

StatusLocationDescription
Accepteddocs/design/rfc/accepted/Formal design document