r/ProgrammingLanguages • • Jan 05 '26

Iterator fusion similar to Rust's — are there other languages that really do this, and what enables it?

52 Upvotes

While trying to learn Rust, and while reading about iterators, I came across the following definition, which really caught my attention:

Iterator fusion is a compilation technique in which a chain of iterator adapters is combined into a single loop, eliminating intermediate iterators and producing code equivalent to an optimal hand-written implementation.

Digging a bit further, I learned that in Rust this means code like:

let sum: i32 = data
    .iter()
    .map(|x| x * 2)
    .filter(|x| *x > 10)
    .sum();

can end up being equivalent (after optimization) to something like:

let mut sum = 0;
for x in data {
    let y = x * 2;
    if y > 10 {
        sum += y;
    }
}

No temporary collections, no multiple passes — just a single tight loop.

This really stood out to me because, in the past, I tried implementing iterators in Go for a toy project. What I ended up with involved:

  • temporary allocations,
  • multiple loops over the data (even when one would be enough),
  • and quite a bit of “voodoo” just to achieve laziness.

I’m sure my design wasn’t ideal, but I learned a lot from it.

What really surprised me here is the idea that iterator handling is largely resolved at compile time, rather than being a runtime library mechanism. That feels very different from what I’m used to, and honestly very appealing.

Coincidentally, I’m once again in the phase of designing yet another programming language (like the previous two attempts, there’s a good chance I’ll abandon it in six months 😄).

Reading that definition immediately made me think:
“If I were designing a language, I wouldn’t even know where to start to get something like this.”

So I have a few questions, mostly from a language-design and learning perspective:

Are there other languages that really offer this in the same sense?

Not just “the compiler might optimize it if you’re lucky” (looking at you, LINQ), but cases where programmers can reasonably expect and rely on this kind of transformation when writing idiomatic code.

What enables this kind of behavior?

From a language-design point of view:

  • What kinds of design choices make iterator fusion possible?
  • What choices make it hard or unrealistic?

This whole question really came from reading that one definition and thinking:
“Wow — this is a powerful idea, and I don’t even know where to begin implementing something like it.”


r/ProgrammingLanguages • • Jan 05 '26

Multi-Pass Bytecode Optimizer for Stack-Based VMs: Pattern Matching & 10-50% Performance Gains

26 Upvotes

I recently finished documenting the bytecode optimizer for my stack-based VM interpreter, and wanted to share the design and results.

The Problem

I have written a vm following Crafting Interpreters part 2 and most toy VMs compile to bytecode and execute it directly. But naive bytecode generation produces patterns like:

OP_Get_Local 0      # x
OP_Constant 1       # Push 1
OP_Add              # x + 1
OP_Set_Local 0      # x = ...
OP_Pop              # Discard result

That's 5 instructions for what should be a x++. Meanwhile, the stack is churning through push/pop operations, the constant table is being accessed, and we're fetching 5 separate instructions from memory.

The Solution: Multi-Pass Pattern-Based Optimizer

I built a bytecode rewriter with a powerful pattern matching engine that transforms bytecode after compilation but before execution. The key insight: treat bytecode like an IR and apply traditional compiler optimizations.

Architecture

PassManager orchestrates multiple optimization passes:

  • Each pass gets multiple iterations until convergence
  • Passes run in sequence (early passes enable later ones)
  • Automatic jump offset adjustment when bytecode size changes
  • Debug mode shows before/after for each pass

BytecodeRewriter provides pattern matching:

  • Match specific opcodes, groups, or wildcards
  • Capture instructions for analysis
  • Lambda-based transformations
  • Conditional rewrites (pattern + semantic checks)

Example: Increment Optimization Pass

Transform that 5-instruction pattern into specialized opcodes:

std::vector<PatternElement> pattern = {
    PatternElement::match(OP_Get_Local, true),    // Capture local index
    PatternElement::constant(true),                // Capture constant
    PatternElement::match(OP_Add),
    PatternElement::match(OP_Set_Local, true),    // Capture local index
    PatternElement::match(OP_Pop),
};

auto condition = [&chunk](auto& captured) {
    // Same local? Constant is 1?
    return (captured[0].operands[0] == captured[2].operands[0]) &&
    (AS_INT(chunk.constants[captured[1].getConstantIndex()]) == 1);
};

auto transform = [](auto& captured) {
    return {OP_Incr_Local, captured[0].operands[0]};  // 2 bytes total!
};

rewriter->addAdvancedRule(pattern, transform, condition);

Result:
5 instructions -> 1 instruction

OP_Get_Local 0      # x  
OP_Constant 1       # Push 1  
OP_Add              # x + 1  
OP_Set_Local 0      # x = ...  
OP_Pop              # Discard result  

gets converted to

OP_Incr_Local 0     # Increment x by 1  

Other Implemented Passes

Constant Folding

OP_Constant 5  
OP_Constant 3  
OP_Add  

gets converted to

OP_Constant 8  

Fuse Multiple Pops

OP_Pop  
OP_Pop  
OP_PopN 3  

gets converted to

OP_PopN 5  

Optimize Binary Operations on Locals

OP_Get_Local 0  
OP_Get_Local 1  
OP_Add  

gets converted to

OP_AddLL 0 1    # Direct register-style op  

Dead Store Elimination

OP_Constant 10  
OP_Define_Global x  
OP_Get_Global x  

gets converted to

OP_Constant 10  
OP_Define_Global_Non_Popping x  # (value stays on stack)  

Real-World Results

Measured on Advent of Code solutions and benchmarks:

  • Bytecode size: 10-30% smaller
  • Execution speed: 10-50% faster (loops benefit most)
  • Optimization time: ~5-10ms per script
  • Cache efficiency: Better (fewer instruction fetches)

The increment optimization alone is huge for loops - common patterns like for (var i = 0; i < n; i++) get massively faster.

Documentation

I just finished writing comprehensive docs for the whole system:

Full Documentation : https://columbaengine.readthedocs.io/en/latest/script/optimizer.html

Covers:

  • All built-in optimization passes
  • Pattern matching API
  • Writing custom passes
  • Performance analysis
  • Debugging techniques

VM Internals: https://columbaengine.readthedocs.io/en/latest/script/vm_internals.html

Covers NaN-boxing, stack architecture, memory management, etc.

Source Code

The engine is open source: https://github.com/Gallasko/ColumbaEngine

Relevant files:

  • Pass manager: src/Engine/Compiler/bytecode_pass.cpp
  • Rewriter: src/Engine/Compiler/bytecode_rewriter.cpp
  • Individual passes: src/Engine/Compiler/pass/

I'm particularly interested if anyone has tried similar approaches or has suggestions for additional optimization passes!


This is part of ColumbaEngine, a game engine with an embedded scripting language. The VM uses NaN-boxing for values, pool-based memory management, and supports closures, classes, and first-class functions.


r/ProgrammingLanguages • • Jan 05 '26

Blog post Blogpost #7 — Meet Duckling #0 — How types and values are one and the same

Thumbnail duckling.pl
15 Upvotes

r/ProgrammingLanguages • • Jan 05 '26

Discussion Syntactic Implicit Parameters with Static Overloading

Thumbnail microsoft.com
29 Upvotes

r/ProgrammingLanguages • • Jan 05 '26

Help Bytecode rules for a strange Structural/Data/Pattern oriented VM?

3 Upvotes

Heyo everyone, I'm working on a meta-programming language focused on procedurally and structurally typing different patterns of data. It's heavily inspired by Perl, Typescript, Smalltalk, Rust('s macros), Haskell, Yaml, MD, and some Zig too.

Some of the core things I'd want it to be able to do are:
- *Structural typing with multiple inheritance* multiple types of inheritance/polymorphism in fact. I want to be able to support lots of weird data shapes and types. The goal is to mask the data with annotations/types/classes etc that explain how to read the data and how to manipulate it etc.
- *Defining nested addressable nodes* allowing sub nodes, values, and metadata. (everything is a tree of defs, even lines of logic like in lisp like languages).
- *build/add to/compose/annotate/re-type* a mutable def or a new def before finalizing.
- *Defining procedural structural prototypes* and interfaces as opposed to just instances of structures.
- The idea here is to be able to use a shape(with holes) as a self building prototype (see ts-like examples):
* `myObj = { key: "value" #str }` this would work as expected and make an object adressed: myObj, with a single structural property (key) with a string value (``#str` is the typing).
* `makeObj >> {key: #str}; makeObj(key: 'value');` This example would produce an interface/archetype (a prototype with a 'hole' that needs to be filled (#str isn't nullable/optional so the value is missing)).
- *Structural prototypes/procs should be self building scopes* that return themselves.
* The idea here is that property lines in a prototype result in captured properties, and local/logic lines in a prototype are executed in order of call each time it's called... for example:
* `Point >> {x#int, y#int, .if(z#int?) ...{z}};` This would be able to produce a structured object with shape `{x#int, y#int}` or `{x#int,, y#int, z#int}` depending on what you pass in.
- *Pattern based parsing* is something I also want to be somewhat 'first class'. The idea is that types could be defined as patterns that use regex/rustmacro like captures to structure tokens into data of a desired type; and potentially even then map that data to the execution of other bytecode.
* Example: `printList ::= word (\, word)* => (PRINT; ...words);`
- *memory management is mostly based on type/annotation*
- Non captured defs (defined with `=` instead of `:`) are cleaned up at the end of their declaring scope.
- Captured defs can be either `#ref` or `#raw` type, ref meaning ref/pointer based and raw meaning raw bytes that are copied when passed (you can wrap any raw type with #ref too of course).
- Dealing with refs is still a bit fuzzy... might do generational counters or require you to copy/own the value if you want to move it to an outer scope, or use some more cursed memory management technique....

I've been following along in Crafting Interpreters and have looked at a few other guides but I think they all focus on stacks-first languages and I think i'm going for something else entirely (a def based VM?)

Does anyone have any good suggestions on how to work out a core set of VM ops for something like this? I have a feeling I want basically everything to be a `def` 'slot' that you then add the following to: pointers for sub-defs(including getters setters funcs, etc), raw value/alloc data, and/or metadata(types etc). I can't really figure out how to structure that in a good modular way in a low memory setting though without... feeling like getting lost in the reeds~

I also am not sure how to reconcile the procedural/logic/quote defs with non proc ones... or if I even need to. Should I have a root `call` and a `def` directive and keep everything under those? Is there a way to combine them without needing to even make logic distinct from the data/defs (so node-based logic... this would be ideal I think?).

Any ideas would be greatly appreciated... even just help with correct terminology for what I'm working on (for some reason standard programming terms are often a weak point for me). Thank you all so much for taking the time to read this!


r/ProgrammingLanguages • • Jan 04 '26

Are there purely functional languages without implicit allocations?

44 Upvotes

I'm coming from Rust, so a lot of my ideas about systems programming come from its models, but I like the idea of purely functional programming and type-level proofs. I've been trying to keep performance as close to compiled code, and one thing that I can't get around is lifetimes.

The simplest way would be to just heap-allocate by default, but I don't really like implicit allocations and want to see if it's possible to have a language that's still usable (i.e. doesn't need lifetime annotations everywhere) but also doesn't implicitly use the heap.

When you have a function type a -> b -> c, where can you put a lifetime annotation in there? Can you differentiate between a function that uses a local variable only after its first argument (meaning the function it returns is valid for the whole lifetime of the program) and one that depends on a local variable after it's received two arguments (meaning the function it returns after the first argument is bound to a local scope)? I've figured out how to resolve other issues, like differing captures, with implicit parameters to put closures on the stack, but I can't figure out how to ensure that everything stays valid.

I'm not tied to the idea of lifetimes, but they're what I'm used to and I don't know any other solutions to memory safety that don't involve heap allocation and garbage collection, which I'm trying everything that I can to avoid.


r/ProgrammingLanguages • • Jan 04 '26

What's wrong with subtypes and inheritance?

31 Upvotes

While working on the formal verification of some software, I was introduced to Shapiro's work and went down a rabbit hole learning about BitC, which I now understand is foundational for the existence of today's Rust. Even though Shapiro made sure to scrub as much as possible any information on the internet about BitC, some writings are still available, like this retrospective.

Shapiro seems to be very much against the concept of subtyping and inheritance with the only exception of lifetime subtypes. Truth to be told today's rust neither has subtyping nor inheritance, except for lifetimes, preferring a constructive approach instead.

I'm aware that in the univalent type theory in mathematics the relationship of subtyping across kindred types leads to paradoxes and hence is rejected, but I thought this was more relevant to axiomatic formulations of mathematics and not real computer science.

So why is subtyping/inheritance bad in Shapiro's eyes? Does it make automatic formal verification impossible, like in homotopy type theory? Can anyone tell me more about this?

Any sources are more than welcome.

EDIT: For future reference, this provides a satisfactory overview of the problem.


r/ProgrammingLanguages • • Jan 04 '26

Meeting Seed7 - by Norman Feske

Thumbnail genodians.org
20 Upvotes

r/ProgrammingLanguages • • Jan 04 '26

Another termination issue

Thumbnail futhark-lang.org
18 Upvotes

r/ProgrammingLanguages • • Jan 04 '26

Task engine VM where tasks can contain executable instructions

Thumbnail github.com
5 Upvotes

Here is my winter holiday project. Current scope and known issues are listed in readme, so thoughts and ideas on them are welcome ^_^

Why? The concept was to provide maximum flexibility with programmable task behaviour as an alternative to the hardcoded features of standard todo apps. That experiment led to a vm with own set instructions.
example code (see other in tests): Task with calldata that creates another task when called

PUSH_STRING Parent PUSH_STATUS 2 \
PUSH_CALLDATA [ PUSH_STRING Child PUSH_STATUS 0 PUSH_CALLDATA [ ] T_CREATE END_CALL ] T_CREATE \
PUSH_U8 0 CALL

r/ProgrammingLanguages • • Jan 03 '26

Velato: Write code by whistling

Thumbnail velato.net
35 Upvotes

I originally created Velato in 2009 as a programming language written in MIDI files. Programmer-composers carefully compose works and the language gives some flexibility to make that easier: allowing for simultaneous notes, changing which note the others are read through, and variable note lengths.

In this new version, we write Velato by whistling to the machine; it immediately transpiles to JS. The lexicon is simplified to make commands shorter, but otherwise the same. Start the interface and then write code hands-free, whistling code line by line.


r/ProgrammingLanguages • • Jan 03 '26

Discussion Is large-scale mutual recursion useful?

15 Upvotes

Avoiding mutual recursion seems beneficial because when the programmer changes the behaviour of one of the mutually recursive functions, the behaviour of them all changes. A compiler might also have to recompile them all.

A tail-recursive interpreter can be structured a a huge mutual recursion but a better approach is to convert opcodes to function pointers and call the next function in that array at the end of each opcode implementation. This results in better performance and is clearer IMO.

In mainstream compilers this also makes the compiler completely unable to change the opcode implementation's signatures. Said compilers can't do anything useful with control flow that complex anyway, though.

If you look at basic blocks as functions that tail call each other, they are mutually recursive but this usually happens on a very small scale.

My question is if there is a case where mutual recursion on a very large scale is desirable or convenient. I know that OCaml requires defining mutually recursive functions next to each other. Does this lead to workarounds like having to turn control into data structures?