8000 GitHub - r-lyeh/C2: Small yet fast embeddable C compiler, with extras. · GitHub
[go: up one dir, main page]

Skip to content
r-lyehPublic

About

Small yet fast embeddable C compiler, with extras.

Resources

Stars

9 stars

Watchers

2 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

C²

I have always needed a C library that could compile C scripts on the fly; primarily for use within game scripts.

In this repository, I am experimenting with something similar to stb_compiler.h. It is capable of parsing a significant amount of C code, includes a preprocessor, is sufficiently fast and compact, and relies on external dependencies for code generation and JIT compilation; making its source code essentially platform-independent.

TinyCC is probably the closest existing solution, but it is not quite what I was looking for; hence the creation of this repository.

While I was at it, I also added another optional language on top of the C compiler. You can use C at any time, or use C², which stays closer to C than C++ while adding objects, reflection, serialization, function overloading, struct operators, and more. See LANGUAGE.md for details.

Platforms

C² runs wherever MIR's JIT generates code. Currently:

Target (MIR backend) OS Status
x86-64 Windows tested
x86-64 Linux tested
x86-64 macOS should work (same SysV ABI as Linux), untested
ARM64 macOS (Apple Silicon) tested
ARM64 Linux its va_list layout and __aarch64__ are in, untested
ppc64le Linux needs its va_list layout and predefined macros
s390x Linux needs its va_list layout, predefined macros and big-endian __BYTE_ORDER__
riscv64 Linux needs its va_list layout and predefined macros

Not MIR targets: 32-bit CPUs, Windows on ARM64, WebAssembly. (C² assumes 64-bit pointers.)

Without JIT

Some platforms (iOS, game consoles) don't let a program generate machine code. Two fallbacks:

  • Interpreter (c2 -i, C2_use_interpreter): no optimizing generator, quicker to start, roughly 10x slower to run. MIR still creates a few small call stubs, so this is for platforms where MIR's generator is missing or startup matters, not for ones that forbid generated code entirely.
  • C output (c2 -C script.c > script_gen.c, plus c2 -Crt > c2_rt.c once): portable C to build with the platform's own compiler. Script functions and globals keep their names; call c2_init() before using them (it runs global initializers); a script main becomes the program's main. Run c2 on a machine with the target's ABI (same CPU family and OS conventions): struct passing and va_list follow the ABI c2 was built for. Compiled with gcc -O2, the C output runs between 1.5x slower and 2x faster than the JIT, depending on the program. The runtime it needs is one function, c2_rt(name), from either of two places: c2_rt.c (c2 -Crt, about 90 KB in the program) for a program without C² in it, or C² itself built as a library (C2_NO_MAIN): a game that embeds C² can compile its scripts ahead of time and link them in with nothing else (tests/c2-abi/aot_lib.c shows the build; the c2-abi suite runs it). c2 -C -prefix ui_ ui.c2 renames what the file defines to ui_... (ui_init, ui_main, and no C main), so several scripts, each with its own copy of the runtime parts it uses, link into one program.

Usage

c2                        a REPL, as python's or lua's: declarations stay, statements run, an expression shows its value
c2 file.c [args...]       compile, JIT and run main(argc, argv); its result is the exit code
c2 -S file.c              print MIR text instead of running
c2 -E file.c              print the preprocessed source
c2 -i file.c [args...]    the same with MIR's interpreter (no machine-code generator)
c2 -C file.c > out.c      translate to C (no JIT at all); compile it with c2_rt.c (c2 -Crt, or -Cruntime)
c2 -C -prefix ui_ ui.c2   the same, with what it defines named ui_... (ui_init, ui_main): scripts link together
c2 -O0..-O3 file.c        MIR optimization level (default -O2; lower compiles faster)
c2 -eager file.c          generate every function's code before main (the default: each at its first call)
c2 -noruntime file.c2     a .c2 program without the runtime (which it otherwise gets without #import)
c2 -g file.c              keep a script call stack: a crash prints where each function was
c2 -sandbox file.c        no deleting, renaming or writing files, starting programs or loading libraries
c2 -det file.c            deterministic: the same results on every machine (math functions, division by 0, float to int)
c2 -T / -A file.c         debug: run through the MIR text path / print what the C API built
options: -Idir, -Dname[=value]

Embedding (c2.h)

#include "c2.h"
typedef struct { float x, y, z; } Vec3;
Vec3 vec3_add(Vec3 a, Vec3 b);                       /* a host function */

C2 *c2 = C2_new();
C2_declare(c2, "typedef struct { float x, y, z; } Vec3;");          /* types every script sees */
C2_add_function(c2, "Vec3 vec3_add(Vec3 a, Vec3 b);", (void *)vec3_add);   /* scripts just call it */
C2_add_variable(c2, "int score;", &score);                              /* ...and use score */
const char *err = C2_compile_file(c2, "game.c");  /* "" on success, else the errors */
if (*err) puts(err);
Vec3 (*update)(float) = (Vec3 (*)(float))C2_get(c2, "update");
update(dt);
C2_compile_file(c2, "game.c");                      /* hot reload; on error the old code stays */
C2_load(c2, "sdl.h", "SDL2");                       /* bind a C library: header + SDL2.dll/.so/.dylib */
C2_delete(c2);
  • Compile c2.c with C2_NO_MAIN into your program and link 3rd/mir.c and 3rd/mir-gen.c (MIR).
  • Host functions and variables, hot reload keeping state, C libraries, a sandbox, call stacks, surviving a script's crash (C2_guard), the interpreter: EMBEDDING.md has all of it, c2.h the details.

Features

  • .c files are compiled as C; .c2 files also get the C² additions.
  • C² compiles most of C89, C95, C99, C11, and a few C23/C2Y features; listed as follows.

Supported C

8000
  • C89: types: char, short, int, long (signed and unsigned), float, double, void, enum, pointers, function pointers, multi-dimensional arrays
  • C89: struct / union: by value, nested, bit-fields; typedef; const, volatile; static, extern, register
  • C89: every operator, with C precedence; if, switch (jump tables when dense), for, while, do, break, continue, goto, return; variadic functions; static locals; recursion
  • C89: multi-character constants, up to 4 characters, packed in source order on every target: '12' == 0x3132, '1234' == 0x31323334
  • C89: trigraphs (??= is #...) in .c files; .c2 files follow C23, which removed them
  • C89: K&R function definitions (int max(a, b) int a, b; { ... }; undeclared parameters are int)
  • C89: wide literals L"..." / L'x' and wchar_t (as in the host C library: 32-bit elsewhere, 16-bit UTF-16 on Windows); wchar.h: the wcs* / wmem* string functions and wcstod/wcstoll/wcstoull
  • C89: implicit int (static x;) and implicit function declarations (they return int: wrong for anything returning a pointer, long or double, so include the header)
  • C89: preprocessor: _Pragma("...") (C99) and digraphs <: :> <% %> %: %:%: (C95); #define (object- and function-like, #, ##), #undef, #if / #ifdef / #ifndef / #elif / #else / #endif with defined(), #include ("file" next to the includer, then -I dirs; <file>: the C standard's headers are C²'s own, any other is read from -I, CPATH / C_INCLUDE_PATH (INCLUDE on Windows) and the system's folders, so a library's real header works: <SDL3/SDL.h>, <zlib.h>; its static inline functions are compiled only when called), #error, #line, #pragma (once; others ignored), __FILE__, __LINE__, __DATE__, __TIME__
  • C89: headers, built in and mapped directly onto the host C runtime: assert ctype errno float limits locale math signal stdarg stddef stdio stdlib string time, and the multibyte functions (mblen mbtowc wctomb mbstowcs wcstombs). malloc/free are the host's own, so memory passes freely between host and scripts.
  • C99: long long, _Bool (stdbool.h), inline, restrict, // comments, __func__
  • C99: declarations anywhere, including in for (int i = 0; ...)
  • C99: designated initializers, compound literals, flexible array members
  • C99: variable-length arrays (outermost dimension); hex floats; \u / \U escapes in strings (UTF-8)
  • C99: variadic macros (__VA_ARGS__)
  • C99: headers: stdbool stdint inttypes; snprintf, isnan/isinf/isfinite/fpclassify and the math.h float variants (sinhf, lrintf, fmaf...)
  • C11: _Static_assert, _Generic, _Alignof, _Noreturn (stdnoreturn.h), stdalign.h
  • C11: _Alignas on struct members (accepted on variables, but ignored there)
  • C11: anonymous struct / union members; u8"..." strings
  • C11: _Thread_local is accepted, with one copy (scripts are single-threaded)
  • C23: preprocessor: #embed (with limit, prefix, suffix, if_empty), __has_include(), __has_embed(), #warning
  • C23: digit separators (1'000'000), binary literals (0b101)
  • C23: bool / true / false as keywords; #elifdef / #elifndef; __VA_OPT__
  • C23: enums with a fixed underlying type (enum E : unsigned char), and enums with values beyond int (their type is the first of unsigned, long long that fits them all)
  • C23: constexpr (an integer one is a named constant, usable in array sizes and case labels); [[attributes]]: [[nodiscard]] (warns when a call's result is thrown away) and [[deprecated("why")]] (warns at each call) work; the others are accepted and ignored, since C² has no warnings for them to silence; several can share one list, as C23 allows: [[export, operator+=]]; alignas / alignof / thread_local as keywords
  • C23: typeof / typeof_unqual (also __typeof__), auto x = expr; type inference, u8'x' character literals (unsigned char)
  • C23: nullptr, static_assert (message optional), empty initializers (= {}), unnamed parameters in definitions, labels before declarations
  • C2y: _Countof(array) (countof with <stdcountof.h>): the element count of an array (a pointer is an error; a variable-length array's is computed at run time)
  • defer TS (ISO/IEC TS 25755): _Defer stmt; (defer with <stddefer.h>) runs stmt when its block is left (closing brace, return, break, continue), latest first; the return value is taken before. Not supported in functions with goto/labels; no jumps out of a deferred statement.
  • GNU: statement expressions ({ int t = f(); t * t; }), the value of the last expression statement
  • GNU/clang: __builtin_add_overflow / _sub_ / _mul_ (exact result, 1 if it doesn't fit the result's type); in #if, __has_builtin, __has_attribute, __has_c_attribute (what C² supports), __has_feature / __has_extension (0)

Missing from standard C

  • C89: long double as its own type (it is double; 1.0L is a double)
  • C89: setjmp.h: setjmp / longjmp
  • C89: locale.h: only setlocale and the LC_* constants (no localeconv)
  • C95: wide character I/O and classification (wprintf, fgetws, wctype.h...); printf("%ls") works
  • C99: _Complex / _Imaginary; headers complex.h fenv.h tgmath.h wctype.h
  • C99: pointers to variable-length arrays (int (*p)[n]); only the outermost dimension may be variable
  • C99: non-ASCII identifiers (UCNs or UTF-8 in names)
  • C11: aligned_alloc
  • C11: _Atomic (stdatomic.h), threads.h
  • C11: u"..." (16-bit), U"..." (32-bit), uchar.h
  • C23: _BitInt; taking the address of an integer constexpr
  • C23: char8_t

Differences from standard C

  • Reading a local before setting it warns in .c files ('var' is used uninitialized).
  • Multi-character constants pack their characters deterministically, in source order: '12' == 0x3132, '1234' == 0x31323334.
  • Self tail calls (return f(...); inside f) become loops, so tail recursion of any depth runs in constant stack. When that can't be done (a local's address is taken, a variable-length array is in scope, ..., struct parameters or results) the call stays recursive and a warning says why. With hooks (below) every call stays a call. [[musttail]] return f(...); turns that warning into an error.
  • long is 64-bit on every platform, Windows included. On Windows, literal formats given to the printf / scanf families are fixed while compiling (%ld becomes %lld), so %ld works everywhere.
  • Bit-fields use gcc's layout on every platform. After #pragma ms_struct on (as in gcc and clang), structs get MSVC's layout, for sharing them with MSVC-built code; headers mounted with C2_load get it automatically on Windows.
  • Structs passed through ... to C functions (printf("%g", s)) follow the platform ABI.
  • The printf family (printf fprintf sprintf snprintf and their v forms) is stb_sprintf's, so a program prints the same on every platform: %p is 16 hex digits without 0x, %'d groups thousands, and the last digit of %g/%e may round differently from glibc's. Wide text (%ls, %lc) goes to the system's. c2 -Crt output does the same when stb_sprintf.h is on its include path. Build with -DC2_NO_STB_SPRINTF for the system's.
  • Hooks: when a script defines void __on_enter(const char *func, const char *file, int line) and/or __on_leave(...) (or the host provides them with C2_add_symbol), every other function calls them on entry and before each return: profilers, script call stacks, tracing. Without them nothing is emitted.
  • Extra: <dlfcn.h> on Windows too (LoadLibrary/GetProcAddress); strdup in <string.h>.
  • On Windows, by-value structs of 3, 5, 6 or 7 bytes to/from external functions are not supported (MIR passes them in a register, MSVC by reference).
  • One translation unit per compile: no object files, no linking of several .c files, no debug info, no inline assembly. Native executables only through c2 -C and another C compiler.

New C² additions (.c2 files)

The C² language, with examples, is in LANGUAGE.md, and one feature per file in tour/ (execute make tour to visualize all of them). In short:

  • C made convenient: the common headers always included, f() meaning f(void), i32-style type names, struct names as types, . on pointers, zeroed locals ([[unclear]] to opt out), [[unroll]] loops, 8-character constants, countof, exact array parameters (int v[3]), defer, nested functions, if (auto *x = get()), int(3.9) casts, trailing commas in calls, one loop for everything: for (int i : 0..n), for (u32 c : text), for (Item *it : bag), for (auto *e : map).
  • Functions and types: default and named arguments, methods (x.f(), 21.twice(), T_f()), constructors (vec3(1, z: 3)), overloading (by the first parameter, or by all of them), operators ([[operator+]]; 2 * v finds v * 2), one call per argument (free(a, b ... ), f(a, b ... x)), [[tail]] calls, const N = 100; constants (constexpr auto), [[weak]] defaults a program replaces (name.weak() calls the default).
  • Owning values: [[destructor]], [[copy]], temporaries freed at the end of their statement, and structs that own things (strings, arrays, maps...) getting both member by member.
  • Programs: modules (#import, [[export]]), macros that stay in their header, several main()s (modules' first: their initialization), try / throw, call stacks with c2 -g and stacktrace(), unit tests (#import "runtime/unittest": suite(), test(), test_eq()).
  • C libraries without bindings (FFI): a library's own header (#include <SDL3/SDL.h>, or a few declarations of your own) and #import "SDL3" (or #pragma comment(lib, "SDL3"), in .c files too); the calls are plain C calls, resolved when the script is linked: no wrapper, no build step.
  • The runtime (in every .c2 file, -noruntime to leave it out): string with operators and f-strings (f"{hp:.1f} hp"), array(T), map(K, V), set(K), coroutines, try/throw, x.hash() on any value, and reflection: reflect(T) describes any type (fields, offsets, enum names), and every value has methods: x.print(), x.text(), f"{hero}" a whole struct, x.save(path) / x.load(path) / x.json5() / x.xml() (JSON5, or XML for .xml); [[skip]] leaves a field or a type out, [[name("hp")]] saves a field under another name. JSON5 and XML documents, read by path (doc.open(path)). global("hero.hp") reaches a global's part by name (consoles, editors; C2_reflected for the host), x.find("pos.x") a value's; [[clamp(0, 100)]], [[clamp(16)]] and [[comment("...")]] say what a field accepts. eval("heal(hero, 20)") calls a function by name (defaults, named arguments, hero.hit(30)); foreach_field(T, X) is a compile-time loop over a struct's fields.

See IDEAS.md for the plans and CHANGELOG.md for what changed.

C, C² and C++

C² sits between the two: C's model (plain structs, pointers, no hidden calls but the ones you declare) with a handful of C++'s and newer languages' conveniences, and a runtime. This table is meant to be honest both ways: what C² adds to C, and what C++ has that C² doesn't.

Feature C C² C++
Types and generic code
_Generic selection ✔️11 ✔️ ❌ (overloading)
templates / generics ❌ ❌ (macros, typeof; containers are built in) ✔️98, concepts 20
auto, constexpr variables, nullptr, typeof ✔️23 ✔️ (and const N = 100;) ✔️11 (decltype)
constexpr / consteval functions ❌ ❌ ✔️11 / 20
references (int &r) ❌ ≈ . on a pointer reads as one (p.x, p.f()), and x.f() passes &x ✔️98
move semantics ❌ partly: a stored container moves, pop() moves out ✔️11
long double, _Complex, _BitInt, _Atomic ✔️ ❌ (long double is double) ✔️ (std::complex, std::atomic)
struct names as types (no typedef) ❌ ✔️ ✔️98
enums with a fixed type, enum Dir : u8 ✔️23 ✔️ (and the name as a type) ✔️11 (enum class scoped)
binary literals, digit separators 1'000 ✔️23 ✔️ ✔️14
multi-character constants, 'SAVEGAME' implementation-defined ✔️ up to 8, in source order implementation-defined
designated initializers {.x = 1} ✔️99 ✔️ ✔️20 (in order only)
RTTI, dynamic_cast ❌ reflect(T) instead ✔️98
smart pointers (unique_ptr, shared_ptr) ❌ ❌ (owners with [[destructor]]) ✔️11
Functions
default arguments, f(int x = 1) ❌ ✔️ ✔️98
named arguments, f(y: 2), f(.y = 2) ❌ ✔️ ❌ (designated initializers 20)
overloading ❌ (_Generic) ✔️ by all the arguments, and by the type wanted (vec3 v = make(...)) ✔️98 by the arguments
one call per argument, f(a, b ... x) ❌ ✔️ ❌ (fold expressions 17)
nested functions ❌ (GNU) ✔️ (no captures) ❌
lambdas, closures ❌ ❌ ✔️11
guaranteed tail calls, [[tail]] ❌ ✔️ self calls ❌ (clang's [[musttail]])
[[weak]] defaults with a call to the default (name.weak()) ❌ (compiler extensions) ✔️ ❌
variadic functions ✔️ (..., va_list) ✔️ ✔️ (and variadic templates 11)
several main()s (module initialization) ❌ ✔️ ❌ (static constructors)
Objects
methods, x.f() ❌ ✔️ (any T_f(T *), on any value) ✔️98 (members only)
constructors, destructors, copies ❌ ✔️ (temporaries destroyed; a value kept in a variable is freed by you, or by its owner) ✔️98 (RAII: every scope exit)
operators on structs, [[operator+]] ❌ ✔️ ✔️98 (more of them, and =)
inheritance, virtual functions, interfaces ❌ ❌ (embed a struct; function pointers) ✔️98
access control (private:), namespaces ❌ modules: private by default, #import g = ... ✔️98
modules ❌ (headers) ✔️ #import, [[export]] ✔️20 (little used yet)
macros scoped to their header ❌ ✔️ (.h2, #export) ❌
Control flow
for-each and ranges, for (int i : 0..10) ❌ ✔️ ✔️11 (no range syntax; std::views::iota 20)
if (auto *x = get()), if (int n = f(); n > 3) ❌ ✔️ ✔️98 / 17
defer ✔️2y (TS) ✔️ ❌ (RAII)
exceptions / try-throw ❌ (setjmp) ✔️ try(fn) / throw(code): an int, no typed catch ✔️98 typed, with unwinding
coroutines ❌ ✔️ stackful (minicoro) ✔️20 stackless
statement expressions ({ }) ❌ (GNU) ✔️ ❌ (GNU)
Library and data
strings, arrays, maps, sets ❌ ✔️ built in, a plain pointer each ✔️98 STL, far larger (algorithms, iterators)
f-strings, f"hp {hp}" ❌ ✔️ ❌ (std::format 20)
reflection ❌ ✔️ every type, at run time ❌ (C++26, compile time)
save/load JSON5 and XML, x.save(path) ❌ ✔️ ❌
x.hash() on any value ❌ ✔️ ❌ (std::hash per type)
threads and atomics ✔️11 (threads.h, stdatomic.h) ❌ (the host's) ✔️11
the same printf output on every platform ❌ (each C library's) ✔️ (stb_sprintf) ❌
call stacks at run time, stacktrace() ❌ ✔️ (with -g) ✔️23 (std::stacktrace)
run code from text, eval("heal(hero, 20)") ❌ ✔️ ❌
Language details
[[attributes]] ✔️23 ✔️ (more of them, and after declarators) ✔️11
countof, #embed, __VA_OPT__ ✔️2y / 23 / 23 ✔️ ❌ / ❌ (26) / ✔️20
int(3.9) casts ❌ ✔️ ✔️98
zeroed locals ❌ ✔️ ([[unclear]] to opt out) ❌
trailing comma in calls, f(a, b,) ❌ ✔️ ❌
C libraries (FFI)
use a C library from its header ✔️ (compile, then link) ✔️ (#include + #import "SDL3", in a script, no link step) ✔️ (compile, then link)
load a library by name from source, #pragma comment(lib) MSVC only ✔️ every platform MSVC only
dlopen / dlsym POSIX (LoadLibrary on Windows) ✔️ on Windows too POSIX
Tools
native executables, debuggers, sanitizers ✔️ through c2 -C and a C compiler ✔️
JIT, hot reload keeping state ([[persist]]), embedding as scripts ❌ ✔️ ❌
a host API: compile and call scripts from C (c2.h) ❌ (libtcc) ✔️ ❌
a guard for scripts, C2_sandbox (not a security boundary) ❌ ✔️ ❌
hooks at every function's entry, __on_enter ❌ (-finstrument-functions) ✔️ ❌ (the same flag)
C output, c2 -C — ✔️ (for any C compiler) ❌
a library's headers, #include <SDL3/SDL.h> ✔️ ✔️ ✔️
maturity: compilers, books, ecosystem decades one compiler, young decades

A number is the standard that brought it (98: C++98, 11: C11 or C++11, 23: C23, 2y: the next C).

Build

Build C² by typing make on a terminal (Windows/Linux/macOS):

make                  # build C² for development: unoptimized + debug symbols
make release          # build C² for release: optimized without debug symbols
                      # (to develop, plain make: much faster to build, and the tests barely notice)
make clang            # build C² with clang / clang-cl: make clang release, or make release clang
make test [SUITE...]  # all test-suites, or only those: make test c2 c2-abi  (-v: why; -k NAME: matching tests)
make bench [NAME]     # the benchmarks, or the ones matching NAME: make bench fib
                      # (Linux/macOS: m
7D01
ake test ARGS="c2 -v", make bench ARGS=fib)
make example          # build and run the embedding example (example.c)
make tour             # run every demo in tour/, one feature each
make tidy

Manually, with any of these options:

cl /O2 /DNDEBUG /MT c2.c 3rd\mir.c 3rd\mir-gen.c                                     # Windows (cl or clang-cl)
cc -O2 -DNDEBUG -fno-tree-sra c2.c 3rd/mir.c 3rd/mir-gen.c -lm -ldl -lpthread -o c2  # Linux, macOS
cmake -S docs -B .build-cmake && cmake --build .build-cmake --config Release         # CMake (generic)

-DNO_MIR=ON would build c2.c alone, without the JIT (only -S and -E work)

Coverage suites

make test [suite ...] (or python tests/test.py [suite ...]) runs the test-suites.

Next to a test, NAME.expect holds its expected output, NAME.expectrc its exit code, and NAME.expecterr lines that must appear in the compiler's messages, in order (:3: error: ...); a test whose .expecterr has an error is meant not to compile (see tests/c2-errors/).

Our own suites are named c2-*; the others come from other C compilers' test-suites.

Suite Tests Windows Linux Notes
c2-tour 59 100% 100% the tour/ demos: each must compile and exit with 0 (the 3 SDL3 ones are skipped)
c2-book 71 100% 100% the book's examples: each must print what the book shows under it
tests/c2 133 100% 100% C² features and runtime (NAME.repl: typed at c2's prompt)
tests/c2-errors 87 100% 100% C² compile errors and warnings
tests/c2-abi 548 checks (460 on Windows) 100% 100% host ⇄ script calls, typed host symbols, C2_load, a script compiled ahead of time
tests/c2-reload 287 checks 100% 100% hot reload and crash containment, in JIT, interpreter and lazy modes
tests/c2-debug 5 100% 100% -g crash reports: the call stack printed must be the expected one
tests/andrewchambers_c 67 100% 100%
tests/lacc 215 100% 97% Linux: 80-bit long double
tests/c2m 105 of 124 100% 100% 19 skipped, each with a NAME.skip saying why: c2m-only builtins (__builtin_prop_*, __builtin_jcall), setjmp across JIT frames, two-file tests, %Lf

Percentages are for make test (modes api, text and debug, which is -g), Nov/2026. --modes api,text,interp,lazy,c,debug adds the interpreter, lazy generation and the C output; they fail only where api does.

tests/c2-abi checks calls between C² scripts and a host program built by the platform's C compiler: structs of 1 to 32 bytes (ints, floats, doubles, mixed) passed and returned both ways, through function pointers and .c2 method calls. test.py builds that host (tests/c2-abi/abi.c, which includes c2.c) into .build/ with --abi-cc when it is missing or out of date. tests/c2-reload is a host program built the same way: it recompiles scripts while running and checks the hot reload rules ([[persist]], __on_reload, C2_keep_previous, failed compiles, hundreds of reload cycles) with the JIT, the interpreter and lazy generation.

python tests/test.py --modes api,text,interp,lazy,c,debug also runs every test through the interpreter, with lazy generation, through the C output (--cc picks the C compiler) and with -g.

Benchmarks

make bench [name] or python tests/bench.py [name] runs the benchmarks (MIR's C benchmarks, in tests/benchmarks/). C² is timed compiling and running (a JIT); gcc only running, after building.

Benchmark (Linux x86-64, Nov/2026) C² gcc -O2 gcc / C²
array 2.94s 3.01s 1.02x
binary-trees 2.86s 2.63s 0.92x
fib 2.89s 0.59s 0.20x
funnkuch-reduce 2.76s 2.66s 0.96x
hash 5.06s 5.25s 1.04x
hash2 7.57s 5.47s 0.72x
heapsort 7.36s 7.58s 1.03x
lists 5.07s 3.48s 0.69x
mandelbrot 3.61s 3.24s 0.90x
matrix 6.02s 3.89s 0.65x
method-call 4.81s 3.72s 0.77x
nbody 5.81s 2.78s 0.48x
particles (struct locals) 3.85s 2.08s 0.54x
sieve 4.63s 2.33s 0.50x
spectral-norm 5.78s 4.83s 0.84x
strcat 6.91s 6.91s 1.00x
16 benchmarks, total 77.92s 60.46s 0.78x

The faster time of each row is in bold. Above 1.00x C² is faster, below it gcc is. fib is all calls: gcc turns its recursion into loops, MIR doesn't. (A table of an earlier machine had C² at 59.7s, c2m -eg at 59.2s and gcc at 45.2s for 15 of them.) The table is refreshed with each change that may move it; make bench writes tests/bench_results.csv for your own machine.

License

Everything is put into the public domain, see LICENSE.μ.

MIR, the agnostic code generator that we use, is MIT licensed.

stb_sprintf, the printf family programs use, is public domain or MIT.

Tests subfolders come from different places and keep their own licenses.

minicoro, the coroutines library that we use, is public domain or MIT No Attribution.

About

Small yet fast embeddable C compiler, with extras.

Resources

Stars

9 stars

Watchers

2 watching

Forks

Releases

Contributors

Languages

0