r/ProgrammingLanguages • • 18h ago

Discussion Design Review of Another Approach to Polymorphism

17 Upvotes

This post and the language we are about to discuss are human-written. No AI writing or coding here.

My Motivation

I'm about to start implementing polymorphism features for a systems language I'm working on. It won't be easy to step back once this is in place, so I'm here to discuss the semantics and design before I start coding. The approach I'm proposing differs from classic OOP, interfaces, or traits, though I make no claim to novelty -- it probably already exists somewhere in some form, and I just don't know about it. This design is mainly inspired by Julia (multiple dispatch) and Rust (traits and where bounds). I'd love to get your feedback on the semantics and plans: ideas, criticism, warnings, advice -- any thoughts are welcome.

Design Explanation

Polymorphism in this language is built on two ideas: Generics and Concepts.

A Generic is a compile-time type abstraction. Nothing special here -- pretty much the same as in other languages.

A Concept is a compile-time abstraction for relations between types. Basically, it's an abstract function signature with generic argument and return types. Concepts are meant to be implemented for specific types, and any language construct (types, functions, or other concepts) can be constrained by them.

It's easier to show, so let's walk through a few examples. I'll start with a Vec2 toy type:

type Vec2 = (F32, F32)

Simple Example (default)

The most basic concept I have in mind is default. It has one generic parameter and no arguments:

concept default[T]() -> T

To implement a concept for a type, we use the impl keyword. You can think of a concept as a single-function interface, or a promise that a function will be implemented:

impl default() -> Vec2 {
    return (0.0, 0.0)
}

Here is what usage looks like:

fn main() {
    let v1: Vec2 = default()
    let v2 = default[Vec2]()
    // Both forms are equivalent
}

Overload Example (add)

Let's overload the + operator using an add concept:

// L, R, O - generics.
concept add[L, R, O](left: L, right: R) -> O

impl add(left: Vec2, right: Vec2) -> Vec2 {
    return (left.0 + right.0, left.1 + right.1)
}

Note that O (short for Output) is a regular generic parameter, not an associated type. This allows multiple implementations with the same input types and different output types -- for instance, impl add(left: F32, right: F32) -> F32 and impl add(left: F32, right: F32) -> F64 can coexist, with the type inference engine picking the right one from context. The obvious trade-off is inference ambiguity: unannotated bindings like let x = a + b or intermediate expressions in chains like a + b + c cannot be resolved without an explicit type constraint (which ties directly into my open questions below).

Usage looks like this:

fn sum3[T](a: T, b: T, c: T) -> T with add[T, T, T] {
    return a + b + c
    // The code above desugars to `add(add(a, b), c)`
}

fn main() {
    let v1: Vec2 = (1.0, 2.0)
    let v2: Vec2 = (3.0, 4.0)
    let v3: Vec2 = (5.0, 6.0)

    let res = sum3(v1, v2, v3)
}

Notice how sum3's arguments are constrained by the add concept using the with keyword. We can only pass arguments whose type implements add in this form (L, R, and O are all the same type T).

Generic Bounds Example (iter & next)

Here is a more advanced example where one concept is tightly bound to another. Later, this is meant to power for loops (for val in sequence {}) under the hood.

concept iter[T, I, Item](t: T) -> I with next[I, Item]
concept next[I, Item](iter: I) -> Item | None

The iter concept takes a type and returns an iterator, where an iterator is any type that implements the next concept. The next concept takes an iterator and returns either a value or None. None is just a zero-sized stub type (type None = struct {}). Let's define a simple List type (like Rust's Vec or C++'s std::vector) and implement these concepts for it:

type List[T] = struct {
    ptr: Ptr,
    len: UWord,
    cap: UWord,
}

type ListIter[T] = struct {
    list: List[T],
    index: UWord,
}

// Stub functions for this demo
fn List[T].new() -> List[T] {...}
fn List[T].push(self: List[T], item: T) -> List[T] {...}

And the implementations:

impl iter[List[T], ListIter[T], T](t: List[T]) -> ListIter[T] {
    return { list: t, index: 0 }
}

impl next[ListIter[T], T](iter: ListIter[T]) -> T | None {...}

fn main() {
    let list = List
        .new()
        .push(1)
        .push(2)
        .push(42)

    let it = list.iter()  // Type: ListIter[I32]
    let val1 = it.next()  // 1
    let val2 = it.next()  // 2
    let val3 = it.next()  // 42
    let val4 = it.next()  // None

    // Equivalent form
    for val in list {}
}

Dynamic Dispatch Example

All the examples above are monomorphized at compile time. In other words, the compiler generates a specialized version of each function for every concrete type it's used with (during IR lowering). However, sometimes we don't know the exact type or concept implementation at compile time, so we need virtual tables (similar to dyn in Rust or virtual in C++). Here is how I plan to handle this:

concept voice[T](self: T)

type Dog = struct {...}
type Cat = struct {...}
type Tiger = struct {...}

impl voice(self: Dog) { print("woof-woof") }
impl voice(self: Cat) { print("meow-meow") }
impl voice(self: Tiger) { print("RRRRRRR") }

fn speak_all[T](list: List[Heap[T]]) with vtable voice[T] {
    for animal in list {
        animal.voice()
        // Or `voice(animal)`
    }
}

Heap is a smart pointer, like Box in Rust or std::unique_ptr in C++. The main idea is that adding the vtable keyword before a concept bound enables dynamic dispatch through virtual tables. Under the hood, Heap[T] becomes a fat pointer, which lets you store different concrete types (like Dog, Cat, and Tiger) in the same list as long as they implement the same concept. Each element's vtable is then used to pick the right concept implementation at runtime.

Open Questions

Here are the main questions I'd like to ask this subreddit. I don't have solid answers to them yet, which is the reason for this post:

How should I deal with "generics explosion" and output-type ambiguity? Because every parameter in a concept is an unconstrained generic, signatures quickly become verbose -- for example, in iter[List[T], ListIter[T], T](t: List[T]), the type arguments take up more space than the signature itself. At the same time, leaving output types independent (like O in add[L, R, O]) weakens local type inference when there isn't enough surrounding context. I'm aware of associated types (as in Rust) and functional dependencies (as in Haskell, e.g., T -> I, Item), but I'm not sure what fits best here:

  • Do associated types make sense syntactically for single-function concepts, or are functional dependencies more natural?
  • Is there a simpler mechanism (such as distinguishing input vs. output type parameters in the concept header, or partial type application) that solves inference and verbosity without adding the complexity of full functional dependencies to the solver?

How should multiple implementations of the same concept be handled?

  • An orphan rule like in Rust? I'd really like semantics that allow writing bridge packages between independent libraries. For example, in Rust, serde is the go-to library for serialization, so authors of other libraries have to maintain a feature flag to support it on their types. If a library defines Vec2 like above, its author has to add serde to dependencies and write #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]. It's very hard to create an independent bridging package like vec2_serde. If a library author didn't add that support and you need it, you end up having to fork the repo or wrap the type yourself. I want to make bridging libraries possible.
  • Force developers to give every implementation a unique name and specify it explicitly? That would make the semantics much harder to use and even more verbose.
  • Just throw a compile error if there's a conflict (like Haskell does)?

How should a specific concept implementation be imported? Should implementations be importable at all, or is it better for the compiler to see all implementations globally regardless of where they are defined?

How should a concept implementation be associated with a specific type -- and more importantly, should it be? As shown in the examples, regular functions can be associated with a type (fn List[T].push(self: List[T], item: T)). Since a concept implementation is basically a function, it would be more symmetric to do the same here. However, syntax like impl List[T].iter[List[T], ListIter[T], T](t: List[T]) -> ListIter[T] is way too verbose and overcomplicated, in my opinion.


r/ProgrammingLanguages • • 6h ago

Discussion Compact notational/numeral-system-like representations for polynomials, series, simple programs and iterating terms?

2 Upvotes

Good evening!

Recently I've stumbled onto the notation [a; b, c, d, e...] for continued fractions "a + 1/(b + 1/(c + 1/...)..)". I have a gut feeling this can be a very useful representation and maybe some clever algebra may be defined over it, turning it effectively into an alternative "numeral-like" system.

I tried searching for such similar compact representations for other finitely and infinitely iterating terms/series in mathematics as well as normal forms for them and rewriting algorithms but I've didn't manage to find anything.

There are series that, if you abstract away the concrete operations and base sets/algebras, seem to have a very similar structure throughout analysis; they almost feel like a very definite class of programs. That would feel amenable for a more abstract characterization in category theory but I've never seen that.

From my intuition most of these series seem to rely a bit on fold, maybe streams, initial algebras and other structures commonly studied in functional programming, but if any of you have other ideas to suggest, I would appreciate :))

I wish everyone a great weekend!


r/ProgrammingLanguages • • 17h ago

Language announcement Cole Backend Update: QBE

1 Upvotes

Hey everyone,

For the past week, I've been working on the new backend of the Cole compiler: QBE. Due to the CLI oriented nature of QBE, I had to modify the source code a little and create my own fork to set up a static library build that I can call from my codebase.

The C backend already had a pretty lowered IR, so I just generate another IR on top of that and generate QBE IR from it.

Since QBE only spits out assembly, I had to ship an assembler as well. I found Minias to be a suitably small and fast assembler for GNU Style x86_64 so I modified its source code to become a static library as well and called it from the codebase.

Lastly, the linker. I already had TCC as a backend, so I decided to reuse it as a linker. The QBE backend first calls into QBE, then into Minias and then into TCC to link the final executable. Thus, we have a self-contained compiler pipeline now.

You can read more about it in this blog entry.

Happy programming!

Note: although the backend is not 100% complete, it can compile the Pong RayLib Demo that's in the source code, so I take that as a success!