像高级语言一样编写,像C一样运行。
Zen-C: Write like a high-level language, run like C

原始链接: https://github.com/z-libs/Zen-C

## Zen C:一种现代系统编程语言 Zen C 是一种新的系统编程语言,旨在实现兼容性和强大功能。它直接编译为人类可读的 GNU C/C11 代码,提供类型推断、模式匹配、泛型、特征(traits)和异步/等待(async/await)等特性——同时保持 100% C ABI 兼容性。 主要特性包括可变/不可变变量、固定大小的数组、结构体(可选位域)、以及带标签的联合体(枚举)。它支持具有命名参数的函数和匿名函数,以及熟悉控制流(if/else、三元运算符、循环和强大的 `match` 语句)。手动内存管理通过 `defer` 和 `autofree` 辅助实现,并提供 `Drop` 特征用于自定义清理。 Zen C 还通过 `impl` 块实现面向对象原则,用于方法和特征,并支持类型安全的泛型。并发性内置于 `async/await` 中,基于 pthreads。编译时执行、文件嵌入和编译器插件进一步增强了其功能。它还允许使用简化的语法进行内联汇编。 目前,Zen C 与 GCC 和 Clang 具有 100% 的兼容性,在 TCC 上支持约 70%(功能有限)。该项目欢迎贡献,并采用递归下降解析器、转译器以及用 Zen C 自身编写的标准库。 [https://github.com/z-libs/Zen-C](https://github.com/z-libs/Zen-C)

一种名为Zen-C的新编程语言旨在提供高级语法,同时编译为C,从而实现类似C的性能。该项目发布在Hacker News上,迅速获得大量关注,在初始提交后的24小时内获得了363颗星和20个fork。 讨论主要集中在其与现有语言(如Nim、Vala和特别是Rust)的相似之处。 许多评论员指出Zen-C的语法与Rust非常相似,但其类型命名约定(I8、F32而不是i8、f32)被认为“不符合人体工程学”。 其核心吸引力似乎在于提供类似Rust的体验,*但*没有Rust复杂的借用检查器,可能为某些人简化开发。 然而,与直接使用C或Rust相比,Zen-C独特贡献是什么仍然是一个问题。 也有人要求公开发布用于开发该语言的提示。
相关文章

原文

Zen C is a modern systems programming language that compiles to human-readable GNU C/C11. It provides a rich feature set including type inference, pattern matching, generics, traits, async/await, and manual memory management with RAII capabilities, all while maintaining 100% C ABI compatibility.


git clone https://github.com/z-libs/Zen-C.git
cd Zen-C
make
sudo make install
# Compile and run
zc run hello.zc

# Build executable
zc build hello.zc -o hello

# Interactive Shell
zc repl

1. Variables and Constants

Zen C uses type inference by default.

var x = 42;                 // Inferred as int
const PI = 3.14159;         // Compile-time constant
var explicit: float = 1.0;  // Explicit type

By default, variables are mutable. You can enable Immutable by Default mode using a directive.

//> immutable-by-default

var x = 10;
// x = 20; // Error: x is immutable

var mut y = 10;
y = 20;    // OK
Type C Equivalent Description
int, uint int, unsigned int Platform standard integer
I8 .. I128 int8_t .. __int128_t Signed fixed-width integers
U8 .. U128 uint8_t .. __uint128_t Unsigned fixed-width integers
isize, usize ptrdiff_t, size_t Pointer-sized integers
byte uint8_t Alias for U8
F32, F64 float, double Floating point numbers
bool bool true or false
char char Single character
string char* C-string (null-terminated)
U0, void void Empty type

Fixed-size arrays with value semantics.

var ints: int[5] = {1, 2, 3, 4, 5};
var zeros: [int; 5]; // Zero-initialized

Group multiple values together.

var pair = (1, "Hello");
var x = pair.0;
var s = pair.1;

Data structures with optional bitfields.

struct Point {
    x: int;
    y: int;
}

// Struct initialization
var p = Point { x: 10, y: 20 };

// Bitfields
struct Flags {
    valid: U8 : 1;
    mode:  U8 : 3;
}

Tagged unions (Sum types) capable of holding data.

enum Shape {
    Circle(float),      // Holds radius
    Rect(float, float), // Holds width, height
    Point               // No data
}

Standard C unions (unsafe access).

union Data {
    i: int;
    f: float;
}
fn add(a: int, b: int) -> int {
    return a + b;
}

// Named arguments supported in calls
add(a: 10, b: 20);

Anonymous functions that can capture their environment.

var factor = 2;
var double = x -> x * factor;  // Arrow syntax
var full = fn(x: int) -> int { return x * factor; }; // Block syntax
if x > 10 {
    print("Large");
} else if x > 5 {
    print("Medium");
} else {
    print("Small");
}

// Ternary
var y = if x > 10 ? 1 : 0;

Powerful alternative to switch.

match val {
    1 => print("One"),
    2 | 3 => print("Two or Three"),
    4..10 => print("Range"),
    _ => print("Other")
}

// Destructuring Enums
match shape {
    Circle(r) => print(f"Radius: {r}"),
    Rect(w, h) => print(f"Area: {w*h}"),
    Point => print("Point")
}
// Range
for i in 0..10 { ... }
for i in 0..10 step 2 { ... }

// Iterator/Collection
for item in vec { ... }

// While
while x < 10 { ... }

// Infinite with label
outer: loop {
    if done { break outer; }
}

// Repeat
repeat 5 { ... }
// Guard: Execute else and return if condition is false
guard ptr != NULL else { return; }

// Unless: If not true
unless is_valid { return; }
Operator Description Function Mapping
+, -, *, /, % Arithmetic add, sub, mul, div, rem
==, !=, <, > Comparison eq, neq, lt, gt
[] Indexing get, set
?? Null Coalescing (val ?? default) -
??= Null Assignment (val ??= init) -
?. Safe Navigation (ptr?.field) -
? Try Operator (res? returns error if present) -

Zen C allows manual memory management with ergonomic aids.

Execute code when the current scope exits.

var f = fopen("file.txt", "r");
defer fclose(f);

Automatically free the variable when scope exits.

autofree var types = malloc(1024);

Implement Drop to run cleanup logic automatically.

impl Drop for MyStruct {
    fn drop(mut self) {
        free(self.data);
    }
}

8. Object Oriented Programming

Define methods on types using impl.

impl Point {
    // Static method (constructor convention)
    fn new(x: int, y: int) -> Point {
        return Point{x: x, y: y};
    }

    // Instance method
    fn dist(self) -> float {
        return sqrt(self.x * self.x + self.y * self.y);
    }
}

Define shared behavior.

trait Drawable {
    fn draw(self);
}

impl Drawable for Circle {
    fn draw(self) { ... }
}

Use use to mixin fields from another struct.

struct Entity { id: int; }
struct Player {
    use Entity; // Adds 'id' field
    name: string;
}

Type-safe templates for Structs and Functions.

// Generic Struct
struct Box<T> {
    item: T;
}

// Generic Function
fn identity<T>(val: T) -> T {
    return val;
}

10. Concurrency (Async/Await)

Built on pthreads.

async fn fetch_data() -> string {
    // Runs in background
    return "Data";
}

fn main() {
    var future = fetch_data();
    var result = await future;
}

Run code at compile-time to generate source or print messages.

comptime {
    print("Compiling...");
}

Embed files as byte arrays.

var png = embed "assets/logo.png";

Import compiler plugins to extend syntax.

import plugin "regex"
var re = regex! { ^[a-z]+$ };

Pass preprocessor macros through to C.

Decorate functions and structs to modify compiler behavior.

Attribute Scope Description
@must_use Fn Warn if return value is ignored.
@deprecated("msg") Fn/Struct Warn on usage with message.
@inline Fn Hint compiler to inline.
@noinline Fn Prevent inlining.
@packed Struct Remove padding between fields.
@align(N) Struct Force alignment to N bytes.
@constructor Fn Run before main.
@destructor Fn Run after main exits.
@unused Fn/Var Suppress unused variable warnings.
@weak Fn Weak symbol linkage.
@section("name") Fn Place code in specific section.
@noreturn Fn Function does not return (e.g. exit).
@derived(...) Struct Auto-implement traits (e.g. Debug).

Zen C provides first-class support for inline assembly, transpiling directly to GCC-style extended asm.

Write raw assembly within asm blocks. Strings are concatenated automatically.

Prevent the compiler from optimizing away assembly that has side effects.

Zen C simplifies the complex GCC constraint syntax with named bindings.

// Syntax: : out(var) : in(var) : clobber(reg)
// Uses {var} placeholder syntax for readability

fn add(a: int, b: int) -> int {
    var result: int;
    asm {
        "add {result}, {a}, {b}"
        : out(result)
        : in(a), in(b)
        : clobber("cc")
    }
    return result;
}
Type Syntax GCC Equivalent
Output : out(var) "=r"(var)
Input : in(var) "r"(var)
Clobber : clobber("rax") "rax"
Memory : clobber("memory") "memory"

Note: When using Intel syntax (via -masm=intel), you must ensure your build is configured correctly (for example, //> cflags: -masm=intel). TCC does not support Intel syntax assembly.


Compiler Support & Compatibility

Zen C is designed to work with most C11 compilers. Some features rely on GNU C extensions, but these often work in other compilers. Use the --cc flag to switch backends.

Compiler Pass Rate Supported Features Known Limitations
GCC 100% All Features None.
Clang 100% All Features None.
TCC ~70% Basic Syntax, Generics, Traits No __auto_type, No Intel ASM, No Nested Functions.

Recommendation: Use GCC or Clang for production builds. TCC is excellent for rapid prototyping due to its compilation speed but misses some advanced C extensions Zen C relies on for full feature support.


We welcome contributions! Whether it's fixing bugs, adding documentation, or proposing new features.

  1. Fork the Repository: standard GitHub workflow.
  2. Create a Feature Branch: git checkout -b feature/NewThing.
  3. Code Guidelines:
    • Follow the existing C style.
    • Ensure all tests pass: make test.
    • Add new tests for your feature in tests/.
  4. Submit a Pull Request: Describe your changes clearly.

The test suite is your best friend.

# Run all tests (GCC)
make test

# Run specific test
./zc run tests/test_match.zc

# Run with different compiler
./tests/run_tests.sh --cc clang
  • Parser: src/parser/ - Recursive descent parser.
  • Codegen: src/codegen/ - Transpiler logic (Zen C -> GNU C/C11).
  • Standard Library: std/ - Written in Zen C itself.
联系我们 contact @ memedata.com