Kof4j README

项目的 README,来自 github.com/KofLang/Kof4j。合并为一个 markdown 文件:README.md。

English | Português

Kof

Kof Logo

One language. One compiler. Many worlds.

pronounced coffe

Less code. More intention. JVM, native, script and web. All starting from the same language.


Mascot

Kof mascot — a civetta

Kof's mascot is a civetta — also known as the musk cat, it is a feline that eats coffee. Nothing more fitting for a language pronounced coffe.


Contributors

Thanks goes to these wonderful people (the Kof badge is their mark):

Mel Santos
Mel Santos

kof original contributor 🤔 💻 🚧 🚇 🛡️ 👀 ⚠️
temmcode
temmcode

kof original contributor 💻 📖 ⚠️
kof-agent-worker[bot]
kof-agent-worker[bot]

kof original contributor 💻 ⚠️ 🚇 📖
jonasrochasilva-prog
jonasrochasilva-prog

kof original contributor 💻 📖
PublioSantos
PublioSantos

kof original contributor 💻 📖
dependabot[bot]
dependabot[bot]

kof original contributor 🚇 🛡️
ViniAguiar1
ViniAguiar1

kof original contributor 💻
lchampz
lchampz

kof original contributor 💻
nillvitor
nillvitor

kof original contributor 💻
FabioRocha231
FabioRocha231

kof original contributor 💻
ViniciusKoiti
ViniciusKoiti

kof original contributor 💻
filipejsales-abinbev
filipejsales-abinbev

kof original contributor 💻
Anderson-Andre-P
Anderson-Andre-P

kof original contributor 💻
jonasrochanasajon
jonasrochanasajon

kof original contributor 💻
matheusdgdcampos
matheusdgdcampos

kof original contributor 💻
lunalully
lunalully

kof original contributor 💻
ronald2329
ronald2329

kof original contributor 💻
ThiagoLange
ThiagoLange

kof original contributor 🤔 📖

Disclaimer

The Kof language has no relationship whatsoever with the game The King of Fighters or its franchise.

The name Kof came about as a reference to the word "coffee" deliberately spelled incorrectly. The choice was made precisely in an attempt to create a short, unique and easily identifiable name for the language.

Koflang and Kof4J do not endorse the association of the name with the The King of Fighters franchise. Any similarity or association made in that sense is incidental and does not represent the origin, purpose or identity of the projects.

Our goal has always been to create a unique identity for the language and its components.


Some people look at a problem and write a library.

Others write a framework.

Some create a tool.

I apparently looked at the entire ecosystem and thought:

"This is all too complicated. I'm going to create a language."

And, apparently, a language alone wasn't enough either.

Welcome to Kof.


What is Kof?

Kof is a general-purpose, statically typed programming language, built around one central idea:

A single language should not force you to choose a single world.

📖 The formal language specification (grammar, type system, semantics, status of each feature) is in docs/language-reference/. The compiler architecture (implementation) is in docs/architecture/compiler-architecture.md. The distinction language ≠ compiler ≠ target is the axis of those documents.

Kof has its own compiler, lexer, parser, type system, semantic analysis and intermediate representation (Kof IR). From that IR, different backends turn the same program into different forms of execution:

            Kof Language  (defined by the specification)
                          │
                    Kof Compiler  (one implementation)
                          │
                       Kof IR  (linear stack machine, 30 ops)
                          │
          ┌───────────────┼────────────────┐
          │               │                │
       JVM Backend    Native Backend    JS Backend
          │               │                │
          ▼               ▼                ▼
        JVM          Native Binary      ES Modules
       (.class)      (ELF x86_64,       (Node /
                      riscv64/aarch64)    browser)

The language does not change. The target changes. JVM, Native and JS are compilation targets of the same Kof — not semantically different dialects. KofScript (.ks, REPL) is a direct execution target: pure Kof consuming the SAME frontend and executed by the IR interpreter, without compiling and without a JVM fork — it is not JavaScript (let/const/async/fn do not exist). KofC is a separate tool (C subset → ELF), it does not consume the Kof IR — see docs/architecture/compiler-architecture.md §7.)


Kof is not a transpiler

Kof does not work like this:

Kof → Java → javac → JVM

It works like this:

Kof → Kof Compiler → Kof IR → Backend → Target

The compiler has its own implementation of:

Kof does not depend on Java as an intermediate language.


Current State

Kof is in active development — 0.8.1.

The compiler has its own frontend, type system, Kof IR and three backends over the IR, which produce six targets: JVM (V21 via ASM), Native x86_64 (ELF, no libc), native.risc/native.arm (real riscv64 + aarch64 via ISA translator), KofJS (ES Modules) and Android (JVM variant + APK packaging). KofScript (.ks, REPL) is a direct execution target: pure Kof on the SAME frontend, executed by the IR interpreter (KofInterpreter) without emitting bytecode or a JVM fork. KofC (C subset → native) is a separate tool, it does not consume the Kof IR — see docs/architecture/compiler-architecture.md §7.

Feature JVM Native KofJS
println, variables, arithmetic ✅ ✅ ✅
if/else, if-expr, while, for, for-in, switch ✅ ✅ ✅
functions (without fun), lambdas with captures ✅ ✅ ✅
records, classes, inheritance, interfaces, virtual dispatch ✅ ✅ ✅
generics (erasure), Box<T> with primitives ✅ ✅ ✅
exceptions (throw "msg", try/catch/finally) ✅ ✅ ✅
null safety String? + narrowing ✅ ✅ ✅
pattern matching case String s + record destructuring ✅ ✅ ✅
spawn/await (Handle<T>, unboxing) ✅ ✅ (pthread) ✅ sequential
strings (concat +, ==, full API) ✅ ✅ ✅
arrays, List<T>/Map<K,V>/Set<T> + map/filter/reduce ✅ ✅ ✅
enums + exhaustive switch ✅ ✅ ✅
JSON encode/decode (objects/records/arrays, 3 targets) ✅ ✅ ✅
kof.io (File, Path, Directory) ✅ ✅ ✅
kof.time (now/sleep/interval), kof.cache ✅ ✅ ✅
kof.web (web.app(), ws, sse, TLS) ✅ base ✅ 03/09; TLS WEB002, ws WEB004, sse WEB003 ✅ base 16/09 + SSE handler-scoped 16/09 (ws WEB004, SSE push pós-return WEB003 compile-time)
kof.http client + retry/circuit ✅ HTTP002 ✅
kof.security (passwords, crypto, jwt, secrets, auth) ✅ ✅ ✅
kof.db / kof.orm (native SQLite, MySQL WIP, MongoDB) ✅ ✅ ✅ 16/09 untyped (GraalJS-host bridge); typed query<T> ✅ 18/09 (DB002 closed); kof.orm ✅ 18/09 (ORM001 closed)
kof.config / kof.log ✅ ✅ CONF001/LOG001
kof.ui (Color, Palette, Theme, widgets) no-op no-op ✅ render

Concurrency: spawn task() / val r = spawn f(); await r — virtual threads on the JVM, pthread_create on Native (CONC001 closed 31/08), sequential on JS (CONC003). See docs/language-reference/concurrency.md.

Null safety: String?/Int? + if (x != null) narrowing on the 3 targets (JVM fix 02/09). Map.get returns V? for reference values.

Tests: test "name" { } + assert(cond, "msg") + kof test — 3225 tests (1907 kof-compiler + 38 kof-script + 7 kof-c-compiler + 262 kof-cli). See learn/23-testing.md.

Debugging: kof debug <file.kf> — DAP server over stdio with raw JDWP (breakpoints by Kof line, call stack with Kof functions/lines, continue, disconnect). See docs/debugging/debugging.md.

Ecosystem audit: stdlib coverage matrix (inventory, gaps G1-G12, priority and strategy) in docs/bugs-and-gaps/ecosystem-coverage.md. Evolution plan toward a complete platform: docs/development/roadmap.md.


kof.ui — The UI platform

Kof's UI foundation: Color (32-bit RGBA), Palette (named colors) and Theme (light/dark with semantic colors) — same semantics on JVM, Native and JS. Rendering is KofJS: widgets → real DOM in the native webview (bin/kof-webview, embedded WebKitGTK) or in the browser.

Widgets: Window (title, bind, show/close, size, theme), Label (text, fontSize, bold, color), Button (text + action via lambda with captures), Input (text), Column/Row containers, View+Style (background, padding, radius).

class App {
    static Int count = 0
}

main() {
    var w = Window("Contador")
    var label = Label("contagem: 0")
    w.bind(label)
    w.bind(Button("+1", () -> {
        App.count = App.count + 1
        label.text = "contagem: " + App.count
    }))
    w.show()
}
kof run contador.kf --target=js   # opens the window; closing ends the program

See: learn/35-kof-ui.md and learn/37-kofjs.md.


Documentation — where to look for what

Folder For whom What it contains
docs/ architects, maintainers, decisions Technical and project documentation: current state (status.md, backend-parity.md; snapshots in history/), architecture (architecture/), philosophy (philosophy.md), stdlib and areas (stdlib/ — includes security, http, web, config, database, logging, observability), concurrency (language-reference/), language (language-reference/), debugging (debugging/), comparison (comparison/), runtime (runtime/), roadmap (development/roadmap.md), targets (targets/), UI (ui/), distribution and license (distribution/), consolidated design decisions (decisions/), tooling (tooling/), future visions (development/future/) and audits (bugs-and-gaps/ecosystem-coverage.md, audits/complexity-audit.md)
learn/ humans learning Kof Learning track in numbered chapters (00 Introduction → 39 stdlib): language, classes, functions, lambdas, UI, security — each chapter a hands-on guide; learn/native/ for the native target
training/ LLMs and AI tools Structured corpus optimized for language models: facts by topic (language/), idioms (idioms/), patterns/anti-patterns (patterns/, anti-patterns/), compilable examples (examples/), reference (reference/), Java→Kof migration (migration/), tooling and releases

Rule of thumb: docs/ says how Kof is (state and architecture); learn/ teaches how to use Kof (step by step); training/ feeds those who generate Kof code (LLMs).


kof.web — Native Web Stack

Web applications without Spring, without a servlet container, without annotations:

record User(String name, Int age)

main() {
    var app = web.app()

    app.use {
        if (header("x-auth") == "secret") {
            return null
        }
        return "{\"error\": \"unauthorized\"}"
    }

    app.get("/hello") {
        return "Hello from Kof"
    }

    app.get("/users/:id") {
        return "user " + param("id") + " q=" + query("name")
    }

    app.post("/user") {
        var user = json.decode<User>(body())
        return json.encode(user)
    }

    app.listen(8080)
}
kof serve app.kf

Path params, query, headers, body, middleware, typed JSON and an HTTP server embedded in the program's runtime. See: docs/stdlib/stdlib-web.md.


kof.io — Filesystem

Files, directories and paths with a single API across all targets:

main() {
    var path = Path("data/users.txt")
    path.parent().createDirectories()
    path.writeText("Mel\nKof\n")
    println(path.readText())
    println(path.size())
}
main() {
    var dir = Directory("data")
    dir.createDirectories()
    for (var entry in dir.list()) {
        println(entry.name)
    }
}

Text always UTF-8; bytes as Int[]; absence as String? (null) and size() throws instead of a -1 sentinel. See: learn/34-file-system.md and docs/stdlib/IO.md.


Installation

Kof is a distribution: install it and get the compiler, CLI, runtime, stdlib, tooling, editor support and an embedded OpenJDK. No external Java installation is required — and you don't need to know the version to install.

  1. Linux/macOS — automated (detects your platform and the newest release, no version to type):

    curl -fsSL https://raw.githubusercontent.com/KofLang/Kof4j/main/scripts/install.sh | bash
    

    Or manual: download the package for your system from GitHub Releases. Kof publishes one release per platform (linux-x86_64.tar.gz / macos-arm64.tar.gz / macos-x86_64.tar.gz (Intel) / windows-x86_64.zip) — pick the newest release whose name ends with yours.

  2. Extract it and add bin to PATH:

# Linux
tar -xzf kof-*-linux-x86_64.tar.gz
export PATH="$PWD/$(ls -d kof-*-linux-x86_64 | head -1)/bin:$PATH"

# macOS (Apple Silicon)
tar -xzf kof-*-macos-arm64.tar.gz
export PATH="$PWD/$(ls -d kof-*-macos-arm64 | head -1)/bin:$PATH"

# macOS (Intel)
tar -xzf kof-*-macos-x86_64.tar.gz
export PATH="$PWD/$(ls -d kof-*-macos-x86_64 | head -1)/bin:$PATH"

# Windows (PowerShell)
Expand-Archive .\kof-*-windows-x86_64.zip
$DIR = (Get-ChildItem -Directory -Filter "kof-*-windows-x86_64" | Select-Object -First 1).FullName
$env:PATH = "$DIR\bin;$env:PATH"
  1. Check it:
kof version   # kof <release version>
kof info      # full environment (embedded JVM, Tooling API 21, targets)

See: docs/distribution/INSTALL.md (complete guide with each system, checksum and troubleshooting) and docs/distribution/ARCHITECTURE.md.


CLI

kof build <dir> [--target jvm|native|native.risc|native.arm|js|android] [--output <dir>] [--release]
kof deploy <dir> [--target jvm|native|js|android] [--output <dir>] [--name <n>] [--version <v>]
kof run <file.kf> [--target jvm|native|native.risc|native.arm|js] [args...]
kof serve <file.kf> [--port <port>] [--host <host>]
kof check <file.kf|dir> [--json]
kof test <file.kf|dir> [--target jvm|native|js]
kof md check|format <file.md>
kof script | repl | c | fmt | config | init | new
kof bench | profile | inspect | debug
kof decompile | translate | compare | migrate | deps | editor | connector | legacy
kof workflow | makealive <plan|apply|destroy> <file.kf>
kof info | lsp | install | version

kof fmt (idempotent formatter) and kof config gen implemented — see docs/tooling/README.md.



Building and installing from source

Requirements: JDK 25 (Temurin recommended — the repo build baseline since D-BASELINE 14/09; --release 25) and Maven 3.9+. For the native target: as/ld (binutils). The js target requires nothing external (GraalJS embedded in the jar).

Three JDK layers, do not confuse them (D-BASELINE):

  • Building this repo: JDK 25 required (pom.xml release=25; the compiler code uses unnamed patterns _ = JEP 443, finalized in 22 — JDK 21 cannot compile the sources).
  • Running the kof CLI: the classes are release 25, so the CLI itself runs on JDK 25; scripts/package.sh --jdk embeds Temurin 25 so the packaged distribution carries its own JVM.
  • Your Kof programs (the LANGUAGE contract — frozen, rule 6): unchanged. The JVM backend still emits V21 bytecode (JvmBackend) and the Android template still targets release 21, so a .kf you compile runs on JVM 21+. Raising the repo toolchain does NOT raise the language's minimum runtime.
# 1. Build everything (compiler, runtime, CLI with embedded GraalJS)
mvn clean package -DskipTests

# 2. Run the full suite (JVM + Native + KofJS E2E)
mvn test

# 3. Use straight from source (dev build, system java)
mkdir -p lib
cp kof-cli/target/kof-cli-$(cat VERSION).jar lib/kof.jar
bin/kof version
bin/kof info

# 4. Install into a prefix (full local installation)
bin/kof install ~/.kof
export PATH="$HOME/.kof/bin:$PATH"
kof version

# 5. Package the official distribution (with embedded OpenJDK 25)
scripts/package.sh --jdk      # generates dist/kof-<version>-<os>-<arch>.tar.gz

kof install <dir> copies kof.jar to <dir>/lib/ and generates the launcher <dir>/bin/kof (it uses the embedded JDK from <dir>/jdk/ when present; otherwise the system java). scripts/package.sh --jdk downloads Temurin 25 from Adoptium and assembles the complete distribution layout.

Versioning centralized in VERSION — see docs/distribution/VERSIONING.md.

Windows: use Git Bash for scripts/package.sh — the generic bash in PATH may resolve to WSL and generate a Linux distribution (OBS-005). On Windows, Python may only be available as the launcher py — the script discovers it automatically (python3/python/py -3).


Architecture

Source (.kf)
  ↓ Lexer
  ↓ Parser
  ↓ AST
  ↓ Type System
  ↓ Semantic Analysis
  ↓ Kof IR (backend-agnostic)
  ├── JVM Backend (ASM) → .class
  ├── Native Backend (x86_64 / riscv64 / aarch64) → ELF
  └── JS Backend (GraalJS) → ES Modules

Principles

  1. Less code, same capability
  2. Strong typing
  3. Intention over ceremony
  4. One frontend, multiple backends
  5. Straight to the target
  6. Interoperability
  7. No unnecessary magic
  8. Tools matter

The "paradigm" of intention

Kof is intention-oriented — which is not a formal paradigm, but rather object orientation taken to the extreme: the code expresses what it wants, and the platform (language + compiler + runtime + stdlib) decides how, per target and per convention.

intention → Kof → compiler → backend

You write spawn task() (not Thread), app.get("/users/:id") (not a servlet container), Window/Button("+1", () -> ...) (not WebView/JavaFX), json.decode<User>(body) (not a manual parser), Palette.red (not 0xFF0000FF). If it is essential to any program, it belongs to the platform.

When a target cannot fulfill the intention, it says so at compile-time with a gap code (CONC001, JSN002, ...) — never silently.

Details: docs/philosophy.md · idioms: training/idioms/ · anti-patterns: training/anti-patterns/.


What Kof is NOT

Kof is a language. A compiler. An IR. Several backends.


Built with Kof

Project What it is Targets
KOOKIE Experimental 3D shooter engine built around Kof (boomer shooters / ARPG FPS). The simulation and engine rules live in .kf; small native adapters sit only at the SDL3/SDL_GPU and ABI boundaries. Native Linux x86-64 (first supported target); JVM as the differential/comparison target — including a Windows JVM archive that embeds a Windows JDK and a PE launcher. Native Windows PE execution is still not available on Kof's native target, and KOOKIE fails closed about it honestly.

License

Kof is free software distributed under the GNU General Public License v3.0.

This applies to the compiler source code, tools and other project components.

Programs written in Kof are NOT automatically GPLv3.

The author of a program retains the right to choose the license for their own software. Using the Kof compiler does not obligate anyone to open their source code.

Proprietary software written in Kof is allowed, as long as it respects the licenses of the dependencies it actually incorporates.

For more details, see docs/distribution/LICENSING.md.

The Kof / Kof4j logo, mascot and visual identity are available for free commercial and community use under CC BY 4.0 — see TRADEMARK.md.


Kof

One language. One compiler. Many worlds.

Less ceremony. More intention.


i'm aways opensource so the whole world can use me so i can build a better world and draw with all my Koffies to build me and control me what's the future hold for me and the community that soldiers on to build the story

(inspired by openSUSE)

Kof4j (KofLang/Kof4j)

正在搜索数据库…

这是什么?Kof(读作 'coffe')是一门通用型静态类型编程语言,带有自己的编译器。同一门语言可以编译到 JVM、原生二进制、JavaScript 和 Android——变的只是目标平台,语言本身不变。
它是真正的编译器还是转译器?是真正的编译器,不是转译器:它自带词法分析器、语法分析器、类型系统、语义分析和中间表示(Kof IR),从不把 Java 当作中间语言。
使用之前需要先安装 Java 吗?不需要——发行包里内置了 OpenJDK,无需单独安装 Java。如果想从源码构建,则需要 JDK 21+ 和 Maven 3.9+,编译原生目标时还需要 binutils。
它适合用于生产环境吗?目前仍在积极开发中,版本为 0.3.0-beta,应视为测试版质量。一些标准库模块在非 JVM 目标上还不完整——例如 kof.db/kof.orm 在 JS 上不完整,kof.ui 目前只能在 JS 上渲染——所以在依赖某个模块之前,请先查看功能对照表。
一个 Kof 程序可以编译成什么?一套前端支持六种目标:JVM 字节码(通过 ASM 生成 V21)、不依赖 libc 的 x86_64 原生 ELF、riscv64 和 aarch64 原生代码、JavaScript ES Modules、Android(打包成 APK 的 JVM 变体),以及 KofScript——一个直接在 IR 解释器上运行 Kof 的 REPL。
如果编译器是 GPLv3,我的代码也必须用 GPL 协议吗?不需要——GPLv3 只约束编译器及其工具,你自己写的程序可以自由选择任何许可证。用 Kof 编写专有软件是明确允许的。
为什么叫 Kof?它是故意拼错的 'coffee'(咖啡),读作 'coffe',吉祥物是一只麝香猫——一种以爱吃咖啡豆闻名的猫科动物。README 中明确声明与《拳皇》(The King of Fighters)系列没有任何关系。
Kof 中 'intent over ceremony'(意图优先于形式)是什么意思?你只写想做什么——比如 spawn tarefa()、app.get('/users/:id')、Window/Button('+1', ...)——具体怎么做由平台(编译器、运行时、标准库)根据不同目标和约定来决定。当某个目标无法实现某个意图时,你会得到一个类似 CONC001 的编译期错误码,而不是默默出现异常行为。
不用 Spring 也能搭建 Web 后端吗?可以——kof.web 提供一个内嵌 HTTP 服务器,支持路径参数、查询字符串、请求头、请求体、中间件、类型化 JSON、WebSockets、SSE 和 TLS,完全不需要 Spring、Servlet 容器或注解。目前在 JVM 上已经完备,原生和 JS 目标上仍有限制。
spawn/await 在所有目标上都能用吗?并发是内置于语言本身的,三种执行后端全部支持:JVM 上使用虚拟线程,原生平台使用 pthreads,JS 上则只能顺序执行。
有哪些类似的项目?scala, crystal, perry, v, clojure, TypeScript, jdk, truffleruby
作者
KofLang
大小
245.1 MB
星标
308
时长
3个月
提交 · 90 天