Nelua

Core

The compiler

Upstream Nelua, tracked closely, plus the pieces a self-hosted libc and freestanding targets asked for.

Spaceghost/nelua is a fork of edubart/nelua-lang at commit a584505 (2025-06-24). Each addition lands with specs in spec/ and a section in the docs, and compiles to ordinary C. Under pragmas.nogc, generated string and container operations use normal allocator rules; pragmas.freestanding continues to reject heap-dependent operations. The guide What this fork adds walks through each one with examples.

Upstream base a584505 · 2025-06-24609 specs passed · 2026-11-21Fork revision 874acdd

necc packages this frontend with a standalone Linux toolchain.

Release compilation and generated programs

On 21 November 2026 the fork at 874acdd and upstream at a584505 used the same input files and GCC backend. The compile interval includes C generation, compilation and linking. The execution interval starts with a fresh process.

WorkloadFork (ms)Upstream (ms)
Hello world · compile134.50113.56
Hello world · run0.770.78
Matrix multiplication · compile1109.311158.70
Matrix multiplication · run29.6229.73

Each median covers seven alternating rounds after warm-up. Both generated matrix programs printed −18.8963499125. The hello-world compile took longer in the fork while the matrix compile finished sooner. The runtime distributions overlapped.

Frontend compile times

On , the two biggest differences came from syntax checking and source-location lookups. A syntax-only invocation can skip the built-in code generator and analyzer. During C generation, the compiler now indexes source line breaks once per file so repeated runtime diagnostics can find their source locations cheaply.

Workload5995eba (ms)874acdd (ms)Old / new
Check syntax · extension tour38.1623.901.60×
Emit C · hello world29.4729.301.01×
Emit C · matrix multiplication131.19130.631.00×
Emit C · standard library test suite1,383.741,379.741.00×
Emit C · 2,048 runtime assertions (synthetic)282.06146.391.93×

Each median covers 30 alternating pairs in two batches on one Intel Core i7-11700F logical CPU under Debian 12. A fresh process parsed the input and either exited after the syntax check or wrote C. All four C workloads produced byte-identical output across the two revisions. The 2,048-assertion fixture compiled 1.93× as fast. Hello world, matrix multiplication and the standard library suite moved by less than 1% in the pooled medians.

What the fork adds

Everything below is opt-in syntax or tooling. Code written for upstream Nelua compiles unchanged. The first five are language features that fit together: variants and optionals carry "one of these" data, match takes it apart safely, ownership keeps resources from being released twice, and closures let the standard algorithms take a function.

Variants

One value out of a fixed list of types, with a tag that remembers which. Written variant(A, B) or A|B through require 'variant'. A variant is a plain record (a uint8 tag and a C union), so it lives in arrays and other records and costs no allocation.

require 'variant'
local Token = @variant(integer, string, boolean)
local t: Token = 42
print(t == 42, t:is(integer))   -- true  true
t = 'end'
print(t:get(string))            -- end

guide overview

Optionals

A value or nothing: T? or optional(T) through require 'optional'. orelse unwraps with a lazily evaluated default, if local x = e then tests and binds in one step, and the postfix ? turns an empty optional, a null pointer or a stdlib (value, errmsg) failure into an early return. *T? stays the size of a pointer.

require 'optional'
require 'io'
local function find(k: integer): integer?
  if k == 1 then return 10 end
  return nil
end
local a = find(1) orelse 0          -- 10
if local x = find(2) then print(x) end
local function open_all(p: string): integer?
  local f = io.open(p)?             -- returns empty on failure
  return 1
end

guide overview

match

Dispatch on the held type of a variant or an optional. Without else every member and nil must be covered, so adding a member to a variant turns every unfinished match into a compile error that lists what is missing. case local x: T binds a copy, case local x: *T a reference into the subject, which is matched in place. The whole statement is lowered at compile time to one C switch on the tag: no runtime code, no call, no allocation.

local Shape = @variant(integer, string)
local shapes: [2]Shape = {7, 'square'}
match shapes[0] do
case local r: *integer then $r = $r * 2   -- writes into shapes[0]
case local name: string then print(name)
case nil then print('empty')
end

guide overview

Owned records and move

A record that releases something in __close can be marked <owned>. Its values are then affine: copying an lvalue needs the move builtin (which zeroes the source), a moved variable cannot be read until it is assigned again, and the check follows the control flow through branches, loops and early exits. Records with owned fields and arrays of owned values are owned implicitly; pointers never move. vector, sequence and hashmap of owned values own their elements: values move in and out, and whatever the container drops (clear, remove/erase, a shrinking resize, destroy) is closed. Everything is checked at compile time and costs nothing at run time.

local Buf <owned> = @record{data: pointer, size: usize}
local a = Buf.create(16)
local c = move(a)   -- `a` is zeroed; reading it now is an error
a = Buf.create(8)   -- live again
inspect(&a)         -- lending a pointer is not a move

guide overview

Closures

Anonymous and nested functions can capture the enclosing locals. The compiler turns the function into a closure record holding a copy of each captured variable and a __call metamethod, so the value is a plain record that works without the GC and can be returned or stored. Annotate it <byref> to capture pointers instead and mutate the enclosing variables; such a closure must not outlive its frame.

local function make_adder(n: integer)
  return function(x: integer): integer return x + n end
end
print(make_adder(2)(1))   -- 3

local total = 0
local function add(v: integer) <byref> total = total + v end
add(4) add(6)             -- total == 10

guide overview

Compile-time evaluation

comptime(f(args)) runs an ordinary Nelua function inside the compiler and folds its result into the program: scalars, strings, and arrays or records as C static initializers. Named <comptime> record configs can be reused across calls, including nested records and arrays. A function marked <comptime> is evaluated at every call and never emitted to C. The sandbox keeps C semantics (integer widths, unsigned division, float32 rounding) and is bounded in steps and depth; it does not execute target memory or perform I/O.

local function crc32_table(): [256]uint32
  local t: [256]uint32
  for i: uint32 = 0, 255 do
    local c: uint32 = i
    for _ = 1, 8 do
      if c & 1 == 1 then c = 0xEDB88320 ~ (c >> 1) else c = c >> 1 end
    end
    t[i] = c
  end
  return t
end
local CRC = comptime(crc32_table())   -- a static table in the C output
print(CRC[1])                         -- 1996959894

full guide compiler docs overview

Syntax extensions

A top-level #syntax directive extends the grammar for the rest of its file. Builders turn each form into ordinary Nelua before type checking. The opt-in library now includes control flow, lazy conditional expressions, concise functions and closures, destructuring, scoped resources, typed vector comprehensions, grouped numbers, byte strings and alternative operators, alongside compound assignment, pipes and interpolation. Load individual modules or the complete syntax.all pack; use syntax.use to compose your own reusable packs.

#syntax 'syntax.all'
require 'string'
require 'vector'

local double = fn(x: integer) => x * 2
let [first, _, third] = (@[3]integer){10, 20, 30}
local total = 0
times 3 as i do total += i end
local label = choose total == 6 then 'ready' else 'waiting' end
print($"{label}: {total |> double}, {first + third}") -- ready: 12, 40

using squares = collect(integer; i = 1, 8 when i % 2 == 0 => i * i) do
  print(squares[0], squares[3])                      -- 4, 64
end

Each extension remains file-scoped and keeps normal type, ownership and lifetime checks. The full guide covers every module, evaluation rules, precedence, templates, diagnostics and the builder API, with a runnable tour.

full guide embed Bend2 compiler docs runnable tour

Const pointers

*const T maps to C const T*. Reads through it are read-only, *T converts to it implicitly, and dropping const needs an explicit cast. It is what most C APIs take, so nelibc and generated bindings can state their intent and have the compiler check it.

guide

pragmas.freestanding

A compiler-enforced runtime-free profile. It implies nogc and noentrypoint, traps on abort, and rejects heap, process, stdio and main symbols at compile time. nelibc's host profile and Drift's kernel drivers build on it; the guarantee is in the emitted C and the linked symbols, not in a convention.

The neboot loader uses this profile to export efi_main and describe firmware tables as Nelua records. It marks the entry point and the protocol function pointer types with ms_abi so the generated C preserves the x86-64 UEFI calling convention.

neboot walkthrough runtime-free guide

--target <triple>

Cross compile with clang or zig cc. The triple reaches the type-size probe, the cache hash and the compile, so a build for another architecture never reuses the host's cached sizes.

tools/nelua-bindgen

Generates <cimport> bindings from C headers with libclang: integer, pointer, array, struct, union, enum and function types, const kept as *const T, string and numeric macros as constants, opaque and forward-declared structs. --match/--exclude select symbols, --opaque and --enum-using shape types, --nullable-returns REGEX wraps pointer-returning functions in *T?, and a JSON --config prepends or appends hand-written text.

tool README

Libraries from nelua-batteries

algorithm (introsort, heapsort, removeif, packn/unpackn), heapqueue (an owned binary-heap priority queue) and tuple were brought over from edubart/nelua-batteries and adapted to the fork's rules: no hidden copies of owned values, *const where nothing is written.

library reference

Toolchain and editor support

Tree-sitter and TextMate grammars under tools/ (the Tree-sitter scanner is itself written in Nelua) know every addition above: *const T, A|B, T?, expr?, orelse, if local, anonymous function expressions and match. A compact C codegen profile for distributable output, and a binary cache that also hashes imported C sources so a changed header rebuilds.

Install

Nelua needs Git, a C compiler and make. The fork builds the same way upstream does.

git clone https://github.com/Spaceghost/nelua
cd nelua
make
sudo make install   # or: make install PREFIX=$HOME/.local
nelua --version

Pinning: the nelibc gate and nebox's container builds run the fork at dabbd9ef. nelibc and nebox compile with upstream-compatible syntax plus const pointers; the newer additions are available to them but not yet required.

How changes are gated

Specs
make test runs upstream's spec suite plus the fork's specs (const pointers, freestanding, target, bindgen, variant, optional, match, ownership, closures, the batteries libraries, comptime). All 609 specs passed on 21 November 2026 at fork revision 874acdd using Clang 23 and Bend 2.0.40.
Examples
Every example in the fork guide was compiled and run with the checkout it documents and prints what its comments say.
Consumers
nelibc's smoke matrix and nebox's conformance suite are rebuilt against the fresh compiler in a pinned container before the pin moves.
Runtime-free audits
A standalone GCC and Clang workflow links the freestanding examples and checks the emitted symbols: no allocator, no GC, no entry point.
Upstream
The fork rebases rather than diverges; language additions are kept small enough to offer upstream.