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

ProductRoleStatus
KlangCore programming language (.kkg)✅ Complete
AelloIntegrated Development Environment→ Next
Arkai AIAI assistant built with Klang AI primitivesPlanned
Alfa GitVersion control platformPlanned
Marisea CloudCloud deployment & serverless runtimePlanned
Ocean OSOperating system kernel written in KlangPlanned

#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

bash
1curl -sSf https://klang.kkg/install.sh | sh

Windows

bash
1winget install KaiserKlowns.Klang

Build from Source (gcc only, no Rust needed)

bash
1git clone https://github.com/kaiser-klowns/klang
2cd klang
3make bootstrap # gcc only Rust not required
4./klangc --version
5# 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

kkg
1// hello.kkg
2fn main() {
3 println("Hello Kaiser Klowns!")
4}
bash
1klang run hello.kkg
2# Hello Kaiser Klowns!

3.2 New Project

bash
1kpkg init my-app
2cd my-app
3klang run main.kkg

3.3 Project Structure

bash
1my-app/
2 main.kkg # entry point
3 klang.toml # project manifest
4 klang.lock # dependency lock file
5 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.

kkg
1let name = "Klang" // immutable, type inferred
2let mut count = 0 // mutable
3const MAX: int = 1024 // compile-time constant
4let age: int = 25 // explicit type
5let ratio: float = 3.14
6let active: bool = true
7let opt: ?int = nil // optional (nullable)

Built-in Types

TypeDescriptionExample
int64-bit signed integer42, -7, 0
float64-bit floating point3.14, -0.5
boolBoolean valuetrue, false
stringUTF-8 string"hello", "🐉"
charSingle UTF-8 character'a', '🐉'
[T]Dynamic array of type T[1, 2, 3]
map[K]VHashMap from K to Vmap["a": 1]
?TOptional / Nullable Tnil or value
(A, B)Tuple(1, "ok")

4.2 Functions

kkg
1fn add(a: int, b: int) -> int { return a + b }
2
3// Arrow shorthand
4fn square(x: int) -> int => x * x
5
6// Async function
7async fn fetchUser(id: int) -> Result<User> {
8 let res = await http.get("/users/" + id)
9 return Ok(res.json())
10}
11
12// Lambda / higher-order
13let doubled = [1,2,3,4,5].map(x => x * 2) // [2,4,6,8,10]

4.3 Control Flow

kkg
1if score >= 90 { println("A") }
2else if score >= 80 { println("B") }
3else { println("C") }
4
5for i in 0..10 { println(i) }
6for item in ["a","b","c"] { println(item) }
7while count > 0 { count -= 1 }
8
9match status {
10 200 => println("OK")
11 404 => println("Not Found")
12 _ => println("Other: " + status)
13}

4.4 Structs & Enums

kkg
1struct User { name: string, age: int, email: string }
2let user = User("Alice", 25, "alice@klowns.dev")
3
4impl User {
5 fn greet(self) -> string => "Hi, I am " + self.name
6}
7
8enum Status { Active, Inactive, Pending(string) }
9let s = Status.Pending("review")
10
11match s {
12 Status.Active => println("live")
13 Status.Pending(m) => println("Pending: " + m)
14 _ => println("off")
15}

4.5 Traits & Generics

kkg
1trait Drawable {
2 fn draw(self)
3 fn area(self) -> float
4}
5
6impl Drawable for Circle {
7 fn draw(self) { println("Circle r=" + self.radius) }
8 fn area(self) -> float => 3.14159 * self.radius * self.radius
9}
10
11fn first<T>(list: [T]) -> ?T {
12 if list.len() == 0 { return nil }
13 return list[0]
14}

4.6 Error Handling

kkg
1fn divide(a: float, b: float) -> Result<float> {
2 if b == 0.0 { return Err("division by zero") }
3 return Ok(a / b)
4}
5
6match divide(10.0, 2.0) {
7 Ok(v) => println(v)
8 Err(msg) => println("Error: " + msg)
9}
10
11// ? operator — propagate error early
12fn calc(x: float) -> Result<float> {
13 let a = divide(x, 2.0)?
14 return Ok(a * 3.0)
15}

4.7 Async & Concurrency

kkg
1async fn fetchData(url: string) -> string {
2 let res = await http.get(url)
3 return res.body
4}
5
6// Parallel tasks
7let task1 = spawn fetchUsers()
8let task2 = spawn fetchProducts()
9let (users, products) = await join(task1, task2)
10
11// Channels
12let 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.

kkg
1let s1 = "hello"
2let s2 = s1 // s1 MOVED to s2
3// println(s1) // ERROR: use after move
4
5let s2 = s1.clone() // explicit copy both valid
6
7fn print_len(s: &string) { println(s.len()) }
8let name = "Klang"
9print_len(&name) // borrow name still valid

4.9 Modules

kkg
1use std::io
2use std::math::{ sqrt, PI }
3use ./services::user::{ UserService }
4use @klowns/auth::{ jwt }
5
6pub 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.

kkg
1app server {
2 port: 8080
3
4 route "/" {
5 return json({ message: "Klang is alive!", version: "1.0.0" })
6 }
7
8 route "/health" {
9 return json({ status: "ok", uptime: sys.uptime() })
10 }
11
12 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.

kkg
1ai model VisionAI {
2 dataset: load("./data/images")
3 architecture: CNN
4 epochs: 50
5 learning_rate: 0.001
6 train: auto
7}
8
9fn 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

FunctionDescription
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 / ConstantDescription
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.Ee = 2.71828182845904...

7.3 std::http

FunctionDescription
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.statusHTTP status code (int)

7.4 std::json

kkg
1let obj = json.parse('{"name":"Klang"}')
2let name = obj["name"]
3let text = json.stringify(obj)
4let pretty = json.pretty(obj)

#8. CLI Reference

CommandDescription
klang run file.kkgRun a .kkg file directly
klang --compile file.kkgCompile to C source
klang --llvm file.kkgCompile to LLVM IR
klang --wasm file.kkgCompile to WebAssembly (.wat)
klang --check file.kkgType-check only
klang fmtFormat all .kkg files
klang lintLint and report warnings
klang testRun test suite
klang replStart interactive REPL
klang --versionShow version information

8.1 REPL Commands

CommandDescription
:helpShow all REPL commands
:quit / :exitExit the REPL
:type <expr>Show inferred type of expression
:load file.kkgLoad and evaluate a file
:resetReset all bindings
:multilineToggle multi-line input mode

#9. kpkg — Package Manager

9.1 Commands

CommandDescription
kpkg init <name>Create new Klang project
kpkg add <pkg>Add a dependency
kpkg remove <pkg>Remove a dependency
kpkg installInstall all from klang.toml
kpkg buildBuild the project
kpkg runBuild and run
kpkg testRun tests
kpkg publishPublish to registry
kpkg search <query>Search the package registry

9.2 klang.toml

toml
1[project]
2name = "my-app"
3version = "0.1.0"
4
5[dependencies]
6klang-web = "^1.0.0"
7"@klowns/auth" = "^2.1.0"
8
9[build]
10target = "native" # native | wasm | c
11optimize = "release" # debug | release

9.3 Built-in Packages

PackageDescription
std::httpHTTP client & server
std::jsonJSON parsing & generation
std::ioFile & stream I/O
std::mathMath functions & constants
std::cryptoHashing, encryption, JWT
std::dbDatabase abstraction layer
std::logStructured logging
std::cliCLI argument parsing
std::asyncAsync runtime utilities
std::webFull-stack web framework
std::aiAI & ML primitives
std::testTesting 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

StageCompilerInputOutputStatus
Stage 0Rust (last time)bootstrap/*.kkgklangc.cDone
Stage 1gccklangc.c + cruntime/klangc binaryDone
Stage 2klangc (Klang!)bootstrap/*.kkgklangc_v2.cDone
Verifydiffv1.c vs v2.cIDENTICALDone 🐉

10.3 C Runtime (cruntime/)

FileProvides
runtime.h / .cArena allocator, KlangArray, 20+ string ops, I/O
klang_stdlib.h / .cMath, file I/O, path, JSON, base64, SHA...
klang_async.h / .cCross-platform threads, channels, mutexes
test_runtime.c93-assertion test suite for the entire C runtime
MakefileCross-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

RangeCategory
E0001 - E0099Syntax errors
E0100 - E0199Type errors
E0200 - E0299Ownership & borrow checker
E0300 - E0399Module & import errors
E0400 - E0499Trait & impl errors
E0500 - E0599Generic type errors
E0600 - E0699Async / concurrency errors
E0700 - E0799Pattern match errors
E9000 - E9999Internal compiler errors (ICE)

#12. Development Roadmap

PhaseNameStatus
Phase 0Bootstrap Compiler (Rust)Done
Phase 1Core Language + StdlibDone
Phase 2Compiler Backends (LLVM, C, WASM)Done
Phase 3Self-Hosting BootstrapDone
Phase 4Enterprise FeaturesDone
Phase 5Production CompletionDone
Phase 6Completion (All Levels)Done
Phase 7Platform & EcosystemDone
Phase 2BRemove Rust — gcc-only installIn Progress
NextAello (IDE)Planned
FutureArkai AI, Alfa Git, Marisea Cloud, Ocean OSPlanned
Anthovai — Intelligence, Engineered.