Custom Data Structures
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.
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:
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:
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
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 | |
|---|---|
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 | |
|---|---|
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 | |
|---|---|
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 | |
|---|---|
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 | |
|---|---|
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:
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):
You can then assign a struct to the pointer, making it reference that specific instance:
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:
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 | |
|---|---|
With this play method, you can directly trigger a Note instance:
| Playing a Note | |
|---|---|
This capability makes structs more flexible, allowing them to represent not only data but also actions associated with that data.
Static Methods
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 | |
|---|---|
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
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 | |
|---|---|
This is equivalent to writing the check by hand:
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 | |
|---|---|
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.
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 | |
|---|---|
This behaves equivalently to the following:
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:
?. 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
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:
Now you can add two Note instances to create a new Note with combined velocity:
| Adding Two Notes | |
|---|---|
Operator Support
Operator Overloading functions are supported for the following operators:
__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
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__:
__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 = nilandv # nilcompare the getter's value with-1instead of checking the pointer, without any diagnostic. Usev as int = -1to test forniluntil this is fixed.- Passing
vto a parameter of typeValue, declaringdeclare w: Value := vor assigningvto an element of aValue[]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
__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:
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 | |
|---|---|
A few rules apply:
- A subscript overload needs at least one index, so both methods take at least two parameters (
selfincluded). - 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 callRow.__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].vandr[1].bump()are rejected. Store the result first, as indeclare c: Cell := r[1], then usec.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, sinceCKSPwrites several indexes as[0, 1]. Use a temporary forrows[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:
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:
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:
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:
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.
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:
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.
You can now create instances of List and link them together to form a linked list. This is often done by prepending new elements:
To traverse the list and display its elements, you could use a while loop:
| Traversing a Linked List | |
|---|---|
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) | |
|---|---|
Generic Structs
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 | |
|---|---|
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,realorstring, 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.
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:
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:
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 | |
|---|---|
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 | |
|---|---|
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:
From the outside the type arguments are part of the name, because the template itself is not a type:
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:
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) | |
|---|---|
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:
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 aBox<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.
In this struct:
value: An integer representing the node's value.children: An array ofTreeNodeinstances. By default, array elements are initialized tonilif not explicitly assigned.
The compiler will automatically generate the __init__ method for this struct. For example, a default __init__ might look like:
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 | |
|---|---|
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.