Forja in one page

Forja is a compiled programming language. This page is a short reference: what the language is, its syntax, twelve complete programs with the output the compiler really prints, the command line, error codes, build targets and known limits.

What Forja is

Forja is a general-purpose compiled language. In short: errors are values, memory is explicit, there are units of measure and value ranges, there is no garbage collector, and the syntax is small, designed for AI agents as well as people.

The compiler is written in Forja. It generates native x64 code (.exe, ELF and DLL), WebAssembly (WASI), Android ARM64 and iOS ARM64 binaries. Source files use the .fj extension. At the time of writing the compiler version is 0.48.0 and the language is v1.13.

Syntax

Twelve programs with real output

Each program below is complete. The output shown after it is what forja run printed when these exact files were compiled and run on Windows x64. Nothing was edited by hand.

1. Default and named arguments

proc double(n: int, times: int = 2) -> int {
    return n * times
}

proc main() {
    print("Hello, Forja!")
    print(double(21))
    print(double(7, times = 3))
}
Hello, Forja!
42
21

2. Errors as values

enum SearchError { not_found }

proc find(id: i32) -> i32 ! SearchError {
    if id == 0 {
        return SearchError.not_found
    }
    return id * 10
}

// "try" passes the error to the caller, which must return the same error type
proc double_of_found(id: i32) -> i32 ! SearchError {
    let value = try find(id)
    return value * 2
}

proc main() {
    // "or_else" gives a default value only when there is an error
    print(find(3) or_else -1)
    print(find(0) or_else -1)

    // "switch" on a result must handle both the value and the error
    switch r in double_of_found(4) {
    case i32:
        print(r)
    case SearchError:
        print("not found")
    }
}
30
-1
80

3. Units of measure and value ranges

unit Meters: f32
unit Seconds: f32
unit MetersPerSecond = Meters / Seconds

struct Target {
    health: i32 in 0..=100 = 100
    level: int in 1..<10 = 1
}

proc main() {
    let distance: Meters = 10.0
    let elapsed: Seconds = 2.0
    let speed: MetersPerSecond = distance / elapsed
    print(speed as int)

    let target = Target{health = 55, level = 9}
    print(target.health)
    print(target.level)
    // distance + elapsed is a compile error (mixed units)
    // a value outside 0..=100 stops a dev build with a runtime error
}
5
55
9

4. Loops, defer and built-in tests

proc sum_up_to(n: int) -> int {
    var total = 0
    for i in 1..=n {
        total += i
    }
    return total
}

proc main() {
    // deferred calls run when the block ends, in reverse order
    defer print("end")
    defer print("almost done")
    print(sum_up_to(10))
}

// run with: forja test file.fj
test "sum from 1 to 10" {
    expect(sum_up_to(10) == 55)
}

test "sum of zero terms" {
    expect(sum_up_to(0) == 0)
}
55
almost done
end

5. Calling C functions

foreign {
    link "msvcrt"
    proc c_calloc = "calloc"(n: u64, size: u64) -> ?^i32
    proc c_free = "free"(p: rawptr)
}

// the slice is borrowed: whoever allocated the memory releases it
proc add_all(values: []i32) -> int {
    var total: int = 0
    for x in values {
        total = total + x as int
    }
    return total
}

proc main() {
    let n: i32 = 5
    let p = c_calloc(5, size = 4)
    var v = slice_from(p, len = n)
    for i in 0..<len(v) {
        v[i] = (i * i) as i32
    }
    print(len(v))
    print(add_all(v[..]))
    c_free(p as rawptr)
}
5
30

6. Constants, mutable and immutable names, units

const MAX: i32 = 9
unit Meters: f32

proc main() {
    let a = 1
    var n: i32 = 0
    let d: Meters = 2.0
    n += 1
    print(MAX + n + (a as i32) + (d as i32))
}
13

7. Structs, mutable references and multiple returns

struct Griffin {
    health: i32 in 0..=100 = 100
}

proc move_step(g: ^Griffin, dt: int, running: bool = false) -> int {
    g.health -= 1
    return dt
}

proc halves(n: int) -> (q: int, r: int) {
    return n / 2, n - n / 2 * 2
}

proc main() {
    var g = Griffin{health = 50}
    print(move_step(&g, dt = 2))
    print(g.health)
    let q, _ = halves(7)
    print(q)
}
2
49
3

8. Enums, unions and loops with continue

enum Color { green, blue }
union Shape { Color, i32 }

proc main() {
    let c = Color.blue
    switch c {
    case Color.green:
        print("green")
    case Color.blue:
        print("blue")
    }
    let f: Shape = 9 as i32
    switch x in f {
    case Color:
        print("color")
    case i32:
        print(x)
    }
    for i in 0..<3 {
        if i == 1 {
            continue
        }
        print(i)
    }
}
blue
9
0
2

9. Formatted text

proc main() {
    let s = format(f"health {7} x={3:03}", alloc = heap)
    defer delete(s)
    print(s)
    print(s == "health 7 x=003")
}
health 7 x=003
true

10. Arrays, lists, maps and bit sets

proc main() {
    var a: [3]int = {1, 2, 3}
    var f: [dynamic, 2]int = {}
    var m = make(map[str]int, alloc = heap)
    defer delete(m)
    insert(&m, key = "x", value = 5)
    append(&f, item = a[1])
    var s: bit_set[Color] = {Color.blue}
    insert(&s, key = Color.green)
    print(get(m, key = "x") or_else 0)
    print(len(a[1..<3]) + len(f) + len(s))
}

enum Color { green, blue }
5
5

11. Heap, frame and arena memory

import "std:mem"

struct Bullet {
    damage: int = 1
}

proc main() {
    let b = new(Bullet, alloc = heap)
    defer delete(b)
    var l = make([dynamic]int, alloc = heap, cap = 4)
    defer delete(l)
    append(&l, item = 7)
    let a = mem.arena_create()
    defer mem.arena_destroy(a)
    let c = new(Bullet, alloc = a)
    print(b.damage + c.damage + l[0])
}
9

12. Calling a C function with a string

foreign {
    proc c_remove = "remove"(path: cstr) -> i32
}

proc main() {
    print(c_remove("does_not_exist.tmp") != 0)
}
true

Command line

The compiler is a single file, forja.exe, with the standard library, the language specification and the runtime embedded. Run forja --help for the full usage text and forja spec --card for the syntax card.

CommandWhat it does
forja check [--max-errors N] [--stdin] a.fjcompiles without running; silence and exit code 0 mean the file is fine
forja run [--release] a.fj [-- args]compiles and runs the program on this machine
forja build [--mode exe|dll] [--release] a.fj -o outwrites the executable or DLL for the chosen target
forja test a.fj [--filter text] [--json]runs the test blocks; exit code 1 if any fails
forja explain CODEexplains an error code and shows the correct form
forja fix a.fjproposes mechanical fixes; --apply writes them
forja query api std:<module>lists the procedures and types of a standard module
forja bind x.h --link libgenerates a Forja wrapper from a C header
forja --versionprints the compiler version

The Portuguese command names also work (for example forja explicar or forja --ajuda); run forja --help for the English usage.

Exit codes: 0 ok; 1 a diagnostic was reported; 2 usage or file error; 3 internal error; 101 runtime failure; 102, 103 and 104 when a --limit-time, --limit-mem or --limit-output limit is exceeded.

Errors and diagnostics

Build targets

The syntax and the standard library are the same on every target. Only --target and the way the output is delivered change.

TargetOutput
x86_64-windows (default).exe, or a .dll with --mode dll
x86_64-linuxstatic ELF
wasm32-wasip1 (alias wasm).wasm (WASI preview 1)
aarch64-linuxstatic ELF for ARM64, built with system calls only
aarch64-linux-androida libNOME.so for a NativeActivity app (--mode dll), or a PIE executable (--mode exe)
aarch64-apple-ios-sim, aarch64-apple-iosMach-O console executable (--mode exe) or .dylib (--mode dll), for the iOS simulator or a device

run and test execute the program on the machine running the compiler, which covers the Windows host and the WebAssembly target when Node is installed. For the Linux and ARM64 targets they report X0003; run those outputs on their own machines (for example with QEMU, adb or xcrun simctl spawn). Packaging an APK or an iOS .app is done by separate helper scripts, not by forja.

A DLL built with --mode dll exports the procedures marked pub export proc. Such a DLL can be called from PHP (FFI) and Python (ctypes). For an Android .so, the export must not carry the forja_ prefix (E0902), and proc main() {} must be present and empty.

Limits stated in the project

Links