Language Specifications

Language Specifications for the Occult programming language.

Language Specification Overview

This language specification will contain information about the language itself. For example, keywords, syntax of the language, as well as the unique features Occult has over other languages.

About Occult

Occult began in 2023 as a C transpiler Occult Source -> C Code -> C Compiler. This allowed for rapid development, and a working programming language pretty much eliminating the need for a custom backend, leveraging the power of C.

In 2024, the transpiler had became too buggy, and very restrictive for Occult to grow as a language, as a result, the project shifted from the C transpiler to a complete compiler rewrite which is and won't be reliant on any 3rd party backends.

Current Status

UNDER REVIEW

Keywords

Occult has keywords split into several categories.

Reserved Words

occult
if
elseif
else
loop
when
do
break
continue
while
for
true
false
return
switch
case
default
goto
try
catch
finally
error
errno
defer
sizeof
type
export
elseif can also be written as else if and it will have the same behavior.
try, catch, finally, error, errno and defer are covered in the Error Handling section further down. goto is covered under Control Flow.

Platform Detection

Built-in boolean constants for the compile-time target.

occult
is_win64
is_linux64

These behave like true and false and can be used in conditions to write platform-specific code. More platform detection constants will be added as more targets are supported.

Datatypes

occult
i64
i32
i16
i8
u64
u32
u16
u8
f32
f64
array
string
bool
char
char and bool behave the same as i8, this will most likely change in the future as more type safety is implemented.

Declaration Keywords

occult
fn
struct
enum
module
generic
const
global
union
extern
link
union is covered in the Unions section. extern and link are covered in the Modules section (external linkage).

Machine Code

occult
shellcode
asm
shellcode allows for raw hex machine code bytes directly in a function body. asm allows for human-readable assembly mnemonics. Both take an architecture tag in parentheses - today only x86_64, e.g. asm(x86_64) { ... } or fn f() shellcode(x86_64) i64 { ... }. Covered in the Functions section. Support will be expanded in future releases, and more architectures will be supported over time.

Misc

occult
import
from
include

include pulls in another .occ file. import ... from ... is sugar over include.

Comments

occult
// Single line

/*
  Multi
  line
  comment
*/

Literals

Integral & Floating Point

Hexadecimal, binary, octal, decimal, and scientific floating point.

Examples

occult
// Binary
0b1010

// Hexadecimal
0xDEADBEEF

// Octal (Same notation as C++)
010 // 8

// Normal base 10
123

// Normal floating point number
3.141

// Scientific floating point
2e10

Strings & Characters

Examples

occult
"Hello, I'm a string literal!\n"

// Character literals
'H'
'i'
'\n'

Operators

Gaps in the precedence numbering are not meaningful.
Precedence Operator(s) Type Associativity Placement
2 +x -x ~x !x Unary Right Pushed to stack
2 @x $x Unary ref Right Output / stack*
3 * / % Binary Left Stack (drained)
4 + - Binary Left Stack (drained)
5 << >> Bitwise Left Stack (drained)
8 > < >= <= Comparison Left Stack (drained)
9 == != Equality Left Stack (drained)
10 & Bitwise AND Left Stack (drained)
11 ^ Bitwise XOR Left Stack (drained)
12 | Bitwise OR Left Stack (drained)
13 && Logical AND Left Stack (drained)
14 || Logical OR Left Stack (drained)
15 = Assignment Left** Stack (drained)
15 += -= *= /= %= Compound Left Stack (drained)
15 &= |= ^= <<= >>= Compound Left Stack (drained)
17 ( ) Grouping N/A Stack / drain stop

Chained assignment (a = b = c) is not supported.

Bare !x as a condition is not accepted — use x == false or !(x == y).

Compound Assignment Operators

occult
fn main() {
  i64 n = 100;

  n += 10;   // n = n + 10
  n -= 5;    // n = n - 5
  n *= 2;    // n = n * 2
  n /= 3;    // n = n / 3
  n %= 9;    // n = n % 9

  // Bitwise compound assignments
  n &= 0xFF;
  n |= 0x01;
  n ^= 0x10;
  n <<= 2;
  n >>= 1;

  return n;
}
++ and -- are not supported and will not be added. Use i += 1 and i -= 1 instead.

Control Flow, Functions, and Expressions

Declaring a Function

Return type is optional; the default is i64. Functions implicitly return 0 when they fall off the end.

occult
fn main() /*return type*/ { }

A function body can be shellcode (raw machine bytes) or asm (mnemonics). Both take an architecture tag.

occult
fn main() shellcode(x86_64) i64 { 0x48 0xC7 0xC0 0x0A 0x00 0x00 0x00 0xC3 }

/*
Shellcode:
  mov rax, 10
  ret
*/
x86_64 is the only architecture tag today; unknown tags are rejected.

ASM Blocks

Whole function or inline block, using x86-64 mnemonics.

Syntax

occult
// whole-function form
fn /*name*/(/*params*/) asm(x86_64) /*return type*/ {
    // x86-64 mnemonics
}

// inline block inside a normal function
fn /*name*/(/*params*/) /*return type*/ {
    // normal Occult code
    asm(x86_64) {
        // x86-64 mnemonics
    }
    // more normal Occult code
}

Example (whole function)

occult
fn print_str(string, i64) asm(x86_64) i64 {
    push rbp
    mov  rbp, rsp
    mov  r11, rdi
    mov  r12, rsi
    mov  rax, 1
    mov  rdi, 1
    mov  rsi, r11
    mov  rdx, r12
    syscall
    mov  rsp, rbp
    pop  rbp
    mov  rax, 0
    ret
}

fn main() {
    print_str("HELLO\n", 6);
    return 0;
}

Referencing Occult Variables and Globals

{name} refers to a local or parameter, sized by the variable's type. A bare T x; on an otherwise empty assembly line reserves a zeroed slot. @name on a global assembles to a 64-bit immediate the compiler fills in at codegen time; 32-bit destinations are rejected.

Example

occult
i64 counter = 0;

fn bump() asm(x86_64) {
    mov rax, @counter
    add qword ptr [rax], 1
    ret
}

fn add_one(i64 x) i64 {
    asm(x86_64) {
        mov rax, {x}
        add rax, 1
        mov {x}, rax
    }
    return x;
}
Inline blocks save and restore rbx and r12-r15. Unknown names inside the block are an error.

Supported Instruction Forms

Over 4,700 x86-64 instruction forms, cross-checked byte-for-byte against GNU as. Highlights:

  • Labels; every jmp/jcc/loop/jrcxz form
  • call / jmp to Occult functions by name, and [rip + label|function]
  • db / dw / dd / dq / ascii / asciz / zero / align
  • Expressions, including label differences
  • Size keywords and fs: / gs: segment overrides
  • cmp, test, inc, dec, xchg, cmovcc, setcc, bt*, bsf, popcnt, rep, lock
  • SSE scalar and packed arithmetic, conversions and moves

Variables

Locals inside a function, globals at the top level.

occult
fn main() {
  i64 v = 30;

  return v;
}

Constants

const declares a value that cannot be reassigned. Works at global or local scope.

occult
const i64 MAX_SIZE = 100;

fn main() {
  const i32 local_max = 42;
  return local_max;
}

Global Variables

global marks a top-level variable as shared. Combines with const.

occult
global i64 counter = 0;
const global i64 LIMIT = 10;

fn bump() {
  counter += 1;
}

fn main() {
  bump();
  bump();
  return counter; // returns 2
}
Globals can be primitives or pointers. A struct itself can't be a global by value — use a pointer.

Calling a Function

occult
fn add(i64 x, i64 y) i64 {
  return x + y;
}

fn main() {
  i64 result = add(5, 5); // assigns 10 to result
  return result; // returns 10
}

Variadic Functions

Variadic functions use .... Extra arguments are accessed through the __varargs built-in array.

occult
include "../std/stdio.occ"

fn sum(i64 count, ...) i64 {
    i64 total = 0;
    i64 i = 0;
    while i < count {
        total += __varargs[i];
        i += 1;
    }
    return total;
}

fn main() {
    std::print_integer(sum(3, 10, 20, 30)); // 60
    std::print_string("\n");
}
The __varargs mechanism may change in later releases.

Function Pointers

The type is written like a function signature without a name. @ takes the address of a function.

Syntax

occult
fn(/*param types*/) /*return type*/ name = @/*function*/;

Example

occult
fn add(i64 x, i64 y) i64 {
  return x + y;
}

fn mul(i64 x, i64 y) i64 {
  return x * y;
}

fn apply(fn(i64, i64) i64 op, i64 x, i64 y) i64 {
  return op(x, y);
}

fn main() {
  fn(i64, i64) i64 op = @add;
  i64 a = op(2, 3);         // 5

  op = @mul;
  i64 b = apply(op, 2, 3);  // 6

  return a + b; // returns 11
}

Function pointers can be used anywhere a type can: variables, parameters, return types, globals, struct fields. For generics, take the address of a specific instantiation: @add.

@ is required to take a function's address — a bare function name won't decay.

Chained and composite calls

A function pointer can be called directly from any chain position:

occult
// call the pointer a function returned
i64 x = pick(1)(3, 4);

// call a pointer stored in a struct field
i64 y = ops.op(2, 3);

// call a pointer out of an array
i64 z = funcs[i](arg);

Type Casting

Casts between integer and floating-point types use function-call syntax. Casting to or from string or custom types is not supported.

Syntax

occult
/*target_type*/(/*expression*/)

Example

occult
include "../std/stdio.occ"

fn main() {
    i64 x = 42;
    f32 as_float = f32(x);       // integer to float

    f32 pi = 3.14;
    i64 truncated = i64(pi);     // float to integer - truncates toward zero

    i64 big = 300;
    i8 narrow = i8(big);         // narrowing cast - wraps

    f64 precise = f64(pi);       // widen float precision
    f32 back = f32(precise);     // narrow float precision

    std::print_integer(truncated); // 3
    std::print_string("\n");
    return 0;
}

Pointer Casts

Pointer types cast through the same function-call syntax, to any depth. At the machine level a pointer cast is a no-op.

Syntax

occult
/*type*/*(/*expression*/)
/*type*/**(/*expression*/)

Example

occult
fn main() {
    i64 a = 0;
    i64* p = i64*(a);         // cast integer address to i64*
    i8** pp = i8**(p);        // double pointer cast
    $p = 42;
    return a; // returns 42
}
Only the type*(expr) form is accepted; i64* p = i64* a; is a parse error.

sizeof

Returns the size in bytes of a type or an expression's type, as a compile-time i64.

Syntax

occult
sizeof(/*type_or_expr*/)

Example

occult
struct Point { i64 x; i64 y; }

fn main() i64 {
    i64 a = sizeof(i64);        // 8
    i64 b = sizeof(Point);      // 16
    i64 n = 10;
    i64 c = sizeof(n);          // 8 (n is i64)
    return a + b + c;           // 32
}
Pointer arithmetic is byte-by-byte. Combine sizeof with explicit arithmetic for C-style stepping: $(p + sizeof(i64)) = v;.

Type Aliases

type Name = ; declares a transparent alias. Pointer, function-pointer, and generic forms all work on the right-hand side.

Syntax

occult
type /*Name*/ = /*type*/;

Example

occult
type FileHandle = i64;
type Callback   = fn(i64, i64) i64;
type IntPtr     = i64*;
type Pair       = KeyValue<i64, i32>;

fn open(string path) FileHandle {
    FileHandle fd = 42;
    return fd;
}

fn apply(Callback cb, i64 a, i64 b) i64 {
    return cb(a, b);
}
Aliases are transparent. Alias names cast too: FileHandle(expr). For a distinct type with the same representation, use a one-field struct. Alias cycles over 32 expansions deep are rejected. type is compile-time; doesn't combine with export.

Strict Type Rules

The linter enforces these separations:

  • Pointers and integers. Assigning a plain integer to a pointer, or a pointer to a plain integer, is an error. Cast through the pointer form (i64*(x)) or back the other way with a numeric cast.
  • Pointers of different pointee types. Assigning an i64* to an i8* without a cast is an error. The pointer cast syntax above makes the intent explicit.
  • bool and the integer types no longer convert into each other silently. Use n == 0 / n != 0 instead of writing bool b = n;.
  • char and the integer types likewise. char and i8 share a representation but no longer convert implicitly.
char and bool still behave the same as i8 at the machine level - the strictness is in the linter, not the backend. Add a cast where you really meant to cross the boundary.

Control Flow

If Statements

Syntax

occult
if /*condition*/ { /*body*/ }
else if /*condition*/ { /*body*/ }
else { /*body*/ }
elseif is valid as well.
occult
fn main() {
  i64 to_compare = 1;
  if to_compare == 1 {
    return 1;
  }
  else {
    return 0;
  }
}

Switch

Matches an expression against case labels; default catches anything else.

Syntax

occult
switch (/*expression*/) {
    case /*value*/: { /*body*/ }
    default: { /*body*/ }
}

Example

occult
include "../std/stdio.occ"

fn main() i64 {
    i64 x = 2;

    switch (x) {
        case 1: {
            std::printf("one\n");
        }
        case 2: {
            std::printf("two\n");
        }
        case 3: {
            std::printf("three\n");
        }
        default: {
            std::printf("other\n");
        }
    }

    return 0;
}

Fallthrough

Cases without a body fall through to the next case that has one.

occult
switch (x) {
    case 1:
    case 2: {
        std::printf("1 or 2\n"); // runs for x == 1 or x == 2
    }
    default: {
        std::printf("other\n");
    }
}

Loop

Infinite loop; break and continue apply.

Syntax

occult
loop { /*body*/ }

Example

occult
fn main() {
  i64 x = 0;
  loop {
    x += 1;
  } // Infinitely add x by 1
}

While

Syntax

occult
while /*condition*/ { /*body*/ }

Example

occult
fn main() {
  i64 i = 0;
  while i < 5 {
    i += 1;
  } // Loop will run 5 times
}

For

C-style for loop, written with when for the condition and do for the step.

Syntax

occult
for /*variable decl*/ when /*condition*/ do /*iterator*/ { /*body*/ }

Example

occult
fn main() {
  for i64 i = 0 when i < 10 do i += 1 {
    // loop body
  } // loop will run 10 times
}

Goto and Labels

A label is name: on its own line; goto name; jumps to it. Labels are function-scoped.

Syntax

occult
label_name:
goto label_name;

Example

occult
fn main() i64 {
  i64 i = 0;
  start:
  if i >= 3 { goto done; }
  i += 1;
  goto start;
  done:
  return i; // returns 3
}
goto composes with try in both directions. goto *out* of a try body runs any covering finally first, then lands at the label. goto *into* a try body lands at the label, runs to the end of the try body, and any covering finally runs on the way out. See Error Handling for the exit-dispatch details.

Arrays

Syntax

occult
array[/*size*/] /*datatype*/ name = { 1, "String", 1.43, x, /*etc.*/ };

Example

occult
fn main() {
  array[5] i64 arr = {1, 2, 3, 4, 5};
  i64 sum = 0;

  for i64 i = 0 when i < 5 do i += 1 {
    sum = sum + arr[i];
  }

  return sum; // returns 15 (sum of the array)
}
Arrays can't be returned from functions. Multidimensional arrays ARE supported. Local arrays hold primitive types or struct values (array[3] Point pts;). Struct elements bulk-copy on pts[i] = some_point; and Point p = pts[i];. For dynamically-sized storage, use a pointer from std::malloc instead.

Inline arrays in structs and unions

Arrays as struct or union fields pack inline at the element's natural alignment. Element type can be a primitive, a struct, or a union.

occult
struct PROCESSENTRY32 {
  i32 dwSize;
  i32 cntUsage;
  i32 th32ProcessID;
  array[260] i8 szExeFile;
}

struct Line {
  i32 n;
  array[2] Point pts;        // array of a struct type
}

struct Buf {
  i32 n;
  union {
    i64 asInt;
    array[8] i8 asBytes;     // allowed inside a union group too
  }
}

@struct.array_field yields a T* to the first element. Fill struct-element arrays by assignment: line.pts[0] = pt;.

Initialiser lists for inline arrays are not supported yet; fill element by element.

Composite access chains

. and [ compose freely, in expression and statement position, for reads and writes.

occult
// member of a subscript, subscript of a member, read or write
b.bytes[0] = 1;
i32 n = pe.szExeFile[0];
p[0].x = 10;
i32 x = p[0].x;
l.pts[1].y = 42;
i32 y = l.pts[0].x;

// address of a composite leaf (stored value)
i32* xa = @line.pts[0].x;

// function-call result as the chain base
i32 v = make_point().x;
i32 w = make_line().pts[1].y;

// parenthesised primary as the chain base
i32 a = (p).x;
i32 b = (make_point()).x;

// method-call result
fn Point::incr(Point self) Point { /* ... */ }
i32 c = source.incr().x;
@make().x (address-of a leaf through a function-call base) is rejected — the hidden temporary would dangle. @expr.field works when expr has a stable address.

Structs

occult
struct node_i64 {
  node_i64* next;
  i64 data;
}

Accessing members

occult
struct node_i64 {
  node_i64* next;
  i64 data;
}

fn main() {
  node_i64 new_node;
  new_node.next = 0; // doesn't point to a new node
  new_node.data = 10; // current node holds the value of 10

  return new_node.data; // return our node's value (10)
}
There is no -> syntax like C, there is only . (works on both values and pointers).

Methods

fn Type::method(Type self, ...) RetType { ... } registers as a method on Type. Call with dot syntax on a value of that type.

occult
struct Point {
  i32 x;
  i32 y;
}

fn Point::incr(Point self) Point {
  Point out;
  out.x = self.x + 1;
  out.y = self.y + 1;
  return out;
}

fn main() i64 {
  Point p;
  p.x = 10;
  p.y = 20;

  Point q = p.incr();        // Point::incr(p)
  i32 got = p.incr().x;      // chains with composite access, see Arrays
  return 0;
}

obj.method() desugars to Type::method(obj, ...). self is by value; take Type@ for a mutating method.

Enums

Variants start at 0 and auto-increment unless an explicit value is given.

Syntax

occult
enum /*Name*/ {
    Variant,
    Variant = /*value*/,
}

Example

occult
include "../std/stdio.occ"

enum Color {
    Red,    // 0
    Green,  // 1
    Blue    // 2
}

enum Status {
    OK = 200,
    NotFound = 404,
    ServerError = 500
}

fn main() i64 {
    i64 c = Color::Green;
    std::printf("Color: %i\n", c);           // 1
    std::printf("Status: %i\n", Status::OK); // 200
    return 0;
}

Enum variants are accessed with ::. An enum type is backed by an integer.

Modules

A module groups functions under a namespace, accessed with ::.

Syntax

occult
module /*name*/ {
    fn /*function*/() { }
}

Example

occult
include "../std/stdio.occ"

module math {
    fn add(i64 a, i64 b) i64 {
        return a + b;
    }

    fn multiply(i64 a, i64 b) i64 {
        return a * b;
    }
}

fn main() i64 {
    i64 sum = math::add(3, 4);
    std::printf("3 + 4 = %d\n", sum);

    i64 product = math::multiply(5, 6);
    std::printf("5 * 6 = %d\n", product);

    return 0;
}

Modules nest; chain ::, e.g. std::math::add(...).

Extern Functions and Linkage

A module can hold extern fn prototypes. With link "name" on the module, every extern fn in it resolves to that library: a dynamic ELF import on Linux, a PE import directory entry on Windows.

Syntax

occult
module /*name*/ link "/*library*/" {
    extern fn /*function*/(/*params*/) /*return type*/;
}

Example

occult
module c link "c" {
    extern fn open(string, i32) i32;
    extern fn close(i32) i32;
    extern fn read(i32, i64, i64) i64;
    extern fn malloc(i64) i64;
    extern fn free(i64);
}

fn main() i64 {
    i64 buf = c::malloc(1024);
    c::free(buf);
    return 0;
}

On Windows swap libraries, e.g. link "kernel32", link "msvcrt". Calling convention is picked per target.

extern fn without link "..." relies on the surrounding build to supply the symbol.

Exporting Functions (Shared Libraries)

export fn marks a function for the shared library's exports table. module name export { ... } marks every function inside the module.

Syntax

occult
export fn /*name*/(/*params*/) /*return type*/ { ... }

module /*name*/ export {
    fn /*name*/(/*params*/) /*return type*/ { ... }
    fn /*name*/(/*params*/) /*return type*/ { ... }
}

Example

occult
export fn add(i64 a, i64 b) i64 {
    return a + b;
}

module math export {
    fn multiply(i64 a, i64 b) i64 { return a * b; }
    fn negate(i64 x) i64         { return 0 - x; }
}

A program with fn main() and no export is an executable; any export and no main is a shared library; mixing is rejected.

Call it from C

c
/* Linux */
#include 
void* h = dlopen("./libmath.so", RTLD_NOW);
long (*add)(long, long) = dlsym(h, "add");

/* Windows */
#include 
HMODULE h = LoadLibraryA("math.dll");
long long (*add)(long long, long long) = (void*) GetProcAddress(h, "add");

Functions export under their bare leaf name.

export is for shared-library emission only; doesn't affect visibility and doesn't combine with type.
Base relocations are emitted so shared libraries relocate freely under ASLR and standard Windows DLL loading.

Generics

generic on the line before a struct or function declares a type parameter. Multiple parameters allowed.

Syntax

occult
generic<T>
struct /*Name*/ {
    T field;
}

generic<T>
fn /*name*/(T param) T {
    return param;
}

Example

occult
include "../std/stdio.occ"

generic<T>
fn identity(T val) T {
    return val;
}

generic<T, U>
struct KeyValue {
    T key;
    U value;
}

fn main() {
    std::printf("%i\n", identity<i64>(42));

    KeyValue<i64, i32> kv;
    kv.key = 10;
    kv.value = 99;
    std::printf("key=%i value=%i\n", kv.key, kv.value);
}

Instantiate at the call or declaration site: identity(42), KeyValue kv;.

Memory

@ is address-of (C's &). $ is dereference (C's *ptr).

Pointers are strictly typed. Cross pointee types with a pointer cast (U*(expr)). Pointer arithmetic is byte-by-byte.

Simple Example

occult
fn main() {
  i64 v = 10;
  i64* p = @v; // assign the address of `v` to `p`
  $p = 30;     // value of `v` is now 30

  return v; // returns 30
}

Heap Allocation

std::malloc and std::free from the standard library.

occult
include "../std/stdio.occ"

fn main() {
  i64 v = std::malloc(16);

  $v = 100;
  $(v + 8) = 200;

  i64 total = $(v + 8) + $v; // 300

  std::print_integer(total); // prints 300
  std::print_string("\n");

  std::free(v);
}
Pointer arithmetic is byte-by-byte; combine with sizeof for typed stepping.

Reference Parameters

occult
fn add(i64@ x_ref, i64 y_ref) {
  $x_ref = $x_ref + y_ref; // you have to explicitly dereference the value to access it
}

fn main() {
  i64 x = 10;
  add(x, 30); // x is now 40 (x_ref has the address of x)
  return x; // returns 40
}

Also work with generic types: T@ and Box@.

occult
generic<T>
struct Box { T v; }

generic<T>
fn set_box(Box<T>@ b, T val) {
  b.v = val; // mutates the caller's Box
}

Strings in Memory

String length is stored 8 bytes before the string's data pointer.

occult
fn strlen_fast(string str) {
  i64 len = $(str - 8);

  return len;
}

Error Handling

Errors are values. Programs that neither raise nor catch pay nothing.

error, try, catch, finally, defer and errno are reserved words — a function or variable can't share the name.

Raising an Error

error "msg"; — the error keyword followed by a string literal or expression. No parenthesised call form.

occult
fn pick(i64 x) i64 {
  if x < 0 {
    error "negative input";
  }
  return x * 2;
}

Expression parens still work:

occult
error ("code " + reason);

Typed Errors

A top-level error declaration is a typed error. Each type gets a numeric id (1..N; 0 reserved for untyped). Up to eight fields per type.

Syntax

occult
error /*Name*/ { /*type field; ...*/ }
error /*Name*/;             // no fields

Example

occult
error NotFound { string path; }
error ParseError { i64 line; string text; }
error Timeout;

fn load(string p) {
  if open(p) < 0 {
    error NotFound { path = p };
  }
}

fn parse(i64 n, string t) {
  error ParseError { line = n, text = t };
}

fn deadline() {
  error Timeout;
}
Field types are i64 or string. Floats, structs by value, and arrays are not yet supported.

Try, Catch, Finally

If a call inside a try raises, control jumps to the matching catch. finally, when present, runs on every exit from the body.

Syntax

occult
try { /*body*/ }
catch /*TypeName*/ e { /*handler*/ }   // zero or more typed catches, matched top to bottom
catch e { /*handler*/ }                // optional untyped catch, matches anything
finally { /*cleanup*/ }                // optional

Example

occult
try {
  load_config("app.cfg");
} catch NotFound e {
  printf("missing: %s\n", e.path);
} catch ParseError e {
  printf("line %ld: %s\n", e.line, e.text);
} catch e {
  printf("other: %s\n", e);
} finally {
  printf("done\n");
}

A typed catch makes e a local of that type. An untyped catch e makes e a string with the message.

A try with only a finally is fine:

occult
try { ... } finally { ... }

Exits Out of a Try Body

return, break, continue, and goto all work from inside a try body. A covering finally runs first, then the exit lands. Nested finallys chain.

goto into a try body is also supported.

occult
fn main() i64 {
  for i64 i = 0 when i < 10 do i += 1 {
    try {
      if i == 5 { break; }
    } finally {
      printf("iter %ld cleanup\n", i);
    }
  }
  return 0;
}

Propagation

No throws lists — the compiler infers which functions are fallible and only emits a post-call check for calls to those. An error reaching main uncaught is printed and the program exits with status 1.

Errno

errno reads the C errno at the point of use. Returns an i64.

occult
error OpenFailed { i64 code; string path; }

fn open_or_fail(string p) i64 {
  i64 fd = c::open(p, 0);
  if fd < 0 {
    error OpenFailed { code = errno, path = p };
  }
  return fd;
}

Re-raising from a Catch

error e; inside a catch re-raises the caught error with its payload intact.

occult
try {
  something_fallible();
} catch ParseError e {
  log("saw a parse error on line %ld", e.line);
  error e;        // keep propagating, line/text payload preserved
}

Defer

defer ; or defer { block } registers a body that runs when control leaves the enclosing block. Multiple defers in a block run LIFO.

Syntax

occult
defer /*statement*/;
defer { /*block*/ }

Example

occult
fn load(string path) i64 {
  i32 fd = c::open(path, 0);
  defer c::close(fd);          // runs at function exit

  for i64 i = 0 when i < 3 do i += 1 {
    i64 buf = c::malloc(1024);
    defer c::free(buf);         // runs once per iteration
    if some_cond(i) { break; }  // free(buf) still runs before the break lands
  }

  return 0;                     // close(fd) runs here
}
defer is block-scoped. A defer in a loop body runs once per iteration, including iterations that break or continue.

Scope and Limits (current release)

  • Up to eight fields per typed error (payload slots __occult_err_payload_0..7).
  • Field types are i64 or string. Floats, structs by value, and arrays are not supported yet.
  • A catch chain matches top to bottom — put narrower types first.
  • error varname; outside a catch is not yet supported; inside a catch, error e; re-raises the caught error with the same type id, message, and payloads.

Unions

Anonymous groups inside a struct, or standalone types. C semantics: writing one field overwrites the others.

Union Fields Inside a Struct

Every field in a union { ... } block shares one offset in the struct. Group size is max(member sizes); alignment is max(member alignments).

Syntax

occult
struct /*Name*/ {
  /*type regular_field;*/
  union {
    /*type field_a;*/
    /*type field_b;*/
  }
  /*type trailing_field;*/
}

Example

occult
enum Kind { Ok, Err }

struct Result {
  i64 tag;
  union {
    i64 ok;
    string err;
  }
}

fn main() i64 {
  Result r;
  r.tag = Kind::Ok;
  r.ok = 42;

  if r.tag == Kind::Ok {
    return r.ok;              // 42
  }
  return 0;
}

Combined with typed errors, union fields cover the ground sum types cover in Rust or Swift - just without the exhaustiveness check. Pick the right half out with a tag check.

Standalone Union Types

A union Name { ... } declaration at the top level is a standalone union. Internally the parser desugars it to a struct whose single child is a union group holding every declared field, so layout, pass-by-value, and member access all go through the same code the embedded form uses.

Syntax

occult
union /*Name*/ {
  /*type field_a;*/
  /*type field_b;*/
}

Example

occult
union Pair {
  i64 n;
  string s;
}

fn main() i64 {
  Pair p;
  p.n = 42;         // writes an i64
  return p.n;       // reads it back; reading p.s here would reinterpret those bytes
}

Niche: Pattern on Reading

The valid field is the one that was last written. Reading another in the union group is a reinterpret, not an error - the bits are the same, you just view them through a different lens. For a Result with union { i64 ok; string err; }, reading r.err after writing r.ok = 42 gives you the i64 42 viewed as a pointer, which almost certainly segfaults the moment you dereference it. The tag field exists precisely so the program knows which side to read.

Byte-view trick with inline arrays

The combination of a union group and an inline byte array gives a clean way to inspect or splice the raw bytes of a value:

occult
struct Buf {
  i32 n;
  union {
    i64 asInt;
    array[8] i8 asBytes;
  }
}

fn main() i64 {
  Buf b;
  b.asInt = 0x4142434445464748;
  return b.asBytes[0];   // 0x48 on a little-endian target
}

Writing asInt and then reading asBytes[i] round-trips the bytes, as a C union does.

Standard Library

The Occult standard library is written in Occult itself and is still being actively developed. Include the files you need from the std/ directory.

How to include / import the modules.

occult
import stdio from std;
import memory from std;
import vec from std;
import strlib from std;

// Alternatively

include "../std/stdio.occ"
include "../std/memory.occ"
include "../std/vec.occ"
include "../std/strlib.occ"
The standard library is minimal and still under active development. More modules will be added over time.

This is the end of the language specification for now, maybe check out the examples section to learn more!

×