// official language reference — sourced from actual source files

Quantum
Language™
Reference

A dynamically-typed scripting language that speaks Python, JavaScript, and C++ simultaneously. Built in C++17. Ships with rot13. Files end in .sa for reasons that remain classified. This reference is complete, accurate, and occasionally horrified by what it's describing.

⚡ Open IDE — Try It Now Read the Docs
// what you're dealing with

Overview

Quantum is a tree-walk interpreted scripting language with a hand-written lexer, recursive descent parser, and 34 AST node types. It was built from scratch in C++17 by one person in 3 weeks. It works. Remarkably well, actually.

The language borrows syntax from Python, JavaScript, and C++ — and accepts all three simultaneously in the same file. This was a design choice. The parser has made peace with it.

hello.sa
# Python-style comment
// C++-style comment — both work

print("Hello from Quantum!")

# Three ways to declare a function — all valid:
fn greet(name):
    return "Hello, " + name

def greet2(name):
    return "Hi, " + name

function greet3(name) {
    return "Hey, " + name
}

print(greet("World"))
print(greet2("World"))
print(greet3("World"))

// three syntaxes, one language

Syntax Modes

Quantum accepts three distinct syntax styles. You can mix them freely. The parser handles it. The parser does not complain. The parser has simply accepted this as its life.

Python Style

Colons and indentation. def for functions. print(), and/or/not, True/False/None.

python-style.sa
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

for i in range(1, 6):
    print(i, "! =", factorial(i))

JavaScript Style

Braces and semicolons. function keyword. let/const. console.log(). &&/||. Arrow functions with =>.

js-style.sa
const square = (x) => x * x;
let nums = [1, 2, 3, 4, 5];

for (n of nums) {
    console.log(n, "squared =", square(n));
}

C++ Style

Type annotations (int, float, string), pointer operators (&, *, ->), cout << output, new keyword. Type hints are decorative — everything is still dynamic underneath.

cpp-style.sa
int x = 42;        // stored as a double. always. this is fine.
string msg = "hello";

cout << x << endl;
cout << msg << endl;

int* ptr = &x;       // actual pointer. in a scripting language.
cout << *ptr << endl;

// 11 types, all in one std::variant

Types & Values

Every value in Quantum is a QuantumValue — a std::variant holding one of 11 possible types. Dynamic typing means you never declare a type explicitly (unless you want to, for aesthetic reasons).

Type Literal / Example Notes
nil nil / null / None All three aliases work. Falsy.
bool true / True / false / False Python & JS casing both accepted.
number 42 / 3.14 / 0xFF Always stored as double. int x = 5 is a double. This is fine.
string "hello" / 'world' Immutable. Rich method set.
array [1, 2, 3] Dynamic. Supports slicing a[1:3], comprehensions.
dict {"key": value} String-keyed hash map.
function fn f(x): ... First-class. Closures. Lambdas. Arrow functions.
class class Foo: ... The class object itself.
instance Foo(args) Instance of a class.
native built-in functions len, range, rot13, etc.
pointer &x QuantumPointer struct. Null checks. In a scripting language. Nobody asked.

Type Checking

types.sa
x = 42
print(type(x))       # number
print(type("hi"))   # string
print(type([1,2]))  # array
print(isinstance(x, "number"))  # true

// declaration styles

Variables

Variables can be declared with let, const, C++ type keywords, or bare assignment. All produce the same result underneath — a dynamic value. C++ type hints are purely decorative.

variables.sa
# All of these work:
x = 10                   # bare assignment
let y = 20               # JS-style
const PI = 3.14159       # immutable
int count = 0            # C++-style hint (still a double)
string name = "Quantum"  # type hint, dynamic value

# Compound assignment:
count += 1
count -= 1
count *= 2
count /= 2

# Increment/decrement (C++ style):
count++
count--

# Trying to reassign a const:
# PI = 3  →  RuntimeError: Cannot reassign constant 'PI'

// the full operator set

Operators

Category Operators Notes
Arithmetic + - * / % ** // ** = power, // = floor division
Comparison == != < > <= >= === !== === strict equality (same as == here)
Logical and or not && || ! Python and JS styles both work
Bitwise & | ^ ~ << >> Integer bitwise ops
Assignment = += -= *= /= %= &= |= ^= Full compound set
Pointer &var *ptr ptr->member QuantumPointer. In a scripting language. We know.
Ternary cond ? a : b Standard ternary expression
Null coalesce a ?? b Returns b if a is nil
Increment ++ -- Postfix only (x++ / x--)

// branching and loops

Control Flow

If / Elif / Else

if.sa
# Python style (colon + indent):
if x > 10:
    print("big")
elif x > 5:
    print("medium")
else:
    print("small")

// C++/JS style (braces):
if (x > 10) {
    console.log("big")
} else {
    console.log("not big")
}

While Loop

while.sa
i = 0
while i < 5:
    print(i)
    i++

For Loop

for.sa
# Python-style for-in:
for i in range(5):
    print(i)

# Iterate over array:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Dict iteration (key, value unpacking):
d = {"a": 1, "b": 2}
for k, v in d.items():
    print(k, "→", v)

# JS-style for-of:
for (x of fruits) {
    console.log(x)
}

Break & Continue

break-continue.sa
for i in range(10):
    if i == 3:
        continue   # skip 3
    if i == 7:
        break      # stop at 7
    print(i)       # prints 0 1 2 4 5 6

// three keywords, one concept

Functions

Functions are first-class values. They can be passed around, returned, and stored. Three keywords declare them: fn, def, and function. They are identical.

functions.sa
# Default arguments:
fn greet(name, greeting = "Hello"):
    return greeting + ", " + name + "!"

print(greet("Saad"))            # Hello, Saad!
print(greet("Saad", "Hey"))  # Hey, Saad!

# Pass by reference (C++ style):
fn increment(int& val):
    val += 1

x = 10
increment(x)
print(x)  # 11 — x was modified in place

# Functions as values:
fn apply(f, val):
    return f(val)

fn double(x): return x * 2

print(apply(double, 5))  # 10

// anonymous functions and closures

Lambdas & Closures

lambdas.sa
# Arrow function (JS style):
square = (x) => x * x
print(square(5))  # 25

# Multi-param arrow:
add = (a, b) => a + b

# Lambda keyword (Python style):
double = lambda x: x * 2
print(double(7))  # 14

# Closure — captures outer scope:
fn make_counter():
    count = 0
    fn inc():
        count += 1
        return count
    return inc

counter = make_counter()
print(counter())  # 1
print(counter())  # 2
print(counter())  # 3

// full object-oriented programming

Classes & OOP

Quantum has a complete OOP system: inheritance with extends, super() calls, static methods, and __str__. Both self and this refer to the instance.

oop.sa
class Animal:
    fn init(name, sound):
        self.name = name
        self.sound = sound

    fn speak():
        return self.name + " says " + self.sound

    fn __str__():
        return "Animal(" + self.name + ")"

class Dog extends Animal:
    fn init(name):
        super(name, "Woof")   # call parent init
        self.tricks = []

    fn learn(trick):
        self.tricks.append(trick)

    fn show_tricks():
        for t in self.tricks:
            print(self.name, "knows:", t)

dog = Dog("Rex")
print(dog.speak())   # Rex says Woof
dog.learn("sit")
dog.learn("fetch")
dog.show_tricks()

# Static methods:
class MathUtils:
    static fn square(x):
        return x * x

print(MathUtils.square(7))  # 49

// arrays, dicts, slices, comprehensions

Collections

Arrays

arrays.sa
arr = [10, 20, 30, 40, 50]

# Indexing:
print(arr[0])       # 10
print(arr[-1])      # 50

# Slicing (Python style — nobody asked, Saad delivered):
print(arr[1:3])     # [20, 30]
print(arr[::2])     # [10, 30, 50]
print(arr[:-1])     # [10, 20, 30, 40]

# Methods:
arr.append(60)
arr.pop()           # removes last
print(len(arr))
print(arr.contains(20))  # true
arr.sort()
arr.reverse()

# List comprehension:
squares = [x * x for x in range(1, 6)]
evens = [x for x in range(10) if x % 2 == 0]
print(squares)  # [1, 4, 9, 16, 25]

Dictionaries

dicts.sa
person = {
    "name": "Saad",
    "age": 18,
    "gpa": "[403 Forbidden]"
}

print(person["name"])
person["stars"] = 0     # add key

for k, v in person.items():
    print(k, ":", v)

print(person.keys())
print(person.values())
print("name" in person)  # true

// QuantumPointer — nobody asked

Pointers

Quantum has a real pointer system. &var returns a QuantumPointer holding a live shared reference to the variable's storage cell. *ptr dereferences it. ptr->member accesses a field through a pointer. Null checks are enforced. This is a scripting language. We are aware.

pointers.sa
x = 42
ptr = &x              # AddressOfExpr → QuantumPointer

print(ptr)            # 0x7ffe8a3c1040 (deterministic fake address)
print(*ptr)           # 42 — dereference

*ptr = 99             # write through pointer
print(x)              # 99 — x was updated

# Class instance through pointer:
class Point:
    fn init(x, y):
        self.x = x; self.y = y

p = Point(3, 4)
pp = &p
print(pp->x)          # 3 — arrow operator

# Null pointer:
null_ptr = nil
# *null_ptr → RuntimeError: Null pointer dereference

// try / except / finally

Error Handling

errors.sa
# Python style:
try:
    x = 10 / 0
except RuntimeError as e:
    print("caught:", e)
finally:
    print("always runs")

# Raising errors:
fn check_age(age):
    if age < 0:
        raise "Age cannot be negative"
    return age

# JS-style try/catch:
try {
    check_age(-5)
} catch (e) {
    console.log("Error:", e)
}

Built-in Error Types

RuntimeError
General runtime failures
TypeError
Wrong type for operation
NameError
Undefined variable
IndexError
Array out of bounds

// built-in functions

Standard Library

I/O

Function Description
print(...) Print values, space-separated, with newline
println(...) Alias for print
console.log(...) JS alias for print
input(prompt) Read line from stdin
cout << x << endl C++ style output

Math

Function Description
abs(x) Absolute value
sqrt(x) Square root
floor(x) / ceil(x) Floor / ceiling
pow(base, exp) Power (same as **)
max(a, b) / min(a, b) Maximum / minimum
round(x) Round to nearest integer
random() Random float in [0, 1)
randint(a, b) Random integer in [a, b]

String

Method Description
s.len() / len(s) String length
s.upper() / s.lower() Case conversion
s.split(sep) Split into array
s.join(arr) Join array with separator
s.strip() Trim whitespace
s.replace(a, b) Replace all occurrences
s.contains(sub) Substring check
s.startswith(p) Prefix check
s.endswith(p) Suffix check
s.find(sub) Index of substring
s.substr(start, len) Substring extraction
str(x) Convert any value to string
int(s) / float(s) Parse string to number

Array

Method Description
arr.append(x) / push(x) Add to end
arr.pop() Remove and return last
arr.insert(i, x) Insert at index
arr.remove(x) Remove first occurrence
arr.sort() Sort in place
arr.reverse() Reverse in place
arr.contains(x) Membership test
arr.len() / len(arr) Length
range(n) / range(a,b) Generate integer range

Security™

Quantum's flagship cryptographic suite. rot13 is the only shipped cipher. The rest are reserved keywords waiting for v2. Caesar used rot13. Caesar was subsequently stabbed by his friends.

Function Status Description
rot13(s) SHIPPED ROT13 cipher. Apply twice to decrypt. This is the entire model.
xor_bytes(s, key) SHIPPED XOR cipher. Same function decrypts. Elegant.
to_hex(s) SHIPPED Hex-encode a string.
encrypt(s) PLANNED v2 AES/RSA. Token reserved. Unimplemented.
decrypt(s) PLANNED v2 See above.
hash(s) MD5 PLANNED MD5. In 2026. We have the screenshot.
scan(target) SIR Network scanning. Public GitHub repo. Sir.
payload() SIR We are not explaining this one.

// every reserved word

Keyword Reference

fn
Declare function
also: def, function
class
Declare class
extends
Inherit from base class
super
Call parent constructor/method
self
Instance reference
also: this
return
Return from function
if/elif/else
Conditionals
while
While loop
for / in / of
For loop iteration
break
Exit loop
continue
Next iteration
let / const
Variable declaration
new
Allocate object/array
try/except/finally
Error handling
also: catch
raise
Throw error
also: throw
print
Output
also: printf
import / from
Module imports
true / false
Boolean literals
also: True, False
nil
Null value
also: null, None, undefined
and / or / not
Logical ops
also: && || !
payload
Reserved 🛡️
sir.
scan
Reserved 🛡️
unimplemented