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
- One statement per line. The body of
if,for,while,switch,procandtestgoes on its own lines inside braces. Braces are always required, there are no semicolons, andif,whileandforconditions take no parentheses. - Names: types and units in
PascalCase, constants inUPPER_CASE, everything else insnake_case. The compiler enforces this (E0102). Non-ASCII letters are allowed only inside string literals. - Comments use
//only. Integer literals look like0xFFor0b1010, without underscores. - Logic operators are
and,or,not. The booleans aretrueandfalse, and the empty optional value isnone. - These do not exist in Forja:
&&,||,!,;,++,?:,nil,range,string,fn,def,:=,/* */. - Reserved words:
const let var proc struct enum union unit pub export import as foreign test if else for in while switch case default break continue return defer try or_else and or not. letdeclares an immutable name,vara mutable one, and onlyvaraccepts assignment (E0705).constrequires a type. A plain integer literal isint(64 bits) and a plain real literal isf32.- Types:
i8 i16 i32 i64 u8 u16 u32 u64 int uint f32 f64 bool str cstr rawptr. There are no implicit conversions:int + i32is E0301, so useas. The bit operators work only on unsigned types. - Units:
unit Meters: f32makes a distinct type.+,-and==work only between values of the same unit; change units withas. - Value ranges:
health: i32 in 0..=100 = 100. A value outside the range stops a dev build with a runtime error. - Procedures take positional or named arguments and may have default values. A positional argument after a named one is E0502. Parameters are immutable; a mutable reference is
^T. Procedures can return several values, received withlet a, b = f(), and_discards one. - Control flow:
if / else if / else,for i in 0..<n,for i in 1..=n,while,break,continue, anddefer f(x), which runs at the end of the block in reverse order. Aswitchmust cover every case or have adefault(E0607). Enum values are always qualified, as inColor.green. - Errors are values.
T ! Emeans a value or an error, and! Emeans only an error.trypasses the error to the caller, which must return the same error type.or_elsegives a default.switch r in f()handles both cases. Optional values are?T. assert(cond, msg = "text")also runs in release builds; when it fails the program stops with R0003 and exit code 101.expect(cond)is allowed only insidetest(E0801).- Memory is explicit. Every allocation names its allocator:
alloc = heap,frame,scope, an arena or a pool. Aheapvalue has one owner and must be released withdeleteordefer delete(E0317). Ascopevalue is released at the end of its block and can only be bound withletorvar(E0316). Aframeregion is 16 MiB and is reset withframe_reset(). A leak found in a dev build is R0009. - Collections:
[N]Tis an array value,[]Tis a slice (a view),[dynamic]Tis a growable list,map[K]Vis a map.geton a map returns?V.bit_set[Enum]holds up to 64 members. Built-in operations includeappend,insert,len,sort_byandwrapping_add. - Text:
stris an immutable UTF-8 byte string. A plain"..."literal never interpolates. Interpolation is written asf"...", andformat(...)returns a newstrthat must be deleted. - C functions are declared in a
foreignblock withproc name = "c_symbol"(...), andlink "lib"names the library. Ownership of C handles is stated withcreates,destroys,takesorends. - Modules:
import "std:mem", with an optional alias such asimport "std:mem" as m. Onlypubsymbols are visible from outside a package. Tests are written astest "name" { expect(...) }.
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.
| Command | What it does |
|---|---|
forja check [--max-errors N] [--stdin] a.fj | compiles 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 out | writes 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 CODE | explains an error code and shows the correct form |
forja fix a.fj | proposes mechanical fixes; --apply writes them |
forja query api std:<module> | lists the procedures and types of a standard module |
forja bind x.h --link lib | generates a Forja wrapper from a C header |
forja --version | prints 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
- Codes starting with
Eare compile errors, codes starting withRare runtime errors, and codes starting withXare targets or modes that are not supported. - A compile error is printed as one JSON line on standard output, with fields such as
codigo,linha,coluna,causaandforma_certa. A runtime error is printed as JSON on standard error. forja explain E0705explains the code. The explanation for E0705 says that onlyvaraccepts assignment.forja check --summaryprints each diagnostic with its code, file, line, cause and suggestion.
Build targets
The syntax and the standard library are the same on every target. Only --target and the way the output is delivered change.
| Target | Output |
|---|---|
x86_64-windows (default) | .exe, or a .dll with --mode dll |
x86_64-linux | static ELF |
wasm32-wasip1 (alias wasm) | .wasm (WASI preview 1) |
aarch64-linux | static ELF for ARM64, built with system calls only |
aarch64-linux-android | a libNOME.so for a NativeActivity app (--mode dll), or a PIE executable (--mode exe) |
aarch64-apple-ios-sim, aarch64-apple-ios | Mach-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
- The ARM64, Android and iOS targets were tested on emulators, simulators and CI. They were not tested on real devices. The iOS device target (
aarch64-apple-ios) has only been checked structurally. - The
forja.exebinary is not code-signed, so Windows may show a warning. Compare its SHA256 withbin/windows-x64/SHA256SUMS.txtin the repository. - There is no C backend: the compiler generates the machine code itself. The old options
--backend cand--mode creport X0003. - Not available yet: text drawn on the screen of an iOS UIKit app, aarch64 vendor libraries, direct Swift or Objective-C code, and running on a real iPhone.