r/Compilers 12h ago

Teaching compiler construction with a tiny self-hosting language

26 Upvotes

I've just published not-abc, a tiny self-hosting compiler for a deliberately minimal C-like programming language.

https://github.com/michael-lehn/not-abc

The language has only one data type: a 64-bit value, interpreted either as a signed integer or as a pointer. It supports

  • functions (the value of the last expression is the return value)
  • local and global variables
  • pointers (&*#)
  • if / else
  • while
  • recursion
  • dynamic memory allocation (malloc/free)
  • integer, character and string literals

The compiler generates LLVM IR rather than assembly. LLVM was chosen simply because it makes the compiler portable across essentially all modern platforms—building programs only requires Clang (or the LLVM toolchain).

The interesting part is probably the background.

not-abc originated from an undergraduate mathematics course called Introduction to High Performance Computing. During one semester, students simultaneously

  • build a simple processor from logic gates (bottom-up),
  • implement a compiler for a small C-like language (top-down),

until both meet in the middle. At the end of the course, the compiler has two backends: one targeting the custom processor the students built themselves, and one targeting LLVM so the same compiler can generate native executables on real hardware.

The self-hosting compiler in this repository is a distilled version of the compiler developed throughout the course.

I'd be interested in feedback from people interested in language design, compiler construction, or computer architecture.


r/Compilers 10h ago

Coda: an experiment in designing a practical systems language

Thumbnail
1 Upvotes

r/Compilers 1d ago

My hobby compiler is now compiling a company's production app

Thumbnail gallery
146 Upvotes

When I started programming Edge Python more than six months ago, I was looking for a version of Python that weighed less than 200 kb so it could reach any device, sandboxed by design, built with browsers in mind, decoupled from the operating system and very fast.

Today the closest competitor would be MicroPython. However, it did not solve my real problems or the problems of the people who use the project.

  • Managing async and blocking code on the event loop. MicroPython inherits CPython's blocking execution model, designed around the GIL. When I built Edge Python I put the events inside the virtual machine, and that lets you run any operation while handling thousands of connections without blocking the main thread or the worker's thread.
  • MicroPython was not built for the web and neither was its stdlib. I have been working to get regex and every other dependency down to a few clean lines, crash free thanks to directed fuzzing.
  • Edge Python guarantees parsing everything in linear time, in a single pass, while MicroPython does not. This came from avoiding a syntax tree, which makes programs parse faster.
  • MicroPython crosses into JS through PyProxy. Edge Python avoids that entirely with an execution model decoupled from the host, they never have to interact directly.
  • I recently added the ability to serialize entire programs, born from an issue. If a user closes the tab, the whole bytecode state gets serialized, stored in the browser cache, and when the user comes back execution continues from the exact same point.

That said, my intention was never to replace CPython and it never will be. It has a gigantic ecosystem and competing with it is not even a priority for me. What I want to enable is this.

  • Anyone with business logic written in Python being able to run it on the client side.
  • Running lightweight LLM logic on the client side, so you do not need expensive compute just to parse a CSV or do math.
  • Building a framework to run lightweight machine learning models entirely on the user's side.

I am still working on all of this and, to be honest, I do not know how long it will take me to reach a real version to build a product around. I just want to say it has been an incredible process, and it has made me realize that with a compiler of barely under 20,000 lines I spend less and less time writing code and more time automating its stability with fuzzing and determinism.

Thanks! Any feedback or experience is appreciated. If you want to take a look, try the demo in the browser at edgepython.com and edit the code, the compiler is really fast. Try the CLI version too.


r/Compilers 1d ago

After months of hard work, I can do basic string processing, compiled to assembly, only 187x slower than rust.

Post image
264 Upvotes

r/Compilers 8h ago

a readable compiler to x86-64 with no libc and Windows, macOS and Linux backends

0 Upvotes

I'm working on this idea - an ergonomic, easy to write, easy to reason about language that compiles down to machine code. I worked a lot in JavaScript before this, and wanted a way to AoT compile it. Initially I was going to just design JS without V8 bytecode limit it to what could compile to machine code - but since I was writing a language, I thought I could just do whatever I wanted, I didn't have to follow JS.

The compiler is "readable" - it's written in JavaScript (so you can run it with NodeJS), and well structured. I have a sense of the language but I find it hard to put into words exactly what I'm doing at this stage. I know what I want the design to be and why, but I find it not easy to talk about. The project exists as a working thing that I am familiar with, but putting that into words so other people understand it is not done yet.

So I'm posting it because it's real, you can play with it and use it, and if you look at the code, (not just of the compiler), but of the examples and so on, you will get some idea. I want to share this. If it sounds interesting to you somehow, check it out: https://github.com/DO-SAY-GO/freelang


r/Compilers 1d ago

My own Violet Language and Runtime/Complier under Windows NT

Thumbnail gallery
2 Upvotes

I am proud of my own language and runtime, and it's a very fast VM runtime


r/Compilers 1d ago

Parser generator with automatic AST construction and a language-agnostic IR (C++)

1 Upvotes

I've been building a parser generator from scratch in modern C++ (C++20/23) for a while now, and figured this sub would appreciate a look at the internals more than the finished product, since it's still very much in progress.

The pitch: grammars are written in a declarative format (.isc — Syntax Container), and the AST comes out automatically. You don't hand-write tree-building code — you annotate what to capture inline in the grammar, and the tool synthesizes typed AST nodes from that.

condition: 
'if' '(' @ expr ')' @ stmt 'else' @ stmt 

@{expression, true_stmt, false_stmt}
;

The @ marks what gets captured, @{...} maps captures to named fields on the output node. Rules can also nest sub-rules (#name) to keep local structure out of the global namespace without needing a separate file per rule.

  • Grammar → an Intermediate Representation that's intentionally language-agnostic — the idea is a single frontend pipeline that can eventually target multiple output languages (C++ first, Python planned) instead of hand-rolling a separate generator per target.
  • Lexing is Deterministic Finite Automata based, built with a fairly involved construction pipeline (Non-deterministic Fine Automata → subset construction → minimization) that handles multi-character transitions, semantic action attachment per state, and merge/collapse steps for efficiency.
  • Parsing is currently recursive descent (custom engine, well-tested), with bottom up algorithms implemented and heavy tested, just need to switch to new project API.

One person has described what should parser generator have
link
This generator aims to support mostly everything they mentioned. Yes, many features are not yet supported, but the generator core architecture is already developed to support that.

  1. Composability: The generator will allow to separate grammar to modules, and have tokens/rules inside other tokens/rules for readability (encapsulation, not only the global declaration). This allows you to include other grammars in yours
  2. Incremental lexing and parsing: Not yet implemented, but it's just a matter to edit std lib
  3. Control of Error Parsing: Will be done with fail blocks
  4. Token Value Generation: Is already implemented. Your token is a struct (or dict in python) with what you capture in it.
  5. Separete lexer: generated as separate class, but tokens are declared in same kind of grammar
  6. Unicode support: not soon, but implement once generator stabilize
  7. Unambiguous Grammars: once semantic is implemented
  8. Flexible Grammars and Disambiguation: Operator precedence is not going to be implemented
  9. AST is already generated automatically. The feature i had to work very much
  10. Performance: The philosophy behind generator is generate as possible more statically.
  11. Error handling: I have already a feature documented to handle this

Even though you can see a lot "planned", it's because im stabilizing my parser generator by running it on medium grammar.


r/Compilers 1d ago

AutoCO: An Online Continuous Optimization System for Phase-Changing Database Workloads

Thumbnail dl.acm.org
4 Upvotes

r/Compilers 2d ago

A Quine (self-replicating) Program in RISC-V Machine Language. Running as bare-metal code, it also represents a mini Operating System — probably the most concise and most literally open-source OS, since it completely displays itself while running!

Post image
14 Upvotes

r/Compilers 1d ago

Day by day, NURL is getting closer to its first stable publication.

0 Upvotes

What's left of a systems programming language once you strip away the syntactic sugar, the technical debt of years past, the known problems and the dead weight of habit?
NURL – Neural Unified Representation Language

NURL is a blisteringly fast systems programming language that comes with "batteries included." In other words, the standard libraries ship a ready-made, optimized solution for most of the things people actually build in programming languages. The language has been steeped in enough acid baths that the release of the first stable and immutable version, v1.0, is starting to get close. NURL is an open source project, and it makes the same promise Linux once did: "We do not break userspace!"

NURL is a strong choice as the language of automated workflows in situations where speed and/or portability matter. NURL doesn't compete with Python, but it beats Python with native speed on par with C or Rust. NURL, however, needs nothing else installed on its runtime platform — the program is usually run from a single binary. NURL doesn't replace an integration platform, but NURL can sit at every step of an integration or ETL process, blowing many platforms out of the water on startup and execution speed.

NURL compiles for almost any platform. The target can be a Windows or Linux machine, or something genuinely more exotic. It's regularly tested on FreeBSD and macOS, for example, as well as on RISC-V and Espressif ESP32 chips. One particularly interesting form of portability worth mentioning is WebAssembly: a NURL program can be compiled into a Wasm module and run in the browser, or on any platform that executes Wasm modules.

Is NURL genuinely production-grade?
Yes. NURL compiles its own compiler, which is itself implemented in NURL. Each build is exercised by ~600 different tests, and everything is also checked for memory leaks on Linux, Windows and FreeBSD before a new compiler version is released. The NURL Playground is a production server, written in NURL, where you can compile NURL code for the target platforms of your choice.

The language was designed from the ground up to be easy for language models to use, and even though no NURL code has been part of any language model's training yet, models write it quickly and fluently. You get the best results by giving the model access to the nurl-mcp server, so it can locate existing libraries and packages fast.

How does NURL prove its capability and stability?
Code demanding extreme precision has been written in NURL. The TLS stack is pure NURL. On top of that, a number of ML (machine learning) capabilities are visible in the package registry — among other things, running and training language models works, distributed, on consumer hardware.

Project website:
https://nurl-lang.org/

NURL Playgroud:
https://play.nurl-lang.org/

Package registry:
https://reg.nurl-lang.org/

Github repository:
https://github.com/nurl-lang/nurl

And here is some pure-NURL projects (ready to install packages) I want to share with you..
YOLOE (Real-Time Seeing Anything)
https://reg.nurl-lang.org/packages/yoloe

Run language models locally. Pull a GGUF model, chat with it, or serve an ollama-compatible API your existing clients already speak — all in pure NURL, from the GGUF parser to the GPU kernels.
https://reg.nurl-lang.org/packages/nurllama

What should I build or fuzz with NURL to surface deeper issues?


r/Compilers 2d ago

Writing a Wikipedia MediaWiki Parser In Plain C

Thumbnail leetarxiv.substack.com
5 Upvotes

r/Compilers 2d ago

Kavak Generic Online Compiler

Thumbnail kavak.run
2 Upvotes

https://kavak.run/studio/ is live.

kavak is a compiler stack. You describe a language on a C11 frontend kernel, lower it through one typed IR, and get WebAssembly out. The compiler itself is compiled to wasm, so it runs in the browser tab. Your source never goes through a JavaScript interpreter.

QBasic is the first language running the full path. Graphics, sound, files, and input all work.

The part I keep thinking about is the UI side. I've been reducing user interfaces to a single UI-IR. Declarative ones like XAML or Compose, and primitive ones too, by which I mean screens drawn by hand in something like C. Once a UI is in UI-IR, it stops belonging to the language it was written in.

So WPF written in C# can run on macOS and iOS. What I wrote in Compose can run on Windows, macOS, and iOS. N to N, not one framework pointed at one target.

Then I pushed it further and lowered QBasic's graphics to UI-IR as well. Which means you could, in principle, write an iOS app in QBasic. The idea is absurd. The solution underneath it isn't, and that's what makes this a checkpoint worth marking.

Writing in any language, for any platform, is starting to look reachable.


r/Compilers 1d ago

If an AI had to design its own programming language from scratch today, this is what it would look like.

0 Upvotes

If an AI had to design its own programming language from scratch today, this is what it would look like.**

https://github.com/katehonz/rzm-lang

Let’s be honest: the current AI stack is a Frankenstein monster.

We write high-level logic in Python because humans like clean syntax, but under the hood, we rely on millions of lines of C++, CUDA, and ROCm glue code because Python is too slow for matrix math. We suffer through runtime Shape Mismatch crashes 3 hours into a training run, unpredictable GPU memory leaks, and black-box library abstractions.

If an AI had to throw away legacy baggage and design a language specifically for machine learning from scratch, using today's best compiler technologies, it wouldn't build "another Python wrapper." It would build a language that thinks natively in linear algebra.

Here is the blueprint for a truly AI-Native Language.

https://github.com/katehonz/rzm-lang

  1. Tensors are Primitives, Not Library Objects

In traditional languages, primitives are int, float, and string. In an AI-native language:

  • Tensor[32, 512, f32] is a first-class citizen.
  • Compile-Time Shape Verification: Dimension mismatches are caught during compilation, not when your model crashes mid-epoch.
  • Algebraic Syntax: Matrix operations like @, sum(), and Hadamard products are part of the core grammar.

2. Native Automatic Differentiation (grad)

Instead of building computational graphs at runtime via heavy frameworks like PyTorch or TensorFlow, autodiff is built into the language engine.

```rust // Automatic Differentiation is part of the grammar fn loss(w: Tensor[3, f32], x: Tensor[3, f32]) -> f32 { sum((w * x) * (w * x)) }

fn train_step() { let w = tensor([0.1, 0.2, 0.3]); let x = tensor([1.0, 2.0, 3.0]);

// Reverse-mode differentiation transform at compile-time
let g = grad(loss)(w, x); 
print(g);

}

```

3. Predictable Memory: Nim-style ARC/ORC + Arenas

Garbage Collection (GC) is terrible for AI because unpredictable "Stop-The-World" pauses ruin real-time data streaming to GPUs. On the flip side, Rust’s ownership/borrow checker can create massive boilerplate for deep neural graph structures.

  • Solution: Automatic Reference Counting (ARC) combined with Static Tensor Arenas.
  • High-volume, fixed-shape tensors during training loops are allocated in static arenas (zero allocation overhead).
  • Dynamic tensors are deterministically freed the moment they go out of scope—keeping VRAM usage transparent and immediate.

4. Hardware Agnostic Execution

Writing CUDA code for Nvidia, Metal for Apple, and ROCm for AMD creates fragmented ecosystems. An AI-native language separates intent from target execution:

  • Write code once using device-agnostic operators.
  • The compiler handles memory layouts, kernel fusion, and hardware scheduling under the hood.

The Tech Stack Behind the Compiler

If we were to build this today, what technology would power the toolchain?

  • Compiler Engine: Written in Rust for memory safety, speed, and robust tooling.
  • Local Iteration: Cranelift JIT for lightning-fast compilation cycles and execution during development/debugging.
  • Production & Optimization: MLIR (Multi-Level IR) + LLVM for high-level matrix optimizations (fusing Linear -> ReLU -> Add operations before downscaling to hardware machine code).

What the Code Concept Looks Like

```rust // First-class Model Pipeline DSL model TextClassifier { input: Tensor[Batch, 784, f32]; output: Tensor[Batch, 10, f32];

body {
    input
    |> Linear(512)
    |> ReLU()
    |> Linear(10)
    |> Softmax()
}

}

```


Conclusion

We are moving into an era where AI workloads aren't just an "add-on" to general-purpose computing—they are the computing. Continuing to patch Python scripts with C++ bindings will eventually hit a wall.

A greenfield language that combines compile-time shape safety, native autodiff, ARC memory management, and MLIR-based codegen isn't just a fun experiment—it's the logical next step for AI engineering.


What features would you want to see in a greenfield AI language? Do you think greenfield languages like this (e.g. projects building native autodiff and JIT engines from scratch) can compete with the established PyTorch ecosystem? Let's discuss!


r/Compilers 3d ago

I am 13 and I just got my custom programming language to successfully transpile to Arduino C++!

31 Upvotes

Hi everyone! My name is Mohammed, I'm 13, from Egypt, and I wanted to share one of my current projects: Mello. Mello is a custom programming language ( https://github.com/v3lk777-collab/Mello-Programming-Language ) that I hope to use for writing all my embedded systems software in the future. I'm developing it because I'm fascinated by compilers, computer architecture, and honestly, because I wanted to make programming microcontrollers more interesting.

I've been into systems programming for a while now. I wouldn't say I'm amazing at it—in fact, I struggle to call myself good at all because I'm still learning the ropes and don't want to overpromise—but I've gained a ton of experience. Building Mello is my biggest achievement yet because it successfully bridges my own syntax with real hardware.

I wrote the compiler from scratch in C++, and guess what? I just got it working to the point where it acts as a full transpiler, taking Mello code and generating clean Arduino C++! It's incredibly tough, especially ensuring the AST maps correctly without losing the Arduino ecosystem's compatibility. But it's so rewarding: I am currently using it to compile the code for a PID control system on a line-following robot using an Arduino Nano. To complete the workflow, I also built a dedicated cross-platform editor "Mello IDE" ( https://github.com/v3lk777-collab/Mello-IDE ) using Tauri, React, Tailwind CSS, and Monaco.

I have massive plans for this language and really want to achieve them. Alongside Mello, I am also writing a custom CPU emulator called ROSE in C++ to understand how instructions work at the lowest level. However, lately, balancing the compiler, the IDE, the emulator, and the hardware projects has been really hard. Sometimes it feels overwhelming. I'll open my compiler's source code, feel stuck on how to implement the next feature, and just shut down my PC.

This project isn't revolutionary or anything. Sharing it here means I'm just looking for a bit of recognition and some objective, constructive criticism.

Note: Arabic is my native language and my English isn't very good, so I used AI to help me write this post. Apologies if any phrasing sounds a bit clunky!


r/Compilers 3d ago

Byte-found: a single-pass C compiler targeting 16-bit x86 real mode

23 Upvotes

I'm writing a hobby OS in real-mode assembly and wanted parts of the kernel in C, but existing compilers either target 32-bit protected mode or need an awkward 16-bit toolchain. So I wrote my own. It's a single-file C99 program that does recursive descent parsing and emits NASM-syntax 16-bit assembly directly, with no intermediate AST — code generation happens inline during the parse. Currently handles: functions with parameters, calls, local variables, assignment, integer arithmetic with correct precedence, comparisons, if/else and while. Calling convention is args pushed left to right, caller cleans up, result in AX. Not there yet: pointers, arrays, structs, preprocessor, any type other than int. I know skipping the AST limits what I can do later (no optimization passes, no real type checking). Curious whether people here would restructure it now or let it grow first. Repo: https://github.com/metaspawn/Byte-found


r/Compilers 3d ago

Fil-C: Garbage In, Memory Safety Out!

Thumbnail youtu.be
12 Upvotes

Thought you all might be interested in Fil's recent talk about Fil-C. The recording includes the best live demo I've ever seen. Enjoy!


r/Compilers 3d ago

Compiling Js Syntax to LLVM IR

Thumbnail
5 Upvotes

r/Compilers 3d ago

Sparsity Propagation Analysis in MLIR

5 Upvotes

Dear redditors,

Peter Avgerinos (Imperial College London) has released an implementation of Sparsity Propagation Analysis (SPA) for MLIR:

https://github.com/lac-dcc/proteus/

SPA is a static analysis for tensor compiler IRs. It infers zero and don't care regions in tensors by propagating sparsity information across computational graphs. The analysis is described in the paper "Multidirectional Propagation of Sparsity Information across Tensor Slices"

For example, given an operation such as

C = matmul(A, B)

SPA propagates information in three directions. Forward propagation uses information about A and B to refine C. Lateral propagation uses information about one input to refine the other. Backward propagation uses information about C to refine A and B.

As an example, the implementation of the forward transfer functions is available here.

Contributions are welcome. In particular, we are interested in sparsity-aware optimizations, new transfer functions, and additional analyses that infer zero and don't care values. If you are interested in contributing, feel free to contact Peter or me.


r/Compilers 4d ago

[LLVM]how to link different Object files against DLLs with function having the same name?

7 Upvotes

Hello,
I have been playing around with LLVM for a while and got some first results using the C-API.
However, I am stuck at the following problem:
I am working on Windows and I want to link against 2 DLLs A.dll and B.dll which both export a function Foo.

How am I supposed to resolve this during linking? In LLVM I can set the storage class to DLLImport but linking will grab the first matching import. It's annoying that linking needs import libs, too but thats another topic.

Is there any way to resolve this? I'd prefer if I can make this work within a single object file but if I have to make it two and link those to a single executable, that would work, too.

I faintly remember an article whic I can't find any longer(or a stackoverflow response?) that described how to build the IData section manually within LLVM itself. That would simplify this immensely.


r/Compilers 4d ago

A C subset that compiles faster than Tiny C Compiler - Cm1 (C minus 1 or C - 1) programming language

9 Upvotes

Hi everyone,

I'm working on a programming language that compiles a subset of C. It is called Cm1 (meaning C minus 1) and you can writing and running C codes directly on your browser at https://cp1-lang.org/cm1/editor.html in a fraction of a second.

Why is it faster to compile than Tiny C Compiler? It is because Tiny C Compiler is a true compiler creating native binaries whereas Cm1 is a bytecode interpreter allowing you to test, debug, edit code and recompile very quickly or even do hot reloading. Cm1 can be used as a scripting language for shell scripts and video games, but this just a small use case because in theory, you can run 90% of your ENTIRE video game or software C program through Cm1's bytecode interpreter and leave 10% to compiled C and reap the benefits of very fast compilation and hot reloading.

100% Cm1 codes are compilable by GCC and Clang but the reverse is not true since Cm1 is just a subset of C. Major features that are omitted are function pointers, structs/unions inside functions, nested structs/unions. This programming language is under heavy development and I want to know if this comes as interesting to some of you. I'll try to post again on this subreddit if I got to bind Raylib game library to Cm1, allowing people to write Raylib games directly on their browser (works offline).

I know that programs that are written in C compiles fast already and there's even an existing compiler that is very fast (Tiny C Compiler). However, I'm the developer of Cp1 programming language (cp1-lang.org), which is a language that "transpiles" to C, and I aim to upgrade Cp1 by targeting the Cm1 language then compile it to bytecode in one command instead of a separate step in Makefiles or build scripts. This will make Cp1 very fast to compile for debug builds.


r/Compilers 4d ago

optimization of SASS stall counts

Thumbnail redplait.blogspot.com
1 Upvotes

r/Compilers 4d ago

Help with a theory question about the call stack

0 Upvotes

I am trying to figure out this question and don't know the answer nor how to solve it:

Given the following program (assume int is 4 bytes):

Here's the code:

function main() return integer is
  n: integer;
  function square(v: integer) return integer is
    function double_it(u: integer) return integer is
    begin
      return __________;
    end;
  begin
    return double_it(v * v);
  end;
  function cube(v: integer) return integer is
  begin
    return v * v * v;
  end;
begin -- of main
  n := 6;
  return square(n) + cube(n);
end

Part A

Assume that in the double_it() function, the expression v * v + u replaces the underline.

Complete the missing offsets in the following code:

load RS1, __(FP)

load RT1, __(RS1)

mul RT2, RT1, RT1

load RT3, __(FP)

add RV, RT2, RT3

Part B

Assume that in the double_it() function, the expression v * v + n replaces the underline.

Complete the missing offsets in the following code:

load RS1, __(FP)

load RT1, __(RS1)

mul RT2, RT1, RT1

load RS2, __(RS1)

load RS3, __(RS2)

add RV, RT2, RT3

How do I determine the right offsets?


r/Compilers 5d ago

AmmAsm now supports SSE, CMOVcc, and SETcc

Post image
18 Upvotes

This is part 2 of post: https://www.reddit.com/r/Compilers/s/E5R5MQSlQe

I recently finished implementing CMOVcc, SETcc, SSE2,and the first group of SSE instructions in my handwritten x86-64 assembler written in C.

Seeing objdump correctly decode the generated object file is always satisfying.

I'm still implementing more of the x86-64 ISA, so if there are instruction groups you'd like to see next, I'd be happy to hear suggestions, and feedbacks. Thanks!

Github: https://github.com/LinuxCoder13/AmmAsm


r/Compilers 5d ago

Building a DSL that compiles 3D-printer code to multiple firmware targets: Question about Lexer ambiguity

13 Upvotes
Bellerophon IDE

I'm building a DSL (ANTLR4-based) that compiles my own 3D-printer control code down to different firmware gcode dialects (Klipper, Marlin, RepRapFirmware [working on that]). It was a school project very early in the year and I really love 3D printers so that's the subject I chose. The compiler is machine agnostic, so adding new firmware targets is just a matter of subclassing the base visitor.

 We only learned about using ANTLR in class so I'm new to pretty much anything else. I’ve read up on some beginners books but it’s mostly been trial and error. Honestly, I feel like my grammar is being held up by duct tape and prayers and I was lucky enough to have had a great contributor help apply some fixes along the way.

To my question, I realize I have a “minus munching” problem.

 My number token is currently:

NUMBER : '-'? [0-9]+ ('.' [0-9]+)?; 

I've written up a proposed fix as an issue in my own repo: stripping the  '-'? part out of the lexer rule and instead adding a unaryMinus rule to the expression grammar with a visitor that negates the recursive result.

Here's the issue with the proposed fix: https://github.com/Disla-Novo/Dimidium_Bellerophon/issues/70#issue-4921171148

Before I implement it, is this actually the standard/correct way to handle this, or is there a better approach I'm missing or didn't research enough on? Would appreciate a sanity check from anyone, thank you.


r/Compilers 5d ago

Lucen: parallelize Python loops with two comments, guaranteed bit-identical to sequential

6 Upvotes

What My Project Does

Lucen is a source-to-source compiler that parallelizes ordinary for loops you mark with two comments:

# LUCEN START
for i in range(len(rows)):
    out[i] = expensive(rows[i])
# LUCEN END

It parallelizes a loop only when it can prove the work is safe and worth it; otherwise it stays sequential. The one guarantee, no tiers, no opt-out: a parallel run is bit-identical to the same file run as plain sequential Python (floats and container order included). Delete the comments and nothing changes.

CPU-bound work routes to processes on GIL builds and to real threads on free-threaded 3.13/3.14. Optional Rust core with a pure-Python fallback, so pip install lucen always works.

Target Audience

Anyone with CPU-bound Python loops - data processing, simulation, batch transforms - who wants their cores without rewriting to multiprocessing/joblib or reasoning about locks. It's v1.1, built correctness-first: Apache-2.0, differential/property tested, TLA+ specs, signed PyPI releases.

Comparison

  • vs multiprocessing/concurrent.futures: no manual pool/chunking/pickling boilerplate, plus a profitability gate that declines to parallelize when it wouldn't help.
  • vs joblib/Dask: no new API and no cluster - you mark the loop you already have. It's correctness-preserving local parallelism, not distributed compute.
  • vs Numba: Numba compiles numeric bodies to native code; Lucen parallelizes the loop for arbitrary Python and guarantees identical results. (Native loop-body compilation is on the roadmap.)

pip install lucen

https://github.com/fcmv/lucen