Skip to content

RSnew/Flux

Repository files navigation

Flux Language

简体中文

A programming language designed for the AI era.

Flux is a harness-first language: every design decision — hot-reload, module isolation, specify contracts, machine-readable tooling — exists to make AI agents productive, safe, and observable in production.

Built in ~5,000 lines of C++17. No external dependencies beyond pthreads.

Flux is not a scripting language. It features a complete type system with HM inference, a bytecode compiler and stack-based VM, multi-level IR optimization (HIR → MIR → JIT/Codegen), module isolation with supervised crash recovery, and a full toolchain (type checker, formatter, package manager, LSP, debugger). Hot reload is a design choice, not a limitation.


Why Flux for AI?

Modern AI workflows need a language that speaks the same language as LLMs — structured, introspectable, crash-tolerant, and instantly iterable.

Challenge What Most Languages Do What Flux Does
AI agents need to understand code intent Comments, docs (unstructured) specify — intent, constraints & examples as first-class types
AI-generated code is unreliable Crash = process death @supervised modules auto-recover, isolating failures
Agents need fast iteration loops Edit → compile → restart Edit → save → instant hot-reload, state preserved
Agents need machine-readable output Parse error strings flux check --json, flux inspect --json, flux eval --json
AI code runs as untrusted services Shared global state Module isolation: each module is a sandboxed unit

Quick Start

# Build
cd flux && mkdir -p build && cd build
cmake .. && cmake --build . -j$(nproc)

# Run a script (with hot-reload file watcher)
./flux examples/hello.flux

# Run once (no watcher)
./flux run examples/hello.flux

# Interactive REPL
./flux

Hello, Flux

var name = "World"
print("Hello, \(name)!")

func factorial(n) {
    if n <= 1 { return 1 }
    return n * factorial(n - 1)
}
print("10! = \(factorial(10))")

AI-Native Features

specify — Intent as a First-Class Type

Declare what your code means, not just what it does. AI agents can introspect contracts without parsing source code.

var paymentValidator = specify {
    intent: "验证用户支付数据的合法性",
    input: "amount: Int, currency: String",
    output: "Bool",
    constraints: ["amount > 0", "currency in [USD, EUR, CNY]"],
    examples: ["amount=100 currency=USD -> true"]
}

Specify.describe(paymentValidator)         // human-readable summary
Specify.schema(paymentValidator)           // structured Map → LLM context
Specify.validate(paymentValidator, input)  // true / false

Machine-Readable Toolchain

Every tool outputs structured JSON for AI consumption:

flux check myapp.flux --json      # type errors as JSON array
flux inspect myapp.flux --json    # all symbols, signatures, contracts
flux eval "1 + 2" --json          # evaluate snippet → {"result": 3}

Design-by-Contract

func divide(a, b)
requires { b != 0 }
ensures  { result != null }
{
    return a / b
}

Contracts are part of the language — agents discover them via flux inspect --json, not by guessing from variable names.

Supervised Crash Recovery — Safe for AI-Generated Code

AI-generated code panics. Flux modules auto-restart:

@supervised(restart: .always, maxRetries: 3)
module AIGeneratedService {
    func run(input) {
        // if this panics, the module restarts automatically
        // other modules are unaffected
    }
}

Hot Reload — Instant Iteration Loop

AI agents can rewrite and test code without restarting the process. Persistent state survives reload:

module Counter {
    persistent { count: 0 }         // survives hot reload
    func increment() { state.count = state.count + 1 }
    func getValue()  { return state.count }
}

Language Highlights

Variables, Constants & Types

var x = 42                    // inferred
var name: String = "Flux"     // annotated
conf MAX = 100                // constant (read-only)
lock RATE = 0.05              // AI-protected (immutable at runtime)
var nums = [1, 2, 3, 4, 5]   // arrays
var m = Map()                 // hash map

Control Flow

if x > 0 { print("positive") } else { print("non-positive") }

while i < 10 { i = i + 1 }

for n in range(5, 10) { print(n) }     // 5, 6, 7, 8, 9
for c in "hello" { print(c) }          // h, e, l, l, o

// break & continue
while true {
    if done { break }
    if skip { continue }
}

// ternary
var label = x > 100 ? "big" : "small"

Enums

enum Direction { North = 0, South = 1, East = 2, West = 3 }
var heading = Direction.North

Structs & Interfaces

var Shape: interface = { func area() }

var Circle = Shape {
    radius: 1,
    func area() { return 3.14159 * self.radius * self.radius }
}
var c = Circle(radius: 5)
print(c.area())   // 78.54

Thread Pool Concurrency

@threadpool(name: "cpu-pool", size: 4)

@concurrent(pool: "cpu-pool")
module ImageProcessor {
    func resize(w, h) { return w * h }
}

var future = ImageProcessor.resize.async(1920, 1080)
var result = future.await()

Standard Library

File.write("/tmp/out.txt", "hello\n")
var content = File.read("/tmp/out.txt")

var obj = Json.parse("{\"x\": 1}")
print(Json.pretty(obj))

Http.download("https://example.com/file.bin", "/tmp/file.bin")

Toolchain

Command Description
flux <file> Run with hot-reload (file watcher)
flux run <file> Run once
flux --vm <file> Run with bytecode VM
flux check <file> Type-check only
flux check <file> --json Type errors as JSON (AI-friendly)
flux inspect <file> List symbols, signatures & contracts
flux inspect <file> --json Same, structured JSON
flux eval "<code>" --json Evaluate snippet, return JSON result
flux fmt <file> Format source to stdout
flux fmt -w <file> Format in-place
flux repl Multi-line REPL with history
flux compile <file> Compile to native binary (x86_64, arm64, riscv64)
flux profile <file> Run with profiling

Package Manager

flux new myapp      # create project with flux.toml
flux add mathlib    # add dependency
flux install        # install all deps
flux build          # build & run
flux publish        # publish to local registry

Feature Status

Feature Status
Language Core (arrays, interpolation, for-in, break/continue, ternary, modules) ✅ Done
Standard Library (File, JSON, HTTP, Time, Map) ✅ Done
Bytecode VM (28-opcode stack VM) ✅ Done
Toolchain (check / fmt / run / REPL / VSCode extension) ✅ Done
Concurrency (thread pools, async/await, channels) ✅ Done
Package Manager (flux.toml, dep resolution) ✅ Done
Structs, interfaces, enums, constants ✅ Done
AI-Native Types (specify, contracts, flux inspect --json) ✅ Done
Native Compilation (x86_64 / arm64 / riscv64) ✅ Done
Self-hosting (Flux compiler written in Flux, 27 tests) ✅ Done
FluxOS (bare-metal x86 microkernel: VGA, keyboard, shell) ✅ Done

Design Philosophy

Flux trades systems-language power for a feedback loop fast enough for AI agents.

Design Choice Rust / C++ Flux Why
Type system Static, generics Dynamic + HM inference Faster save→effect; no <T> noise for agents
Memory Ownership / RAII GC GC overhead ≪ borrow-check friction in hot-reload loops
Error handling Result / exceptions exception + @supervised Failures isolated at module boundary; auto-recovery
AI integration External tooling specify first-class + --json everywhere Contracts are the language, not comments
Dev feedback Edit → compile → run Edit → save → instant The reason Flux exists

See docs/design-comparison.md for full details.


Project Structure

Flux/
├── flux/                       # Language implementation (C++17)
│   ├── src/                    # Lexer, parser, type checker, interpreter,
│   │                           # compiler, VM, stdlib, JIT, LSP, debugger...
│   └── examples/               # 22 demo scripts (incl. self-hosting compiler)
├── vscode-flux/                # VSCode extension (syntax, snippets, folding)
├── learner/                    # Self-training AI learner for Flux basics
├── Flux Language Spec.docx     # Language specification
└── README.md

Build Requirements

  • C++17 compiler (GCC 7+ / Clang 5+)
  • CMake 3.16+
  • pthreads

License

MIT License — Copyright (c) 2026 RSnew

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors