Klang Documentation
Complete language reference, tools, and architecture.
#1. Introduction
Klang (Klowns Language) is a modern, statically-typed, compiled programming language designed for the Kaiser Klowns ecosystem. It covers every domain: Web, AI, Backend, Mobile, Desktop, Cloud, and OS development.
Design Goals
- Speed of C / Rust — compiles to native LLVM IR, C, or WebAssembly
- Readability of Python — clean, expressive syntax with minimal boilerplate
- Structure of TypeScript — strong static typing with full type inference
- Scalability of Go — first-class concurrency, channels, and module system
File Extension
All Klang source files use the .kkg extension — e.g. main.kkg
Kaiser Klowns Ecosystem
| Product | Role | Status |
|---|---|---|
| Klang | Core programming language (.kkg) | ✅ Complete |
| Aello | Integrated Development Environment | → Next |
| Arkai AI | AI assistant built with Klang AI primitives | Planned |
| Alfa Git | Version control platform | Planned |
| Marisea Cloud | Cloud deployment & serverless runtime | Planned |
| Ocean OS | Operating system kernel written in Klang | Planned |
#2. Installation
2.1 Requirements
gcc 10+— the only dependency (available on every OS)- No Rust, no LLVM, no virtual machine required
- Supported: Windows, macOS, Linux, ARM (Apple Silicon)
2.2 Install
macOS / Linux
bash1curl -sSf https://klang.kkg/install.sh | sh
Windows
bash1winget install KaiserKlowns.Klang
Build from Source (gcc only, no Rust needed)
bash1git clone https://github.com/kaiser-klowns/klang2cd klang3make bootstrap # gcc only — Rust not required4./klangc --version5# klangc v1.0.0 — Kaiser Klowns Dragon
Tip: After Phase 2, Klang only needs
gcc— which ships with every major OS. No rustup, no cargo, no LLVM required.
#3. Quick Start
3.1 Hello World
kkg1// hello.kkg2fn main() {3 println("Hello Kaiser Klowns!")4}
bash1klang run hello.kkg2# Hello Kaiser Klowns!
3.2 New Project
bash1kpkg init my-app2cd my-app3klang run main.kkg
3.3 Project Structure
bash1my-app/2├── main.kkg # entry point3├── klang.toml # project manifest4├── klang.lock # dependency lock file5└── src/ # additional source files
#4. Language Tour
4.1 Variables & Types
Variables are immutable by default. Use mut for mutable bindings, const for compile-time constants.
kkg1let name = "Klang" // immutable, type inferred2let mut count = 0 // mutable3const MAX: int = 1024 // compile-time constant4let age: int = 25 // explicit type5let ratio: float = 3.146let active: bool = true7let opt: ?int = nil // optional (nullable)
Built-in Types
| Type | Description | Example |
|---|---|---|
int | 64-bit signed integer | 42, -7, 0 |
float | 64-bit floating point | 3.14, -0.5 |
bool | Boolean value | true, false |
string | UTF-8 string | "hello", "🐉" |
char | Single UTF-8 character | 'a', '🐉' |
[T] | Dynamic array of type T | [1, 2, 3] |
map[K]V | HashMap from K to V | map["a": 1] |
?T | Optional / Nullable T | nil or value |
(A, B) | Tuple | (1, "ok") |
4.2 Functions
kkg1fn add(a: int, b: int) -> int { return a + b }23// Arrow shorthand4fn square(x: int) -> int => x * x56// Async function7async fn fetchUser(id: int) -> Result<User> {8 let res = await http.get("/users/" + id)9 return Ok(res.json())10}1112// Lambda / higher-order13let doubled = [1,2,3,4,5].map(x => x * 2) // [2,4,6,8,10]
4.3 Control Flow
kkg1if score >= 90 { println("A") }2else if score >= 80 { println("B") }3else { println("C") }45for i in 0..10 { println(i) }6for item in ["a","b","c"] { println(item) }7while count > 0 { count -= 1 }89match status {10 200 => println("OK")11 404 => println("Not Found")12 _ => println("Other: " + status)13}
4.4 Structs & Enums
kkg1struct User { name: string, age: int, email: string }2let user = User("Alice", 25, "alice@klowns.dev")34impl User {5 fn greet(self) -> string => "Hi, I am " + self.name6}78enum Status { Active, Inactive, Pending(string) }9let s = Status.Pending("review")1011match s {12 Status.Active => println("live")13 Status.Pending(m) => println("Pending: " + m)14 _ => println("off")15}
4.5 Traits & Generics
kkg1trait Drawable {2 fn draw(self)3 fn area(self) -> float4}56impl Drawable for Circle {7 fn draw(self) { println("Circle r=" + self.radius) }8 fn area(self) -> float => 3.14159 * self.radius * self.radius9}1011fn first<T>(list: [T]) -> ?T {12 if list.len() == 0 { return nil }13 return list[0]14}
4.6 Error Handling
kkg1fn divide(a: float, b: float) -> Result<float> {2 if b == 0.0 { return Err("division by zero") }3 return Ok(a / b)4}56match divide(10.0, 2.0) {7 Ok(v) => println(v)8 Err(msg) => println("Error: " + msg)9}1011// ? operator — propagate error early12fn calc(x: float) -> Result<float> {13 let a = divide(x, 2.0)?14 return Ok(a * 3.0)15}
4.7 Async & Concurrency
kkg1async fn fetchData(url: string) -> string {2 let res = await http.get(url)3 return res.body4}56// Parallel tasks7let task1 = spawn fetchUsers()8let task2 = spawn fetchProducts()9let (users, products) = await join(task1, task2)1011// Channels12let ch = channel<string>()13spawn { ch.send("hello") }14let msg = ch.receive()
4.8 Memory & Ownership
Each value has exactly one owner. The borrow checker enforces safety at compile time — no garbage collector.
kkg1let s1 = "hello"2let s2 = s1 // s1 MOVED to s23// println(s1) // ERROR: use after move45let s2 = s1.clone() // explicit copy — both valid67fn print_len(s: &string) { println(s.len()) }8let name = "Klang"9print_len(&name) // borrow — name still valid
4.9 Modules
kkg1use std::io2use std::math::{ sqrt, PI }3use ./services::user::{ UserService }4use @klowns/auth::{ jwt }56pub fn createUser(name: string) -> User { ... }7pub const VERSION: string = "1.0.0"
#5. Web Server
Klang has first-class web server syntax via the app block. No external framework is needed.
kkg1app server {2 port: 808034 route "/" {5 return json({ message: "Klang is alive!", version: "1.0.0" })6 }78 route "/health" {9 return json({ status: "ok", uptime: sys.uptime() })10 }1112 route POST "/users" {13 let body = request.json()14 let user = db.create(body)15 return json({ created: true, id: user.id })16 }17}
#6. AI & Machine Learning
Klang is the first general-purpose language with AI primitives as core syntax — not a library.
kkg1ai model VisionAI {2 dataset: load("./data/images")3 architecture: CNN4 epochs: 505 learning_rate: 0.0016 train: auto7}89fn main() {10 let model = ai.load(VisionAI)11 let result = model.predict("cat.jpg")12 println("Label: " + result.label)13 println("Confidence: " + result.confidence)14}
#7. Standard Library
7.1 std::io
| Function | Description |
|---|---|
io.read(path) | Read file as string |
io.write(path, content) | Write string to file |
io.append(path, content) | Append to file |
io.exists(path) | Check if path exists → bool |
io.delete(path) | Delete file or empty dir |
io.list_dir(path) | List directory → [string] |
io.make_dir(path) | Create directory (recursive) |
io.read_lines(path) | Read as array of lines |
7.2 std::math
| Function / Constant | Description |
|---|---|
math.sqrt(x) | Square root |
math.pow(x, n) | Power: x^n |
math.abs(x) | Absolute value |
math.min/max(a, b) | Minimum / Maximum |
math.floor/ceil(x) | Round down / up |
math.round(x) | Round to nearest integer |
math.sin/cos(x) | Trigonometric functions |
math.log/log2(x) | Natural / base-2 logarithm |
math.PI | π = 3.14159265358979... |
math.E | e = 2.71828182845904... |
7.3 std::http
| Function | Description |
|---|---|
http.get(url) | HTTP GET → Response |
http.post(url, body) | HTTP POST with JSON body |
http.put(url, body) | HTTP PUT |
http.delete(url) | HTTP DELETE |
response.json() | Parse body as JSON |
response.text() | Get body as string |
response.status | HTTP status code (int) |
7.4 std::json
kkg1let obj = json.parse('{"name":"Klang"}')2let name = obj["name"]3let text = json.stringify(obj)4let pretty = json.pretty(obj)
#8. CLI Reference
| Command | Description |
|---|---|
klang run file.kkg | Run a .kkg file directly |
klang --compile file.kkg | Compile to C source |
klang --llvm file.kkg | Compile to LLVM IR |
klang --wasm file.kkg | Compile to WebAssembly (.wat) |
klang --check file.kkg | Type-check only |
klang fmt | Format all .kkg files |
klang lint | Lint and report warnings |
klang test | Run test suite |
klang repl | Start interactive REPL |
klang --version | Show version information |
8.1 REPL Commands
| Command | Description |
|---|---|
:help | Show all REPL commands |
:quit / :exit | Exit the REPL |
:type <expr> | Show inferred type of expression |
:load file.kkg | Load and evaluate a file |
:reset | Reset all bindings |
:multiline | Toggle multi-line input mode |
#9. kpkg — Package Manager
9.1 Commands
| Command | Description |
|---|---|
kpkg init <name> | Create new Klang project |
kpkg add <pkg> | Add a dependency |
kpkg remove <pkg> | Remove a dependency |
kpkg install | Install all from klang.toml |
kpkg build | Build the project |
kpkg run | Build and run |
kpkg test | Run tests |
kpkg publish | Publish to registry |
kpkg search <query> | Search the package registry |
9.2 klang.toml
toml1[project]2name = "my-app"3version = "0.1.0"45[dependencies]6klang-web = "^1.0.0"7"@klowns/auth" = "^2.1.0"89[build]10target = "native" # native | wasm | c11optimize = "release" # debug | release
9.3 Built-in Packages
| Package | Description |
|---|---|
std::http | HTTP client & server |
std::json | JSON parsing & generation |
std::io | File & stream I/O |
std::math | Math functions & constants |
std::crypto | Hashing, encryption, JWT |
std::db | Database abstraction layer |
std::log | Structured logging |
std::cli | CLI argument parsing |
std::async | Async runtime utilities |
std::web | Full-stack web framework |
std::ai | AI & ML primitives |
std::test | Testing framework |
#10. Compiler Architecture
10.1 Compilation Pipeline
Source (.kkg)
|
V Lexer -- tokenize source into tokens
|
V Parser -- Pratt parser, 10 precedence levels -> AST
|
V Type Checker -- ownership, borrow checker, generics
|
+---> C Codegen -> .c -> gcc -> native binary
|
+---> LLVM Codegen -> .ll -> llc -> native binary
|
+---> WASM Codegen -> .wat -> browser / edge compute
10.2 Self-Hosting Bootstrap
| Stage | Compiler | Input | Output | Status |
|---|---|---|---|---|
| Stage 0 | Rust (last time) | bootstrap/*.kkg | klangc.c | Done |
| Stage 1 | gcc | klangc.c + cruntime/ | klangc binary | Done |
| Stage 2 | klangc (Klang!) | bootstrap/*.kkg | klangc_v2.c | Done |
| Verify | diff | v1.c vs v2.c | IDENTICAL | Done 🐉 |
10.3 C Runtime (cruntime/)
| File | Provides |
|---|---|
runtime.h / .c | Arena allocator, KlangArray, 20+ string ops, I/O |
klang_stdlib.h / .c | Math, file I/O, path, JSON, base64, SHA... |
klang_async.h / .c | Cross-platform threads, channels, mutexes |
test_runtime.c | 93-assertion test suite for the entire C runtime |
Makefile | Cross-platform build — gcc only, no Rust required |
Phase 1 Complete: 93/93 tests passed with gcc 15.2.0 on Windows. C Runtime is fully operational. Rust is no longer needed at runtime.
#11. Error Reference
Klang uses Rust-style error messages with ANSI colors, source context, column underlines, and helpful notes.
11.1 Error Format
error[E0001]: use of moved value: `name`
--> src/main.kkg:12:10
|
11 | let s2 = name
| ---- value moved here
12 | println(name)
| ^^^^ value used after move
|
= note: move occurs because `name` has type `string`
= help: use `name.clone()` to make an explicit copy
11.2 Error Code Categories
| Range | Category |
|---|---|
E0001 - E0099 | Syntax errors |
E0100 - E0199 | Type errors |
E0200 - E0299 | Ownership & borrow checker |
E0300 - E0399 | Module & import errors |
E0400 - E0499 | Trait & impl errors |
E0500 - E0599 | Generic type errors |
E0600 - E0699 | Async / concurrency errors |
E0700 - E0799 | Pattern match errors |
E9000 - E9999 | Internal compiler errors (ICE) |
#12. Development Roadmap
| Phase | Name | Status |
|---|---|---|
| Phase 0 | Bootstrap Compiler (Rust) | Done |
| Phase 1 | Core Language + Stdlib | Done |
| Phase 2 | Compiler Backends (LLVM, C, WASM) | Done |
| Phase 3 | Self-Hosting Bootstrap | Done |
| Phase 4 | Enterprise Features | Done |
| Phase 5 | Production Completion | Done |
| Phase 6 | Completion (All Levels) | Done |
| Phase 7 | Platform & Ecosystem | Done |
| Phase 2B | Remove Rust — gcc-only install | In Progress |
| Next | Aello (IDE) | Planned |
| Future | Arkai AI, Alfa Git, Marisea Cloud, Ocean OS | Planned |