Skip to content

Custom Data Structures

0.0.7 experimental 7.2

CKSP supports user-defined data structures in the form of structs, which allow you to group related data and define custom methods for manipulating that data. With structs, you can model complex entities, making your scripts more organized and aligned with real-world applications. Structs in CKSP behave similarly to classes in object-oriented languages, offering familiar functionality such as fields, methods, and constructors. This chapter explores how to create and use structs effectively, providing insights into memory management and pointer functionality to optimize your data handling in CKSP.


Introduction to Data Structures

In programming, data structures play a fundamental role in organizing information logically, making it easier to manage, manipulate, and interpret. CKSP’s structs let you combine related data fields and methods, giving you the tools to create complex data types that reflect real-world concepts. These structures allow for more readable and maintainable code, particularly in scripts with complex data requirements.

Structs in CKSP are pseudo-dynamically allocated, meaning they can be created within any scope, and the compiler manages their memory automatically using reference counting. When the scope in which a struct was created exits, the compiler cleans up the struct if it's no longer referenced elsewhere. Since vanilla KSP does not allow for dynamically allocating memory, the compiler tries to model this behaviour by automatically allocating sufficiently large arrays in the on init callback. This approach effectively simulates a "heap" where struct instances reside.

To determine how large this "heap" needs to be for each struct type, the compiler statically analyzes every constructor call reachable from on init or on persistence_changed (directly or through helper functions) and adds up how many instances can exist at the same time.

0.1.0 As of this version, constructor calls inside for and for-each loops with a statically known iteration count are correctly multiplied by that count, including loops with a step, downto, or a non-default starting value.

1
2
3
4
5
on init
    for i := 0 to 9 // 10 iterations
        declare temp: Note := new Note(i, 100) // counted 10 times
    end for
end on

Dynamically-Sized Heaps

If the number of instances cannot be determined statically (e.g. the constructor is reachable from a callback other than on init, or the number of loop iterations depends on a runtime value), the compiler falls back to a fixed, generous default heap size for that struct type.


Defining a Simple Struct

Structs are blueprints for creating custom data types. They enable you to define fields for data storage and methods for data manipulation, much like classes in object-oriented languages. Let’s start by defining a simple struct in CKSP to represent a musical Note with a pitch and a velocity.

Consider the following Note struct, which models the attributes of a musical note:

1
2
3
4
struct Note
    declare pitch: int
    declare velocity: int
end struct

In this example, the Note struct contains two integer fields, pitch and velocity, which represent the note’s pitch and volume intensity. Each instance of Note can store its own values for these fields, allowing you to create and manipulate multiple notes individually.

Allowed struct Member Types

Struct member variables can be standard variables, arrays, or multidimensional arrays. However, UI control variables are excluded from struct definitions, so you cannot include them as fields within a struct. This ensures that struct instances remain focused on managing and representing data rather than interfacing directly with UI elements.


Adding a Constructor

To initialize fields when a new instance of a struct is created, CKSP uses a special method called __init__. This method, often referred to as a constructor, ensures that all necessary fields are set with meaningful values as soon as a struct is created. In CKSP, __init__ works similarly to constructors in Python and is called automatically when a struct is instantiated.

If you do not define an __init__ method, CKSP will generate one for you. This auto-generated function initializes fields in the order they are declared, setting up each instance without requiring manual intervention. However, defining your own __init__ method provides more control over how fields are initialized.

Here’s how you can define an explicit __init__ method for the Note struct:

1
2
3
4
5
6
7
8
9
struct Note
    declare pitch: int
    declare velocity: int

    function __init__(self, p: int, v: int)
        self.pitch := p
        self.velocity := v
    end function
end struct

In this version, __init__ takes two parameters, p and v, and assigns them to pitch and velocity. The keyword self allows access to the struct’s own fields, ensuring that each new Note instance has independent values for pitch and velocity. Therefore self must always be the first parameter in all struct methods.


Default Values and Persistence

Member variables in structs can be initialized with default values directly in their declarations. If a variable is not assigned a value in its declaration or through the __init__ method, it will take on the default value for its data type. However, in cases where a field remains unset (as in the example above) and is not initialized in the constructor, it may unintentionally retain the values of previously deleted instances. To avoid such issues, it’s good practice to ensure that all fields are initialized in the constructor.

Struct fields can also be made persistent, meaning they retain their values even after the instrument is closed and reopened. However, this persistence is reliable only for struct instances that are declared globally, as instances created within local scopes are deleted when their scope ends.

Constructors and Asynchronous Operations

Asynchronous operations like wait are not allowed in constructors due to variable consistently and possible memory corruption when a subsequent callback is triggered before the constructor completes. This restriction ensures that the struct's memory is stable and predictable during its initialization phase. The compiler will raise an error if such usage is detected.


Static Members

0.1.0 experimental

Every member described so far belongs to an instance: each Note carries its own pitch. Some values, however, belong to the struct as a whole — a limit that applies to all notes, a counter of how many were created, a lookup table shared by every instance. Declaring such a member static gives it a single value that all instances share.

A static member is accessed through the struct name rather than through an instance:

A Shared Counter
struct Note
    static counter: int := 0
    declare pitch: int

    function __init__(self, p: int)
        self.pitch := p
        Note.counter := Note.counter + 1
    end function
end struct

on init
    declare a: Note := new Note(60)
    declare b: Note := new Note(64)
    message(Note.counter)  // Outputs: 2
end on

Because the value exists only once, a static member costs one variable instead of one slot per possible instance, and it does not reduce the number of instances that fit on the heap.

Static Constants

Combining static with const yields a value that is fixed at compile time. It is shared like any static member, but since the compiler knows its value it is substituted directly into every use and no variable is emitted at all:

A Static Constant
struct Voice
    static const MAX_VOICES: int := 16
    static const CURVE[4]: int[] := (0, 30, 70, 100)
    declare index: int
end struct

on init
    declare slots[Voice.MAX_VOICES]      // usable as an array dimension
    message(Voice.CURVE[2])              // Outputs: 70
end on

Because the value is a compile-time constant, it can be used wherever a constant is required — including as an array size, which a per-instance member can never be.

A static const must be given its value at the declaration. Its value is shared by every instance, so a constructor, which runs per instance, cannot supply it.

const without static

A plain const member keeps its own value per instance and is therefore still stored per instance. Use static const when the value is genuinely the same for the whole struct.

Constant Blocks

Related constants that belong to a struct — the states it can be in, the modes it supports — are grouped in a Constant Block declared in the struct body. Since a block holds compile-time values, it is always shared by the whole struct and is written static const:

States as a Constant Block
struct Voice
    static const State
        IDLE
        ACTIVE
        RELEASED
    end const

    declare state: int

    function __init__(self)
        self.state := Voice.State.IDLE
    end function
end struct

The entries are reached as Voice.State.ACTIVE and behave like any other compile-time constant.

Restrictions

Only a static member can be reached through the struct name. Accessing a per-instance member as Note.pitch is an error, since there is no instance to read it from — use a variable holding an instance instead.

A static member that holds an object is reference counted like a global pointer: assigning to it releases the previously referenced object and retains the new one, and destroying an instance of the owning struct leaves it untouched.


Using Structs and Pointers

Structs become even more useful when you start creating instances, accessing their properties, and referencing them dynamically through pointers. CKSP allows you to instantiate structs, access their fields with dot notation, and manage references to them using pointers.

Creating Instances

You can create an instance of a struct by calling the struct name as if it were a function, which automatically invokes the __init__ method. Additionally, you can use the new keyword to allocate instances dynamically (the usage is optional but recommended for clarity). Here’s an example of creating two Note instances:

Creating Note Instances
declare note_a: Note := new Note(60, 100)
declare note_b: Note := new Note(64, 90)

In this code, note_a and note_b are declared as pointer variables and are assigned instances of the Note struct, initialized with specific values for pitch and velocity. More about the new pointer variable type later.

Accessing and Modifying Properties

Once you have created an instance, you can access and modify its fields using dot notation.

Accessing and Modifying Note Properties
1
2
3
message("Note A pitch: " & note_a.pitch)  // Outputs: "Note A pitch: 60"
note_a.pitch := 62
message("Updated Note A pitch: " & note_a.pitch)  // Outputs: "Updated Note A pitch: 62"

This code demonstrates how to read the pitch field of note_a and update it to a new value. Each struct instance maintains its own set of fields, so changes to note_a.pitch do not affect other instances.

Struct representation

In addition, CKSP offers the __repr__ method, which is automatically called whenever a struct instance is used in a string context, such as within the message function. If no custom __repr__ method is defined, the compiler generates one by default. However, for more user-friendly output, you can explicitly implement this method to provide a more descriptive representation of the struct.

Here’s an example of a custom __repr__ method for the Note struct:

1
2
3
4
5
6
7
8
struct Note
    declare pitch: int
    declare velocity: int

    function __repr__(self): string
        return "Note: Pitch " & self.pitch & ", Velocity " & self.velocity
    end function
end struct

With this custom __repr__, calling message(note_a) would output:

declare note_a: Note := new Note(62, 100)
message(note_a)  // Outputs: "Note: Pitch 62, Velocity 100"

This allows you to easily create structured, readable representations of your struct instances in string contexts, enhancing the clarity of debug output and logs.

Working with Pointer Variables

Pointers provide a way to reference struct instances dynamically. Declared like normal variables, pointers can have any user-defined struct type and hold either a reference to a struct or nil if not currently assigned. Pointers are helpful when managing references to structs without duplicating data or when passing data between functions.

To declare a pointer, specify its type and either initialize it with the constructor of a struct or optionally set it to nil (if you do not want to assign it to anything initially, it will be automatically set to nil):

declare note_ptr: Note := nil

You can then assign a struct to the pointer, making it reference that specific instance:

note_ptr := new Note(67, 80)

Now note_ptr holds a reference to a Note instance with pitch = 67 and velocity = 80. Using pointers allows you to indirectly access or modify the original struct, making it easier to work with instances without copying data.

Similar to other CKSP data types, pointers can be used with composite types. For instance, you can create arrays of pointers for multiple Note instances, or even multidimensional arrays:

1
2
3
4
5
6
declare chord[3]: Note[] := [
        new Note(60, 100), 
        new Note(64, 100), 
        new Note(67, 100)
    ]
declare patterns[2,2]: Note[][] := [new Note(60,80)]

The last example creates a 2x2 array with all elements referencing the same Note instance.

Global Pointers in Asynchronous Callbacks

While local pointer variables are safeguarded against asynchronous operations not. Assigning a global pointer variable within a thread-unsafe callback (i.e., a callback that contains wait commands or calls functions with wait commands) can lead to inconsistencies in memory addresses and incorrect reference counts.

For example, if a global pointer n is assigned to a Note object within an on note callback, and this callback is re-triggered during a wait period, n might be reassigned to a new Note object. When the first wait period expires, the subsequent operations would mistakenly apply to the new object, leaving the original object's reference count un-decremented and potentially causing a memory leak.

The compiler will issue a warning if it detects an assignment to a global pointer variable (l_value) within a thread-unsafe callback. It is highly recommended to use local pointer variables for object assignments in such scenarios to ensure predictable memory management.


Adding Custom Methods to Structs

Beyond field initialization, you can define custom methods in structs, enabling you to add behavior. For example, you might want a method to play the note based on its pitch and velocity. The following code defines a play method that triggers the note:

Adding a Play Method to the Note Struct
1
2
3
4
5
6
7
8
struct Note
    declare pitch: int
    declare velocity: int

    function play(self): int
        return play_note(self.pitch, self.velocity, 0, -1)
    end function
end struct

With this play method, you can directly trigger a Note instance:

Playing a Note
1
2
3
4
5
on note
    declare current_note : Note := new Note(EVENT_NOTE, EVENT_VELOCITY) // Initialize the note
    ...
    current_note.play() // Plays input note with input velocity
end on

This capability makes structs more flexible, allowing them to represent not only data but also actions associated with that data.

Static Methods

0.1.0 experimental

A regular method acts on an instance and receives it as self. A helper that only works on a struct's shared state has no instance to act on, and declaring it static says so: it takes no self and is called on the struct itself.

A Static Helper
struct Voice
    static const MAX_VOICES: int := 16
    declare index: int

    static function is_valid(i: int): int
        return i >= 0 and i < Voice.MAX_VOICES
    end function
end struct

on note
    if (Voice.is_valid(EVENT_ID))
        ...
    end if
end on

Since a static method has no instance, using self inside its body is an error, as is declaring self as its first parameter. If the method needs an instance, pass it as a regular parameter or drop static to make it a regular method.

Calling a static method on an instance is allowed — some_voice.is_valid(3) behaves exactly like Voice.is_valid(3) — but reads misleadingly, since the instance plays no part.

Which methods cannot be static

__init__, __repr__, __del__ and overloaded operators all act on a specific instance and therefore cannot be declared static.


Optional Chaining and Nullish Coalescing

0.1.0 experimental

Since pointer variables can be nil, accessing a field or calling a method on one always carries the risk of a runtime error if the pointer happens to be unassigned. CKSP provides two operators, familiar from TypeScript, to make working with potentially-nil pointers safer and more concise: optional chaining (?.) and nullish coalescing (??).

Optional Chaining (?.)

The ?. operator accesses a field or calls a method only if the pointer in front of it is not nil. If the pointer is nil, the access is skipped entirely, rather than raising a runtime error.

Guarding a method call
declare current_note: Note := nil
current_note?.play() // Only calls play() if current_note is not nil

This is equivalent to writing the check by hand:

1
2
3
if current_note # nil
    current_note.play()
end if

Short-Circuiting Arguments

Just like with regular function calls, arguments to a method called through ?. are only evaluated if the call actually happens, so it is safe to pass in expressions with side effects.

The same operator can also be used as an assignment target, guarding the assignment itself:

Guarding an assignment
current_note?.pitch := 62 // Only assigns if current_note is not nil

Chaining Multiple ?.

Multiple ?. in the same chain each guard the pointer directly in front of them, producing nested nil checks. A plain . after a checked pointer is not guarded and assumes the value is already safe to access — if that assumption is wrong, accessing it can still raise a runtime error.

Nested optional chaining
1
2
3
4
5
6
7
8
struct Instrument
    declare lead_note: Note
end struct

declare instrument: Instrument := new Instrument(nil) // lead_note starts out nil

instrument?.lead_note?.play()   // safe: checks both instrument and instrument.lead_note
instrument?.lead_note.play()    // only checks instrument; errors here, since lead_note is nil

Nullish Coalescing (??)

Because a ?. chain might skip its access entirely, it cannot be used directly wherever a value is required (e.g. in a declare, as a function argument, or inside an arithmetic expression) — the compiler will raise an error. The nullish coalescing operator ?? resolves this by providing a fallback value, used whenever the pointer in front of the ?. is nil:

Providing a fallback value
1
2
3
declare current_note: Note := nil
declare pitch: int := current_note?.pitch ?? -1
message(pitch) // Outputs: -1

This behaves equivalently to the following:

1
2
3
4
5
6
7
8
declare current_note: Note := nil
declare pitch: int

if current_note # nil
    pitch := current_note.pitch
else
    pitch := -1
end if

The fallback value must be type-compatible with the value produced by the chain. ?? can also resolve a chain with multiple ?., following the same nesting rules described above:

1
2
3
declare instrument: Instrument := new Instrument(nil)
declare pitch: int := instrument?.lead_note?.pitch ?? -1
message(pitch) // Outputs: -1

?. requires either ?? or a call/assignment context

Outside of a standalone method call or an assignment target, a ?. chain must always be paired with ??. Writing declare x := current_note?.pitch without a fallback raises a compile error, since there would be no defined value for x if current_note were nil.

Discarding a Value-Returning Method Call

current_note?.play() calls a method that returns a value (see Adding Custom Methods to Structs) without capturing it. Just like a regular bare call, this raises a compiler warning by default. See Discarding Return Values for how to silence it intentionally.


Operator Overloading

0.0.8 experimental

Operator overloading is supported, enabling you to define custom behaviors for standard operators like +, -, *, and more. By implementing specific methods in a struct, you can control how instances interact with operators, making their usage intuitive.

To overload an operator, define the corresponding method in your struct. For example, the __add__ method defines how instances respond to the + operator. Here’s how you could enable addition for the Note struct, treating the addition as combining the velocity of two notes:

1
2
3
4
5
6
7
8
struct Note
    declare pitch: int
    declare velocity: int

    function __add__(self, other: Note): Note // Explicitly declare return type
        return Note(self.pitch, self.velocity + other.velocity)
    end function
end struct

Now you can add two Note instances to create a new Note with combined velocity:

Adding Two Notes
1
2
3
4
declare note_a: Note := new Note(60, 70)
declare note_b: Note := new Note(60, 50)
declare note_c: Note := note_a + note_b  // note_c has pitch 60 and velocity 120
message("Combined Note C: " & note_c) // Output with overriden repr() method: Note: Pitch 60, Velocity 120

Operator Support

Operator Overloading functions are supported for the following operators:

    +   -> __add__(self, other)
    -   -> __sub__(self, other)
    * -> __mul__(self, other)
    /   -> __div__(self, other)
    mod -> __mod__(self, other)
    =   -> __eq__(self, other)
    #   -> __ne__(self, other)
    <   -> __lt__(self, other)
    <=  -> __le__(self, other)
    >   -> __gt__(self, other)
    >=  -> __ge__(self, other)
Two further groups of overloads act on reading, assigning and subscripting an object rather than on an operator: property accessors (__get__, __set__) and subscript overloads (__getitem__, __setitem__).

An overload's signature is checked where the method is defined: a binary operator takes exactly two parameters (self included) and returns exactly one value. A wrong count is reported at the method, not where the operator is used.

Property Accessors

0.1.0 experimental

Some structs exist to stand for a single value: a wrapped engine parameter, a clamped level, a value with change tracking. For these, the property accessors __get__ and __set__ let the object be used as that value. Reading the object where a value is expected calls __get__, and assigning a value to it calls __set__:

A Struct Standing for a Value
struct Value
    number: int

    function __get__(self): int
        return self.number
    end function

    function __set__(self, value: int)
        self.number := value
    end function
end struct

on init
    declare v := new Value(5)
    message(v + 7)    // __get__: outputs 12
    v := 42           // __set__: v still points to the same object, its number is now 42
    v += 1            // __get__ and __set__: 43
    message(v)        // __get__: outputs 43
end on

__get__ takes only self and returns exactly one value. __set__ takes self and the new value and must not return anything. The getter's return type can be any type, including real and string: "value=" & text concatenates whatever __get__ of text returns.

The getter is used wherever a value is read: in expressions, conditions, message(), string concatenation, as an argument to a parameter of the getter's type and as the initializer of an unannotated declaration (declare copied := v declares an int holding the current value). This includes elements of object arrays: with declare cells[2]: Cell[], message(cells[1]) reads the element and then calls its getter.

The object itself is still reached by everything that addresses the object rather than its value: member access (v.number), method calls (v.raw()), use_count(v), the cast v as int and delete v. When message() receives an object with both __get__ and __repr__, the getter wins.

Known Issue: The Getter Also Applies Where the Object Is Expected

Currently the getter is also called where an object of the struct's own type is expected (issue #138):

  • v = nil and v # nil compare the getter's value with -1 instead of checking the pointer, without any diagnostic. Use v as int = -1 to test for nil until this is fixed.
  • Passing v to a parameter of type Value, declaring declare w: Value := v or assigning v to an element of a Value[] array is rejected as a type mismatch.

A __set__ Turns Every Assignment into a Call

Once a struct defines __set__, assigning to a variable, member or array element of that type always calls the setter. It can no longer be pointed at another object or at nil. For a variable, assign the object in its declaration. For a member, pass the object to the constructor of the struct that holds it, as in Slot(EnginePar(1)). The compiler names the setter as the reason when such an assignment is attempted. Without a __set__, a member of a type that only has a __get__ stays an ordinary object reference and can be reassigned as usual.

Subscript Overloads

0.1.0 experimental

__getitem__ and __setitem__ give a struct its own subscript, written like an array access on a single object. The getter takes self followed by one parameter per index and returns the element. The setter takes the same indexes followed by the value and returns nothing:

An Engine Parameter Addressed by Group and Slot
struct EnginePar
    par: int

    function __getitem__(self, g: int, s: int): int
        return get_engine_par(self.par, g, s, -1)
    end function

    function __setitem__(self, g: int, s: int, value: int)
        set_engine_par(self.par, value, g, s, -1)
    end function
end struct

on init
    declare volume := new EnginePar(ENGINE_PAR_VOLUME)
    volume[0, -1] := 630000     // __setitem__: group 0, slot -1
    message(volume[0, -1])      // __getitem__
    volume[0, -1] += 10000      // __getitem__, then __setitem__
end on

The indexes are ordinary arguments: they don't address storage, so a sentinel such as -1 reaches the method unchanged, and any type can be used for them. The getter can also return an object, which makes a subscript a convenient lookup into a data model:

Looking Up a Zone by Group, Key and Velocity
struct KeyMap
    function __getitem__(self, g: int, key: int, velo: int): Zone
        ...
    end function
end struct

declare map := new KeyMap()

on note
    declare zone: Zone := map[0, EVENT_NOTE, EVENT_VELOCITY]
end on

A few rules apply:

  • A subscript overload needs at least one index, so both methods take at least two parameters (self included).
  • A struct defines one __getitem__ and one __setitem__, and they take the same indexes. Every subscript on the object has to use exactly that number of indexes. Overloading them for different index counts isn't supported.
  • Reading a subscript requires __getitem__; a struct that only defines __setitem__ is reported as such. Writing one requires __setitem__.
  • A subscript on an array of objects is an array access. With declare rows[4]: Row[], rows[1] selects the array element and doesn't call Row.__getitem__.

Current Limitations

For now, a subscript overload has to be the last part of an expression, and its receiver has to be a variable or a namespace path (group.slot.volume[g, -1]):

  • The result can't be followed by a member access or method call: r[1].v and r[1].bump() are rejected. Store the result first, as in declare c: Cell := r[1], then use c.v.
  • A member can't be subscripted directly: holder.row[1] is read as a multidimensional array.
  • Subscripts can't be chained: rows[0][1] is a syntax error, since CKSP writes several indexes as [0, 1]. Use a temporary for rows[0].

The first two are tracked in issue #137.


Memory Management

Object IDs and Explicit Casts

Object pointers compile to integer IDs that select an instance's slot in the arrays backing a struct. The explicit cast syntax exposes this representation when low-level storage operations require it:

declare object_id: int := note_ptr as int
declare same_note: Note := object_id as Note

The cast only changes how the value is typed; it neither allocates an object nor changes its reference count. Assigning the result to same_note follows the normal pointer-assignment rules and retains the referenced object. Conversely, keeping only object_id does not keep the object alive.

Only convert an integer that is known to identify a live instance of the target struct. The compiler cannot verify an ID at runtime, so converting an unrelated index or using an ID after its object was released creates a dangling pointer.

A parenthesised cast can also be used directly as a receiver, as in (object_id as Note).pitch := 60. For the complete syntax, generic object targets and a storage/search example, see Type Conversion.

Automatic Memory Management

CKSP uses reference counting to automatically manage memory. Structs created within a local scope (e.g., inside a function) are automatically cleaned up when that scope exits, provided they are not referenced elsewhere. This ensures efficient memory usage without requiring manual management.

For example, a struct created within a function will be cleaned up once the function finishes:

1
2
3
4
5
6
7
8
9
function create_temporary_note()
    declare temp_note: Note := new Note(64, 90)
    message("Temporary note created:", temp_note.pitch, temp_note.velocity)
end function

on init
    create_temporary_note() // Call the function
    // After create_temporary_note finishes, temp_note is deallocated
end on

Here, temp_note is only valid within the create_temporary_note function. When the function exits, temp_note is automatically deallocated unless assigned to a pointer in an external scope.

Releasing a Reference

Assigning nil to an object pointer releases its previous reference. If that was the last reference, the instance is freed automatically; otherwise it stays alive for the remaining references. This also applies to individual elements of object arrays:

1
2
3
4
5
6
7
declare events[8]: Note[]
events[0] := new Note(60, 100)
declare alias: Note := events[0]

events[0] := nil          // Releases the array's reference and clears the slot
message(use_count(alias)) // 1: alias still keeps the instance alive
alias := nil              // Releases the last reference and frees the instance

For ordinary cleanup, use := nil. Assigning a different object likewise releases the previous reference before retaining the new one.

Circular References

Reference counting does not collect unreachable cycles. For example, two objects that reference each other remain allocated even after all external references have been released:

struct Node
    declare value: int
    declare next: Node
end struct

on init
    declare node_a: Node := new Node(10, nil)
    declare node_b: Node := new Node(20, nil)

    node_a.next := node_b
    node_b.next := node_a

    // Break the cycle while both objects are still accessible.
    node_b.next := nil
    node_a := nil // Frees A and releases A's reference to B
    node_b := nil // Frees B
end on

Break an appropriate link in the cycle before dropping the external references. Setting only the external pointers to nil does not remove the references within the cycle.

Manual Memory Management: delete

delete explicitly destroys the referenced instance, even if its reference count is greater than one. This is the escape hatch for cyclic references described in Section 5.5 of Retrofitting a Virtual Instrument DSL with Programming Abstractions. For ordinary cleanup, use := nil instead: it releases only the reference being removed and preserves the instance for other owners.

1
2
3
4
declare node: Node := new Node(42, nil)
node.next := node // A self-reference would keep the instance alive

delete node      // Forces deallocation and sets node to nil

The compiler captures the instance ID, clears the operand to nil, and, if the captured ID is not nil, calls the struct's __decr__ method with the instance's full reference count. References held by the destroyed instance are released normally, one per member reference; objects that still have other owners remain alive. This may cascade through a cycle, but it is not a general cycle collector for an arbitrary object graph.

delete also works on object members and individual object-array elements:

1
2
3
declare events[8]: Note[]
events[0] := new Note(60, 100)
delete events[0] // Destroys the instance and clears this slot

Destination indexes are evaluated once. Deleting an entire object array applies the operation to its elements and clears their slots. Deleting an operand that is already nil does nothing. A subsequent := nil, repeated delete, or automatic scope cleanup of the cleared operand therefore does not release the old instance again. Local pointers remain tracked for scope cleanup, so an object assigned after a delete is still released normally.

Other aliases are not cleared

delete clears only its operand. Other pointers or array slots that reference the destroyed instance become dangling pointers; they are not updated automatically. Do not dereference or release those stale references, including through later assignments or scope cleanup. Use forced deletion only when you control the remaining references. Prefer breaking a cycle with := nil when ordinary reference counting can handle the rest.

Compatibility

Earlier compiler versions lowered explicit delete to a decrement of 1 and left the operand unchanged. Code that used delete to release one of several references should use := nil instead. In particular, do not delete several aliases of the same instance.


Recursive Data Structures

Recursive data structures are those where a struct contains instances of itself. They are useful for modeling hierarchical data like linked lists, trees, and graphs.

Example: The List Struct (Linked List Node)

The List struct represents a node in a linked list, where each node contains a value and a reference to the next node.

1
2
3
4
5
6
7
8
9
struct List
    declare value: string // Changed type to string for better example
    declare next: List

    function __init__(self, val: string, next_node: List) // Renamed parameters for clarity
        self.value := val
        self.next := next_node
    end function
end struct

You can now create instances of List and link them together to form a linked list. This is often done by prepending new elements:

Creating a Linked List from Group Names
declare ls: List := nil // Initialize the head of the list to nil

// This loop creates a linked list where each node stores a group name.
// The list is built in reverse order of how the groups are processed (prepended).
for idx in range(NUM_GROUPS)
    ls := new List(group_name(idx), ls)
end for

// Example: If NUM_GROUPS is 3 and group_name(0) is "Piano", group_name(1) "Strings", group_name(2) "Drums":
// 1st iteration: ls = new List("Piano", nil)
// 2nd iteration: ls = new List("Strings", new List("Piano", nil))
// 3rd iteration: ls = new List("Drums", new List("Strings", new List("Piano", nil)))
// Final 'ls' points to "Drums", which points to "Strings", etc.

To traverse the list and display its elements, you could use a while loop:

Traversing a Linked List
1
2
3
4
5
declare current: List := ls // Start from the head of the list
while current # nil
    message("Node value: " & current.value)
    current := current.next
end while

This loop will output the value of each node in the list until it reaches the end (nil).

Output (Example based on above list creation)
1
2
3
Node value: Drums
Node value: Strings
Node value: Piano

Generic Structs

0.1.0 experimental

The List above stores a string. A list of int values would require a second struct that is identical except for the type of a single member, a third one for Note, and so on. A generic struct removes that duplication: it declares one or more type parameters that stand in for a type, and the concrete types are filled in at the place where the struct is used.

Declaring Type Parameters

Type parameters are listed in angle brackets directly after the struct name. Inside the struct body, a type parameter can be used wherever a type annotation is allowed — member declarations, member arrays, method parameters and method return types.

A Generic Box
struct Box<T>
    value: T

    function get(self) : T
        return self.value
    end function

    function set(self, v: T)
        self.value := v
    end function
end struct

A few rules apply to the parameter list:

  • A generic struct must declare at least one parameter; struct Box<> is rejected.
  • Parameter names must be unique within the struct and must not be a built-in type name such as int, real or string, nor a reserved keyword.
  • The list may span multiple lines and may end with a trailing comma, which keeps longer parameter lists easy to edit.
Two Parameters, Written Across Lines
1
2
3
4
5
6
7
struct Pair<
    T,
    U,
>
    first: T
    second: U
end struct

The struct name together with the number of type parameters identifies a struct, so a plain struct and generic ones of the same name can coexist:

struct Pair
    x: int
end struct

struct Pair<T>
    only: T
end struct

struct Pair<T, U>
    a: T
    b: U
end struct

Using a Generic Struct

Everywhere the struct is referred to as a type — in a type annotation, in a constructor call, as a function parameter or as an array element type — the type arguments have to be supplied:

1
2
3
4
5
6
7
8
on init
    declare a: Box<int> := new Box<int>(1)
    declare b := new Box<string>("hello")
    declare boxes[8]: Box<int>[]

    b.set("bye")
    message(a.get() & b.get())
end on

Type arguments are built-in types (int, real, string) or struct types. Each distinct list of type arguments forms its own type: Box<int> and Box<string> are unrelated to each other and to any other struct, and instances of one cannot be assigned to a variable of the other.

Type Arguments Are Never Inferred

The type arguments always have to be written out, both in the annotation and in the constructor call. new Box(1) does not resolve to Box<int>; the compiler reports that a function Box has not been declared, because a template without arguments is not a type.

Generic Structs Within Generic Structs

Inside its own body, a generic struct may refer to itself together with its type parameters. This is what makes a generic version of the recursive List possible:

A Generic Linked List
struct List<T>
    value: T
    next: List<T>
end struct

on init
    declare tail := new List<int>(2, nil)
    declare head := new List<int>(1, tail)
    message(head.next.value) // Outputs: 2
end on

A type parameter can also be passed on to another generic struct. Instantiating the outer struct then instantiates the inner one along with it:

Passing a Type Parameter On
struct Wrapper<T>
    inner: Box<T>

    function __init__(self, v: T)
        self.inner := new Box<T>(v)
    end function
end struct

on init
    declare w := new Wrapper<string>("hi") // instantiates Wrapper<string> and Box<string>
    message(w.inner.value)
end on

Static Members of a Generic Struct

Static members work in a generic struct as they do anywhere else, but they belong to an instantiation rather than to the template. Box<int> and Box<string> each keep their own count.

Inside the struct body the struct name refers to the current instantiation, exactly as it is written in a plain struct:

1
2
3
4
5
6
7
8
9
struct Box<T>
    static count: int := 0
    value: T

    function __init__(self, v: T)
        self.value := v
        Box.count := Box.count + 1 // the counter of this instantiation
    end function
end struct

From the outside the type arguments are part of the name, because the template itself is not a type:

1
2
3
4
5
6
7
on init
    declare a := new Box<int>(1)
    declare b := new Box<string>("x")

    message(Box<int>.count)    // Outputs: 1
    message(Box<string>.count) // Outputs: 1
end on

The same applies to static const entries, constant blocks and static methods — Box<int>.MAX, Box<int>.State.ACTIVE and Box<int>.reset(). A static const stays a compile-time constant, so it can still be used as an array dimension:

1
2
3
4
5
6
7
8
struct Buffer<T>
    static const SIZE := 8
    value: T
end struct

on init
    declare pool[Buffer<int>.SIZE]: Buffer<int>[]
end on

One Counter per Instantiation

Because each instantiation is compiled into a struct of its own, a static member is shared by all instances of that instantiation only. There is no storage shared across Box<int> and Box<string> — which is also why a static member may be declared with a type parameter.

How Generic Structs Are Compiled

A generic struct is a template, not a type — on its own it produces no output at all. For every distinct list of type arguments that appears in the script, the compiler generates one copy of the struct with the type parameters replaced by those arguments. This is the same monomorphization that C++ templates or Rust generics use. Two identical instantiations share a single copy, and a template that is never instantiated costs nothing.

Every copy is a full struct in its own right, so everything else described in this chapter applies to it individually — including memory management. Box<int> and Box<string> therefore receive separate "heaps", each sized from the constructor calls for exactly that instantiation.

The generated name combines the struct name with its type arguments. It shows up in compiler diagnostics as Box::int and in the compiled script as Box____int:

Generated KSP (Excerpt)
1
2
3
declare $Box____int____free_idx
declare %Box____int____allocation[1]
declare %Box____int____value[1]

Because all copies originate from the same source, a type error that only surfaces for one instantiation is reported at the line inside the generic struct. The following double method is valid for Box<int>, but multiplication is not defined for the string instantiation, and the error points at the method body rather than at the constructor call:

struct Box<T>
    value: T

    function double(self) : T
        return self.value * 2 // Type mismatch: string and int.
    end function
end struct

on init
    declare b := new Box<string>("hi")
    message(b.double())
end on

Restrictions

Generic structs are intentionally limited in this first version:

  • No nested type arguments. List<List<int>> is rejected. Wrap the inner instantiation in a named struct and use that struct as the type argument instead.
  • No generic functions or methods. Type parameters can only be introduced by a struct. A function operating on a boxed integer takes a Box<int>, not a Box<T>.
  • Built-in types stay plain. int<string> is rejected, just like a built-in type name used as a type parameter (struct Box<int>).

Advanced Usage

Structs can be more complex, containing arrays of structs or other data structures. This allows you to model more intricate relationships and data models.

Structs with Arrays of Structs: The TreeNode Struct

Let's define a tree node that can have multiple child nodes.

1
2
3
4
struct TreeNode
    declare value: int
    declare children[5]: TreeNode[] // Array of TreeNode instances
end struct

In this struct:

  • value: An integer representing the node's value.
  • children: An array of TreeNode instances. By default, array elements are initialized to nil if not explicitly assigned.

The compiler will automatically generate the __init__ method for this struct. For example, a default __init__ might look like:

1
2
3
4
5
6
function __init__(self, value: int, children: TreeNode[])
    self.value := value
    // This will assign the *reference* to the 'children' array passed as an argument.
    // Changes to 'children' inside the function will affect the original array.
    self.children := children
end function

When you pass an array to __init__ or directly assign it, remember that arrays in CKSP are passed by reference (or rather, by sharing the reference). This means if you modify the children array passed into the constructor, the original array might also be affected.

You can define methods to manipulate the tree nodes.

Adding a Child to a TreeNode
1
2
3
4
5
6
7
8
9
function add_child(self, child: TreeNode)
    for el in self.children
        if el = nil
            el := child // Assign the child to the first empty slot
            return
        end if
    end for
    message("Error: Maximum children reached. Cannot add more children to this node.")
end function

As of v0.0.7, recursive functions are not supported, so iterative methods are needed to traverse the tree. This often involves using explicit stacks or queues to manage the traversal state.