Pseudocode Reference

Complete language reference for Pseudocode, a high-performance language with an x86-64 JIT compiler. This document covers all language constructs and 80+ built-in functions, with links to example programs.

Syntax Overview

Pseudocode uses a clean, readable syntax inspired by natural language. Statements are terminated by newlines, and blocks are delimited by keywords like end rather than braces.

Comments

// Single-line comment

/* Multi-line
   comment */

Variables

Variables are declared with let. Pseudocode is dynamically typed, so variables can hold any value.

let name = expression
let x = 42
let name = "Alice"
let items = [1, 2, 3]

// Reassignment
x = x + 1

Data Types

Type Description Example
number 64-bit floating point 42, 3.14, -17
string UTF-8 text "hello", 'world'
boolean True or false true, false
nil Absence of value nil
array Ordered collection [1, 2, 3]
dict Key-value mapping dict_new()
function First-class function fn foo() ... end
bytes Binary data bytes_new(16)

Operators

Arithmetic

Operator Description Example
+ Addition 5 + 3 = 8
- Subtraction 5 - 3 = 2
* Multiplication 5 * 3 = 15
/ Division 5 / 2 = 2.5
% Modulo 5 % 3 = 2

Comparison

Operator Description
== Equal
!= Not equal
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal

Logical

Operator Description
and Logical AND
or Logical OR
not Logical NOT

Bitwise

Function Description
bit_and(a, b) Bitwise AND
bit_or(a, b) Bitwise OR
bit_xor(a, b) Bitwise XOR
bit_not(n) Bitwise NOT
bit_lshift(n, count) Left shift
bit_rshift(n, count) Right shift

Control Flow

If / Then / Else

if condition then
    // true branch
else
    // false branch
end

While Loop

while condition do
    // loop body
end

For Loop

for i in range(10) do
    print(i)
end

for item in array do
    print(item)
end

Functions

Functions are defined with fn and are first-class values.

fn name(param1, param2) body end
fn add(a, b)
    return a + b
end

fn factorial(n)
    if n <= 1 then
        return 1
    end
    return n * factorial(n - 1)
end

Pattern Matching

Use match for expressive control flow based on values.

match value
    case 1 -> print("one")
    case 2 -> print("two")
    case "hello" -> print("greeting")
    case _ -> print("default")
end

JIT Intrinsics

JIT intrinsics compile to native x86-64 machine code for C-like performance (0.97x C speed).

__jit_inc_loop(iterations)

JIT-compiled increment loop. Returns final value after iterations of x = x + 1.

__jit_inc_loop(iterations) -> int
let result = __jit_inc_loop(100000000)
// ~33ms for 100M iterations (vs 1600ms interpreted)

__jit_arith_loop(iterations)

JIT-compiled arithmetic loop. Returns final value after iterations of x = x * 3 + 7.

__jit_arith_loop(iterations) -> int

__jit_branch_loop(iterations)

JIT-compiled branch loop with if/else. Alternates x++ and x--.

__jit_branch_loop(iterations) -> int

Built-in Functions

Input / Output

print(value)

Outputs a value to standard output with a newline.

print(value) -> nil
print("Hello, World!")
print(42)

input(prompt)

Reads a line from standard input.

input(prompt) -> string
let name = input("Enter name: ")

String Functions

len(string)

Returns the length of a string or array.

len(value) -> number

upper(string)

Converts string to uppercase.

upper(str) -> string

lower(string)

Converts string to lowercase.

lower(str) -> string

trim(string)

Removes leading and trailing whitespace.

trim(str) -> string

split(string, delimiter)

Splits string into an array by delimiter.

split(str, delim) -> array

join(array, separator)

Joins array elements into a string.

join(arr, sep) -> string

substr(string, start, length)

Extracts a substring.

substr(str, start, len) -> string

replace(string, old, new)

Replaces all occurrences of old with new.

replace(str, old, new) -> string

index_of(string, substring)

Returns position of substring, or -1 if not found.

index_of(str, substr) -> number

starts_with(string, prefix) / ends_with(string, suffix)

Tests if string starts/ends with given text.

starts_with(str, prefix) -> boolean

char_at(string, index)

Returns character at position.

char_at(str, index) -> string

char_code(char) / from_char_code(code)

Converts between characters and ASCII codes.

char_code(char) -> number

Math Functions

Basic Math

Function Description
abs(n) Absolute value
floor(n) Round down
ceil(n) Round up
round(n) Round to nearest integer
min(a, b) Minimum of two values
max(a, b) Maximum of two values
clamp(val, min, max) Constrain to range

Advanced Math

Function Description
sqrt(n) Square root
pow(base, exp) Exponentiation
exp(n) e^n
log(n) Natural logarithm
log10(n) Base-10 logarithm
log2(n) Base-2 logarithm

Trigonometry

Function Description
sin(n), cos(n), tan(n) Trigonometric functions (radians)
asin(n), acos(n), atan(n) Inverse trig functions
atan2(y, x) Two-argument arctangent
sinh(n), cosh(n), tanh(n) Hyperbolic functions
degrees(rad) Radians to degrees
radians(deg) Degrees to radians

Special Functions

Function Description
hypot(a, b) Hypotenuse: sqrt(a*a + b*b)
fmod(a, b) Floating-point modulo
copysign(mag, sign) Copy sign of number
lerp(a, b, t) Linear interpolation
random() Random number 0-1
random_int(min, max) Random integer in range

Constants

Function Returns
pi() 3.14159...
e() 2.71828...
infinity() Positive infinity
nan() Not a number

Array Functions

Function Description
len(array) Array length
push(array, value) Add to end
pop(array) Remove and return last
shift(array) Remove and return first
unshift(array, value) Add to beginning
slice(array, start, end) Extract portion
concat(arr1, arr2) Combine arrays
reverse(array) Reverse in place
contains(array, value) Check if value exists
index_of(array, value) Find position
range(n) or range(start, end) Generate number sequence

Dictionary Functions

Function Description
dict_new() Create empty dictionary
dict_set(dict, key, value) Set key-value pair
dict_get(dict, key) Get value by key
dict_has(dict, key) Check if key exists
dict_delete(dict, key) Remove key
dict_keys(dict) Get all keys as array
dict_values(dict) Get all values as array
dict_size(dict) Number of entries
let user = dict_new()
dict_set(user, "name", "Alice")
dict_set(user, "age", 30)
print(dict_get(user, "name"))  // Alice

File System I/O

Function Description
read_file(path) Read file contents as string
write_file(path, content) Write string to file
append_file(path, content) Append to file
file_exists(path) Check if file exists
delete_file(path) Delete a file
file_size(path) Get file size in bytes
list_dir(path) List directory contents
mkdir(path) Create directory
getcwd() Get current working directory
chdir(path) Change working directory

HTTP I/O

Function Description
http_get(url) Perform GET request
http_post(url, body) Perform POST request
let response = http_get("https://api.example.com/data")
let data = json_parse(response)

JSON

Function Description
json_parse(string) Parse JSON to value
json_stringify(value) Convert value to JSON string

Vector Operations New

SIMD-optimized operations on numeric arrays.

Function Description
vec_add(a, b) Element-wise addition
vec_sub(a, b) Element-wise subtraction
vec_mul(a, b) Element-wise multiplication
vec_div(a, b) Element-wise division
vec_dot(a, b) Dot product
vec_sum(array) Sum all elements
vec_mean(array) Average value
vec_min(array) Minimum value
vec_max(array) Maximum value
vec_sort(array) Sort ascending
let a = [1, 2, 3]
let b = [4, 5, 6]
print(vec_dot(a, b))  // 32
print(vec_sum(a))    // 6

Binary Data New

Function Description
bytes_new(size) Create byte array
bytes_get(bytes, index) Get byte at index
bytes_set(bytes, index, value) Set byte at index
bytes_length(bytes) Length of byte array
bytes_to_string(bytes) Convert to UTF-8 string
string_to_bytes(string) Convert string to bytes
base64_encode(bytes) Encode to base64
base64_decode(string) Decode from base64

Cryptographic Hashing New

Function Description
hash_sha256(data) SHA-256 hash (hex string)
hash_md5(data) MD5 hash (hex string)
let hash = hash_sha256("hello world")
print(hash)  // b94d27b9934d3e08...

Time

Function Description
clock() CPU time in seconds
time() Unix timestamp
time_ns() Nanosecond precision timestamp
sleep(seconds) Pause execution
let start = time_ns()
// ... work ...
let elapsed = time_ns() - start
print("Took " + str(elapsed) + " ns")

Type Functions

Function Description
type(value) Get type name as string
str(value) Convert to string
num(value) Convert to number
is_nan(n) Check if NaN
is_finite(n) Check if finite

System

Function Description
exit(code) Exit with status code
getenv(name) Get environment variable
setenv(name, value) Set environment variable
assert(condition, msg) Assert condition is true

Tensor and Matrix Operations

Pseudocode provides NumPy-like tensor and matrix types with SIMD-accelerated operations (AVX2). These are designed for numerical computing, machine learning, and scientific applications.

Creating Tensors

Function Description Example
tensor_zeros(shape) Create tensor filled with zeros tensor_zeros([2, 3]) - 2x3 tensor
tensor_ones(shape) Create tensor filled with ones tensor_ones([100]) - 1D tensor
tensor_rand(shape) Create tensor with random values [0, 1) tensor_rand([3, 3])
tensor_randn(shape) Create tensor with normal distribution tensor_randn([10, 10])
tensor_arange(n) Create tensor [0, 1, 2, ..., n-1] tensor_arange(100)
tensor_linspace(start, end, n) Create n evenly spaced values tensor_linspace(0, 1, 50)
// Create tensors
let a = tensor_zeros([3, 4])  // 3x4 matrix of zeros
let b = tensor_rand([100])      // 100 random values
let c = tensor_arange(10)       // [0, 1, 2, ..., 9]

Tensor Arithmetic (SIMD-Accelerated)

All operations use AVX2 intrinsics to process 4 doubles per CPU instruction.

Function Description
tensor_add(a, b) Element-wise addition
tensor_sub(a, b) Element-wise subtraction
tensor_mul(a, b) Element-wise multiplication (Hadamard product)
tensor_div(a, b) Element-wise division
tensor_dot(a, b) Dot product (sum of element-wise products)
tensor_sum(a) Sum of all elements
tensor_mean(a) Mean of all elements
tensor_max(a) Maximum element
tensor_min(a) Minimum element

Tensor Shape Operations

Function Description
tensor_reshape(t, shape) Reshape tensor to new dimensions
tensor_squeeze(t) Remove size-1 dimensions
tensor_unsqueeze(t, dim) Add dimension at position
tensor_shape(t) Get shape as array

Matrix Operations

Function Description
matrix_zeros(rows, cols) Create zero matrix
matrix_ones(rows, cols) Create ones matrix
matrix_eye(n) Create n x n identity matrix
matrix_rand(rows, cols) Create random matrix
matrix_mul(a, b) Matrix multiplication (not element-wise)
matrix_transpose(m) Transpose matrix
matrix_det(m) Matrix determinant (LU decomposition)
// Matrix multiplication
let a = matrix_rand(3, 4)
let b = matrix_rand(4, 5)
let c = matrix_mul(a, b)  // Result is 3x5

// Identity matrix
let I = matrix_eye(4)  // 4x4 identity

Neural Network Primitives

Built-in activation functions and loss functions for machine learning.

Function Description Formula
relu(t) Rectified Linear Unit max(0, x)
sigmoid(t) Sigmoid activation 1 / (1 + exp(-x))
softmax(t) Softmax (normalizes to probabilities) exp(x) / sum(exp(x))
mse_loss(pred, target) Mean Squared Error loss mean((pred - target)^2)
ce_loss(pred, target) Cross-Entropy loss -sum(target * log(pred))
// Neural network forward pass
let input = tensor_rand([10])
let weights = matrix_rand(10, 5)
let hidden = relu(matrix_mul(input, weights))
let output = softmax(hidden)
print(tensor_sum(output))  // 1.0

Cryptographic Functions

Built-in cryptographic hashing and encoding functions. No external libraries required.

Function Description Output
sha256(string) SHA-256 cryptographic hash 64-character hex string
md5(string) MD5 hash (not for security) 32-character hex string
encode_base64(string) Base64 encode Base64 string
decode_base64(string) Base64 decode Original string
// Cryptographic hashing
let hash = sha256("hello")
print(hash)  // 2cf24dba5fb0a30e26e83b2ac5b9e29e...

// Base64 encoding
let encoded = encode_base64("Hello, World!")
let decoded = decode_base64(encoded)
print(decoded)  // Hello, World!

Glossary

Key terms and concepts used throughout the Pseudocode documentation.

Bytecode

An intermediate representation of your code that runs on the Pseudocode virtual machine. Source code is compiled to bytecode, which can then be interpreted or JIT-compiled to machine code.

JIT (Just-In-Time) Compiler

A compiler that generates native machine code at runtime rather than ahead of time. Pseudocode uses a tracing JIT that identifies hot code paths and compiles them for faster execution.

Tracing JIT

A type of JIT compiler that records the actual execution path (trace) of code and compiles that specific path. More efficient than method-based JIT for loop-heavy code because it can inline across function boundaries.

Hot Path

Code that is executed frequently (e.g., loop bodies). The JIT compiler detects hot paths and prioritizes compiling them to native code for maximum performance.

NaN-Boxing

A technique for encoding multiple value types (numbers, booleans, nil, pointers) in a single 64-bit value by exploiting the unused bits in IEEE 754 floating-point NaN representations.

Virtual Machine (VM)

Software that executes bytecode instructions. The Pseudocode VM is a stack-based virtual machine that interprets bytecode and optionally JIT-compiles hot code.

Register Allocation

The process of assigning CPU registers to variables during JIT compilation. Good register allocation minimizes memory access and improves performance.

Constant Folding

A compiler optimization that evaluates constant expressions at compile time instead of runtime. For example, let x = 2 + 3 becomes let x = 5.

Function Inlining

A compiler optimization that replaces a function call with the function's body. Eliminates call overhead and enables further optimizations on the combined code.

Closure

A function that captures variables from its surrounding scope. The captured variables persist even after the outer function has returned.

Pattern Matching

A control flow mechanism that matches a value against multiple patterns and executes code based on which pattern matches. More powerful than switch/case statements.

Guard Clause

An additional condition in a pattern match case. The pattern only matches if both the structural pattern and the guard condition are true.

How Compilation Works

Pseudocode uses a multi-stage compilation pipeline to transform your source code into executable instructions.

Compilation Pipeline

1

Lexer

Converts source code into a stream of tokens (keywords, identifiers, operators, literals).

2

Parser

Validates syntax and builds an implicit AST during a single-pass compilation.

3

Bytecode Compiler

Generates stack-based bytecode instructions with constant folding optimizations.

4

VM / JIT

Executes bytecode via interpreter, or traces hot paths and compiles to native x86-64 code.

Execution Modes

Mode Command Description
Interpreter ./pseudo file.pseudo Default mode. Fast startup, suitable for short scripts and development.
JIT ./pseudo -j file.pseudo Enables tracing JIT. Best for compute-intensive programs with hot loops.
Debug ./pseudo -d file.pseudo Prints bytecode disassembly and execution trace for debugging.

Supported Architectures

Pseudocode runs on multiple platforms with varying levels of optimization.

JIT Compilation (Native Performance)

Architecture OS Status
x86-64 (Intel/AMD) macOS, Linux, Windows Fully Supported
ARM64 (Apple Silicon, etc.) macOS, Linux Planned

Interpreter (Portable)

The bytecode interpreter runs on any platform with a C99 compiler. This includes ARM32, RISC-V, MIPS, WebAssembly, and embedded systems. Performance is lower than JIT but still competitive with Python.

Example Programs

Explore complete example programs demonstrating Pseudocode's capabilities across different domains. All examples are available in the examples/ directory.

Algorithms

Example Description Concepts
quicksort.pseudo In-place quicksort with Lomuto partitioning Recursion, arrays, sorting
binary_search.pseudo Iterative and recursive binary search Search algorithms, arrays
dynamic_programming.pseudo Fibonacci, knapsack, edit distance DP, memoization, arrays
primes.pseudo Sieve of Eratosthenes Number theory, loops

Networking & I/O

Example Description Concepts
http_client.pseudo GitHub API client with JSON parsing HTTP requests, JSON, dictionaries
text_analyzer.pseudo Text statistics and word frequency Strings, dictionaries, file I/O
password_generator.pseudo Secure random password generator Crypto, strings, randomness

Machine Learning

Example Description Concepts
neural_network.pseudo Multi-layer perceptron from scratch Tensors, matrix ops, backprop
tensor_example.pseudo Tensor operations and SIMD Tensors, vectors, matrices

Getting Started

Example Description Concepts
hello.pseudo Hello World Basic output
fibonacci.pseudo Recursive Fibonacci Functions, recursion
fizzbuzz.pseudo Classic FizzBuzz Loops, conditionals
match.pseudo Pattern matching showcase Match expressions, guards