IDEKA

IDEKA is a compiled, general purpose programming language formerly known as IDEKA.

It's easy to write as it does not require to use its higher level constructs. The learning curve is low, but the skill ceiling is high.

If you like IDEKA, please consider contributing to the language or joining the IDEKA Discord server where you can ask questions, provide feedback, and talk with other IDEKA enjoyers!

Creator note: Everything in IDEKA is stack allocated unless specified.

IDEKA was designed primarily for reverse engineering and secondarily for general purpose software development.


Table of Contents

Functions

You cannot define a function within a function. They must be module, namespace, or object level.

Prototype:

IDEKA
// Single declaration
def name(parameters) -> void;

// Multi-declaration
def name(int) -> bool,
    name(float) -> void,
    name(char*) -> int;   // Can prototype multiple functions at once, comma separated signatures.

Prototype signatures do not need a variable name, only types like def foo(int,int,void*)->bool;

Signature:

IDEKA
def name (parameters) -> return_type
{
    return return_value;
};

Example:

IDEKA
def myAdd(int x, int y) -> int
{
    return x + y;
};

Definitions require a variable name.

Overloading example:

IDEKA
def myAdd(float x, float y) -> float
{
    return x + y;
};

How an overload is chosen at a call site:

  1. Filter by argument count. Only overloads whose parameter count matches the call's

argument count are considered.

  1. Prefer an exact type match. Among the count-matching candidates, the compiler looks for

one whose parameter types are an exact match to the arguments' actual types, in declaration order.

  1. Otherwise, fall back to the first count-matching overload declared, and adapt the

arguments to fit its parameter types rather than treating the mismatch as an error.

This means overload selection is driven by argument count first and exact type match second; it does not attempt the kind of best-match ranking among multiple inexact candidates that C++ does. If none of the overloads for a given arity match exactly, you get whichever one was declared first, with its arguments coerced to fit - so when overloading on type for the same arity actually matters, declaration order matters too.

Argument coercion at call sites. Once an overload is selected, arguments that don't already match the parameter types exactly are adapted automatically:

parameter is expected bitcasts automatically (decaying through an array-to-pointer step first if needed), and passing a void* argument where a concrete pointer type is expected does the reverse. Neither direction requires an explicit cast at the call site.

the array's element type - you can pass an int[8] directly where an int* parameter is expected.

than the parameter declares truncates or extends it to fit (sign- or zero-extending based on the argument's known signedness). Unlike the array/integer packing casts described under "Casting", there is no "sizes must match exactly or it's an error" rule for ordinary function arguments - a call site adapts silently, because passing a value into a parameter is about conveying a value, not reinterpreting a fixed memory layout the way an explicit pack/unpack cast is.

Built-in operator overloads (see "Custom infix operators and overloading") follow a stricter rule than ordinary functions: an operator overload is only used when its parameter types are an exact match for the operands. There is no fall-back-and-coerce step for operators - if nothing matches exactly, the native operation runs instead, since silently falling back to the wrong user-defined overload for a built-in symbol would be far more surprising than just doing the default thing.

Variadic functions

Variadics in IDEKA are very straightforward, and use the ... elipse operator. You can index the elipse operator to yield the arguments passed, example:

IDEKA
#import <standard.idk>;

using standard::io::console;

def variadic(...) -> void
{
    print(...[0]); print();
    print(...[1]); print();
    print(...[2]); print();
    print(...[3]); print();
};



def main() -> int
{
    variadic(1,2,3,4);

    return 0;
};

Result:

IDEKA
1
2
3
4

Error Returns

IDEKA supports dual return-type functions, the most common use case is in error returns.

IDEKA
#import <standard.idk>;

using standard::io::console;

struct LogError { /// ... /// };
// LogFile omitted

def Logger(LogFile* lf) -> int ^| LogError // definition, return type is L xor R, either L or R.
{
    if (some_bad_thing_happened)
    {
        // LogError e;
        // set values
        error -> e;
    };

    -> 0;
};

def main() -> int
{
    LogFile lf("/path/to/file.log");
    int ^| LogError result,err = Logger(@lf);

    if (err!?)      { println(err.message); }
    elif (result!?) { println(result); }

    -> 0;
};

Chaining functions

The chain operator <- is a binary operator, like A <- B. Chaining with <- passes the right operand into the function call's param on the LHS. This only works with single-parameter functions.

IDEKA
def foo(int x) -> int
{
    return x / 2;
};

def bar () -> int
{
    return 0xFF;
};

int z = foo() <- bar(); // identical to writing int z = foo(bar());

Shorthand Functions

First, it is good to know that the return arrow itself -> can take the place of the return keyword. Example:

IDEKA
def foo(int x) -> int
{
    -> x / 2;
};

It should also be known that def does not mean define but actually means default, and is located in the calling convention position. Because of this, def can be omitted:

IDEKA
foo(int x) -> int
{
    -> x / 2;
};

This function if written on one line would look like this (and kind of ugly): foo(int x) -> int { -> x / 2; };

If a function is return-only and has no other statements but that one, it can be reduced. IDEKA already has a lot of semicolons, and braces. Like an if that has one statement, we can eliminate the braces and write: foo(int x) -> int -> x / 2;

This creates a very nice, almost mathematical-looking line of code.


External Functions (FFI)

Single-line:

IDEKA
extern def foo() -> void;
extern def !!foo() -> void;  // !! tells the compiler do not mangle this function name

Block-based:

IDEKA
extern
{
    def foo() -> void;
    def bar() -> void;
    def !!zed() -> void;
};

Or multiple prototypes at once:

IDEKA
extern
{
    // Memory allocation
    def !!
        malloc(size_t) -> void*,
        memcpy(void*, void*, size_t) -> void*,
        free(void*) -> void,
        calloc(size_t, size_t) -> void*,
        realloc(void*, size_t) -> void*,
        memcpy(void*, void*, size_t) -> void*,
        memmove(void*, void*, size_t) -> void*,
        memset(void*, int, size_t) -> void*,
        memcmp(void*, void*, size_t) -> int,
        abort() -> void,
        exit(int) -> void,
        atexit(void*) -> int;
};

String-literal based function name support to target any compiled library function:

IDEKA
def "??foo@"()->void;

Exporting Functions with export

Using export will cause a function to be marked as external for linkage. Use this when writing libraries, or to allow a function to be "seen".

IDEKA
#import "types.idk";

export
{
    def !!stub() -> void {};
};

This is a valid library and will compile if you do: python idkc.py tests\testlib.idk --library -o mylib.dll on Windows, and python3 idkc.py tests/testlib.idk --library -o testlib.so on Linux.


Importing with #import

Any file you import will take the place of the import statement.

IDEKA
#import <standard.idk>;  // <> means stdlib, "" means local to source file
#import "mylib.idk", "foobar.idk";  // Multi-line imports are processed from left to right in the order they appear.

Example: somefile.idk

IDEKA
int myVar = 10;

main.idk

IDEKA
#import "somefile.idk";  // int myVar = 10;

def main() -> int
{
    if (myVar < 20)
    {
        // Do something ...
    };
    return 0;
};

Importing with #package

Packages are imported from the compiler's local FPM registry located inside .fpm\packages.

To import a package, use the package name directly:

IDEKA
#import <standard.idk>;

#package super-types, IDEKA-boost;  // these don't exist, yet..

You still need to perform using statements unless the package self-uses, meaning it has the using statements inside of it near the end of entrypoint file.

Packages and FPM are still in development and should not be used for now.


The Preprocessor

IDEKA
#import <standard.idk>;

#ifdef __WINDOWS__
#def DEFAULT_CONFIG_FLAG 0x4000;
#elif __LINUX__
#def DEFAULT_CONFIG_FLAG 0x8000;
#endif;

#warn "This will show a warning message.";

#stop "This will hard-stop compilation.";

#dir "C:\\path\\to\\some\\lib";
// Adds a path to the preprocessor's search list

#def defines a preprocessor text substitution constant. This is not a macro, just a "dumb" replacement. It is not parameterized, meaning you cannot pass anything in to it.

Parameterized Substitution:

To achieve C macro-like behavior, you can use #psub.

#psub is also "dumb" replacement, and is the other half of #def.

Example:

IDEKA
#import <standard.idk>;

using standard::io::console;

#psub test(x,y) println(x); #
                println(y);

def main() -> int
{
    test("Hello", "world!");

    return 0;
};

How #psub works

Defining

Expanding

IDEKA
  #psub add(a, b) a + b

  x = add(b, 1);   // a -> b gives "b + b", then b -> 1 gives "1 + 1"
                   // result: x = 1 + 1;

Conditionals #ifpsub NAME is true when the #psub NAME is defined, and #ifnpsub NAME is true when it is not. Both are closed with #endif;. A parameter list written after the name, as in test2(a) below, is ignored.

You can also perform conditional logic with #ifpsub and #ifnpsub:

IDEKA
#import <standard.idk>;

using standard::io::console;

#psub test(x,y) println(x); #
                println(y);

#ifnpsub test2(a)
#warn "[Warning] #psub test2(a) not defined!";
#endif;

def main() -> int
{
    test("Hello", "world!");

    return 0;
};

Namespaces

Prototype: namespace myNamespace; Definition: namespace myNamespace {}; Scope access: myNamespace::myMember;

Example:

IDEKA
namespace myNamespace
{
    def myFoo() -> void; // Legal
};

namespace myNamespace
{
    def myBar() -> void;        // namespace myNamespace now has myFoo() and myBar()
};

namespace myNamespace
{
    namespace myNestedNamespace
    {
        def myFooBar() -> void;
    };
};

Duplicate namespace definitions do not redefine the namespace, the members of both combine as if they were one namespace. This is so the standard library or any library can have a core namespace across multiple files. Namespaces are the only container that have this functionality.


Structs

Prototype / forward declaration: struct myStruct; Definition: struct myStruct {int x,y,z;}; Instance: myStruct newStruct; Instance with assignment: myStruct newStruct {x = 10, y = 20, z = -5}; Member access: newStruct.x;

Structs are packed and have no padding naturally. There is no way to change this. You set up padding with alignment in your data types. Members of structs are aligned and tightly packed according to their width unless the types have specific alignment. Structs are non-executable, and therefore cannot contain functions or objects. Placing a for, do/while, if/elif/else, try/catch, or any executable statements other than variable declarations will result in a compilation error.

Example:

IDEKA
struct xyzStruct
{
    int x,y,z;
};

struct newStruct
{
    xyzStruct myStruct {x = 1, y = 1, z = 1};              // structs can contain structs
};

Structs are non-executable. Structs cannot contain functions, or objects. This includes prototypes and definitions. Pointers are ok, including function pointers.

Structs support composition via prepending and appending other structs. Example:

IDEKA
struct Header
{
    data{16} sig;
    data{32} filesize, reserved, dataoffset;
};

struct InfoHeader
{
    data{32} size, width, height;
    data{16} planes, bitsperpixel;
    data{32} compression, imagesize, xpixelsperm, ypixelsperm, colorsused, importantcolors;
};

struct ExtraData
{
    byte[64] author;
};

struct BMP : Header, InfoHeader
{
    // More bitmap fields
} : ExtraData;

Block assignment

Below is an example snippet from the standard library in runtime\allocators.idk around line 415. If the object[at this index] is a struct, you can do block assignment instead of writing new_tbl[rm_hole] 4 times.

IDEKA
new_tbl[rm_hole]
{
    .key  = new_tbl[rm_next].key;
    .size = new_tbl[rm_next].size;
    .kind = new_tbl[rm_next].kind;
    .slab = new_tbl[rm_next].slab;
};

Struct recast with from

from reinterprets an existing value's bytes as a struct, without copying. It's the struct-typed counterpart to casting a byte array into an integer - useful for parsing a buffer into a structured view in place rather than building the struct field by field.

IDEKA
struct Header
{
    data{16} sig;
    data{32} filesize;
};

byte[6] buf = [0x42, 0x4D, 0x00, 0x01, 0x02, 0x03];

Header h from buf;
// h.sig == 0x424D, h.filesize == 0x00010203
// `buf` is no longer usable after this point.

The right-hand side of from may be a plain identifier (an array or other addressable variable) or an array slice (buf[a:b]). When the source is a slice, the compiler builds the struct view directly over the original buffer starting at the slice's offset - there is no intermediate copy of the sliced range.

The total size of the source must match the struct's total byte size; a mismatch is a compile-time error, the same as casting one struct type to another of a different size.

By default, from consumes its source. After the recast, the original identifier is removed from scope - referencing it again is a compile-time error. This mirrors the ownership-transfer behavior of the ~ tie operator: once the bytes are viewed as the new struct type, the old name for them is gone, so there's exactly one live name pointing at that memory.

To keep the source usable after the recast, append ! to the source expression:

IDEKA
Header h from buf!;   // buf is still valid and usable after this line
IDEKA
// Recasting directly from a slice - no copy, h aliases buf[2:6]
Header h from buf[2:6];

Objects

Prototype / forward declaration: object myObj; Definition: object myObj {}; Instance: myObj newObj(); Member access: newObj.x

Objects are functional with behavior and are "executable" as opposed to structs which are pure data-only.

Object Methods this never needs to be a parameter as it is always local to its object.

Required methods:

IDEKA
__init()       -> this               Example: thisObj newObj();            // Constructor
__exit()       -> void               Example: newObj.__exit();             // Destructor
__expr()       -> any

__init is always called on object instantiation. __exit called manually to destroy the object. __expr is the instance's expression context method. This method cannot take arguments.

If an object's __init method takes only one parameter, you may instance it like sO:

IDEKA
#import <standard.idk>;

using standard::io::console;

object SomeOBJ
{
    int val;

    def __init(int x) -> this { this.val = x; return this; };

    def __exit() -> void {};

    def __expr() -> int { return this.val; };
};

def main() -> int
{
    SomeOBJ sobj = 5;

    println(sobj.val);   // Direct access

    println(sobj);  // Compiler detects object instance, emits print(sobj.__expr());

    println(sobj + sobj); // 10

    return 0;
};

It is syntactic sugar for SomeObj sobj(5);

Deferred object cleanup with defer:

Deferred statements execute in LIFO order. Deferred calls execute after post-contract code, immediately before the function returns.

IDEKA
#import <standard.idk>;

using standard::io::console;

object SomeOBJ
{
    int val;
    def __init(int x) -> this
    {
        this.val = x;
        return this;
    };

    def __exit() -> void { print("Cleaning up!"); };

    def __expr() -> int { return this.val; };
};

def main() -> int
{
    SomeOBJ sobj = 5;
    defer sobj.__exit();

    print(sobj);
    // deferred statements injected here
    return 0;
};

You can also defer in blocks:

IDEKA
#import <standard.idk>;

using standard::io::console;

def main() -> int
{
    println("Hello!");
    defer
    {
        println("Test1!");
        println("Test2!");
    };
    return 0;
};

Result:

IDEKA
Hello!
Test2!
Test1!

Inheritance

Object inheritance follows simple rules which eliminate the diamond problem. It will not permit the diamond problem to exist.

Inheritance syntax is: object B : A, which means B inherits from A.

Multiple inheritance is: object C : A, B

Here's an example:

IDEKA
#import <standard.idk>;

using standard::io::console;

object A
{
    int a1, a2, a3;
    def __init() -> this { return this; };
    def __expr() -> A*   { return this; };
    def __exit() -> void { (void)this;  };
};

object B
{
    int b1, b2, b3;
    def __init() -> this { return this; };
    def __expr() -> A*   { return this; };
    def __exit() -> void { (void)this;  };
};

object C : A, B
{
    int c1, c2, c3;
    def __init() -> this { return this; };
    def __expr() -> A*   { return this; };
    def __exit() -> void { (void)this;  };
};

You may use !+ before def to indicate no override, like so:

IDEKA
object B
{
    int b1, b2, b3;
    def __init() -> this { return this; };
    def __expr() -> A*   { return this; };
    def __exit() -> void { (void)this;  };

    !+ def foo() -> void {};
};

object C : B
{
    +  def foo() -> void {}; // compiler will error, child must inherit foo from parent
}

Traits

Traits are contracts imposed on objects dictating they __must__ implement the defined prototypes.

IDEKA
trait Drawable
{
    def draw() -> void;
};


// Implementation
Drawable object myObj
{
    // ... required methods ...

    def draw() -> void
    {
        // Implementation code, if the block is empty the compiler throws an error.
        return void;
    };

    // ... other methods ...
};

You may have multiple traits to apply such as:

IDEKA
Drawable Deletable Resizable object Square
{
    /// ... ///
};

This can get hard to read fast, so you can compose traits together:

IDEKA
trait GeomT1 = Drawable & Deletable & Resizable;

GeomT1 object Square
{
    /// ... ///
};

Interfaces

An interface is a compile-time rule set describing which methods two objects may use on each other. Interfaces generate no code: they exist only to make the compiler reject calls that the interface does not sanction.

An interface has a name and a list of roles. Each role is bound to a trait, and a role stands for "any object that implements that trait". Inside the body, protocol blocks list the methods allowed between two roles.

IDEKA
interface Name(RoleA: TraitA, RoleB: TraitB)
{
    RoleA : RoleB   { method() -> type, ... };   // call permission
    RoleB(RoleA)    { method() -> type, ... };   // pass-into permission
    RoleA -> RoleB  { method() -> type, ... };   // return-to permission
};

Attaching an interface

An interface takes effect when it is attached to an object, after the closing brace of the object definition:

IDEKA
object Client { /// ... /// } : Database(this, Store);

The arguments bind to the interface roles in declaration order: Database(this, Store) binds A to Client (this) and B to Store. Several interfaces may be attached by separating them with commas: } : Database(this, Store), Audit(this, Log);.

When an interface is attached, the compiler:

  1. Adds each role's trait to the object it is bound to, so an object bound to a role must implement every method of that trait.
  2. Checks that the attaching object and every named partner object implement their role's trait. A partner is checked even if it never attaches the interface itself.
  3. Checks that the number of attachment arguments matches the number of roles, and that the interface is defined.
  4. Builds the method lists for each protocol block, keyed by the concrete pair of objects.

Failing any of these is a compile error. An interface may be attached to either or both participants; one attachment registers the rules for the pair. Interfaces are not applied to templated objects.

Protocol relationship operators

SyntaxMeaning
A : B { methods }Code inside A may call these methods on a B instance
B(A) { methods }The return value of these A methods may be passed as an argument into B
A -> B { methods }These A methods may be called from inside a B method body

All three may coexist for the same pair of roles. Each is enforced independently.

For every pair of objects that a protocol block governs, the listed methods form a whitelist. Once a pair is governed, any method not on the list is rejected, even if it is public. A pair with no protocol block of a given kind is unrestricted in that direction.

A : B - call permission

Restricts which methods of B may be called from inside A's method bodies.

IDEKA
interface Link(A: Sender, B: Receiver)
{
    A : B { accept(byte* data) -> bool };
};

If Sender code calls Receiver.accept(...) it compiles. If it calls any other method on a Receiver (for example Receiver.flush()), the compiler reports:

IDEKA
Interface violation: Sender is not permitted to call flush from Receiver

This check applies to calls made inside object method bodies. Calls made from free functions such as main are not covered by A : B.

B(A) - pass-into permission

Controls what may be fed into B. When a call to a B method has an argument that is itself a method call on an A instance, the A method must be listed in the B(A) block.

IDEKA
interface Pipe(A: Source, B: Sink)
{
    B(A) { read() -> byte* };
};

// OK: read is listed
sink.write(src.read());

// Error: peek is not listed
sink.write(src.peek());
// Interface violation: return value of 'Source.peek' is not permitted to be passed as an argument into 'Sink'

The check looks at arguments that are direct method calls on a named variable (src.read()). A value first stored in a variable and then passed is not tracked.

A -> B - return-to permission

Controls which A methods may be called from inside B's method bodies.

IDEKA
interface Report(A: Meter, B: Logger)
{
    A -> B { value() -> int };
};

object Logger
{
    def log(Meter* m) -> void
    {
        int v = m.value();    // OK: value is listed in A -> B
        int r = m.reset();    // Error: reset is not listed
    };
};
// Interface violation: 'Meter.reset' is not permitted to be called from inside 'Logger'

Precedence

Inside a method body, A -> B is checked before B : A. If a call is explicitly allowed by an A -> B list, the B : A list is not consulted for that call. This lets one interface permit a call in one direction while restricting the reverse direction.

Full example

IDEKA
trait Queryable   { def query(byte* sql) -> byte*; };
trait Connectable { def connect() -> bool; };

interface Database(A: Connectable, B: Queryable)
{
    A : B
    {
        connect()    -> bool,
        disconnect() -> void
    };

    B(A)
    {
        result() -> byte*
    };

    A -> B
    {
        result() -> byte*
    };
};

object Client, Store;

object Store
{
    def __init() -> this { return this; };
    def __exit() -> void {};
    def __expr() -> int { return 0; };
    def query(byte* sql) -> byte* { return sql; };
    def disconnect() -> void {};

    def fetch(Client* c) -> byte*
    {
        // Allowed: result() is listed in A -> B
        byte* r = c.result();
        return r;
    };
};

object Client
{
    def __init() -> this { return this; };
    def __exit() -> void {};
    def __expr() -> int { return 0; };
    def connect() -> bool { return true; };
    def result()  -> byte* { return "data"; };
} : Database(this, Store);

def main() -> int
{
    Client c();
    Store  s();

    // Allowed: result() is listed in B(A), so its value may be passed into Store
    byte* out = s.query(c.result());

    c.connect();

    return 0;
};

Here Client is bound to role A (it must implement Connectable) and Store to role B (it must implement Queryable). Attaching Database(this, Store) to Client also checks Store against Queryable.

Attachment rules


Public/Private with Objects

Struct public and private works by only allowing access to private sections by the parent object that "owns" the struct. The struct is still data where public members are visible anywhere, but its private members are only visible/modifiable by the object immediately containing it.

IDEKA
struct myStruct
{
    int x, y;
};

object Obj2;

object Obj1
{

    Obj2 myObject();

    // ... required methods ...

    private : Obj2    // Obj2 is a friend class and can inherit Obj1's private members
    {
        // code
    };

    def foo() -> int
    {
        return this.myObject.myStruct.y;    // ERROR - Need to use a getter of Obj2
    };
};

object Obj2
{
    private
    {
        myStruct objStru;
    };

    // ... required methods ...

    def get_y() -> int
    {
        return this.myStruct.y;
    };
};

i-Strings and f-Strings

f-string Example

IDEKA
#import <standard.idk>;

using standard::io::console,
      standard::strings;

def main() -> int
{
    string h = "Hello";
    string w = "World!";
    print(f"{h} {w}");
    return 0;
};

Result: Hello World!

i-string Example The brackets are replaced with the results of the statements in order respective to the statements' position in the statement array in i-strings. This allows you to write clean interpolated strings without strange formatting. It keeps code out of the string making them easier to read.

IDEKA
#import <standard.idk>; // imports types.idk

using standard::io::console;

def bar() -> noopstr { return "World"; };    // We get the non-OOP string type from the types library

def main() -> int
{
    println(i"Hello {} {}" : {bar() + "!"; "test";});

    x = i"Bar {}":{bar()};     // "Bar World!"

    noopstr a = "Hello", b = "World!",
            c = f"{a} {b}";    // "Hello World!"

    println(c);

    return 0;
};

Result: Hello World!


Pointers

A pointer is a variable that holds the address of another value. IDEKA uses three symbols for pointer work:

SyntaxMeaning
T*In a type: pointer to T
@xAddress-of: yields a pointer to x
*pDereference: reads or writes the value p points to

Taking an address

@ produces the address of a variable, array element, object, struct, or function. The result type is a pointer to the operand's type.

IDEKA
int idata = 0;
int* p_idata = @idata;     // p_idata holds the address of idata

Dereferencing

*p accesses the pointed-to value, on either side of an assignment. Compound assignments work through the pointer.

IDEKA
*p_idata += 3;             // idata is now 3
print(idata);              // 3

string a = "Test";
string* pa = @a;
*pa += "ing!";
print(a);                  // Testing!

Function pointers

A function pointer is declared with def{}*, followed by a name, the parameter types, and the return type. Assign a function to it with @. A function pointer is called directly by name; it is dereferenced automatically.

IDEKA
def{}* p_add(int,int)->int = @add;
def{}* p_sub(int,int)->int = @sub;

print(p_add(0,3)); // 3
print(p_sub(5,2)); // 3

Pointers to objects, structs, and arrays

IDEKA
object    myObj {};                 // Definition
object* p_myObj = @myObj;           // Pointer

struct    myStruct {};              // Definition
struct* p_myStruct = @myStruct;     // Pointer

int*[] pi_array = @i_array;         // Array of pointer

Address cast (@)

(@) converts an integer into a pointer, so you do not have to write the pointer type of the cast by hand. The compiler parses (@)expr as a cast of expr to void*, and the result converts to the typed pointer it is assigned to.

IDEKA
uint* px = @x;
u64 kx = (u64)px;       // address stored as an integer
uint* py = (@)kx;       // integer back to a pointer

long val = 0x4700FF33324EBA60;
byte* some_byte = (@)val;

The intended width of the resulting pointer is the compiler's configured default pointer width. That is not implemented yet: currently the width is 32 bits on a 32-bit system and 64 bits on a 64-bit system.

Address-equals @=

@= assigns the address of the right-hand side. T<em> p @= expr; is shorthand for T</em> p = @expr;, and p @= expr; is shorthand for p = @expr;.

IDEKA
int x = 10;
int* px = @x;     // normal
int* px @= x;     // address-equals, same result

It is cleaner when the right-hand side is itself an address:

IDEKA
int* px @= @x;

This is not an identity. px @= @x; is equivalent to px = @@x;: the right-hand side @x is evaluated first and yields a pointer value that lives somewhere on the stack, then the address of that pointer is taken and becomes the value of px. px therefore holds the address of a pointer, not the address of x. IDEKA does not allow writing @@x directly.

const and pointers

The position of const decides what is constant:

IDEKA
const int*  px; // Pointer to const value

const* int* px; // Constant pointer to int pointer

See also Advanced pointer manipulation and Function Pointers below.


You can also use in-line assembly directly:

Assembly in IDEKA is done AT&T style. The constraints follow the block in the pattern outputs : inputs : clobbers Here's an example:

IDEKA
_exchange64(i64* ptr, i64 value, i64* out) -> void
{
    #ifdef __ARCH_X86_64__
    volatile asm
    {
        movq $0, %rsi
        movq $2, %rdi
        movq $1, %rax
        xchgq %rax, (%rsi)
        movq %rax, (%rdi)
    } : : "r"(ptr), "r"(value), "r"(out) : "rax", "rsi", "rdi", "memory";
    #endif;
    #ifdef __ARCH_ARM64__
    volatile asm
    {
    .retry_xchg64:
        ldaxr x0, [$0]
        stlxr w3, x1, [$0]
        cbnz  w3, .retry_xchg64
        str   x0, [$2]
    } : : "r"(ptr), "r"(value), "r"(out) : "x0", "w3", "memory";
    #endif;
};

Here, the clobber list is "r"(ptr), "r"(value), "r"(out) : "x0", "w3", "memory"; Using volatile tags the assembly block for the compiler, saying do not touch this for any reason.


Logic with if/elif/else

IDEKA
if (condition1)
{
    doThis();
}
elif (condition2)      // You can also use `else if`
{
    doThat();
}
else if (condition 3)  // Equivalent to `elif`
{
    doAnythingElse();
}
else
{
    doThings();
};

You can also do if expressions:

IDEKA
int x = 0;
int y = x if (x > 5) else noinit;

You can also use if expressions in the following manner:

IDEKA
#import <standard.idk>;

using standard::io::console;

foo() -> int
{
    return 10;
};

main() -> int
{
    int* px @= 5;  // Take value of the integer literal 5 on the stack at runtime.

    print(foo()) if (px); // if (pointer) is a validity check, true if pointer not null

    -> 0;
};

You may also use groups of statements in a block before an if:

IDEKA
#import <standard.idk>;

using standard::io::console;

foo() -> int
{
    print("Hello");
};
bar() -> void
{
    print(" World!");
};

main() -> int
{
    { foo(); bar(); } if (true);

    -> 0;
};

Ternary logic with the standard ternary ?::

IDEKA
#import <standard.idk>;

using standard::io::console;

main() -> int
{
    int x = 0,
        y = 5;

    int z = x < y ? y : 0; // if x < y then y else 0

    if (z is 5)
    {
        print("Success!");
    };
    -> 0;
};

Ternary assignment ?= (if LHS is null):

IDEKA
#import <standard.idk>;

using standard::io::console;

main() -> int
{
    int x = 10,
        y;

    x ?= 50; // x = 50 if x == 0
    y ?= x;  // y =  x if y == 0

    if (x == y) { println("Success!"); };

    -> 0;
};

Null coalesce ?? operator (result is RHS if LHS is null):

IDEKA
#import <standard.idk>;

using standard::io::console;

main() -> int
{
    int x = 0,
        y = 5;

    int z = y ?? 20; // result 20 if y is null

    if (z is 5)
    {
        print("Success!");
    };
    -> 0;
};

Not null !? operator (boolean unary postfix - is LHS not null):

IDEKA
#import <standard.idk>;

using standard::io::console;

main() -> int
{
    int* px;
    int* py @= px;

    if (px!?) { println("px may be live!"); };

    if (py!?) { println("py is definitely live!"); };

    -> 0;
};

The data keyword

Data is a variable bit width, primitive binary data-type creation keyword. Anything can cast to it, and it can cast to any primitive like char, int, float. It is intended to allow IDEKA programmers to build any basic integer type to fit their needs. Data types use big-endian byte order by default. Manipulate bits as needed. Bit-width bust always be specified.

Syntax for declaring a datatype:

IDEKA
(const) (signed | unsigned) data {bit-width:alignment} (as) your_new_type

//    Example of a non-OOP string:

      unsigned data {8}[] as noopstr;    // Unsigned byte array, default alignment

This allows the creation of primitive, non-OOP types that can construct other types. data creates user-defined types.

For example, you can just keep type-punning: unsigned data{16} as dbyte; dbyte as xbyte; xbyte as ybyte; You can pun and declare a variable as well: ybyte as zbyte zbx = 0xFF;

Data decays to an integer type under the hood. All data is binary, and is therefore an integer.

Minimal specification unsigned data{8} as byte; // 8-bit

Full specification data{width : alignment : endianness}

Example unsigned data{16::0} as custom_le; // 16-bit, 16-bit aligned, little endian

To prevent a custom type from having functions, use data!. See functionless types


Mixing Signed/Unsigned in Expressions

IDEKA
signed data{32} as i32;
unsigned data{32} as u32;

i32 a = -10;
u32 b = 20;

// Mixed arithmetic (result type determined by widest type)
i32 result1 = a + (i32)b;    // -10 + 20 = 10 (signed)
u32 result2 = (u32)a + b;    // 4294967286 + 20 (unsigned, wraps)

// Comparison with mixed signs
if (a < (i32)b)  // true: -10 < 20
{
    print("Signed comparison");
};

if ((u32)a < b)  // false: 4294967286 > 20
{
    print("Unsigned comparison");
};

Endianness Handling

IDEKA
data{16::0} as le16;  // Little-endian 16-bit
data{16}    as be16;  // Big-endian default 16-bit

def swap_endian_16(be value) -> data{16}
{
    data{16::0} v2 = value; // Explicit byte swap on assignment
    return v2;
};

// Network byte order (big-endian) to host (little-endian)
def network_to_host(be16 net_value) -> le16
{
    le16 x = net_value;     // Explicit byte swap on assignment
    return x;
};

// Reading from network buffer
data{8::0}[4] buf = [0x12, 0x34, 0x56, 0x78];
be16[2] net = buf; // autopack and convert endianness
  1. Single-endian arithmetic model - All math is performed in one endianness (big).
  2. Swapping on assignment means the compiler doesn't need to track mixed-endian states through complex expressions.

Casting

Casting in IDEKA is C-like.

IDEKA
float x = 3.14;
i32 y = (i32)x;                  // 3 (numeric conversion, the value is truncated)

// To reinterpret the bits instead, route through a same-size array:
u32 bits = (u32)(u16[2])x;       // 0x4048F5C3 == 1078523331 (bit pattern of 3.14f)

There are only two types. Integers, and floating point decimals. float and double are floating point types. All other types are integer types.

Casting anything to void is the functional equivalent of freeing the memory occupied by that thing. This is dangerous on purpose, it is equivalent to free(ptr) in C. This syntax is considered explicit in IDEKA once you understand the convention. It calls ffree() under the hood, which uses the standard heap allocator. You should not void cast free anything unless it was allocated with fmalloc()

Void casting in relation to the stack and heap

IDEKA
def example() -> void {
    int stackVar = 42; // Stack allocated

    (void)stackVar;    // What happens here?
}

In this case, stackVar is zeroed out and the reference invalidated.

The general casting rules. Every cast falls into one of the following cases, determined by the source and target type pair:

to share the same underlying machine representation (for example, le32 and uint are both a plain 32-bit integer), the cast performs no bit-level work. Instead, the compiler re-tags the value with the target type's metadata. This is the mechanism behind clearing an endianness tag explicitly:

IDEKA
  le32 netValue = ...;
  uint plain = uint(netValue);   // same bits, but now untagged as native/no endianness

target width, sign-extending for signed sources and zero-extending for unsigned sources.

(int)/(long)-style casts from a float or double, convert the numeric value (not the bit pattern) using standard signed conversion. (float)x and (double)x between each other extend or truncate the floating-point value as expected. To convert bits rather than value between an integer and a float of the same width, route through a same-size array (see "Arrays" below).

any other pointer type directly. Pointer to integer normally takes the pointer's address and stores it as an integer value. The one exception is a pointer whose pointee is an array type - casting an array pointer to an integer does not produce the array's address as a number; it packs the array's contents into the integer, following the array-packing rules below. To get the numeric address of an array instead of its packed contents, take the address of the array variable itself and cast through a non-array pointer type first (see "Pointer to integer conversions"). Integer to pointer zero-extends the integer to a full machine address width if it's narrower, then reinterprets it as the target pointer type.

provided both structs have the same total bit width. A size mismatch is a compile-time error - there is no implicit padding or truncation when reinterpreting one struct as another. Casting a struct value to a pointer type takes its address (allocating a temporary stack slot first if the value doesn't already live in memory); casting a struct pointer to another pointer type is a plain reinterpretation.


Direct type conversion:

You can do function-like conversion only with built-in types like int, long, double, bool, etc.

IDEKA
#import <standard.idk>;

using standard::io::console;

def main() -> int
{
    double d = 3.1415925658;

    int i = int(d);

    print(i);

    return 0;
};

Result: 3


The typeof, sizeof, alignof, and endianof built-ins

IDEKA
data{8:8:0}* as lestr;
signed data{13:16} as strange;

sizeof(lestr);    // 8
alignof(lestr);   // 8
typeof(lestr);    // unsigned data{8:8}*
endianof(lestr);  // 0

sizeof(strange);   // 13
alignof(strange);  // 16
typeof(strange);   // signed data{13:16}
endianof(strange); // 1

void as a literal

IDEKA
if (x == void) {...code...};    // If it's nothing, do something
void x;
if (x == !void) {...code...};   // If it's not nothing, do something

In literal context, void is 0. false is also 0, which means void == false;. Therefore, anything can be void-checked.


Arrays

Array declarations have the syntax type[n] var. Never type var[n].

A single dimension array: int[] x = [1,2,3,4,5]; A two dimensional array: int[][] y = [[1,2,3,4],[5,6,7,8]]; A three dimensional array:

IDEKA
int[][][] z = [
                [
                  [ 1,  2,  3], [ 4,  5,  6], [ 7,  8,  9]
                ],
                [
                  [10, 11, 12], [13, 14, 15], [16, 17, 18]
                ],
                [
                  [19, 20, 21], [22, 23, 24], [25, 26, 27]
                ]
              ];

Static array comprehension

Ranges are inclusive on both ends: 1..10 is the ten values 1 through 10.

IDEKA
// Python-style comprehension
int[10] squares = [x ^ 2 for (int x in 1..10)];

// With condition
int[20] evens = [x for (int x in 1..20) if (x % 2 == 0)];

// With type conversion
float[sizeof(int_array)] floats = [(float)x for (int x in int_array)];

// C++-style comprehension
int[10] squares = [x ^ 2 for (int x = 1; x <= 10; x++)];

// With condition
int[20] events = [x for (int x= 1; x <= 20; x++) if (x % 2 == 0)];

Static array comprehension using a dynamic type

IDEKA
#import <standard.idk>;

using standard::collections; // For the dynamic array 'Array'

Array[] myArr = [x.name for (Array x in oldArr) if (x.name.len() > 5)];

Casting between arrays, integers, and floating-point values

Casting a fixed-size array to an integer or floating-point type (and back) packs or unpacks the array element by element, following one fixed convention:

**Element 0 occupies the most significant bits of the integer; the last element occupies the
least significant bits.** This holds regardless of array length, element width, or any
endianness tag on the element type - array packing is always big-endian at the array level.
IDEKA
u64 packed = (u64)[0x12u, 0x34u, 0x56u, 0x78u, 0x9Au, 0xBCu, 0xDEu, 0xF0u];
// packed == 0x123456789ABCDEF0 - element 0 is the highest byte.

byte[8] bytes = (byte[8])packed;
// bytes == [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0]

Floats and doubles participate in the same packing rule by having their raw bit pattern treated as the integer payload for that slot - packing four bytes into a float reinterprets those four bytes' bits as the float's bit pattern (not as a numeric conversion of the bytes' values).

The total bit width must match exactly. Packing an array into an integer (or unpacking an integer into an array) requires element_count * element_bit_width == target_bit_width. There is no implicit zero-padding or truncation to make a mismatched size fit - a three-element byte[3] cannot be packed directly into a 32-bit integer; pack into a 24-bit data{24} instead, or pad the array to four elements first.

Unpacking into a byte or char array adds one extra, null element. (byte[8])someValue allocates and returns nine bytes: the eight packed bytes followed by a 0 terminator, so the result can be used immediately as a C-style string. This applies specifically to 8-bit element arrays; arrays of wider elements (u16[4], for example) are not null-padded.

This packing convention is also what powers the rewrites shown under "Advanced data manipulation techniques" - hash[0..3] = (byte[4])(be32)ctx.state[0]; relies on exactly this element-0-is-high-bits ordering to place the most significant byte of ctx.state[0] at hash[0].

Block initialization with {}

IDEKA
noopstr[3] test =
[
    "String 1", // this is a list of items, not assignment statements
    "string 2",
    "string 3!"
];

test
{
    [0] = "New string!";    // these desugar to individual assignments
    [1] = "Another one!";   // like test[0] = "New string!"; <- would be required here, so sugar requires it
    [2] = "Changed again?"; //
};

Loops

IDEKA supports 2 styles of for loops:

IDEKA
for (x in y)                     // Array iteration
{
    // ... code ...
};

for (int c = 0; c < 10; c++)     // init ; cond ; expr
{
    // ... code ...
};

A for-ever loop: for (;;) {};

A do loop:

IDEKA
do
{
    // some code;
};

You can also do comprehension on while conditions:

IDEKA
do
{
    y[i--] = void;     // Nulled out of array
}
while (x in y & i > 0);

while (condition)
{
    // ... code ...
};

An infinite while loop:

IDEKA
while (true)
{
    // ...
};
// or
while (1)
{
    // ...
};

Membership testing with in

Beyond for (x in y), in is also a general binary operator usable in any expression context - if, ternaries, return, assignments, anywhere a boolean is expected:

IDEKA
int x = 5;
int[5] arr = [1, 2, 3, 4, 5];

if (x in arr) { ... };          // true: 5 is an element of arr
bool found = 3 in arr;

It resolves differently depending on what the needle and haystack look like:

NeedleHaystackBehavior
single valuestring (byte<em>/char</em>)true if that single byte/char occurs anywhere in the string
single valuefixed-size or decayed arraytrue if any element of the array equals the value
array / sub-sequencestringtrue if the sequence occurs as a substring
array / sub-sequencearraytrue if the sequence occurs as a contiguous sub-sequence anywhere in the array
IDEKA
byte* greeting = "Hello, World!";
if ('W' in greeting) { ... };          // true
if ("World" in greeting) { ... };      // true - substring search

int[6] nums = [1, 2, 3, 4, 5, 6];
int[2] pair = [3, 4];
if (pair in nums) { ... };             // true - contiguous sub-sequence

Single-initialized variables with singinit

IDEKA
#import <standard.idk>;

using standard::io::console;

def foo() -> void
{
    singinit int x;
    x += 1;
    print(x); print();
};

def call(int y) -> void
{
    if (y == 0) { return; };
    foo();
    call(--y);
};

def main() -> int
{
    call(10);
    return 0;
};

Recursion:

IDEKA
def rsub(int x, int y) -> int
{
    switch (x == 0 | y == 0)
    {
    };

    rsub(--x,--y);
};

Strict Recursion with <~:

Functions that have the recurse return operator will always return to themselves. Their stack frame never grows because they become tail calls, and get optimized as such.

IDEKA
#import <standard.idk>;

using standard::io::console;

noopstr m1 = "[recurse ",
        m2 = "]";

def recurse1(int x) <~ int
{
    singinit int y;
    print(m1); print(y); println(m2);
    return ++y;
};


def recurse2() <~ void
{
    singinit int z;
    print(m1); print(++z); println(m2);
};


def main() -> int
{
    recurse2(); // Step into tail function
    return 0;
};

Escaping strict recursion with escape

escape can only be used inside a strictly-recursive function defined with a recurse arrow <~. Example:

IDEKA
def recurse2() <~ void
{
    if (!entered_flag) {entered_flag = true;};
    singinit int z;
    print(m1); print(++z); println(m2);
    if (z >= 10) { escape main(); }; // or any other function
};

Error handling with try/throw/catch

IDEKA
unsigned data{8}[] as string;  // Basic string with no functionality (non-OOP string)

object ERR
{
    string e;

    def __init(string e) -> this
    {
        this.e = e;
        return this;
    };

    def __expr() -> string
    {
        return this.e;
    };
};

def myErr(int e) -> void
{
    switch (e)
    {
        case (0)
        {
            ERR myErrObj("Custom error from object myE");
            throw(myErrObj);
        }
        default
        {
            throw("Default error from function myErr()");
        };                                                  // Semicolons only follow the default case.
    };
};

def thisFails() -> bool
{
    return true;
};

def main() -> int
{
    string error = "";
    try
    {
        try
        {
            if(thisFails())
            {
                myErr(0);
            };
        }
        catch (ERR e)                                     // Specifically catch our ERR object
        {
            string err = e.e;
        }                                                 // No semicolon here because this is not the last catch in the try statement
        catch (string x)                                  // Only catch a primitive string (unsigned data{8}[]) thrown
        {
        }                                                 // No semicolon here because this is not the last catch in the try statement
        catch (auto x)
        {
        };                                                // Semicolon follows because it's the last catch in the try/catch sequence.
    }
    catch (string x)
    {
        error = x;  // "Thrown from nested try-catch block."
    };

    return 0;
};

Enumerated Lists

Definition: enum myEnum {val1, val2, val3, val4, ...}; Instance: myEnum newEnum; Member access: newEnum.val1;

Enumerated lists are type int by default. Each item in an enumerated list has an associated ordinality if no value is set. Imagine we want to name index values so we don't have to remember the indexes themselves.

IDEKA
enum Skills
{
    FIREBOLT,    // 0
    ICE_SHARD,   // 1
    THUNDERSTORM // 2
    //...
    // 999
};

Now say we need something more specific, like named pointers. We can't use int on a 64 bit system to store a 64 bit address, so we use a typed enum by putting a type before the enum keyword:

IDEKA
u64 enum PointerMap
{
    DedupSchedule   = 0xDEADBEEFCAFEFOOD,
    ReallocEntities = 0xFFFF00000037EADC,
    _Function3      = 0xF000000000000001,
    //...
    //
};

Then we can create a function pointer to that function:

IDEKA
PointerMap pm;

def foo() -> void = (@)pm.DedupSchedule; // (@) treats the value as an address

foo();

Unions

Prototype: union myUnion; Definition: union myUnion {int iVal; float fVal;}; Insance: myUnion newUnion; Instance with assignment: myUnion newUnion {iVal = 10}; Member access: newUnion.iVal;

Unions are similar to structs, the difference is only one of its members can be initialized at any time. Initializing another member changes the actively initialized member. Attempting to access an uninitialized member results in garbage data for that member.

Example:

IDEKA
union myUnion
{
    int iVal;
    float fVal;
};

myUnion u {iVal = 10};

def main() -> int
{
    u.iVal = 10;   // iVal is the active member
    u.fVal = 3.14; // iVal overwritten by fVal in memory
};

Tagged unions

IDEKA
#import <standard.idk>;

using standard::io::console;

enum ErrorUnionEnum
{
    INACTIVE,
    INT_ACTIVE,
    LONG_ACTIVE,
    BOOL_ACTIVE,
    CHAR_ACTIVE,
    FLOAT_ACTIVE,
    DOUBLE_ACTIVE   
};

union ErrorUnion
{
    int  iRval;
    long lRval;
    bool bRval;
    char cRval;
    float fRval;
    double dRval;
} # ErrorUnionEnum; // # is the 'tag' operator


def foo() -> ErrorUnion
{
    ErrorUnion err;

    err.bRval = false; // Set bool to active element
    err.# = ErrorUnionEnum.BOOL_ACTIVE;

    return err;
};


def main() -> int
{
    ErrorUnion e = foo();

    switch (e.#)
    {
        case (ErrorUnionEnum.INT_ACTIVE) -> print("Integer active in error union!\n");

        case (ErrorUnionEnum.LONG_ACTIVE) -> print("Long active in error union!\n");

        case (ErrorUnionEnum.BOOL_ACTIVE) -> print("Bool active in error union!\n");

        case (ErrorUnionEnum.CHAR_ACTIVE) -> print("Char active in error union!\n");

        case (ErrorUnionEnum.FLOAT_ACTIVE) -> print("Float active in error union!\n");

        case (ErrorUnionEnum.DOUBLE_ACTIVE) -> print("Double active in error union!\n");
    };

    return 0;
};

Dictionaries

Definition: dict{KeyType:ValueType} myDict

Dictionaries keys and values can be any types except objects.

Instance with initializer:

IDEKA
dict{"":""} myDict
{
    "Hello": "World!",
    "hey": "you"
};

Access: myDict["Hello"] Merge: dict{"":""} merged = myDict + myDict2;

Dictionaries are key-value stores with a homogeneous key type and homogeneous value type declared in the dict{K:V} type specifier.

IDEKA
dict{"":""} greetings
{
    "en": "Hello",
    "es": "Hola",
    "jp": "Konnichiwa"
};

println(greetings["en"]); // Hello

Dictionaries can be passed to and returned from functions using the templated dict{T:U} type:

IDEKA
def foo<T,U>(dict{T:U} d) -> dict{T:U} -> d;

Dictionaries can be merged with +:

IDEKA
dict{"":""} a { "x": "1" };
dict{"":""} b { "y": "2" };
dict{"":""} c = a + b;

Inline dict literals with d{}

A d{} expression creates an anonymous dict inline without declaring a named variable. The result can be immediately accessed with [key]:

byte* status = d{true:"Logged In", false:"Guest"}[a.logged_in];

When all keys and values are compile-time constants, the entire expression folds at compile time and is baked directly into the binary with no runtime cost.

IDEKA
// Compile-time constant -- no runtime dict lookup
byte* msg = d{///some computed dictionary///}[///some computed result index///];

The [key] access on a d{} expression is handled by the existing array access postfix, so the inline dict participates naturally in any expression context.


Switching

switch is static, value-based, and non-flexible. Switch statements are for speed.

IDEKA
switch (e)
{
    case (0)
    {
        // Do something
    }
    case (1)
    {
        // Another thing
    }
    default
    {
        // Something else
    };
};

If a case contains only one statement, the braces can be omitted, similar to a single-statement if.


Namespace elimination with !using or not using

This is a very heavy-duty form of DCE. By doing !using you are totally removing a namespace, which in most cases will cause a number of compiler errors from any code still relying on that namespace being available. Once !using is used somewhere, it is permanent. This is not recommended for code elimination unless you know what you're doing and intend this.

IDEKA
!using standard::io::file; // anything that was written with `standard::io::file` available will now error.

not using some::specific::namespace;

Deprecation with deprecate

IDEKA
#import <standard.idk>;

namespace test1
{
    namespace test2
    {
        def foo() -> void {};
    };
};

deprecate test1::test2;

def main() -> int
{
    test1::test2::foo();

    return 0;
};

Compiling gives this output:

IDEKA
✗ Compilation failed: Deprecated namespace 'test1::test2' is still referenced:
Function call test1__test2__foo()

Assertion with assert()

assert automatically performs throw if the condition is false if it's inside a try/catch block, otherwise it writes the message to standard error output and aborts the program.

IDEKA
#import <standard.idk>;

using standard::io::console;

def main() -> int
{
    int x;
    try
    {
        assert(x == 0, "Something is fatally wrong with your computer.");
    }
    catch (string e)
    {
        println(e);
        return -1;
    };
    return x;
};

Heap allocation

IDEKA
heap int x = 5;      // Allocate
(void)x;             // Deallocate

(void) casting works on both stack and heap allocated items. If you do this to a stack element, it is nulled, and all references invalidated. You will need to redeclare x. Doing this to a heap element will call ffree() under the hood.

Allocating with heap calls fmalloc(sizeof(T)) under the hood. x is a pointer.

Freeing from the heap

IDEKA's standard heap allocator is incompatible with C's malloc and free.

You must use ffree for anything allocated with fmalloc, including heap allocations. Alternatively you may void cast.


The Ditto Operator #"

The ditto operator repeats the previous initializer expression in a multi-declarator variable declaration. It is shorthand for writing the same expression again.

IDEKA
ulong p0 = alloc_stub_page(),
      p1 = alloc_stub_page(),
      p2 = alloc_stub_page(),
      p3 = alloc_stub_page(),
      p4 = alloc_stub_page(),
      p5 = alloc_stub_page();

Is identical to:

IDEKA
ulong p0 = alloc_stub_page(),
      p1 = #",
      p2 = #",
      p3 = #",
      p4 = #",
      p5 = #";

This works for any initializer expression, including those with side effects:

IDEKA
int i;
int x = ++i,   // 1
    y = #",    // 2
    z = #";    // 3

Each #" produces an independent evaluation of the repeated expression - it is not a reference to the prior variable's value.

#" must be followed immediately by , or ; in variable declarations. It is not valid as part of a larger expression (for now).


Repeating Statements With Ditto

Using #" on its own line will repeat the statement previous to it. Here's a simple example that should be straightforward enough to understand in all applications. Try not to invent edge cases, they don't exist. If the parser would error, it's not an edge case, it's an error.

IDEKA
#import <standard.idk>;

using standard::io::console;

def main() -> int
{
    println("Hello!");
    #";
    return 0;
};

Result:

IDEKA
Hello!
Hello!

Parameterized Ditto in Function Calls

#" may also appear as a function call argument, where it repeats the argument at the same position from the immediately preceding statement, provided that statement was a call to the same function with the same arity.

IDEKA
foo(x, y, z);
foo(y, #", z);   // identical to foo(y, y, z)

Each #" is replaced by a copy of the corresponding positional argument from the previous call - independently evaluated, not a reference.

IDEKA
foo(x, y, z);
foo(#", #", #");  // identical to foo(x, y, z)

The previous statement must satisfy all of the following, or it is a compiler error:

IDEKA
foo(x, y, z);
bar();
foo(x, #", #");   // error: previous statement was bar, not foo

foo(x, y);
foo(x, #", #");   // error: arity mismatch (2 vs 3)

foo(x, y, z);
a + b;
foo(x, #", #");   // error: previous statement is not a function call

Ditto in argument lists always refers to the previous statement, not the previous argument. Chaining across multiple calls works naturally:

IDEKA
foo(x, y, z);   // prints "1 2 3"
foo(#", #", #"); // prints "1 2 3"
foo(#", #", #"); // prints "1 2 3"

Example program:

IDEKA
#import <standard.idk>;

using standard::io::console;


def foo(int a, int b, int c) -> void
{
    println(f"{a} {b} {c}");
};

def main() -> int
{
    int i;
    int x = ++i,
        y = #",
        z = #";

    foo(x, y, z);
    foo(y, #", #");
    foo(z, #", #");

    return 0;
};

Output:

IDEKA
1 2 3
2 2 3
3 2 3

Custom operators and overloading

IDEKA allows you to define many types of operators. | Form | Definition | Usage | |---|---|---| | Binary | operator (int L, i32 R) [+++] -> int { ... }; | a +++ b | | Unary, prefix | operator (i32 a) [!!] -> int { ... } # binding {this:}; | !!a | | Unary, postfix | operator (i32 a) [&] -> int { ... } # binding {:this}; | a& | | Ternary | operator (int a, i32 b, byte c) [$%][%$] -> int { ... }; | a $% b %$ c | | Circumfix | operator (i32 x) [|][|] -> int { ... }; | |x| | | Variadic | See Variadic Operators |

IDEKA
operator (int L, int R) [+++] -> int
{
    return ++L + ++R;
};

Usage: a +++ b

IDEKA
operator (int L, int R) [NOPOR] -> bool
{
    return !L | !R;
};

Usage: a NOPOR b

Overloading built-in operators is allowed, with rules.

  1. One parameter must not be a built-in type.
  2. The precedence and associativity cannot be changed.
IDEKA
operator (int L, BigInt R) [+] -> bool
{
    // Implementation for adding an int and a BigInt
};

Each symbol is either a bare identifier or a run of the language's existing punctuation tokens. Identifier symbols such as NOPOR read as word operators.

Unary. A one-parameter operator is unary only when it carries # binding after the body, written before the closing ;. {this:} makes it prefix (the operand follows the symbol) and {:this} makes it postfix (the operand precedes the symbol). # binding is only valid on an operator with exactly one parameter. A prefix operator takes a unary expression as its operand, like built-in -x or *p.

IDEKA
operator (i32 a) [&] -> int
{
    return ++a;
} # binding {:this};

int y = 9&;      // 10

Ternary. Two bracket groups and three parameters. The left symbol sits between the first and second operands and the right symbol between the second and third. Both symbols are required at the use site; a missing right symbol is a compile error.

IDEKA
operator (int a, int b, byte c) [$%][%$] -> int
{
    return a + b * c;
};

int x = 1 $% 2 %$ 3;   // 7

Circumfix. Two bracket groups and one parameter. The operand sits between the left and right symbols, and the two symbols may be identical. A missing closing symbol is a compile error.

IDEKA
operator (int x) [|][|] -> int -> x < void ? -x : x;

int m = 5 * |a|;

Binding to an existing function. A function may be declared as an operator with as operator[...], written after the return type and before the body or ;. The function is then usable with that symbol. The same forms apply: one bracket group for binary, two for ternary or circumfix, and # binding {...} for unary.

IDEKA
add(int a, i32 b) -> int as operator[\]
{
    return a + b;
};

int s = 5\2;   // 7

Precedence. Binary, ternary, and variadic custom operators share one tier between +/- and <em>///%, always left-associative, and their operands are parsed at the </em> tier. Prefix and circumfix operators bind at the unary tier, and postfix operators at the postfix tier, alongside [], . and ++. Parenthesize to get any other grouping.

How this actually works under the hood:

A symbol that isn't already one of IDEKA's built-in operators (anything not found in the "Operator list") is registered as a new piece of grammar. From that point on, the parser recognizes that exact token sequence anywhere an expression is expected and rewrites it directly into a call to the operator's generated function. This rewrite happens at one single, fixed precedence tier - between +/- and <em>///%/^, always left-associative - no matter what the symbol looks like or what a programmer might expect a symbol like <=> or </em>* to bind like in another language. If you want a custom operator to behave as though it binds tighter or looser than that tier, parenthesize at the call site.

A custom symbol can be either a single bare identifier (NOPOR, used like a word-operator) or a sequence of the language's existing punctuation tokens glued together (+++, <=>, ??= are all legal, since +, <, =, >, ? are each already meaningful punctuation on their own).

When the bracketed symbol is one of the language's built-in operators, nothing changes about how that symbol parses - + still parses as ordinary addition, at its normal precedence, because the parser never rewrites built-in symbols into function calls the way it does for new ones. This is the actual mechanism behind rule 2 above: there is no separate code path for an overloaded + to take at parse time. Resolution happens later, during code generation: for every + expression, the compiler checks whether a registered overload exists whose two parameter types exactly match the operands' types, and calls that function instead of emitting the native add instruction if so. If no overload matches the operand types, the built-in behavior runs as normal.

Rule 1 above ("one parameter must not be a built-in type") is enforced as a compile error, not just a convention: an attempt to overload + for two plain primitives (int and int, float and double, etc.) is rejected, specifically so that user overloads can never silently hijack ordinary primitive arithmetic everywhere it's used. A non-built-in parameter is a struct, an object, a custom data type alias, or a pointer.

Templated operators declare their concrete instantiation lazily:

IDEKA
operator<T> (T L, T R) [+] -> T
{
    // ...
};

Each time that operator symbol is used in an expression with operand types the compiler can determine, it automatically generates a concrete overload for that specific pair of types (if one hasn't already been generated). The same non-built-in-parameter restriction still applies once concrete types are known: a templated + is never instantiated for an expression where both operands turn out to be plain primitives.

Custom operators accept the exact same pre- and post-contract syntax as ordinary functions (see "Functions and contract" and "Contracts on operators" below) - the contract's assertions are spliced into the operator's generated function body at compile time, so they run on every call that dispatches to that specific overload, whether the call arrived through the rewritten-call-site path (new symbols) or the type-matched-dispatch path (built-in overloads).


Variadic Operators

A variadic operator is one symbol used in a chain of operands. Every use of the symbol and every operand is recorded, and the same operator function receives four values describing the chain:

operator count: how many times the symbol appears in the chain. parameter count: how many operands appear in the chain. is leading: the chain starts with the symbol, so there is no operand before the first one. is trailing: the chain ends with the symbol, so there is no operand after the last one.

ChainOperator countParameter countLeadingTrailing
a ##;11noyes
## a;11yesno
## a ##;21yesyes
a ## b;12nono
## a ## b;22yesno
a ## b ##;22noyes
## a ## b ##;32yesyes

The operator count follows from the other three values: operator count = parameter count - 1 + leading + trailing. The count alone cannot tell a ## b apart from ## a ##, because both have one fewer or equal operands than symbols. Leading and trailing are what separate them.

Here's an example of a variadic operator:

IDEKA
#import <standard.idk>;

using standard::io::console;

// varop.idk - Variadic Operator example

operator(...) [##] -> void
{
    println(f"Operator count:    {##}");
    println(f"Operand count:     {...}");
    println(f"Is {$##} leading:  " + "true" if (##.is_leading) else "false");
    println(f"Is {$##} trailing: " + "true" if (##.is_trailing) else "false");
};

main() -> int
{
    ## 0 ## 1 ## 2 ## 3 ##;
    -> 0;
};

Output:

IDEKA
Operator count:    5
Operand count:     4
Is ## leading:  true
Is ## trailing: true

Functions and contract

Contracts are compile time function modification. They prepend or append the code contained to a function's body.

Pre-contract form puts the contract's statements before the function's code. Post-contract form puts the contract's statements before the function's return.

Currently post-contracts insert before all return points, including error returns. There will be an update soon for post-contract return sites.

Contracts are not specifically assert-only, they can contain any statement. They are similar to macros and expand before type checking and semantic analysis.

IDEKA
#import <standard.idk>;

using standard::io::console;

contract NonZero
{
    assert(x > 0, "x must be positive");
};

contract rValGT10
{
    assert(x > 10, "x must be greater than 10");
};

def foo(int x) -> int : NonZero
{
    x = x / 2;
    return x;
} : rValGT10;

def main() -> int
{
    int y = foo(30);   // 30 / 2 = 15, passes both contracts

    return 0;
};

Turns into:

IDEKA
def foo(int x) -> int : NonZero
{
    assert(x > 0, "x must be positive");
    x = x / 2;
    assert(x > 10, "x must be greater than 10");
    return x;
};

The contracts disappear from the compilation unit after transformation.


Contract # binding

A contract may declare a binding that the compiler enforces at every function that attaches it. The binding specifies which other contracts must (or must not) appear as pre- or post-contracts on the same function, and in what order. This lets a contract author express relationships between contracts and catch misuse at compile time rather than at runtime.

Syntax

IDEKA
contract Name(params)
{
    // body
} # binding { pre_side : post_side };

The binding block is written after the contract body, before the terminating ;.

pre_side describes what must or must not appear as a pre-contract on any function that attaches Name:

FormMeaning
!No pre-contracts are allowed on that function.
thisName itself must be used as a pre-contract (not post).
OtherContractOtherContract must also be a pre-contract on the function.
this, OtherContractBoth requirements apply, in that order.

post_side describes what must or must not appear as a post-contract:

FormMeaning
!No post-contracts are allowed on that function.
thisName itself must be used as a post-contract (not pre).
A, BBoth A and B must be post-contracts, in that order (,).
`A \B`Any subset of A, B that is present must appear in that order (`\`).
A & BBoth A and B must be post-contracts, in any order (&).
!AA must not be a post-contract on the function.
A(2)Specifically the two-parameter overload of A is required.

The pre and post sides are separated by :.

Examples

Require the contract itself to be a pre-contract only (never post):

IDEKA
contract Validated(x)
{
    assert(x != 0, "x must not be zero");
} # binding { this : ! };

// OK -- Validated is pre
def foo(int x) -> int : Validated(x) { return x * 2; };

// ERROR -- Validated is post, binding requires it to be pre
def bar(int x) -> int { return x; } : Validated(x);

Require a companion post-contract whenever this contract is used as pre:

IDEKA
contract CheckInput(x)
{
    assert(x > 0, "input must be positive");
} # binding { this : CheckOutput };

contract CheckOutput
{
    assert(rval > 0, "output must be positive");
};

// OK
def process(int x) -> int : CheckInput(x) { return x + 1; } : CheckOutput;

// ERROR -- CheckOutput is missing
def process2(int x) -> int : CheckInput(x) { return x + 1; };

Forbid any pre-contracts when this contract is used as post:

IDEKA
contract Finalize
{
    cleanup();
} # binding { ! : this };

// OK -- no pre-contracts, Finalize is post
def shutdown() -> void { do_work(); } : Finalize;

// ERROR -- SomeSetup is a pre-contract, binding forbids pre-contracts
def shutdown2() -> void : SomeSetup { do_work(); } : Finalize;

Require two post-contracts in order:

IDEKA
contract Stage1
{
    log("stage 1");
} # binding { this : Stage2, Stage3 };

contract Stage2 { log("stage 2"); };
contract Stage3 { log("stage 3"); };

// OK
def pipeline() -> void : Stage1 { work(); } : Stage2 : Stage3;

// ERROR -- wrong order
def pipeline2() -> void : Stage1 { work(); } : Stage3 : Stage2;

Forward declarations

Contracts may be forward-declared before their body is defined, including in comma-separated lists:

IDEKA
contract A, B(x, y), C;

A binding may only be placed on the definition, not the forward declaration.

Compiler errors

When a function violates a binding, the compiler emits an error at the function definition naming the contract whose binding was violated, which side (pre or post) was violated, and what was required vs. what was found.


Contracts on operators:

IDEKA
#import <standard.idk>;

using standard::io::console;

contract NonZero(a,b)
{
    assert(a != 0, "a must be nonzero");
    assert(b != 0, "b must be nonzero");
};

operator(int x, i32 y)[+] -> int : NonZero(x,y)
{
    return x+y;
};


def main() -> int
{
    0 + 4;

    return 0;
};

Result at runtime: a must be nonzero


Expression-based macros with macro

IDEKA
#import <standard.idk>;

using standard::io::console;

macro xyz(a,b,c)
{
    (a + b) ^ c
};

def main() -> int
{
    int x, y, z = 1, 2, 3;

    println(f"xyz(abc) = {xyz(x,y,z)}");

    return 0;
};
IDEKA
println(f"xyz(abc) = {(1 + 2) ^ 3}");

Result: xyz(abc) = 27


Defining Type Functions:

IDEKA has the ability to define functions for a given type, allowing . call notation on a value or variable of that type. Inside of a type function _ is reserved, and acts as the this parameter.

IDEKA
// noopstr is alias for byte*
noopstr.add_world() -> noopstr
{
    return _ + ", World!";  //  "Hello".add_world() == return "Hello" + ", World!"
};

/// Alternatively, you may use "" - Note this is special for type functions ///
"".add_world() -> ""
{
    return _ + ", World!";
};

You can use plain types or pointer types, and named struct types, like so:

IDEKA
struct MyStru
{
    // .. members ..
};

MyStru.mystru_func1() -> MyStru
{
    // impl
};

You may also use tied ~types:

IDEKA
~byte*.sub11() -> ~byte*
{
    return _[0] - 11; // set first char - 11, _ is tied type, no need for explicit move
};

You can make literal modifiers as well by using 0 with an appropriate suffix:

IDEKA
0.my_int_func() -> int   // 55.my_int_func()
{
    return _;
};

0l.my_long_func() -> long
{
    return _;
};

0d.my_double_func() -> double
{
    return _;
};

struct.my_struct_func() -> struct
{
    // impl for your arbitrary struct func
};

Functionless Types

To forbid a type from having functions, you can declare it with data! like so:

IDEKA
#import <standard.idk>;

using standard::io::console;

data!{32} as u32i;

u32i.foo() -> u32i { return 0u; };

def main() -> int
{
    return 0;
};

The compiler will error with: ✗ Compilation failed: Type u32i is non-functional (declared with data!) and cannot have type functions defined on it at x:y


<Templates>

Templates in IDEKA are extremely simple.

There are no keywords for templates, only syntax, and involve only type substitution. There is no SFINAE, so templates are not subject to the pitfalls SFINAE allows.

Templates can be applied to functions, structs, objects, and custom operator definitions.

Here's an example of using a template:

IDEKA
#import <standard.idk>;


def foo<T>(T x) -> T
{
    return x;
};


def main() -> int
{
    float y = foo<float>(5.5f);
    int z = foo<int>(3);

    println(y);
    println(z);

    system("pause");
    return 0;
};

The compiler can also infer templates at call sites, so you don't end up with a mess of angle brackets:

IDEKA
#import <standard.idk>;

using standard::io::console;

struct myStru<T>
{
    T a, b;
};

def foo<T, U>(T a, U b) -> U
{
    return a.a * b;
};

def bar(myStru<int> a, int b) -> int
{
    return foo(a, 3); // inferred from signature via 'a'
};

def main() -> int
{
    myStru<int> ms = {10,20};

    //int w = foo<myStru<int>, int>(ms, 3); // <brackets> at call site

    int x = foo(ms, 3); // inferred locally

    int y = bar(ms, 3);

    println(x == y);
    return 0;
};

Template Constraints:

You can add constraints to template parameters on their allowed types like so:

IDEKA
<T: int | i32, U: long | i64>

The syntax is Param: type (| type)* comma separated.

Here's an example:

IDEKA
#import <standard.idk>;
 
using standard::io::console;

"".idk<T: "", U: "">(T x, U y) -> ""
{
    return _ + f"{x} {y}";
};

def main() -> int
{
    byte* new = "Hello".idk(",", "World!");
    println(new);
    return 0;
};

"new" isn't a keyword in IDEKA, so this is fine.

To set a default type constraint, use + before the type like so:

IDEKA
<T: +float | int>

To enforce no default constraint, use !+ before your parameter like so:

IDEKA
<!+T: float | int>

Using + on any constraint type when the parameter has no default set with !+ will throw a compiler error.

Templates and Type Relationships

IDEKA allows ways to describe how a type - or pair of types - can behave.

There is a dedicated type relationships operator set specifically to describe relations between types. Since all operators are binary, to perform a unary operation, you do A <op> A, which is type self-referential. All template type relationships operators are distinct and not related to regular operators and cannot be overloaded.

See the Algebraic Types documentation for more details on the operators.

To use type relationships expressions, they must be constrained in a set.

Here's the same example using ~=, the "must be compatible" operator, and the :{} set constraint.

IDEKA
#import <standard.idk>;
 
using standard::io::console;

"".idk<T: "", U: "", :{T ~= U}>(T x, U y) -> ""
{
    return _ + f"{x} {y}";
};

def main() -> int
{
    byte* new = "Hello".idk(",", "World!");
    println(new);
    return 0;
};

You can separate expressions with a comma like:

IDEKA
#import <standard.idk>;
 
using standard::io::console;

"".idk<T: "", U: "", :{T ~= U, T !`< U}>(T x, U y) -> ""
{
    return _ + f"{x} {y}";
};

def main() -> int
{
    byte* new = "Hello".idk(",", "World!");
    println(new);
    return 0;
};

However, you do not have to comma separate, and can instead write them circularly. Circular expressions can be very long, terse, and carry a lot of meaning. Example:

IDEKA
D !~= B & [A !@ A] !~= C !`< D !-= A

This reads as (inner most []):

There is a similar relationship here, D !~= A & B !~= C. This means D ~= C by relation, and doesn't need to be explicitly defined. This is the type geometry of IDEKA.

This can be hard to see if you do not write your expression with care, because you may intend D !~= C. See the following:

IDEKA
C !~= D !~= B & [A !@ A] !~= C !`< D !-= A

Just place the relationship in an open position.

No one wants to see that long expression in their template definition, that's why constraint exists. constraint creates named, generic and parameterized relational expression sets that can be used with a template like so:

IDEKA
#import <standard.idk>;
 
using standard::io::console;

constraint MyCS(A)
{
    A !`< A    // This is a unary expression, read as the relation !`< "between A types"
};

def foo<T: int, :{MyCS}>(T x) -> byte
{
    return 5 + x; // lowering would occur here, violating MyCS
};

def main() -> int
{
    foo(10);
    return 0;
};

Compiler will output:

IDEKA
✗ Compilation failed: Type relation T !`< T violated: illegal truncation on int at 12:5
    return 5 + x;
----^ // 5 + x will lower to byte

The complete type-relationship operator set and what each one enforces once a template is instantiated with concrete types:

OperatorMeaningScope
~=The two types must be compatiblepairwise
!~=The two types must be incompatiblepairwise
!@A variable of this type must never have its address taken (@) anywhere in the template bodyindependent
` !< ``This type must never appear as either side of a narrowing (truncating) conversion in the bodyindependent
` !<= ``A narrowing conversion specifically between these two named types is forbiddenbetween
` !> ``This type must never appear as either side of a widening conversion in the bodyindependent
` !>= ``A widening conversion specifically between these two named types is forbiddenbetween

"Compatible" (for ~=/!~=) means: both types are pointers or both are non-pointers; if both are pointers, their pointer depth matches; and if both have a known bit width, the widths are equal.

The independent vs between distinction matters once more than two parameters are in play. ` T !< T ` (independent, self-referential, as in the MyCS example above) forbids T from ever being narrowed by <em>anything</em> - any cast or implicit arithmetic narrowing involving T's width is a violation, regardless of what the other side of that conversion is. T !<= U ` (between) only forbids narrowing conversions where <em>both</em> the source and destination widths belong to {T, U} specifically - narrowing T` to some unrelated third type is still allowed.

These checks aren't purely static type comparisons - for the truncation/widening operators, the compiler walks the instantiated function body looking for the actual operations that would violate the constraint: explicit casts ((Type)expr), return statements whose expression is wider or narrower than the declared return type, and ordinary arithmetic where an implicit narrowing happens because one operand is wider than the other. This is exactly how the MyCS example above produces a violation from return 5 + x; with no explicit cast in sight - the + between an int literal and a byte-constrained x implicitly narrows the result, and that narrowing context is what gets flagged.

Joining multiple names with & lets one relation apply to a whole group of parameters at once: T & U ~= V requires both T and U to individually satisfy ~= V. This reuses the ordinary & (logical AND) token, but inside a constraint set it's a list-joiner for the relation's operands, not a boolean evaluation of two relation results.

You can comma separate named constraints in your template definition like so: <T: int, :{MyCS1, MyCS2, MyCS3}>

Template constraints can be used in any template, including operator, struct, and object templates.

Named constraint sets can be merged, combining the relations of two or more existing sets into a new one:

IDEKA
constraint MyCS3 = MyCS1 + MyCS2;

All sources must declare the same number of parameters. The merged set adopts the first source's parameter names unless you supply your own rename list before the =:

IDEKA
constraint MyCS3(M, N) = MyCS1 + MyCS2;

Relations from every source are carried over into the merged set, with each source's own parameter names remapped to the merged set's names.

IDEKA
struct myStru<A,B>
{
    A ax, ay, az;
    B bx, by, bz;
};

Composition and templates can be combined, however they will shadow.

IDEKA
struct myStru1<A,B>
{
    A a1x, a1y;
    B b1x, b1y;
};

struct myStru2<A,B,C> : myStru1
{
    A a2x, a2y, a2z;
    B b2x, b2y, b2z;
};

// Becomes,

struct myStru2<A,B,C>
{
    A a1x, a1y;
    B b1x, b1y;
    A a2x, a2y, a2z;
    B b2x, b2y, b2z;
};

If you intended for a1x to be a different type than a2x, you must use different parameter names.

Structs cannot contain objects, but objects can contain structs. This means struct template parameters cannot be object type.

Templating operators:

IDEKA
operator<T, K>(T t, K k)[+] -> int
{
    return t + k;
};

Combining templates, contracts, and operators:

IDEKA
#import <standard.idk>;

using standard::io::console;

struct myStru<T>
{
    T a, b;
};

def foo<T, U>(T a, U b) -> U
{
    return a.a * b;
};

def bar(myStru<int> a, int b) -> int
{
    return foo(a, 3); // Template inferred from parameter
};

macro macNZ(x)
{
    x != 0
};

contract ctNonZero(a,b)
{
    assert(macNZ(a), "a must be nonzero");
    assert(macNZ(b), "b must be nonzero");
};

contract ctGreaterThanZero(a,b)
{
    assert(a > 0, "a must be greater than zero");
    assert(b > 0, "b must be greater than zero");
};

operator<T, K>(T t, K k)[+] -> int : ctNonZero(t,k)
{
    return t + k;
} : ctGreaterThanZero(t,k);

def main() -> int
{
    myStru<int> ms = {10,20};

    int x = foo(ms, 3); // Template inferred from myStru<int> above

    i32 y = bar(ms, 3);

    println(x + y);

    return 0;
};

Result: 60


Advanced pointer manipulation

Taking address of literals

IDEKA
// You can take the address of a literal value
int* p = @42;
print(*p);  // 42

// The address can be manipulated as an integer
unsigned data{64}* as u64ptr;
u64ptr addr = (u64ptr)p;
addr += 8;  // Move 8 bytes forward in memory
int* p2 = (int*)addr;

// Pointer arithmetic on literal addresses
int* base = @100;
int* offset = base + 5;
*offset = 200;  // Writing to calculated memory location

Pointer to integer conversions

IDEKA
#import <standard.idk>;

using standard::io::console;

def main() -> int
{
    uint x, y = 10, 0;

    uint* px, py = @x, @y;

    // A pointer is simply a variable and its value is an address
    // An address is a number.
    // Therefore, we can store that address
    //
    u64 kx = px;

    // (@) is address-cast. It reinterprets the number as an address
    // When we treat a number as an address, we call that a pointer.
    // Therefore, we can assign this to another pointer.
    //
    py = (@)kx;

    // py now points to x

    // Dereference py to get the value at the address
    // Cast to make sure it's the proper type to print

    if (x == 10 & y == 0 & *py == x & px == py & px == (@)kx)
    {
        print("Success, y unchanged, py points to x.\n");
        print((uint)*py);
        return 0;
    };

        return 0;
};

Memory Layout and Alignment Tricks

Bit-Field Manipulation

IDEKA
// 13-bit signed value, 16-bit aligned
signed data{13:16} as strange13;

strange13 value = 0x0FFF;  // Max positive value for 13 bits
print(value);              // 4095

value = 0x1000;            // Sign bit set (bit 12)
print(value);              // -4096 (two's complement)

// Extract specific bit ranges
u32 packed = 0x12345678;

def extract_bits(uint32 value, int start, int length) -> uint32
{
    uint32 mask = ((1 << length) - 1) << start;
    return (value & mask) >> start;
};

uint32 nibble0 = extract_bits(packed, 0, 4);   // 0x8
uint32 nibble3 = extract_bits(packed, 12, 4);  // 0x5
uint32 byte1 = extract_bits(packed, 8, 8);     // 0x56

Advanced data manipulation techniques

C:

IDEKA
len_block[0]  = (byte)((aad_bits    >> 56) & 0xFF);
len_block[1]  = (byte)((aad_bits    >> 48) & 0xFF);
len_block[2]  = (byte)((aad_bits    >> 40) & 0xFF);
len_block[3]  = (byte)((aad_bits    >> 32) & 0xFF);
len_block[4]  = (byte)((aad_bits    >> 24) & 0xFF);
len_block[5]  = (byte)((aad_bits    >> 16) & 0xFF);
len_block[6]  = (byte)((aad_bits    >>  8) & 0xFF);
len_block[7]  = (byte)( aad_bits           & 0xFF);
len_block[8]  = (byte)((cipher_bits >> 56) & 0xFF);
len_block[9]  = (byte)((cipher_bits >> 48) & 0xFF);
len_block[10] = (byte)((cipher_bits >> 40) & 0xFF);
len_block[11] = (byte)((cipher_bits >> 32) & 0xFF);
len_block[12] = (byte)((cipher_bits >> 24) & 0xFF);
len_block[13] = (byte)((cipher_bits >> 16) & 0xFF);
len_block[14] = (byte)((cipher_bits >>  8) & 0xFF);
len_block[15] = (byte)( cipher_bits        & 0xFF);

IDEKA equivalent

IDEKA
len_block[0..7]  = (byte[8])(u64)aad_bits;
len_block[8..15] = (byte[8])(u64)cipher_bits;
IDEKA
uint* pd = @p.digits[0];

// Proper IDEKA
pd = [0xFFFFFFEDu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu,
      0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu];

/// C-like
pd[0] = 0xFFFFFFED;
pd[1] = 0xFFFFFFFF;
pd[2] = 0xFFFFFFFF;
pd[3] = 0xFFFFFFFF;
pd[4] = 0xFFFFFFFF;
pd[5] = 0xFFFFFFFF;
pd[6] = 0xFFFFFFFF;
pd[7] = 0x7FFFFFFF;
///

Reworking a loop

IDEKA
for (i = 0; i < 4; i++)
{
    hash[i] = (byte)((ctx.state[0] >> (24 - i * 8)) & 0xFF);
    hash[i + 4] = (byte)((ctx.state[1] >> (24 - i * 8)) & 0xFF);
    hash[i + 8] = (byte)((ctx.state[2] >> (24 - i * 8)) & 0xFF);
    hash[i + 12] = (byte)((ctx.state[3] >> (24 - i * 8)) & 0xFF);
    hash[i + 16] = (byte)((ctx.state[4] >> (24 - i * 8)) & 0xFF);
    hash[i + 20] = (byte)((ctx.state[5] >> (24 - i * 8)) & 0xFF);
    hash[i + 24] = (byte)((ctx.state[6] >> (24 - i * 8)) & 0xFF);
    hash[i + 28] = (byte)((ctx.state[7] >> (24 - i * 8)) & 0xFF);
};

Turns into:

IDEKA
hash[0..3]   = (byte[4])(be32)ctx.state[0];
hash[4..7]   = (byte[4])(be32)ctx.state[1];
hash[8..11]  = (byte[4])(be32)ctx.state[2];
hash[12..15] = (byte[4])(be32)ctx.state[3];
hash[16..19] = (byte[4])(be32)ctx.state[4];
hash[20..23] = (byte[4])(be32)ctx.state[5];
hash[24..27] = (byte[4])(be32)ctx.state[6];
hash[28..31] = (byte[4])(be32)ctx.state[7];

Bit Slices

The bit-slice operator ` x[ab] ` addresses individual bits of a value using one consistent numbering scheme: bit 0 is the most significant bit of the entire value, and bit numbers increase moving toward the least significant bit. This numbering runs across the whole source - for a struct, it continues across field boundaries in declaration order, exactly as if the struct's fields had been concatenated into one big-endian buffer. Because struct members are packed tightly with no padding between them (see "Structs"), bit numbering never has to skip over hidden padding bits when it crosses from one member into the next - member N's last bit is immediately followed by member N+1's first bit.

A slice written with the start index greater than the end index (as in the example below) reads the same bit range but reverses the order of the bits in the result. Bit slices may span up to the full width of a native integer type (8 through 64 bits).

Bit slices are distinct from array slices: x[a:b] selects elements of an array by index, while ` x[ab] ` selects bits of a value.

IDEKA
#import <standard.idk>;

using standard::io::console;

main() -> int
{
    byte x = 55;

    x[0``7] = x[7``0]; // Reverse the bits

    println(int(x)); // 236

    return 0;
};

Taking bit slices from structs

Bit slicing structs can cross member boundaries, because structs members are packed tightly in memory. If a type inside the struct has an alignment greater than its width, there will be padding in the struct. Padding from alignment is filled with zeros.

IDEKA
#import <standard.idk>;

using standard::io::console;

struct xx { int a, b; };

main() -> int
{
    data{4} as u4;
    xx yy = {5,10};
    u4 a = yy[60``63]; // 10 because 0b1010

    print((int)a);

    return 0;
};

Bit slices of bit slices

IDEKA
#import <standard.idk>;

using standard::io::console;

struct xx { int a, b; };

main() -> int
{
    data{4} as u4;
    data{2} as u2;
    xx yy = {5,10};
    u4 a = yy[60``63]; // 10 because 0b1010
    u2 b = a[0``1];

    print(int(b)); // 2, because 0b10

    return 0;
};

Bit-slice results are ordinary integer values of the slice's width, so a bit slice can itself be the source of another bit slice - there's no special chaining logic, it falls out naturally.

Assigning into a bit slice ( x[ab] = value;) replaces just that bit range in place, leaving every other bit of the target untouched:

IDEKA
u32 packed = 0x12345678;
packed[24``31] = 0xFF;   // replace just the lowest byte
// packed == 0x123456FF

The assignment target must be a plain variable, and the start/end indices must be compile-time constants.

Bit Indexing

Let's say you want to mess with individual bits without storing it in a new 1 bit type variable. Bit indexing lets you target a specific bit of a value, or even a struct!

IDEKA
#import <standard.idk>;

using standard::io::console;

main() -> int
{
        byte b;

        b[`7] = 1;

        print("Success!") if (b == 1);
        -> b[`0];
};

Bit Iteration

To iterate over the bits of a value or struct, use bitwise iteration. Here's what that looks like:

IDEKA
#import <standard.idk>;

using standard::io::console;

def main() -> int
{
    int i = 420691337;

    for (`x in i)  // "for bit x in i"
    {
        print((int)x);  // x is a data{1} type
    };

    -> 0;
};

Output:

IDEKA
00011001000100110011110110001001

This iterates through the bits of i, where x equals the bit at i[`current_iteration].


Advanced Data Type Features

Unusual Bit Widths

IDEKA
// 3-bit unsigned value (0-7)
unsigned data{3} as tiny = 5;

// 17-bit signed value
signed data{17} as weird17 = -1000;

// 7-bit with 8-bit alignment (1 bit padding)
unsigned data{7:8} as aligned7 = 127;

// Array of 5-bit values
unsigned data{5}[10] as 5b_array arr;
arr[0] = 0x1F;  // Max value for 5 bits

// Casting between weird widths
unsigned data{13} as u13 a = 8191;
unsigned data{17} as u17 b = (u17)a;  // Zero-extend
signed data{13} as s13 c = (s13)a;    // Truncate LTR, losing most significant bits

You may take arbitrary width slices as well, stored in your arbitrarily sized types.


Function Pointers

IDEKA
#import <standard.idk>;

using standard::io::console;

def foo(int x) -> int
{
    print("Inside foo!\n");
    return 0;   
};


def main() -> int
{
    def{}* pfoo(int)->int = @foo;
    print("Function pointer created.\n");
    print();

    pfoo(0); // Compiler auto dereferences

    return 0;
};

Callbacks

One of a few ways you can set up callbacks:

IDEKA
#import <standard.idk>;

using standard::io::console;

def foo() -> void
{
    println("In foo()!");
};

def callback(long x) -> int
{
    def{}* cb()->void = x;
    cb();
    return 0;
};

def main() -> int
{
    callback(long(@foo));
    return 0;
};

Raw bytecode functions

IDEKA
#import <standard.idk>;

using standard::io::console;

def main() -> int
{
    byte[] some_bytecode = [0x48, 0x31, 0xC0, 0xC3];  // xor rax,rax ; ret
    def{}* fp()->void = @some_bytecode;
    fp();
    
    return 0;
};

Ownership with the tie operator ~

Ownership only occurs if you use ~ to tell the compiler to perform a very simple set of rules:

A function returning a tied type cannot return to a variable of non-tied type. Similarly, you cannot pass a non-tied variable to a tied parameter.

IDEKA
#import <standard.idk>;

def foo(~int z) -> void  // accepts a tied parameter
{
    return;
};

def main() -> int
{
    ~int x;
    int  y;  // Non-tied var

    foo(~x); // Untie from main, tie to foo()

    foo(~x); // Compile error, use after untie

    foo(y);  // Compile error, foo expects tied param

    return 0;
};

Control Flow Edge Cases

Nested Switches with Fallthrough

IDEKA
def classify_value(int x, int y) -> void
{
    switch (x)
    {
        case (0)
        {
            switch (y)
            {
                case (0)
                {
                    print("Both zero");
                }
                case (1)
                {
                    print("X zero, Y one");
                }
                default
                {
                    print("X zero, Y other");
                };
            };
        }
        case (1)
        {
            print("X is one");
        }
        default
        {
            print("X is other");
        };
    };
};

Complex Try/Catch with Multiple Types

IDEKA
object ErrorA
{
    int code;
    def __init(int c) -> this { this.code = c; return this; };
    def __exit() -> void {return;};
};

object ErrorB
{
    string message;
    def __init(string m) -> this { this.message = m; return this; };
    def __exit() -> void {return;};
};

def risky_operation(int mode) -> void
{
    if (mode == 1)
    {
        throw(ErrorA(100));
    }
    elif (mode == 2)
    {
        throw(ErrorB("Something failed"));
    }
    else
    {
        throw("Generic error");
    };
};

def main() -> int
{
    try
    {
        risky_operation(1);
    }
    catch (ErrorA e)
    {
        print(f"ErrorA caught: code {e.code}");
    }
    catch (ErrorB e)
    {
        print(f"ErrorB caught: {e.message}");
    }
    catch (string s)
    {
        print(f"String error: {s}");
    }
    catch (auto x)
    {
        print("Unknown error type");
    };
    
    return 0;
};

Nested Loops with Break/Continue

IDEKA
def find_in_matrix(int[][] matrix, int target) -> bool
{
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            if (matrix[i][j] == target)
            {
                print(f"Found at [{i}][{j}]");
                return true;  // Break out of both loops
            };
            
            if (matrix[i][j] < 0)
            {
                continue;  // Skip negative values
            };
        };
    };
    
    return false;
};

// Do-while with complex condition
def wait_for_ready(int* status_reg) -> void
{
    int timeout = 1000;
    do
    {
        if (*status_reg & 0x01)  // Ready bit
        {
            break;
        };
        timeout--;
    }
    while (timeout > 0 & !(*status_reg & 0x80));  // Not error bit
};

Simple Packet Parser

IDEKA

struct IPHeader
{
    nybble version, ihl;
    byte tos;
    be16 total_length, identification, flags_offset;
    byte ttl, protocol;
    be16 checksum;
    be32 src_addr, dst_addr;
};

def parse_ip_header(bytes* packet) -> IPHeader
{
    IPHeader* header = (IPHeader*)packet;
    return *header;
};

def format_ip(be32 addr) -> string
{
    bytes* bp = (bytes*)@addr;
    return f"{bp[0]}.{bp[1]}.{bp[2]}.{bp[3]}";
};

// Usage
bytes packet_data = [
    0x45, 0x00, 0x00, 0x3c,  // Version=4, IHL=5, ToS=0, Length=60
    0x1c, 0x46, 0x40, 0x00,  // ID, Flags
    0x40, 0x06, 0xb1, 0xe6,  // TTL=64, Protocol=TCP, Checksum
    0xc0, 0xa8, 0x01, 0x01,  // Source: 192.168.1.1
    0xc0, 0xa8, 0x01, 0x02   // Dest: 192.168.1.2
];

IPHeader hdr = parse_ip_header(@packet_data[0]);
print(f"Source: {format_ip(hdr.src_addr)}");
print(f"Dest: {format_ip(hdr.dst_addr)}");

Fixed-Point Math

IDEKA
// 16.16 fixed-point format
signed data{32} as fixed16_16;

def to_fixed(float value) -> fixed16_16
{
    return (fixed16_16)(value * 65536.0);
};

def from_fixed(fixed16_16 value) -> float
{
    return (float)value / 65536.0;
};

def fixed_mul(fixed16_16 a, fixed16_16 b) -> fixed16_16
{
    i64 temp = ((i64)a * (i64)b) >> 16;
    return (fixed16_16)temp;
};

def fixed_div(fixed16_16 a, fixed16_16 b) -> fixed16_16
{
    i64 temp = ((i64)a << 16) / (i64)b;
    return (fixed16_16)temp;
};

// Usage
fixed16_16 a = to_fixed(3.14159),
           b = to_fixed(2.0);
fixed16_16 result = fixed_mul(a, b);
print(from_fixed(result));  // approx 6.28318

Type System Edge Cases

void semantics

IDEKA
// Void as a value
void x = void;      // Cannot have void type, only void pointer
void* px = @0;      // Null void pointer. Allocates a 0 and takes its address
                    // Based on default pointer width (64)

if (px is void)
{
    print("px is null");
};

// Conditional void assignment
void y = condition ? void : some_value;

// Void in arrays (creates holes)
int[] sparse = [1, 2, void, 4, void, 6];
if (sparse[2] == void)
{
    sparse[2] = 3;  // Fill the hole
};

// Function returning void pointer
def get_nullable() -> int*
{
    if (error_condition)
    {
        return (int*)void;  // Return null
    };
    return @some_value;
};

Calling Conventions

IDEKA allows you to use different calling conventions at the language level.

IDEKA
stdcall foobar() -> void;

def is fastcall by default. You may change this in the configuration. You may also create function pointers of different calling conventions:

IDEKA
vectorcall{}* someSIMDfunc() -> u64*;

Stringification with $:

IDEKA
#import <standard.idk>;

using standard::io::console;

def main() -> int
{
    int Hello = 5;

    println($Hello);
    return 0;
};

Result: Hello

Codification:

Codification is the inverse of stringification, using the codify operator ~$

IDEKA
#import <standard.idk>;

using standard::io::console;

def main() -> int
{
    byte* test = "int x = 5;";

    ~$test;

    println(x);
    
    return 0;
};

Result: 5


Compile-Time Execution with comptime

IDEKA can execute itself at compile time. It is capable of performing I/O as well. For now IDEKA will be limited to standard I/O and file I/O. Networking will come in a future update.

A dedicated VM was created to handle compile time execution, and is what powers the REPL (coming soon).

To perform compile time code execution in IDEKA, wrap code in a comptime block.

Compile-time code has no main function, the start of execution is at the first statement. Here's an example of programming at compile time:

IDEKA
#import <standard.idk>;

comptime
{
    def foo() -> void
    {
        compiler.io.console.print("Hello from compile time!\n");
    };
};

def main() -> int
{
    return 0;
};

This program will do nothing, because foo() was not called. The compiler will not automatically call a function that it sees, simply call it afterwards.

IDEKA
#import <standard.idk>;

comptime
{
    def foo() -> void
    {
        compiler.io.console.print("Hello from compile time!\n");
    };

    foo();
};

def main() -> int
{
    return 0;
};

Result:

IDEKA
[INFO] [lexer] ► Lexical analysis
[INFO] [parser] ► Parsing
[INFO] [parser] ► AST generated.
[INFO] [codegen] ► LLVM IR code generation
[AST] Begining codegen for IDEKA program ...
[AST] Total statements in AST: 45
[AST] Namespace definitions: 10
[AST] Pass 1: Processing using statements...
[AST] Pass 2: Processing not using statements...
[AST] Pre-pass: Registering all object types and extern blocks...
[AST] Pass 3: Processing all other statements...
Hello from compile time!
[AST] Pass 4: Re-emitting pending bodies...
[INFO] [compiler] ► Compiling to object file (Windows)
[INFO] [llc] opt IR optimization pass complete
[INFO] [linker] ► Linking executable: ./test.exe
✓ Compilation completed: ./test.exe

You can spread functions across comptime blocks like so:

IDEKA
#import <standard.idk>;
 
using standard::io::console;

comptime
{
    def foo() -> void
    {
        compiler.io.console.print("comptime foo!!!\n");
    };
};

comptime
{
    foo();

    int x;
    int* px = @x;

    compiler.io.console.print(f"Hello from comptime! {ulong(px)}\n");
};

def main() -> int
{
    return 0;
};

Result:

IDEKA
[INFO] [lexer] ► Lexical analysis
[INFO] [parser] ► Parsing
[INFO] [parser] ► AST generated.
[INFO] [codegen] ► LLVM IR code generation
[AST] Begining codegen for IDEKA program ...
[AST] Total statements in AST: 47
[AST] Namespace definitions: 10
[AST] Pass 1: Processing using statements...
[AST] Pass 2: Processing not using statements...
[AST] Pre-pass: Registering all object types and extern blocks...
[AST] Pass 3: Processing all other statements...
comptime foo!!!
Hello from comptime! 17
[AST] Pass 4: Re-emitting pending bodies...

You may use any keyword inside comptime blocks except for comptime itself. Yes, you may write an infinite loop at compile time.


emitideka - Compile-Time Code Generation

emitideka is used inside a comptime block to inject IDEKA source code into the surrounding scope. The emitted definitions are deferred and finalized during Pass 4 ("Re-emitting pending bodies"), so they do not need to be written contiguously - you can build up a single logical definition across multiple emitideka calls within one or more comptime blocks.

Basic usage:

IDEKA
comptime
{
    int x = 42;

    emitideka
    {
        def get_x() -> int { return ~$f"{x}"; };
    };
};

// get_x() is now available at runtime
def main() -> int
{
    return get_x();   // returns 42
};

~$f"..." and ~$i"..." expand comptime variables into identifiers or expressions inside an emitideka block.


Splice terminators

By default the closing }; of an emitideka block ends emission and returns control to the surrounding comptime context. Two special terminators allow you to interleave comptime logic with emitted code - splicing a single logical construct across multiple emitideka calls:

}#; - exit emitideka, stay in comptime

}#; terminates the current emitideka block and returns to the surrounding comptime context, leaving the emitted construct open. This lets you run arbitrary comptime code (loops, conditionals, I/O) between emitted chunks.

#}; - close a brace inside emitideka without ending it

#}; emits a closing brace into the generated IDEKA source without being interpreted as the closing brace of the emitideka block itself. Use this to close switch, if, function bodies, or any other braced construct inside emitted code when the bare } would prematurely end the emitideka.

How to tell them apart

Both terminators are the same two characters in a different order. The position of the # says which brace it belongs to:

IDEKA
#};   // # is on the inside: it closes an inner brace of the emitted code (do not end the splice yet)
}#;   // # is on the outside: it attaches to the `{` of the emitideka block itself, leaving the emitted construct open

Braces opened in one emitideka fragment are closed by #}; in a later fragment, so the spliced construct is balanced across the whole splice even though no single fragment is balanced on its own.


Spliced code generation example

The following generates a dispatch function whose switch body is built case-by-case in a comptime loop:

IDEKA
#def NUM_OPS 4;

comptime
{
    byte*[NUM_OPS] op_names = ["add", "sub", "mul", "div"];

    // Step 1: open the function and switch, then exit emitideka with }#;
    emitideka
    {
        def dispatch(int id, int a, int b) -> int
        {
            switch (id)
            {
    }#;

    // Step 2: comptime loop emits one case per op
    int i = 0;
    while (i < NUM_OPS)
    {
        byte* nm = op_names[i];
        int   iv = i;

        emitideka
        {
                case (~$i"{}":{iv;}) { return ~$i"op_{}":{nm;} (a, b); }
        };

        i++;
    };

    // Step 3: close switch and function using #}; to avoid ending emitideka
    emitideka
    {
                default { return -1; };
           #};   // closes switch body
       #};       // closes function body
    };
};

Pass 4 collects all of the emitted fragments in order and finalizes dispatch as a single coherent function. The comptime loop runs during Pass 3 and is never present in the output binary.


Execution order

PassWhat happens
Pass 3comptime blocks execute; emitideka fragments are collected
Pass 4All collected emitideka fragments are finalized into the surrounding scope

This means emitted definitions are always available to runtime code, but are not visible to other comptime blocks that execute before Pass 4.


Async Functions

An async function is declared with async before the calling convention position. Async is colorless: the function is called like any other function, and the compiler decides when a call becomes a concurrent task. There is no await keyword and no future type in the source. The future is implicit.

IDEKA
async fill(i32* table, i32 lo, i32 hi) -> void
{
    i32 i = lo;
    while (i < hi) { table[i] = i + 1; i++; };
};

Example of async used with a calling convention:

IDEKA
async vectorcall some_simd_func(...) -> SIMDResult*;

When a call launches a task

A call to an async function launches a task only in one of these positions:

PositionExample
Statement expressionfill(@t[0], 0, 512);
Variable initializeri64 s = sum_range(@t[0], 0, 512);
Right-hand side of an assignments = sum_range(@t[0], 0, 512);

Any other position (an argument, an operand, a condition) is an ordinary synchronous call.

IDEKA
fill(@t[0], 0, 512);                      // launches a task
i64 s = sum_range(@t[0], 0, 512);         // launches a task
print(sum_range(@t[0], 0, 512));          // synchronous: the call is an argument

When a task is joined

A task is joined at the earliest of:

  1. The first use of its result variable.
  2. The end of the enclosing block.

Joins at block end are emitted through defer, so they run in reverse order of launch (free first, then join). A task that returns void has no result variable and is joined at block end.

Requirements

Async lowering uses the threading library and the heap runtime, so the program must import it:

IDEKA
#import <standard.idk>, <atomics.idk>, <threading.idk>;

Without it the compiler reports: [ASYNC] error: async lowering needs the threading library; add #import <threading.idk>;

Async tags

By default the compiler infers what each async function reads and writes and orders conflicting tasks sequentially. A tag states relations between calls so that independent work can overlap.

Defining a tag

IDEKA
async Tag(a, b)
{
    a # b;
    b > a;
};

A tag has a name, a list of formal parameters, and a body of relation statements. Each statement is lhs OP rhs where lhs and rhs are formal parameters.

Relation operators

OperatorMeaningKind
a # bDisjoint: a and b touch disjoint memoryClaim, checked
a ~ bCommute: overlapping accesses are atomic, any order is correctClaim, checked
a ! bMutual exclusion: never run at the same time, any orderEnforced with a mutex
x > yy waits for x: x must finish before y startsOrdering

# and ~ are claims about the code. The compiler verifies them and rejects a contradicted claim. ! is enforced: each ! group gets a global Mutex that the task holds while it runs. > is an ordering edge between two calls.

A relation between a parameter and itself (a # a) applies between two calls of the same function.

Attaching a tag

A tag is attached after the function body with #<Tag>(targets):

IDEKA
async sum_range(i32* table, i32 lo, i32 hi) -> i64
{
    ...
} #<After>(this, fill);

The targets bind positionally to the tag's formal parameters. A target is one of:

TargetBinds to
thisThe function being defined
nameThe async function name
name(types)The overload of name with those parameter types
name(types)->retThe overload with those parameter types and return type

Several clauses may be attached to one function: } #<A>(this) #<B>(this, other);

Footprints and checking

For each async function the compiler computes a footprint: a set of (param, const) terms over half-open ranges with read, write or free modes. Reads never conflict with reads. Operations from standard::atomic count as atomic accesses.

SituationResult
A # or ~ claim is contradicted by the codeasync_contradiction, always fatal, printed even in warn mode
Two calls conflict and no relation covers themasync_conflict: downgraded to sequential execution in warn mode, an error under --borrowcheck

Static errors

Lowering

For each launched call the compiler generates a frame struct __af_N holding the arguments and result, a trampoline __af_N_run, and a thread_create call. Each ! group gets a global Mutex __am_i. The threading and heap runtime functions are added as DCE roots.

Example

IDEKA
async Disjoint(a) { a # a; };
async After(a, b) { b > a; };

async fill(i32* table, i32 lo, i32 hi) -> void { ... } #<Disjoint>(this);
async sum_range(i32* table, i32 lo, i32 hi) -> i64 { ... } #<After>(this, fill);

def main() -> int
{
    i32[1024] table;
    fill(@table[0], 0, 512);          // runs concurrently with the next call
    fill(@table[0], 512, 1024);       // disjoint ranges, no conflict
    i64 lo = sum_range(@table[0], 0, 512);     // waits for fill
    i64 hi = sum_range(@table[0], 512, 1024);
    return (int)(lo + hi != (i64)524800);      // joins at first use of lo and hi
};

Modules and Build Blocks

A module is a named unit of a program with its own build settings. Modules let one file hold several programs, let modules be pulled in from other files with from, and let each module opt in to checks such as borrow checking.

A module is either defined in place or referenced from a source file.

Defining a module

IDEKA
module Name
{
    def main() -> int { ... };
}
# build
{
    #[entrypoint] = this,
    #[name] = prog,
    #[borrow_check] = true,
    #[requires] = {Logging, Net},
};

Referencing a module with from

IDEKA
module TargetName from "target_source.idk";   // module from a file
module TargetName from <target_source.idk>;   // module from the standard library

This declares TargetName as the module of that name found in the given source. Quotes give a path resolved relative to the including file, then relative to the working directory; angle brackets name a standard library module. A missing file or an include cycle is an error.

A referenced module is not part of a build until a module lists it in #[requires].

Using modules with #[requires]

#[requires] = {M1, M2, M3, ...} lists the modules a module uses. Each name must be a module defined in the same file or declared with module ... from.

IDEKA
module Logging from "logging.idk";
module Net     from <net.idk>;

module App
{
    def main() -> int { ... };
}
# build
{
    #[requires] = {Logging, Net},
};

Placement

Build tags

TagDefaultValues
entrypointthisthis or a module name
namemodule nameOutput name
targetexecutableexecutable, bootloader, compact, library, driver (validated only, other targets are not yet routed)
debugfalsebool
borrow_checkfalsebool
effect_checkfalsebool
dcetruebool, false makes every function of the module a DCE root
requires{}List of module names this module uses
using{}List of namespaces, acts as a global using
platform{} (any)List such as {Windows, Linux, Darwin}, case-insensitive

An unknown tag is an error.

Overrides and locks

A module can set tags on other modules:

IDEKA
#[override for {Logging}] = { #[borrow_check] = true },

Overrides are applied breadth-first from the entry module, so the override closest to the entry wins. The override target must be a known module. entrypoint cannot be overridden, and an override block cannot itself be locked.

!+ before a tag locks it: !+#[borrow_check] = false. A locked tag ignores overrides.

The command line flags --borrowcheck and --effects force the checks on for every module, including locked ones.

Programs

A module in the root file is a program if it defines main or sets #[entrypoint] = this. A file with several programs builds each one separately (one subprocess per program, equivalent to --module NAME). Only the entry module of a build keeps its main. If no program is found, the compiler reports an error. If platform does not include the current platform, the build reports a platform mismatch.

Modules in the same file see each other without from. A sibling that is not reached through #[requires] is not in the entry's module graph, so its checks are off for that build.

Flatten order is dependencies first, then siblings, then the entry module last.

Per-module checks

The borrow checker, the effects checker and dead code elimination are applied per module. Violations are attributed to the function that owns them and filtered to the modules with the check enabled. Violations with an unknown owner are kept. Each live checked module prints one line:

IDEKA
[INFO] [FBC] ► Borrow checking Name

Output

IDEKA
build/<name>/<Platform>/Release/<name>[.exe]
build/<name>/<Platform>/Debug/<name>[.exe]

When a file builds several programs the last line is Compilation successful: build/{A, B} (executable).

Command line

FlagMeaning
--module NAMEBuild only the named program
--borrowcheckForce the borrow checker on for every module
--effectsForce the effects checker on for every module

Errors

ErrorCause
cyclefrom references form a cycle
missing filefrom names a file that is not found
no programNo module defines main or sets #[entrypoint] = this
platform mismatchplatform excludes the current platform
unknown tagA #[tag] that does not exist
unknown override targetoverride for {M} names an unknown module
cannot override entrypointOverride sets entrypoint
cannot lock an override!+ on an override entry
nestingModule or module reference inside a function, namespace or module

The Effect System - Algebraic Effect Tracking

See IDEKA Effect System for a more thorough explanation of effects.

Effects are compile-time properties of computation. They describe what a function does beyond its return value - whether it allocates, touches IO, modifies memory, hooks into running code, or any other observable behavior. The compiler tracks these properties statically, enforces constraints across call chains, and erases them entirely before codegen and has zero runtime cost.


Overview

An effect is a label. An effect is a set of relationships between other effects. The algebra is what makes it possible for the compiler to reason about functions without inherently knowing what the labels mean.

There are two annotation sites: origin and boundary.

Origin (# effect {}) declares what effects a function introduces.

Boundary (# attenuate {}) declares what effects are contained and cannot escape a function's interface.

Everything in between is inferred. Effects propagate transitively up the call chain without annotation. If a calls b calls c, and c introduces Alloc.Heap, then a's transitive effect set includes Alloc.Heap even if b has no annotation. The compiler computes this through fixed-point propagation over the full call graph.


Syntax

Effect declaration

IDEKA
effect Name { expr };
effect Name.Sub { expr };

Declares a user-defined named effect. The body is an effect algebra expression. Effect names may be dot-separated to express namespacing. User-defined effects compose on top of built-in effects.

IDEKA
effect ShadowStack { *Hook & !@Unsafe & !Alloc };
effect RealTime    { !Alloc & !IO & !Throw };
effect NetworkIO   { *IO.Socket & [Mem.Write | Mem.Read] };

Origin annotation

IDEKA
def foo() -> void # effect { expr };
def foo() -> void { ... };

Declares that foo introduces the effects described by expr. The annotation goes on the prototype. Definitions inherit it -- you do not repeat the tag on the definition site.

Tags may be chained in any order after contracts:

IDEKA
def foo() -> void : SomeContract # effect {*Alloc.Heap} # attenuate {IO};
def foo() -> void { ... };

Tags may also appear after the closing brace of a definition body:

IDEKA
def foo() -> void
{
    ...
} # effect {*IO.Console};

Compiler Flags

FlagBehavior
(default)Transparent -- annotations stored, no enforcement
--effects-warnViolations reported as warnings, compilation continues
--effectsViolations are errors, compilation aborted

Operator Set

All operators are only valid inside effect {} and # attenuate {} blocks.

Unary operators

OperatorMeaning
*XImplies X -- X propagates upward through the call chain
!XExcludes X -- X must not be present
~XRequires X -- X must already be present
?XWeak propagation -- X propagates but can be suppressed
@XExplicitly marks X as attenuatable at a boundary
!@XPermanently non-attenuatable -- X can never be stripped
^XSuppresses X even if something else implies it
..XPropagates exactly one level up, then stops
...XPropagates indefinitely (this is the default behavior)
<*XPropagates to the caller only, not further up the chain

Binary operators

OperatorMeaning
X & YBoth X and Y must hold
`X \Y`At least one of X or Y must hold
X > YX takes priority over Y at conflict boundaries
X -> YIf X is present then Y must also be present
`X ^Y`Exactly one of X or Y -- exclusive or
X <-> YMutual implication -- both present or neither
X <-> !YIf X present then Y must be absent, and vice versa

Grouping

Parentheses () and brackets [] both group subexpressions and are interchangeable.


Propagation Rules

  1. Effects propagate implicitly up the call chain through fixed-point analysis.

No annotation is needed at intermediate functions.

  1. Only two annotation sites exist: origin (# effect {}) and boundary

(# attenuate {}).

  1. *X in an effect definition means introducing that effect also introduces X.
  1. !@X means X cannot be stripped at any boundary. The compiler rejects any

# attenuate {X} attempt on a !@ effect.

  1. ?X propagates unless explicitly suppressed with ^X somewhere in the chain.
  1. ..X stops propagating after one level up from the annotated function.
  1. ...X propagates indefinitely. This is the default for unannotated effects.
  1. <*X propagates to the immediate caller only, not further up.
  1. Parent effects imply all children. IO implies IO.Console, IO.File, etc.
  1. Attenuating a parent blocks all children. # attenuate {IO} blocks all IO.*.
  1. Attenuating a child is precise. # attenuate {IO.Socket} only blocks network IO,

leaving IO.File and all other IO.* to propagate normally.

  1. Attenuation applies to transitive effects too. If foo calls bar which

introduces IO.Console, and foo declares # attenuate {IO}, then callers of foo see no IO effect regardless of what bar does internally.


Conflict Detection

When a function's transitive effect set violates a constraint declared by a user-defined effect it references, the compiler reports a conflict.

Exclusive or (^|)

X ^| Y means exactly one of X or Y may be present in the function's transitive set. If both are found, it is a conflict.

IDEKA
effect ExclusiveIO { IO.Console ^| IO.File };

// Conflict: introduces both sides of the exclusive-or.
def bad() -> void # effect {ExclusiveIO};
def bad() -> void
{
    write_console("x");
    read_file("y");
};

// OK: introduces only one side.
def good() -> void # effect {ExclusiveIO};
def good() -> void
{
    write_console("x");
};

Mutual implication (<->)

X <-> Y means both or neither must be present. X <-> !Y means if X is present then Y must be absent.

IDEKA
effect ReadOnly { *Mem.Read <-> !Mem.Write };

// Conflict: both Mem.Read and Mem.Write present, violating <-> !Mem.Write.
def bad() -> void # effect {ReadOnly};
def bad() -> void
{
    read_process_memory(addr);
    write_exec_memory(addr, 0);
};

// OK: only Mem.Read present.
def good() -> void # effect {ReadOnly};
def good() -> void
{
    read_process_memory(addr);
};

Pure Enforcement

Pure is a special anchor effect. A function declaring Pure must not transitively introduce any of: IO, Alloc, Mem.Write, Throw. The compiler verifies this against the full transitive call graph.

IDEKA
// OK: only calls other Pure functions.
def add(int a, int b) -> int # effect {Pure};
def add(int a, int b) -> int { -> a + b; };

// Violation: calls heap allocator, which introduces Alloc.Heap.
def bad() -> int # effect {Pure};
def bad() -> int
{
    void* p = allocate_something();
    -> 0;
};

Built-in Effects

Built-in effects are defined by the compiler and cannot be redefined or made self-referential. They are namespaced with . -- capital letter distinguishes effect namespaces from code namespaces (IO.Socket vs standard::io::socket).

IO family

EffectDescription
IOAny external communication
IO.Consolestdin / stdout / stderr
IO.FileFilesystem read or write
IO.SocketNetwork communication
IO.PipeIPC and named pipes
IO.DeviceHardware device communication
IO.SerialSerial port
IO.USBUSB device IO
IO.GPUGPU command submission

Alloc family

EffectDescription
AllocAny allocation
Alloc.HeapStandard heap allocation
Alloc.PoolPool or arena allocator
Alloc.StackStack allocation (VLAs etc.)
Alloc.VirtualVirtualAlloc / mmap -- page-level
Alloc.SharedShared memory allocation

Unsafe family

All Unsafe.* effects carry !@ -- they are permanently non-attenuatable.

EffectDescription
UnsafeAny unsafe operation
Unsafe.PtrRaw pointer dereference
Unsafe.CastUnsafe type cast
Unsafe.ASMInline assembly
Unsafe.FFICalling foreign functions
Unsafe.UninitReading uninitialized memory

Mem family

EffectDescription
MemAny memory operation
Mem.ReadAny memory read
Mem.Read.ProcessReading another process
Mem.Read.KernelKernel memory read
Mem.Read.MappedMapped file or shared memory read
Mem.WriteAny memory write
Mem.Write.ProcessWriting another process
Mem.Write.KernelKernel memory write
Mem.Write.ExecWriting executable memory
Mem.Write.MappedMapped file or shared memory write
Mem.ExecExecuting memory directly
Mem.Exec.JITJIT-compiled execution
Mem.Exec.ShellcodeRaw shellcode execution

Sync family

EffectDescription
SyncAny synchronization operation
Sync.LockMutex or critical section
Sync.AtomicAtomic operations
Sync.SignalSignals or events
Sync.WaitBlocking wait

Crypto family

EffectDescription
CryptoAny cryptographic operation
Crypto.HashHashing
Crypto.EncryptEncryption
Crypto.DecryptDecryption
Crypto.RandomRandom number generation
Crypto.KeyKey generation or management

Process family

EffectDescription
ProcessAny process operation
Process.SpawnCreating processes
Process.KillTerminating processes
Process.InjectCode injection
Process.SuspendSuspending or resuming threads
Process.TokenToken or privilege manipulation

Hook family

EffectDescription
HookAny hooking operation
Hook.DetourInline detour or trampoline
Hook.IATImport address table hook
Hook.SSDTSSDT hook (kernel)
Hook.VtableVtable hook
Hook.ExceptionException handler hook

Privilege family

EffectDescription
PrivilegeAny privilege operation
Privilege.ElevatePrivilege escalation
Privilege.DropPrivilege dropping
Privilege.CheckPrivilege checking

Time family

EffectDescription
TimeAny time-sensitive operation
Time.RealTimeHard real-time constraint
Time.SleepThread sleep or delay
Time.TimerTimer creation or management

Anchor effects

EffectDescription
PureNo side effects -- implies !IO & !Alloc & !Mem.Write & !Throw
ThrowCan raise exceptions

Built-in Implication Rules

Some effects automatically imply others when introduced. These implications are applied transitively by the compiler without requiring explicit annotation.

EffectImplies
Hook.DetourHook, Unsafe, Mem.Write.Exec
Hook.IATHook, Mem.Write
Hook.SSDTHook, Privilege, Mem.Write.Kernel, Unsafe
Hook.VtableHook, Mem.Write
Process.InjectProcess, Alloc.Virtual, Mem.Write.Exec, Hook, Unsafe
Crypto.KeyCrypto

Primitive Effect Sources

Certain language constructs introduce effects implicitly without requiring annotation. The compiler seeds these into the call graph automatically.

SourceEffect introduced
heap allocationAlloc.Heap
Inline asm blockUnsafe.ASM
Raw pointer dereferenceUnsafe.Ptr
throw statementThrow
Unsafe castUnsafe.Cast
FFI callUnsafe.FFI

Complete Example

IDEKA
// Real-time constraint: no allocation, no IO, no exceptions.
effect RealTime { !Alloc & !IO & !Throw };

// Shadow stack: uses hooks, permanent Unsafe, no allocation.
effect ShadowStack { *Hook & !@Unsafe & !Alloc };

// Pure math -- no side effects.
def dot_product(float* a, float* b, uint n) -> float # effect {Pure};
def dot_product(float* a, float* b, uint n) -> float
{
    float acc;
    uint  i;
    while (i < n) { acc += a[i] * b[i]; i++; };
    -> acc;
};

// Real-time safe: only calls Pure functions.
def rt_update(float* state, float* input, uint n) -> void # effect {RealTime};
def rt_update(float* state, float* input, uint n) -> void
{
    float v = dot_product(state, input, n);
    state[0] = v;
};

// Attenuates its own IO -- callers see no IO effect from this function.
def log_event(byte* msg) -> void # attenuate {IO};
def log_event(byte* msg) -> void
{
    write_to_ring_buffer(msg);
};

// Shadow stack install: uses detour hook, permanent Unsafe, zero allocation.
def install_shadow_stack(void* target) -> void # effect {ShadowStack};
def install_shadow_stack(void* target) -> void
{
    hook_detour(target, (@)void);
};

Notes

Effect annotations on prototypes are inherited by definitions. You do not repeat the tag at the definition site.

User-defined effects compose freely on top of built-ins. An effect body is evaluated by the same algebra engine as all other effect expressions -- there is no separate language for defining effects.

The > priority operator inside an effect definition resolves conflicts at boundaries deterministically. Without it, two conflicting effects at a boundary produce a conflict diagnostic. With it, the compiler applies the declared ordering and proceeds.

The effect system is purely compile-time. Nothing is emitted. Effects disappear before codegen. The binary is affected only indirectly -- through what the effect system proves, which feeds optimizer signals like Pure and !Alloc.


Keyword list:

IDEKA
and, as, asm, assert, async, auto, bool, break, byte, case, catch,
cdecl, char, comptime, const, constraint, continue, contract, data, def, default, defer,
deprecate, dict, do, double, effect, elif, else, emitideka, enum, error, escape, export, extern,
false, fastcall, float, for, from, global, goto, has, heap, if, in, inline, int, interface, is,  
jump, label, local, long, macro, module (contextual, top level only), namespace, noinit, noreturn, not, object,
operator, or, private, public, register, return, signed, singinit,
stack, stdcall, struct, switch, this, thiscall, throw, trait, true,
try, uint, ulong, union, unsigned, using, vectorcall, void,
volatile, while, xor

Compiler Built-Ins:

The compiler. namespace:

Operator list:

IDEKA
ADD = "+"
SUB = "-"
INCREMENT = "++"
DECREMENT = "--"
MUL = "*"
DIV = "/"
MOD = "%"
NOT = "!"
POWER = "^"
# Logical
AND = "&"
OR = "|"
NAND = "!&"
NOR = "!|"
XOR = "^|"
# Comparison
EQUAL = "=="
NOT_EQUAL = "!="
LESS_THAN = "<"
LESS_EQUAL = "<="
GREATER_THAN = ">"
GREATER_EQUAL = ">="
# Assignment
ASSIGN = "="
PLUS_ASSIGN = "+="
MINUS_ASSIGN = "-="
MULTIPLY_ASSIGN = "*="
DIVIDE_ASSIGN = "/="
MODULO_ASSIGN = "%="
POWER_ASSIGN = "^="
# Bitwise operators
# Logical
BITNOT = "`!"
BITAND = "`&"
BITOR = "`|"
BITNAND = "`!&"
BITNOR = "`!|"
BITXOR = "`^|"
BITXNOT = "`^|!"
BITXNAND = "`^|!&"
BITXNOR = "`^|!|"
# Assignment
AND_ASSIGN = "&="
OR_ASSIGN = "|="
XOR_ASSIGN = "^|="
BITAND_ASSIGN = "`&="
BITOR_ASSIGN = "`|="
BITNAND_ASSIGN = "`!&="
BITNOR_ASSIGN = "`!|="
BITXOR_ASSIGN = "`^|="
BITXNOT_ASSIGN = "`^|!="
BITXNAND_ASSIGN = "`^|!&="
BITXNOR_ASSIGN = "`^|!|="

# Ternary operators / Null-oriented operators
TERN_ASSIGN = "?="  // Assign if LHS is null
NOT_NULL = "!?"     // unary boolean postfix operator, primary use for pointers `if (px!?) {...};`
NULL_COALESCE = "??"

# Async tag relations (inside `async Tag(...) { }` bodies)
ASYNC_DISJOINT = "#"   // a # b : disjoint footprints (claim)
ASYNC_COMMUTE = "~"    // a ~ b : overlapping accesses commute (claim)
ASYNC_EXCLUDE = "!"    // a ! b : mutual exclusion (mutex)
ASYNC_BEFORE = ">"     // x > y : y waits for x

# Async tag use and module build locks
ASYNC_TAG_USE = "#<Tag>(...)"  // after an async function body
BUILD_LOCK = "!+"              // prefix on a build entry, locks it against overrides

# Shift
BITSHIFT_LEFT = "<<"
BITSHIFT_RIGHT = ">>"
BITSHIFT_LEFT_ASSIGN = "<<="
BITSHIFT_RIGHT_ASSIGN = ">>="

BITSLICE = "``"

ADDRESS_OF = "@"
ADDRESS_ASSIGN = "@="
ADDRESS_CAST = "(@)"
RANGE = ".."
SCOPE = "::"
QUESTION = "?"
COLON = ":"
TIE = "~"
STRINGIFY = "$"
RETURN_ARROW = "->"
CHAIN_ARROW = "<-"
RECURSE_ARROW = "<~"      // def foo() <~ void;  // Emits musttail, 0 stack growth
NO_MANGLE = "!!"          // prevent the compiler from mangling the function name
FUNCTION_POINTER = "{}*"
DITTO =  #"

Operator Precedence and Associativity

IDEKA's operators bind in the following order, from loosest (evaluated last) to tightest (evaluated first):

LevelOperatorsAssociativity
1= += -= *= /= %= ^= &= `\= ^= &= ` \= ` !&= ` !\= ` ^!= ` <<= >>= @= ?=`right
2?: (ternary)right
3?? (null-coalesce)right
4or / `\`left
5and / &left
6xor / `^` (logical xor)left
7` \` !\`` (bitwise or / nor)left
8` ^` ^!\`` (bitwise xor / xnor)left
9` & ` !& `` (bitwise and / nand)left
10== != is inleft
11<- (chain arrow)right
12< <= > >=left
13<< >> (shift)left
14.. (range)n/a
15+ - (additive)left
16user-defined infix operators (operator)left
17* / % ^ (multiplicative, including power)left
18(Type)expr (cast)right (prefix)
19unary - + * (deref) @ (address-of) ++ -- ` ! ` not is not ^! ` ^!& ` ^!\``right (prefix)
20postfix [i] [a:b] ` [ab] (...) .field ->field postfix ++/--`left

A few rules worth calling out individually, since they differ from the C-family languages IDEKA otherwise resembles:

evaluated left to right.* 2 </em> 3 ^ 2 is (2 <em> 3) ^ 2, not 2 </em> (3 ^ 2). If you want exponentiation to bind tighter than multiplication, parenthesize explicitly.

  • Bitwise ` & `, \| `, and ^| `` bind tighter than the comparison operators

(==, !=, <, <=, >, >=). a == b & c means a == (b & c). This is the opposite of C, where bitwise operators are notoriously looser than comparisons - in IDEKA you do not need extra parentheses to get the intuitive reading.

  • xor/^| is a logical connective, sitting with and/or above the bitwise tier. It is

a different operator from the bitwise ` ^| ``, which lives down with the other bitwise operators.

  • The range operator .. wraps an arithmetic expression on each side, so 1 + 2 .. 3 + 4 is

valid and means (1+2)..(3+4). A range cannot directly be the left or right operand of a shift or relational operator without parentheses, since those sit at a looser level than ...

  • User-defined infix operators (declared with operator) always bind tighter than +/- and

looser than <em>///%/^, and are always left-associative, regardless of what the operator symbol "looks like" it should do mathematically. See "Custom infix operators and overloading" for how this is enforced and how it differs for overloads of built-in* operator symbols.

  • Casts ((Type)expr) bind tighter than every binary operator, including multiplication, and

chain right to left: (byte[8])(u64)x first casts x to u64, then casts that result to byte[8]. Each cast in a chain applies to everything written after it.


Primitive types:

bool true/false, byte 0xFF, int 5, uint 300u, long 23492399393233, ulong 983787283748727u, float 3.14159/20f, double 3.1415926585/360d, char "B" == 66 - 65 == 'A', data

All types:

bool, byte, int, uint, long, ulong, float, double, char, data, void, object, struct, union, enum

Preprocesor directives:

#import, #dir, #def, #ifdef, #ifndef, #else, #warn, #stop