DEV Community

Cover image for Learn KingCobra in 30 minutes: a hands-on tutorial
Divyanshu Sinha
Divyanshu Sinha

Posted on

Learn KingCobra in 30 minutes: a hands-on tutorial

This tutorial takes you from "nothing installed" to writing, testing and organising real KingCobra programs. Every example below was run on KingCobra 1.0.0, and the output shown is the real output.

You don't need to know C or systems programming. If you've used Python or JavaScript, most of it will feel familiar. The new parts are explicit memory and pointers, and the language checks those for you, so mistakes become clear errors instead of crashes.

1. Install and say hello

KingCobra runs on Linux, macOS and Windows, and the same source file runs unchanged on all three. Pick the install that matches your machine.

Windows (x64; ARM machines run it through the built-in emulation)

# Chocolatey (PowerShell as Administrator)
choco install kingcobra

# Scoop
scoop install https://github.com/DivyanshuSinha136/kingcobra/releases/latest/download/kingcobra.json

# or PowerShell with no administrator rights
irm https://github.com/DivyanshuSinha136/kingcobra/releases/latest/download/install.ps1 | iex
Enter fullscreen mode Exit fullscreen mode

Linux and macOS

curl -fsSL https://github.com/DivyanshuSinha136/kingcobra/releases/latest/download/install.sh | sh
Enter fullscreen mode Exit fullscreen mode

The installer picks the right package for your machine and verifies its SHA-256 checksum: a .deb on Debian and Ubuntu, an .rpm on Fedora and RHEL-family systems, and a tarball into ~/.local on macOS and on Alpine and other musl systems. If there is no prebuilt package for your CPU (a Raspberry Pi Zero, for example), it compiles KingCobra on your machine, which needs a C compiler and make.

From source (any platform with make and a C compiler; on Windows use MSYS2 / MinGW-w64)

git clone https://github.com/DivyanshuSinha136/KingCobra
cd KingCobra
make
./kingcobra repl
Enter fullscreen mode Exit fullscreen mode

After an installer or package manager, open a new terminal (so your PATH is refreshed) and check it. If you built from source, run ./kingcobra from the build folder instead, or sudo make install to put it on your PATH:

kingcobra version
kingcobra repl
Enter fullscreen mode Exit fullscreen mode

To update, run choco upgrade kingcobra or scoop update kingcobra on Windows, or run the install script again on Linux and macOS.

The REPL keeps your definitions, continues unclosed brackets on the next line, and _ is the last result:

>>> let x = 10
>>> x * 3
30
>>> _ + 1
31
Enter fullscreen mode Exit fullscreen mode

Tip for Windows: if non-ASCII text looks garbled in cmd.exe (for example an em dash printing as ΓÇö), the console is using an old code page. Run chcp 65001 first, or use Windows Terminal, which uses UTF-8 by default.

Now a real file. Save this as hello.kc:

fn main() {
    print("Hello, KingCobra!");
}
Enter fullscreen mode Exit fullscreen mode
kingcobra run hello.kc
Enter fullscreen mode Exit fullscreen mode
Hello, KingCobra!
Enter fullscreen mode Exit fullscreen mode

Programs start at fn main. Files use the .kc extension. The command is the same in PowerShell, Terminal, bash or zsh: kingcobra run hello.kc.

2. Values and variables

fn main() {
    let name = "Ada";            // immutable
    var score = 10;              // mutable
    const LIMIT = 100;           // same as let, but reads as intent
    score += 5;
    print(f"{name} has {score} of {LIMIT}");

    let big = 9007199254740993;  // exact 64-bit integers
    print(big + 1);
    print(7 / 2, 8 / 2, idiv(7, 2), 7 % 3);
    print('a', len("h\u{e9}llo"), typeof(3.5), typeof(null));
    print(0xFF, 0b1010, 1_000_000);
}
Enter fullscreen mode Exit fullscreen mode
Ada has 15 of 100
9007199254740994
3.5 4 3 1
97 6 float null
255 10 1000000
Enter fullscreen mode Exit fullscreen mode

Things to notice:

  • let is immutable, var is mutable. Type annotations (let x: int = 5) are optional.
  • Integers are exact 64-bit. 9007199254740993 + 1 is correct, where a double-based language would round it. _ separates digits and 0x / 0b literals work.
  • / returns an int when the division is exact (8 / 2 is 4) and a float otherwise (7 / 2 is 3.5). idiv is floor division.
  • A character literal like 'a' is an int holding the Unicode code point (97).
  • Strings are UTF-8 and len counts bytes. "h\u{e9}llo" is 6 bytes because é (written here as the escape \u{e9}) takes two. Save your .kc files as UTF-8 so text typed directly into a string gets the same result on every platform.
  • f-strings evaluate any expression inside {...}. A plain string never interpolates, so JSON text with braces is safe.

3. Control flow

enum Level { Low, Mid = 5, High }

fn describe(n: int) -> string {
    return match (n) {
        0 => "zero",
        1 | 2 | 3 => "few",
        _ => "many",
    };
}

fn main() {
    for (i in 0..4) { print(i, describe(i)); }

    var total = 0;
    var i = 0;
    while (i < 5) { total += i; i += 1; }
    print("total", total);

    outer: for (a in 0..3) {
        for (b in 0..3) {
            if (b == 2) { continue outer; }
            if (a == 2) { break outer; }
            print("pair", a, b);
        }
    }
    print(Level.High, describe(Level.Mid));
}
Enter fullscreen mode Exit fullscreen mode
0 zero
1 few
2 few
3 few
total 10
pair 0 0
pair 0 1
pair 1 0
pair 1 1
6 many
Enter fullscreen mode Exit fullscreen mode
  • 0..4 is a half-open range (0, 1, 2, 3). You can also loop over arrays, strings and objects.
  • match is an expression. Arms are checked top to bottom, | lets several patterns share an arm, and _ is the catch-all. With no match and no _, it's a runtime error and never a silent null.
  • Labeled loops let you break outer and continue outer.
  • Enums are int constants: Level.Low is 0, Level.Mid is 5 and Level.High follows at 6.

4. Functions and closures

fn area(w: int, h: int = w) -> int { return w * h; }
fn sum(...xs: int) -> int {
    var t = 0;
    for (x in xs) { t += x; }
    return t;
}
fn make_counter() -> fn {
    var n = 0;
    fn next() -> int { n += 1; return n; }
    return next;
}

fn main() {
    print(area(3), area(3, 5), sum(1, 2, 3, 4));
    let c = make_counter();
    print(c(), c(), c());
    let double = fn(x: int) -> int { return x * 2; };
    print(double(21));
}
Enter fullscreen mode Exit fullscreen mode
9 15 10
1 2 3
42
Enter fullscreen mode Exit fullscreen mode
  • A default value is evaluated at each call and may use earlier parameters (h defaults to w).
  • ...xs collects extra arguments into an array.
  • Closures capture variables. make_counter returns a function that remembers its own n.
  • Functions are values, so fn(x: int) -> int { ... } works anywhere an expression does.

5. Arrays, objects and strings

fn main() {
    let nums = [5, 3, 8, 1, 9];
    let [first, ...rest] = nums;
    print(first, rest, nums[1..3], len(nums));
    print(nums.map(fn(x) -> int { return x * x; }));
    print(nums.filter(fn(x) -> bool { return x > 4; }));
    print(nums.reduce(fn(a, b) -> int { return a + b; }, 0));
    print(sorted(nums), nums);
    print(8 in nums, "ell" in "hello");

    let user = { name: "ada", langs: ["c", "kc"] };
    user["age"] = 36;
    print(user.name, user.keys(), len(user));
    for (k, v in user) { print(k, v); }
    print("  Hello  ".trim().upper(), "a,b,c".split(","));
}
Enter fullscreen mode Exit fullscreen mode
5 [3, 8, 1, 9] [3, 8] 5
[25, 9, 64, 1, 81]
[5, 8, 9]
26
[1, 3, 5, 8, 9] [5, 3, 8, 1, 9]
true true
ada [name, langs, age] 3
name ada
langs [c, kc]
age 36
HELLO [a, b, c]
Enter fullscreen mode Exit fullscreen mode
  • Destructuring with let [first, ...rest] = nums; splits an array into a head and a tail.
  • Slicing nums[1..3] copies a range. Out-of-range bounds are an error and are never silently clamped.
  • map, filter, reduce, sort, find, any, all and more are built in. sorted(a) returns a sorted copy, while a.sort() sorts in place.
  • in tests membership in arrays, substrings in strings, and keys in objects.
  • Objects like { name: "ada" } are open: you can add keys with user["age"] = 36, and a missing key reads as null with index syntax.
  • Strings have upper, lower, trim, split, replace, pad_left, repeat and more.

6. Structs, enums and impl

struct Point { x: int, y: int }

impl Point {
    fn len2(self) -> int { return self.x * self.x + self.y * self.y; }
    fn origin() -> Point { return Point { x: 0, y: 0 }; }
}

impl string {
    fn shout(self) -> string { return self.upper() + "!"; }
}

fn main() {
    let p = Point { x: 3, y: 4 };
    print(p.len2(), Point.origin().len2());
    let q = p;           // structs are reference types
    q.x = 10;
    print(p.x);
    print("hello".shout());
}
Enter fullscreen mode Exit fullscreen mode
25 0
10
HELLO!
Enter fullscreen mode Exit fullscreen mode
  • A function whose first parameter is self is a method (p.len2()). Any other function in an impl is called on the type (Point.origin()).
  • impl also works on built-in types. impl string { ... } added .shout() to every string.
  • Structs are reference types. let q = p; makes q another name for the same struct, so changing q.x changed p.x. The same is true of arrays.
  • Struct literals must provide exactly the declared fields, and the static checker verifies each field's type.

7. Errors and defer

fn parse_age(text: string) -> int {
    let n = int(text);
    if (n < 0) { throw error("age cannot be negative"); }
    return n;
}

fn main() {
    for (text in ["30", "-4"]) {
        try { print("age", parse_age(text)); }
        catch (e) { print("rejected:", e.message); }
    }

    try { let a = [1, 2, 3]; print(a[10]); }
    catch (e) { print("caught:", e.message); }

    fn demo() {
        defer print("cleanup runs last");
        print("working");
        throw "boom";
    }
    try { demo(); } catch (e) { print("error:", e); }
}
Enter fullscreen mode Exit fullscreen mode
age 30
rejected: age cannot be negative
caught: index 10 out of bounds (len 3)
working
cleanup runs last
error: boom
Enter fullscreen mode Exit fullscreen mode
  • Every runtime error is catchable, including out-of-bounds indexing. Inside catch (e), runtime errors give you e.message, e.file, e.line and e.col.
  • You can throw any value (a string, a number, an object). error("text") builds a standard error object.
  • defer runs when the block exits, including while an error unwinds, in reverse order. It's the main tool for cleanup.
  • An uncaught error prints the message with the source line and a caret, and exits with status 65.

8. Memory and pointers

This is what makes KingCobra a systems language. There is no garbage collector. You free what you allocate, and the runtime catches the classic mistakes.

fn checksum(n: int) -> int {
    let p = alloc(n);
    defer free(p);               // runs on every exit path
    memset(p, 1, n);
    return p[0] + p[n - 1];
}

fn main() {
    print(checksum(16));

    let a = [1, 2, 3];
    let b = a;                   // same array, two names
    free(a);
    try { print(b[0]); }
    catch (e) { print("caught:", e.message); }

    let buf = alloc(4);
    try { buf[10] = 1; }
    catch (e) { print("caught:", e.message); }
    free(buf);

    var x = 41;
    let p = &x;                  // &x of a var is writable
    *p += 1;
    print(x);
}
Enter fullscreen mode Exit fullscreen mode
2
caught: use after free (this array was freed)
caught: pointer write of 1 byte(s) at offset 10 is out of bounds (valid range 0..4 of allocation #2)
42
Enter fullscreen mode Exit fullscreen mode
  • alloc(n) gives you n bytes. free releases memory, and defer free(p) guarantees it happens on every path out of the function, including errors.
  • Use after free is an error, not silent corruption. free(a) freed the array that b also points to, and reading through b was caught.
  • Pointers are bounds-checked. Writing at offset 10 of a 4-byte allocation raised a precise error.
  • &x, *p and p->field work like C. Pointers into KingCobra variables, array elements and struct fields are all checked.

Double free is also an error, and you can ask KingCobra to report what you forgot to free. Given prog.kc:

fn main() {
    let a = alloc(32);
    print("allocated, never freed");
}
Enter fullscreen mode Exit fullscreen mode
kingcobra --leaks prog.kc
Enter fullscreen mode Exit fullscreen mode
allocated, never freed
kingcobra: memory report
  leaked blocks (allocated, never freed):
          32 bytes  alloc()  at prog.kc:2:13
  total: 1 block(s), 32 byte(s)
Enter fullscreen mode Exit fullscreen mode

Raw machine addresses (from FFI, or forged from an integer) still exist, but dereferencing them needs an unsafe { } block. Anything that could actually corrupt memory has to be marked.

Learn more in docs/MEMORY.md and docs/POINTERS.md in the repo.

9. Modules and the standard library

Split code into files and import them. Given mathlib.kc:

/// Square of a number.
fn square(x: int) -> int { return x * x; }
fn cube(x: int) -> int { return x * x * x; }
Enter fullscreen mode Exit fullscreen mode

you can use it next to the standard library:

import std.json;
import std.regx;
import "mathlib.kc" as m;

fn main() {
    print(m.square(7), m.cube(3));

    let doc = json.parse("{\"name\":\"Ada\",\"langs\":[\"c\",\"kc\"],\"age\":36}");
    doc["age"] = doc["age"] + 1;
    print(doc.name, doc.langs, doc.age);
    print(json.stringify(doc));

    print(regx.test("^\\d+$", "12345"));
    print(regx.find("\\d+", "order #4821 shipped"));
    print(regx.split("\\s*,\\s*", "a , b,c"));
}
Enter fullscreen mode Exit fullscreen mode
49 27
Ada [c, kc] 37
{"name":"Ada","langs":["c","kc"],"age":37}
true
4821
[a, b, c]
Enter fullscreen mode Exit fullscreen mode
  • import "file.kc" as m brings in your own files under a name. import std.json; loads a standard module.
  • json.parse returns an open object, which you read with doc.name or doc["name"].
  • Run kingcobra modules to list all 21 standard modules: system, memory, network, http, rhex, io, vector, regx, nlp, nn, gui, mmio, acpi, json, csv, fbin, mmu, game, ascii_screen, tts and music_note.
  • Most modules behave the same everywhere. The ones that talk to the operating system use the native facility on each platform: std.gui uses X11 on Linux and Win32 on Windows, with a headless mode for servers and tests, and std.system reports the OS, CPU and memory of the machine it runs on.
  • Imports use forward slashes on every platform, including Windows, so import "../main.kc" as app; works the same everywhere.
  • The examples/ folder has a runnable program for each one.

10. Build a small program: word frequency

Putting it together:

/// Count how often each word appears.
fn word_counts(text: string) -> object {
    let counts = {};
    for (w in text.lower().split(" ")) {
        if (w == "") { continue; }
        counts[w] = (counts[w] ?? 0) + 1;
    }
    return counts;
}

fn main() {
    let text = "the quick brown fox jumps over the lazy dog the end";
    let counts = word_counts(text);
    let rows = counts.items();                       // [[word, count], ...]
    rows.sort(fn(a, b) -> int { return b[1] - a[1]; });
    for (row in rows[..3]) {
        print(row[0].pad_right(6), row[1]);
    }
}
Enter fullscreen mode Exit fullscreen mode
the    3
quick  1
brown  1
Enter fullscreen mode Exit fullscreen mode

?? supplies a default when a key is missing, items() turns an object into [key, value] pairs, and sort takes a comparator that returns a negative, zero or positive number. The /// comment above word_counts is a doc comment: help(word_counts) prints it.

11. Tooling: projects, tests, type checks

Create a project:

kingcobra new myapp
Enter fullscreen mode Exit fullscreen mode
  created  myapp/main.kc
  created  myapp/tests/test_main.kc
  created  myapp/README.md
  created  myapp/.gitignore
Enter fullscreen mode Exit fullscreen mode

The scaffold includes a function and a test:

// tests/test_main.kc
import "../main.kc" as app;

fn test_greet() {
    assert_eq(app.greet("KingCobra"), "Hello, KingCobra!");
}
Enter fullscreen mode Exit fullscreen mode

A test is any global fn test_...(). It passes if it returns and fails if an assert or assert_eq fails.

cd myapp
kingcobra test
Enter fullscreen mode Exit fullscreen mode
tests/test_main.kc
  ok   test_greet

1 passed, 0 failed  (0 ms)
Enter fullscreen mode Exit fullscreen mode

Useful options: kingcobra test -k parse runs tests whose name contains "parse", -l lists them, and -x -q stops at the first failure.

KingCobra also has a static type checker. It runs before your program does, and you can run it on its own:

fn double(n: int) -> int { return n * 2; }
fn main() {
    let s: string = "hi";
    print(double(s));
}
Enter fullscreen mode Exit fullscreen mode
kingcobra check bad.kc
Enter fullscreen mode Exit fullscreen mode
bad.kc:4:18: error: 'double' argument 1: expected int, got string
    4 |     print(double(s));
      |                  ^
1 of 1 file(s) have errors
Enter fullscreen mode Exit fullscreen mode

The checker is deliberately permissive, so it catches clear mistakes without getting in your way. Skip it with --no-typecheck.

12. Speed

KingCobra is a tree-walking interpreter with a closure JIT. After a function has been called 50 times, if it uses only integers (arithmetic, comparisons, if/while, self-recursion), it's compiled to x86-64 machine code. A recursive fib(32) runs in about 0.025 s with the JIT and 0.34 s with --no-jit on a typical x86-64 machine (your numbers will differ). Results are identical either way.

The JIT covers a specific int-only shape and only exists on x86-64, which includes the Windows x64 build. On other CPUs (Apple Silicon, ARM and RISC-V boards) everything runs in the interpreter, which is also correct but slower. Check what your build has with kingcobra info. For a faster interpreter overall, build from source with make pgo.

Where to go next

  • The expert guide (PDF): https://github.com/DivyanshuSinha136/KingCobra/blob/main/tutorial/KingCobra_Complete_Expert_Guide.pdf
  • Language reference: docs/LANGUAGE.md and the formal grammar in docs/GRAMMAR.md
  • Examples: the examples/ folder, one runnable program per module, plus larger programs in examples/showcase
  • Tools: kcide (terminal IDE with a debugger), kcc (native compiler), kasm (assembler)
  • Platforms and packaging: docs/PLATFORMS.md and docs/PACKAGING.md
  • Roadmap and stability: docs/ROADMAP.md and docs/STABILITY.md

Repo: https://github.com/DivyanshuSinha136/KingCobra

If you build something, or hit a bug or a confusing error message, please open an issue. Feedback on the language design is welcome too.

Top comments (0)