Syntax Reference
A complete reference for every syntax construct in the Chuks language.
Variables and Constants
Section titled “Variables and Constants”// Mutable variablevar name: string = "Chuks";name = "New Name";
// Immutable constantconst pi: float = 3.14159;// pi = 3.14; // Error: Cannot assign to const
// Type inferencevar age = 25; // Inferred as intBasic Data Types
Section titled “Basic Data Types”| Category | Types |
|---|---|
| Integers | int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, byte, rune |
| Floats | float, float32, float64 |
| Complex | complex64, complex128 |
| Boolean | bool (true, false) |
| String | string |
| Dynamic | any |
| Void | void (return type) |
| Nullable | T? — any type suffixed with ? (e.g., string?, int?, User?) |
Nullable Types
Section titled “Nullable Types”Append ? to any type to allow null values:
var name: string? = null; // nullable stringvar count: int? = 42; // nullable intvar user: User? = null; // nullable dataType/class
function find(id: int): string? { if (id == 0) { return null; } return "found";}Type Conversions
Section titled “Type Conversions”Chuks provides Go-style builtin functions for converting between primitive types:
| Function | Returns | Description | Example |
|---|---|---|---|
int(value) | int | Convert to integer (truncates) | int(3.99) → 3 |
float(value) | float | Convert to float | float(42) → 42.0 |
string(value) | string | Convert any value to string | string(42) → "42" |
// Float to int (truncates decimal)var x: int = int(3.99) // 3
// Int to floatvar y: float = float(42) // 42.0
// String to numbervar z: int = int("123") // 123var w: float = float("3.14") // 3.14
// Any value to string representationvar s: string = string(42) // "42"var s2: string = string(true) // "true"
// Boolean conversionsvar b1: int = int(true) // 1var b2: int = int(false) // 0var b3: float = float(true) // 1.0Numeric Literals
Section titled “Numeric Literals”Chuks supports decimal, hexadecimal, octal, and binary integer literals:
var dec = 255; // Decimalvar hex = 0xFF; // Hexadecimal (0x prefix)var oct = 0o77; // Octal (0o prefix)var bin = 0b11111111; // Binary (0b prefix)| Prefix | Base | Digits | Example |
|---|---|---|---|
| (none) | 10 | 0-9 | 255 |
0x | 16 | 0-9, a-f | 0xFF |
0o | 8 | 0-7 | 0o77 |
0b | 2 | 0-1 | 0b1010 |
Operators
Section titled “Operators”Arithmetic
Section titled “Arithmetic”var a = 10 + 5; // Additionvar b = 10 - 5; // Subtractionvar c = 10 * 5; // Multiplicationvar d = 10 / 5; // Divisionvar e = 10 % 3; // ModuloComparison
Section titled “Comparison”var eq = (a == b); // Equalvar ne = (a != b); // Not equalvar gt = (a > b); // Greater thanvar lt = (a < b); // Less thanvar ge = (a >= b); // Greater than or equalvar le = (a <= b); // Less than or equalLogical
Section titled “Logical”var and = (a > 0 && b > 0); // Logical ANDvar or = (a > 0 || b > 0); // Logical ORIncrement / Decrement
Section titled “Increment / Decrement”var i = 0;i++; // i is now 1i--; // i is now 0Compound Assignment
Section titled “Compound Assignment”+= (add), -= (subtract), *= (multiply), /= (divide), %= (modulo). x op= y is shorthand for x = x op y.
var x = 10;x += 5; // x is now 15x -= 3; // x is now 12x *= 2; // x is now 24x /= 4; // x is now 6x %= 4; // x is now 2+= also works for string concatenation:
var msg = "Hello";msg += ", world!"; // "Hello, world!"Bitwise
Section titled “Bitwise”var a = 0xFF & 0x0F; // Bitwise AND → 15var b = 0xF0 | 0x0F; // Bitwise OR → 255var c = 0xFF ^ 0x0F; // Bitwise XOR → 240var d = ~0; // Bitwise NOT → -1var e = 1 << 8; // Left shift → 256var f = 256 >> 4; // Right shift → 16| Operator | Name | Description |
|---|---|---|
& | AND | Sets bit to 1 if both bits are 1 |
| | OR | Sets bit to 1 if either bit is 1 |
^ | XOR | Sets bit to 1 if only one bit is 1 |
~ | NOT | Inverts all bits |
<< | Left shift | Shifts bits left (multiply by 2ⁿ) |
>> | Right shift | Shifts bits right (divide by 2ⁿ) |
Ternary Operator
Section titled “Ternary Operator”var label = count == 1 ? "item" : "items";
// Nested (right-associative)var grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";Built-in Functions
Section titled “Built-in Functions”| Function | Description |
|---|---|
print(value) | Print a value to stdout |
println(value) | Print a value followed by a newline |
len(collection) | Return the length of an array, string, or map |
copy(collection) | Return a shallow clone of an array or map |
clear(collection) | Remove all elements from an array or map |
delete(map, key) | Delete a key-value pair from a map |
append(arr, ...items) | Append elements to an array and return it |
int(value) | Convert a value to integer |
float(value) | Convert a value to float |
string(value) | Convert any value to its string representation |
strings.fromCharCode(code) | Convert an integer char code to a single-character string (via import { strings } from "std/strings") |
Collections
Section titled “Collections”Arrays
Section titled “Arrays”var numbers: []int = [1, 2, 3];var empty: []string = [];
// Access and modifyprint(numbers[0]);numbers.push(4);numbers.pop();print(numbers.length);
// Slice expressions (Go-style)var sub = numbers[1:3]; // elements at index 1, 2var head = numbers[:2]; // first two elementsvar tail = numbers[2:]; // from index 2 to endvar scores: map[string]int = { "Alice": 95, "Bob": 88};
scores["Charlie"] = 90;var aliceScore = scores["Alice"];scores.delete("Alice");scores.keys();DataType (Structs)
Section titled “DataType (Structs)”Lightweight data containers. Supports quoted keys for JSON compatibility.
dataType Point { x: int; y: int; "z-coord": int;}
var p: Point = { "x": 10, "y": 20, "z-coord": 30 };Classes
Section titled “Classes”Basic Class
Section titled “Basic Class”class Animal { var name: string
constructor(name: string) { this.name = name }
speak(): string { return "..." }}
var a = new Animal("Rex")println(a.speak())println(a.name)Inheritance
Section titled “Inheritance”class Dog extends Animal { override speak(): string { return "Woof!" }}
var dog = new Dog("Rex")println(dog.speak()) // Woof!Constructor Chaining
Section titled “Constructor Chaining”class Shape { var kind: string
constructor(kind: string) { this.kind = kind }}
class Circle extends Shape { var radius: int
constructor(radius: int) { super("circle") this.radius = radius }}Multi-Level Inheritance
Section titled “Multi-Level Inheritance”Chuks supports deep inheritance chains with proper super() chaining:
class Base { var value: int constructor(v: int) { this.value = v } function describe(): string { return "Base(" + string(this.value) + ")" }}
class Middle extends Base { var label: string constructor(v: int, label: string) { super(v) this.label = label } override describe(): string { return "Middle:" + super.describe() }}
class Top extends Middle { constructor(v: int) { super(v, "top") } override describe(): string { return "Top->" + super.describe() }}
var t = new Top(42)println(t.describe()) // Top->Middle:Base(42)Access Modifiers
Section titled “Access Modifiers”class BankAccount { private var balance: int = 0 var owner: string
constructor(owner: string, initial: int) { this.owner = owner this.balance = initial }
public getBalance(): int { return this.balance }
public deposit(amount: int) { this.balance = this.balance + amount }}| Modifier | Access |
|---|---|
public | Anywhere (default) |
private | Declaring class only |
protected | Declaring class and subclasses |
Readonly Properties
Section titled “Readonly Properties”class Config { readonly var appName: string var version: int = 1
constructor(name: string) { this.appName = name }}Static Methods
Section titled “Static Methods”class MathUtils { static add(a: int, b: int): int { return a + b }}
println(MathUtils.add(3, 4)) // 7Abstract Classes
Section titled “Abstract Classes”abstract class Shape { abstract area(): float;
describe(): string { return "I am a shape" }}
class Rectangle extends Shape { var w: float var h: float
constructor(w: float, h: float) { this.w = w this.h = h }
override area(): float { return this.w * this.h }}Final Classes and Methods
Section titled “Final Classes and Methods”final class Singleton { static getInstance(): string { return "instance" }}// class Child extends Singleton { } // Error: cannot extend final class
class Base { final greet(): string { return "Hello" }}// Cannot override final methods in subclassesOverride Keyword
Section titled “Override Keyword”The override keyword is required when overriding a parent method. The compiler verifies the parent class has that method.
class Parent { greet(): string { return "Hello from Parent" }}
class Child extends Parent { override greet(): string { return "Hello from Child" }}Interfaces
Section titled “Interfaces”interface Runnable { run(): void;}
class Runner implements Runnable { public function run(): void { print("Running..."); }}enum Color { Red, Green, Blue}
var c: Color = Color.Green;Functions
Section titled “Functions”function add(a: int, b: int): int { return a + b;}
// Optional parameters with defaultsfunction greet(name: string, greeting: string = "Hello"): string { return greeting + ", " + name;}greet("Alice"); // "Hello, Alice"greet("Alice", "Hi"); // "Hi, Alice"Closures
Section titled “Closures”function makeCounter(): any { var count = 0; return function(): int { count = count + 1; return count; };}
var counter = makeCounter();println(counter()); // 1println(counter()); // 2
// Lambdavar multiply = function(a: int, b: int) { return a * b; };println(multiply(3, 4)); // 12Function Type with Named Parameters
Section titled “Function Type with Named Parameters”Function type annotations can include parameter names for readability:
// Positional syntax (arrow)var add: (int, int) => int = (a: int, b: int): int => a + b;
// Named parameter syntax (function keyword)var greet: function(name: string): string = function(name: string): string { return "Hello, " + name;}
// In callback positionfunction applyOp(a: int, b: int, op: function(x: int, y: int): int): int { return op(a, b);}Forward References
Section titled “Forward References”Functions and classes can be referenced before their declaration:
function main() { println(greet("World")); // works — greet is defined below}
function greet(name: string): string { return "Hello, " + name + "!";}Control Flow
Section titled “Control Flow”Conditionals
Section titled “Conditionals”if (x > 10) { print("Big");} else if (x == 10) { print("Ten");} else { print("Small");}While Loop
Section titled “While Loop”while (x > 0) { x = x - 1;}For Loop
Section titled “For Loop”for (var i = 0; i < 10; i++) { print(i);}
// With compound assignmentfor (var i = 0; i < 100; i += 10) { print(i);}For…of Loop (Arrays)
Section titled “For…of Loop (Arrays)”var fruits = ["apple", "banana", "cherry"];for (var fruit of fruits) { println(fruit);}For…in Loop (Maps)
Section titled “For…in Loop (Maps)”var scores: map[string]int = {"math": 90, "science": 85};for (var key in scores) { println(key);}Switch
Section titled “Switch”switch (x) { case 1: print("One"); break; default: print("Other");}Error Handling
Section titled “Error Handling”try { if (x < 0) { throw new Error("Negative value"); }} catch (e) { print("caught error: " + e.message);} finally { print("clean up");}Concurrency
Section titled “Concurrency”Async / Await
Section titled “Async / Await”async function fetchData(): string { return "data";}
var result = await fetchData();spawn(function() { print("Running in background");});Channels
Section titled “Channels”import { channel } from "std/channel"
var ch: Channel = channel.new(1);
channel.send(ch, "hello");var msg = channel.receive(ch);println(msg); // "hello"
// Non-blocking operationsvar result = channel.tryReceive(ch);var sent = channel.trySend(ch, 42);
channel.close(ch);| Function | Description |
|---|---|
channel.new(size?) | Create channel (default buffer 0) |
channel.send(ch, value) | Blocking send |
channel.receive(ch) | Blocking receive |
channel.close(ch) | Close channel |
channel.tryReceive(ch) | Non-blocking receive → {value, ok} |
channel.trySend(ch, value) | Non-blocking send → true/false |
Modules
Section titled “Modules”// Exportingexport class MyClass { ... }export function myFunction() { ... }
// Importingimport { MyClass, myFunction } from "./myModule";Pointers
Section titled “Pointers”var x: int = 10;var p: *int = &x;print(*p); // 10Comments
Section titled “Comments”// Single-line comment
/* Multi-line comment*/Runtime Error Messages
Section titled “Runtime Error Messages”Chuks provides source-mapped error messages with file name and line number:
test.chuks:14: property 'missing' not found on maptest.chuks:10: division by zerotest.chuks:5: unsupported operator for types