Skip to content

Literals and Expressions

Literals

A literal is a fixed value written directly into the source code. In cksp, literals can be of the following types:

Integer literal

Integer literals are whole numbers without a decimal point.

1
2
3
42
-7
0

Integer literals can also be written in hexadecimal or binary form:

Hexadecimal literals start with 0x and use digits 0–9 and letters A–F:

1
2
3
a := 0x77AAFF  // assigns 7 742 559 in decimal
b := 0x10      // assigns 16 in decimal
c := 0xFF      // assigns 255 in decimal

Binary literals can be written in two orientations:

  • With a trailing b: bits are interpreted least-significant-bit (LSB) right

    a := 1100b   // assigns 12 decimal (binary 1100 → decimal 12)
    b := 101b    // assigns 5 decimal
    

  • With a leading b: bits are interpreted least-significant-bit (LSB) left

    a := b1100   // assigns 3 decimal (binary reversed 0011 → decimal 3)
    b := b101    // assigns 5 decimal (reversed 101 → 101)
    

Real (floating point) literal

Real literals represent numbers with a fractional part, indicated by a decimal point.

1
2
3
3.14
-0.5
2.0
Real literals can also be expressed in scientific notation, allowing compact representation of very large or very small values.

0.0.8

Scientific notation uses the letter e or E to represent powers of ten.
The syntax follows this pattern:

[integer or decimal part] e [exponent]

The exponent can be positive or negative, with or without a sign.
The following examples are all valid:

1
2
3
4
5
1e3      // 1 × 10³ = 1000.0
1.5e2    // 1.5 × 10² = 150.0
3e-2     // 3 × 10⁻² = 0.03
.5e2     // 0.5 × 10² = 50.0
1.2e-10  // 1.2 × 10⁻¹⁰ = 0.00000000012

You may use uppercase E interchangeably with lowercase e:

6.022E23  // Avogadro’s number
9.81E0    // 9.81 × 10⁰ = 9.81

Precision and Type Inference

All literals written in scientific notation are inferred as real values. They support the same precision and arithmetic operations as normal floating-point literals.

String literal

String literals are sequences of characters enclosed in double quotes (" ) or single quotes (').

"Hello World"
'Score: '
Strings can contain letters, digits, spaces, and special characters.

String Literal Escape Sequences

String literals can contain escape sequences such as \" for quotes or \n for newlines.

Boolean literal

Boolean literals represent truth values and can be either true or false.

true
false

Expressions

An expression is any valid combination of literals, variables, operators, and function calls that produces a value. They can not stand alone; they must be part of a larger statement, e.g. as an l-value in assignments or as arguments in function calls.

Expressions in CKSP follow KSP semantics and support a wide range of operations.

Arithmetic Operators

The following operators can be used with integer and real values:

1
2
3
4
5
6
7
+    // addition
-    // subtraction or negation
*    // multiplication
/    // division (integer or real, depending on operands)
**   // exponentiation (real only)
>>   // right shift (integer only)
<<   // left shift (integer only)

In addition, CKSP supports:

1
2
3
mod   // remainder of integer division
abs() // absolute value
sgn() // returns -1, 0, or 1 depending on the sign

Increment and decrement functions are also available for integers:

inc(x)  // equivalent to x += 1
dec(x)  // equivalent to x -= 1

Real-Specific Functions

1
2
3
4
5
6
exp(x), exp2(x)           // exponentials
log(x), log2(x), log10(x) // logarithms
pow(x, y)                 // power function
sqrt(x), cbrt(x)          // square and cube root
ceil(x), floor(x)         // round up or down
round(x)                  // round to nearest integer

Trigonometric functions:

sin(x), cos(x), tan(x)
asin(x), acos(x), atan(x)

Bitwise Operators

For integer values:

1
2
3
4
.and.   // bitwise AND
.or.    // bitwise OR
.xor.   // bitwise XOR
.not.   // bitwise NOT

Bit shifting:

sh_left(expr, bits) // shifts bits to the left, same as expr << bits
sh_right(expr, bits) // shifts bits to the right, same as expr >> bits

String Concatenation

Strings can be concatenated using the & operator:

"Hello " & "World"        // → "Hello World"
"Score: " & score         // converts score to string and appends

Concatenation is evaluated left to right and can be combined with other expressions:

"Result: " & (a + b)

Logical Operators

Logical operators work only in expressions using boolean types or values:

1
2
3
and   // logical AND
or    // logical OR
not   // logical NOT

Examples:

if a > 0 and b < 5
    // both conditions must be true
end if

declare ready: bool := true

if not ready
    // executes if ready = false
end if

while(true)
    // infinite loop
end while

Type Conversion

0.1.0

CKSP supports explicit casts with as. The target type follows the expression:

1
2
3
4
declare whole := 3.75 as int       // 3; the fractional part is truncated
declare precise := 3 as real       // 3.0
declare enabled := 12 as bool      // true; zero becomes false
declare label := 42 as string      // "42" in a string context

The conversion functions remain available, so value as int and int(value) are equivalent for numeric values. The as form is particularly useful when the target is an object type, since a struct name is not a conversion function.

Cast precedence

A cast binds to the value immediately before as. Use parentheses when a complete binary expression should be converted:

1
2
3
declare rhs := 1.0 + 2 as real          // 1.0 + (2 as real)
declare total := (1.5 + 2.5) as int     // converts the complete sum
declare normalized := value as int as real

Casting object IDs

Every object pointer is represented by an integer ID in the generated KSP. An object can be converted to that ID, and an integer ID can be given an object type:

1
2
3
declare note: Note := new Note(60, 100)
declare id: int := note as int
declare restored: Note := id as Note

This is useful when a low-level operation returns an index into a struct's storage. Generic object types are valid cast targets as well:

struct List<T>
    value: T

    function find(self, val: T): List<T>
        declare id := search(List<T>.storage(.value), val)
        if id # -1
            return id as List<T>
        end if
        return nil
    end function
end struct

A cast does not validate an object ID

id as Note does not construct a Note and does not check whether the corresponding allocation slot is alive. Only cast IDs obtained from a matching object's storage or from a previously converted pointer. Reading fields through an invalid or stale ID can access the wrong storage slot.

Casts do not change reference counts

Evaluating note as int does not release note, and evaluating id as Note does not retain it by itself. Normal object assignment and return handling takes care of ownership when the result is stored as an object pointer. A raw integer ID does not keep an object alive.

When an object-valued cast is used in a string context, CKSP uses the target struct's __repr__ method just as it does for an ordinary object pointer:

message(id as Note)  // formats the object through Note.__repr__

A cast in parentheses can be used like any other object reference. Its fields can be read and assigned, and its methods called, without storing the pointer in a variable first:

1
2
3
4
5
message((id as Note).pitch)
(id as Note).velocity := 100
(id as Note).velocity += 10
(id as Note).next.pitch := 60
(id as Note).play()

The parentheses are required: in id as Note.pitch the part after as is read as a type name. Only a member can be assigned this way, not the cast itself, so (id as Note) := other is rejected.

Casts operate on scalar values. Arrays and other composite values cannot be used as the source or target of a cast.

Struct Memory Management


f-Strings (Formatted Strings)

CKSP supports formatted strings, also known as f-strings, for embedding variables or expressions directly into a string literal.

1
2
3
4
5
declare name := "Alice"
declare score := 42

message(f"Player <name> scored <score> points.")
// Output: Player Alice scored 42 points.

You can also embed expressions:

message(f"Sum is <3+4+5>")
// Output: Sum is 12

Function calls are allowed as well:

message(f"Elapsed: <time_elapsed()> seconds")

Using f-Strings

f-strings let you avoid manual concatenation:

1
2
3
4
// Instead of:
message("Level " & level & " complete.")
// Use:
message(f"Level <level> complete.")